# Question
Title: Why can't cross-platform multiplayer games exist?
At least, why are they so difficult to make? - assuming that's the reason why not even AAA studios accomplish this feat for their games. Especially with modern cross-platform game engines like Unreal and Unity that can build on Xbox, PS4, and PC, why hasn't this been done yet on a large scale?

For example, Diablo III is a game released on a variety of platforms. Despite it being a product of Blizzard, one of the wealthiest video game companies in the world, it does not allow an Xbox player to play with someone using a PC.

# Answer
> 19 votes
It's no real hardware or software limitation. Cross-platform gameplay **is** possible, if implemented. **Final Fantasy XIV - A Realm Reborn** is a perfect example, featuring cross-play between consoles and PC.

If a game is released on multiple consoles and/or as a PC game in parallel, non-cross-platform multiplayer is most likely a design decision either due to contractual reasons or for fairness.

A very recent example for both would be **The Elder Scrolls Online: Tamriel Unlimited**. The game has been released on PC/Mac last year. Both platforms play on the same servers, so are able to play against each other or together.

However, both console versions they're releasing next month (PS4 and Xbox One) will be limited to their own platforms, i.e. PS4 players won't be able to play with non-PS4 players and XBOne players won't be able to play with non-XBOne players (and the same for PC/Mac).

The game is played on a different pace and precision when comparing mouse/keyboard and gamepad controls and since there's PvP involved, this would get PC/Mac players a clear advantage (let's ignore the fact that consoles might support mouse and keyboard, it's not the preferred input schema there).

But even besides that, couldn't PS4 and Xbox One players play with or against each other? Sure they can, but I guess neither Microsoft nor Sony really want this (*Want to play with your friend? Buy him one of our consoles!*).

Similar considerations might have existed for **Diablo III**, although it's no real PvP game (besides duelling).

The differences you mention in number of players etc. are another thing, mostly due to hardware power and framerate issues I guess. These wouldn't prevent cross-platform gameplay though, just prevent console players from entering 64 player servers (for example).

# Answer
> 2 votes
Answer: They don't exist because there are too many marketing, licensing, and other business-related obstacles.

The ports are often developed by contracted studios that are different for each platform, the xbox and ps4 both have payed subscription service for connection, different player account setups, etc and so forth. Who pays for what, and when, and how is it tracked, etc? Just a huge can of worms.

Not to mention that, the console market is very close competition and they prefer to not even indicate that the other console exists, let alone cooperate or accomodate or do anything that might help the enemy or hinder themselves.

For those and other reasons, what is more likely is to see console/pc but not console/console.

The only problem is that in fps games the pc players absolutely dominate the console players, regardless of how skilled, because a mouse is many times faster and more accurate than a thumbstick. In racing or 3rd person games, it's a much more even match.

# Answer
> -2 votes
One of the main reason why Cross-platform is not possible is due to the security requirement of each sides.

Each console is, as we all know, like a computer, but with hard and light restrictions as to the access to the OS. That's why you hear about things like devs console and demo consoles and other "version" of a console. Each has different kind of restrictions.

Where I'm going with this is this: Consoles can act like ports toward their respective online services: PlayStation Network and Xbox Live and Nintendo \**** Online Services (Like Nintendo Switch Online Services or Nintendo Wii Online Services, etc.)

Those systems are the responsibility of their respective "owner" (Microsoft, Sony, Nintendo) and as they allow you to chat with other players, purchase online and do many action, their security are considered paramount. If a system (like a Xbox One) could connect to another system (Like a PS4) through something like a game (which is a software), depending on the level of authorization allowed by the game's software, there's a security risk involved.

Especially with the authentication system of those games. If you allow players from a console to play with another player on another console, both uses different authentication system. Kinda like you got a player who's authentication is handled by PlayStation Network while another player has its authentication handles by Xbox Live. How do you make it so that the PlayStation player can "download" the player's data (icon, name, etc.) from the Xbox player? How do you handle communication between both? How would you handle things like friends/Message?

There are 3 possible solutions:

1) Every console would use 1 single authentication service. That's close to impossible. Sony, Microsoft and Nintendo would never allow such a thing. That's because this would involve, for one of them at least, some kind of cost like a cut from sales (usually 25%-35%) and for the other, that would means a lot of investment (and risks) for better hardware.

2) The game publisher run its own hosting server. This requires a long and painful process of approbation from all concerning parties involved. Basically, this requires that a per-authorized server load players data from both system and only that server can manage the player data from both consoles at once. The PlayStation doesn't access Xbox Live and vise versa. They both access a third party server that load and upload the data.

The game ***Rocket League*** does something similar to that way with PC gamer (Using Steam) and PlayStation 4 gamer (using PlayStation Network). PC gamer only see the name of the players from PSN as that information is public. PC gamer can't see the PSN player's icon as that is restricted. (Instead, PC player only see PSN icon). The server connects the clients, but doesn't do anything like managing the purchases. Instead, it's a Key-Based secured transaction system (similar to Paypal's Key-Link system you use every time your use PayPal) which is managed by PSN and Steam directly which is then managed by the local console. (So a Steam PC can't access the PSN account at all.)

The main issue with this solution, outside of data fetching being quite restricted and complex to implement, is that you got to keep all ports compatible, meaning if you release a patch for PlayStation with new content, that content must be available and ready for PC or any other console. This makes it like you got to make 2 or more build of your game at once, test them, release them, be ready for double the bug/crash report etc.

3)Each consoles run on a separate partition/layer on the server. This is what's usually happens with most console driver MMOs. 1 networks that act as a server for all the consoles and PC, but each access a different part of the system. This system doesn't requires that each port has the same version nor anything. The only thing is that PSN can't join XBox Live and neither can the PCs. Each are "in their own world".

This is why you don't rarely see any interactivity shared between consoles and PC. Too much risks of problems and restrictions. 99% of the cases uses 3). The remaining 1% usually involve a simplistic system like Rocket League where you only load names of the other player's profile and their latest action through a streaming sub-system.

---
Tags: multiplayer, cross-platform, xbox360, pc
---


title: Fastest solution to compute normal

text:
# Question
Title: Fastest solution to compute normal
A physics engine return a deformed mesh (only geometry vertices). I take this mesh to render the geometry (~500000 vertices). What is the fastest solution and the least expensive to compute normal vertices every frame? OpenCL? Geometry Shaders? In a CPU thread? Other?

# Answer
> 3 votes
A lot of this depends if you need interpolated normals over the polygon or can live with a the 'faceted look' of per-triangle normals.

The per-triangle normals are a lot easier to compute: a simple cross prod of the three vertices with one of them being made a local-origin by subtracting it from the other two first.

Smooth per-vertex require finding all the triangles that share a vertex, and averaging their per-triangle normals, by weighting their angle by some factor, typically the angle of the corner made at the vertex for that triangle.

If your mesh can have an arbitrary number of triangles meeting in a corner this can be rather difficult implement on a GPU.

# Answer
> 0 votes
So I coded simple C++ test program that calculates normal for pair of vectors using cross product 500000 times. Source highlights are:

```
struct Vector3
{
  float x, y, z;

  Vector3();
};

const int n = 500000;

Vector3 a[n], b[n], c[n];

void CalculateNormals()
{
  for (int i = 0; i < n; ++i)
  {
    c[i].x = a[i].y * b[i].z - a[i].z * b[i].y;
    c[i].y = a[i].z * b[i].x - a[i].x * b[i].z;
    c[i].z = a[i].x * b[i].y - a[i].y * b[i].x;
  }
}

```

I've executed 1000 passes on random data. And average time of `CalculateNormals()` function to finish is `3.11` ticks. So I think the idea to calculate this stuff on CPU is straithforward and efficient. By the way my CPU is `Intel Core i5-2400 @ 3.10 GHz`.

# Answer
> 0 votes
Try looking at implementing it in either OpenCL or CUDA. A lot of medical applications are going towards that field because of the insane amount of data they have to process per frame.

The problem you have should be easy to parallelize (run on the multiple cores of a videocard). You have a fixed input (three vertices) and a fixed output (one normal). So, a version of the program could be:

* Physics simulation deforms the mesh.
* Upload data to OpenGL using vertex buffers.
* Lock buffers for OpenCL processing.
* OpenCL writes to normal buffer, keeping everything in video memory.
* Unlock buffers for OpenGL usage.
* Rendering using vertex data with normals.

# Answer
> 0 votes
If you're doing this on the CPU with indexed meshes and I'm assuming smooth vertex normals, then the fastest way I've come up with is:

1. Make sure polygon-\>vertex access is cache-friendly. This makes a world of difference if you minimize cache misses here. You can look at Tom Forsythe's Linear-Speed Vertex Cache Optimization as a start.
2. If the mesh is super high res like millions of vertices, it might take too long to do these vertex cache optimizations and their results might not be so great. In that case, split your big mesh into multiple smaller sub-meshes with special handling of the vertices at the boundary of each sub-mesh to produce seamless results. That will also allow you to do these vertex cache optimizations in parallel.
3. Use fast SIMD inverse square root if you're okay with an approximation of the normal like `rsqrtps`.
4. This is a little bit dirty and could lead to noticeable artifacts if you aren't careful but sometimes you can delay the normal computations and do them in parallel/async with deforming objects without the user noticing. This way you might deform the mesh for a few iterations before you update the normals once. Now I'm not sure if this would be acceptable for a game engine. I'm coming at this from the VFX side of the industry when users do things like sculpt deformations on meshes with 10 million polygons (and not necessarily triangles). I've found in those cases at least that you can be sneaky and not update the normals necessarily with every single frame rendered and get away with it, using a separate thread for updating normals which tends to lag a frame or two behind the deformations.

---
Tags: c++, opengl, vertex, normals
---


# Question
Title: How to rotate something around a fixed point WebGL
I have created a simple robot in webgl with cubes and now i want to rotate one "leg" around a point. But the leg is rotating around its origin. I want to rotate it around the point that connects with the body. I dont understand how to do it. How i am supposed to use translations and rotations outside of a push/pop when these translations will change the center of the world for the cubes i want to draw later on?? A little help would be appreciated. Thanks.

# Answer
> 2 votes
One way is using a matrIx stack

https://webglfundamentals.org/webgl/lessons/webgl-2d-matrix-stack.html

Basically you need to translate the object so it's center point is at the origin, rotate, then translate it back

# Answer
> 0 votes
```
push();
rotateY(frameCount*0.01);
translate(-100, 0, 0);
sphere(10);
pop();

```

This is literally your entire code, this is literally ALL you need, that link in the other answer is almost entirely useless. This code will do the job.

---
Tags: webgl
---


# Question
Title: How to make a door stay open if the player is inside the trigger zone?
I've been struggling with this for all day long, I want to make a door to stay open when the player is inside the trigger zone, but I cannot make it happen...

Here is what I did:

* A basic animations and animator (Open, Close, Idle/Default)
* Default transitions between states (with and without "Exit Time")
* A basic script to check if the player is inside the trigger:

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

public class DoorScript : MonoBehaviour
{
    Animator _animator;
    bool doorOpen;

// Use this for initialization
void Start ()
{
    doorOpen = false;
    _animator = GetComponent<Animator>();
}

/* // Update is called once per frame
void Update ()
{

} */

void OnTriggerEnter(Collider other)
{
    if (other.tag == "Player")
    {
        doorOpen = true;
        DoorController("isOpen");
    }
}

void OnTriggerExit(Collider other)
{
    if (other.tag == "Player")
    {
        doorOpen = false;
        DoorController("isClosed");
    }
}

void DoorController(string trigger)
{
    _animator.SetTrigger(trigger);
}
}

```

And my result is the same, the animation of the door repeats itself even when the player is in the trigger zone, I tumbled upon some other resources (here... here... here... here I tried to copy what this person did, but is the same... here... and here) about doors and triggers, and I still don't know how I am wrong or what am I doing wrong, I tried everything in those links

The door goes through all animations regardless the script, and the parameters, when I move my player inside the trigger zone loops between open and close animations no matter what

Could some one help me with this?

Thanks in advance

EDIT:

Here are some screenshots of my animator and updated code, for this update I followed this tutorial, just a little difference, I'm using a FPS Controller from the Unity standard assets

Updated code:

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

public class DoorScript : MonoBehaviour
{
    Animator _animator;
    bool doorOpen;

    // Use this for initialization
    void Start ()
    {
        doorOpen = false;
        _animator = GetComponent<Animator>();
    }

    /* // Update is called once per frame
    void Update ()
    {

    } */

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "Player")
        {
            doorOpen = true;
            DoorController("isOpen");
        }
    }

    void OnTriggerExit(Collider other)
    {
         //These lines were modified
        if (doorOpen)
        {
            doorOpen = false;
            DoorController("isClosed");
        }
    }

    void DoorController(string trigger)
    {
        _animator.SetTrigger(trigger);
    }
}

```

# Answer
Seems that other objects can trigger the door closing if they exit the trigger zone while the player is in it. Try using `if (other.gameObject.tag == "Player")` with the onTriggerExit(), too.
> 1 votes

# Answer
you have to make the trigger to fill the who room. **onTriggerEnter()** you have to play door-open animation and **onTriggerExit()** you have to play door-close animation. there are a lot of approaches to do this. I just told one of them.

sorry for careless answer. I edit. repeating animation is because loop time of animation is checked and you have to uncheck it. other reason can be that your trigger is colliding with other objects. you can simple ignore them by making different layers for them.
> 0 votes

# Answer
Solved! I'm so stupid! In the end, the trigger zone was very small and my player collided everytime and that's why the door opened and closed like crazy... I'm really thankful for all your answers and comments
> 0 votes

---
Tags: unity, c#, animation-states
---


# Question
Title: How to maintain artistic consistency when working with multiple artists?
I'm making a game that requires a volume of artistic content which is not practical to be created by a single person, so I've enlisted the help of additional artists.

The problem is, each artist has their own style, and mixing the content produced by all artists results in a very inconsistent experience. This is true for graphical as well as musical content.

I've tried having each artist work on completely different parts of the content, such as having a background artist, a sprite artist and a graphic designer, but this clearly doesn't scale as the art volume increases or when circumstances require me to replace an artist, and is not trivial with content such as music.

How can I work with an arbitrary amount of artists, yet maintain artistic consistency across the entire game?

**Addendum**: The current answers mention the creation of an art spec, but even though useful, and probably even necessary, it is simply not enough.

In programming terms, "make an art spec" is similar to "make a tech spec", which is definitely a good thing, but a spec by itself does nothing to improve overall code quality.

Same goes for having an art director. In programming terms, "get a lead programmer" is not a very useful answer for "how do I improve code quality in my team?", even though it is a very good thing.

I'm looking for specific detailed answers on how to solve specific common problems in the field of artistic consistency. For example:

* When doing lineart, draw them with vector tools instead of freehand, with predetermined brush parameters so everybody gets their lines similar.
* Some people use the gradation tool, while others use blurring tools, and results are very different, so make sure everybody uses the same technique for gradations.
* For music, once the percussion and chord progression is set, it doesn't really matter who finishes the song, so make sure the percussion and chord progression for all the music is written by the same person.

I just made these up, so I don't know if they would work. I'm asking this question so people who *do* know what works can give me specific hints on how to improve artistic consistency.

**In my particular case**, I am not having a problem *yet*, but I need a relatively large volume of music for the project I'm currently planning. I have two musicians who want to help, but their styles (and skill level) are quite different. If I let them both make the music the way they want, I will have a pretty inconsistent result, and I want to avoid that *before* they start writing the music.

Also, I'll be needing lots of character drawings, and I have two artists who want to help (plus me), but our drawing styles are very different. In particular, this is how each artist draws the same character:

Notice how even though we're all drawing the same character, with the same palette, the results are wildly different, and telling everybody "you all have to draw in the style of artist B" is most likely not going to be very effective.

# Answer
You need an art lead and proper art style documentation. There are things like palettes to determine, plus various bits of example concepts, a lot of art terminology that clearly defines things to artists in ways that tech terminology clears things up for developers. A good art lead can define all these and *make* your consistent art style, and properly communicate all this to artists.

The art lead can also be your "human" element who simply rejects art that fails to meet criteria and properly explain what's wrong and how to fix it, rather than just saying "no good" or "tighten up the graphics on level 3." Ideally this wouldn't happen often, but humans are humans, and at the end of the day you need someone to wrangle other people and push things into the right shape rather than having it all magically fall into place.

As with all things in large teams, the trick is finding experienced, charismatic people to lead. There's little that a programmer or producer can do to solve any art problems besides talk to the art lead about it.

I myself am not an artist and can't give any advice on how an art lead does his or her job well. I just know that as advice to another non-artist trying to produce a game, the answer is to delegate to a good art lead.
> 38 votes

# Answer
The question "*How can I work with an arbitrary amount of artists, yet maintain artistic consistency across the entire game?*" cannot be solved with a one-size-fits-all answer - it is dependant on your specific project. If you edit your question and provide more details on your specific problem, then perhaps we can help with your problem of scale and arbitration.

However your question is a very good one - but it sounds like the tail is wagging the dog. **You should not be managing your project around the various artistic techniques your team has - they should be managing their own techniques to fit in with your project.** If they are not, then honestly I do question the value of your art team. If you find yourself with an artistic team who cannot work together to achieve the same styles using the same techniques - then you have a problem with your art team. This reinforces the need to check your artists techniques and skills before you take them on.

Although I do not have experience as an Art Director myself, I do have experience working in the games industry and can tell you that the art teams I have worked with have been very well structured. In terms of art hierachy, it started with junior artists who were in charge of the more minor, less noticeable art tasks. The senior artists would then be responsible for centre-piece props, weapons, characters etc (and usually only focus on their specialized field, for example a character modeller). Above them, we had leads for each field; eg a lead environment artist, lead character artist etc etc - then the buck pretty much stopped at the art director. That is an example of the art structure I have had experience with.

Anyway, I believe these five points will help you find your answer:

**1) Concept Art -** Having a team of graphic artists without any concept art on which to base their work is a recipe for disaster. Each artist will have their own impression of how the game should be presented and the end result will be an awful mess. It is absolutely vital to have a concept art team (however small it may be), which will help to maintain consistency across your project.

**2) Internal documentation -** something that artists can refer to for questions such as "*What kind of locomotion engines are used by the vehicles in this game universe?*" - its no use having one artist make a vehicle that is a combustion engine and another artist make a vehicle which uses some sort of higher-tech gizmo. Documentation is vital for consistency. Also, on this topic - try not to have artists overlapping different areas of art. Eg, if you are the art lead - try and keep individual artists stuck to one aspect of the art without bouncing them around too much. The few people working on a specific area of art, the less inconsistency there will be.

**3) Art Director -** Someone who makes the final decisions on art related topics and can make sure everything is kept coherent and consistent. As artists can clash in their ideals, styles and techniques - it is of utmost importance to have somewhere there to make the final call.

**4) 'Palettes' -** A tiny level, scene, or just a collection of props that serve as an 'example' to your art team. This should ideally be built by one of the art leads, or possibly even the art director (depending on how hands-on he/she is). It should be accessible to your art team whenever they want to view it, and should serve as a standard on which to base all their artistic decisions on. If an artist needs to be steered towards a particular style or technique, he should be able to refer to this palette and look at how he *should* be doing things.

**5) Common inspiration -** What is the inspiration of your project? Don't be afraid to share it with your entire team. It doesn't matter what that inspiration is - tell your team to research it. Is *Star Wars* the inspiration for the game? Get your team to watch the star wars saga at home (oh what a chore!). Your team will be more in-tune with the overall intended 'feel' of the game and as such - technique and style will be more likely to be consistent.

(Answer edited based on OP feedback)

Further reading: http://www.gamecareerguide.com/features/501/an\_artist\_grown\_reflections\_on\_.php http://www.imaginefx.com/02287754330842797110/the-20-rules-of-game-concept-art.html
> 15 votes

# Answer
I see three methods to approach this.

**Method A** is to do it like most cartoon/anime studios are doing it. They have one **lead artist** who designs the characters. The job of all other "artists" is to suppress any own creative urges and copy his technique and design as accurately as possible, including the number of spikes of the hair. This is a very boring and repetitive job without much creative fulfillment. That's why this job is often outsourced to China or Korea. The advantage with this way of working is that it leads to a very consistent style and a high efficiency, but unfortunately it isn't enjoyable for anyone except the lead artist.

**Method B**: Topic segregation. **Make each artist responsible for something entirely different**. When one artist is responsible for the design of the backgrounds, one for inanimate objects, one for special effects, one for animals and one for human characters (which could be further divided into male/female, old/young or main/background), it isn't that apparent when they have a different style, because you will rarely see a similar motive interpreted by two different artists. This way of working gives everyone a greater degree of creative influence and freedom, so it's much more enjoyable to work that way. But it doesn't scale well when you add or remove people from the team and there is still a potential for style and technique clash.

**Method C**: Pipeline segregation. **Make each artist responsible for a different stage of the art pipeline**. One artist scetches, one artist inks, one artist colors, one artist shades, one artist adds after effects. That way everyone can live out their style and the end-results are still a consistent collective work of everyone.
> 3 votes

# Answer
As Sean said earlier you could potentially do with an art lead as well as documentation to do with the style and direction in which you want the art to be produced.

Another possible way of doing it (which I have used in the past) is to layout the general style in which you want the art to look like and then get the artists to work on very specific things which should not overlap. For example in the past I had Artist #1 working on terrain and building art whilst I had Artist #2 working on Guns and Characters, we also had a third artist that worked on different things that fell outside what the were assigned to. This approach we found during development to be the best way as the document gave the artists the direction and then them having their own specific things to do gave the final product we finished the have a consistent style.

Hope this is of some help
> 2 votes

# Answer
If you're talking about small indie productions and maybe not the most formalized hierarchical structure, one possibility is just *significantly* constrain the design.

I'm reminded of 4-color CGA graphics in the late 80s. In spite of the graphics being drawn by so many different artists with different styles, ranging from pro to very amateur, it still looked so consistent. My memories of those games are one giant blur of cyan and magenta, like so:

... and so:

And there was a beauty there to me that came from the artistic consistency that inadvertently came from the severe hardware limitations. Similar type of thing with the music from hardware like the Commodore 64 and Nintendo. In spite of many different musicians with different musical sensibilities, there was a uniformity to it all: beeps and blips on limited palettes and purple girls in cyan bikinis.

That's not to suggest that you go all the way to limiting yourselves to using 4 color palettes and chiptune music, but it shows how such heavy restrictions on design freedom lead to something inadvertently oozing with stylistic consistency even among people who didn't coordinate together whatsoever.

So that's one economical strategy if you can't get the tightest coordination: to seek out those heavy constraints. They could be whatever. For example, if you draw all your artwork using predominantly straight lines instead of curves, that becomes a unifying design language that ties all visual elements together. Pen and ink artwork tends to look more similar between artists than graphite or charcoal, e.g., since the former lacks the ability to create subtle gradations of value. Low polygon artwork of the early 3D era looked a whole lot more similar to each other than today due to the extreme restrictions on polygon counts, lighting, and textural detail. Low-res pixel graphics look a lot more similar to each other than ultra-high res graphics.

This is a heavy-handed way to achieve a uniform design language but it's a surefire way to get some if you're willing to accept some heavy constraints on design freedom. And I think it's often a wortwhile exchange in an indie context since what makes indie games look polished or not often has a lot more to do with stylistic consistency than anything else. A game using super retro-style blocky pixel graphics or something resembling minecraft can look a whole lot more polished than something using ultra-high res detailed graphics if the former looks consistent and the other really looks like it was drawn by 10 different people with no consistent design language whatsoever.

And the more heavily you impose restrictions, the more consistency you'll inevitably get. Take writing music using a 5-note scale, for example, like Japanese (in sen). Just about everything starts to sound the same at that point, like this: https://www.youtube.com/watch?v=7pYYpOFPy5o. You almost can't sound too original even if you tried with such a restrictive scale. Just about everything made with that scale will tend to sound rather familiar.
> 2 votes

# Answer
I know this is an old question, but I think you have to look at the issue from a producer's standpoint, not as a rank-and-file member of the team. Just like in music or film/TV production, the creative whims of members eventually have to be subordinated to the need to produce a finished work.

Team members can decide on the overall direction together, especially in a small team. But finding a way to contribute your artistic strengths **within the established framework** is an essential skill needed to transition from "art for yourself" to "art for the team/project".

Studio musicians, TV episode writers & directors, animators, illustrators, clothing designers - plenty of people earn their living doing art according to spec. Not every artist (or programmer) has the skill and temperament to work this way, and that's cool, but the mature approach is not to hold back (or sabotage) the project because you don't have what it takes.
> 0 votes

---
Tags: art, music, project-management, teamwork
---


# Question
Title: Fading in textures at a constant rate over a controlled duration
I'm trying to fade textures onto the screen using SDL2.

I've tried some different methods I've looked up, but I always encounter the same problem. It seems that the fading takes longer and longer as Alpha gets higher and higher, meaning that the very end of the fade takes the longest amount of time, and thus the fade takes an unreasonably long amount of time. I want the image to fade in at the same rate, and not dramatically slow down when the image gets more and more opaque.

The code that was causing the issue described above has been deleted, and I'm working on an entirely new system to hopefully avoid the problem. However, it doesn't work at all. Any advice would be awesome!

My NEW code:

```
for (float alpha = 0; alpha <= SDL_ALPHA_OPAQUE; alpha += fadeSpeed * elapsedTime) {
        if (SDL_SetTextureAlphaMod(spriteTex, alpha) == -1) cout << "ERROR" << endl;
        SDL_RenderCopy(renderer, spriteTex, NULL, &destRect);
        math::present();
        cout << "ALPHA: " << alpha << endl;
    }

```

# Answer
@Jay was absolutely right. I am going to make a separate fade function, which takes a background and image parameter.

This function will:

1) Draw background

2) Draw sprite with alpha starting at zero

3) Increase alpha

4) Loop until alpha reaches SDL\_ALPHA\_OPAQUE (255)
> 0 votes

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


title: How to properly manage memory in SDL2?

text:
# Question
Title: How to properly manage memory in SDL2?
I have yet another question regarding SDL2.

I have some `drawSprite` & `drawBackround` & `drawText` functions, all draw to the screen. They do this by creating a new surface, turning it into a new texture, rendering the texture, then destroying/freeing everything.

This worked fine until I wanted to put it in a very fast loop. There was a slight delay (or something) which caused images on the screen to flicker. (It would draw a background, draw sprites, draw text, then loop. So this caused the sprites to flicker.)

I looked up the issue, and found that you shouldn't create and destroy a texture every single frame, AKA allocate and deallocate memory every single frame. So, I created some a global texture and surface variables, with the intent to re-assign these variables every time I called any of the drawing functions, and then destroy them when the program closed. (Reduce, Reuse, Recycle!)

This did not work. My memory required by my program ballooned upward into the gigabytes, which made it totally unresponsive. Through some trial and error, I found that I STILL had to run DestroyTexture and FreeSurface functions at the end of each drawing function. I don't understand why this is, since I'm reusing the variables.

Anyways, once I added those back in I've found that my program is working but is MUCH SLOWER in rendering than before!!! Why is this??? What did I do wrong? (again)

# Answer
> 2 votes
Your `drawSprite` and `drawBackground` functions definitely shouldn't be allocating any memory. What are you doing inside them that requires you to allocate memory?

Anyways, I'll start by explaining how manual memory management works. The functionality behind `SDL_CreateTexture` & `SDL_DestroyTexture` is very similar to how `new` and `delete` work in C++.

Let's do an example:

```
SDL_Texture* texture = SDL_CreateTexture(...);

```

Here we create a texture. One texture exists in our program.

```
SDL_DestroyTexture(texture);

```

Here we destroy the created texture. No textures exist anymore.
Now let's change things up a little:

```
texture = SDL_CreateTexture(...);
texture = SDL_CreateTexture(...);

```

Here we create two textures, so two textures exist in total. But now, if we call `SDL_DestroyTexture`, we will only delete the latter created texture, since that's what `texture` points to! There's also no way to access the result of the first `SDL_CreateTexture` call, so we have a memory leak. A general rule is that there has to be a matching `SDL_DestroyTexture` call for each `SDL_CreateTexture`.

Now, text rendering is a little more tricky. Textures required for text rendering are something that change relatively often, and do indeed need to be created as they are rendered. However, there's no need to do this every frame, since it's not likely that you're rendering text for just a single frame.

I personally use an LRU cache for text rendering in SDL. Essentially, in your text rendering function, you check if there exists an item with the same color, text and size in the cache, and if it does, you just fetch the cache item, and blit the texture inside it to the screen. If there isn't a cache item for the text, you create one by using the correct `TTF_*` calls. That way if you render the same text next frame, there already exists a texture to be used for the rendering. We use an LRU cache with a fixed size so that we don't end up leaking memory. I think I keep 200 cache items around at once in my game.

As a last note, globals are definitely not the way to go. I'm unsure about why you are allocating stuff inside the very basic sprite and background rendering functions, since you should probably just preload the textures you need to the objects that use them at start up.

```
struct Sprite
{
    float X, Y;
    SDL_Texture* texture;

    ~Sprite() { SDL_DestroyTexture(texture); }
};

Sprite player { 0.0f, 0.0f, SDL_CreateTexture(...) };

while (runGame)
{
    handleEvents();
    updateStuff();

    render(player);
}

```

Essentially something like this for sprites.

---
Tags: c++, sdl, sdl2, memory
---


# Question
Title: Random tile-based floor plan generation with enclosed rooms
I've been working on a project for a while which takes a grid of n\*n tiles (starting at n=16 and with n increasing by 4 every so often for new floors), and fills it with rooms of random rectangular sizes, and have been having issues creating an **efficient** algorithm to do so that fits my requirements:

1. The outside ring (where x = 1 or n | y = 1 or n) must be corridor tiles (obviously easy)
2. All rooms must be entirely surrounded by corridor tiles
3. In no place may there be a 2x2 grid of corridor tiles (so corridors are all 1 tile thick)
4. There are certain rooms of specific sizes that must be present, and then there are other types of rooms which just fill in the remaining space afterward.
5. Do not have any corridors that go all the way through the floor.
6. (Preferably) Room min side length = 2 (relatively easy to program in my code, perhaps not in one of 'your' suggestions)

My algorithm works fine, however at n=12 it takes ~2s to compute on my 4790k, and grows ridiculously exponentially from there: taking 6s for n=14, 29s for n=16, etc... Because there are two particular shapes whose creation must be avoided, as once created they make it impossible to fill up the grid entirely, and so my logic must make sure that doesn't happen, which leads to the performance issues.

My code is far too long to post here, but essentially what it does is: Go through each 'open tile' (tiles that are not in rooms nor that are a corridor), find the maximum size it can be, then `for loop` through that size's x and y, see if a room at that x and y would create any of the aforementioned 'illegal' shapes, and if not, add this open tile and this open tile's size to an array of possible sizes and size positions. I then choose a random size (more or less) from the list, and then create a room there.

Here is an example picture (though some seeds are better than this one) of what my algorithm results in:

Looking all over the internet I haven't been able to find an algorithm that fits my needs - mainly in the 'no corridors going through entire grid' issue. (This issue is present in the picture I attached due to the smallness of n=12, the larger the grid, the less likely this occurs with my code - the issue is there are some algorithms, like what I am calling the 'recursive' method - ~halving all sectors that are larger than minimum size until done, which will always have at least one, no matter how large, ie...)

(n=64 with recursive method, minSize = 2, maxSize = 4)

# Answer
I think the best approach to solving this problem is using a recursive method. Starting large and splitting into smaller chunks is going to guarantee that you have all your space filled with rooms (no 2x2 corridors). Also, if you have a problem segment, you can just regenerate that small part of the map.

If you only use bisection of the rectangles you will obviously get corridors that run through the map. You should try to find another way to recursively split the rectangles.

For example, splitting each rectangle into 5 might work better. You could apply your existing algorithm or another recursive algorithm to fit rooms into each larger rectangle.

This approach avoids problems but doesn't guarantee a solution. However, if a corridor is found that is too long, it can be fixed by reshaping just the rectangles that it passes through.
> 1 votes

---
Tags: mathematics, tiles, random
---


title: Unity Blurry on new Windows 4k Computer

text:
# Question
Title: Unity Blurry on new Windows 4k Computer
I just got a Razer 14 Inch 4k with a GTX 1060 and am having some blurry rendering in unity. Also the cursor is tiny... Here is a screen shot:

As you can see, the rendering is really blurry. I came from a mac and did not expect unity to look worse after switching to a computer with a great screen res and graphics card...

Please help!

EDIT:

I am still getting jagged shadows but now I seem to be able to fix it with changing shadow distance in Quality Project Settings:

But then the shadow disappears really quick if i have low shadow distance...

# Answer
The Unity Editor doesn't work with DPI scaling on Windows yet, so on a high DPI display it's upscaled. You can disable that in Windows (using the Properties screen for the application) but that will almost certainly make the UI unusably tiny.

Unfortunately there is no way around this except to wait for Unity to add support in a later version.

Note that this only affects the Editor, and if you build your project and run it on the same machine, it shouldn't appear upscaled.
> 1 votes

---
Tags: unity, resolution
---


# Question
Title: What are width and height supposed to be in Nez TiledTileLayer?
The constructor of TiledTileLayer.cs takes 4 simply-named arguments. I'm assuming `name` is the layer's name but I can't figure out what `width` and `height` are supposed to represent.

```
public TiledTileLayer( TiledMap map, string name, int width, int height ) {}

```

Is it the width of the map, the width of the tile, the number of tiles? Should I hardcode it or get it from another object?

Thanks

# Answer
So apparently, if anyone else is wondering, according the `populateTilePositions()` method, `width` and `height` represent the number of tile (horizontally and vertically) and not the width and height in pixels.

```
TiledTile[] populateTilePositions()
{
    for( var y = 0; y < height; y++ )
    {
        for( var x = 0; x < width; x++ )
        {
            if( tiles[x + y * width] != null )
            {
                tiles[x + y * width].x = x;
                tiles[x + y * width].y = y;
            }
        }
    }

    return tiles;
}

```

The tiles positions are therefore `0,0`, `1,0`, `2,0`, ..., `0,1`, `1,1` etc. until the last one which will be `x-1,y-1`.

This also means that you can simply pass the values from the map object passed as first parameter like so:

```
var tiledMap = content.Load<TiledMap>("mytilemap");
var backgroundLayer = new TiledTileLayer(tiledMap, "layername", tiledMap.width, tiledMap.height);

```

I guess my confusion was due to the fact that those could have been the default values and where not. Maybe something to improve in the future.
> 1 votes

---
Tags: monogame
---


# Question
Title: Managing Character Bones in Unity 3D at runtime
I'm trying to do the following:

1. Have a **rotation only** (no transforms) with **x,y,z**.
2. Each **rotation axis** above respectfully having a **minimal** and **maximum** **rotation angle** with a **current angle**.
3. This will be for each **bone** of said character's skeleton, note the weights will be applied as per usual when doing animations, however there will be no animation data.

bones to rotation info, apply changes, info back to bones, apply changes, info back to bones...

**Q: SetBones And GetBones, how would I get and set the bone data?**

```
//imports...

public class BoneControllerClass : MonoBehaviour {
    //used to modify the bone data struct for each bone (ediable via Unity Editor)
    public BoneConstraintData[] BoneData;

    //gets refs to bone data from character
    public Bones[] GetBones(){ /*..Help..Here..*/ }
    public BoneConstraintData[] SetBoneConstraints(BoneConstraintData[] _BoneData) { /*..CODE..HERE..*/}
    public void SetBones(BoneConstraintData[] _BoneData){ /*..Help..Here..*/ }

    public void Start(){
        // generate bone data with zeros
        BoneData = GetBones();
        // set bone data constraints
        BoneData = SetBoneConstraints(BoneData);
    }

    public void Update(){
        // do something for smooth clamping, optionally this could be applied above as with Delta Time...
        // CODE EXAMPLE HERE, optionally another function can be added...
        BoneData[0].currentXAngle = 12.0f * Time.DeltaTime; //or BoneDataNew[0].currentXAngle = 12.0f;
        // END CODE EXAMPLE HERE

        // applies new bone rotation information, (note each bone carries the bone information of rotation like in IK Bone Logic...)
        SetBones(BoneData);
    }
}

//holds Min, Max, Current Angles And Bone Ref.
public class BoneConstraintData{
    string bone_name;
    float minXAngle, maxXAngle, currentXAngle;
    float minYAngle, maxYAngle, currentYAngle;
    float minZAngle, maxZAngle, currentZAngle;
}

```

I'm using version 5.x.x of Unity 3D.

# Answer
> 0 votes
I'm not sure what exact setup do you have on your character but the last time I've worked with bones in Unity they were just a transforms in `GameObject` hierarchy.

I've had some `GameObject` representing a character and one of their children was `"ROOT"` or `"HIPS"` and it had children for the rest of the bones.

I couldn't find an example for entire character but here you have some pictures with bone hierarchy:

https://forum.unity.com/threads/bones-appear-in-avatar-not-in-inspector.374953/

Look at your character and find a name of main bone `GO`, at the `Start` or `Awake` you can find this object by name and then you can iterate over its children to get/set bone transforms.

**One other idea to consider:**

If you change the string in your `BoneConstraintData` to `GameObject` you could store bone reference in your class instead of a name. Then you could iterate over bones only once, on read and when you compute your final data you can do something like this:

```
for( Data data in dataArray )
    data.bone.setSomething( data.something );

```

This should be faster than iterating over bones again.

---
Tags: unity, c#, bones
---


# Question
Title: Opengl Model Render symmetr issue in c++
I'm building an OpenGL program that imports and render models wich work quite well. but recently I've been facing a problem with a model(Just one model) that works fine in everything else but my project and I would like to fix it since it can get worse in the future.

Here is the rendered model:

As you can see, one side of the body and leg don't get the UVs ok (it happens with diffuse, ambient, specular, emissive ... etc maps so i guess it's the UVs)

So I made a change in the texture to See if the problem was with the program just rendering the wrong side... So I changed it to a shitty Photoshop draw:

And with that I saw two things.

* First one is that it's trying to render the right part of the texture for everything(Which doesn't match the texture at all!!!!)
* Second thing I noticed is that instead of rendering it with points, it do with lines.. So my final guess is that it just select some random point everytime and use it.

Here you can see the result my yourselves:

Need to say that I use OpenGL 4 and those libs (Glew, SDL2, Glm, Soil2, Assymp)

Here is the code where it load the model (I skip the texture part because I thing that it's not really important here)

PD: Don't pay attention to the part where it store the texture in "usedTextures", it's just to prevent from having copies of the same thing that I implemented recently

```
Mesh Model::processMesh(aiMesh* mesh, const aiScene* scene)
{
    //Allocate memory for each vertex, normal map and texture coordinate
    Vertex vertex;
    vector<GLuint> indices;
    if (mesh->HasPositions())
    {
        vertex.vertices = new glm::vec3[mesh->mNumVertices]();
        vertex.normal = new glm::vec3[mesh->mNumVertices]();
        vertex.texCoords = new glm::vec2[mesh->mNumVertices]();
    }

    //Process allocated memory
    for (GLuint i = 0; i < mesh->mNumVertices; i++)
    {
        //Positions
        if (mesh->HasPositions())
            vertex.vertices[i] = glm::vec3(mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z);
        //Normals
        if (mesh->HasNormals())
            vertex.normal[i] = glm::vec3(mesh->mNormals[i].x, mesh->mNormals[i].y, mesh->mNormals[i].z);
        // Texture Coordinates
        if (mesh->HasTextureCoords(0))
            vertex.texCoords[i] = glm::vec2(mesh->mTextureCoords[0][i].x, mesh->mTextureCoords[0][i].y);
        else
            vertex.texCoords[i] = glm::vec2(0.0f, 0.0f);

    }

    vector<Texture> textures;
    if (mesh->mMaterialIndex) {
        aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex];
        for (int i = 1; i < aiTextureType_UNKNOWN; i++)
        {
            Texture texture = processTexture(material, (aiTextureType)i);
            if (texture.GetLocation() != "")
                textures.push_back(texture);
        }
    }

    return Mesh(vertex, textures, mesh->mNumVertices);
}

Texture Model::processTexture(aiMaterial *mat, aiTextureType type)
{
    //Act like there's only one texture by type of map
    aiString fname;
    mat->GetTexture(type, 0, &fname);
    std::string dir = directory + "\\" + fname.C_Str();

    Texture texture;
    if (mat->GetTextureCount(type) > 0)
    {
        GLuint id;
        if (!isTexLoaded(dir, &id))
        {
            texture = Texture(dir, type);
            usedTextures.push_back(&texture);
        }
        else {
            texture = Texture(id, type);
        }
        return texture;
    }
    return texture;
}

```

Here is the Mesh class wich just draw everything (Again, I skipped the Texture part so please tell me if you find it important to add)

```
struct Vertex
{
    glm::vec3 *vertices, *normal;
    glm::vec2 *texCoords;
};
class Mesh
{
public:
    // Position
    Vertex vertex;
    vector<Texture> textures;
    GLuint indices;

    /*  Functions  */
    // Constructor
    Mesh(){}
    Mesh(Vertex vertex, vector<Texture> textures, unsigned int indices)
    {
        this->vertex = vertex;
        this->textures = textures;
        this->indices = indices;

        // Now that we have all the required data, set the vertex buffers and its attribute pointers.
        this->setupMesh();
    }

    // Render the mesh
    void Draw()
    {
        for (unsigned int i = 0; i < textures.size(); i++)
            textures[i].Set();
        glBindVertexArray(VAO);
        glDrawArrays(GL_TRIANGLES, 0, indices);
    }

private:
    /*  Render data  */
    GLuint VAO, VBO, EBO, TEB;

    /*  Functions    */
    // Initializes all the buffer objects/arrays
    void setupMesh()
    {

        glGenVertexArrays(1, &VAO);
        glBindVertexArray(VAO);

        /* copy mesh data into VBOs */
        glGenBuffers(1, &VBO);
        glBindBuffer(GL_ARRAY_BUFFER, VBO);
        glBufferData(GL_ARRAY_BUFFER, 3 * indices * sizeof(GLfloat), vertex.vertices,
            GL_STATIC_DRAW);
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
        glEnableVertexAttribArray(0);
        delete[]vertex.vertices;

        //GLuint vbo;
        glGenBuffers(1, &EBO);
        glBindBuffer(GL_ARRAY_BUFFER, EBO);
        glBufferData(GL_ARRAY_BUFFER, 3 * indices * sizeof(GLfloat), vertex.normal,
            GL_STATIC_DRAW);
        glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, NULL);
        glEnableVertexAttribArray(1);
        delete[]vertex.normal;

        //GLuint vbo;
        glGenBuffers(1, &TEB);
        glBindBuffer(GL_ARRAY_BUFFER, TEB);
        glBufferData(GL_ARRAY_BUFFER, 2 * indices * sizeof(GLfloat), vertex.texCoords,
            GL_STATIC_DRAW);
        glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, NULL);
        glEnableVertexAttribArray(2);
        delete[]vertex.texCoords;

    }
};

```

Don't know if it has been posted before, I've been doing a research for every "texture issue" page that i found but nothing like that.

Any idea of where the problem could be or what can be producing it?

Thanks!

# Answer
This has been answered by @DMGregory, I'm just posting it.

My problem was that this specific mesh had some UV points outside the range of the texture(the other part) and whenever OpenGL tried to render it, It just applied the property that I set in the sampling wrap(GL\_CLAMP\_TO\_EDGE), Which was taking the outside points back to the edge of the texture.

I changed it to repeat the texture instead of just taking the points to the edge and it fixed the problem.

Here is the code:

```
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

```
> 2 votes

---
Tags: opengl, c++, textures, rendering
---


# Question
Title: UnassignedReferenceException : The variable player of FollowPlayer has not being assigned
My current task is to make the camera follow the moving cube in a stable way where the camera won't get locked in the center of the object so it won't get dizzy once the cube starts to collide or fall down.

I have done the parenting right, I have named the cube as the player and then selected it as the Transform reference in the new component that I have created for the camera to follow.

But it just says:

> UnassignedReferenceException : The variable player of FollowPlayer has not being assigned.

and I am unable to get the right results. What should I do ?

Here is the C# script that I wrote:

```
using UnityEngine;

public class FollowPlayer : MonoBehaviour {
    public Transform player;
    public Vector3 offset;

    void Update() {
        transform.position = player.position + offset;
    }
}

```

My scene setup looks like this:

So I have un-parented the main camera from the player and it works perfectly fine but I still get the error, Have any ideas why?

# Answer
> 1 votes
Check to see if you have a stray second instance of your `FollowPlayer` script somewhere in your scene, with its `player` variable unset.

You can have every instance print its name to the debug console in `Start()` to help track it down.

If the camera's reference to the `Player` transform was deleted or cleared, you'd get a MissingReferenceException or NullReferenceException instead, so this is almost certainly a scene & inspector setup issue.

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


# Question
Title: How does the logic "column < row + 1" work? The output gives half an asterisk pyramid
This code creates half a pyramid on the compiler, but I'm not sure how that works. The only thing I understand is that the `column < row + 1` line is what influences the code, because when I change it to `column < 10`, then it creates a square when run.

```
for(int row = 0; row < 10; row++) {
    for(int column = 0; column < row + 1; column++) {
        Console.Write("*");
    }
    Console.WriteLine();
}

//The output gives half the asterisk pyramid.
//I don't get the logic of how "row + 1" works.
//How does this influence the asterisk to not be entered in the particular places?

```

# Answer
As Quentin says, this is pretty clear to see for yourself if you walk through what the program is doing step by step, following the rules of a `for` loop.

Let's draw row 0

column = 0, that's less than 0+1, so we draw an *
Now column = 1, that's not less than 0+1, so we exit the inner loop
We drop down a line.

The outer loop repeats: now we're drawing row 1

column = 0, that's less than 1+1, so we draw an *
Now column = 1, that's less than 1+1, so we draw an *
Now column = 2, that's not less than 1+1, so we exit the inner loop
We drop down a line.

The outer loop repeats: now we're drawing row 2

column = 0, that's less than 2+1, so we draw an *
Now column = 1, that's less than 2+1, so we draw an *
Now column = 2, that's less than 2+1, so we draw an *
Now column = 3, that's not less than 2+1, so we exit the inner loop
We drop down a line.

What do we have so far?

```
*
**
***

```
> 2 votes

---
Tags: c#
---


title: Procedural planet to sphere texture

text:
# Question
Title: Procedural planet to sphere texture
I'm making a 4x space game. I have a procedurally generated galaxy with planets in 3D space. The view is above the planet plane at -45 dec y-up i.e 45 deg isometric. I procedurally generate the planet surfaces on a hex grid which can be viewed 2D / 2.5D when clicking on the planets, ala GalCiv etc by placing meshes for mountains, seas, forest and so on on the hex grid.

For realism, I'd like the textures of the planets when viewed from space to (at least roughly) mirror the view you get in the surface view. I'm struggling to think how this might be achieved in Unity.

I figure I could create a render texture after generating the planet's surface and store it on the users HD. This has a few problems though - taking up HD space and not mapping well to a sphere (unless I always make the poles a uniform colour, which doesn't look good as the rest of the surface is quite highly detailed).

Another idea would be to create many generic textures for the space view of roughly each type of planet generated (blue / green / large continent / archipelago etc) and select a texture which most closely fits the procedurally generated map at run time. As long as the same texture isn't used for planets close to each other and the user doesn't compare the 3D view with the 2D view to closely then hopefully they won't notice!

So, any other ideas of how this might be achieved? I'm not looking for code, just a brainstorm of how I might get a procedural 2D map to be represented on a 3D sphere, or at least create a convincing illusion.

# Answer
> 1 votes
If you are content to not allow full 3D motion around the planet (ie, fly a ship around the planet to arbitrary locations), you might take the approach outlined in this post I did a long time ago...

3D Illusion of a 2D Planet Texture

It creates somewhat the illusion of 3D from a 2D map texture and works fairly well if your camera view is at the equator. If you want to be able to actually fly around the planet it's not so useful. You could simulate orbiting around the equator of the planet pretty well, but not pole to pole.

---
Tags: unity, textures, rendering, uv-mapping
---


# Question
Title: Main camera transform.forward becomes up and down when looking from above
The camera script is a 3rd person orbit camera, when I look straight it does what it supposed to do which is walk in the direction the camera is pointing, but when the camera is looking down from above the player, the camera's forward is now up. This means when I press W to go forwards I go into the ground and when I press S it goes upwards.

Here is my movement script:

```
    private void FixedUpdate()
    {
    float x = Input.GetAxisRaw("Horizontal");
    float z = Input.GetAxisRaw("Vertical");

    Vector3 moveDirection = Vector3.zero;
    moveDirection += Camera.main.transform.right;
    moveDirection += Camera.main.transform.forward;
    moveDirection.y = 0;
    // Rotation
    if (x != 0 || z != 0)
    {
        anim.SetBool("Walking", true);
        if (x != 0)
        {
            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(moveDirection), 0.4f);
        }
        else
        {
            transform.localEulerAngles = new Vector3(transform.localEulerAngles.x, Camera.main.transform.localEulerAngles.y, transform.localEulerAngles.z);
        }

    }
    else
    {
        anim.SetBool("Walking", false);
    }
    // Moving
    if (Input.GetKey(KeyCode.LeftShift) && !idle)
    {
        anim.SetBool("Running", true);
        rb.position += z * Camera.main.transform.forward * Time.deltaTime * runSpeed;
        rb.position += x * Camera.main.transform.right * Time.deltaTime * runSpeed;
    }
    else
    {
        anim.SetBool("Running", false);

        rb.position += z * Camera.main.transform.forward * Time.deltaTime * moveSpeed;
        rb.position += x * Camera.main.transform.right * Time.deltaTime * moveSpeed;
    }
}

```

while I'm asking, the movement script gets doubled when two keys are pressed, how do I fix it while keeping the same functionality of my current movement script?

# Answer
> 1 votes
This is normal behavior for the code you've written. You have to design your code around this issue.

You need a parent object for your camera which is always facing the horizon and can only turn left or right. So, while your camera is looking at the ground, your parent object will be looking towards the horizon. Then you just move your parent object instead of moving the camera itself.

I can't really write any code for this since this is not actually a coding problem but a system design problem. (i.e. your code is working the way it's supposed to but the system should be designed around how the code would work)

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


# Question
Title: C++ read access violation when deleting object
In my game, I've created (likely a very bad) Entity Manager that handles all entities in my game. It will assign random ID's to these entities and then add them to a map:

```
player = new Player(entityManager);
player->SetPosition(S2D::Vector2(50, 250));
entityManager->AddEntity(player);

```

---

```
//Adds entites to a list and assigns a random ID to them
void EntityManager::AddEntity(Entity* entity)
{
    int ID = rand();
    for(int i = 0; i < IDS.size(); i++)
    {
        if(IDS[i] == ID)
        {
            ID = rand();
            i = 0;
        }
        else
        {
            break;
        }
    }

    entity->SetID(ID);
    entities.insert(pair<int, Entity*>(ID, entity));
}

```

Each of these entities has a Update and Render function that is ran by the Entity Manager through it's Update and Render functions which are called by the Game Loop:

```
void EntityManager::Update(float deltaTime)
{
    if(!entities.empty())
    {
        //Removes entities that need to be deleted
        for(int i = 0; i < toDeleteEntities.size(); i++)
        {
            RemoveEntity(toDeleteEntities[i]);
            toDeleteEntities.erase(toDeleteEntities.begin() + i);
        }

    //Runs the Update function of all entities and adds Entites that need to be deleted to a list
        for(const auto entity : entities)
        {
            if(entity.second->ShouldDestroy())
            {
                toDeleteEntities.push_back(entity.second);
            }

            entity.second->Update(deltaTime);
        }
    }
}

void EntityManager::Render()
{
    if(!entities.empty())
    {
        for(const auto entity : entities)
        {
            entity.second->Render();
        }
    }
}

```

As well as looping through each entity, the Update function also loops through a vector called "toDeleteEntities" which contains entities that are to be deleted. Each Entity has a boolean called "Destroy" and if it's set to true, the Update function in the Entity Manager will add that entity to the vector.

```
//Runs the Update function of all entities and adds Entites that need to be deleted to a list
    for(const auto entity : entities)
    {
        if(entity.second->ShouldDestroy())
        {
            toDeleteEntities.push_back(entity.second);
        }

        entity.second->Update(deltaTime);
    }

```

Then before that for loop, the Update function will run this for loop that will remove each entity from the "toDeleteEntities" vector and then pass it onto another function that will delete it:

```
//Removes entities that need to be deleted
    for(int i = 0; i < toDeleteEntities.size(); i++)
    {
        RemoveEntity(toDeleteEntities[i]);
        toDeleteEntities.erase(toDeleteEntities.begin() + i);
    }

```

That delete function is this:

```
//Removes an Entity from the Game
void EntityManager::RemoveEntity(Entity* entity)
{
    if(entity->GetID() == -572662307)
    {
        return;
    }

    entities.erase(entity->GetID());
    delete entity;
}

```

The if Statement is there because of a previous error I had where I believe the for loop would pass the same entity to the delete function twice resulting in it trying to delete a already deleted object. I know it would be better to fix the error but truthfully it's easier to just do that XD.

Anyway hopefully that's enough context, if you need anymore then just ask. So all of this seems to work correctly somewhat with this Gem entity I have, it runs correctly and gets deleted without problems. But I've noticed when I attempt to add new entities and try and delete them, I get this \_Pnext error:

And I just can't figure out why. It seems to be coming from this loop here in the xutility class:

Does anyone know why this error is happening?

**EDIT** Screenshot of the Call Stack:

# Answer
> 1 votes
Looks like the issue is your toDeleteEnemies loop. As you remove entries, your list will shrink, but your counter is still going up. So when you get past half way, you're now out of bounds of the array. You can also optimize this either way by just clearing the list after going through each entry, as you are only acting on each item once

Example:

```
for (auto entity : toDeleteEntities)
    RemoveEntity(entity);
toDeleteEntities.clear();

```

A few other suggestions, Use smart pointers, to avoid having to manually call delete (and end up with other potential memory bugs).

And, avoid hard coded numbers (magic numbers). Define them as constants somewhere and refer to them by name

One other note, if you are adding an item to the toDelete list, you probably don't need to call its update method afterwards

---
Tags: c++
---


title: Draw edges of a complex 3D shape

text:
# Question
Title: Draw edges of a complex 3D shape
I have a 3D complex shape composed of simpler primitive geometric shapes. The geometric shapes are made of triangles.

I already know how to draw the edges of a single object (*geometric shapes*). In this case I am comparing each pair of triangles that are adjacent and comparing its normals. If the normals are not the same then it's an edge, so I draw a line.

However, when combining primitive shapes to form a more complex shape (*current rendering*), I don't know how to remove the edges of the faces that are coplanar with the faces of the adjacent shape.

How can I know what lines are not anymore edges in the complex shape so I get the *desired rendering*?

# Answer
> 0 votes
After struggling with the problem I found a solution that solves the use case.

Here are the steps to draw the edges of the complex shape:

1. Merge the different objects into a single mesh
2. Remove hidden faces in object space (I use raytracing)
3. Find and draw the edges

---
Tags: opengl, 3d, geometry, 3d-meshes
---


# Question
Title: When drawing transparent object in OpenGL it cuts some sides of other object?
I am making some OpenGL program, and I have a lost of cubes next to each other like this:

When I am making this hole, I am just skipping those cubes, just don't draw them.

```
for (int i=0;i<NUM_OF_CUBES;i++) {
        for (int j = 0; j < NUM_OF_CUBES; j++) {
                if ((i==3 && j==3) || (i==4 && j==3) ||
                    (i==3 && j==4) || (i==4 && j==4))
                        continue;
                cubes[i][j].draw(true);
        }
}

```

The result is:

But when I make those cubes invisible, by setting alpha to 0, the result is:

The code is:

```
for (int i=0;i<NUM_OF_CUBES;i++) {
        for (int j = 0; j < NUM_OF_CUBES; j++) {
                if ((i==3 && j==3) || (i==4 && j==3) ||
                    (i==3 && j==4) || (i==4 && j==4))
                        cubes[i][j].draw(true);
                else
                        cubes[i][j].draw(false);
        }
}

```

true/false fleg which I send to draw function just sets alpha to 0 or 1, if true alpha coordinate of glColor4f is set to 0, and if false is sent alpha coordinate is set to 1.

Does anyone have idea why it looks like some sides of the other cubes are cut? Like they don't exist.

# Answer
> 3 votes
It has to do with draw order. Not drawing something and drawing it as transparent/translucent are not the same thing. The transparent/translucent cubes are actually in front of the lower cubes so they get culled out even though they should be still visible.

Generally all transparent/translucent objects are drawn *after* all opaque objects to help mitigate the issue. There are ways to draw "order-independent transparency" but they get complicated quickly.

---
Tags: opengl
---


# Question
Title: How do I handle collision sounds with many objects?
I have a game where I am dropping blocks onto a wooden platform. The idea of the game is to stack them whilst keeping them balanced.

The blocks fall from a height. Sometimes they land on the plank, other times on other blocks. Players will opt to stack them close together.

I want to make a noise when the block hits something, so I have the following code:

```
void OnCollisionEnter(Collision other)
{
    Debug.Log("Cube collided");
    Debug.Log(other.collider.GetComponent<Collider>().tag);
    GetComponent<AudioSource>().Play();
}

```

This is attached to my block.

The sound plays, however it feels extremely unrealistic. The block makes the same noise no matter what the velocity of the impact. If a block becomes jammed between other blocks then it makes a few sounds, all of the same sound it makes when hitting the plank from a height.

Is there a way of creating more realistic 3D sounds? I guess I'm after a noise and falloff based off of the velocity, but that might not be the case, I'm a little unsure. This seems like a very common usecase but I am struggling to find anything online about it.

# Answer
> 2 votes
```
AudioClip audioClip;
AudioSource audioSource;

void Start () {
    audioClip = Resources.Load("click") as AudioClip;
    audioSource = gameObject.AddComponent<AudioSource>();
}

private void OnCollisionEnter(Collision collision)
{
    float audioLevel = collision.relativeVelocity.magnitude / 10.0f;
    audioSource.PlayOneShot(audioClip, audioLevel);
}

```

The above code is from another project I have worked on, so I know it works. You'll probably have to modify it or your existing code to match your scenario.

# Answer
> 4 votes
Unity provides you with `Collision.relativeVelocity`

https://docs.unity3d.com/ScriptReference/Collision-relativeVelocity.html

The basic example inside the documentation already solves one of your problems: **Don't play a sound, when the collision occured with a low velocity by using a threshold**. This prevents small unwanted turbulence inside the physics engine or insignificant vibrations to cause a storm of sounds to be played.

You can also **use the relative velocity to play the sound at different volume levels**. A "soft landing" is going to be quiet and a block falling at high speed will be loud. Don't forget to cap the volume to prevent unpleasant loud sounds. You can take it a step further, by **playing different sounds for different impact strengths**.

**Use multiple impact sounds and pitch variations to create variety**. If the same sound is being repeated often, it can quickly become annoying.

**Use different sounds when two different materials collide**, if your objects are made out of different materials.

Edit: Another obvious pitfall, you can easily fall into is described in DMGregorys comment below.

---
Tags: unity, c#, sound, sound-effects
---


title: 3D picking for mouse move event

text:
# Question
Title: 3D picking for mouse move event
I implemented color picking recently and I would like to use it as kind of highlight when mouse is over an object but I am concerned about performance. Color picking requires whole frame to be drawn, loosing effectively up to half of performance (MouseMove can happen nearly every frame).
Also, when mouse moves it is very likely to be nearly above previous point - is there any way how to use this fact to improve performance of 3D picking? Or is my best chance to use some other technique of 3D picking or approximation of results?
**tl;dr** If I wanted to do "realtime" 3D picking - on MouseMove, what is the best technique for doing so performance-wise?
EDIT: the exact numbers are even worse, when rendering 1m triangles render time increase from 1.5ms to 2-6ms and in spikes up to 15ms.

# Answer
> 2 votes
Considerations:

A. Do the color-frame less frequently, for example at 10 fps (every 6th frame if you run at 60fps). Small lag won't be that noticeable;

B. Render color-frame at lower resolution, e.g. 1/4, if you don't need pixel-perfect precision;

C. Render only one pixel that you need below the cursor. I'm not confident with the math, but surely there's a way to setup a view/projection matrix to take a tiny portion from the full view/projection matrix. If done right, frustum culling will reduce a lot too - meaning less overhead of unpickable objects ever getting sent to render at all;

D. Make sure you strip off any unnecessary parts and computations, alike non-pickable objects;

E. Forget about color-picking and switch over to Ray-Object intersection technique.

# Answer
> 2 votes
You need to, as comments indicated, project a ray from the camera's world location and using the unprojection of your camera look vector.

For multi-object selection, you will basically use two of these rays to generate a pyramid shape and do object collision detection against that. One corner would be the initial ray when the user first clicks, the opposite corner would be the current ray from where the mouse is dragged, and you can derive the other two.

I definitely wouldn't do the color technique. The actual rendering of the colors is trivial and not at all a performance concern. However, stalling the GPU so you that you can read back the results onto the CPU is a huge performance concern that you want to avoid. Doing it (somewhat) right at least requires a lot more coordination on the CPU, such as drawing the color buffer at the beginning of your frame and then not trying to read it back until the end of the frame (or next frame), giving the GPU as much time as possible to finish the color render. There's also a lot of shenanigans to play with the texture allocation to make sure it's in fast-to-read GPU memory well before you try to read it. Really, though, just don't do the color picking technique.

# Answer
> 0 votes
I'd echo Sean and avoid the rendering solution and use ray intersection. That said, you can generally get fast enough results without sophisticated spatial partitioning if you can quickly limit a pick to, say, tens of thousands of triangles to test against and not millions.

It's worth remembering that you only need to do one pick on a mouse over, not collect a billion samples worth of ray intersections as with the cast of a raytracer using path tracing. So you can generally get away without using a BVH, octree, or K-D tree, for example, or at least not ones that have to go all the way to storing things at the triangle level, if all you need is picking.

So a lot of times you can get away with a "good enough" solution, like just start off checking to see if a ray hits any one of your object's AABBs (or an object's "part", like a robot's arm), and if so, just test for ray/tri intersection with each of the triangles in that object. That can usually be "good enough" without building and constantly updating a much more elaborate data structure unless you have need for one for other purposes (collision detection, e.g.).

---
Tags: opengl, c++, performance, picking
---


# Question
Title: CrossPlatformInput Prefabs - Button handler to move?
I am currently trying to put two buttons on my UI that move a character left and right if touched down (Held). I would like to use the cross platform input, and would like the buttons to change the value of the Horizontal axis as my "A" and "D" keys would...

And my code for moving my character is as follows:

```
private void Update()
    {
        isGrounded = Physics2D.OverlapCircle(groundChecker.position, .15f, groundLayer);

        float move = CrossPlatformInputManager.GetAxis("Horizontal") * moveSpeed;
        playerRB.velocity = new Vector2(move, playerRB.velocity.y);

    }

```

# Answer
Try to check few things:

1) Canvas (Root) with buttons must have own higher order layer (sorting layers)
2) Buttons must have Z axis enough close to the camera
3) In Event trigger you should:

* use trigger Pointer Down and ButtonHandler.SetAxisNegativeState (for the left)
* use trigger Pointer UP and ButtonHandler.SetAxisNeutralState (for the left)
* use trigger Pointer Down and ButtonHandler.SetAxisPositiveState (for the right)
* use trigger Pointer Up and ButtonHandler.SetAxisNeutralState (for the right)

4) Maybe you will need add a Graphic Raycaster for parent (of buttons) canvas

I had same issue today and I think it is also in your case, buttons was just un-clickable.

Cheers
> 1 votes

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


# Question
Title: Why is custom memory management needed for assets?
Pretty much all resources relating to game programming, especially 3D open-world games, talk about how you have to constantly be unloading and reloading assets to and from disk, system memory, and video memory. I can understand this on consoles, as they have very simple memory management schemes that cannot deal with any potential overflow.

However, on the PC, the situation is very different. There is virtual memory provided by the OS for system memory and the graphics driver handles swapping back and forth from the CPU to the GPU. So why is it that it's not sufficient to load everything at once and only have to deal with prefetching and possibly making sure that there is no blocking while a required asset is being swapped?

---

This is not to say that everything is being allocated naively using something like `malloc`. Everything will be kept contiguous and cache-coherent. It's arguably easier to make your memory access efficient if you don't have to worry about paging in and out manually anyways...

---

**UPDATE:**

After reading a bit into asynchronous buffer transfers, I get the idea that the way the graphics driver can automatically page memory in and out is suboptimal. Does this also hold true for CPU resources; i.e., is it better to always manually manage when a given resource is to be loaded and unloaded even in the presence of virtual memory?

# Answer
Modern open-world games simply don't fit in memory. Keep in mind that most games are still 32-bit due to the number of gamers with 32-bit OSes, and a 32-bit process at best can only have 4GB of addressed memory at a time (independent of virtual memory) but realistically is limited to 2-3 GB. Toss in fragmentation and the actual amount of usable objects you can have in a memory at a time is a fair bit smaller than the total data you need for a large environment. Even on a 64-bit OS, you often need to target low-spec machines with only 4GB of memory to ensure maximum end-user compatibility. Let's not forget mobile devices, "under-powered" hardware like the WiiU, etc. Developers have to target a lot more than big fancy gaming PC rigs.

Virtual memory is not a solution, firstly because it doesn't negate address space limitations and also because it is not optimal. The OS can page things out at inopportune times or in inopportune ways. This was a problem dealt with by OSes when hibernation first came around; paging out the processes to disk and then paging them back in was significantly slower in some cases than having the application explicitly stream the resource back in. You can still see the problems today when a system is running out of memory, pages are paged out to disk, and the system becomes unresponsive becomes critical things necessary to run your WM/explorer.exe get paged out. Virtual memory was a solution devised to a problem decades ago where systems had very little RAM and the gap between memory and disk speeds was much smaller. Even today's fastest SSDs are a tiny fraction of the speed of cheap/slow RAM, and trying to pretend that you can use your disk as virtual RAM just isn't the best idea anymore. This is an age where some people do the opposite and load up file systems into RAM disks; the constraints that led to the creation of virtual memory don't hold true anymore.

Even aside from disk issue, custom resource management is still a big part of game development. From debugging hooks to fragmentation concerns to intelligent streaming of complex resources, simply pretending the whole world is an infinitely big box of bits is not realistic.
> 17 votes

# Answer
For a 32-bit game, as most games are for a variety of reasons, even a game that comes on one single-sided DVD (4.3GB) already has far more content that can be fitted into a 32-bit address space. And that's assuming the content isn't compressed on disc, and a perfectly optimal, load everything at once into contiguous address space approach. Many games now come on multiple DVDs, easily surpassing 10GB of content. In my experience on PC, once your address space approaches 2GB allocations will start to fail, and that becomes a hard limit, regardless of how much physical memory the user has.

If you do make the jump to 64-bit, assuming your engine supports it, that hard limit goes away, only to be replaced by an effective soft limit - as soon as virtual memory swapping begins to happen, the performance of the game will drop unacceptably. If the main process ever has to wait for memory to be paged back in, the frame-rate will stutter and glitch. Virtual memory might make that transparent, but it doesn't make it performant. It physically takes time to get that memory back from disk, and while you are waiting, your game has stalled. While it's possible to work around (with background pre-fetching of memory pages that you know you'll need soon), it's a difficult and unreliable process, and will still have performance implications.

The OS's algorithms for deciding what pages to swap out to disk have no knowledge of your game and what it is likely to need next. Furthermore, the OS still has to support other applications running simultaneously with your game, as well as the OS itself. Having to stall while pages are returned from disk is a massive performance hit, and it doesn't matter whether it's your game, another application or the OS that incurs it, the game's performance will suffer massively.

So regardless of whether the memory limit is soft or hard, memory is still limited. But even if you could just load everything at once, without hitting a limit of performance, there are still reasons why you wouldn't want to:

1. Your game takes far longer to load and get to an interactive state than it needs to, because it simply loads everything at the start and keeps it resident. You can load about 150MB/sec from a hard disk, and even the fastest DVD drive (24x) loads at 33MB/sec. That means the example 4.3GB DVD worth of content will take at least 30 seconds to load from HDD, and over 133 seconds to load from DVD. Those are unacceptably long load times.
2. Your game takes much more memory than is justified. If only 10% of the content is visible at any one time, holding the rest resident is simply wasteful, and prevents the user from using that memory for something else. Users are generally unforgiving of games which require a disproportionately large amount of memory to run properly.

Streaming assets from disk dynamically, whether in the background or synchronously during a loading screen, allows you to be far more efficient in your use of memory, with negligible effort and only a minor downside for the user. But it's an optimisation, and like any other optimisation it has diminishing returns the more you try to apply it. At some point the increase in memory footprint for keeping something resident is outweighed by the advantages gained from having it there without the need to load. But until that point is reached, it's better to load only what you need, when you need it.
> 6 votes

# Answer
Just speaking very generally and simplistically, and without considering the details of virtual memory implementations, the developer always has knowledge in foresight that the VM implementation lacks.

The developer can always say, *"I don't need to load this audio file right now. The music inside is only used for the game over screen."* And immediately after the game over screen, the developer can say, *"I don't need this audio clip anymore in physical memory. It's only used for this game over screen."*

The OS has no such foresight. It might be able to figure out, many page faults later, that some audio clip is no longer needed in physical memory since it hasn't been accessed in a good while. But turning foresight into hindsight translates into lots of page faults, and lots of page faults translates to hiccups in frame rates in a software as time-critical as a video game. There the foresight of the developer really helps if you want to avoid such hiccups.

And that applies conceptually regardless of the hardware and software. Assuming paging in memory is expensive, then the developer's foresight will always help in reducing that expense.

Speaking even more broadly, there's a never-ending cycle between hardware designer, compiler designer, OS/driver designer, and application developer. The hardware/compiler/OS/driver developers often try to implement optimizations to speed up your average application based on its usual memory access patterns, and perhaps sometimes with the hope like, *"People should just be able to write code however they want and it should be fast."* But if there was any thought of that type going on, it usually fails for performance-critical fields, because then the performance-critical developers start learning the intricate details of their compiler, hardware, OS, drivers, etc. and start writing code specifically designed to exploit that as much as possible to write the fastest code possible (like prefetches, hot/cold field splitting, SoAs, etc. for cache-friendly code). And that's like a game that never ends. These things are never treated as black boxes in performance-critical fields, since the developers are competing for performance.

Personally I kinda wish virtual memory didn't exist since it adds an additional layer of performance unpredictability in ways that tend to be too extreme and incur way, way too much of a performance penalty when things go really south to the point of *unusability*. I have sometimes run into cases where I used some application where I typed an extra digit or two by accident when drunk into some input field which then caused it to exhaust physical memory so quickly in ways that brought the OS to a crawl where I couldn't even click the cancel button on the progress bar anymore and had to wait 10 minutes while jamming Ctrl+Alt+Del to kill a process and cursing to myself while spilling my drink to get back to a point where things are usable again, and that was in spite of the page file being stored on an SSD. In those cases I would have rather preferred an "out of memory" error or something, at which point I might close some of my 17 tabs of porno (it's okay, I bookmark my favorites anyway) to free some memory and then immediately go about resuming my business.
> 1 votes

---
Tags: memory-efficiency, resource-management, memory
---


# Question
Title: Draw selected instances of VAO (glDrawArraysInstanced)
I'm using glDrawArraysInstanced to draw multiple instances of a tree at different positions to generate a forest.

Is there a way to draw selected instances? For example: I got 100 trees with different attributes. Due to culling I only want to draw instance 3, 65, 89 and 95.

# Answer
> 4 votes
There are two main ways to get instance data into a shader program:

* Setting the instance divisor for one or more vertex attributes (instead of advancing every vertex, it will advance every N instances)
* Using `gl_InstanceID` or an instanced attribute to select part of an array of instance data stored in a uniform buffer, shader storage buffer, etc.

`gl_InstanceID` always starts at `0`. Even if you use `glDraw*BaseInstance`, the base instance offset only applies to instanced attributes.

Therefore, the only way I can see to do what you want is to store all your instance data in an array of structs in a buffer accessed through the vertex shader, and a list of instance IDs in another buffer, which is bound to an instanced vertex attribute.

If the specific instances you want to draw is dynamically changing, updating the instance ID buffer will likely cause more of a performance hit than instancing gains you over multiple draw calls (and if you're only drawing 4 instances, you might not get any gains anyway - instanced rendering works best with dozens to hundreds of instances). On the other hand if you have multiple sets of instances that might need to be drawn, but the specific instances are known beforehand, you can put multiple lists of instance IDs in the same buffer and select the first ID using `glDraw*BaseInstance`.

---

Keep in mind that various instancing features have been added to OpenGL at different times:

* **OpenGL 3.1** `ARB_draw_instanced` and `ARB_uniform_buffer_object` become core, allowing basic instanced rendering using `gl_InstanceID`.
* **OpenGL 3.3** `ARB_instanced_arrays` becomes core, allowing for instanced vertex attributes through `glVertexAttribDivisor`.
* **OpenGL 4.2** `ARB_base_instance` makes instanced attributes more flexible. `ARB_transform_feedback_instanced` allows for instanced drawing from transform feedback buffers.
* **OpenGL 4.3** `ARB_vertex_attrib_binding` becomes core, adding `glVertexBindingDivisor`, which works like `glVertexAttribDivisor` but operates on any attributes that use a particular buffer binding index rather than just one attribute index. Also, `ARB_shader_storage_buffer_object`, while not directly related to instancing, solves some issues with `ARB_uniform_buffer_object`.
* **OpenGL 4.5** `ARB_direct_state_access` becomes core, including `glVertexArrayBindingDivisor`, the DSA version of `glVertexBindingDivisor`.

---

On an side note, consider using `glDrawElements*` instead of `glDrawArrays*` if you're concerned about performance. In addition to usually reducing the size of your vertex data, it enables the GPU to use the Post Transform Cache.

# Answer
> 2 votes
I know this question was asked prior, but with OpenGL 4.6 you can now call glDrawArraysInstancedBaseInstance to do exactly what was asked.

Another option is with OpenGL 4.2 the ARB\_base\_instance extension was added for this as well.

So to draw tree 3, 65, 89 and 95 you could make 4 draw calls of size 1 instance and put the offsets for each

---
Tags: opengl, instancing
---