title: OpenGL self-test in a mobile game

text:
# Question
Title: OpenGL self-test in a mobile game
I've made an Android game that uses no/custom game engine. It renders using OpenGL ES 2.0 and optionally uses some extensions for optimization or extra effects. Over the time I have dealt with various issues in OpenGL drivers, I had to implement workarounds or disable usage of some features on some devices. I am still getting reports from users that something does not render correctly on their device, but in most cases I have no way to debug it as it is happening on some strange device that I don't have. I am using AWS device farm for testing and all the devices there render the game correctly...

So I have come with an idea to implement some kind of self-test. It would run shortly after the first start and render off-screen some samples that test the shaders and features I use. The images would be compared to how they are supposed to look like. (I know the comparison must have some tolerance.) If it detects a mismatch, it could send me screenshots and detailed information about the OpenGL environment. Possibly it could even self-heal by disabling some features and trying again.

Was something like that already done in a (mobile) game?

Are there any caveats I should be aware of?

# Answer
> So I have come with an idea to implement some kind of self-test. It would run shortly after the first start and render off-screen some samples that test the shaders and features I use. The images would be compared to how they are supposed to look like.

On it's own, this is a reasonable technique to verify the correctness of a rendering operation. It is vulnerable to false failures though, particularly if you implement a precise pixel-by-pixel equality test. But there are ways to make it effective, and I've seen it used on large projects as a way to do integration tests on rendering systems.

> If it detects a mismatch, it could send me screenshots and detailed information about the OpenGL environment.

You will generally want to obtain permission from your users, or at least tell them that you will be collecting certain system information and reporting it back to yourself. In some cases it may be legally mandated that you disclose what you are collecting, allow a user to review it, or allow a user to opt-out of such collection.

Given that, it doesn't seem like a good use of your time to bother running this self-test on their machines. Rather you should just implement the bits that collect their system information and have them send you *that* when they have a bug or other rendering issue. Perhaps include some functionality to capture the current framebuffer to see the rendering issue, et cetera.

You're going to do it anyway and this way you will not be quite as inundated with reports (the bandwidth and storage of which may cost you money) of too many issues.

> Possibly it could even self-heal by disabling some features and trying again.

This is potentially tricky, but a reasonable idea if done at a fairly granular level. This is often done under the umbrella of "scalability" features, although one doesn't need to actually render anything to do it. Generally detecting device capability bits and flags, or running some basic throughput tests, are all that is needed. It can be difficult to determine what you need to "turn off" based on trying to render some scene and coming up with an arbitrarily mangled output scene, for example.
> 0 votes

---
Tags: android, opengl-es, opengl-es2, testing
---


title: Flipped Normals On Back Faces

text:
# Question
Title: Flipped Normals On Back Faces
I'm trying to create grass quads and have therefore disabled backface culling when rendering these quads. With each vertex normal set upwards ( 0.f, 1.f, 0.f ), all front faces are lit correctly, but backfaces are black. If I change the the Y normal to -1.f the backfaces light up and the front faces go black.

```
D3D11_RASTERIZER_DESC desc {};

desc.AntialiasedLineEnable  = false;
desc.CullMode               = D3D11_CULL_NONE;
desc.DepthBias              = 0;
desc.DepthBiasClamp         = 0.f;
desc.DepthClipEnable        = true;
desc.FillMode               = D3D11_FILL_SOLID;
desc.FrontCounterClockwise  = false;
desc.MultisampleEnable      = false;
desc.ScissorEnable          = false;
desc.SlopeScaledDepthBias   = 0.f;

```

I'm not so sure there's a problem here. Any ideas?

# Answer
> 0 votes
Okay I've solved this - I should have provided more information; I'm using normal mapping and it turned out that since I hadn't provided tangent or bitangent vectors for the grass quads, that was causing the problem. Thanks for your assistance.

# Answer
> 1 votes
Back faces are facing in the opposite direction to front faces, so yes, their normals should also point in the opposite direction.

You can use the SV\_IsFrontFace semantic to detect if you're currently drawing a backfacing primitive.

Alternatively, duplicate the data for front and back faces.

---
Tags: directx11
---


title: Ray & Segment Intersection

text:
# Question
Title: Ray & Segment Intersection
I'm writing some code to check intersection between all of a rectangles segments and a ray. It will sometimes use the Left and Right side of the rectangle as the closest face hit (face DA & BC) even when it is clearly on the top of the rectangle (face AB).

This is what the Rectangle v Ray collision looks like.

```
    // Ray intersections
    static public IntersectData IntersectRectRay(Rectanglef rect, Vector2 origin, float dir)
    {
        IntersectData data = new IntersectData();

        // Create segments for all the sides of a rectangle
        Segment topLeftRight = new Segment(rect.TopLeft, rect.TopRight);
        Segment leftTopBottom = new Segment(rect.TopLeft, rect.BottomLeft);
        Segment bottomLeftRight = new Segment(rect.BottomLeft, rect.BottomRight);
        Segment rightTopBottom = new Segment(rect.TopRight, rect.BottomRight);

        // Check collision with all the faces and use the closet one
        float smallestDepth = float.PositiveInfinity;

        IntersectData topLeftRightData = IntersectSegmentRay(topLeftRight, origin, dir);
        if (topLeftRightData.intersecting && topLeftRightData.depth.Length() < smallestDepth)
        {
            smallestDepth = topLeftRightData.depth.Length();
            data = topLeftRightData;
            data.face = "AB";
            data.dir = MathHelper.PI / 2f;
        }

        IntersectData leftTopBottomData = IntersectSegmentRay(leftTopBottom, origin, dir);
        if (leftTopBottomData.intersecting && leftTopBottomData.depth.Length() < smallestDepth)
        {
            smallestDepth = leftTopBottomData.depth.Length();
            data = leftTopBottomData;
            data.face = "DA";
            data.dir = 0f;
        }

        IntersectData bottomLeftRightData = IntersectSegmentRay(bottomLeftRight, origin, dir);
        if (bottomLeftRightData.intersecting && bottomLeftRightData.depth.Length() < smallestDepth)
        {
            smallestDepth = bottomLeftRightData.depth.Length();
            data = bottomLeftRightData;
            data.face = "CD";
            data.dir = MathHelper.PI / 2f;
        }

        IntersectData rightTopBottomData = IntersectSegmentRay(rightTopBottom, origin, dir);
        if (rightTopBottomData.intersecting && rightTopBottomData.depth.Length() < smallestDepth)
        {
            data = rightTopBottomData;
            data.face = "BC";
            data.dir = 0f;
        }

        return data;
    }

```

and this is the ray v Segment intersection

```
    static public IntersectData IntersectSegmentRay(Segment seg, Vector2 origin, float dir)
    {
        IntersectData data = new IntersectData();

        // Get vector between p1 and p2
        Vector2 q = seg.p1;
        Vector2 s = seg.p2 - seg.p1;
        Vector2 p = origin;
        Vector2 r = new Vector2((float)Math.Cos(dir), (float)Math.Sin(dir)) * 100000f;

        float t = MathHelper.Vec2CrossProduct(q - p, s) / MathHelper.Vec2CrossProduct(r, s);
        float u = MathHelper.Vec2CrossProduct(q - p, r) / MathHelper.Vec2CrossProduct(r, s);

        if (MathHelper.Vec2CrossProduct(r, s) != 0 && t <= 1 && t >= 0 && u <= 1 && u >= 0)
        {
            data.intersecting = true;
            data.depth = p + t * r;//q + u * s;
            data.dir = dir;
        }

        return data;
    }

```

Extra Info: My Vec2CrossProduct is V × W to be Vx Wy − Vy Wx

I imagine there is something wrong with the ray segment intersection because if I tried to replace that 100000f with float.PositiveInfinity() it won't work.

# Answer
Well a simple ray vs line segment intersection is:

```
function RayToLineSegment(x, y, dx, dy, x1, y1, x2, y2)
{
    var r, s, d;
    //Make sure the lines aren't parallel, can use an epsilon here instead
    // Division by zero in C# at run-time is infinity. In JS it's NaN
    if (dy / dx != (y2 - y1) / (x2 - x1))
    {
        d = ((dx * (y2 - y1)) - dy * (x2 - x1));
        if (d != 0)
        {
            r = (((y - y1) * (x2 - x1)) - (x - x1) * (y2 - y1)) / d;
            s = (((y - y1) * dx) - (x - x1) * dy) / d;
            if (r >= 0 && s >= 0 && s <= 1)
            {
                return { x: x + r * dx, y: y + r * dy };
            }
        }
    }
    return null;
}

```

That said a ray to rectangle aka axis-aligned boundary box (AABB) can be done without doing a normal ray vs line segment check since the line segments are all horizontal or vertical you end up with a very simple algorithm: most efficient AABB vs Ray collision algorithms
> 3 votes

# Answer
thanks to Sirisian wrote, i adopted it a bit to my code for proximity sensor for neural network:

```
// convenient mapping for neural network distance sensor;
scalar get_distance_inverse_squared(const point& qp, const point& d, const segment& s)  {
    auto s0s1 = s[1] - s[0];
    auto s0qp = qp - s[0];
    auto dd = d[0] * s0s1[1] - d[1] * s0s1[0];
    if (dd != 0) {
        auto r = (s0qp[1] * s0s1[0] - s0qp[0] * s0s1[1]) / dd;
        auto s = (s0qp[1] * d[0] - s0qp[0] * d[1]) / dd;
        if (r >= 0 && s >= 0 && s <= 1) {
            // linear inverse of distance, always less than 1.0
            return scalar(1) / (r + 1);
        }
    }
    return 0; // infinitely far, parallel, etc, no signal
}

```
> 0 votes

---
Tags: c#, collision-detection, raycasting, intersection
---


# Question
Title: Unity collisions often have exaggerated physics, sending the player flying off the scene
I'm building a car driving game in Unity 2017.3.1f1.

The car movement works fine over a flat surface and even over gently rolling terrain. It's a city environment, and there are lots of small lips and angles where the street meets the sidewalk, where terrain ends, and around ramps and other features.

When the car hits one of these small seams in the ground, 60% of the time it flies up in the air over the buildings, rotating like crazy. It often flies off the game world. When going off a ramp, sometimes the car will continue driving forward and rotating up on the x-axis in mid-air, as if it's going through an invisible loop-the-loop.

I'm not sure what's causing the extreme physics reactions.

Here's the car object:

And here's the car's movement code:

```
  void Update ()
    {
    if (Input.GetKeyDown (KeyCode.UpArrow) && !key_up) key_up = true;
    if (Input.GetKeyUp (KeyCode.UpArrow) && key_up) key_up = false;

    if (Input.GetKeyDown (KeyCode.DownArrow) && !key_down) key_down = true;
    if (Input.GetKeyUp (KeyCode.DownArrow) && key_down) key_down = false;

    if (Input.GetKeyDown (KeyCode.LeftArrow) && !key_left) key_left = true;
    if (Input.GetKeyUp (KeyCode.LeftArrow) && key_left) key_left = false;

    if (Input.GetKeyDown (KeyCode.RightArrow) && !key_right) key_right = true;
    if (Input.GetKeyUp (KeyCode.RightArrow) && key_right) key_right = false;
    }

  //////////////////////////////////////////////////

  void FixedUpdate ()
    {
    if (on_ground)
      {
      // driving
      if (key_up)
        {
        if (current_speed < top_speed) current_speed += acceleration;
        }
      else if (key_down)
        {
        if (current_speed > -top_speed) current_speed -= acceleration;
        }
      else
        {
        if (current_speed > -.1f && current_speed < .1f) current_speed = 0f;
        if (current_speed != 0f) current_speed = current_speed * 0.9f;
        }

      // turning
      if (key_left) turning_rotation = current_speed * 2.5f * -1f;
      if (key_right) turning_rotation = current_speed * 2.5f;
      }

    // rotation
    transform.Rotate (0f, turning_rotation, 0f);

    forward_movement = transform.forward * current_speed;
    body.MovePosition (body.position + forward_movement);

    // reset values
    turning_rotation = 0f;
    }

  //////////////////////////////////////////////////

  void OnCollisionStay ()
    {
    update_on_ground ();
    }

  //////////////////////////////////////////////////

  void OnCollisionExit ()
    {
    update_on_ground ();
    }

  //////////////////////////////////////////////////

  void update_on_ground ()
    {
    // check if car is grounded
    Vector3 ray_start = transform.position + new Vector3 (0f, 1f, 0f);
    if (Physics.Raycast (ray_start, Vector3.down, 1.1f))
      {
      if (!on_ground) on_ground = true;
      }
    else if (on_ground) on_ground = false;
    }
  }

```

Any ideas are appreciated.

**NOTES:**

There was a ton of extra code in here attempting various fixes, including trying to manually restrict rotations on the z and x axes, to reduce velocity while airborne, to use several alternative types of movement code, and to increase the car's mass to a ridiculous amount. None of them ever worked, so I've removed them here.

**By request, other solutions I've tried:**

* Changing the car's mass seems to have no effect on anything.
* Trying to clamp the car's rotations led down an enormous rabbit hole that would require a separate question to resolve, but the short version is that Euler angles don't seem to work correctly and I don't understand quaternions (yet).
* Gradually reducing the car's velocity in mid-air helped slightly in keeping it airborne shorter, but not enough to stop it from launching upward like a rocket in the first place or bouncing like crazy when it hits the ground.
* I've also messed around with using transform.translate() rather than RigidBody.MovePosition(), but this doesn't seem to affect the bounciness, gravity, or rotations of the car. In fact, it sometimes makes the collisions glitchier.
* The last thing I tried was using the car's direction and velocity to figure out its global, separate x,y,z velocities and move it globally based on only the x and z. My thought process was that if the car is going off a ramp, then the nose is pointed up, which means it's technically still moving in that direction relative to itself (transform.forward) when it leaves the ramp, even though gravity is pushing it down on the global y axis. I got this working correctly, but it didn't have a noticeable impact on the physics.
* Freezing the X and Z rotations in the car's Unity inspector actually does work and addresses all the physics problems. However, it looks pretty damn silly when the car goes up a ramp or over terrain and stays perfectly level no matter what.

All the world geometry is currently just built from Unity primitives.

# Answer
> 0 votes
**It was the gravity.**

Based on the video DMGregory linked to, I realized my game has "floaty" physics, as the speaker describes it.

I did some research and found out Unity lets the user specify the amount of gravity in the world under Edit -\> Project Settings -\> Physics.

I changed mine from -9.81 to -30 and now the game runs great. No more flying cars. Maybe my city was modeled on a much smaller scale than what Unity was expecting. It makes me wonder what the correct Unity/Blender units-to-feet ratio would be for a game to feel realistic with the default gravity.

I also found a bug in my physics code related to a function I wrote to flip the car with a key press if it's been turned upside-down or on its side. I wasn't reducing the vertical velocity in certain situations, resulting in a lot of excess bounciness when using that function.

---
Tags: unity, collision-detection, physics, car
---


# Question
Title: Scan for water in 2D procedural terrain locale
In my 2D-sideview game, I have certain biomes, each one having a unique sea level, or water height, (depending on the humidity of the biome). The terrain is composed of stacks of blocks, each being a type of land or being water. I want the height map to look something like this:

*Terrain height does not always correlate to water height. It does so here for demo purposes.*

Each lake must have a constant water height across.

**What I've tried:** To calculate if there is water in a region, I want to know the minimum water height of all biomes in that region. That will be the lake's water height.

However, I don't know how far the region extends on each side, so I can't find the minimum water height. If the water height was global/constant, I would search in both directions until I found a block above sea level (or a maximum distance was reached), but I don't know the water height, because I can't search for it, because I need the other water heights to search for this water height!

**Some ideas that seem inefficient:**

* Search for the endpoints of a potential lake at each biome water level, and choose the smallest water level to generate the lake.
* Find the smallest biome level in a max distance on each side, and choose the smallest water level to generate the lake.

Please tell there is a better way!

**Edit:**

* Terrain stacks (columns) are generated individually, then loaded into memory. When the player reaches a certain distance from the stack, it will get unloaded, and then regenerated again when the player is near. *Every time a terrain stack is generated it must be exactly the same.*
* For querying stack heights over and over again for calculating whether water should be on a stack, I cache the height and biome of some stacks beyond the loaded stacks in each direction; thus, it is not considered loaded (so entities can't move), but the basic information does not have to be recalculated.

# Answer
This is a **maximum subarray problem** in disguise! It's a popular interview question. Instead of finding subarray sums, we're finding terrain that can hold water, and instead of finding *the* biggest subarray, we're finding all subarrays.

With the maximum subarray problem, we can track the current maximum subarray as we scan the array. The key insight is that once the sum is less than zero (because we have negative values), there is no point keeping the current subarray, so we reset and start counting from the current position instead.

Here's how we'd do it. Suppose we have the current terrain (a simplified version of your example:

```
#
##   ##
### ####
##########   #
########### ##
##############

```

First, flip it so that we start from the lower end (here we'll just scan right-to-left instead). Then transform it into the maximum subarray problem by looking at the **slope** of the terrain:

```
Heights: [3, 2, 1, 2, 3, 3, 4, 5, 5, 4, 3, 4, 5, 6]
Slopes:   [-1,-1, 1, 1, 0, 1, 1, 0,-1,-1, 1, 1, 1]

```

Then, we scan the slopes looking for largest subarrays. Since we're looking for valleys that can hold water, we are actually looking for *negative* sums.

```
const levels = [3, 2, 1, 2, 3, 3, 4, 5, 5, 4, 3, 4, 5, 6];
const slopes = [-1,-1, 1, 1, 0, 1, 1, 0,-1,-1, 1, 1, 1];
let currentSum = 0;
let currentWaterStart = 0;
let minSum = 0;
for (let i = 0; i < slopes.length; i++) {
  currentSum += slopes[i];
  minSum = Math.min(currentSum, minSum);
  if (currentSum >= 0) {
    if (minSum < 0) {
      console.log('Found water from ' + currentWaterStart + ' to ' + i);
      console.log(' depth ' + -minSum + ' level ' + levels[i+1]);
    }
    currentSum = 0;
    currentWaterStart = i;
    minSum = 0;
  }
}
```

The time complexity is O(n) and space complexity is O(1).
> 5 votes

# Answer
Rather than giving you exact solutions, I'm rather going to primarily offer you ideas and tools that may help you to solve problems of this sort. *Teach a man to fish* and all that.

**Principles**

1. Any computation must be limited (in range).
2. When you have problems like "I cannot do that till I do this, but I cannot do this till I do that", you are usually doing too much at once. You need to layer your approach more finely to do one set of things at a time, then another set, then another etc.
3. You are better off reducing the dataset you work with, even in finite ranges.

I'll refer back to these principles by number through this answer, so keep them in mind.

**Finity vs. Infinity**

> how do you know which one's the lower end if it goes on indefinit(el)y?
>
> I don't know how far the region extends on each side

...Your words. You need to start defining limits (principle #1), because *your code* cannot process inifinite ranges in finite time. Only you can decide those limits. What's the worst that can happen? You a try a value and it doesn't work out: so try another. Until you get something that works.

**Biomes**

I noticed in your question that you have a blue and a green area, one smaller than the other. OK. These are usually called terrain *chunks*, but we'll call them *biomes*: these are important processing elements, as using them *we don't have to* scan every single column every time we need to do something - e.g. seeking water. Instead, we can scan just the biomes.

You can generate your world in two ways: by column primarily, OR by biome and *then* by column. I would suggest the latter, as it gives better control and efficiency (principle #3). Imagine we start out generating the world as a biome array:

```
[
  {
     type:sand
     start:0
     end:7
     columns: [empty]
  },
  {
     type:grass
     start:7
     end:13
     columns: [empty]
  },
  {
     type:stone
     start:13
     end:17
     columns: [empty]
  },
  ...
]

```

Now you have an abstract idea of each biome: What it consists of, where it `start`s in x, where it `end`s in x. You can see that the `end` of each biome is neighboured by the `start` of the next.

Now we take this data and from it and (principle #2) create an array of heights, per biome as `width = biome.end - biome.start; biome.columns = new Column[width]`. Then we populate each column in that array. So for the array above we might get

```
      *#
*    **##
**  ***###
*******#####   oo
*******######oooo ...etc.

```

*Looping over the columns* as shown here, we'd now fill in some important intermediate data to the biomes array:

```
[
  {
     type:sand
     start:0
     end:7
     columns: [7 elements]
     minheight: 2
     maxheight: 5
  },
  {
     type:grass
     start:7
     end:13
     columns: [6 elements]
     minheight: 1
     maxheight: 5
  },
  {
     type:stone
     start:13
     end:17
     columns: [4 elements]
     minheight: 1
     maxheight: 2
  },
  ...
]

```

We've now populated `minHeight` and `maxHeight` fields accordingly for that biome from our generated columns. This gives more control, as you will see next.

Remember: Chunks are used to *limit the problem* (#2). That's why we generate biomes *first* (i.e. our primary data structures) and *then* only generate columns. This makes the world manageable.

You can cheaply generate large numbers of biomes without the considerably higher cost of generating large numbers of columns for every one - *until later*. What's more: You could dictate the `minheight` and `maxheight` *before* you generate the columns. Maybe you can already begin to see how this might help you to determine lake heights without *having to examine every single column*: You could maybe even (no guarantees), before ever generating columns, pre-dictate min and max levels of lakes, given the min and max ground heights. Then generate ground and water columns.

**Scanning solutions**

You cannot determine water levels for columns / biomes you haven't generated yet. You cannot scan around the current location when you haven't yet generated the locations that come after it. With that in mind, here are some solutions.

1. Only scan backward, to biomes you have already generated along with their water heights (assuming you always generate forward from `world.biomes[0]`). This will always be a scan of some fixed distance backward, let's call it `scanDistance`.
2. Generate forward, but only scan from a biome that is say `scanDistance / 2` units back from the highest-indexed biome (last generated). Generate at least `scanDistance` biomes before you begin scanning. Now you can scan back, and forward to the end, by `scanDistance / 2`, from the centre, without hitting the bounds of your world's array of biomes.

OR (my recommendation)

3. Generate biomes only in your 1st pass (see *Chunks / Biomes*); figure out in your 2nd pass what the water levels will be. To do this, run through the world around the current location-of-interest by some excessive extent first, in a `scanDiameter` that is centred around the current location, generating land with indentations first. P.S. You can generate ***many*** biomes this way (probably millions if you like, though I'd start smaller - see principle #3). Then run a second pass and evaluate parameters like `minheight`s and `maxheight`s of those areas.

Remember, you cannot scan further than the range of biomes (even if they don't yet have columns) that you have already generated (principle #1). Your code must take this into account.

**Decisions, decisions...**

Maybe you are happy with just generating `minheight` and `maxheight`, then generating columns, then determining lake levels via scan. Maybe you prefer to pre-generate numbers for `minheight`, `maxheight`, `minlakeheight`, `maxlakeheight` before touching concrete columns at all. Maybe you generate land columns and in another pass, use that to determine water columns / levels. Or maybe you do something altogether different that is only inspired by what we've talked about here.

Procedural generation is a field of infinite possibilities. Nothing we've talked about is set in stone. Don't be locked into just one way of thinking. Keep an open mind in your explorations.
> 1 votes

---
Tags: 2d, algorithm, procedural-generation, terrain, water
---


# Question
Title: GLSL - Stencil buffer - instanced geometry
I have geometry that have attached some "ID" data. I have generated stencil buffer, that holds these IDs. Now, in second pass, I render different geometry, but this time I need to mask it with already existing stencil. Each part of geometry can have different "ID". Is there a way, how to control stencil buffer test value from shader?

I give an example:

> 1. render geometry with ID = 1, writes 1 to stencil
> 2. render geometry with ID = 2 if ID in stencil != 1, writes 2 to stencil
> 3. do some other rendering with stencil turn off
> 4. render bunch of particles at one go, but some of them have ID 1, some of them ID 2 -\> I want to mask them, so 1 is rendered only if 1 is in stencil and 2 only if 2 is in stencil

I need this for OpenGL ES 2.0

# Answer
> 1 votes
I don't know a way to do it with pure OpenGL ES 2.0, but it would be possible with the ARM\_shader\_framebuffer\_fetch\_depth\_stencil extension.

You can not control the stencil test value from the shader, but it allows you to read the current value from the stencil using `gl_LastFragStencilARM` and then you can compare and `discard` as you wish.

There are also ways to attach stencil as a texture, so you can do something similar, but as far as I can find all need at least OpenGL ES 3.0.

If a majority of your target devices support this, you can use it and implement a fallback where the particles are split into groups by ID and rendered separately.

---
Tags: glsl, opengl-es
---


# Question
Title: Why does an emulator use more RAM than the original system?
Why does an emulator use more RAM than the original system? What are emulators doing that requires so much more power?

For example, when using the PSP emulator PPSSPP I'm experiencing lag on a modern PC with gigabytes of RAM, even though the PSP runs with only 32MB of RAM.

When developing my own console emulator, should I not expect it to use a similar amount of RAM / CPU cycles / other resources as the original system has to offer? Or is there extra overhead that makes emulating much more demanding than what the original hardware's specs would suggest?

# Answer
Emulation usually requires a lot more processing power than the original platform. The reason is that a good and accurate emulator needs to simulate all the quirks and specialities of the original hardware, but can only do so using software methods. Just one example which applies to the PSP in particular is that it doesn't have an x86 CPU like your PC does. It uses a MIPS CPU with a completely different architecture and instruction set. And all the other components of a PSP (graphic chip, sound chip, memory controller...) are just as exotic from a PC viewpoint.

You often won't get around to create a complete simulation of the original hardware in software.

So when you are playing a PSP game on your PC using an emulator, then your PC isn't running the game. It is running a virtual simulation of the PSP hardware which is running the game.

This additional layer of abstraction requires quite a lot of resources. This is why the first feasible emulators often only appears decades after the release of a system. It just takes that long for a generation of PC hardware to appear which is powerful enough to accurately simulate a past generation of completely different hardware in real-time.

Now that game consoles become more and more PC-like in their hardware design (both XBox One and PS4 use common x86 CPUs and GPUs from AMD which are almost identical to those sold on the PC market), it actually becomes a lot easier to emulate their hardware. But a new obstacle has appeared on the software front. Modern game consoles have very advanced Digital Rights Management systems. They also rely on very sophisticated firmware. Just copying that firmware would be a copyright infringement. Creating a free clone of the firmware would be theoretically possible, but quite a lot of additional work for the emulator developers.
> 9 votes

---
Tags: performance, emulation
---


title: LibGDX and Typing Label

text:
# Question
Title: LibGDX and Typing Label
I am attempting to have animated dialog text for my libGDX game. I found a useful resource on github called Typing Label and i am having some troubled getting it working. Could someone help me with this. Also in the examples it says stage.add and i dont have a stage object declared. what type of object should that be.

```
 TypingLabel label = new TypingLabel("Hello world!", skin);

```

# Answer
> 1 votes
To use any type of `Actor` (`TypingLabel` is an `Actor`) you need a `Stage` object like the examples say. You also need to draw and update this stage object every game tick so that the Actors can animate and render properly.

```
// Instance variable
private Stage stage;

@Override
public void create() {
    stage = new Stage(); // Note: There are multiple constructors available
    stage.add(new TypingLabel("Hello world!", skin));

    Gdx.input.setInputProcessor(stage); // Only needed if you have input such as buttons
}

@Override
public void render(float delta) {
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // Clear screen so we don't get artifacts.

    stage.act(); // Update all actors
    stage.draw(); // Draw all actors
}

```

The official libgdx wiki has more information about how to use Stage, Actors, and other parts of Scene2D.

---
Tags: libgdx
---


# Question
Title: Optimization of 2D terrain generation algorithm
I am generating 2D terrain with 2D opensimplex noise, however I am having a problem with the FPS that is low when generating the terrains in TileMap. An example of how my game generates the terrain in **javascript**:

```
function generator(map_size=0, _posWorld=[0, 0], size=[1, 48], seed=0) {
    var simplex = new SimplexNoise(seed);

    var x = 0;
    var y = 0;
    var pos_modx = 0;
    var pos_mody = 0;
    while (x < size[0]) {
        pos_modx = utilsfunctions.mod(_posWorld[0] + x, map_size);
        y = 0
        while (y < size[1]){
            pos_mody = utilsfunctions.mod(_posWorld[1] + y, map_size);
            // GENERATION NOISE
            // TEMPERATURE
            var nx = parseFloat(pos_modx)/map_size - 0.5;
            var ny = parseFloat(pos_mody)/map_size - 0.5;
            var v1 = temperature * simplex.noise2D(1 * nx, 1 * ny);
            var v2 = 0.4 * simplex.noise2D(2 * nx, 2 * ny);
            var v3 = 0.23 * simplex.noise2D(4 * nx, 2 * ny);
            var v4 = 0.134 * simplex.noise2D(8 * nx, 8 * ny);
            var e = v1 + v2 + v3 + v4;

            // HUMIDITY
            var unx = parseFloat(pos_modx)/map_size - 0.4;
            var uny = parseFloat(pos_mody)/map_size - 0.5;
            var u1 = humidity * simplex.noise2D(1 * unx, 1 * uny);
            var u2 = 0.6 * simplex.noise2D(2 * unx, 2 * uny);
            var u3 = 0.7 * simplex.noise2D(4 * unx, 2 * uny);
            var u4 = 0.073 * simplex.noise2D(8 * unx, 8 * uny);
            var u5 = 0.09 * simplex.noise2D(16 * unx, 16 * uny);
            var u6 = 0.03 * simplex.noise2D(32 * unx, 32 * uny);
            var ue = u1 + u2 + u3 + u4 + u5 + u6;

            if (pos_modx >= 0 && pos_mody >= 0) && (pos_modx < map_size && pos_mody < map_size) {
                tile_map.set_cell(_posTileMap.x + x, _posTileMap.y + y, biomes.solos(e, ue));
            }
            y += 1;
        }
        x += 1;
    }

```

The problem is that I am generating several layers of tilemap, one for terrain, one for relief and one for trees. That is three scripts of these, of course for the relief and trees is much less complex, and alone for example, even the two together do not interfere almost anything in the FPS. However, only generating with the above-ground script is already a big problem, and I generate only one minimum possible bit at a time, which is (1, 48) for when moving up or down, and (48, 1) when moving to the right and left, it is clear that there is the case of the diagonal movement, having to generate 48 + 48, which is the worst case. However, even only the 48 are already leaving the FPS bad, nor do I need to move diagonally to feel the FPS suffer.

I would like tips to be able to optimize this generation, and if know any way to use only one algorithm to generate everything (terrain + relief + trees), or any help that can take me to a better way.

Understand why I am generating with 3 different scripts for terrain, relief and trees:

**Terrains** are large areas within large areas.

**Reliefs** are crooked lines on the map.

**Trees** are only points of a dirty noise on the map.

# Answer
You should profile your code. Since it is in Javascript, I assume it is a browser game. Try Chrome, it has good profiler that will visualize you which functions take the longest.

If you say that it is slow even for 1x48 generation, ie the inner loop is run only 48 times, something is really wrong. Generating few random numbers and some floating point arithmetic 48 times is no big deal.

What happens in this call?

```
tile_map.set_cell(_posTileMap.x + x, _posTileMap.y + y, biomes.solos(e, ue));

```

My guess is that whatever is happening in here (any rendering?) takes the longest. You could try to first generate all the new tiles and then update the world in one transaction.

Also don't call `parseFloat` repeatedly if you can cache the value. Ideally don't work with strings at all, have all your hot functions take and return numbers.
> 1 votes

---
Tags: 2d, javascript, procedural-generation, tilemap
---


# Question
Title: Segmentation Fault using Allegro_Tiled, function al_open_map();
I have consistently segfaulted trying to load a TMX file into a \*map.

```
int main(int argc, char *argv[])
{
    ALLEGRO_DISPLAY *display = NULL;
    ALLEGRO_EVENT_QUEUE *event_queue = NULL;
    ALLEGRO_TIMER *timer = NULL;
    ALLEGRO_KEYBOARD_STATE keyboard_state;
    ALLEGRO_MAP *map = al_open_map("data/maps", "TestMap.tmx");
...

```

---

```
Active debugger config: GDB/CDB debugger:Default
Building to ensure sources are up-to-date
Selecting target:
Debug
Adding source dir: /home/X/Desktop/Programming/C/AllegroRoboticsTest/
Adding source dir: /home/X/Desktop/Programming/C/AllegroRoboticsTest/
Adding file: /home/X/Desktop/Programming/C/AllegroRoboticsTest/bin/Debug/AllegroRoboticsTest
Changing directory to: /home/X/Desktop/Programming/C/AllegroRoboticsTest/.
Set variable: LD_LIBRARY_PATH=.:/usr/local/lib:/opt/opencascade/lib
Starting debugger: /usr/bin/gdb -nx -fullname -quiet  -args /home/X/Desktop/Programming/C/AllegroRoboticsTest/bin/Debug/AllegroRoboticsTest
done
Setting breakpoints
Debugger name and version: GNU gdb (GDB) 8.1
Program received signal SIGSEGV, Segmentation fault.
In al_get_standard_path () (/usr/lib/liballegro.so.5.2)
#2  0x00005555555563ba in main (argc=1, argv=0x7fffffffe3a8) at /home/X/Desktop/Programming/C/AllegroRoboticsTest/main.c:45

```

At first I thought, maybe I just didn't build the library right, so I rebuilt it 2 more times, once as a static and another as a shared library.

The interesting thing is that it builds just fine when using the cmake files that came in the example.

I cannot recreate it though.

---

This is the callback after I moved the open map command into it's usual place, directly from the example that comes with allegro\_tiled.

```
// If MAP_FOLDER is relative to the working directory and not the running
// executable, then add a call to `al_find_resources_as(RELATIVE_TO_CWD);`
// before calling `al_open_map()`.
//al_find_resources_as(RELATIVE_TO_CWD);
map = al_open_map("data/maps", "TestMap.tmx");
int map_total_width = al_get_map_width(map) * al_get_tile_width(map);
int map_total_height = al_get_map_height(map) * al_get_tile_height(map);

// Draw the map
al_clear_to_color(al_map_rgb(0, 0, 0));
al_draw_map_region(map, map_x, map_y, screen_width, screen_height, 0, 0, 0);
al_flip_display();

```

---

```
   ...
   Setting breakpoints
   Debugger name and version: GNU gdb (GDB) 8.1
   Child process PID: 25749
   In ____strtoll_l_internal () (/usr/lib/libc.so.6)
   #3  0x0000555555556615 in main (argc=1, argv=0x7fffffffe3a8) at /home/X/Desktop/Programming/C/AllegroRoboticsTest/main.c:114

```

# Answer
Looks like you are not initializing the library with `al_init` call.

It tries to retrieve some standard directory to know where is the map stored, but crashes because these were not initialized.
> 2 votes

---
Tags: tilemap, c, tiled, allegro
---


# Question
Title: Scene building for procedurally generated tile based world in Unity
i'm making a procedurally generated side-scrolling and destructible tile based world. So far I've got : \- the values generator (for deciding which tile to place where) \- a testing scene generating one object per tile (a mesh with 2d box collider, inactive at start) \- map chunking (separating the map into chunks to show only what is visible) \- visibility based on orthographic camera size (it's not much but the camera can zoom in or out) \- the chunks are 32x32 tiles in size \- the maximum chunks I've seen is around 25

This works fine for testing the world generation, however there is massive stuttering when moving around with camera zoomed out to the maximum. It's less when zoomed in, but it is still noticeable.

From testing, I've found out that its obviously the building in the scene that causes the major part of the stuttering.

I've been searching for better ways of building the scene but there are a few constraints that make most of the non viable : \- The world is destroyable, so I need to be able to interact with each tile \- There are textures coming on top of the tile texture depending on context (selection rectangle, decoration, glow...) \- The tile texture itself is not a single sprite but a repeatable texture, so it needs to be places based on coordinates so it properly repeats itself.

So far I've looked at : \- TileMaps \- Mesh melding \- Texture bombing

None of these seem to be able to fulfill the constraints fully.

Is there a way to fulfill the constraints while improving scene building or am I missing something? Please help.

# Answer
> 1 votes
It is a lot more expensive to destroy and create objects than to move objects around. For some objects, you might not know how many are supposed to appear, and so they might not be ideal for reuse, but even some of the destructible tiles could be disabled when destroyed, moved ahead when out of view, and then re-enabled. You may even create extra tiles at the start just in case, leaving them disabled or somewhere out of view until you need them.

---
Tags: unity, c#, procedural-generation, tiles, block-world
---


# Question
Title: How do I remove the background from pixel art sprites in Gimp?
I drew a pixel art tree using GIMP. My problem is, how can I cut out the white background, because if I want to build a tile map with it, in my case with tiled, it always has the white background with it.

I know you can cut it manually, but I want to know whether there is an easier way.

# Answer
You need to right click the layer and select "Add Alpha Channel"

Then you can do one of 2 things...

1. Use the "Fuzzy Select Tool" to select the white color (you can adjust the tolerance to select more or less of it) and delete the area.
2. Go to "colors \> color to alpha" select white and hit okay.
> 4 votes

---
Tags: pixel-art, gimp
---


title: Drawing Explosions Respecting Walls

text:
# Question
Title: Drawing Explosions Respecting Walls
I am creating a tiled game (2D top down) and I created explosions working this way:

The blue lines are walls, the white grid is accessable space. The red dot is the origin of the explosion with the green explosion radius. The orange lines are how I am doing raycasting (I am using Box2d) at the moment to ensure that only accessable things are hit (nothing behind the blue walls should be hit).

I cant just draw a circular sprite over the whole area as I dont want to let the explosion look like it is going over walls and stuff. My solution: I will draw an explosion tile over each tile that is in the radius.

This is how I want the explosion to look like:

Everything in the yellow "polygon" should be drawn as an explosion.

There are some issues seen here in the purple circles:

In "real life" the explosion will go around corners.

My question simply is: Do you have any idea on how to find all tiles that should be drawn as an explosion? Or maybe you do have a better approach!

The effect I want reminds me of minecraft water physics but in 2d.

Thank you!

# Answer
This looks like a perfect usage case for flood fill. Recursively visit all neighbouring tiles, starting from the explosion origin, that are not a wall and still in the explosion radius.

All tiles that are visited this way are part of the explosion by your logic.

If you want the explosion to only go around corners a certain distance, you can track how far the path from the explosion origing to the tile is, only taking those tiles where the path length is less or equal to your explosion radius.
> 1 votes

---
Tags: libgdx, box2d, raycasting
---


# Question
Title: A way around the deprecation of AppInvite in Unity
I was using FB.Mobile.AppInvite, but according to the Facebook documentation, it is deprecated.

So, how could I send an app invite?

# Answer
> 1 votes
If you are using firebase : https://firebase.google.com/docs/invites/unity

Some people gave the figure 18% of the app invite through facebook (other through wathsapp, etc...)

---
Tags: unity, facebook
---


# Question
Title: Lightmap not moving properly with camera movement
I´ve implemented a 2d lighting system (also with support of 2d shadows). Everything was fine until today when I realised that its not working when moving the camera, as it looks like the lightmap has still some offset than the camera position (for example, if camera.x is 100, the lightmap is x=-200)

Little video showing the problem : Video

I can post any piece of code, for now Im sending you my light shader(fragment)

```
#version 440

in vec4 fragmentColor;
in vec2 TexCoords;

out vec4 color;

uniform float ambientStrength;

uniform vec2 resolution;
uniform sampler2D textureSampler;
uniform sampler2D lightMapTexture;

uniform bool textureON;

void main(){

    //Calc the ligthMap
    vec2 lightCoord = (gl_FragCoord.xy / resolution);
    vec4 lightMap = texture(lightMapTexture,lightCoord);

    if (textureON){

        vec4 textureColor =  texture(textureSampler, TexCoords);

        vec4 finalColor = lightMap * textureColor * fragmentColor;
        color =  vec4(finalColor.rgb,textureColor.a* fragmentColor.a);

    } else {

        color = fragmentColor;
    }
}

```

**Vertex**

```
#version 440

in vec3 vertexPosition;
in vec4 vertexColor;
in vec2 vertexUV;

out vec4 fragmentColor;
out vec2 TexCoords;

uniform mat4 Projection;
uniform mat4 View;
uniform mat4 Model;

void main(){

    gl_Position = Projection * View * Model * vec4(vertexPosition.xy,0,1);

    fragmentColor = vertexColor;

    TexCoords = vec2(vertexUV.x, 1.0 - vertexUV.y);
}

```

At first I thought that its a problem with resolution, but everything is good. Everything is working fine until I move the camera(or change its position from 0,0 to something else - all other objects have good position, also mouse coords)

# Answer
> 0 votes
Well I found a solution. The problem was , I was using the "render to texture" method for creating the lightmap. I forgot that it renders the screen including the camera position, so basically when I moved the created the lightmap with the camera offset, it was moved 2 times already. I solved it by creating a static camera (static I mean it does not move, not in programming context) and using this cameras view matrix for the render to texture part. Then i switched to normal camera. And now it works perfectly!

---
Tags: opengl, 2d, lighting
---


# Question
Title: Unity - how to remove standard sky but keep the lighting?
How can I remove the standard Unity sky (to have an empty space with no texture around my scene), but keep all the lighting effects from it?

# Answer
In your scene, select your Main Camera and, in the *Inspector*, change its "*Clear Flags*" settings in the `Camera` component from "*Skybox*" to "*Solid Color*." Then choose the color you'd like:

Note: There are no "lighting effects" in the skybox, it's simply a collection of textures. Any lighting effects should be the result of lights placed in the scene and shaders on the materials of your objects.
> 4 votes

# Answer
(This is an old post I know but in the mere chance of someone passing through this page still)

If he was referring to "scene" as the Scene View window in Unity, not the game view. You can toggle the sky view from the scene view's menu bar. There's a simple toggle button with a drop down menu allowing you to disable the skybox entirely from the scene view.

Which is what I personally was looking for, although creating a new one is optional too.

For those who simply want a mere single click or two this option works as well.

The default skybox is such an eye sore, prefer a solid background.
> 3 votes

# Answer
Create a custom skybox. Not much else to say.

https://docs.unity3d.com/Manual/class-Skybox.html
> 0 votes

---
Tags: unity, lighting
---


# Question
Title: Why would I want to use multiple ad providers for my game?
I have seen mobile games with multiple video and banner ad providers. While Adsense tends to be used for banner ads, anything that takes over the screen (full screen) typically has redundancies (in my experience) in the form of multiple Ad providers.

Why would I want to do this too?

# Answer
While using only one ad network is fine for some projects, there are several problems that can arise. Using multiple ad networks can help resolve them. However, managing multiple ad networks can sometimes be a chore and require significant manpower to keep at optimum efficiency.

I'm not sure what this community's idiom for backing up answers is, but this answer is based on my experience in publisher-side ad operations, which includes optimizing ad network revenue. Although I have never worked with a mobile game, I have worked with mobile app advertising.

## Empty Impressions

An ad network usually won't fill 100% of all the impressions your app requests. When that happens, the network can either leave the space blank or it may fill it with a free ad for a charitable cause or government program. For example, when AdSense doesn't have a paying ad available for mobile sites it will often provide an ad for the U.S. Forest Service ("only you can prevent forest fires").

You don't get much (if any) revenue for these, so its preferable if you can fill them with something else. Many publishers use multiple ad networks to resolve this. A common technique is daisy chaining: when your first ad network doesn't return a paid ad, you can ask a secondary ad network to fill it, and so on. Another (more difficult) approach is to allow each network to bid on the ad placement and return only the ad which is the most profitable. Some ad networks discourage this, so it's best to check into the terms of your agreement with them.

## Low-Value Impressions

A second related, but less severe, problem is that sometimes an ad network will provide low-value ads. For example, your ad network may not have many advertisers who want to advertise on your particular app. One solution is to switch to an ad network which specializes in your audience, but that can be a pain - when their client base changes are you going to switch to a new ad network?

Instead, most publishers will use multiple ad networks to make sure that they are getting good deals. They will set a minimum CPM (cost per thousand) or CPC (cost per click) and only accept ads which meet those requirements. When their primary ad network doesn't return something suitable, ask the secondary network, and so on.

## Maximizing Value

Ad networks only have a certain number of impressions to give away. If your app has a significant number of impressions in a small advertising market, you will quickly exhaust the high-value campaigns and your network will return lower-value campaigns.

Using multiple ad networks can help you maximize your revenue in this case. By opening yourself up to a larger pool of advertisers you will be less likely to exhaust the pool of higher-paid ads. In addition, you will be more likely to find advertisers interested in your particular app.
> 10 votes

# Answer
One thing we do is use "mediators". Supersonic is a mediator. You install their plugin plus, let's say two others for simplicity, Vungle and AdColony. When an ad is requested, Supersonic figures out whether a Vungle or AdColony ad will pay better.

Another reason to use mediators is that most ad providers only allow a single client to play a certain number of ads per day (or some other time period that depends on the provider). With Supersonic, we can serve the maximum number of ads for both Vungle and AdColony.

In practice, you can use many more than two ad providers as well.
> 18 votes

# Answer
Two other reasons are for **serving up fresh content** & for **back-fill purposes**.

1. Sometimes people don't want repetitive ad content to be shown on their site/game.

Too many repetitive ads tend to make people think that nobody is using their site/game anymore & what they are look at are default pre-canned ads.

*Example:* If you see the same ad somewhere for months, then you assume that it's not a good place to go spend ad dollars on. The assumption is that nobody is watching those ads at that site/game. So advertisers move along to the next site/game.
2. To make sure that ads are served up, in case of an outage at the ad provider's network location.

Switching ad providers for back-fill purposes, ensures that if 1 ad provider is down & can't serve up ads, then another one will be able to provide an advertisement.

*Example:* It seems to happen quite often, when a 3rd party ad provider is plugged into a site & then 6+ months later, they go out of business. That can cause sites to wait until the http request times out, before the page is fully loaded. The net effect is that the ad is never displayed & could render out like a broken image box.

Using multiple ad content providers can alleviate those 2 problems. If a smart developer writes a set of back-fill rules for a website, then they can potentially check to make sure that the user isn't seeing a repetitive ad & the ads load fast enough. (The script could possibly force a timeout to switch to another ad provider, if an ad doesn't show up with-in a pre-determined threshold.)
> 0 votes

---
Tags: mobile, advertisements
---


# Question
Title: How do I create inertia when my character turns around?
I've been trying to give my character some inertia when it turns in the opposite direction, but for some reason my acceleration variable only seems to apply itself when my horizontal velocity is 0. For example, if my character is standing still, and my horizontal acceleration is set to 0.5 seconds, it takes my character 0.5s to reach its maximum velocity. However if I reach this velocity and then begin to turn around, the transition is much faster. This doesn’t make sense to me because it should take less time to go from 0 to 10 than it does to go from 10 to -10.

It is very easy to see this difference in my game, as even if I change my acceleration to 3s, once I reach my maximum velocity I can turn around almost instantly. I'm using the smoothdamp function, and have tried a few other methods than the one in the code below, one of which distinguished between two distinct velocity smoothing variables. I felt that this created a better feeling of drag, but could result in jerky movement depending on input.

Should I be using smoothdamp for this kind of movement, or is there a more effective solution? Ideally I'd like to have this drag increase or decrease according to my current velocity.

```
private void FixedUpdate ()
{
    HandleInput();
}

private void SetHorizontalForce(float x)
{
    if (directionalInput.x != 0)
    {
        velocity.x = Mathf.SmoothDamp(velocity.x, x, ref velocityXSmoothing,
                (State.IsCollidingBelow) ? Parameters.accelerationTimeGrounded : Parameters.accelerationTimeAirborne);
    }

    else if (directionalInput.x == 0) //Prevents the character from 'sliding' if suddenly moving left and right at low velocities
    {
            velocity.x = Mathf.SmoothDamp(velocity.x, 0, ref velocityXSmoothing, Parameters.stopTime);
    }
}

private void HandleInput()
{
    directionalInput = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));

    if (!Controller2D.State.IsClimbingLadder && !Controller2D.State.ClampLadderMovement)
    {
        SetHorizontalForce(directionalInput.x * stats.movementSpeed);
    }
}

```

# Answer
> 1 votes
Your `SmoothDamp` function can take a fifth `maxSpeed` parameter. See if giving it a proper limit works.

```
 if (directionalInput.x != 0)
    {
        velocity.x = Mathf.SmoothDamp(velocity.x, x, ref velocityXSmoothing,
                (State.IsCollidingBelow) ? Parameters.accelerationTimeGrounded : Parameters.accelerationTimeAirborne),
                 maxTransitionSpeed;
    }

```

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


# Question
Title: Does Unity store temporary autosaves for scripts? If not, how do I avoid data corruption
My PC lost power in the midst of a save(twice in a row) and I've lost my scene setup as well as a script(its contents actually). I would like to know if there are any fail-safes for saving files. If not, how would I prevent future data loss/corruption.

# Answer
Professional software developers (not just game developers and not just Unity developers) usually save themselves from this problem (and many more) by using a version control tool. Whenever you accomplished something in your project, you save your progress by creating a revision. When your project (or parts of it) get corrupted, you just revert to the last revision. Think of them as savegames for software development - when you get killed, you just reload :)

They are also essential if you are working in a team to prevent you from overwriting each others work.

Unity offers special integration support for Perforce and PlasticSCM. But if you would like to use a free solution, you can also use a technology-agnostic version control tool which just operates on your filesystem, like Git, Mercurial or Subversion.

For more information, check the chapter in the Unity documentation about version control.
> 3 votes

# Answer
For scripts you're in the middle of editing, I know Visual Studio has some amount of auto-save/recovery functionality. Once relaunched, it will prompt you if you want to recover the auto-saved version.

I mostly encounter it when Visual Studio crashes in the middle of typing, which is a perfectly normal thing for a text editor to do in 2018 I guess? :/
> 0 votes

---
Tags: unity
---


# Question
Title: OpenGL (Java) FrameBuffer DepthTexture doesn't works
I have written a Java class for a FrameBuffer and the DepthTexture is simply black or white depending on the order of the creation of the DepthTexture and DepthRenderbuffer. If the createDepthBufferAttachment is called first and then the createDepthTextureAttachment my DepthTexture is a solid white (and by that I really mean 1.0 for every coordinate, I checked that). If its the opposite way around it's a solid black. I am sure I am missing something obvious and would be very happy if someone could save me another week fiddling around with this problem.

By the way to get the texture id i use getDepthTexture() or getTexture() depending on what I want. getTexture() works like it should, the texture gathered through getDepthTexture() doesn't.

I also checked the FrameBuffer by doing glCheckFramebufferStatus(GL\_FRAMEBUFFER) == GL\_FRAMEBUFFER\_COMPLETE but it was complete so there is no issue.

If you have any questions concerning the Code feel free to ask

```
package render;

import java.nio.ByteBuffer;

import org.lwjgl.opengl.*;

public class FrameBuffer
{
    private int frameBuffer;
    private int texture;
    private int depthTexture;
    private int depthBuffer;
    private int width;
    private int height;

    public FrameBuffer(int width, int height)
    {
        this.width = width;
        this.height = height;
        initialiseResultFrameBuffer();
        Loader.registerFrameBuffer(this);
    }

    public void initialiseResultFrameBuffer()
    {
        frameBuffer = createFrameBuffer();
        texture = createTextureAttachment();
        depthBuffer = createDepthBufferAttachment();
        depthTexture = createDepthTextureAttachment();
        unbindCurrentFrameBuffer();
    }

    public int createFrameBuffer()
    {
        int frameBuffer = GL30.glGenFramebuffers();
        GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, frameBuffer);
        GL11.glDrawBuffer(GL30.GL_COLOR_ATTACHMENT0);
        return frameBuffer;
    }

    public void bindFrameBuffer()
    {
        //GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0); // I don't ever need this right?
        GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, frameBuffer);
        GL11.glViewport(0, 0, width, height);
    }

    public static void unbindCurrentFrameBuffer()
    {
        GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0);
        GL11.glViewport(0, 0, DisplayManager.getWidth(), DisplayManager.getHeight());
    }

    private int createTextureAttachment()
    {
        int texture = GL11.glGenTextures();
        GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture);
        GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, width, height, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, (ByteBuffer) null);
        GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
        GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
        GL32.glFramebufferTexture(GL30.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, texture, 0);
        return texture;
    }

    private int createDepthTextureAttachment()
    {
        int texture = GL11.glGenTextures();
        GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture);
        GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL14.GL_DEPTH_COMPONENT32, width, height, 0, GL11.GL_DEPTH_COMPONENT, GL11.GL_FLOAT, (ByteBuffer) null);
        GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
        GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
        GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
        GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
        GL32.glFramebufferTexture(GL30.GL_FRAMEBUFFER, GL30.GL_DEPTH_ATTACHMENT, texture, 0);
        return texture;
    }

    private int createDepthBufferAttachment()
    {
        int depthBuffer = GL30.glGenRenderbuffers();
        GL30.glBindRenderbuffer(GL30.GL_RENDERBUFFER, depthBuffer);
        GL30.glRenderbufferStorage(GL30.GL_RENDERBUFFER, GL11.GL_DEPTH_COMPONENT, width, height);
        GL30.glFramebufferRenderbuffer(GL30.GL_FRAMEBUFFER, GL30.GL_DEPTH_ATTACHMENT, GL30.GL_RENDERBUFFER, depthBuffer);
        return depthBuffer;
    }

    public int getFrameBuffer()
    {
        return frameBuffer;
    }
    public int getTexture()
    {
        return texture;
    }
    public int getDepthTexture()
    {
        return depthTexture;
    }

    public void cleanUp()
    {
        GL30.glDeleteFramebuffers(frameBuffer);
        GL11.glDeleteTextures(texture);
        GL11.glDeleteTextures(depthTexture);
        GL30.glDeleteRenderbuffers(depthBuffer);
    }
}

```

# Answer
> 0 votes
Finally! I found the issue. I will post it here so everyone who has the same issue can find this post. Hope this will be useful.

As I said I really was missing something really obvious. The Depthtexture must be configured to be rendered to. In my code there was a call of GL11.glDrawBuffer(GL30.GL\_COLOR\_ATTACHMENT0) which activates the drawing to the COLOR\_ATTACHMENT0. If I try to call GL11.glDrawBuffer(GL30.GL\_DEPTH\_ATTACHMENT) after that it won't render anymore to the colorattachment.

The Solution was this piece of Code here:

```
IntBuffer buffers = BufferUtils.createIntBuffer(2);
buffers.put(GL30.GL_COLOR_ATTACHMENT0);
buffers.put(GL30.GL_DEPTH_ATTACHMENT);
buffers.flip();
GL20.glDrawBuffers(buffers);

```

---
Tags: opengl, java, lwjgl3
---


# Question
Title: Help to understand positive rotation direction on left/right handed cord spaces
I began to study 3D math and noticed about left/right handed cord spaces and clockwise/counterclockwise rules. I understand that left-handed use clockwise positive rotation and right-handed counterclockwise. But what i don't understand is way this rules exists, on what technical problem this decision is based or this is just an agreement and nothing more?

# Answer
The reason is that "direction" or "clockwise / counter-clockwise" exist only in the *interpretation* of the numbers.

No matter what coordinate system we use, the math of operations like the cross product remains the same.

(Otherwise you'd have to remember to use different multiplication rules in each coordinate system, which would be even more error-prone and confusing!)

Let's try a simple cross product, between basis vectors on the positive x and y axes:

$$\begin{align}\begin{bmatrix}1\\0\\0\end{bmatrix} \times \begin{bmatrix}0\\1\\0\end{bmatrix} &=\begin{bmatrix}0\cdot0 - 0\cdot1\\0\cdot0 - 1\cdot0\\1\cdot1 - 0\cdot0\end{bmatrix}\\ &=\begin{bmatrix}0\\0\\1\end{bmatrix}\end{align}$$

We get a unit vector on the local z axis. So "x cross y equals z" is what this tells us. Note that nowhere in there did we have to "tell" the math how the axes are arranged spatially. It doesn't care, it's just rules for manipulating numbers.

Now, when we try to *interpret* that result as a statement about 3D space in a particular coordinate system, that's where differences creep in.

Say I'm working in Unity, with its coordinate system `x:right, y:up, z:forward`

I can point the fingers of my left hand so that my thumb points right, my index finger points up, and my middle finger points forward, so I can think of this relationship we just calculated as:

**x** (thumb) cross **y** (index) equals **z** (middle)

And we can call this a left-handed coordinate system.

Now let's say I move to 3DS Max, with its coordinate system `x:right, y:forward, z:up`

With the y & z axes interchanged relative to Unity's, there's no way I can contort my left hand to point in the new directions while keeping the same axis labels. But I can do it with my right hand:

And the same rule now holds for my *right* hand instead:

**x** (thumb) cross **y** (index) equals **z** (middle)

So we call 3DS Max's coordinate system right-handed.

Moving from one coordinate system to the other didn't change how the vector math works in terms of its numbers, but it did mirror the spatial interpretation of those numbers - turning a left hand to a right hand.

That same mirroring applies to rotations, turning a clockwise rotation counter-clockwise or vice versa.

If I have a particular angle-axis rotation, and when I apply that rotation in a left-handed coordinate system it moves an object clockwise when viewed from the direction of the rotation axis, then copying the same numerical operation over to a right-handed coordinate system will make an object rotate counter-clockwise when viewed from the direction of the rotation axis.
> 3 votes

# Answer
You got it backwards, the rotation direction defines the handedness.

Take both of your hands and point with your thumbs in the positive direction on the X axis. Now make an "OK" gesture with your hands without rotatong it, now the otjer fingers define a circle. If the fingers on the left hand point in the same direction as the direction of rotation around the X axis, then the coordinate system is left handed, otherwise it's right handed.

The same in a picture:
> 1 votes

---
Tags: 3d
---


title: Picking multiple choices from an enum

text:
# Question
Title: Picking multiple choices from an enum
I recall in a certain code, there were named constants with exponential values. Two constants' values could be added two include both of them in one go.

Example:

{ STR = 1, AGI = 2, INT = 4} From this, combining the enumerations would always give a unique number, which lets us identify "3" as "STR&AGI" and 5 as "STR&INT".

How I would implement this is somewhat confusing.

# Answer
> 0 votes
You can use the `Flags` decoration

```
 // Powers of two
[Flags] public enum AttackType {
    // Decimal     // Binary
    None   = 0,    // 000000
    Melee  = 1,    // 000001
    Fire   = 2,    // 000010
    Ice    = 4,    // 000100
    Poison = 8     // 001000
}

```

Then use a bitwise operator like OR

```
attackType = AttackType.Melee | AttackType.Fire;
// OR
attackType = AttackType.Melee;
attackType |= AttackType.Fire;

```

Source: A blog post by Alan Zucconi about this argument:

http://www.alanzucconi.com/2015/07/26/enum-flags-and-bitwise-operators/

You'll get all the answers you need about this topic there.

# Answer
> 12 votes
This is called a Flags enumeration.

You mark it with the `System.Flags` attribute, and give it a backing type that's some kind of integer:

```
[System.Flags]
public enum Characteristics : int {
   None    = 0x00,
   Heavy   = 0x01,
   Hot     = 0x02,
   Shiny   = 0x04,
   Squishy = 0x08,
   Loud    = 0x10,
   Large   = 0x20
}

```

You can then stack multiple flags in a single variable with an OR operator:

```
var myCharacteristics = Characteristics.Loud | Characteristics.Squishy;

```

or stack on more later with `myCharacteristics |= Characteristics.Shiny;`

You can check for the presence of a particular flag with an AND operator:

```
if((myCharacteristics & Characteristics.Loud) != Characteristics.None)
    Debug.Log("I am loud");

```

or for any of a group of flags

```
var conspicuous = Characteristics.Shiny | Characteristics.Large | Characteristics.Loud;

if((myCharacteristics & conspicuous) != Characteristics.None)
    Debug.Log("I am conspicuous");

```

To edit this properly in the Unity inspector, you can define a custom PropertDrawer like the one shown here (modified below to work with the new `EnumFlagsField` instead of `EnumMaskField`) and mark your variable with an attribute:

```
[EnumFlags]
public Characteristics myCharacteristics;

```

Here are the scripts to make this work:

EnumFlagsAttribute - place in your Assets folder.

```
using UnityEngine;

public class EnumFlagsAttribute : PropertyAttribute {
    public string enumName;

    public EnumFlagsAttribute() { }

    public EnumFlagsAttribute(string name) {
        enumName = name;
    }
}

```

EnumFlagsDrawer - place in an Assets sub-folder called "Editor" so it's not compiled into the game:

```
using System;
using System.Reflection;
using UnityEditor;
using UnityEngine;

[CustomPropertyDrawer(typeof(EnumFlagsAttribute))]
public class EnumFlagsDrawer : PropertyDrawer {
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
        EnumFlagsAttribute flagSettings = (EnumFlagsAttribute)attribute;
        Enum targetEnum = GetBaseProperty<Enum>(property);

        string propName = flagSettings.enumName;
        if (string.IsNullOrEmpty(propName))
            propName = property.name;

        EditorGUI.BeginProperty(position, label, property);
        var enumNew = EditorGUI.EnumFlagsField(position, propName, targetEnum);
        property.intValue = (int)Convert.ChangeType(enumNew, targetEnum.GetType());
        EditorGUI.EndProperty();
    }

    static T GetBaseProperty<T>(SerializedProperty prop) {
        // Separate the steps it takes to get to this property
        string[] separatedPaths = prop.propertyPath.Split('.');

        // Go down to the root of this serialized property
        System.Object reflectionTarget = prop.serializedObject.targetObject as object;
        // Walk down the path to get the target object
        foreach (var path in separatedPaths) {
            FieldInfo fieldInfo = reflectionTarget.GetType().GetField(path);
            reflectionTarget = fieldInfo.GetValue(reflectionTarget);
        }
        return (T)reflectionTarget;
    }
}

```

---

Edit: based on a link from the article Galandil shared, here's a different way to draw the flags in the inspector. I souped up the linked version to support different enum backing types, multi-object editing, and multiple rows in a single enum. It will also skip over "None" or compound flags. Still experimental, but it seems to work.

```
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;

[CustomPropertyDrawer(typeof(EnumFlagsAttribute))]
public class EnumFlagsAttributeDrawer : PropertyDrawer {

    [System.Flags]
    enum TriBool {
        Unset = 0,
        False =  1,
        True = 2,
        Both = 3
    }

    struct Entry {
        public string label;
        public int mask;
        public TriBool currentValue;
    }

    List<SerializedProperty> _properties;
    List<Entry> _entries;
    int _rowCount;
    int _columnCount;

    public override float GetPropertyHeight(SerializedProperty property, GUIContent label) {
        if (_properties == null)
            Initialize(property);
        return _rowCount * EditorGUIUtility.singleLineHeight;
    }

    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
        label = EditorGUI.BeginProperty(position, label, property);

        Rect labelRect = new Rect(
            position.x,
            position.y,
            EditorGUIUtility.labelWidth,
            position.height);
        EditorGUI.LabelField(labelRect, label);

        float buttonStride = (position.width - labelRect.width) / _columnCount;
        float buttonWidth = buttonStride * 1.0f;
        Rect buttonRect = new Rect(
            labelRect.max.x,
            labelRect.y,
            buttonWidth,
            EditorGUIUtility.singleLineHeight);

        int column = 0;

        GUIStyle mixedButton = new GUIStyle(GUI.skin.button);
        mixedButton.normal.textColor = Color.grey;

        for(int i = 0; i < _entries.Count; i++) {
            //Debug.Log(_entries[i].label + " : " + _entries[i].currentValue);
            var entry = _entries[i];

            EditorGUI.BeginChangeCheck();
            bool pressed = GUI.Toggle(
                buttonRect,
                entry.currentValue == TriBool.True,
                entry.label,
                entry.currentValue == TriBool.Both ? mixedButton : GUI.skin.button);

            if (EditorGUI.EndChangeCheck()) {

                if (pressed) {
                    foreach (var prop in _properties)
                        prop.intValue |= entry.mask;
                    entry.currentValue = TriBool.True;
                } else {
                    foreach (var prop in _properties)
                        prop.intValue &= ~entry.mask;
                    entry.currentValue = TriBool.False;
                }
                _entries[i] = entry;
            }

            buttonRect.x += buttonStride;
            if(++column >= _columnCount) {
                column = 0;
                buttonRect.x = labelRect.max.x;
                buttonRect.y += buttonRect.height;
            }
        }

        foreach (var prop in _properties)
            prop.serializedObject.ApplyModifiedProperties();

        EditorGUI.EndProperty();

        EditorGUI.showMixedValue = false;
    }

    void Initialize(SerializedProperty property) {
        var allTargetObjects = property.serializedObject.targetObjects;
        _properties = new List<SerializedProperty>(allTargetObjects.Length);
        foreach (var targetObject in allTargetObjects) {
            SerializedObject iteratedObject = new SerializedObject(targetObject);
            SerializedProperty iteratedProperty = iteratedObject.FindProperty(property.propertyPath);
            if (iteratedProperty != null)
                _properties.Add(iteratedProperty);
        }

        var parentType = property.serializedObject.targetObject.GetType();
        var fieldInfo = parentType.GetField(property.propertyPath);
        var enumType = fieldInfo.FieldType;
        var trueNames = System.Enum.GetNames(enumType);

        var typedValues = GetTypedValues(property, enumType);
        var display = property.enumDisplayNames;
        var names = property.enumNames;

        _entries = new List<Entry>();

        for (int i = 0; i < names.Length; i++) {
            int sortedIndex = System.Array.IndexOf(trueNames, names[i]);
            int value = typedValues[sortedIndex];
            int bitCount = 0;

            for (int temp = value; (temp != 0 && bitCount <= 1); temp >>= 1)
                bitCount += temp & 1;

            //Debug.Log(names[i] + ": " + value + " ~ " + bitCount);

            if (bitCount != 1)
                continue;

            TriBool consensus = TriBool.Unset;
            foreach (var prop in _properties) {
                if ((prop.intValue & value) == 0)
                    consensus |= TriBool.False;
                else
                    consensus |= TriBool.True;
            }

            _entries.Add(new Entry { label = display[i], mask = value, currentValue = consensus });
        }

        _rowCount = Mathf.CeilToInt(_entries.Count / 4f);
        _columnCount = Mathf.Min(_entries.Count, (Mathf.CeilToInt(_entries.Count / 3f) == _rowCount) ? 3 : 4);
    }

    int[] GetTypedValues(SerializedProperty property, System.Type enumType) {
        var values = System.Enum.GetValues(enumType);
        var underlying = System.Enum.GetUnderlyingType(enumType);

        if (underlying == typeof(int))
            return ConvertFrom<int>(values);
        else if (underlying == typeof(uint))
            return ConvertFrom<uint>(values);
        else if (underlying == typeof(short))
            return ConvertFrom<short>(values);
        else if (underlying == typeof(ushort))
            return ConvertFrom<ushort>(values);
        else if (underlying == typeof(sbyte))
            return ConvertFrom<sbyte>(values);
        else if (underlying == typeof(byte))
            return ConvertFrom<byte>(values);
        else
            throw new System.InvalidCastException("Cannot use enum backing types other than byte, sbyte, ushort, short, uint, or int.");
    }

    int[] ConvertFrom<T>(System.Array untyped) where T : System.IConvertible {
        var typedValues = new int[untyped.Length];

        for (int i = 0; i < typedValues.Length; i++)
            typedValues[i] = System.Convert.ToInt32((T)untyped.GetValue(i));

        return typedValues;
    }
}

```

---
Tags: unity
---


title: How to adjust scaling with rotation?

text:
# Question
Title: How to adjust scaling with rotation?
I'm rendering a texture to a square.

I have to scale the texture because it is 10 times wider than it is tall.

In my fragment shader I divide both the X and Y texture coordinates (I'm using OpenGL), but I divide the x texture coordinates by 10 times more than the y coordinates and I get this nice looking image:

Then I do some rotation of the texture (the square stays put). I rotate my texture coordinates using a matrix that looks like this:

\[cosr sinr\]

\[-sinr cosr\]

where r is the angle of rotation in radians of the player. (OpenGL uses column-major matrices).

When I rotate, of course I have to do something about scaling differently now, but I'm not sure what. For now, I'm doing nothing to adjust my scale factor for the orientation of the texture. Thus, if I rotate a little it looks like this:

And if I rotate by a lot it looks like this: (that green is the green circles from before)

What can I do to accurately adjust scale for changes in orientation in a way that makes mathematical sense?

# Answer
> 1 votes
I needed to use matrices. The same stuff that one would do for 3D, I applied to 2D for the textures.

Roughly as follows, multiplying the matrix first on the CPU then sending it to my shader. Note that OpenGL uses column-major matrices, and just like you would use 4x4 augmented matrices with a 1 at the end for transformations in 3D space, I use 3x3 augmented matrices to manipulate the 2D textures.

```
    mat3 textures_position_mat;
    mat3 textures_scale_mat;
    mat3 textures_orientation_mat;
    mat3 textures_transform_mat;

    glm_mat3_identity(textures_position_mat);
    textures_position_mat[0][2] = player.y / 1.0;
    textures_position_mat[1][2] = player.x / 1.0;

    glm_mat3_identity(textures_scale_mat);
    textures_scale_mat[0][0] = 1.0/10.0;
    textures_scale_mat[1][1] = 1.0/1.0;

    glm_mat3_identity(textures_orientation_mat);
    textures_orientation_mat[0][0] = cos(player_rotation_radians);
    textures_orientation_mat[0][1] = sin(player_rotation_radians);
    textures_orientation_mat[1][0] = -sin(player_rotation_radians);
    textures_orientation_mat[1][1] = cos(player_rotation_radians);

    glm_mat3_identity(textures_transform_mat);
    glm_mat3_mul(textures_orientation_mat, textures_scale_mat, textures_transform_mat);
    glm_mat3_mul(textures_transform_mat, textures_position_mat, textures_transform_mat);

    glUniformMatrix3fv(glGetUniformLocation(shader_perspective, "textures_transform_mat_input"), 1, GL_FALSE, textures_transform_mat);

```

My fragment shader looks like this. Note that at the end, the texture coordinates are located in the \[0\]\[2\] and \[1\]\[2\] positions as OpenGL is column-major.

```
mat3 textures_transform_matrix;

mat3 TexCoord_to_mat3;

mat3 foo_mat3;

//textures_transform_matrix = textures_transform_mat_input;

//textures_transform_matrix[0][2] = -textures_transform_matrix[0][2];

TexCoord_to_mat3[0][0] = 1.0;
TexCoord_to_mat3[1][1] = 1.0;
TexCoord_to_mat3[2][2] = 1.0;
TexCoord_to_mat3[0][2] = TexCoord.x;
TexCoord_to_mat3[1][2] = TexCoord.y;

//vec2 foo = vec2(-TexCoord.x + textures_transform_matrix[2][0], TexCoord.y + textures_transform_matrix[2][1]);
foo_mat3 = TexCoord_to_mat3 * textures_transform_mat_input;
vec2 foo = vec2(foo_mat3[0][2], foo_mat3[1][2]);

vec2 bar = vec2(TexCoord.x, TexCoord.y);
color = texture(ourTexture1, foo);

```

---
Tags: opengl, glsl, graphics-programming
---


title: Wavy effect/shader in LibGDX

text:
# Question
Title: Wavy effect/shader in LibGDX
HaxeFlixel has a nifty built-in shader called `FlxWaveEffect`.

* Video
* Demo (Flash required) if you start the game and steer the player into an enemy.
* Usage (search for FlxWaveEffect)

How does one go about creating a similar effect in LibGDX?

# Answer
These are generally done using post processing shaders. Instead of rendering the game to the screen, you render it to a framebuffer, then use it as a texture and draw a quad filling the screen with it. You can use custom shaders in the last part to enhance or stylize the game. This is how blur, DOF or sometimes special shaders (such as skyward swords water painting look) are made.

In your case, you just render everything to a framebuffer, bind that to a shader, pass the current time as a uniform and render a quad on the screen. Inside the shader you'll have:

```
gl_FragColor = texture2D(sampler, UV + vec2(sin(time + UV. y / waviness * 2.0 * 3.1415) * waveStrength, 0);

```

where waviness is the amount of waves on the screen and waveStrength is the amplitude of those waves in pixels.
> 0 votes

---
Tags: libgdx, shaders
---


# Question
Title: How can I improve my rendering performance in Java?
How can I improve the performance of my rendering? Currently, I'm rendering with java.awt.Graphics, but it seems to be starting to slow down since I'm adding new stuff to render.

My rendering setup:

Loading a spritesheet: `Spritesheet sheet = new Spritesheet(ImageLoader.loadImage("/textures/spritesheet.png"));`

Loading sprites: `BufferedImage player = sheet.crop(5, 0, Spritesheet.DEF_WIDTH, Spritesheet.DEF_HEIGHT);`

And then rendering it with java.awt.Graphics in my gameloop: `g.drawImage(player, x, y, Entity.DEF_WIDTH, Entity.DEF_HEIGHT);`

`Spritesheet.DEF_WIDTH` and `Spritesheet.DEF_HEIGHT` refer to 32px for quick access since most of my sprites are 32x32px. `Entity.DEF_WIDTH` and `Entity.DEF_HEIGHT` refer to 64px to render the entity on the screen.

One way I know that could solve my problem is that I could use smaller sprites but scale them up while rendering, but let's see if it's possible without that first.

# Answer
> 5 votes
First of all, instead of relying on the ideas of people, who didn't see a single line of code or even a picture of your game, try profiling it, finding the bottleneck and removing it.

If that isn't option, here are some general tips:

* Scaling won't help if your sprites are only 32x32, period. Maybe it would use less RAM, but that's not a problem.
* Only render things if they are on the screen. If you render 900 bullets, but 99% of them aren't seen by the player, then you might as well just calculate the exact square root of 2, it would waste the same amount of processing power.
* Make sure you aren't loading the sprites every frame. IO is usually a blocking call, which means nothing else will happen on that thread until it finishes.
* Use more threads if you can. Make sure to tread carefully when doing that though, it can make your life much harder, than not using it.
* Try using an engine or a framework (not an APi if you actually want to finish the game). The CPU is not designed to render stuff, but the GPU is. Use it

---
Tags: java, rendering, optimization
---


# Question
Title: What do I do with a libgdx rectangle collision?
The edge of the rectangle is not detached

But if the rectangle is narrowed, it will affect the left and right collision detection

# Answer
You do not need to use the same collision math for every type of collision you recognize. Try using a smaller shape to detect whether the character is level with the ground, and using a larger shape to detect whether the character collides with your other components.
> 1 votes

---
Tags: java, libgdx, android
---


# Question
Title: how to make skills and their animations in opengl ? are skills 3d model or 2d?
1)slash effect 2)area skills like dota2 crystal maiden ulti and first skill 3)over an enemy skills example dota2 crystal maiden second skill

how they make in opengl

i know opengl billboards way and texture atlas i can make basic flame effect with using these 2 way together. But how they make others ? area skills are 3d model animation ? then its texture is changing every frame? over an enemy skills can 3d model i think? how they make skills transparent ? with glblend ? what is best way to make them sorry for bad english i searched but i couldn't find any suggestion help please im using c++,sdl,opengl

# Answer
First of all, you seem very confused.

You want to create an visual effect whenever the player attacks another player. These are called **Particle Systems**. Here is a *simple* definition of a texture atlas and billboarding:

## Texture Atlas

A texture atlas looks something like this:

all it does is storing a bunch of textures in one single image, so that we can specify some coordinates(relative to this texture atlas) and get a specific texture.

## Billboards

Billboarding let's you rotate something(a quad in this case) towards the camera, so that the object is always facing you.

## Making these effects:

To make these effects, we need to use particle systems and animated quads(simple textured quads with an animation). Here is an example seen in the video:

Basically, you need a textured quad, that gets spawned onto the terrain (looks like it's projected onto the terrain, but this is the easiest way i can think of), once that is done, you need to spawn some particle systems(the fire) relative to the position of the quad.

For the other particle systems like this one:

all you need to do is get a position on the terrain, and spawn the 3D models on top of that position.
> 2 votes

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


# Question
Title: What methods are there to discard points on one side of a surface but not the other?
**Goal:** Given a surface mesh (terrain), discard all points above a given elevation relative to the terrain. The terrain can change quite often due to tiling and LODs, so the point culling will need to be dynamic and have good performance. The camera in our scene is free floating, so no assumptions can be made in that respect.

Here is a side view of the problem:

My initial attempt was to draw the terrain, translated to the given elevation, only to the depth buffer. Then, when rendering the point cloud, discarding points that fail the depth test. There are a couple problems with this method though: I have to determine which side of the translated terrain the camera is on and, if above, flipping the depth test. Also, if the camera is looking at the terrain edge-on, points will be discarded that shouldn't be.

Any ideas are welcome, and let me know if I need to make clarifications regarding the task.

# Answer
> 1 votes
If you have a height map for your terrain (or can generate one for culling purposes), you can write a vertex shader for your point cloud that samples this heightmap at the vertex's worldspace position to compute the culling altitude at that point.

Then you can abort points above the culling altitude with this line:

```
projectedVertex.x /= step(worldspaceVertex.y, cullingAltitude);

```

when the vertex is above the culling altitude, this puts an infinity or `NaN` into its projected position, which will block it and any triangles / rasterized points depending on it from being drawn.

If you're using point topology you could also just push the vertex's projected position past the far plane. The trick above is handy for triangles that may straddle the culling threshold, because it aborts the whole triangle rather than distorting it.

# Answer
> 0 votes
Your technique is mostly correct. You need to tweak it to be more like basic shadow mapping. Render the terrain to texture, depth buffer only, using a top-down orthographic projection (this corresponds to the light source in shadow mapping). Use what ever lod/tile geometry you want to clip against. The bounds of this camera represent the area you’re interested in. Then, in your shader, check if the point + offset is “shadowed”.

This should work even if the camera is under the terrain. If you want the camera position to affect the results then calculate what side the camera is on once per frame and boil it down to a +-1. Use that in your distance equation.

---
Tags: 3d-meshes, mesh, culling, point-cloud
---


# Question
Title: How to create pixel perfect noise shader?
I would like to know how they created the pixel perfect noise shader in monument valley 2 in that b/w level (example picture). I think it starts with a billboard shader, but I have no clue how to scale the texture to it's native size.

I'm using ShaderLab (unity, mobile platforms)

# Answer
> 1 votes
The trick I like to use is reading the `_TexelSize` information in the shader to adapt to whatever size of noise or other overlay we're using.

Here's an example using an image effect to get an overlay blend mode:

```
Shader "Hidden/ScreenspaceOverlay"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _OverlayTex ("Overlay", 2D) = "white" {}
        _Effect ("Effect", Range(0, 1)) = 1.0
    }
    SubShader
    {
        // No culling or depth
        Cull Off ZWrite Off ZTest Always

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 screenUV : TEXCOORD0;
                float2 overlayUV : TEXCOORD1;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            sampler2D _OverlayTex;
            float4 _OverlayTex_TexelSize;
            float4 _OverlayTex_ST;
            float _Effect;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);

                // Map the scene render normally, 0...1
                o.screenUV = v.uv;

                // Scale the overlay UV according to the size of the texture,
                // so we get 1 overlay texel per screen texel.
                o.overlayUV = v.uv * _ScreenParams.xy * _OverlayTex_TexelSize.xy;

                // In case you want to use material.SetTextureOffset()
                // to scroll or randomize the noise position.
                o.overlayUV += _OverlayTex_ST.zw;

                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                // Sample the composed scene render & the overlay texture.
                half4 col = tex2D(_MainTex, i.screenUV);
                half4 overlay = tex2D(_OverlayTex, i.overlayUV);

                // Overlay blend mode.
                half4 blended = lerp(
                    2.0f*col*overlay,
                    1.0f - 2.0f * (1.0f - col) * (1.0f - overlay),
                    step(0.5f, col)
                );

                // Return anything from 0% to 100% of the effect.
                return lerp(col, blended, _Effect);
            }
            ENDCG
        }
    }
}

```

The key bit is this line:

```
o.overlayUV = v.uv * _ScreenParams.xy * _OverlayTex_TexelSize.xy;

```

Once we have the position on screen in the 0...1 range from left to right, bottom to top (which we get conveniently as the input UV when blitting an image effect - for 3D geometry it's a bit trickier), we just need to

* scale it up by `_ScreenParams.xy`, which contains the width & height of the current render target in pixels. This gives us the position in pixel coordinates.
* scale it down by `_OverlayTex_TexelSize.xy`, which contains one divided by the texture width & height. This normalizes the texture coordinates within the texture's sampling space.

(eg. if I'm 256 pixels from the left edge of my screen, and my texture is 128 pixels wide, this will give me 2.0, meaning the image tiles twice horizontally up to this point)

I then use a tiny little script on my camera to glue a material using this shader into the rendering pipeline after the whole scene has been drawn:

```
using UnityEngine;

[ExecuteInEditMode]
[RequireComponent(typeof(Camera))]
public class PostEffector : MonoBehaviour {

    public Material effect;

    void OnRenderImage(RenderTexture source, RenderTexture destination) {
        if (effect == null)
            Graphics.Blit(source, destination);
        else
            Graphics.Blit(source, destination, effect);
    }
}

```

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


# Question
Title: Help me understand the numbering of buttons in GetMouseButtonDown
I'd like to know what the "0" stands for in this code:

```
if  (Input.GetMouseButtonDown (0))
// Do something here

```

# Answer
When you have questions about how part of the built-in Unity API works, the best place to start is the Unity documentation.

On the page for Input.GetMouseButtonDown you'll find this:

```
public static bool GetMouseButtonDown(int button);

```

> **Description**
> Returns true during the frame the user pressed the given mouse button.
>
> You need to call this function from the Update function, since the state gets reset each frame. It will not return true until the user has released the mouse button and pressed it again.
>
> *button* values are **0 for left button**, 1 for right button, 2 for the middle button.

(Emphasis added)

One caveat to add here: 0 isn't necessarily the "left" button but the *primary* button. If the player has configured their mouse to be left-handed in their OS, with click-selection on the right button and context menus on the left, then 0 will register clicks from their right button, and 1 from their left.

(I've submitted feedback to Unity asking them to clarify this in the documentation)

---

There are definitely gaps in the documentation where you'll find you need to ask clarifying questions, but it's always worth taking a quick read first in case your answer is already published - much faster than waiting for a response here!
> 2 votes

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


title: Mip map artifacts

text:
# Question
Title: Mip map artifacts
I have created a texture in Blender in texture paint mode.

Then I have started to add some details for side and corner texture. They are primarily height maps.

I had some minor pixels being a different colour on the edges (don't know why they appeared). So I painted them out with colour picker. If you look at the texture (the one that I cleaned up is third) there shouldn't be any artifacts or missing pixels. Though, data from them was somehow stored inside the texture on different layer or what I don't understand that. As a result it created weird pixels that appear only on mip maps.

Notice that original texture doesn't have these problems.

If I use image in texture on a displacement modifier in blender it uses that data to displace the mesh which is totally weird for me because I have painted out those pixels. Did I do something wrong? I have tried all the blending modes in Blender. I have tried to do everything I thought of in Krita, Paint, Paint3D.. I have changed the colours, erased the alpha, erased the colour and painted over and over again. Nothing helps. Even if the colour is set to bump the mesh, it uses the data normally but as soon as I change it back to neutral colour it uses wrong data again.

Result in Unity.

Original texture result

All the settings are the same.

# Answer
> 1 votes
Looks like you need some padding/margins in your texture so it doesn't bleed from edge to edge.

Edit:

I should probably elaborate, Ill probably come back to this ( can't right now ). So if someone else can elaborate that would be cool too.

# Answer
> -2 votes
It is happening because of the mesh quality. Use a subsurf modifier or subdivide the plane

---
Tags: unity, textures, blender, blending, mipmaps
---


title: SpriteBatch Draw

text:
# Question
Title: SpriteBatch Draw
Ok so i have 3 sprite textures and while i have a stage being drawn with Stage.draw(); only the first two will draw. but if i add a 4th then 3 will draw. However if i remove Stage.draw then everything works as normal (except my labels)

```
public void render(float delta) {
    Gdx.gl.glClearColor(.3f, .3f, .35f, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    game.batch.begin();

    game.batch.draw(headbox, HEADBOX_X, HEADBOX_Y, HEADBOX_W,HEADBOX_H);

    game.batch.draw(textbox, TEXTBOX_X, TEXTBOX_Y, TEXTBOX_W,TEXTBOX_H);

    if(Gdx.input.isKeyPressed(Input.Keys.ESCAPE)){
        //TODO: Pause menu
    }

    if(Gdx.input.isKeyJustPressed(Input.Keys.ENTER) && labelCount < Labels.size() - 1){
        Labels.get(labelCount).remove();
        labelCount++;
        stage.addActor(Labels.get(labelCount));
    }
    if(labelCount == 5){
        game.batch.draw(jame, HEADA_X, HEADA_Y, HEADA_W, HEADA_H);
        System.out.println("drawing");

    }

    stage.draw();
    stage.act();

    game.batch.end();
}

```

In ther code here only the headbox texture will draw until Label count gets to 5 then textbox will draw

# Answer
I had to put stage.act before batch.begin and stage.draw after batch.end
> -1 votes

---
Tags: java, libgdx
---