# Question
Title: creating cartoon explosions like in jetpack squad
I followed this excellent tutorial for creating volumetric explosions: https://stevencraeynest.wordpress.com/2013/03/29/easy-volumetric-explosion-in-unity3d/

I get the explosions as the tutorial mentioned, however, I noticed that jetpack squad does a similar technique but has getting much nicer cloud formations. My Question is, what kind of noise texture would I have to use to get a more cartoony explosion cloud like in jetpack squad vs the tutorial

# Answer
> 1 votes
### Short answer

Simplify your textures.

### Longer Answer

First, simplify, or blur, your displacement map. One way of doing this is to generate the displacement maps with a lower resolution. Then, scale it up, using interpolation, to the original dimensions. This will simplify the shape of the explosion. It should end up looking more like the second image, and less like the first: (original image from provided link):

This will make your explosion look less *detailed*.

---

Second, simplify your ramp texture so that it looks more like this:

This will make your explosion look less *smooth*, since there are essentially only two color values (besides the gradient in the middle).

### Conclusion

Simplifying your textures creates a more cartoony explosion, since cartoons are really just simplified graphics, right?

---
Tags: unity, graphics
---


# Question
Title: How can I find the perpendicular to a 2D vector?
I'm making a top down game where the player moves forwards towards the position of the mouse cursor. As part of the player's movement code, I need to determine a vector that is perpendicular to the player's current facing vector (to implement strafing behavior).

How can I compute the perpendicular vector of a given 2D vector?

# Answer
> 36 votes
I always forget how to do this when I need it so I wrote a couple of extension methods.

```
    public static Vector2 PerpendicularClockwise(this Vector2 vector2)
    {
        return new Vector2(vector2.Y, -vector2.X);
    }

    public static Vector2 PerpendicularCounterClockwise(this Vector2 vector2)
    {
        return new Vector2(-vector2.Y, vector2.X);
    }

```

And a unit test

```
    [Test]
    public void Vector2_Perpendicular_Test()
    {
        var a = new Vector2(5, -10);
        var b = a.PerpendicularClockwise();
        var c = a.PerpendicularCounterClockwise();

        Assert.AreEqual(new Vector2(-10, -5), b);
        Assert.AreEqual(new Vector2(10, 5), c);
    }

```

# Answer
> 55 votes
To get the 2D vector perpendicular to another 2D vector simply swap the `X` and `Y` components, negating the new `Y` component. So `{ x, y }` becomes `{ y, -x }`.

# Answer
> 8 votes
If , then a-perp obtained by a counterclockwise rotation by 90 degrees, i.e.,

See this link :)

---
Tags: vector, linear-algebra
---


# Question
Title: In unity, some part of mesh doesn't show only in play mode
This is screenshot of not playing mode. You can see the the speedloader and bullets inside of the revolver.

And this is when playing mode.

As you can see, I can see the speedloader and bullets in scene view, but not player's camera. Sometimes, it disappears in scene view either!

I made this model same as other weapons, but others are working fine. Only this weapon causes this problem. All weapons that I made are based on same model and rigs, and I kept the weapon's scale fit as same as possible.

I tried move the camera and scale down a little bit, but still couldn't saw.

Why this is happening? How do I solve this? Any advice will very appreciate it.

# Answer
Solved! Just check "Update when offscreen" of Meshrenderer component!
> 0 votes

---
Tags: unity, 3d, models
---


title: Using real-life names in fantasy league

text:
# Question
Title: Using real-life names in fantasy league
I am looking into creating a fantasy soccer league, where users can create their own virtual team of real-life soccer players. The performance the virtual team depends on how those soccer players perform in real life.

There are data providers (eg: http://www.xmlteam.com, https://fantasydata.com) targeted at fantasy leagues, their licenses are for using their data, which includes those real names, but it's obviously not the license one would need for using real names in a game. There are some articles online that state that fantasy leagues do not need licensing for showing real names and data, because it's considered the same as showing public information, similar to how the news or papers would report about sports games. Some fantasy leagues have been in court over this and succesfully defended themselves, thus not needing a license. I also contacted 2 of the biggest fantasy soccer leagues in my country, if they could inform me about how and where to obtain such a license. One didn't respond (yet), the other one replied that they have someone present at every soccer game to gather the data, so that they don't need a license to get this data from someone else - they weren't aware of other licenses regarding the usage of real names.

I also contacted the organizer of the professional soccer competition (Pro League) in my country (Belgium), on their website they advertise their licensing deal with EA, but they haven't replied (yet).

I am aware that this should be discussed with a lawyer, but for me it's more about having a reusable fantasy sports game (without the actual sports data) than having a lot of users in a functional game. In other words, if it would be OK to develop and test this game in a closed environment (on the internet, without public registration, let's call it "friends-only"), that would be sufficient for me for now.

Does this type of game need a license? At what point does or doesn't it need a license? Can I test my game online with 16 participants (registrations closed, so not open to the public) without needing a license (yet)?

# Answer
The last relevant US legal case was *C.B.C. Distribution and Marketing, Inc. vs. Major League Baseball Advanced Media, L.P. et. al*.

The decision is *generally* read to mean that one can use the same data as CBC (i.e., player names and statistics) without obtaining a license from the relevant professional sports league.

A petition to rehear was denied (without explanation) & presently, it has not gone to the supreme court. Thus, you should still consult a lawyer regarding your particular situation as:

* the ruling involves complex interactions between state and federal law
* it's not necessarily 'settled'
* it's unclear how far the ruling reaches regarding other games
* the ruling is US only; international laws may apply
* answers given here are not legal council
> 2 votes

---
Tags: legal, licensing
---


# Question
Title: Why is Unreal Engine Blueprint Editor so slow?
Blueprint Editor is extremely slow on my Ubuntu 16.04. Can I improve performance without upgrading?

# Answer
> 5 votes
The poor performance in the widget editor appears to be a bug. However, keep in mind that your system does not meet the recommended specs suggested by Epic for developing using the engine;

```
Desktop PC or Mac
Windows 7 64-bit or Mac OS X 10.9.2 or later
Quad-core Intel or AMD processor, 2.5 GHz or faster
NVIDIA GeForce 470 GTX or AMD Radeon 6870 HD series card or higher
8 GB RAM

```

Your best course of action is to file a detailed bug report with Epic to fix this specific issue, and consider upgrading for the long term.

Src: https://wiki.unrealengine.com/Recommended\_Hardware

# Answer
> 1 votes
This is a bug due to FNullSourceCodeAccessor::CanAccessSourceCode() being called too often.

There is a fix that has been applied to 4.17, and you can manually add it to your code by applying the changes found here.

https://github.com/EpicGames/UnrealEngine/commit/dbd864dc2de889a87a5b5a1d4d0c7cb58249c372

---
Tags: unreal-4, blueprints
---


# Question
Title: Intersection point of two lines with given formula
I have following formula to check the intersection of two line segments:

```
Edge is defined like point2-point1 vector.
    bool intersects(const Line2D& line2)
            {
                float s, t;
                s = (-edge.y * (point1.x - line2.point1.x) + edge.x * (point1.y - line2.point1.y)) / (-line2.edge.x * edge.y + edge.x * line2.edge.y);
                t = (line2.edge.x * (point1.y - line2.point1.y) - line2.edge.y * (point1.x - line2.point1.x)) / (-line2.edge.x * edge.y + edge.x * line2.edge.y);

                if (s >= 0 && s <= 1 && t >= 0 && t <= 1) {
                    return true;
                }
                return false;
            }

```

However I´m trying to figure out how to implement the "find the point of intersection" option for this as most of the answers with the same theme are "math based". Thanks for your help.

# Answer
`s` and `t` are the percentage of the line before the intersection point.

If `t` is between 0 and 1, them the intersection point is

```
x = point1.x + (point2.x - point1.x) * t
y = point1.y + (point2.y - point1.y) * t

```
> 1 votes

---
Tags: mathematics, vector, linear-algebra, intersection
---


# Question
Title: How do you manage / collaborate on a project in Unreal with Developers and Designers?
We have a team of 3 designers and 2 developers with no prior industry experience working on a Unreal Engine 4 project. The designers will be creating assets & laying the scene out in the editor while developers work on the functionalities in C++ side. What's a general strategy of partitioning work for such setup? More specifically, how do you have the team collaborating so that the project can be worked in parallel with minimal conflicts?

I understand that you can partition the map into sublevels and make sure that only one sublevel is being worked at a time. Well, what if you needed the designer to modify the scene while the developer adds some functionality to a sublevel? Is this not possible in Unreal?

Then there's the matter of source control. Ideally, I'd like to setup a git repository but the designers probably doesn't know how git works at all. Do game companies generally educate the designers so that they at least have working knowledge of source control to do what they need?

I'm just very confused about what the proper workflow should be.

# Answer
> 5 votes
Stock Unreal uses a binary file format for its assets; switching this would be prohibitively expensive and is thus effectively a no-go. That means you have to life with binary assets, and the problem with binary assets is that they don't merge well, if at all. This complicates collaboration.

Unreal has built-in support for most major source control systems, and where possible (e.g., with Perforce integration) will encourage you to use a system of exclusive checkout on asset files, so that only one developer can be making modifications to a file at a time (excluding some workarounds that are generally only good for temporary, scratch work one won't check in). There is some basic support for diffing certain binary assets within the Unreal editor, but it's not great, and merging support isn't really a thing.

So the best strategy is to partition your work: where feasible, break up data into different asset files so different people can modify individual files as they need. Use Unreal's sub-level support to partition your world in a fashion that works well for your design process. For example, you might put the terrain in one sub-level, major, broad-strokes environment art in another, set dressing and minor detail work in yet a third, and audio stuff in a fourth, et cetera. Such an organization would in theory let four different developers work on the same area concurrently so long as they only need to check out one of those levels.

Of course it is still possible for, say, an audio developer to be laying out a bunch of audio volumes around a building to get correct reverb settings while somebody else is busy moving that entire building somewhere else, thus creating a logical conflict. You can basically only avoid these through communication and coordination, and by paying attention to who has what other levels checked out. With a small team, this isn't that hard.

You could alternatively split the world up into several small chunks in a grid-based fashion and just dictate that everybody work in different regions of the world at once. This helps solve the major downside of the first approach (except maybe at the seams of the levels), but can also make more bottlenecks when people need to make changes to the same region of the world at the same time. This also requires communication to resolve.

---

The above mostly applies to developers who need to work on the binary assets (levels, art, Blueprints). It usually excludes programmers who work on the C++ side of things. Generally, so long as C++ programmers are not making destructive or other major file-format changes, they can work on anything concurrently with the asset-focused developers, and can use standard source control and collaboration techniques (merging, et cetera) to synchronize work with other programmers.

Where you can run into trouble with C++ changes is in scenarios where your non-programmers do not build the entire editor from scratch themselves -- that is, when they're using a pre-built binary of your editor version from a build server or whatever.

If a programmer makes certain changes, for example, if they change a file format, they generally have to be careful not to check in new assets in that format until a build is available to the non-programmers. If they check in assets in a new format before a new binary is available, and an artist syncs those new assets from source control, the artist may no longer be able to load the assets and end up blocked or even crashing, depending on the nature of the change.

This sometimes means programmers have to do this annoying dance of checking in changes with shim code supporting both old and new versions, letting that build go in, and then later removing the old shims. There are processes you can put into place to enforce these rules, and even tools you can build to help enforce it, but nothing really comes with Unreal itself.

# Answer
> 0 votes
Unreal has source control built in, I recommend checking out git, and setting up a local git server to track the users and their changes.

Good practice includes working in a separate branch per sub project. for example. If I am working on a blueprint script for a light switch I would create a branch called light switch, and after it has been tested I can merge the branch into the main branch. This prevents issues that can break the entire project until they are resolved or files from being inadvertently deleted.

As for partitioning the project, Take the overall project, and decide what components need to be built or designed, assign those to a group, then split those down into tasks. assign each group member a task based on their skills.

Slack can help in organizing communication within each group, and overall. I recommend no more than having meetings 3 times a week. This helps the programmers a lot. mainly due to the common requirement of maintaining the overall code they are working on in their head until it is complete in code.

Be sure that the code is properly commented. I can't stress how important that is especially in large projects.

---
Tags: unreal-4, project-management
---


title: Change Pawn movement speed

text:
# Question
Title: Change Pawn movement speed
I'm newbie in Unreal development and I don't know how to move my pawn faster.

By the way, I'm using Unreal 4.16.

I'm developing Pong game and I have this method to move the pawn:

```
void AAIPaddle::MovePaddle(float Scale)
{
    // Add a movement input, hardcoding Z speed to 100.0f
    FVector direction = FVector(0.0f, 0.0f, 100.0f);

    // Scale could be -1.0f or 1.0f or 0.0f.
    AddMovementInput(direction, Scale);
    if (OurMovementComponent &&
        (OurMovementComponent->UpdatedComponent == RootComponent))
    {
        OurMovementComponent->AddInputVector(direction * Scale);
        ZVelocity = Scale;
    }
}

```

You can find the class AAIPaddle here.

I use this `FVector direction = FVector(0.0f, 0.0f, 100.0f);` to set its speed, but I change the value 100.0f with 400.0f or another greater values and it moves with the same speed.

Maybe I haven't understood anything. How can I change its movement speed?

I'm using the following class that inherits from `UPawnMovementComponent`.

```
void UPaddlePawnMovementComponent::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction)
{
    Super::TickComponent(DeltaTime, TickType, ThisTickFunction);

    // Make sure that everything is still valid, and that we are allowed to move.
    //      PawnOwner: which pawn owns this MovementComponent.
    //      UpdatedComponent: the component we move and update.
    //      ShouldSkipUpdate: Possibly skip update if moved component is not rendered or can't move.
    // If none own this component or there isn't anything to move or we have to skip this update, then return.
    if (!PawnOwner || !UpdatedComponent || ShouldSkipUpdate(DeltaTime))
    {
        return;
    }

    // Get (and then clear) the movement vector that we set in ACollidingPawn::Tick
    FVector DesiredMovementThisFrame = ConsumeInputVector().GetClampedToMaxSize(1.0f) * DeltaTime * 150.0f;
    // If movement isn't nearly zero
    if (!DesiredMovementThisFrame.IsNearlyZero())
    {
        FHitResult Hit;
        // Move our UpdatedComponent by the given DesiredMovementThisFrame, and sets rotation to
        // UpdatedComponent->GetComponentRotation(), do a bSweep and store any hit on Hit.
        SafeMoveUpdatedComponent(DesiredMovementThisFrame, UpdatedComponent->GetComponentRotation(), true, Hit);

        // If we bumped into something, try to slide along it
        if (Hit.IsValidBlockingHit())
        {
            StopMovementImmediately();
        }
    }
};

```

The project is public in Github.

Maybe I don't understand something about Vectors.

# Answer
> 2 votes
I agree with Westside Tony that GetClampedToMaxSize(1.0f) is limiting the max size of the vector,

you can easily test this by increasing that number for example instead of

`FVector DesiredMovementThisFrame = ConsumeInputVector().GetClampedToMaxSize(1.0f) * DeltaTime * 150.0f;`

you can try

`FVector DesiredMovementThisFrame = ConsumeInputVector().GetClampedToMaxSize(200.0f) * DeltaTime * 150.0f;`

or you can manually scale using

`FVector DesiredMovementThisFrame = ConsumeInputVector().GetClampedToMaxSize(1.0f) * DeltaTime * 600.0f;`

---
Tags: c++, movement, unreal-4
---


title: Classes in Unity - internal vs public

text:
# Question
Title: Classes in Unity - internal vs public
Why are classes created by the game developer in Unity public (by default) when you could just as easily make them internal? For example: I go Assets-\>Create-\>C# Script. Via the default script template, I have just created a public class that derives from MonoBehaviour. But technically shouldn't this class only *have* to be internal? If so, I really want to delete that public keyword, because having the word public is a slight distraction to me.

Do outside DLLs call functions within the developer-created DLL? I don't think so, right? Because the classes in other DLLs wouldn't know what funcitons are in there beforehand anyway.

I don't know much about how these DLLs interact with each other, but I get the feeling outside DLLs don't particularly care about the one DLL assembly the game developer himself generates.

Take a look at my picture - it seems like Unity just jams all developer-created scripts in one assembly. Yes, the assembly does reference MonoBehaviour, (so I assume other classes in all the other dlls are public, not internal) but no classes outside of this one need be concerned with the details inside *this* assembly.

It doesn't matter that much. Yes, I could go on living my life peacefully and making my classes public within Unity. But is there any potential drawback, and isn't it considered better practice, to make them internal? If there's nothing wrong with making my classes internal, then I'm going to edit the default template.

# Answer
`internal` types are only visible within the assembly they are defined in. `public` types are visible outside that assembly.

The choice to have the user types generated by Unity's tools default to `public` is *probably* (but see below) simply a matter of convenience: while you are correct that in most cases these types could be `internal`, it doesn't *hurt* anything to make them `public`, and it means Unity can assume less about what the developer is going to do. It's a safe bet, basically, since it's the least restrictive option.

Also, Unity relies on reflection to accomplish some of its work. C#'s reflection APIs often take flags that specify whether to search for private types or public ones, and by default generally only search for public types. It's possible Unity's internal code is relying on that default and only expecting to be able to extract public types from the generated assemblies.
> 4 votes

---
Tags: unity, c#, assembly
---


# Question
Title: How can I execute GLFW fullsceen in a secondary monitor (Xorg)?
I am currently learning GLFW using C++. I have found many tutorials on initializing windows, but not many on initializing full screen, and next to nothing on initializing full screen on a secondary display (In this case, my television). This way I can use my primary display for logging and debugging.

I have visited the man-pages for GLFW. However, even after going over examples for **glfwGetMonitors()**, I am still not entirely sure how to use these in conjunction with **glfwCreateWindow()**.

I have included links to the reference pages.

GLFW Monitor Guide

GLFW Window Guide

# Answer
> 1 votes
You can use `glfwGetMonitors` to get a pointer into an array of `GLFWmonitor*` pointers.

You can create a window on a particular monitor using `glfwCreateWindow`. The fourth parameter is the monitor you want to create the window on.

As it says in the GLFW documentation

> To create a full screen window, you need to specify which monitor the window should use. In most cases, the user's primary monitor is a good choice.

The example given is

```
GLFWwindow* window = glfwCreateWindow(640, 480, "My Title",
                                      glfwGetPrimaryMonitor(), NULL);

```

But for your purpose, creating a window on a secondary monitor, you should do this:

```
int count;
GLFWmonitor **monitors = glfwGetMonitors(&count);
GLFWwindow *window = glfwCreateWindow(640, 480, "My Title",
                                      monitors[1], NULL);

```

Of course, you need to ensure that there are enough monitors and there are no errors (check that `count >= 2` and `monitors != NULL`). The error-handling is up to you. There are many ways to deal with errors.

This function stores the length of the array in the integer you pass a pointer to. This is quite standard in C, as C does not support tuples or pairs or multiple return values.

You also need to get the dimensions of the monitor so you can create a window of the correct size. You can do this like this:

```
const GLFWvidmode *mode = glfwGetVideoMode(monitors[1]);
... = glfwCreateWindow(mode->width, mode->height, ...);

```

There are other video modes as well that you might want to set on the window, like the refresh rate. If the video modes you set match the current video modes of the monitor exactly, you will get a 'borderless fullscreen' window, which is basically fullscreen but smoother.

> If the closest match for the desired video mode is the current one, the video mode will not be changed, making window creation faster and application switching much smoother. This is sometimes called windowed full screen or borderless full screen window and counts as a full screen window. To create such a window, simply request the current video mode.

---
Tags: c++, glfw, fullscreen
---


# Question
Title: Unity - are particles rendered and calculated when off-screen?
I have a scene where I have a lot of instances of the same particle system. As the game will go for mobile, I fear the particles are calculated even when they are not shown. So to cut it short, I would like to know if the particle system is being calculated and rendered even if off-screen.

# Answer
> 0 votes
Yes they are calculated when offscreen as stated in this library's README (this was quite a problem for them). What is cool is that this library can be used to lower the performance lost by using a second camera. If you don't have much particles then it's not worth but it might be a great improvement if you run a game heavy on particle :

> In our game, we're drawing several dozen screens worth of overlapping particles, so the speedup is pronounced.

---
Tags: unity, rendering, particles
---


title: Behavior Tree with interrupted sequence

text:
# Question
Title: Behavior Tree with interrupted sequence
I'm reading up on Behavior Trees and would like to know how a good implementation for a scenario where the conditions can change or where a selector with a higher priority interrupts the current one.

To keep it simple I will use only tree "states".

> FLEE
>
> IDLE (/DECIDE NEXT POSITION)
>
> WALK

WALK is running as long as the player has a target position. IDLE is running when player reached position or if player has no position.

Now to my question. FLEE should always interrupt the other nodes. How is this achieved in a good way?

I know this can be done in a lot of different ways so I just want to know how you would solve it.

(Sorry for no fancy node graphic. I'm on my mobile)

# Answer
Firslt remember that a decision tree is not the same as a state machine. You have listed three 'states' but they are not exactly 'states', they are compositions of other actions. Because of this, I will call them 'nodes'.

In the 'idle' and 'walk' nodes, make the logic poll for something to flee from after every fixed time period or step. If there is something to flee from, transition the logic to fleeing.

Behaviour trees are like compositions of coroutines - they must be cooperative to make sense.

---

If you have not already done so, I recommend reading Chris Simpson's Gamasutra article about behaviour trees.

It was an image of his that inspired this answer:

Note that all of these nodes are very small, quick, actions/checks. That is a very important principle of behaviour trees - to make sure that all nodes are small, fast actions and that longer running actions are merely the repetition of smaller actions, hence walking can consist of a sequence of moving once and then checking for danger without incurring overhead. If danger has been spotted, the walk 'fails' and some higher up node transitions the AI to 'flee'.
> 4 votes

# Answer
Interrupt masks (sets) and ordering resolution by priority.

Some general rules:

* any unhandled interrupts abort actions
* interrupts are handled in the order of most important to last important
* while they're handled, the current and less important interrupts are temporarily disabled
* disabling interrupts means preventing them from entering the interrupt set (bitwise mask or excluded set query)
* the interrupt set can be queried by the actions at convenient times to stop execution prematurely (forced aborting is possible but not always convenient)

The tree would look like this (increased indent = subnodes):

```
- <some AI behavior>
- if HIGH_PRIORITY_EVENT in current_interrupt_set do
  - disable interrupts HIGH_PRIORITY_EVENT and LOW_PRIORITY_EVENT
    - <handle this interrupt>
- if LOW_PRIORITY_EVENT in current_interrupt_set do
  - disable interrupts LOW_PRIORITY_EVENT
    - <handle this interrupt>

```

This structure is pretty much the same as that of exception handlers in code. (And, in fact, something not told often enough - behavior trees are basically abstract syntax trees describing code that will be cooperatively executed in parallel - so they have lots of structural similarities with code).

I implemented interrupt set as an integer where bits specify interrupts (not planning to have more than 32) but an unordered set should be fine for this as well.
> 1 votes

# Answer
I believe ultimately you can implement this as a push down automaton (PDA). The high level design is that you want some actions to take priority over others, so lets delve deeper.

It's actually not that much deeper.

(IDLE) --\[NO TARGET POSITION\] --\> (IDLE)

(IDLE) --\[TARGET POSITION\]--\> (WALK)

(WALK) --\[NO TARGET POSITION\] --\> (IDLE)

(IDLE) --\[UNDER ATTACK\] --\> (FLEE)

(WALK) --\[UNDER ATTACK\] --\> (FLEE)

(FLEE) --\[NO TARGET POSITION, NOT UNDER ATTACK\] --\> (IDLE)

(FLEE) -- \[TARGET POSITION, NOT UNDER ATTACK\] --\> (WALK)

Turns out you can use an FSM. It's possible your example is not truly representative of what you are trying to do. Interestingly enough every FSM can be represented with a directed graph which is also how you represent a behavior tree. So you could represent your behavior tree with a directed graph and equivalently a FSM.

You could in fact create behavior tree's which are not representable by an FSM, but they probably wont make sense. To do so in a manner that is not "repairable" you would need to create a behavior tree where a node has a path to two different nodes for the same condition. This seems to be an unlikely condition because it probably doesn't make sense. Consider a behavior tree where being attacked resulted in fleeing and idle.

Furthermore, if you want your character to return to their initial state AFTER a behavior, you can use a PDA. In this case you simply PUSH their current state, and then continue on your merry way to the next state. When it is completed it pops your previous state and returns to it.

IDLE -\> WALK -\> (UNDER ATTACK) -\> PUSH STATE (WALK) -\> FLEE -\> (NOT UNDER ATTACK, TARGET POSITION) -\> (POP) -\> WALK
> -1 votes

---
Tags: design-patterns, behavior
---


title: glGenVertexArray crash my program

text:
# Question
Title: glGenVertexArray crash my program
Hi I started today to make an OpenGL program, I made the shader class, mesh class and texture class. When I tried to test it, it stopped working. After a little debug with Visual Studio(thanks Microsoft for this useful tool). It showed me that my problem is:

```
glGenVertexArrays(1, &m_vao);

```

I use glew. I searched on internet, and I found that glewExperimental needs to be GL\_TRUE, so I init it like this:

```
glewExperimental = GL_TRUE;
GLenum error = glewInit();
if (error != GLEW_OK)
    std::cerr << "Glew: " << glewGetErrorString(error);

```

nothing changed.

Error given by Visual Studio:

```
Exception thrown at 0x00000000 in DirtyCraft.exe: 0xC0000005: Access violation executing location 0x00000000. occurred

```

I do use Glew 2.0.0, 32-bits, SDL2.

If you need any additional information, feel free to request them.

# Answer
> 1 votes
The Window that holds the rendering must be opened first. Also, you need to call glew first before calling any opengl functions.

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


# Question
Title: Running an Existing Game Inside of Unreal Engine
# Goal

Be able to add an overlay (a webcam feed with greenscreen processing) to an existing VR capable flight simulator so that the user can see their physical controls and the sim utilizing green screen tech.

# Problem

I need a way to run a flight simulator (XPlane, MSFSX, etc) within Unreal Engine 4. Any advice/direction is greatly appreciated. Also a solution that doesn't involve using Unreal is also valid, but I prefer to stick with Unreal.

# What I Have So Far

I currently have a way to display a webcam stream on a plane surface in Unreal with the green screen processing occurring in a blueprint.

# Ideas/Examples That I Would Need Advice On

-Running the flight simulator directly

-Emulation

~Working Example in UE4

-Running the simulator on a monitor and using some form of screen cast software to send to Unreal

-Using an existing free flight simulator UE4 project (not prefered)

# Answer
A good streaming software can do what you are describing. Having multiples video inputs and processing green screen filters...

OBS can certainly do that and it's free and open source. You can send the output of OBS to a second monitor (or in your case vr headset) using projector mode:

Right click your preview window -\> Projector -\> select monitor

OBS website
> -1 votes

---
Tags: unreal-4, unreal, virtual-reality, emulation
---


# Question
Title: Compressed vs Uncompressed Textures differences?
What is the difference?

As far as i know, compressed textures would speed things up, because the PCIe bus has to transfer less amount of data, and the interconnect is the main latency issue with GPU's. For this i'm certain.

What i'm not sure of, and this is what i mainly want an answer to is, does the GPU decompress the textures on the fly, or does it display the uncompressed textures? In other words, is there any visual impact of using the compressed textures? The GPU decompresses them automatically? Does this vary with the compression algorithm used, or is it a GPU specific thing?

Thanks in advance.

# Answer
> 5 votes
All GPU texture compressions are lossy. There is a slight degradation in image quality that may or may not be noticeable depending on what is in the texture.

The compressed textures are stored compressed in memory (both CPU and GPU memory) and decompressed on the fly during texture lookups. This reduces both the memory requirement on the GPU and increases texel lookup rate by reducing memory bandwidth requirement.

Depending on the GPU it can also increase texture cache efficiency as less cache is used per texel when the texture is held compressed into the GPU texture (and/or unified) cache.

The entire texture **does not** get decompressed to RAM when used. It remains compressed in memory. The GPU reads the compressed texture itself (through its texture samplers).

In practice the impact on the PCIe (or other) bus is minimal as textures are rarely transfered between CPU memory and GPU memory. It's on the GPU's RAM bus during texture lookups that the big difference happens. This also applies to unified memory integrated GPUs.

In some cases when the hardware does not support the compression the texture will be converted by the driver (CPU) to either another compressed format or uncompressed. In other cases the texture won't be supported at all but generally game engines take care of this for you.

---
Tags: textures, gpu, compression
---


# Question
Title: how to achieve smooth 360 Degree input with joystick as opposed to 8 angles
I have been trying to figure out how to implement controller input in my unity project. I figured out a lot of things except for how to take the 360 degree input of a thumbstick and apply that to a transform. I would like smooth movement in whatever degree the thumbstick is currently pushed towards instead of the 8 angle movement(I.E. up, down, left, right, down right, up right, down left, up left).

I have done a lot of research on this topic for a whole day now and have not come up with an answer that I could make sense of or implement correctly. I believe I need to use MathF.Atan2 but I am unsure how to incorporate it correctly.

I currently am in the process of figuring out how to do this and move a UI Image on the canvas to act as a virtual cursor for my controller support.

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

public class JoystickCursor : MonoBehaviour {

public Image cursor;
RectTransform currentPosition;

// Use this for initialization
void Start ()
{

    currentPosition = GetComponent<RectTransform>();
}

// Update is called once per frame
void Update ()
{
    float x = Input.GetAxis("JoymouseX");
    float y = Input.GetAxis("JoymouseY");

    float angle = Mathf.Atan2(x, y);

    if (Input.GetAxis("JoymouseX") > 0)
    {
        currentPosition.localPosition += Vector3.right;
    }

    if (Input.GetAxis("JoymouseX") < 0)
    {
        currentPosition.localPosition += Vector3.left;
    }

    if (Input.GetAxis("JoymouseY") > 0)
    {
        currentPosition.localPosition += Vector3.down;
    }

    if (Input.GetAxis("JoymouseY") < 0)
    {
        currentPosition.localPosition += Vector3.up;
    }

    if (Input.GetAxis("JoymouseX") > 0 && Input.GetAxis("JoymouseY") > 0)
    {
        currentPosition.localPosition += Vector3.right;
        currentPosition.localPosition += Vector3.down;
    }
}
}

```

As you can see, my current script has not implemented the atan2 portion of it because anywhere I tried has failed to give the correct results. Can anyone help me figure out how to get smooth movement so the user can aim better with the cursor since it is going to act as a crosshair in the game? Any advice is appreciated! Thanks!

# Answer
I'm going to let you in on a secret:

```
float x = Input.GetAxis("JoymouseX");
float y = Input.GetAxis("JoymouseY");

```

Here we have input with two components, an `x` and a `y`. **That's a vector!**

```
Vector2 input = new Vector2(
                      Input.GetAxis("JoymouseX"),
                     -Input.GetAxis("JoymouseY")  );

```

(Here I negated the `y`, since I noticed when `y > 0` you want to move `down`. You can also do this by checking the "Invert" box when configuring the Y axis in the Input Manager)

Now you can just add this vector to your position:

```
currentPosition.localPosition += input;

```

(A `Vector2` in Unity can implicitly convert to a `Vector3` with `z = 0`)

You can verify that when `x=1`, this moves 1 unit to the right, same as your code above, and likewise for each other cardinal direction, so it matches at the extremes of each axis. And it also varies smoothly for all axis values in between. (That includes moving at reduced speed if the player doesn't push the joystick all the way, but we can discard this analog ramp-up if you prefer for your application)

This is a typical pattern in game calculations: if you have vector inputs and vector outputs, there's very often a way to get from one to the other without using angles in between. :)

We can extend this a bit further, to move at a defined speed independent of the current framerate:

```
currentPosition.localPosition += input * speed * Time.deltaTime

```

Out of the box, this will allow diagonal movement to go slightly faster than direct horizontal/vertical, since moving at a rate of 1.0 in two perpendicular directions at once means moving at a rate of 1.414 (`sqrt(2)`) combined. That's consistent with what you've written above, but if you want to keep a constant max speed you can clamp the input to a circle like so:

```
if(input.sqrMagnitude > 1.0f)
   input = input.normalized;

```
> 5 votes

---
Tags: unity, c#, gui, joystick, gamepad
---


# Question
Title: What are the advantages of constraint-based solvers?
I am a fairly competent programmer and I am not bad at math. I have been working on game physics simulations for around 2 years now.

In some books and tutorials that I have read, they introduce constraints. They calculate Jacobian matrices and use Baumgarte constants and all that complicated stuff.

Even when I try really hard and follow their logic, I always feel lost. It is not that the mathematics or algorithms of the technique are too complicated. It is just that when things like Jacobian matrices enter the picture, it is not intuitive anymore.

In my experience applying simple impulses to resolve collisions have given satisfactory results.

So my concern is: What am I losing by not utilizing constraints? What are the situations that can benefit from having constraints? Maybe some complicated objects with joints under inverse kinematics for example?

For example: http://twvideo01.ubm-us.net/o1/vault/gdc09/slides/04-GDC09\_Catto\_Erin\_Solver.pdf and http://www.bulletphysics.com/ftp/pub/test/physics/papers/IterativeDynamics.pdf

# Answer
If you read in to Catto's notes that you posted the link to where he talks about using an iterative solver that works based on impulses, it is probably in practice not that much different than what you might be doing by, as you say "applying simple impulses to resolve collisions". Though the jacobian sounds like a complicated math idea, I reality it is basically just a bunch of vectors which 1) allow you to measure whether the constraint is met, and 2) give you the most efficient directions to apply impulses to keep the constraint satisfied. If you are already applying impulses to satisfy some constraint then you are probably doing something similar or even equivalent without being conscious of it.

When dealing with 3 dimensional rigid bodies and multidimensional constraints like hinges, the jacobian math provides a framework for expressing the constraint on the linear and angular velocities and deriving both linear and angular impulses to solve the constraints. It also provides a way where you could throw all of the constraints together (e.g. For a collection of bodies with many constraints) and solve them simultaneously. But in practice, and especially in games, we tend to use iterative solvers which are more or less a fancy way of doing a little impulse here, and a little there, and so on until everything is just right.

When you say that you "apply simple impulses to resolve collisions" perhaps that means you are constraining the position but not constraining the velocities? Such an approach can work in some contexts, but it implies that you only are applying impulses when the objects are penetrating? How about when an object is resting on a surface, under the influence of gravity? A constraint solver that works on a velocity or acceleration constraint will tell you the appropriate and correct forces at the contact points allowing you to do proper friction and such, whereas constraint only on a position level will result in constraint forces that oscillate and are much more unstable under changes in frame rate. E.g., if you have a position constraint where the impulse is proportional to the amount of penetration then equilibrium is only met at a specific spot where gravity and the constraint impulse cancel each other out. So that might be another critical difference between your approach and a constraint based approach, but it is hard to tell without knowing your algorithm and problem domain (2d particles in a meteor simulation in space? 3d simulation of a human body in a car crash simulation?)
> 2 votes

# Answer
The classical example for a constrained system is a pendulum. Assuming that the rope of the pendulum is under tension, the position of the bob of the pendulum is constrained to a circle. You can simulate this system by using Newton's laws, i.e., to simulate the force of gravity and the force the rope exerts on the bob. The problem with this approach is, however, that it is more complicated to simulate and the bob may leave the circle, due to round of errors during the simulation.

Both issues disappear when you use a constrained system. You do not have to deal with constraining forces and your simulation is guaranteed to always fulfill the constraints.
> 4 votes

# Answer
In addition to the other good answers above, a common use of constraints for physics sim is conserving energy. As mentioned for constraint to circular motion of a pendulum, it's possible that rounding error can lead a solver off from the known correct configuration of the system. Similarly, if you know energy should be conserved, that constraint can ensure that you don't accidentally start getting magic energy appearing from nowhere. Inverse kinematics is another great example.

That said, it really depends on your use case, which you haven't elaborated. In my experience it's not usually an issue unless you have incredibly ill-conditioned systems that exacerbate small errors over time and feed them back to create larger errors (think chaos theory's butterfly effect). I doubt your average game mechanics bother with constraint-based solvers unless they need high precision of detailed kinematic interactions. These solvers are much more sophisticated to write and set up correctly, as you can see from all the math.

Bottom line: unless you suspect QWOP-level insanity may ensue from the setup of your mechanical systems, just add enough damping and small enough step sizes to your system and you'll probably be fine with regular solvers.

Bonus: A cheap hack if you are concerned about numerical stability in your case but not about scientific precision (this is gaming after all) is that small constraint/conservation corrections could be made periodically in such a way that isn't visually noticeable but keeps things in check if the error crosses some tolerance. Or add some hacky checks on calculations of forces and make sure they don't cross some extreme threshold through divisions by numbers close to zero (e.g. arising from poor precision in a subtraction in the denominator).

For context, I have a PhD in applied math and have developed my own solver / simulation package for scientists.
> 2 votes

# Answer
Im not expert on this topic, but i have read the presentation and skipped over the paper.

As Rittich said, you can apply the newtonian impuls calculations on a system of pendulums, which are paired by constrains to each other. In this case, you would need to calculate the force that applies to the inner pendulum, then the outer pendulum and the forces between them seperatly. This problem only gets stonger, the more bodys can interact with each other, so for example an n-elemental pendulum.

With the constraint-based solver, you got information for a body consisting of several constrains, that can be solved via numerical calcultaions. That means, instead of calculation the exact position every time a force works on the the contrains, you can use iterative calculations to approximate the results.

Approximation sound problematic, but in most cases it is not noticable after a few iterative steps.
> 1 votes

---
Tags: physics
---


title: Room-based camera movement

text:
# Question
Title: Room-based camera movement
I'm trying to make a camera system where the camera never goes outside the edges of the current room (like Link to the Past or Mega Man, for example)

This is what I have right now:

```
using UnityEngine;
using System.Collections;
public class CameraFollow : MonoBehaviour {
public BoxCollider roomBounds;
public Player target;
Vector3 velocity;
float halfHeight,halfWidth;
void Start(){
    halfHeight = Camera.main.orthographicSize;
    halfWidth = halfHeight * Camera.main.aspect;
}
void LateUpdate(){
    Vector3 targetPosition = target.transform.position;
    if (targetPosition.x+halfWidth >= roomBounds.bounds.max.x || targetPosition.x-halfWidth <= roomBounds.bounds.min.x) {
        velocity.x = 0;
    } else {
        velocity.x = targetPosition.x - transform.position.x;
    }
    if (targetPosition.y+halfHeight >= roomBounds.bounds.max.y || targetPosition.y-halfHeight <= roomBounds.bounds.min.y) {
        velocity.y = 0;
    } else {
        velocity.y = targetPosition.y - transform.position.y;
    }
    transform.position += velocity;
}
}

```

It works on a rudimentary level, but the problem is, whenever you're moving out from a wall after the camera's stopped, it snaps a little to the left or the right, and then goes back. Same vertically.

Any idea as to what might be causing this and how to solve it?

P.S. I know there have been a lot of threads about this kind of system (even one 21 hours ago), but none I've found helped me much.

# Answer
> 1 votes
Clamping the Camera's position at the end of position calculation would fix your problem. Put this code at the end of your ''LateUpdate()'' method.

```
float finalXPos = Mathf.Clamp(transform. Position.x, roomBounds.bounds.min.x + halfWidth, roomBounds.bounds.max.x - halfWidth);
float finalYPos; // Do the same calculation for Y position.
transform.position = new Vector2(finalXPos, finalYPos);

```

**Note**: Code might be little of syntactically (since I cannot test it right now), and also there might be a clamping function for `Vector2`, which you can search for it.

---
Tags: unity, c#, camera
---


# Question
Title: Direct3D11 and SharpDX - How to pass a model instance's world matrix as an input to a vertex shader
Using Direct3D11, I'm trying to pass a matrix into my vertex shader from the instance buffer that is associated with a given model's vertices and I can't seem to construct my `InputLayout` without throwing an exception.

The shader looks like this:

```
cbuffer ConstantBuffer : register(b0)
{
    matrix World;
    matrix View;
    matrix Projection;
}

struct VIn
{
    float4 position: POSITION;
    matrix instance: INSTANCE;
    float4 color: COLOR;
};

struct VOut
{
    float4 position : SV_POSITION;
    float4 color : COLOR;
};

VOut VShader(VIn input)
{
    VOut output;
    output.position = mul(input.position, input.instance);
    output.position = mul(output.position, View);
    output.position = mul(output.position, Projection);
    output.color = input.color;
    return output;
}

```

The input layout looks like this:

```
var elements = new[]
{
    new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
    new InputElement("INSTANCE", 0, Format.R32G32B32A32_Float, 0, 0, InputClassification.PerInstanceData, 1),
    new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0)
};
InputLayout = new InputLayout(device, signature, elements);

```

The buffer initialization looks like this:

```
public ModelDeviceData(Model model, Device device)
{
    Model = model;
    var vertices = Helpers.CreateBuffer(device, BindFlags.VertexBuffer, model.Vertices);
    var instances = Helpers.CreateBuffer(device, BindFlags.VertexBuffer, Model.Instances.Select(m => m.WorldMatrix).ToArray());
    VerticesBufferBinding = new VertexBufferBinding(vertices, Utilities.SizeOf<ColoredVertex>(), 0);
    InstancesBufferBinding = new VertexBufferBinding(instances, Utilities.SizeOf<Matrix>(), 0);
    IndicesBuffer = Helpers.CreateBuffer(device, BindFlags.IndexBuffer, model.Triangles);
}

```

The buffer creation helper method looks like this:

```
public static Buffer CreateBuffer<T>(Device device, BindFlags bindFlags, params T[] items)
    where T : struct
{
    var len = Utilities.SizeOf(items);
    var stream = new DataStream(len, true, true);
    foreach (var item in items)
        stream.Write(item);
    stream.Position = 0;
    var buffer = new Buffer(device, stream, len, ResourceUsage.Default,
        bindFlags, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
    return buffer;
}

```

The line that instantiates the `InputLayout` object throws this exception:

\*HRESULT: \[0x80070057\], Module: \[General\], ApiCode: \[E\_INVALIDARG/Invalid Arguments\], Message: The parameter is incorrect.\*

Note that the data for each model instance is simply an instance of `SharpDX.Matrix`.

**EDIT**

Based on Tordin's answer, it sems like I have to modify my code like so:

```
var elements = new[]
{
new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0),
new InputElement("INSTANCE0", 0, Format.R32G32B32A32_Float, 0, 1, InputClassification.PerInstanceData, 1),
new InputElement("INSTANCE1", 1, Format.R32G32B32A32_Float, 16, 1, InputClassification.PerInstanceData, 1),
new InputElement("INSTANCE2", 2, Format.R32G32B32A32_Float, 32, 1, InputClassification.PerInstanceData, 1),
new InputElement("INSTANCE3", 3, Format.R32G32B32A32_Float, 48, 1, InputClassification.PerInstanceData, 1),
};

```

and in the shader:

```
struct VIn
{
    float3 position: POSITION;
    float4 color: COLOR;
    matrix instance: INSTANCE;
};

VOut VShader(VIn input)
{
    VOut output;
    output.position = mul(input.position, input.instance);
    output.position = mul(output.position, View);
    output.position = mul(output.position, Projection);
    output.color = input.color;
    return output;
}

```

However I still get an exception.

# Answer
in your input layout, you are only specifying one part of the matrix. you have to specif the other three. You are saying that you have a VECTOR, not a matrix. to build a matrix, you must have 4 elements for a matrix, and saying that they belong into a specific register.

Reading this link, says on the second argument "a 4x4 matrix would have four components each with the semantic name"
MSDN LINK INPUTLAYOUTS
> 3 votes

# Answer
This may be a bit late but if anyone else would come across this topic, this answer is supposed to be a more extensive answer to the question as I believe some things are not properly pointed out.

First off, as clarified by a comment above the input layout has to use a predefined sematic name, in this case we could use:

```
{ "TEXCOORD", 1, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 0, D3D11_INPUT_PER_INSTANCE_DATA, 1 },
{ "TEXCOORD", 2, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_INSTANCE_DATA, 1 },
{ "TEXCOORD", 3, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_INSTANCE_DATA, 1 },
{ "TEXCOORD", 4, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_INSTANCE_DATA, 1 },

```

Although this will only work if your instance vertex buffer is bound at slot 1. Also note that we start with the sematic name "TEXCOORD1" as most applications already have "TEXCOORD" bound to the actual texture-coordinates for the object.

Now in the vertex shader we will have to provide an appropriate input struct which should match the input layout we have defined, for example:

```
struct VS_IN
{
    float3 Pos : POSITION;
    float2 UV : TEXCOORD;
    float3 Normal : NORMAL;
    float3 Tangent : TANGENT;
    float4 InstancePos0 : TEXCOORD1;
    float4 InstancePos1 : TEXCOORD2;
    float4 InstancePos2 : TEXCOORD3;
    float4 InstancePos3 : TEXCOORD4;
};

```

Then we simply have to construct a 4x4 matrix from the instanced data we have provided:

```
float4x4 world = float4x4(input.InstancePos0, input.InstancePos1, input.InstancePos2, input.InstancePos3);

```
> 1 votes

---
Tags: shaders, directx11
---


# Question
Title: LibGDX - How to do more things asynchronously
Most documentation only mentions how to load assets asynchronously, eg with code similar to

```
private void render(float delta){
  if (assetManager.update()){
     // ** HERE ** //
     game.setScreen(new MainGameScreen(game));
  } else {
    progress = assetManager.getProgress();
  }

  // draw progress bar or whatever
}

```

but what if, as part of game initialization, I have to do other things before switching to the main game screen (marked with \** HERE \** in the above code)? Sure, the user is still seeing the splash screen, but what if I wanted to do these things in background as well, and give some sign of progress (another progress bar, or whatever). I haven't found examples of similar things (or perhaps I haven't looked hard enough).

# Answer
You can use the asynchronous executor, `AsyncExecutor`, to run things asynchronously in **libGDX**.

```
class MyScreen extends Screen {
  private AsyncExecutor executor = new AsyncExecutor(4);
  private AsyncResult<Void> task;
  private float someProgressValue;

  public void create() {
     assetManager.load(...);
     task = executor.submit(new AsyncTask<Void>() {
       public Void call() {
          // Do something here and update someProgressValue as you go
          return null;
       }
     }
  }
}

private void render(float delta){
  // Here check for both the assetManager and the task's completion state
  if (assetManager.update() && task.isDone()){
     game.setScreen(new MainGameScreen(game));
  } else {
    progress1 = assetManager.getProgress();
    progress2 = someProgressValue;
  }

  // draw progress bar for progress1
  // draw progress bar for progress2
}

```
> 4 votes

---
Tags: libgdx, initialization
---


title: How to optimise mesh data

text:
# Question
Title: How to optimise mesh data
So i have some procedurally generated mesh data and i want to reduce it down to its minimum number of verts. In case it matters this is a unity project.

Working on the basis of a simple example, lets assume a typical flat surface of points 2 by 3.

The point / vertex at \[1,1\] is used in many triangles.

I've generated mesh for a voxel type engine that adds verts to a list based on face visiblility and now I want to remove all the duplicates.

Can anyone come up with an efficient way of doing this because what i have is sooo bad its not even funny (and i don't even think it's logically correct) ...

```
private void Optimize()
{
    Vector3 v;
    Vector3 v2;
    for (int i = 0; i < Vertices.Count; i++)
    {
        v = Vertices[i];
        for (int j = i+1; j < Vertices.Count; j++)
        {
            v2 = Vertices[j];
            if (v.x == v2.x && v.y == v2.y && v.z == v2.z)
            {
                for (int ind = 0; ind < Indices.Count; ind++)
                {
                    if (Indices[ind] == j)
                    {
                        Indices[ind] = i;
                    }
                    else if (Indices[ind] > j && Indices[ind] > 0)
                        Indices[ind]--;
                }

                Vertices.RemoveAt(j);
                Uvs.RemoveAt(j);
                Normals.RemoveAt(j);
            }
        }
    }
}

```

EDIT: Ok i managed to get this (code sample above updated) to render an "optimised" set of verts but the UV data is all wrong now, which would make sense because i'm basically just removing any UV Vector that represents a UV coord for a removed vert and not actually considering what I need to do to "fix the tri" so to speak.

The code now seemingly does work but its quite time consuming, still looking to further optimise.

# Answer
> 3 votes
Unity's `Mesh` class has an `Optimize` method which should give you what you want.

From the wiki page:

> You should use it if you generate a mesh from scratch procedurally and you want to trade better runtime performance against higher load time.

# Answer
> 0 votes
I think you will have to spend time running the optimization and there isn't much way around that. Maybe the implementation itself could be faster but still.

Try loading chunks of mesh at a time, its a common solution, or decreasing the number of optimizations that have to be done.

Another solution could be optimizing the mesh itself (the assets) rather than doing it at runtime

---
Tags: c#, unity, optimization, mesh
---


# Question
Title: How do I reconfigure my GLES frame buffer after a rotation?
*Note: In order to keep the question as simple as possible, I am actively changing the body of the question to reflect the current state of affairs, instead of adding stuff at the bottom.*

I am implementing interface rotation for my GLES based game for iOS, written in Xamarin.iOS with OpenTK.

I am detecting the rotation by overriding `WillRotate`, in my `UIViewController`, and I correctly re-setup all of my projection matrices.

However, the results of drawing a sprite on landscape and portrait modes are slightly different -landscape is a bit blurry-.

This is the test sprite I am using, which is 128x128 to avoid any rounding errors:

My test projection matrix is based on a 1024x768 display for an iPad. Even though I won't be scaling the image, I am using point filtering, so I expect rendering to be pixel perfect. The rendering position is (0, 0) once again to avoid any rounding errors. The sprite should fall exactly into the pixel boundaries for both portrait and landscape.

Additionally, in both cases, I'm using the same texture with the same sampler, the same shader, and the same GL state.

This is what happens when I render the sprite in portrait mode. This is pretty much how I expect it to be rendered (magnified 5x):

And this is what happens when I render the same sprite in landscape mode.

My belief is that the framebuffer was created as 768x1024, but when rotated, it is made to fit the 1024x768 screen, squished on the horizontal and stretched in the vertical, and this is what is causing the problem.

If I set OpenTK to create a 1024x1024 framebuffer, the result becomes consistent in portrait and landscape. This is portrait:

Notice how there is be no distortion on the vertical, which happens to be 1024 pixels as well. The distortion is limited to the horizontal, where the resolution doesn't match. This is landscape:

This time the distortion moved to the vertical, supporting my hypothesis.

Furthermore, creating it at 3072x3072, 3072 being the least common multiple of 1024 and 768, the results are correct both in portrait and landscape:

Notice that this is not a solution, since not only I'm wasting a lot of memory, but also will create inconsistent multisampling artifacts with 3D, as the vertical scaling is different from the horizontal scaling. Additionally, this is not an option for the iPhone 5, whose resolution of 1136x640 would require me to create a framebuffer of 45440x45440.

Since a device rotation could be thought of as a window resize, I think that the framebuffer has to be recreated to match the new size. This is necessary for Windows on Direct3D. I would have to call `swapChain.ResizeBuffers()` to do this in SharpDX.

I have tried setting `AutoResize = true` in my `iPhoneOSGameView`, but then the framebuffer gets clipped as I rotate the interface, and then everything disappears when rotating the interface again.

I'm not doing anything strange, my framebuffer initialization is pretty vanilla:

```
int scaling = (int)UIScreen.MainScreen.Scale;
DeviceWidth = (int)UIScreen.MainScreen.Bounds.Width * scaling;
DeviceHeight = (int)UIScreen.MainScreen.Bounds.Height * scaling;
Size = new System.Drawing.Size((int)(DeviceWidth), (int)(DeviceHeight));
Bounds = new System.Drawing.RectangleF(0, 0, DeviceWidth, DeviceHeight);
Frame = new System.Drawing.RectangleF(0, 0, DeviceWidth, DeviceHeight);
ContextRenderingApi = EAGLRenderingAPI.OpenGLES2;
AutoResize = true;
LayerRetainsBacking = true;
LayerColorFormat = EAGLColorFormat.RGBA8;

```

I get inconsistent results when changing `Size`, `Bounds` and `Frame` on my `CreateFrameBuffer` override. Unfortunately, the documentation is very incomplete, so I have resorted to randomly changing stuff here and there without really knowing what is going on.

There is a similar question which has no answers. However, I don't know if they're experiencing the same problem as I am.

Also, there is a similar concern over at the xamarin forums, specifically mentioning the rotation issue. There seems to be no solution outside of dropping `GameView` completely.

Is my supposition that recreating the framebuffer is necessary, correct? If so, does anybody know how to do it correctly in OpenTK for Xamarin.iOS?

# Answer
Yes, the renderbuffer must be recreated when the interface is rotated, and set to the new size.

Recreating it is not difficult. However, the renderbuffer ID is private in `iPhoneOSGameView`, and only accessible via the `Renderbuffer` property, which doesn't have a public setter.

Reflection to the rescue! By inspecting `iPhoneOSGameView`, I found out that it contains a field called `renderbuffer` that seems to be quite promising as the backing field behind `Renderbuffer`.

So, when I detect a rotation, I recreate my renderbuffer, and then set it via reflection.

Doing things like this is kinda risky, since I don't really know what else (if anything) I have to change, but so far it looks good.

```
public void ResizeFrameBuffer(int newWidth, int newHeight)
{
    DeviceWidth = newWidth;
    DeviceHeight = newHeight;

    Size = new System.Drawing.Size(DeviceWidth, DeviceHeight);
    Bounds = new System.Drawing.RectangleF(0, 0, DeviceWidth, DeviceHeight);

    MakeCurrent();

    int renderbuffer = Renderbuffer;

    GL.DeleteRenderbuffers(1, ref renderbuffer);

    GL.BindFramebuffer(FramebufferTarget.Framebuffer, Framebuffer);
    GL.GenRenderbuffers(1, out renderbuffer);
    GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, renderbuffer);
    EAGLContext.RenderBufferStorage((uint)RenderbufferTarget.Renderbuffer, (CAEAGLLayer)Layer);
    GL.FramebufferRenderbuffer(FramebufferTarget.Framebuffer, FramebufferSlot.ColorAttachment0, RenderbufferTarget.Renderbuffer, renderbuffer);
    GL.Viewport(0, 0, DeviceWidth, DeviceHeight);
    GL.Scissor(0, 0, DeviceWidth, DeviceHeight);

    var type = typeof(iPhoneOSGameView);
    var renderbufferField = type.GetField("renderbuffer", BindingFlags.NonPublic | BindingFlags.Instance);
    renderbufferField.SetValue(this, renderbuffer);

    Frame = new System.Drawing.RectangleF(0, 0, DeviceWidth, DeviceHeight);
}

```

`iPhoneOSGameView` never saw it coming...
> 1 votes

# Answer
This is now part of OpenTK. `iPhoneOSGameView` now has a `ResizeFrameBuffer` method based on @Panda Pajama's answer, which should be called on screen rotation.

https://github.com/opentk/opentk/pull/521
> 0 votes

---
Tags: ios, opengl-es2, opentk, monotouch
---


# Question
Title: What's a way to improve this wall collision detection code to keep objects within a perimeter made of these walls
How can I improve the following code to keep objects from leaving a perimeter made of these walls?

Sometimes Player will collide with both a wall and an NPC (using same type of collision detection) and will end up outside of the perimeter.

I want to keep Player inside the perimeter of walls.

```
// Player Collides with Wall
        counter1 = 0;
        for (iter60 = wallArray.begin(); iter60 != wallArray.end(); iter60++)
        {
            if (Player1.rect.getGlobalBounds().intersects(wallArray[counter1].rect.getGlobalBounds()))
            {
                int direction = Player1.direction;
                Player1.sprint = false;
                int arraySize1 = wallArray.size();

                switch (direction)
                {
                case 1:
                    if (Player1.rect.getPosition().y > wallArray[counter1].rect.getPosition().y)
                    {
                        if (abs(abs(Player1.rect.getPosition().y) - abs(wallArray[counter1].rect.getPosition().y)) <= 5)
                            Player1.rect.setPosition(Player1.rect.getPosition().x, Player1.rect.getPosition().y + 3.5);
                        else if (abs(abs(Player1.rect.getPosition().y) - abs(wallArray[counter1].rect.getPosition().y)) <= 7)
                            Player1.rect.setPosition(Player1.rect.getPosition().x, Player1.rect.getPosition().y + 3.2);
                        else if (abs(abs(Player1.rect.getPosition().y) - abs(wallArray[counter1].rect.getPosition().y)) <= 10)
                            Player1.rect.setPosition(Player1.rect.getPosition().x, Player1.rect.getPosition().y + 2.9);
                        else if (abs(abs(Player1.rect.getPosition().y) - abs(wallArray[counter1].rect.getPosition().y)) <= 15)
                            Player1.rect.setPosition(Player1.rect.getPosition().x, Player1.rect.getPosition().y + 2.7);
                        else if (abs(abs(Player1.rect.getPosition().y) - abs(wallArray[counter1].rect.getPosition().y)) <= 20)
                            Player1.rect.setPosition(Player1.rect.getPosition().x, Player1.rect.getPosition().y + 2.5);
                        else if (abs(abs(Player1.rect.getPosition().y) - abs(wallArray[counter1].rect.getPosition().y)) <= 25)
                            Player1.rect.setPosition(Player1.rect.getPosition().x, Player1.rect.getPosition().y + 2.0);
                        else if (abs(abs(Player1.rect.getPosition().y) - abs(wallArray[counter1].rect.getPosition().y)) <= 30)
                            Player1.rect.setPosition(Player1.rect.getPosition().x, Player1.rect.getPosition().y + 1.8);
                        else if (abs(abs(Player1.rect.getPosition().y) - abs(wallArray[counter1].rect.getPosition().y)) <= 32)
                            Player1.rect.setPosition(Player1.rect.getPosition().x, Player1.rect.getPosition().y + 1.5);
                    }
                    break;
                case 2:
                    if (Player1.rect.getPosition().y < wallArray[counter1].rect.getPosition().y)
                    {
                        if (abs(abs(Player1.rect.getPosition().y) - abs(wallArray[counter1].rect.getPosition().y)) <= 5)
                            Player1.rect.setPosition(Player1.rect.getPosition().x, Player1.rect.getPosition().y - 3.5);
                        else if (abs(abs(Player1.rect.getPosition().y) - abs(wallArray[counter1].rect.getPosition().y)) <= 7)
                            Player1.rect.setPosition(Player1.rect.getPosition().x, Player1.rect.getPosition().y - 3.2);
                        else if (abs(abs(Player1.rect.getPosition().y) - abs(wallArray[counter1].rect.getPosition().y)) <= 10)
                            Player1.rect.setPosition(Player1.rect.getPosition().x, Player1.rect.getPosition().y - 2.9);
                        else if (abs(abs(Player1.rect.getPosition().y) - abs(wallArray[counter1].rect.getPosition().y)) <= 15)
                            Player1.rect.setPosition(Player1.rect.getPosition().x, Player1.rect.getPosition().y - 2.7);
                        else if (abs(abs(Player1.rect.getPosition().y) - abs(wallArray[counter1].rect.getPosition().y)) <= 20)
                            Player1.rect.setPosition(Player1.rect.getPosition().x, Player1.rect.getPosition().y - 2.5);
                        else if (abs(abs(Player1.rect.getPosition().y) - abs(wallArray[counter1].rect.getPosition().y)) <= 25)
                            Player1.rect.setPosition(Player1.rect.getPosition().x, Player1.rect.getPosition().y - 2.0);
                        else if (abs(abs(Player1.rect.getPosition().y) - abs(wallArray[counter1].rect.getPosition().y)) <= 30)
                            Player1.rect.setPosition(Player1.rect.getPosition().x, Player1.rect.getPosition().y - 1.8);
                        else if (abs(abs(Player1.rect.getPosition().y) - abs(wallArray[counter1].rect.getPosition().y)) <= 32)
                            Player1.rect.setPosition(Player1.rect.getPosition().x, Player1.rect.getPosition().y - 1.5);
                    }
                    break;
                case 3:
                    if (Player1.rect.getPosition().x > wallArray[counter1].rect.getPosition().x)
                    {
                        if (abs(abs(Player1.rect.getPosition().x) - abs(wallArray[counter1].rect.getPosition().x)) <= 5)
                            Player1.rect.setPosition(Player1.rect.getPosition().x + 3.5, Player1.rect.getPosition().y);
                        else if (abs(abs(Player1.rect.getPosition().x) - abs(wallArray[counter1].rect.getPosition().x)) <= 7)
                            Player1.rect.setPosition(Player1.rect.getPosition().x + 3.2, Player1.rect.getPosition().y);
                        else if (abs(abs(Player1.rect.getPosition().x) - abs(wallArray[counter1].rect.getPosition().x)) <= 10)
                            Player1.rect.setPosition(Player1.rect.getPosition().x + 2.9, Player1.rect.getPosition().y);
                        else if (abs(abs(Player1.rect.getPosition().x) - abs(wallArray[counter1].rect.getPosition().x)) <= 15)
                            Player1.rect.setPosition(Player1.rect.getPosition().x + 2.7, Player1.rect.getPosition().y);
                        else if (abs(abs(Player1.rect.getPosition().x) - abs(wallArray[counter1].rect.getPosition().x)) <= 20)
                            Player1.rect.setPosition(Player1.rect.getPosition().x + 2.5, Player1.rect.getPosition().y);
                        else if (abs(abs(Player1.rect.getPosition().x) - abs(wallArray[counter1].rect.getPosition().x)) <= 25)
                            Player1.rect.setPosition(Player1.rect.getPosition().x + 2.0, Player1.rect.getPosition().y);
                        else if (abs(abs(Player1.rect.getPosition().x) - abs(wallArray[counter1].rect.getPosition().x)) <= 30)
                            Player1.rect.setPosition(Player1.rect.getPosition().x + 1.8, Player1.rect.getPosition().y);
                        else if (abs(abs(Player1.rect.getPosition().x) - abs(wallArray[counter1].rect.getPosition().x)) <= 32)
                            Player1.rect.setPosition(Player1.rect.getPosition().x + 1.5, Player1.rect.getPosition().y);
                    }
                    break;
                case 4:
                    if (Player1.rect.getPosition().x < wallArray[counter1].rect.getPosition().x)
                    {
                        if (abs(abs(Player1.rect.getPosition().x) - abs(wallArray[counter1].rect.getPosition().x)) <= 5)
                            Player1.rect.setPosition(Player1.rect.getPosition().x - 3.5, Player1.rect.getPosition().y);
                        else if (abs(abs(Player1.rect.getPosition().x) - abs(wallArray[counter1].rect.getPosition().x)) <= 7)
                            Player1.rect.setPosition(Player1.rect.getPosition().x - 3.2, Player1.rect.getPosition().y);
                        else if (abs(abs(Player1.rect.getPosition().x) - abs(wallArray[counter1].rect.getPosition().x)) <= 10)
                            Player1.rect.setPosition(Player1.rect.getPosition().x - 2.9, Player1.rect.getPosition().y);
                        else if (abs(abs(Player1.rect.getPosition().x) - abs(wallArray[counter1].rect.getPosition().x)) <= 15)
                            Player1.rect.setPosition(Player1.rect.getPosition().x - 2.7, Player1.rect.getPosition().y);
                        else if (abs(abs(Player1.rect.getPosition().x) - abs(wallArray[counter1].rect.getPosition().x)) <= 20)
                            Player1.rect.setPosition(Player1.rect.getPosition().x - 2.5, Player1.rect.getPosition().y);
                        else if (abs(abs(Player1.rect.getPosition().x) - abs(wallArray[counter1].rect.getPosition().x)) <= 25)
                            Player1.rect.setPosition(Player1.rect.getPosition().x - 2.0, Player1.rect.getPosition().y);
                        else if (abs(abs(Player1.rect.getPosition().x) - abs(wallArray[counter1].rect.getPosition().x)) <= 30)
                            Player1.rect.setPosition(Player1.rect.getPosition().x - 1.8, Player1.rect.getPosition().y);
                        else if (abs(abs(Player1.rect.getPosition().x) - abs(wallArray[counter1].rect.getPosition().x)) <= 32)
                            Player1.rect.setPosition(Player1.rect.getPosition().x - 2.0, Player1.rect.getPosition().y);
                    }
                    break;
                }
            }
            else
            {

            }
            counter1++;
        }

```

# Answer
You are using absolute positions in world space to detect "in bounds" or "out of bounds" on a 2D xy axis plane. It would be easier and less code to do line intersect testing where each wall is two points connected by a line and your collision testing line intersections with your player line of motion. That line of motion can be current position and previous position. For two line intersection go to this older post here: https://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect
> 1 votes

# Answer
You're trying to vector math without using vectors. Actually using vectors allows you to "find the right answer" using an equation rather than polling several possible solutions.

I would axe "direction" and replace it with "velocity" to fit nicer with vector formulas (nextPos = currentPos + velocity)

My general advice would be to create a new var "nextPos" equal to "Player1.rect.getPosition() + (direction * speed)". Then you compare nextPos to all the walls. Should there be a collision, you calculate the penetration and add that to nextPos

in pseudoCode it would be like this

```
//compute the next location as if there were no collisions
auto nextPos = Player1.rect.getPosition() + (velocity);
for(auto& w : walls){
   //for every wall, check if the new pos collides. If it does return
   //collision resolution information (-velocity with a magnitude of
   //penetration) but add as many params as you want
   auto penetration = w.CollidesWith(w,velocity)

   //if there is a collision, adjust the next pos and then leave
   //I'm assuming it's not possible to collide with multiple objects,
   //if it is, then don't break
   if(penetration) {nextPos += penetration.value; break;}
}
//Set the playerPosition to nextPosition
Player1.rect.setPosition(nextPos);

```

If you're interested in learning how to detect collisions and calculate their resolutions. I'd recommend looking into "collision manifolds".
> 0 votes

---
Tags: c++, collision-detection, sfml
---


# Question
Title: How to detect collision between entities using Ashley?
I am developing a game using Libgdx and Ashley, and I would like to know the best way to detect collisions between different entities. Currently I have been using a ContactListener that detects contacts between different types of entities but I think this could negatively affect the performance of the game, especially considering that in a mobile application.

I would like to clarify that the type of contact I am wanting to perform is between the player and coins or entities in which it is not necessary to have a body.

# Answer
> 2 votes
I assume both the player and the coins are circles for easy collision detection. So you can use the method shown in this blog https://www.gamedevelopment.blog/collision-detection-circles-rectangles-and-polygons/ which is:

```
public boolean isCirclesColliding(Circle cir1, Circle cir2){
    float sidea = Math.abs(cir1.x - cir2.x);
    float sideb = Math.abs(cir1.y - cir2.y);
    sidea = sidea * sidea;
    sideb = sideb * sideb;
    float distance = (float) Math.sqrt(sidea+sideb);
    if(circle1.radius + circle2.radius < distance){
        return true;
    }
   return false;
}

```

Now, to limit the amount of checks you are doing against player you can reject all coins that are too far from the player since any coin over player.radius + coin.radius cannot be touching.

```
if(coin.radius + player.radius < math.abs(player.x - coin.x)){
    // only coins close enough on x axis enter here
    if(coin.radius + player.radius < math.abs(player.y + coin.y)){
         //only coins close enough on both x axis and y axis enter here
         if(isCirclesColliding(player,coin)){
             // contact is happeneing
         }
    }
}

```

This can be put in your system that loops for all coins

---
Tags: libgdx, collision-detection, entity-system
---


# Question
Title: Using different shaders based on desktop or mobile?
Most of my assets use the Unity standard shader. It looks and runs fine on Desktop, but on mobile the performance isn't good.

I assume the solution is to switch to one of the mobile friendly vertex-lit shaders for mobile. But how can I switch shaders depending on platform? Is there a way that Unity can do this for you, or do I need to manually change them before building? Also, would I be able to just specify the shader, or would I need to create all new materials for all my assets?

I really have no idea how to approach this, and I'd appreciate it if I can be pointed in the right direction.

# Answer
It may lead to longer load times, but you could switch shaders in Awake based on the platform:

```
// Your Assets folder should contain a folder called Resources,
// containing a shader called mobileShader
Shader mobileShader = Resources.Load("mobileShader") as Shader;

// Called when a GameObject with this script is loaded
void Awake()
{
    // Check if we are on mobile
    if (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer)
    {
        // Change just the shader
        GetComponent<Renderer>().material.shader = mobileShader;
    }
}

```
> 2 votes

# Answer
You can also use shader compile directives in custom shaders to skip over expensive sections, resulting in a simpler look, which only triggers when on a mobile device.

https://docs.unity3d.com/Manual/SL-MultipleProgramVariants.html

I've got a shader I wrote which uses that feature that wraps around a visual effect, the effect can then be disabled in the in-game options menu (and being purely visual, although cool, the game play isn't changed).
> 2 votes

---
Tags: unity, c#, shaders, cross-platform, materials
---


# Question
Title: How do you compute the tangent space vectors with normals given in the mesh?
Suppose you are given a mesh with normals for each vertex. These normals might not correspond to the face normals, as the artist could have tweaked them. In this case, how would you go about computing the tangent and binormal vectors for the vertex?

The best algorithm I can think of, and the one that looks to be used by assimp, is to take all the faces in a given smoothing group and compute the tangent and binormal per face. Once that is done, project them into the plane determined by the normal and average over all the faces in the smoothing group.

I am uncertain as to whether this algorithm works exactly as needed. For example, does the projection operator preserve the angle between the tangent and binormal?

Another issue I have is that the assimp implementation of the algorithm does not seem to use the smoothing groups specified in the mesh. They instead seem to calculate the smoothing groups manually using nearby vertices. What is the advantage of doing this?

Finally, is this the ideal algorithm? Some other things I have found (such as this) seem to suggest that it is not, but they do not go into any more details.

**EDIT:**

So I checked out the MikkTSpace algorithm that was suggested in the comments, and while it answers my question of what the industry standard method for generating tangent spaces is, I do not fully understand why the algorithm works.

As described in the paper, the algorithm works by collecting triangles into groups and then averaging the tangent spaces for each individual triangle in the group. I ran into two problems understanding this: first and once again, why discard the smoothing groups specified in the mesh? It seems wasteful to discard information that is already given to you about how the mesh is supposed to appear.

Secondly, how do the groups even work? The paper specifies that two triangles are considered to be in a group if the share two vertices, two texture coordinates, and two normals. The first two requirements make sense to me, but the third does not. Suppose you are approximating a sphere by something like an icosahedron. In this case there will be no vertex normals shared by any two vertices, so each individual triangle is going to have its own tangent space. This seems counterintuitive.

# Answer
> 5 votes
**Summarizing the clarifications above as an answer:**

There are multiple ways to generate tangent spaces for a mesh, and not all of them agree on the result.

This is a common source of rendering errors in games, where the normal map baking tool generated the texture with respect to one tangent space, and the 3D modelling software or game's mesh importer decided on a different tangent space, leading to mismatches and artifacts, as shown in these examples from the Handplane documentation:

So, we need to pick a standard tangent space to use.

A popular choice is "MikkTSpace" a method for generating tangent spaces that Morten S. Mikkelsen developed as part of his master's thesis. He specifically designed the algorithm to be robust for use by multiple tools in an asset pipeline, so they can independently generate the same tangent basis regardless of quirks like choices of vertex welding or the order of the vertices & faces.

Code for the MikkTSpace algorithm is freely available online, and I'm not an expert in all of its workings, so I won't describe a complete implementation here. Instead I'll address the specific questions about it raised above.

**Why do these algorithms disregard smoothing groups?**

"Smoothing groups" don't really exist on GPUs or in most game engines - they're a concept used in 3D modelling tools to make manipulating normals more intuitive.

By the time a mesh is pushed down the graphics pipeline, it's just a raw stream of vertices combining position, texture coordinates, normals, etc.

Wherever two entries in this stream coincide at the same position, but have different normals, you'll get a hard crease or lighting seam along any edges they share (or a point discontinuity like the tip of a cone if they don't share any edges)

Wherever you have an edge where all vertices at the start of the edge agree on their normal, and all vertices at the end of the edge agree on their (possibly different) normal, you'll get a smooth join with no discontinuity.

Smoothing groups exist to tell the 3D package where it should force vertices along a shared edge to share a normal, versus where the normal can be independently chosen for each vertex.

By the time the mesh gets to the tangent space baking step, these smoothing groups have typically already been converted to vertex splits, so the tangent space algorithm doesn't need to be aware of a particular tool's smoothing conventions - it can just work with the literal vertex data.

No artist-authored smoothing information is lost this way, it's just already been translated into the lower level form these algorithms understand.

**Why does the MikkTSpace algorithm group only faces that share two vertices, two texture coordinates, AND *two normals*?**

> "Suppose you are approximating a sphere by something like an icosahedron. In this case there will be no vertex normals shared by any two vertices, so each individual triangle is going to have its own tangent space. This seems counterintuitive."

This looks like a misunderstanding of the algorithm, as though it said:

"Two triangles can be grouped only if the vertices at both ends of the shared edge agree on a *single* shared vertex normal."

But it actually says:

1. two vertices \[(vertex positions)\] are shared.
2. vertex normals at the two vertices are shared.
3. texture coordinates at the two vertices are shared.
4. the triangles must have the same sign of det(T). \[(ie. Either neither, or both, are mirrored in texture space - not one of each)\]

Point 2 means that:

* triangle A and triangle B's vertices at the START of the shared edge must share one vertex normal
* triangle A and triangle B's vertices at the END of the shared edge must share a (possibly distinct) second vertex normal

...for a total of two shared normals along the common edge.

So you can see this is the same condition we described above with regard to smoothing groups. If this condition is not met - the vertices at at least one end of the edge disagree about their normal direction - then we'll have a sharp crease along this edge. Since the normal experiences a sharp discontinuity along this edge, the tangent basis (which includes the normal) will also be discontinuous along this edge.

**Why does the algorithm accumulate magnitudes of vectors?**

Checking through the code, you'll find the magnitudes of the partial derivatives are not used for the "basic" version of the tangent space.

For the more advanced version, here is Mikkelsen's original comment:

```
// This function is used to return tangent space results to the application.
// fvTangent and fvBiTangent are unit length vectors and fMagS and fMagT are their
// true magnitudes which can be used for relief mapping effects.

```

Relief Mapping is an effect where we approximate parallax and self-occlusion of surface structure by ray-marching through a height field texture from our initial surface sample point. We imagine the surface has some depth to it, and that our view ray can continue some distance from where it hit the bounding volume of the polygon geometry, before it actually hits the displaced surface underneath.

To make it work, we need to transform our view vector from eye/world/object space into texture space:

(Diagram of Relief Mapping from GPU Gems)

To do that precisely, we need to know more than just how the texture is oriented with regard to the 3D geometry (what we get from tangent & normal directions), we also need to know how it's scaled. If we ignore this, then a ray entering a compressed part of the texture will behave like it's refracted in water, covering less worldspace distance parallel to the surface for each unit of travel perpendicular, distorting the effect. We can use the magnitude information provided by the algorithm to compensate and ensure our texture space ray matches the direction of our view ray in the world.

There are other effects that might benefit from having this type of scale information about the texture mapping (maybe some forms of tesselation using a control texture?) but if you're just using the tangent space for standard normal mapping and only care about directions, then you can safely ignore the magnitude tracking the MikkTSpace algorithm does and use the basic version instead.

---
Tags: 3d, 3d-meshes, assets, normal-mapping
---


# Question
Title: How do I work out what resolution my backgrounds should be?
I'm working on a game that's 1200 x 800. The pixels per meter ratio is 1:20. When I add my background texture that is 400 x 225. It fits well in the zone however the lines on the image are pixelated. How can I work out what resolution my background should be in order for it to not look pixelated?

Here's what I have so far:

```
@Override
public void show() {
   ...
   b1 = new Texture(Gdx.files.internal("backgrounds/spr_stars01.png"), true);
   b1.setFilter(TextureFilter.Linear, TextureFilter.Linear);
   ...
}

@Override
public void render(float delta) { //(43, 55, 61)
   ...
   Gdx.gl.glClearColor(132/255f, 0/255f, 35/255f, 1f);
   Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
   world.step(TIMESTEP, VELOCITYITERATIONS, POSITIONITERATIONS);
   world.getBodies(bodies);

   camera.position.set(player.getPosition().x, player.getPosition().y, 0);
   camera.update();

   timer += (delta*1.25f);
   batch.setProjectionMatrix(camera.combined);

   batch.begin();
   batch.draw(b1, player.getPosition().x/20, player.getPosition().y/20);
   batch.end();
   ...
}

@Override
public void resize(int width, int height) {
    camera.viewportWidth = 1200 / 20; //60m
    camera.viewportHeight = 800 / 20; //40m
    hud.getViewport().update(width, height);
}

```

The result:

The original background:

**edit:** my windows resolutions is 1200x800

**edit2:** Both answers have helped greatly in understanding background scaling. I have decided to create reusable polygon textures, much smaller than my original background, that I can scale with my box2d world. Thanks for the help!

# Answer
As I understand, your game window has a size of `1280x720` and the texture has `400x225`.

This is how this setup looks like in `Photoshop`:

And this is how the photo behaves after a resize-up:

Keep in mind that it was optimized by the `Photoshop` itself during the resize process (it has more power than `LibGDX` and still looks blurry).

I don't why is the background in your game zoomed that much, but if this is an expected size - your only option is to create it in a higher resolution.

As you applied `TextureFilters.Linear` \- it's already smoothed. You can check this by commenting the `setFilter(TextureFilter.Linear, TextureFilter.Linear);` line.

Also, what happens here is called Aliasing. You can try messing with `AntiAlias` buffers (LibGDX AA question on SO), but it won't help much (and if so, it'll decrease performance dramatically, especially on mobile devices). If your want your image to be in a good quality in-game, it has to match the windows dimensions or be even larger.
> 2 votes

# Answer
Judging by what you are trying to accomplish, *there isn't a size that would work,* as it would require a texture many times the size of your screen resolution.

You have three options in this situation:

1. Vector graphics - which alias exactly to the resolution no matter what size you scale them. Examples being SVG. You would probably need a library *and* a tool that can create vector art for this, such as Adobe Illustrator.
2. Create the background using a flat 3d mesh. This is the quickest and dirtiest method if no vector art library is available. You would use something like Blender to make a mesh that is colored appropriately and can be scaled the same way. I've made a quick mockup for demonstration:

3. The usual way - compose your background using many smaller sprites each placed at various points specified in a map.

Personally, I would recommend option 2 or 3.

2 is good in that it doesn't require anything you have to already have access to - 3d rendering ability and free software. The know-how is another story, but there's plenty of help laying around. However, you're going to have a tougher time generating enough background to make the background interesting this way.

3 is good as you can make a lot of reusable "stamps" that can be recombined in interesting ways so as to not bore the eye.

This is where you'll want to reflect on what the purpose of the background is. Is it there to tell the player where they are in the world, or just give a sense of where they're going, or...?
> 2 votes

---
Tags: libgdx, textures, scale
---