# Question
Title: How to prevent multiple playing sounds from destroying your hearing?
The problem is that when I play 100 sounds almost at same time, all I hear is noise. It's not very attractive to listen it for 30 minutes straight.

I tried to fix this by allowing only 1 sound of each sound type to be played at once. But it still sounds really ugly; eventually my brain keeps hearing only the very end of the shot sounds (or the start of it?), and that gets on my nerves really quickly. Eventually I would just decide to turn off the sounds completely. So is there any point of using sounds in a game like this at all?

How does our dear reality handle this problem? If there is a war out there, how does it sound when hundred of men shoot almost at the same times?

**Edit:** Here is how the game sounds currently; there isn't even 100 sounds playing at once, maybe 20? http://www.speedyshare.com/VTBDw/headache.mp3 At the beginning it sounds OK, but then it becomes unbearable! In that audio clip there is allowed only 1 sound to be played at once, so it will stop the previous playing sound when new sound is played.

**Edit2:** And here is same headache but 32 simultaneous sounds allowed to be played at same time: http://www.speedyshare.com/TuWAR/headache-worse.mp3 Quite a torture, eh?

# Answer
> 5 votes
In reality, our hearing is adaptable. Just like our vision adapts to different light conditions by becomming more or less sensitive, our hearing adapts to different noise coditions. Unfortunately this doesn't work as well for computer audio output.

But you could simulate it. When the game gets particularly noisy, reduce the overall volume down to a bearable level.

There is a name for such an audio filter: It's called dynamic range compression. An advanced audio API might even provide it out-of-the-box.

Also, when events *technically* happen at once, you should still try to offset their sound effects by some microseconds. When 10 enemies fire their guns in the same game-logic-frame, the 10 gunshot sounds should not play in perfect unison. This will sound like one very loud gunshots, not multiple which happen simultaneously. They will sound more realistic when they are slightly offset (chorus effect).

# Answer
> 3 votes
* Leave at least -3dB headroom for your sounds. In your case it can be -6dB or more. This way you will get rid of the digital distortion caused by reaching the maximum capacity of how a sound can be represented digitally.
* Apply a good randomization or use sufficiently big enough number of recordings of the same sound.
* Ask the question that "Do playing that many sounds tell something meaningful?". Integrate a system that attaches priority indexes to sounds and put a cap to maximum number of sounds can be played simultaneously. Most background sounds become a part of background noise when there are significant sounds in the front. Some game engines do that for you.
* Instead of assigning a sound to every object, let only important objects have their dedicated sounds and design one long ambiance sound loop for other sounds. Again, background sounds are a part of the background. You don't need to attach a sound file for everything.

It is also a burden and waste of CPU to play sounds that you won't hear or associate with the source object. Use your resources wisely.

# Answer
> 2 votes
Your sound files are gone, but just attenuate the sounds that are further away, severely.

So use an INVERSE CURVE, or an EXPONENTIAL CURVE to attenuate the noise volume.

If that's not enough, you can even use an exponential curve:

In OpenAL, use the function `alDistanceModel` with any of:

```
AL_INVERSE_DISTANCE AL_INVERSE_DISTANCE_CLAMPED
AL_LINEAR_DISTANCE AL_LINEAR_DISTANCE_CLAMPED
AL_EXPONENT_DISTANCE AL_EXPONENT_DISTANCE_CLAMPED
AL_NONE

```

The default is `AL_NONE`, so that would be pretty noisy if you have many sounds playing at once.

# Answer
> 2 votes
Try limiting the total number of things that can play a sound at a given time. For example if numberOfSoundsPlayingRightNow \> 5, then ignore the sound effect that just got triggered.

Also try bringing the volume down for sound effects that are less important.

Another thing to try is to limit how often a single game object can emit sound to prevent a single object form spamming the same SFX over and over. For example an object would check before playing: if lastTimePlayed \< 1 second, then the sound trigger.

You can also look into an game audio tool like Wwise where you can easily tweak the audio from the game.

---
Tags: sound, sound-effects, openal
---


# Question
Title: Should I use one line per .wav or one scene per .wav for character speech?
I'm building a game in XNA and I wanted to know how I would organize the character speech portions of the game. These would include both cutscenes and anything else where characters interact.

I wanted to know if it would be more efficient to use sound file (.wav) per character line, such as:

```
SCENE 4: ENTERING THE CAVE

PLAYER1: Wow, this is going great! } One file called "04_PLAYER1_01.wav"
PLAYER2: I know! } A file called "04_PLAYER2_01.wav"
PLAYER1: Let's get going! } A file called "04_PLAYER1_02.wav"

```

I wanted to know if that would be better opposed to:

```
SCENE 4: ENTERING THE CAVE

PLAYER1: Wow, this is going great! }
PLAYER2: I know!                   } One file called "scene_04.wav"
PLAYER1: Let's get going!          }

```

I am aware that by going with option 2, you'd probably save a bit more space because you have less files (but they might be larger) but it poses the problem of coordinating it all.

I was thinking maybe XML for coordinating the speech and cutscenes, but am open to other suggestions. :)

**P.S. This not intended to be a "DIALOG-TREE". These are actual models moving their lips in accordance with sound!**

# Answer
Using a separate file for each line is going to be much easier to deal with. Here's why:

Typically, several segments will require multiple takes, since actors stutter or misspeak. If the actors are being recorded together, you'll need to merge these takes into a final cut. If you need to change something, you'll have to edit the entire sequence (changing the offsets for each line after that one). It's going to much quicker and less programming effort to use multiple files.

This is especially true when you're working in a team. If we're both working on the same scene, I can't make changes until you're done with that sound file.

Either way, you would still want to build a descriptor file to trigger each sound, ie

```
Delay - Subtitle - Sound
0:04 - [Explosions] - explode04.wav
0:01 - Wow, this is going great! - p1dlg01.wav
0:03 - I know! - p2dlg01.wav
0:02 - [Rocks falling] - tumble08.wav
0:03 - Let's get going! - p1dlg02.wav

```

I've added subtitles to this example for continuity, but actually these should be separate considerations. You'll want to integrate camera movement, animated events, etc., into your script, just like a movie's shooting script.

XML is fine for this, and XNA supports XML content out of the box. Lua is also a good choice, though it comes with more overhead.

It also follows that each scene should have its own script. If someone is helping, you don't need to merge differences to the files.
> 1 votes

# Answer
One wav for the whole scene can turn into a big headache if you want to alter the scene later, even a minor one.

And if any of the players have a problem during the playback (memory, CPU, bug...etc), the rest of the audio will be asynchronous. Players will skip the scene or close the game without you knowing about that. Which will throw away all your efforts.

Do that only if you are making a video scene and encoding the audio together with the video using a video codec. In this case the audio editing should be done last.

Otherwise always use one line per wav. You will be safe and peaceful.
> 2 votes

---
Tags: xna, sound, xml, cutscene
---


# Question
Title: Stuttering Character When Colliding With Wall XNA 4.0 Help!
I'm trying to make a platformer game without tiles. I've made a collision handler to handle collision between Player and Stage(platform)and a collision checker, here's the code:

```
public void handleCollision(GameObject OtherObject)
    {
        if(this.CollidesWith(OtherObject))
        {

            if(OtherObject is Stage)
            {

                float rightEdgeDistance = OtherObject.BoundRect.X - (Position.X + this.BoundRect.Width);
                float leftEdgeDistance = OtherObject.BoundRect.X + OtherObject.BoundRect.Width - Position.X;

                float TopEdgeDistance = OtherObject.BoundRect.Y - (Position.Y + this.BoundRect.Height);
                float BottomEdgeDistance = OtherObject.BoundRect.Y + OtherObject.BoundRect.Height - Position.Y;

                float Left_Right_SmallerDistance = Math.Min(Math.Abs(rightEdgeDistance), Math.Abs(leftEdgeDistance));
                float Top_Bottom_SmallerDistance = Math.Min(Math.Abs(TopEdgeDistance), Math.Abs(BottomEdgeDistance));

                float smallerDistance = Math.Min(Math.Abs(Left_Right_SmallerDistance), Math.Abs(Top_Bottom_SmallerDistance));

                if (smallerDistance == Math.Abs(leftEdgeDistance))
                {
                    Position.X = OtherObject.BoundRect.X + OtherObject.BoundRect.Width;
                    Velocity.X = 0;
                }
                else if (smallerDistance == Math.Abs(rightEdgeDistance))
                {
                    Position.X = OtherObject.BoundRect.X - this.BoundRect.Width;
                    Velocity.X = 0;
                }
                else if (smallerDistance == Math.Abs(BottomEdgeDistance))
                {
                    Position.Y = OtherObject.BoundRect.Y + OtherObject.BoundRect.Height;
                    Velocity.Y = 0;
                }
                else if (smallerDistance == Math.Abs(TopEdgeDistance))
                {
                    Position.Y = OtherObject.BoundRect.Y - this.BoundRect.Height;
                    Velocity.Y = 0;
                }
            }
        }
}

```

My collision checker:

```
public bool CollidesWith(GameObject OtherObject)
    {
            return BoundRect.Intersects(OtherObject.BoundRect);
    }

```

Here's my inputHandler method for the Player class:

```
public void inputHandler(GameTime gameTime)
    {
        Velocity = Vector2.Zero;

        if (Keyboard.GetState().IsKeyDown(Keys.W) )
        {
            Velocity.Y -= moveSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
        }
        else if (Keyboard.GetState().IsKeyDown(Keys.S) )
        {
            Velocity.Y += moveSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
        }
        else
            Velocity.Y = 0;

        if (Keyboard.GetState().IsKeyDown(Keys.A) )
        {
            Velocity.X -= moveSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
        }
        else if (Keyboard.GetState().IsKeyDown(Keys.D) )
        {
            Velocity.X += moveSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
        }
        else
            Velocity.X = 0;

    }

```

And here's my code for the Update method in Player:

```
public void Update(GameTime gameTime,List<Stage> lstOtherObject)
    {
        inputHandler(gameTime);
        foreach (GameObject OtherObject in lstOtherObject) { handleCollision(OtherObject); }

        Position += Velocity;
    }

```

This works, if I don't continue to press the keys in the bounded direction. If I do, it will stutter in and out of the platform bounds. Like this: It goes a bit into the grey platform and then it goes out of the grey platform to the intended place. Can someone help? I want to learn, but I cant seems to figure out whats wrong with this.I tried many things, but still I can't achieve what I want, that is for the player to stop when it reaches the bounds of the platform and never going into it.Appreciate if someone can bring a clear solution and explanation to this. Thanks.

# Answer
You were right about checking it before it collides but the handling collision algorithm you code will not solve it. As it doesn't handle all the case that can occur.

Lets say that the player comes and grounded on the top of the platform. Yes the case of:

```
if(Position.Y < OtherObject.Position.Y){verticalPoint = OtherObject.Position.Y - BoundRect.Height;}

```

will work here,but so does the case:

```
if(Position.X > OtherObject.Position.X) {horizontalPoint = OtherObject.Position.X + OtherObject.BoundRect.Width;}

```

which will cause a logical error. This can be overcome with the method I used and by changing it a bit, I have achieved what I needed. Here's the code

```
public void handleCollision(GameObject OtherObject)
    {

        if(OtherObject is Stage)
        {

            if (CollidesWith(OtherObject, Position.X + Velocity.X, Position.Y))
            {
                float rightEdgeDistance = OtherObject.BoundRect.X - (Position.X + this.BoundRect.Width);
                float leftEdgeDistance = OtherObject.BoundRect.X + OtherObject.BoundRect.Width - Position.X;

                float Left_Right_SmallerDistance = Math.Min(Math.Abs(rightEdgeDistance), Math.Abs(leftEdgeDistance));

                if (Left_Right_SmallerDistance == Math.Abs(leftEdgeDistance))
                {
                    Position.X = OtherObject.BoundRect.X + OtherObject.BoundRect.Width;
                    Velocity.X = 0;
                }
                else if (Left_Right_SmallerDistance == Math.Abs(rightEdgeDistance))
                {
                    Position.X = OtherObject.BoundRect.X - this.BoundRect.Width;
                    Velocity.X = 0;
                }
            }

            if (CollidesWith(OtherObject, Position.X, Position.Y + Velocity.Y))
            {
                float TopEdgeDistance = OtherObject.BoundRect.Y - (Position.Y + this.BoundRect.Height);
                float BottomEdgeDistance = OtherObject.BoundRect.Y + OtherObject.BoundRect.Height - Position.Y;

                float Top_Bottom_SmallerDistance = Math.Min(Math.Abs(TopEdgeDistance), Math.Abs(BottomEdgeDistance));

                if (Top_Bottom_SmallerDistance == Math.Abs(BottomEdgeDistance))
                {
                    Position.Y = OtherObject.BoundRect.Y + OtherObject.BoundRect.Height;
                    Velocity.Y = 0;
                }
                else if (Top_Bottom_SmallerDistance == Math.Abs(TopEdgeDistance))
                {
                    Position.Y = OtherObject.BoundRect.Y - this.BoundRect.Height;
                    Velocity.Y = 0;
                }
            }

        }

    }

```

Thank you good sir, For helping me realize that I need to predict collision of the next update :)
> 0 votes

# Answer
I have looked into your code and I could see some wrong procedures ( I think , I might be wrong though ) but I will try to look more into it to see what are its problems . However , since your main goal is to stop the rectangles from intersecting each other , I have another way that works well ( mostly ) and I think is more efficient than your algorithm . ( I know that as a not a pro myself that you want an explanation why your way didn't work , I will post it in another answer).

So what I actually use in my way is that rather than changing the position of the object when it hits another , I prevent the change if its going to hit it one frame ahead .

If we changed the code of HandleCollision() method to my way it will look like this :

```
public void handleCollision(GameObject OtherObject)
{
    if(OtherObject is Stage)
    {
            if(CollidesWith(OtherObject , Position.X + Velocity.X (float)gameTime.ElapsedGameTime.TotalSeconds , Position.Y)
            {
                Velocity.X = 0;
            }
            if(CollidesWith(OtherObject , Position.X, Position.Y  + Velocity.Y (float)gameTime.ElapsedGameTime.TotalSeconds )
            {
                Velocity.Y = 0;
            }
    }
}

```

And the CollideWith() method

```
public bool CollidesWith(GameObject OtherObject , float X , float Y)
{
        return New Rectangle(X,Y,BoundRect.width,BoundRect.height).Intersects(OtherObject.BoundRect);
}

```

So now , the explanation : As you see in the image below , ( P square is player , ghost is change in Pos in next frame and the purple is another rectangle ) when we add the velocity ( change in position , multiplied by the time to get the exact change in the next frame ) to the position , we change it .

So the handle collision method checks if that change would cause an intersection between the rectangles of the objects , if it does then the velocity will be 0 .

But how do we achieve this ? well first of all lets take a look at the CollidesWith method . We add 2 new parameters X and Y , We will use these to create our new Rectangle , but Why ? The new rectangle will have the position as X and Y and the dimensions will be the same as the BoundRect , we do this so we are able to manipulate the position of collision so we are able to detect if the player , for example collides 10 pixels ahead ( Posision.X + 10 ) and of course use it to determine our "Ghost" rectangle position , which is the change that will affect the Position of the player ( Velocity ) .

And in the HandleCollision() method we call the CollidesWith() method two times , one for X collision and the other for Y collision , each time setting the X or Y of the CollidesWith() Method as the position of the current object + its velocity . Since Velocity is the change in the position then we simply apply that change by adding it to the position , that way we get the future change before it actually applies , with it we check if we should move the player or not , if not the we set the velocity to 0 to make sure that the position won't change .

In the input handle method you should simply change the velocity to the value you would like , then in the update method after the input handle method we place the handle collision ( must be after it ) so it detects of the collision after setting the velocity , and after that we apply the velocity to the position .

With this way of collision there is a disadvantage I found , probably you think of it now , what if the object velocity per frame is 5 pixels ? would that mean that if its 3 pixels close the other rectangle it wont move to it because if it moved that 5 pixels it will intersect the other rectangle ? meaning that object will stay at a distance of 3 pixels from the rectangle ? Yes this is right a high speed moving object will probably stay at a distance from the another rectangle , but this can be solved very quickly in many ways , here is a very easy one after changing the HandleCollision() method :

```
public void handleCollision(GameObject OtherObject)
{
    if(OtherObject is Stage)
    {
            float horizontalPoint;
            float verticalPoint;
            if(Position.X < OtherObject.Position.X){horizontalPoint = OtherObject.Position.X - BoundRect.width}
            if(Position.X > OtherObject.Position.X) {horizontalPoint = OtherObject.Position.X + OtherObject.BoundRect.width}
            if(Position.Y < OtherObject.Position.Y){verticalPoint = OtherObject.Position.Y - BoundRect.height}
            if(Position.Y > OtherObject.Position.Y) {verticalPoint = OtherObject.Position.Y + OtherObject.BoundRect.height}
            if(CollidesWith(OtherObject , Position.X + Velocity.X (float)gameTime.ElapsedGameTime.TotalSeconds , Position.Y)
            {
                Velocity.X = 0;
                if(Position.X != horizontalPoint){Position.X = horizontalPoint}
            }
            if(CollidesWith(OtherObject , Position.X, Position.Y  + Velocity.Y (float)gameTime.ElapsedGameTime.TotalSeconds )
            {
                Velocity.Y = 0;
                if(Position.Y != verticalPoint){Position.Y = verticalPoint}
            }
    }
}

```

We here simply get some point calculations to get the point where our position should be after colliding with the rectangle , and if its not then we sit it to be .

Hope that helped ,note that game objects don\`t actually move , they teleport from point to another , so in most collision methods ( if not all ) if your velocity per frame is more that that the width of the bound rectangle it will probably go through it .
> 0 votes

---
Tags: xna, collision-detection, collision-resolution, bounding-boxes
---


# Question
Title: How important is music to mobile phone (smart PDA) games?
Specifically iPhone/iTouch, Droids, and the new Windows Phone 7? I don't know how to quantify this, or if any research has been done. I am wondering how important the music is to the gaming and what % of games come with music at all, if good music at that.

# Answer
> 5 votes
I wouldn't say music is critical, but good music on any platform can greatly enhance the player's experience. The most important consideration with respect to music is that the music be appropriate--it should fit the game, and it should be somewhat subtle; it should not be too distracting. I would argue that poorly chosen music can easily be worse than no music at all, so it's worth investing time (and often money) to put together a good soundtrack. Your soundtrack should be large enough that it does not become too repetitive, and there *must* be a way to adjust the volume and switch the music on/off entirely (this functionality is usually provided for you in mobile devices).

If securing a proper soundtrack is not a viable option for you, then consider subtle ambient background sounds instead (see *Angry Birds* for an example).

I have no meaningful figures about the percentage of mobile games shipping with music, but most of the games I've played do include music, or at least ambient background sounds. There are some notable exceptions of excellent games without music, including *Trainyard* on the iPhone, which easily ranks in my Top 10 favorite mobile games.

# Answer
> 0 votes
The perception of audio quality usually is a plus or minus to overall game quality perceived. Generally most good audio is not spotted by the user, but their perception of game quality is increased.

Also consider that music themes and characterized sound effects are quickly recognized and can quickly become a symbol for a game. Music is a very strong IP like a strong character, and leaves its traces even hearing once. A good music, when switched off later, will continue playing in people's head while playing the game, and later also while not playing the game.

We recently published a puzzle game with minimal sound design with no music and received plenty of comments asking why the game has no music and should have one. In addition to that, although the sound design was minimal but careful, we have also seen people using headphones to play the game instead of turning the sound off.

Considering the fact that it is usually very hard to get feedback on audio (unless it is really bad or have great emotional songs), and experiencing people asking for music and preferring headphones even for minimal designs, music is quite important for all games. Game developers shouldn't underestimate its potential for mobile games.

---
Tags: game-design, audio, sound, music, mobile
---


# Question
Title: Will changing the scale of objects in Unity have adverse effects?
Relative to what they are by default, I mean. For example compared to the character controllers that come with Unity. If I make the character 4 times the size, will that cause problems, with the physics and everything? Or are there just changes in a couple values that I'd need to make?

Does Unity expect that 1 unit will always be around 1 meter?

# Answer
> 1 votes
Floating point errors will start creeping in if things are *WAY* bigger than Unity expects, but just 4 times bigger should be fine (assuming of course you're consistent with everything!) I'm talking more like if you tried to simulate the entire solar system at 1 unit = 1 meter.

# Answer
> 0 votes
No, scaling an object will not have adverse effects as described by yourself. Physics will still function. And like @gjocking mentions in his answer, floating point errors might creep in on a way bigger size.

The only adverse effect scaling has is the **extra draw call** if you are using dynamic batching

* scale changing will break dynamic batching - so you will get one more draw call

However with static batching you would still get 1 draw call.

> also in case of scaled meshes GPU re-normalization state must be set (otherwise your lighting will go wonky), therefore scaled and non-scaled meshes can not be batched together.

Also if a non uniform scale is used the mesh will be copied. **ONLY** if non-uniform scale is used. In case of uniform scale (both X, Y and Z scale are equal) Unity will **NOT** make a copy of a mesh and will be completely handled by the GPU.

---
Tags: unity
---


title: C# xna/monogame ghost trail effect

text:
# Question
Title: C# xna/monogame ghost trail effect
I would like some know how can someone make an animation like this, in Monogame specifically.Since i am completely clueless on how to go around this i how should i go about this ? I hate asking questions this general, but since i don't know how to do that, adding any more to the question wouldn't really help. Even the general concept behind this is highly appreciated.

# Answer
> 2 votes
This animation is likely a bunch of different colored sprites moving or fading in to follow the path of the trail. Look up particle systems. They let you control many sprites/objects at once easily with a set of rules to define their movement.

For this example, you can start with a white circle moving in pre-defined path. Using trigonometric functions is a good way to easily make some curved paths, and you can use bezier curves or splines, although they are more complex to define mathematically. You can also just make it follow the mouse cursor.

Either way you choose, once you have the moving circle, you make a list of sprites to store them in different sizes and colors depending on their order in the structure. You pass on the location to the other sprites in the list the on each frame to create a motion lag, which makes the trail.

This tutorial does a great job at showing how to make particles with this kind of behavior in XNA (MonoGame follows almost the same syntax).

# Answer
> 1 votes
What you are looking for is called ribbon trail. While a particle trail does the job as well there are a few problems with using particles:

* missing particles at high speed
* gpu overdraw
* effect limited to particle settings

However if this effect fits your game better then here is a good tutorial: World of Goo Cursor

This porblems were the reason i implemented a 2d ribbon trail in my self made xna like ios/opengl es 2 framework. here is a gist of the objective-c code (syntax is different, functions are more or less the same): Ribbon Trail

My implementation is not perfect and i can list you my known issues:

* The end of the trail is ontop of the beginning (fix: reserve vertices)
* There is a buged triangle at the start of the trail (had no time to work on it since ages)

but this should give you a good idea how to get this effect (trail + round particle on top to make it smooth or generated verticed attached to the trail to make it round)

---
Tags: xna, 2d, monogame
---


# Question
Title: What do these Google Play Buildbox settings mean?
I am using Buildbox to design my first game to put on Google Play store, however I am having some issues. The game is finalized now. But I have a few questions. The settings in Buildbox ask for my

* Bundle ID
* Name on Device
* Review Link
* Leaderboard ID
* Share Message
* License Key
* Google Play ID
* Version Code

Where do I find some of this information? Also is the share message just what I want to have said when the player shares my game?

# Answer
You make up most of this information, and the rest of it is supplied to you when you signed up for your relevant store publishing account. It's all documented in the manual:

> * Bundle ID: A unique identifier that gets embedded into the app and must be unique within a single app store. Usually in the form of com.short-company-name.short-game-name.
> * Name on Device: a short name that will be displayed on the device, once the game is installed. This will appear under the game icon. If the this is too long to display, the device will usually abbreviate the middle of it by using ".."
> * Review Link: link within the app store that will take ther player to a page on the app store where your game can be reviewed.
> * Leaderboard ID: the code-name of the leaderboard. This is what you setup in Apple's Itunes Connect so the game can use it.
> * Share Message: the message to show to the user when prompting to share the game. If you want to show the players' score in this message you can insert the special tag "\[\[SCORE\]\]" into your text. If you want this message to be useful, you will need to put in a link. If you are pushing to multiple platforms, you may want to make this link go to a web pages instead of an app store (perhaps their friend has a different kind of device).
> * Licence Key: Google play only – signing key from the game on Google Play.
> * Google Play ID: If using Google Game Services (leaderboard) then you grab the ID from setting the game up for Google Game Services.

Some of this information is optional, so if you don't have a clue what you should be using (for example, for the leaderboard ID), it's probably because your game does not make use of that feature and you can omit the data.

Your speculation about the use of the share message is correct.
> 2 votes

---
Tags: google-play
---


# Question
Title: Access Entities components via the Entity that holds them, or via a separate System?
Now, I'm implementing a component based game engine and I came to a thought: Which way should I access my components?

* Have a list of Entities, which have a list of Components, and access them by going trough each entity, and updating/drawing/whatever on each component.

or

* Have separate systems for each component type and acces them by going trough that systems components.

Or does it really matter? I think that the second way would seem faster...

# Answer
> 4 votes
I would recommend having *both*.

**Entity/Component Graph**

This defines which entities are attached to which components. In my engine, there is no such thing as an "entity", but any component can have child components. This graph is *not* used to draw or update components, but is only used for logical queries and events that are supposed to effect component sub-trees in the graph. The graph is just made of weak references to components (in C++, pointers. In other languages, unique identifiers), and doesn't contain the components itself.

For example, I have an "onDeath" event that uses the component graph to tell which components need to be destroyed when a parent component has died.

**Component Lists and Systems**

Parallel to the component graph is a set of component lists. For instance, there is a list of all the `Physics` components in the game, a list of all the `Sprite` components, and so on. These lists are aggregated into a big map of component type to component list called the `ComponentManager`.

`ComponentManager` is responsible for updating and drawing all components, one component type at a time. This is far faster than iterating through the component graph, because it has much better cache performance, and allows you to batch state of components before drawing/updating them.

---
Tags: game-design, component-based
---


# Question
Title: Is it OK to use player supplied music in my game?
Is it copyright infringement if I create a game based around music beats but allow the players to use their own mp3 files?

# Answer
> 4 votes
When in doubt, always talk to a lawyer. People on this website are not qualified to give legal advice. That includes me, so don't come back and sue me for giving you incorrect information.

That said, you have to copy something to be breaking any copyright laws. If you're using the music files in-place on the player's computer, you can't be infringing on any copyrights. (There have been arguments made that, when you open a file, you are copying the file to memory and should be subject to those copyright laws. I don't think they were taken very seriously, though.)

Even if you copy the files to another location on the same device, I can't see that being a problem.

Just don't move the player's music collection to the cloud. That can get you in trouble.

# Answer
> 0 votes
Your use of music should stay within the boundaries of personal use. Your case is not very different from listening to music while reading a book. Even the book can suggest to go get and listen a music track while reading one of its chapters.

The game should act like a local music player. It shouldn't publicize the gameplay on social media, multiplayer modes shouldn't broadcast music to other peers, you shouldn't keep the data in cloud where the user can grant access to other users...etc Then there should be no problem.

BUT! It is always a good practice to take legal advice from a lawyer before starting something serious.

---
Tags: legal, music, copyright
---


# Question
Title: Using modified copyrighted music in non-commercial games
Background: I'm making a retro style game for both fun, and an unofficial contest.

I have bought a song, song X. However, I then found notation for song X, and all the instruments. So basically, it's a program recreating song X in a sense.

I took the notation, and used another program to make it sound like a chiptune does (just for the fun of it, and it sounds good :P). However, I would like to use this in my game. It's non-commercial, but is this allowed? I would've said yes, because I'm not actually using the original, copyrighted song.

I think the main point is can I:

* Use the music with no reference to the author
* Use the music with a reference, since it's non-profit.
* Not use the music at all since the melody and rhythm is copyright.

# Answer
> 14 votes
You are using a derivative of the song, which falls under copyright. Also it doesn't matter whether you credit the original artist or not make a profit. It is still copyrighted.

# Answer
> 11 votes
I'll paraphrase my answer from Audio copyright questions (and I am **Not** a Lawyer :)

Note that this assumes you're in the US (or other Berne signatory countries), and in particular, Canada *may* be different, as was discussed.

It also assumes that when you say, "bought a song", you meant bought a *copy* from Amazon or somewhere - if you actually bought *the copyright*, then that's different. :) But buying a copy of a song, does not give you a whole lot of rights. For instance, you can't play it at public performances, without paying royalties (say you were a bartender at a bar, and broadcast the song over the bar's PA system - that's a no-no.)

In general: Anything that is copyrighted, *requires* the copyright owner's permission to use - regardless of whether you intend to make money with the project or not. There are certain very *limited* exceptions, like Fair Use, but that generally only applies to *educational* projects that use short *excerpts* of the material, not an entire piece. And this applies to derivative works (although a parody of the original material is also an exception to that).

Granted - if you aren't making money, the copyright owners probably *won't* come after you - but that's not the same as saying they *can't* legally. Even if it's a free project, they *could* take legal action against you.

RIAA goes after YouTube
RIAA sues the Girl Scouts

# Answer
> 2 votes
When you reproduce a song yourself (making a cover song and not using the original recording), you owe a royalty to the composer of that piece.

If you want to use your version without breaking the copyright and paying anything, you need a written permission from the composer. Since you are reproducing the song this license is called a mechanical license. It doesn't matter your use is commercial or not.

You can get a mechanical license to make covers for many songs from LimeLight or similar services, or you can find the composer (maybe online) and ask directly.

*NOTE: Seems like LimeLight will no longer be operational after March 31st, 2015.*

# Answer
> 1 votes
Don't use existing music, hire a composer to write a parody song or something stylistically similar. Game soundtracks should be unique. ;)

---
Tags: legal, music, audio, copyright
---


# Question
Title: How can I preserve momentum during a jump, but cancel it when a character lands?
I am attempting to code a run key for my platform game in Game Maker. I'm attempting to keep my momentum when I jump, but yet stop moving at a run speed as soon as I hit the ground if Shift has been let go during the jump. How do I go about coding this?

# Answer
No code was presented.

You want to create an algorithm that handles momentum decay.

The underlying run function already causes the object to move quicker. You should store that value and create a function that when released takes that value and starts decaying it, rather than cuts you off immediately.

If you want this to occur only when you jump, you will need to handle the code for that case.
> 1 votes

---
Tags: game-maker
---


# Question
Title: How do find the right GLxx object for a given function in LWJGL?
I'm just starting to learn the fundamentals of OpenGL via LWJGL. Every OpenGL function is implemented as a method on a `GLxx` class. The `xx` corresponds to the version of the spec when that function was introduced, such as `GL20` for functions added in OpenGL 2.0. So far, so good.

The difficulty comes when following tutorials or looking at code that is written against the C API. I'm finding myself having to either guess or Google the version for every single function that I want to use. This is quite time consuming.

Is there a quick way of finding out which version of OpenGL any given feature was introduced? (Or any other way of figuring out the right LWJGL class for a function?).

# Answer
> 0 votes
The reference material on the OpenGL website is a good source for this. The function reference pages there have a "Version Support" section that details which version of the API the function in question is available in. Here's the page for `glDrawElementsBaseVertex`, for example.

A machine-readable form of this data is available via the API XML, which would allow you to write a parser for the `supported` attributes if you were so inclined, and thus build a summary page. It's a bit of work though, you may want to start from an existing tool that can parse this information. Personally I'd stick to site-restricted searches against `opengl.org` for the functions you are interested in. Since you know the mechanical transformation used to go from version to LWJGL scope, you should be good to go; it's a little tedious, unfortunately, but it's not the end of the world.

# Answer
> 0 votes
For me the fastest way has been "Find in files" feature of the IDE / text editor. Recursively searching for the function name from either LWJGL API documentation or source folder quickly reveals the correct class name. This is just a few key presses compared to switching to a web browser and searching from the reference pages.

---
Tags: opengl, lwjgl
---


title: Design pattern for level editor modes?

text:
# Question
Title: Design pattern for level editor modes?
In a level editor that supports multiple editing modes, written in an oop language, how would you go about switching from mode to mode, considering that data itself remains the same?

I am using a MVC pattern like so.

1. A data model for the level's structure.
2. One model for the editor's state depending on the current editing mode and it contains data about the user's editing activities that was not applied or does not affect the level model (i.e what entities or item are currently selected).
3. A view for each mode (they all render similarly but differently cause they put emphasis on different items in the level).
4. Controllers accepting input and manipulating the state. These also differ from one mode to another.

The `Controller` accepts input from the user. It calls the corresponding methods on the `State` model which in turn modifies the `LevelData`. The controller refreshes the `View` after changes are made to the `LevelData` and `State` so these changes are properly reflected to the user.

Currently, to switch, I have all controllers inherit from a base controller that contains the mode switching capability. I have a class called AppContainer (each mode is like an app) that is being informed that a switch needs to be made. This class deactivates the controller and activates a new controller instead. The new controller refreshes the view and clears the state upon reinitialization.

I am wondering if there is a simple way to accomplish the same thing that I haven't though of.

I basically need to switch the Controller, the State and the View. HaxeFlixel does this pretty elegantly. Does anyone know how that is accomplished in high level abstraction?

# Answer
> 2 votes
You can also use the MVVM (Model-View-ViewModel) pattern instead of MVC. You can read the article on wikipedia. I also like this article on codeproject.

Whereas it is mostly used together with WPF, Silverlight, etc. in the .NET world it is also used by AngularJS for example.

So MVVM could be an alternative for you. It is hard to exaplain software architecture patterns accurately with only few words so I leave it up to you to read the articles.

You can abstract your scenario by having different views with the same view-model behind. Or (the way I would do it) a model and then a view-model for every mode. Every view-model type gets coupled to a view and then we switch from one view-model to another with the same model behind to render different aspects of the level (called view-model-driven MVVM).

---
Tags: design-patterns, oop
---


# Question
Title: Pass parameters from html page to start() function in unity3D webplayer application
I want to pass a parameter from web browser to Unity3D web player as soon as it is loaded. I know that, as soon as the web-player is loaded, the `start()` function is execute inside web-player. So I want to pass parameter from web browser to this `start()` function.

# Answer
The documentation you need is here: http://docs.unity3d.com/Documentation/Manual/UnityWebPlayerandbrowsercommunication.html

If you are able to control when you call `Start()`, eg. because that object isn't immediately created, then you can use the `getUnity().SendMessage` route to send in the parameters from the web page.

Otherwise, you might want to embed an `Application.ExternalCall()` into your Start() function to call out to a Javascript function in the web page, which can return the parameters you need.
> 3 votes

# Answer
This one was worked well. (then automatically read parameters from html page as soon as web-player is loaded, this method is good for read the URL parameters)

inside html-\>

```
function OnUnityReady()
{

    u.getUnity().SendMessage("GameObject", "myTest", GET.Use_id);
}

```

inside unity3D C# code -\>

```
void Start()

{

Application.ExternalCall("OnUnityReady");

}

```
> 1 votes

# Answer
I would rather consider using Application.srcValue which is the path to the web player data file relative to the html file (Read Only). Then you can attach a "?" with a parameter string.
> 0 votes

---
Tags: unity, javascript
---


# Question
Title: Is my skeletal animation algorith/representation correct?
I'm representing a rig (skeleton) as:

1. A root pivot point, with a position (Vector3) and a direction (Vector 3).
2. A tree of bones, where each bone is a struct with a rotation (Quaternion) and a length (Float).

I'm projecting the positions of the joints by:

1. Start with the root pivot point and the root bone, rotate it by `bone.rotation` and project it by `bone.length` across its new direction. The new pivot is a pair of position, direction.
2. Repeat for each child bone.

Is that correct?

# Answer
> 6 votes
This will work if all you're concerned about is the translation part of each bone, but it is more common to represent your bone structure as a transformation matrix tree, which is probably the most popular way to do Forward Kinematics.

Define a `Node` as follows:

```
class Node
{
    Transform localTransform;
    Node parent;
    List<Node> children;

    // Computes the global transform of the node with respect to the world.
    Transform ComputeGlobalTransform()
    {
        if (parent == null) return localTransform;
        else return parent.ComputeGlobalTransform() * localTransform;
    }
}

```

A `Link` is a `Node` that has mesh geometry. A `Joint` is a node that connects two links, and rotates around its `Z` axis.

```
class Link : Node
{
    Mesh geometry;
}

class Joint : Node
{
   void SetJointAngle(float value)
   {
         // The local transform is a rotation around the Z axis by convention.
         // Make sure to preserve the translation part of the transform.
         localTransform.SetRotationPart(Matrix.CreateRotationZ(value));
   }
}

```

You can make more complicated joints such as prismatic and ball-in-socket joints fairly easily this way. Representing your links and joints as transforms rather than just a direction and a length also disambiguates the rotation part of your skeletal animation system. It also allows you to offset links in an arbitrary way.

---
Tags: animation, skeletal-animation
---


title: Any way to embed Pygame in webpages?

text:
# Question
Title: Any way to embed Pygame in webpages?
I have a Pygame game, and I was wondering if there was any way to embed it into a webpage to make it easily playable, or if there is a games website that accepts Pygame games.

EDIT: I am now using Unity and am not after the answer anymore, but please answer if you want as it could help others.

# Answer
> 7 votes
You could look at Skulpt.org which provides a completely brower-based implementation of PyGame. However I do not know what external APIs PyGame uses and which are supported by Skulpt.

Edit: it seems Skulpt also has WebGL bindings so this should be very possible!

# Answer
> 0 votes
While poking around looking for PyGame GUI toolkits I came across these two libraries: PyJ2D: http://gatc.ca/projects/pyj2d/ PyJSDL: http://gatc.ca/projects/pyjsdl/

The both seem to allow the execution of PyGame scripts in a browser, the first through Jython and a Java applet and the second through Javascript and HTML5.

I've never used either but they seem to be what you are after.

---
Tags: python, pygame
---


# Question
Title: Client/Server best way of telling client which player it is
I'm making a client/server, everything works grand its very simple, a simple login system, ID, empty variable and the X and Y positions of the player.

Should my server tell my client who it is? and if so what kind of relationship would a client/server usually have?

My server currently stores each connection so I can communicate with one, or all clients - is this the right type of architecture?

# Answer
The question is rather unclear. How exactly the client should manage info about who he is, if that is just to display on players screen "I'm Mike" or to send out commands "I'm Mike, moving knight from c5 to e6" ?

When client connects to a server, it says who he is during login. Then both client and server have that info. Since servers can't trust clients, the server must manage list of clients and know which one is which when sending out packets/messages.

Servers can't trust clients, to disallow kind of cheats, when client named Jack sends a message "I'm Mike, moving knight from c5 to e6", hijacking the game.

Some game messages are addressed and others are broadcast to all. Being able to send messages via server to a single client, to a set of clients or to all at once is a right kind of design.
> 1 votes

---
Tags: architecture, client-server, client
---


# Question
Title: Voronoi / Delaunay Graph - Triangle Circumcenter error
I have written a Delaunay Graph script that given a set of points (voronoi cell/region) will generate the Delaunay triangles with their edges. Considering that the Voronoi diagram is complimentary to the Delaunay graph, I can infer the Voronoi regions, edges and corners once the Delaunay graph is complete.

I had previously implemented this in 2D without any troubles and the results were flawless in all of the diagrams I generated. However, I have since tried to implement this in 3D and have now encountered issues.

My implementation of this appears to work fine in 99.9% of cases which leads me to believe that perhaps floating point/rounding errors may be the problem or (more likely) my understanding of the code used to determine the circumcenter is incorrect.

I have based the following implementation on this answer from How do I find the circumcenter of a triangle in 3D?

```
public static Vector3 Circumcenter(Vector3 a, Vector3 b, Vector3 c)
{
    Vector3 ab = (b - a);
    Vector3 ac = (c - a);

    Vector3 abXac = Vector3.Cross(ab, ac);

    Vector3 i = (ab.sqrMagnitude * ac);
    Vector3 j = (ac.sqrMagnitude * ab);
    Vector3 k = Vector3.Cross((i - j), abXac);

    return (a + (k * (0.5f / abXac.sqrMagnitude)));
}

```

The screenshots below are of two separate graphs both generated by creating the Voronoi cells/regions in nested for-loop's before attempting to solve the graph. I have tried creating the points randomly, hard coding them, setting different values along the Y-axis or having them all set to a specific constant on the Y-axis, all of which exhibit the same behaviour.

These examples do not use Lloyd relaxation but for the sake of completion, running the solver over several iterations also produces incorrect results.

I have been trying to debug this for weeks now and cannot for the life of me understand why this does not work. My understanding of the math is fairly solid but I really can't begin to narrow this down to resolve the issue.

It would appear that when solving the graph, the circumcenter for three of the nodes is sometimes incorrect (or so i'm lead to believe from the visual output). However, the Delaunay representation appears to be correct which leads to even more confusion on my part.

In the above images, the lines and points represent:

* Red point: Voronio cell/region.
* Black Line: Delaunay Edge.
* Blue point: Voronoi Corner.
* White Line: Voronoi Edge.

The Voronoi graph is determined by creating a Delaunay edge between two nodes and first setting the start point of a Voronoi edge. Once the graph finds another Delaunay triangle along this exact same edge between two nodes, the end point of the Voronoi edge is then set completing this edge entirely.

As you can see in the both images, the Delaunay representation of the graph is correct. However, again in both images, the Voronoi representation has incorrect corners which then leads to incorrect edges.

If anyone can shed any light on this, or point me in the right direction, that would be greatly appreciated.

# Answer
> 1 votes
It's hard to tell without source code but it looks like some triangles are overlapping one another:

I'm guessing another issue is that segment A-B is not always considered the same as segment B-A and you end up with internally 2 different edges sharing the same points.

Because the edge looks twice as thick on your screenshot `Red & Blue` are probably 2 edges that should be 1, same with `Green and Purple`:

It could be a bad triangle winding with one edge going backward.

To debug this I recommend printing a log and analyzing it by hand.

First you need to identify the exact edge/vertex indices that are causing issues, then recompile your program to print debug information whenever processing those particular edges/vertices.

You'll be able to gradually narrow down where the error occurs.

---
Tags: graph
---


# Question
Title: Play continuous music when swapping between multiple scenes
I have the following scenario

1. "Main menu" scene containing a game object with an audio source component and a music manager script.
2. An "about us" scene

Music manager script :

```
using UnityEngine;
using System.Collections;
public class ManageMusic : MonoBehaviour {

public static ManageMusic Instance;

void Awake()
{

    if (Instance)
        DestroyImmediate (gameObject);
    else {
        DontDestroyOnLoad (gameObject);
        Instance = this;

    }
  }
}

```

When I click on the "about us" button, the `Game Music object` keeps on playing and I can hear the music, but when I return back to the main menu no music is playing. I can see that the music game object is not destroyed when I return to the main menu and the audio listener has the value of the volume set to `1` , but I can't figure out the problem.

# Answer
Use `DontDestroyOnLoad` for the music player. Reference Also make sure that the music player is a singleton and is not instanciated when re-loading scenes.

See here for details
> 1 votes

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


title: Shader - Realtime texture masking

text:
# Question
Title: Shader - Realtime texture masking
The first thing that comes in mind is masking using RGBA values. With this you can obtain this kind of textures and this kind of results.

But with this, you can only store up to 4 masks inside a texture and blend between maximum 4 textures.

I am wondering if there's a way to store more than 4 masks inside a texture and being able to blend more than 4 textures using this mask texture. The aim would be to store as much as possible masking data inside a texture.

Is it possible ? How ?

# Answer
> 1 votes
If you use a point sampler for your mask texture, then you can store as many IDs as bits in your texture: for a 32-bit RGBA texture you'd be able to store 128 different IDs. In such a case though, as you have a single bit per ID, there's virtually no blending as you have only 0 or 1.

The more bits you devote per ID, the greater the blending granularity, but of course that reduces the number of total IDs. If you go with RGBA32 textures, you have 128 bits at your disposal. You can store 128 IDs with blending value "full" or "none", or 64 IDs with "full", "half", "none" and so on - it's up to you what you write to those 128 bits and how you interpret them.

I can't point you to a whitepaper/link, as this is something that I'd do (and might have done in the past). I will also not provide any detailed code, as it's just bit fiddling; nothing else. The function that you'd need in your shader would be like:

```
    /* Extract the bits that refer to a particular texture id and return the blend factor.
    E.g. if you have 4 bits per id and the bits in the texture are 1001,
    then the blend value would be 9/15 */
    float unpack_id_blend_factor_from_texture_value( uint4 lookup_value, int id, int bits_per_id)
{
    const int total_ids = 128/bits_per_id;
    const int total_ids_per_component = total_ids / 4;
    // get the component that contains the id, and modify
    int value = 0;
    if( id < total_ids_per_component )
    {
        value = lookup_value.x;
    }
    else if( id < (2*total_ids_per_component) )
    {
        value = lookup_value.y;
        id -= total_ids_per_component;
    }
    else if( id < (3*total_ids_per_component) )
    {
        value = lookup_value.z;
        id -= 2*total_ids_per_component;
    }
    else
    {
        value = lookup_value.w;
        id -= 3*total_ids_per_component;
    }

    // shift the value data so that the bits used by the id are in the front
    uint used_bits = value >> (bits_per_id*id);
    // make the rest of the bits -- after the used ones -- zero
    used_bits &= (1 << bits_per_id) -1;
    // get and return the blend value
    return used_bits / float((1 << bits_per_id) -1);
}

```

Now the above should give you an idea how you extract the bits. You use the inverse process to fill the lookup texture.

---
Tags: opengl, textures, shaders, directx, rendering
---


title: NPC daily routines and scene loading

text:
# Question
Title: NPC daily routines and scene loading
I'm making a basic survival RPG in Unity 3d. I'm separating my world into different scenes to save memory but I'm not sure how I'm going to program NPC daily routines.

For example, if the player arrives in a town scene in the morning, how do I ensure that the NPCs are working in appropriate places with the appropriate equipment? I suppose I could hard code it so NPCs are in certain places at certain times. Therefore, if the player arrives at 9:00am then all the NPCs will move to their 9:00am places. I'm just wondering if there is a better way of doing it than that. I can see myself needing to write a lot of code to cover all the possibilities so it could get really messy. I was hoping there was some way I could have the NPC routines continue seamlessly in the background but this would be taxing on memory -if it's even possible.

Any ideas/pointers on this issue would be appreciated.

# Answer
Don't hard-code it, or it'll indeed end up very messy.

You need to script the NPCs daily routines into some data file (XML or other).

Something along the lines of:

```
<npc name="george">
  <schedule start="0:00" end="8:00">
    <sleep at="home"/>
  </schedule>
  <schedule start="8:00" end="9:00">
    <walk leave="home" destination="smithy"/>
  </schedule>
  <schedule start="9:00" end="17:00">
    <runshop at="smithy"/>
  </schedule>
  <schedule start="17:00" end="18:00">
    <walk leave="smithy" destination="home"/>
  </schedule>
  <schedule start="18:00" end="24:00"> <!-- note: no warp-around -->
    <sleep at="home"/>
  </schedule>
</npc>

```

This way you can figure out where every NPC is supposed to be and initialize them properly at loading time.

This doubles as your NPC event script file.
> 5 votes

# Answer
Since this is Unity, I do not recommend working with XML files. The work needed to parse them is just useless. Instead, focus on creating custom editors for your scripts. This will help you in the long run.

1. Create a script for the basic routine. In the editor of this script, you should be able to enter a location and an activity. If you want extra stuff, you may want to use some base class for routines and extend it as needed. A NPC will have *multiple* routine components, and you will choose between them depending on the current time. Identify routines by name, or something else, for each NPC. Make sure the `Location` and `Activity` properties of the routine are editable in Unity's editor. More exactly, you want to be able to *select a location from the scene*. Sleep routine for the king? Find the bed in the scene's list of objects and drag it to the routine's location slot :) Pretty handy.
2. Create a script for the schedule. Schedules map timeframes to routine scripts. `Dictionary<Timeframe, Routine>`.
3. Attach a schedule to each of your NPCs. Schedules will manage the routine components that you have and will add.
4. Create a custom editor for your schedule script so that it provides a nice and GUI-driven way to select the hours for each routine.
5. Make a nice red glowing warning message in the editor if you haven't filled the 24 hours a NPC needs. This is useful, and will catch plenty of bugs. The same applies for empty location slots or empty activities.
6. Add any sort of other functionality you might want, extending the editor will make it a breeze.

Extend the editor to add custom functionality. It's worth it. Don't ignore Unity's engine features by using workflows that fit other engines better.

When the player enters a level at a specific hour, you have a few choices. Spawn multiple NPCs in similar places and make them walk to their routine's location. This might look weird. Some old games did it (Gothic). Personally, I'd auto-teleport all NPCs to their routine's location when the level starts.

`me.teleportAt(mySchedule.myCurrentRoutine.location);`
> 0 votes

---
Tags: unity, scripting, scene, npc
---


title: Perspective Projection - Drawing Lines

text:
# Question
Title: Perspective Projection - Drawing Lines
So I sort of understand the math behind projecting 3d points onto a 2d plane. It's just some simple dividing and multiplication of distances. However I can't seem to wrap my head around projecting lines from 3d space onto a 2d plane.

Demonstration:

Just to make this a little more simple, I'm going to be talking in terms of 2d projection onto a 1d line, because it's the same concept for 3d to 2d. So my issue is that if I want to project the line AB onto the viewing window which has a set focal length, I can just project both of the points of the line (A and B) onto the perspective line, and then draw the line between those two on the viewing window. However the difficulty comes when trying to project the line CD onto the line. The second point (D) of the line is behind the viewing window, and therefore cannot be projected onto the line. So how would one go about drawing line CD in the perspective window?

# Answer
> 1 votes
If You subdivide the line into CE and ED and the projection of the 2 lines combined will be the projection of the full line.

Using that we split the line where it intersects the screen then EC' will be the resulting line and you ignore the ED part of the line.

Current day graphics pipelines will do this automatically using frustum culling with the near plane.

---
Tags: 2d, 3d, projection, perspective, lines
---


# Question
Title: How can I draw things just in an area that can have a shape such as the shape of the letter B and not draw outside this form?
I want to draw stuff on an image, for Example, if I have a letter, as an image and I want to draw on the letter it is necessary that this image is touchable. This is what I did:

```
Image.addListener (new clickListener () {
public boolean Touchdown (InputEvent event, float x, float y, int pointer, int button)
{
/ * posCurseurX = x;
posCurseurY = y * /

// Begin to draw on the screen

touch = true;
traitSprite = new Sprite (rectangleTexture, 0.0, tailleTrait, tailleTrait)

traitSprite.setPosition (x-tailleTrait / 2 (height) -y - tailleTrait / 2);
tabRectangelSprite.add (traitSprite);
counter ++;

dessinerTrait (touch);
dessinerCurseur ();
// The index of the number of meter rectangle forming a line

return true;
}
});

```

But I want to add another listener for mouse movements, but it does not work with MouseMove. and the other thing I would like, is to draw that if I'm on my image. If the cursor position is not between the coordinates of the image so I will not draw.

that's what I tried:

```
if (posCurseurX> = image.getX posCurseurX && <= + image.getX image.getWidth) {

```

..}

But the texture does not necessarily have that width, that's an example:

# Answer
> 1 votes
Check out the principles behind stencil buffers and/or masking.

Essentially what you want to do is generate a mask/stencil to mark out your drawing area and use this mask to decide if the user can draw or not.

For example, take your shapes you want the user to draw on and render them as pure white into a full-screen buffer, with a default colour of black. When the user tries to draw you simply take the screen pixel coordinate and lookup that pixel in the full-screen buffer. If the pixel is white, then the user can draw, if it's black the user can't.

You can avoid this check altogether. If you just want the user to be able to draw on top of an image, just let them draw everywhere, but use a stencil buffer to limit the area of the image you show on the screen - much like using a stencil.

In other words, let the user draw all over the screen but only show the parts of the image that are overlaid by the B shape.

How to do this? Draw B to a stencil buffer. Let the user draw all over a full screen buffer. Draw the buffer with the B stencil in place.

If you don't want to use stencil buffers there are a host of other methods such as custom shaders that do the query for white in the mask or using the black & white stencil buffer as the alpha channel of the buffer the user is drawing to.

Check out this example of OpenGL stencil buffers. There are numerous examples of how to use this and they can be used on Android devices. Here is one that seems to be related to doing this process in libgdx.

---
Tags: libgdx
---


title: 2D Smooth Tile Lighting

text:
# Question
Title: 2D Smooth Tile Lighting
I am currently working on a 2d platformer and have the general idea of how to apply 'lighting' to my level, but I am not sure at all how to make it smooth, similar to Terraria, as you can see here.

I apply a tint to my tiles based on how many lights or open tiles there are nearby. This tint varies from Color.White to a gray to Color.Black.

My question is how to 'smoothen' this out and if there is generally a better method to do this. I'm not entirely a fan of shaders at the moment, as I am still learning about them.

Thanks!

# Answer
> 2 votes
I recently attempted this very thing and the question and answer here got me through it - How can I acheive a smooth 2D lighting effect?.

**I'll explain it for you though:**

What this method does is instead of 'tinting' your tiles directly, it draws that 'tinting' color to a new texture (called the LightMap), scaled down to 1 pixel for each tile. Then you draw all the tiles normally without any color tinting at all. After that you draw the LightMap to the screen and blend the LightMap colors with the tile colors. By scaling the LightMap up to the screen size before drawing, XNA will handle interpolating the lighting values for you.

**Let's begin:**

According to the answer linked above you will need a custom `BlendState` so put one somewhere in your lighting engine and initialize it like this:

```
BlendStateMultiply = new BlendState()
{
    AlphaSourceBlend = Blend.DestinationAlpha,
    AlphaDestinationBlend = Blend.Zero,
    AlphaBlendFunction = BlendFunction.Add,
    ColorSourceBlend = Blend.DestinationColor,
    ColorDestinationBlend = Blend.Zero,
    ColorBlendFunction = BlendFunction.Add
};

```

You are going to use this `BlendState` to draw your `RenderTarget2D` with the lighting values onto the scene and have them light the tiles appropriately.

So first thing first you are going to need to do is draw your lighting values to the `RenderTarget2D`. Place a `RenderTarget2D` somewhere in your lighting engine and then add the following to the beginning of your `Draw()` method:

```
spriteBatch.GraphicsDevice.SetRenderTarget(renderTarget);
spriteBatch.GraphicsDevice.Clear(Color.Transparent); //or Color.White.
spriteBatch.Begin();

```

**EDIT: --------------------------------**

To figure out the size of the RenderTarget2D you need to examine how you are drawing your tiles. If you are drawing your entire map of tiles then it is simply the amount of tiles going horizontally as the width, and vertically as the height. If you are being clever and using a 2D camera and culling tiles that are not on the screen then you need to work around that.

For example if your rendering looks something like this:

```
for(int x = tileStartX; x < tileEndX; x++)
{
    for(int y = tileStartY; y < tileEndY; y++)
    {
        spriteBatch.Draw(tiles[x][y].texture, new Vector2(x, y), Color.White);
    }
}

```

Where `tileStartX` & `tileStartY` is the top left most tile that should be drawn and `tileEndX` & `tileEndY` is the bottom right most tile, then you should initialize the `RenderTarget2D` to the distance between `tileStartX` & `tileEndX` and between `tileStartY` & `tileEndY`. This is generally your screenSize plus a single tile buffer. So for example with a screen size of 1280x720 and a tile size of 32 you would end up with 42 tiles for the width (1280 / 32 = 40 + 1 tile buffer on each side) and 25 for the height (720 / 32 = 22.5 rounded up to 23 + a 1 tile buffer on each side) which are the dimensions for the `RenderTarget2D`.

**End Edit: ---------------------------**

Now you need a `Texture2D` that is a single, white, pixel so go ahead and make one in whatever photo editing software you've got and add it to your project. Then you are going to use this texture to draw your lighting colors to the `RenderTarget2D` like so:

```
for(int x = 0; x < tiles.count; x++)
{
    for(int y = 0; y < tiles[x].count; y++)
    {
        spriteBatch.Draw(whitePixelTexture, new Vector2(x, y), tiles[x][y].tintingcolor);
    }
}

```

I'm assuming all your tiles are in a 2D list or array. Basically you need to loop through all the tiles you want to draw and then draw their tinting color value with the single pixel texture. The end result is that the `RenderTarget2D` is now a LightMap, containing all the `Color` values you want to blend over your tiles.

Now you need to switch back to drawing to the screen so add this:

```
spriteBatch.End();
spriteBatch.GraphicsDevice.SetRenderTarget(null);
spriteBatch.Begin();

```

Right after that line is where you need to draw your tiles, but make sure that instead of drawing them with the 'tinting' color you just draw them with `Color.White`. Also make sure to `spriteBatch.End();` after drawing your tiles.

There's one final thing to do in order to light your tiles and that is to draw the LightMap to the screen. When you do this you need to stretch it to the correct width/height. You can find this value by multiplying the size of the texture by the size of your tiles. The complete example at the bottom will explain better.

Before drawing your LightMap you need to set a few things in the `spriteBatch.Begin()` method. The first is the `SpriteSortMode` (which doesn't matter at this point) and the second is the `BlendState` which is where you will use the custom BlendState we created earlier.

```
spriteBatch.Begin(SpriteSortMode.Deferred, BlendStateMultiply);
spriteBatch.Draw(renderTarget, new Rectangle(0, 0, renderTarget.Width * tileWidth, renderTarget.Height * tileHeight, Color.White);
spriteBatch.End();

```

If all was done correctly then you should have a properly lit scene with a mild amount of interpolation between the lighting on your tiles. Though this effect may not be exactly what you desired, it is definitely a good step towards learning about lighting and finding your own method later on.

Here is the complete Draw() method in your lighting engine.

```
public void Draw(SpriteBatch spriteBatch)
{
    //Swap drawing to target the RenderTarget2D and Begin()
    spriteBatch.GraphicsDevice.SetRenderTarget(renderTarget);
    spriteBatch.GraphicsDevice.Clear(Color.Transparent);
    spriteBatch.Begin();

    //Draw the lighting values to the RenderTarget2D
    //This loop needs to be the exact same one you use to Draw your tiles later.
    for(int x = 0; x < tiles.count; x++)
    {
        for(int y = 0; y < tiles[x].count; y++)
        {
            spriteBatch.Draw(whitePixelTexture, new Vector2(x, y), tiles[x][y].tintingColor);
        }
    }
    //End the current batch and switch to drawing to the screen
    spriteBatch.End();
    spriteBatch.GraphicsDevice.SetRenderTarget(null);

    spriteBatch.Begin();
        //Draw the tiles normally, with a Color.White parameter
        for(int x = 0; x < tiles.count; x++)
        {
            for(int y = 0; y < tiles[x].count; y++)
            {
                spriteBatch.Draw(tiles[x][y].texture, new Vector2(x * tileWidth, y * tileHeight), Color.White);
            }
        }

    //End and Begin the spriteBatch with our custom BlendState
    spriteBatch.End();
    spriteBatch.Begin(SpriteSortMode.Deferred, Multiply);

        //Draw the RenderTarget2D (LightMap) over the scene, stretching to the correct values..
        //..where tileWidth is the width of your tiles and tileHeight the height.
        spriteBatch.Draw(renderTarget, new Rectangle(0, 0, renderTarget.Width * tileWidth, renderTarget.Height * tileHeight), Color.White);
    spriteBatch.End();
}

```

# Answer
> 1 votes
Okay, you've done the right thing. To get smooth lighting, all that's necessary is to have a separate brightness for each tile *vertex* rather than each tile. Then, render the tiles using a series of textured quads. The brightness of each vertex is just the average of the brightness of its neighboring tiles.

However, you are using XNA, so in order to do this, you will *have* to make use of a custom shader passed in to your spritebatch so that it can use vertex coloring. It is not too hard to do this. However, if you want it to have good performance, you will need to abandon spritebatch and draw textured quads manually.

# Answer
> 1 votes
You draw the lighting values into a small gray scale (or color) texture with 1 texel per map tile, enable interpolation, then sample this interpolated texture to tint your tiles.

This will smooth out the lighting.

Note: doing per-vertex interpolation rather than texture sampling will cause to interpolate over the 2 triangles that makes up the quad and you'll see the 2 triangle gradient split for the tile like on the left cube:

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


# Question
Title: How can I merge multiple sprite into one sprite or texture using Unity3d?
I have an avatar generator where someone can create a custom avatar with layers superimposed. And in order to reuse this image multiple times, i want to merge all layers in one image. Is there any way on unity3D to create this image.

I've already coded that :

```
atlas = new Texture2D (width, height, TextureFormat.RGBA32, false);
foreach (Sprite s in allSprite) {
        atlas.SetPixels (0, 0, atlas.width, atlas.height, s.texture.GetPixels (0, 0, atlas.width, atlas.height));
        atlas.Apply ();
}

```

My problem is to keep the transparency and not erase old layers where pixels are transparent. The `setPixels` method replace old pixels in `atlas` by new one. I can't loop over pixels because of the size of the image (1024\*1024) and more than 6 layers.

# Answer
You can use a RTT (render-to-texture) and a custom camera to one-shot render to it to merge all the layers using the GPU.

You can then save and use the resulting texture.

http://docs.unity3d.com/Manual/class-RenderTexture.html

If your render texture has alpha then it will maintain the composited alpha values as long as you use the proper separate color-alpha blending mode in the shaders:

```
Blend SrcAlpha OneMinusSrcAlpha, OneMinusDstAlpha One

```

If you only need full-size texture blending you can use graphic blit commands to get pixel-aligned full-texture blend (http://docs.unity3d.com/ScriptReference/Graphics.Blit.html)

Otherwise you'll need to draw pixel-aligned (http://docs.unity3d.com/ScriptReference/GL.LoadPixelMatrix.html) quads using the GL namespace functions (http://docs.unity3d.com/ScriptReference/GL.html)
> 4 votes

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


title: Discarding triangles in Unity

text:
# Question
Title: Discarding triangles in Unity
I have about 2+ years of experience in computer gaming development and I just started writing my own shaders to help me utilize performance. I have this problem that I'm trying to work around but after several tries nothing seems to work.

Basically, I have a plane that's made of `16641` vertices - thats `32768` triangles and I know that is pretty much. The plain has a texture on it with some colors. Now, what I am trying to do is placing units on that plane. Where they stand, the vertex under them will have a certain color but all other vertexes on the plain will have the color white. The idea is to discard and don't draw vertexes that aren't white.

Now in the shader, I tried two things.

1 - In the vertex input I check if the vertex, called o, had the o.color.b value != 0. If so it was given the alpha value of 0 and would not be seen when rendering.

2 - In the vertex output, I checked the same thing ( if(i.color.b !=0) discard;) and discarded the fragment so it would not be rendered. That way I thought Unity should not count these triangles and thus wouldn't waste performance.

Now when I run my game and open the stats, with the plane active I have 85.8k triangles and only `28` draw calls. With the plane un-active I have `20.2k` triangles and `26` draw calls (Note : there are some units, interface, skies etc around that counts up to 26 draw calls, thus the plane is just `2` draw calls).

I thought this solution would be clever to save draw calls (developing for mobile games) by treating this plane and the colors under the units as one instead of making them all a separate gameobject. Turns out, I'm way over budget on the triangles. Does anyone know if this is possible and if so, give a good answer or explenation?

Here is the following shader.

```
Shader "Custom/Ottar_VertexBasic" {
Properties {
    _MainTex ("Particle Texture", 2D) = "white" {}
    _Transparency("Transparency", Range(0,1)) = 1
}

SubShader {
    Tags { "Queue" = "Transparent" }
    Blend SrcAlpha OneMinusSrcAlpha
    AlphaTest Greater .01
    ColorMask RGB
    Lighting Off
    ZWrite Off
    //Fog { Color (0,0,0,0) }
    Pass {
        CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma multi_compile_builtin
            #pragma fragmentoption ARB_precision_hint_fastest
            #include "UnityCG.cginc"

            uniform float4  _MainTex_ST;
            float _Transparency;
            //VertexInput
            struct vI {
                float4 vertex : POSITION;
                float4 texcoord : TEXCOORD0;
                float4 color : COLOR;
            };

            uniform sampler2D _MainTex;
            //VertexOutput
            struct vO {
                float4 pos : SV_POSITION;
                float2  uv;
                float4 color;
            };

            vO vert (vI v) {
                vO o;
                o.pos = mul (UNITY_MATRIX_MVP, v.vertex);
                o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
                float4 viewPos = mul(UNITY_MATRIX_MV, v.vertex);
                o.color = float4(v.color.rgb, v.color.a*1);
                //if(o.color.b != 0) o.color.a = 0;
                //else o.color.a = 1;
                return o;
            }

            float4 frag (vO i) : COLOR {

                if(i.color.b !=0) discard;
                else
                {
                half4 texcol = tex2D( _MainTex, i.uv );
                return texcol*i.color*_Transparency;
                }
            }
        ENDCG
    }
}
Fallback "Particles/Alpha Blended"
}

```

# Answer
> 2 votes
Unity cannot know which triangles are eliminated in the GPU shaders, it counts the number of triangles sent to the GPU, not just the ones that end up drawn.

Using the discard keyword forces the shader to run on all pixels, breaking the GPU's hidden surface removal optimization.

That is on top of processing all the triangles.

If you want to eliminate triangles at the vertex shader set all its vertices to the same value (such as zero). It will create a **degenerate triangle** that will be eliminated by the GPU.

```
        vO vert (vI v) {
            vO o;
            o.pos = mul (UNITY_MATRIX_MVP, v.vertex);
            o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
            o.color = float4(v.color.rgb, v.color.a*1);
            if(o.color.b != 0) { // all vertices must end up with the same color.b
                o.pos = 0;
            }
            return o;
        }

```

And disable blending if you don't need it:

`Blend One Zero`

---
Tags: unity, shaders, clipping
---


# Question
Title: D3D11/C++ Inaccuracies in uv interpolation in pixel shader. How to avoid?
I'm trying to draw a quad with a texture onto the screen such that texels and pixels perfectly align. Sounds pretty easy. I draw 2 triangles (as TRIANGLE\_LIST, so 6 vertices) using these shaders:

```
struct VSOutput
{
    float4 position     : SV_POSITION;
    float2 uv           : TEXCOORD0;
};

VSOutput VS_Draw(uint index : SV_VertexId)
{
    uint vertexIndex = index % 6;
    // compute face in [0,0]-[1,1] space
    float2 vertex = 0;
    switch (vertexIndex)
    {
        case 0: vertex = float2(0, 0);  break;
        case 1: vertex = float2(1, 0);  break;
        case 2: vertex = float2(0, 1);  break;
        case 3: vertex = float2(0, 1);  break;
        case 4: vertex = float2(1, 0);  break;
        case 5: vertex = float2(1, 1);  break;
    }
    // compute uv
    float2 uv = vertex;
    // scale to size
    vertex = vertex * (float2)outputSize;
    vertex = vertex + topLeftPos;
    // convert to screen space
    VSOutput output;
    output.position = float4(vertex / (float2)outputSize * float2(2.0f, -2.0f) + float2(-1.0f, 1.0f), 0, 1);
    output.uv = uv;
    return output;
}

float4 PS_Draw(VSOutput input) : SV_TARGET
{
    uint2 pixelPos = (uint2)(input.uv * (float2)outputSize);
    // output checker of 4x4
    return (((pixelPos.x >> 2) & 1) ^ ((pixelPos.y >> 2) & 1) != 0) ? float4(0, 1, 1, 0) : float4(1, 1, 0, 0);
}

```

where `outputSize` and `topLeftPos` are constants and expressed in pixel units.

Now for outputSize = (102,12) and topLeftPos = (0,0) I get (what I would expect):

But for outputSize = (102,12) and topLeftPos = (0,0.5) I get:

As you can see there is a uv-discontinuity where the two triangles connect and interpolation of uv is inaccurate. This basically happens (in x and y) only at positions around the .5 (actually below .49 it correctly snaps to texel 0 and above .51 it snaps correctly to texel 1, but in between I get this artifact).

Now for the purpose I need this for it is essential to have pixel perfect mapping. Can anyone enlighten me why this happens?

# Answer
In theory it should not happen but because of the way the GPU rasterizes triangle lines there are some rounding errors on this particular GPU that differ between the texture coordinates and the pixel coordinates.

Texture coordinates does not use the same precision as the vertex coordinates, add to this perspective correction (even though the triangles are flat on screen) plus the way float numbers work and you get those pixel wiggles.

It could also be a loss of precision or difference in precision in the GPU's sub-pixel accuracy calculation of both vertex and texture coordinates.

Different GPUs and drivers will give different results.

Try changing the `output.position` line by adding floor() :

```
output.position = float4(floor(vertex) / (float2)outputSize * float2(2.0f, -2.0f) + float2(-1.0f, 1.0f), 0, 1));

```

This will remove the fractions of pixels and fix the rounding errors on most GPU/Drivers.
> 2 votes

---
Tags: c++, directx11, hlsl, uv-mapping
---


# Question
Title: GLSL: Incompatible Types at Initialisation (and no available implicit conversion)
I'm recieving the following error when compiling my GLSL shader:

```
 Incompatible types in initialization (and no available implicit conversion)

```

It occurs on line `94`:

```
 int shadowMap = lightToShadowMapMapping[i];

```

I'm guessing its an incorrect type somewhere, however it doesn't make sense as `lightToShadowMapMapping` is an int array and the `i` variable is an int as well.

Here is the full source:

```
    0   | #version 400
    1   | #define MAX_LIGHTS 10
    2   |
    3   | in vec3 lightIntensity;
    4   | in vec3 surfacePosition;
    5   | in vec4 eyeSpacePosition;
    6   | in vec3 normal;
    7   |
    8   | uniform int numLights;
    9   | uniform struct Light {
    10  |    vec4 position;
    11  |    vec3 intensities; //a.k.a the color of the light
    12  |    float attenuation;
    13  |    float ambientCoefficient;
    14  |    float coneAngle;
    15  |    vec3 direction;
    16  | } allLights[MAX_LIGHTS];
    17  |
    18  | uniform float materialShininess;
    19  | uniform vec3 materialSpecularColor;
    20  |
    21  | uniform vec3 cameraPosition;
    22  |
    23  | // shadows
    24  | in vec4[MAX_LIGHTS] shadowTextureCoordinates;
    25  | uniform sampler2D[MAX_LIGHTS] shadowMaps;
    26  | uniform int[MAX_LIGHTS] lightToShadowMapMapping;
    27  |
    28  | layout(location = 0) out vec4 finalColor;
    29  |
    30  | vec3 applyLight(Light light, vec3 surfaceColor, vec3 normal, vec3 surfacePosition, vec3 surfaceToCamera) {
    31  |     vec3 surfaceToLight;
    32  |     float attenuation = 1.0;
    33  |     if(light.position.w == 1) {
    34  |         // directional light
    35  |         surfaceToLight = normalize(light.direction);
    36  |     } else {
    37  |         // point light
    38  |         surfaceToLight = normalize(light.position.xyz - surfacePosition);
    39  |         float distanceToLight = length(light.position.xyz - surfacePosition);
    40  |         attenuation = 1.0 / (1.0 + light.attenuation * pow(distanceToLight, 2));
    41  |
    42  |         // cone restrictions
    43  |         if(light.coneAngle > 0.0) {
    44  |             float lightToSurfaceAngle = degrees(acos(dot(-surfaceToLight, normalize(light.direction))));
    45  |             if(lightToSurfaceAngle > light.coneAngle) {
    46  |                 attenuation = 0.0;
    47  |             }
    48  |         }
    49  |     }
    50  |
    51  |     // ambient
    52  |     vec3 ambient = light.ambientCoefficient * surfaceColor.rgb * light.intensities;
    53  |
    54  |     // diffuse
    55  |     float diffuseCoefficient = max(0.0, dot(normal, surfaceToLight));
    56  |     vec3 diffuse = diffuseCoefficient * surfaceColor.rgb * light.intensities;
    57  |
    58  |     // specular
    59  |     float specularCoefficient = 0.0;
    60  |     if(diffuseCoefficient > 0.0) {
    61  |         specularCoefficient = pow(max(0.0, dot(surfaceToCamera, reflect(-surfaceToLight, normal))), materialShininess);
    62  |     }
    63  |     vec3 specular = specularCoefficient * materialSpecularColor * light.intensities;
    64  |
    65  |     return ambient + attenuation * (diffuse + specular);
    66  | }
    67  | //#include "lighting/fog"
    68  | float sampleShadowMap(sampler2D shadowMap, vec2 coords, float compare) {
    69  |     return step(compare, texture(shadowMap, coords).r);
    70  | }
    71  |
    72  | float calculateShadow(sampler2D shadowMap, vec4 initialCoords) {
    73  |     vec3 coords = (initialCoords.xyz / initialCoords.w) * 0.5 + 0.5;
    74  |
    75  |     return sampleShadowMap(shadowMap, coords.xy, coords.z);
    76  | }
    77  |
    78  | in vec2 textureCoordinate;
    79  |
    80  | uniform sampler2D materialTexture;
    81  |
    82  | void main() {
    83  |     vec4 surfaceColor = texture(materialTexture, textureCoordinate);
    84  |     vec3 surfaceToCamera = normalize(cameraPosition - surfacePosition);
    85  |
    86  |     vec3 newNormal = normal;
    87  |     if(!gl_FrontFacing) {
    88  |         newNormal = -normal;
    89  |     }
    90  |
    91  |     vec3 linearColor = vec3(0);
    92  |     for(int i = 0; i < numLights; ++i) {
    93  |         vec3 shadowAmount = 1;
    94  |         int shadowMap = lightToShadowMapMapping[i];
    95  |         if(shadowMap != -1) {
    96  |             shadowAmount = calculateShadow(shadowMaps[shadowMap], shadowMapCoordinates[shadowMap]);
    97  |         }
    98  |
    99  |         linearColor += applyLight(allLights[i], surfaceColor.rgb, newNormal, surfacePosition, surfaceToCamera) * shadowAmount;
    100 |     }
    101 |
    102 |     vec3 gamma = vec3(1.0/2.2);
    103 |     finalColor = vec4(pow(linearColor, gamma), surfaceColor.a);
    104 |
    105 |     /*float fogCoordinate = abs(eyeSpacePosition.z / eyeSpacePosition.w);
    106 |     finalColor = mix(finalColor, fogParams.color, getFogFactor(fogParams, fogCoordinate));*/
    107 |
    108 |     /*if(!gl_FrontFacing) {
    109 |         finalColor = mix(vec4(1, 0, 0, 1), finalColor, 50);
    110 |     }*/
    111 | }

```

I usually don't like posting huge code samples for others to check, but in this case I have racked my brains and searched the net for a solution but I can't find it. Thanks very much if you can help!

# Answer
I think it's the line right above it:

```
 vec3 shadowAmount = 1;

```

change it to:

```
 vec3 shadowAmount = vec3(1.0);

```

Looks like your line numbering is off by one.

Otherwise try explicitly casting to int in case the compiler has a different bug.

```
 int shadowMap = (int)(lightToShadowMapMapping[i]);

```
> 2 votes

---
Tags: opengl, glsl
---


title: OpenGL position from depth is wrong

text:
# Question
Title: OpenGL position from depth is wrong
My engine is currently implemented using a deferred rendering technique, and today I decided to change it up a bit.

### First I was storing 5 textures as so:

`DEPTH24_STENCIL8` \- Depth and stencil
`RGBA32F` \- Position
`RGBA10_A2` \- Normals
`RGBA8` x 2 - Specular & Diffuse

I decided to minimize it and reconstruct positions from the depth buffer. Trying to figure out what is wrong with my method currently has not been fun :/

## Currently I get this:

which changes whenever I move the camera... weird

---

# Vertex shader

**really simple**

```
#version 150

layout(location = 0) in vec3 position;
layout(location = 1) in vec2 uv;

out vec2 uv_f;

void main(){
    uv_f = uv;
    gl_Position = vec4(position, 1.0);
}

```

---

# Fragment shader

**Where the fun (and not so fun) stuff happens**

```
#version 150

uniform sampler2D depth_tex;
uniform sampler2D normal_tex;
uniform sampler2D diffuse_tex;
uniform sampler2D specular_tex;

uniform mat4 inv_proj_mat;
uniform vec2 nearz_farz;

in vec2 uv_f;

... other uniforms and such ...

layout(location = 3) out vec4 PostProcess;

vec3 reconstruct_pos(){
    float z = texture(depth_tex, uv_f).x;
    vec4 sPos = vec4(uv_f * 2.0 - 1.0, z, 1.0);
    sPos = inv_proj_mat * sPos;

    return (sPos.xyz / sPos.w);
}

void main(){
    vec3 pos = reconstruct_pos();
    vec3 normal = texture(normal_tex, uv_f).rgb;
    vec3 diffuse = texture(diffuse_tex, uv_f).rgb;
    vec4 specular = texture(specular_tex, uv_f);

    ... do lighting ...

    PostProcess = vec4(pos, 1.0); // Just for testing
}

```

---

# Rendering code

**probably nothing wrong here, seeing as though it always worked before**

```
this->gbuffer->bind();
gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);

gl::Enable(gl::DEPTH_TEST);
gl::Enable(gl::CULL_FACE);

... bind geometry shader and draw models and shiz ...

gl::Disable(gl::DEPTH_TEST);
gl::Disable(gl::CULL_FACE);
gl::Enable(gl::BLEND);

... bind textures and lighting shaders shown above then draw each light ...

gl::BindFramebuffer(gl::FRAMEBUFFER, 0);
gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);

gl::Disable(gl::BLEND);

... bind screen shaders and draw quad with PostProcess texture ...

Rinse_and_repeat(); // not actually a function ;)

```

---

# Why are my positions being output like they are?

# Answer
Your positions are converted from WCS ( World Coordinate System) to NDC (Normalized Device Coordinates) in order to by saved inside the depth buffer. This is achieved by multiplying your coordinates with the view matrix to convert them to ECS (Eye Coordinate System) and then with the projection matrix. And at last they are divided by W component in order to be converted to NDC.
So in order to get them back to WCS you need to multiply the coordinates by the inverse(projectionMatrix * viewMatrix).
Your fragment code should be:

```
#version 150

uniform sampler2D depth_tex;

uniform mat4 inv_proj_view_mat;
uniform vec2 nearz_farz;

in vec2 uv_f;

... other uniforms and such ...

layout(location = 3) out vec4 PostProcess;

vec3 reconstruct_pos(){
    float z = texture(depth_tex, uv_f).x;
    vec4 sPos = vec4(uv_f * 2.0 - 1.0, z, 1.0);
    sPos = inv_proj_view_mat * sPos;

    return (sPos.xyz / sPos.w);
}

void main(){
    vec3 pos = reconstruct_pos();

    ... do lighting ...

    PostProcess = vec4(pos, 1.0); // Just for testing
}

```

OpenGL Transformation

**UPDATE**
Also as Lasse said in his comment you can do the lighting calculations in view space (ECS). You can achieve that by multiplying the position and light direction of each light with your view matrix. Keep in mind that if you use a scaling factor inside your view matrix you should multiply the light direction with the inverse(transpose(viewMatrix)) as you do with normals.
> 3 votes

# Answer
You seem not to have a remapping matrix. By adding it, it fixed my issues. I do not know if it helps you since I've not had a problem looking like that, but here it is anyway:

```
uniform mat4 RemapMatrix;
...
vec4 Viewspacepixel = (InvProj * RemapMatrix * vec4(FragScreenCoords, DepthSample, 1.0));

```

And in my camera code:

```
RemapMatrix = Matrix4.CreateScale (2) * Matrix4.CreateTranslation (-1, -1, -1);

```

What this remapping matrix does, is that it translates the coordinates back in -1..1 range from 0..1 range. Source and more info here.

Also, for optimization purposes I'd send the inverted projection matrix for the shader through uniform. Inverting the matrix is quite costly process and with your current implementation you do that on every fragment while you only need to do that only once for the scene.
> 0 votes

# Answer
After a full day of testing and google searching I finally came upon the fix so I'm sharing it here :

```
uniform vec2 Resolution;//This is the render target size, i.e. what you feed into glViewport

        vec2 screen;
        screen.x = ( gl_FragCoord.x - Resolution.x / 2.0 ) / ( Resolution.x / 2.0 );
        screen.y = ( (Resolution.y - gl_FragCoord.y) - Resolution.y / 2.0 ) / ( -Resolution.y / 2.0 );
        float D = texture2D( DepthTextureSampler, Texcoord ).r;
        D = D * 2.0 - 1.0;
        vec4 WorldPos = InvMVP * vec4( screen.x, screen.y, D, 1.0);
        WorldPos.xyz /= WorldPos.w;

```

InvMVP is computed as inverse( Projection * View ), no RemapMatrix thing needed ! One of the issues I had is that I think my matrix code is DirectX-like hence why the Y of the screen coord needs to be inverted(Resolution.y - gl\_FragCoord.y). I suggest doing simple tests to figure out if the gl\_FragCoord is in the right space. The depth for some reason needs to be brought back to -1..1 space, I didn't knew that either since my DX code never does that and works fine. Hope it helps.
> 0 votes

---
Tags: opengl, c++, glsl, deferred-rendering, mathematics
---


# Question
Title: How can I end my game when the right character statistics get to 0?
I'm creating a text-based RPG game. In my game, a player has five different stats, which might decrease over time as the player does certain things.

```
public static int HP = 100;         //CHARACTER STARTING VITAL HIT POINTS
public static int food = 100;       //CHARACTER STARTING FOOD
public static int water = 100;      //CHARACTER STARTING WATER
public static int sanity = 100;     //CHARACTER MENTAL SANITY
public static int stamina = 100;    //CHARACTER STARTING STAMINA

```

I'm not sure how I can implement the logic to *end* the game when any of those stats reaches zero. My main game loop looks like this:

```
public static void main(String args[]){
    Map mainMap = new Map(10, 10);
    Character hero = new Character(mainMap);
    Main.start();

    while (true) {
        printmap(hero, mainMap);

        // Ask the player what direction to move, move the player.
        Character.moving();

        // ...
    }
}

```

The `Character` type has instances of all the players stats (as well as methods to increase or decrease them). How can I accomplish ending the game when a stat hits zero?

# Answer
> 2 votes
You already have a game loop that (currently) runs "forever:"

```
while (true) {
  ... do stuff ...
}

```

What you want to do instead is guard this loop with a variable that says if the game is done yet:

```
bool done = false;
while (!done ) {
  ... do stuff ...
}

```

Then, every time through the loop after you've checked for player input, drawn the map, et cetera, you can check to see if you ending conditions (winning or losing) have been met. For example, if `Character` has a method to check individual player stats, you could do:

```
bool done = false;
while (!done ) {
  ... do stuff ...

  if (Character.HP <= 0 || Character.food <= 0 || ... ) {
    done = true;
  }
}

```

Alternatively, you could encapsulate the logic slightly more inside the `Character` class with a method like:

```
public bool IsDead () {
  return HP <= 0 || food <= 0 || ...
}

```

So your loop can check just check if the character is dead:

```
bool done = false;
while (!done ) {
  ... do stuff ...

  done = Character.IsDead();
}

```

You can easily extend this to support victory conditions as well.

# Answer
> 1 votes
I would recommend having something like this in your loop:

```
if (<death check>) break;

```

`<death check>` would probably best be suited to a method (to steal from Josh Petrie, `Character.IsDead()`) which does the actual checking and returns a boolean `true` if they are dead.

What the `break` keyword does is immediately, unhesitatingly break out of the innermost loop it's in. It doesn't perform any other statements in the loop -- as soon as you hit that statement, you're out. If you have some last thing you need to do when the character is dead but, for any reason, it has to be inside the loop, you can do something like this:

```
while (true) {
    //Game logic
    if (<death check>) {
        //Whatever logic must be executed
        break;
    }
}

```

This is good if you want to check mid-turn or multiple times per turn, and break immediately.

Alternatively, if you want to put it at the beginning of every loop, you can do this:

```
while (!<death check>) {
    //Game logic
}

```

When it finishes the last line of code, it will wrap back around, check the statement, and if that's false, it won't go into the loop again.

This is good for if you want the entire turn to be completed before ending the turn. However, it may cause some bugs if the death check should return false, but due to something else happening between the actual "death" and the check at the beginning of the turn, it returns true. One way to solve this would be to keep running track, with a boolean:

```
boolean stillAlive = true;
while (stillAlive) {
    //Game logic
    if (<death check>) stillAlive = false;
}

```

This way, you can have whatever logic you want happen, but the player still dies at the end of the turn.

---
Tags: java, rpg
---