# Question
Title: Large Armies fight : Looping through a million elements
I'm currently developing my first game. I had the idea to do something similar to the old browser games like Ogame, Travian, etc (with some differences though), and I'm kind of unsure about how to calculate the output of two armies fighting. There are for now no multiplayer aspect in the game, but that's something I would like to do in the future, si I'd like to plan with that in mind, if possible.

Each unit has an attack, HP and armor value. The armor is regenerated between each round (in my idea). There are different unit types, with strength/weaknesses against other units.

I had two ideas about how I could calculate the outcome of a fight :

**1. Loop through each unit**

In this scenario, I would basically loop through two dictionary\<Unit, Int\[\]\>) where each int\[\] would be the HP remaining on each single unit. One dictionary per army.

I would assign a random target to each unit, apply the modifiers (either a simple attacker multiplier or a chance to hit a new target depending on a value), and store back the HP values.

Rinse and repeat for either a fixed number of rounds or until one army is out.

I love the idea behind this solution, but I'm afraid it could take too much time to loop through big numbers of units. At some points, armies could reach over 1M units (not more than 10M though I think), and even though my operations inside the loop are quite simple, I'm a bit afraid of performance issues, especially with multiplayer in mind.

**2. Have a global value**

In this scenario, I would just calculate the total Atk/Armor/HP of each unit type, spread the attack value amongst ennemy army (if I have 100 units attacking 50 units of type 1 and 50 units of type 2, half of the damage would be applied to each ennemy), apply my damage multipliers, and get a global remaining HP for each unit type. Then I would divide by an individual unit HP to display the remaining units number. Rinse and Repeat.

This solution is obviously much faster, as I have at max to loop through 4 to 6 different unit type. The issue would be when dealing with smaller amounts of units, I did some tests and I didn't like the results. Also I'm not too sure about how to implement a bit of RNG in this system.

**3. A mix of both ?**

I had other ideas such as dividing the army in groups of units (let's say an army is always divided in 100 groups), and then apply method 1 to each group. Then I would have some RNG still, but each group would have its global HP. You could then never lose an amount of units smaller than a group.

I'm not too sure about this one :/

My main concern overall is about the method 1 and the possible performance issues. Do you think it's doable to loop through arrays containing millions of values or is it just stupid performance wise ? Any other idea ?

Thanks in advance !

# Answer
Before I begin, I apologize if it seems like I'm breaking this down Barney-style; I do so for the benefit of other readers, and I promise I mean no offense.

I would say go with option 3; the reason is that armies are, in fact, divided into smaller groups to deal with a similar problem, which is that managing 1M units all at once is a right pain in the bum. You could even take this further by mimicking reality and having multiple levels of units, and then you can defer certain processing until later.

Let's suppose that you have an army of 100,000 units, each unit having an attack, HP, armor, etc. Well first, let's combine them into small squads, let's say 10 units per squad, so now instead of dealing with 100,000 objects directly, on the surface-level we're only dealing with 10,000. Each squad now has the *sum* of each of the attributes of its individual units. When a squad takes a hit, the damage is applied to the *squad* immediately, but not to any individual *units* within until later when that information is actually needed (at the end of the battle, for instance). Your RNG could be applied at this time to apply damage to individual units, for example in a "damage pool" where the RNG chooses how much to take out of the pool and apply to an individual unit (or subgroup).

Now let's take those 10,000 squads and organize them further. We'll organize them into platoons(?) and we'll say 10 squads per platoon. Now we're only dealing with 1,000 objects, and we can apply the same methods *even faster*. Extrapolate this concept until you reach your top-level unit; what you can do then, is track how much damage each army is taking *at the top level* and only apply damage processing to subgroups *when needed*, and then you're only applying it to a subset of the army rather than having to process the *entire* army at once.

Another option is to account for the notion of *space*. If you have two massive armies fighting on a field, "Total War" style, more than likely only a very small subset of those units are going to be actively fighting and taking damage because only the units at the very front are able to reach the enemy. You could determine how "wide" an army is, and then in general you only need to process for the frontline units, not necessarily everyone else.

Like others have said, it may be a moot point because you're not trying to do things in real time; but personally I like to be efficient, so I know I would go to the effort regardless, and I hope my answer helps you to this end.
> 1 votes

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


# Question
Title: How do I corretly use a Direct X 12 Root Signature?
I know a Direct X 12 Root Signature tells Direct X 12 how to use the resources between the CPU and GPU, but I'm having a hard time using it.

I tried using it before but it kept failing saying the pixel shader was not fully registered to the root signature, and I couldn't figure out why or how to fix it.

When I write a shader, how do I incorporate that shader with a root signature and should I have multiple root signatures to handle different shaders?

# Answer
> 1 votes
There are two ways to define root signatures.

1. You can create the root signature C++ code, and then when you load the shader with the root signature it will 'rebuild' it to bind to that particular rootsig. This is what you'll see in most of the official samples on DirectX-Graphics-Samples.
2. You can define the root signature in HLSL. You here you use any shader blob built with that signature to create the root signature object. An example of this usage can be found in this sample. *For Xbox console development, this is far more efficient.*

The main limitation is that ALL shaders bound at the same time must use the SAME root signature. That means you can't as easily reuse the same shader and mix & match, and will need to generate more combinations of shader blobs.

For example, in the DirectX Tool Kit for DX12, I have to build the same shader a few times with different root signatures. For example, there are two different root signatures used in this NormalMapShader depending on if I have a specular texture or not, so I need two different builds of the same vertex shader:

```
[RootSignature(NormalMapRS)]
VSOutputPixelLightingTx VSNormalPixelLightingTx(VSInputNmTx vin)
{
    VSOutputPixelLightingTx vout;

    CommonVSOutputPixelLighting cout = ComputeCommonVSOutputPixelLighting(vin.Position, vin.Normal);
    SetCommonVSOutputParamsPixelLighting;

    vout.Diffuse = float4(1, 1, 1, DiffuseColor.a);
    vout.TexCoord = vin.TexCoord;

    return vout;
}

[RootSignature(NormalMapRSNoSpec)]
VSOutputPixelLightingTx VSNormalPixelLightingTxNoSpec(VSInputNmTx vin)
{
    return VSNormalPixelLightingTx(vin);
}

```

Another limitation is that you can't have 'unused' slots in root signatures on some older hardware. For my BasicEffect shader, I therefore have to have two different root signatures for 'textured' vs. 'untextured'.

> The *Direct3D Debug Layer* will warn when you try running 'unused slots' on these older systems, but if you aren't aware of it, this may be difficult to notice unless you do a fair amount of testing.

For examples of lots of different HLSL-defined root signatures, see RootSig.fxh.

---
Tags: c++, graphics-programming, directx12
---


title: Unable to add AR session

text:
# Question
Title: Unable to add AR session
I am new to unity and i am trying to make a AR app. I have installed AR foundation, Arcore Xr plugin, Arkit XR plugin via package manager. Then if i go to the Hierarchy panel to add a AR session and right click, I am not seeing any XR option to add a AR session. What should i do now? Anyone please help me.

# Answer
Check your Unity install configuration, I see the option with this configuration:

* Unity 2019.4.3f1 (LTS)
* The Android and iOS modules installed (at Unity install time, or later via Unity Hub's "Add Modules")
* AR Foundation, ARCore XR plugin, ARKit XR plugin via package manager

The following options appears when right clicking inside the Hierarchy panel:

When adding an "AR Session", you'll find it under the "XR" menu option. This is a very similar menu that appears when selecting "GameObject-\>XR" from Unity's top menu bar.
> 0 votes

# Answer
I had the same problem. I couldn't load any AR specific objects in Unity 2019. I decided to go for Unity 2020 but I got some others issues there too.

Cause:

A couple of months earlier I uninstalled Anaconda for Python. It left some incorrect registries.

Solution:

I deleted "Computer\HKEY\_CURRENT\_USER\Software\Microsoft\Command Processor\AutoRun" registry and now everything works as expected.

I know it sounds crazy but it really worked out.
> 0 votes

---
Tags: unity, augmented-reality
---


# Question
Title: Need help with Assimp skeleton animation
I have recently implemented skeleton animation in my custom engine by following this tutorial. I made several improvements based on that, and was able to load/play simple humanoid animations without problem, like the final output in that link. Now I'm very excited to try out more animations, unfortunately it doesn't work all the time. For example, this model comes with a small sample animation, I can correctly play the legs, arms, necks, fingers and eyes, everything. But if I try some MMD-style animations (exported from Blender as FBX), or those downloaded from Mixamo, none of them works, the animation is still playing but looks very weird, the legs/feet are not moving when they are supposed to, instead the hips bone is rotating (luckily the mesh is not broken though).

After some trials and errors, I found such weirdness might be related to inverse kinematics, because when I play the same animation in Blender but have all IK disabled, it looks just like how it would appear in my own engine. It seems that both Mixamo and Blender have built-in IK support, but I don't know what to do in my case, do I need to implement IK from scratch? Or is there a way to "bake" IK into the animation? Perhaps I'm not using the correct import settings? Does Assimp have an import flag specific to this? I'm still not 100% sure it's caused by IK, just want to know if other people have encountered the same issue, could anyone give me some hints as to what might be the cause?

# Answer
> 0 votes
Okay, turns out this is much easier to solve than I thought...... The problem is simply because my engine does not have an IK solver as Blender or Unity does, so it can only handle animations driven by FK (forward kinematics) only. I learned a lot more about FK/IK while struggling with this issue.

So, we need to convert the original armature that use IKs to a new armature that uses only FK bones. For this, I found a Blender addon called Landon that does the convertion, it's as simple as running a line in the Blender Python Console:

```
import bpy
bpy.ops.rigging.iktofk()

```

After the convertion, I can play it normally in my engine, there are some small position "flickerings" around the feet, but that might vary from model to model, and overall the animation is very smooth.

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


# Question
Title: Why does RigidBody.MovePosition ignore collisions?
I want my object to collide with a wall (i.e not be able to walk through it), from all docs I read MovePosition should take this into account:

```
private void FixedUpdate()
{
    rb.MovePosition(transform.position + direction * movementSpeed * Time.deltaTime);
}

```

I've made sure all layers are detecting each other in physics settings and neither is marked as a trigger. What am I missing?

# Answer
> 3 votes
You've marked your object as Kinematic.

That tells the physics engine "don't worry about pushing this object away from collisions, I'll handle that part".

So, since you promised to handle that part, it's up to you to handle it. For instance, you could fire a CapsuleCast to your planned destination position, and adjust back to an earlier position if the cast hits something.

---
Tags: unity
---


# Question
Title: How can I properly render multiple layers/components in game?
I'm making a Love2D board game video game, which has multiple different components which need to be run and displayed on the screen at the same time. For example, I need to display the board, the characters, and the UI. Ideally, I would like to store each component in a seperate file (similar to Unix philosphy) In what way should I go about this?

My first idea was to create a screen/gamestate for each of these componenets, and stack them on top of each other so each is running/displaying at the same time. This feels like it's not a very proper solution so I'm open to other ideas.

# Answer
> My first idea was to create a screen/gamestate for each of these components, and stack them on top of each other so each is running/displaying at the same time. This feels like it's not a very proper solution so I'm open to other ideas.

Seems like a fine solution. Especially as a first implementation.

After that, you might see if some parts are static and can be rendered to a canvas instead.

I'd only steer away from the "draw them on top of each other" plan if some aren't visible at all. Then you might have a list of drawables for each gamestate.
> 1 votes

---
Tags: 2d, architecture, love2d
---


# Question
Title: How to get rid of gradient shading on the bottom of grass
I've been using Unity's terrain system and a Vegetation Spawner asset (https://assetstore.unity.com/packages/tools/terrain/vegetation-spawner-177192) to make some terrain for my game. While using the Flooded Grounds (https://assetstore.unity.com/packages/3d/environments/flooded-grounds-48529) grass meshes for the grass, I've stumbled upon an issue with how the grass is colored. As seen in the attached picture, the bottom of the grass blades is black, the tips are the desired color, and everything in between is a gradient between the two colors. I've tried everything I could from changing material properties to editing and disabling lighting/shadows and post processing effects like ambient occlusion, all to no avail. The grass material doesn't seem to be shaded in this manner, but when the grass prefab is placed with or without the vegetation spawner, I get this effect, even in a new project. How can I just have the grass be one solid color with no gradient?

# Answer
> 0 votes
This effect is not coming from the Unity terrain. It is most likely coming from your vegetation spawner or flooded grounds asset. Look into the settings for those assets.

---
Tags: unity, rendering, ambient-occlusion
---


# Question
Title: problem showing cubemap shadows for point lights in texturecube mode
I'm adding cubemap shadow for point lights. Rendering each face in a separate texture2D seems to work (see picture, right, rendering from yellow point light view). With the same pipeline I can't get it working for cubemap or I'm not able to see it correctly in my visualisation panel. I'm using the almost same code as in the GSCubemap demo for DX10 except I want to render only in the depth buffer so I don't set pixelshader. Note : my cubemap is D24S8 and current shadow is from another directional light, there's no shadows from point lights at the moment.

here the modified code

```
  struct VS_INPUT
 {
    float3 Pos : POSITION;
    float3 Norm : NORMAL;
     float4 Col : COLOR0;
   float2 Tex : TEXCOORD0;
};

struct GS_INPUT
{
    float4 Pos      : SV_POSITION;
};

 struct PS_CUBEMAP_IN
{
     float4 Pos : SV_POSITION;
      uint RTIndex : SV_RenderTargetArrayIndex;
};

```

The LightPos\[2\].xyz below is the position of the yellow point light

```
     GS_INPUT VS_CubeMap( VS_INPUT input )
 {
     GS_INPUT output = (GS_INPUT)0.0f;
     output.Pos = mul( float4(input.Pos,1), World ); output.Pos.xyz -= LightPos[2].xyz;
    return output;
 }

```

below LightViewCube\[f\] are the 6 view matrices for the 6 faces from the yellow point light view. Projection is projection matrix

```
 [maxvertexcount(18)]
 void GS_CubeMap( triangle GS_INPUT input[3], inout TriangleStream<PS_CUBEMAP_IN> CubeMapStream )
{
    for( int f = 0; f < 6; ++f )
     {
         PS_CUBEMAP_IN output;
         output.RTIndex = f;
         for( int v = 0; v < 3; v++ )
         {
             output.Pos = mul( input[v].Pos, LightViewCube[f] );
             output.Pos = mul( output.Pos, Projection );
             CubeMapStream.Append( output );
          }
          CubeMapStream.RestartStrip();
     }
  }

  float PS_CubeMap( PS_CUBEMAP_IN input ) : SV_Target
  {
       return 0;
  }

```

for viewing the cubemap in 6 different quad panels I do the following to calculate the 3D uvw direction coordinates based on the 2D coordinate of my quad used as panel (Face is the index of the cubemap face):

```
 float3 UVW = float3(Input.Tex,1);//default value
 float2 UV2 = Input.Tex*2 - float2(1,1);
 switch ( Face )
 {
    case 0:UVW = float3 (1, -UV2.y, -UV2.x);break;//X+
    case 1:UVW = float3 (-1, -UV2.y, UV2.x);break;//X-
    case 2:UVW = float3 (UV2.x, 1, UV2.y);break;//Y+
    case 3:UVW = float3 (UV2.x, -1, -UV2.y);break;//Y-
    case 4:UVW = float3 (UV2.x, -UV2.y, 1);break;//Z+
    case 5:UVW = float3 (UV2.x, -UV2.y, -1);break;//Z-
 }

```

I've tried either at the vertex or pixel shader level but get the same half black quad for the first panel (Face=0) and full red for the others (left panel image).

# Answer
I've solved my problem that was simply due to geometry shader not compiled (silly me). This get the shadow cubemap rendering working and confirmed the code used for panel views was correct.
> 0 votes

---
Tags: shadow-mapping, deferred-shading
---


title: Pygame Traffic signal logic

text:
# Question
Title: Pygame Traffic signal logic
I am currently working on a traffic simulator with Pygame, however i am struggling with implementing the logic of the traffic signals.

Any help is welcome.

My traffic simulation is grid based. The tiles in the grid are being drawn by looping trough a tile list.

```
    self.map = [['/','/','/','/','s','n','/','/','/','/'],
                ['/','/','/','/','s','n','/','/','/','/'],
                ['/','/','/','/','s','n','/','/','/','/'],
                ['/','/','/','t1','s','n','t2','/','/','/'],
                ['w','w','w','w','c','c','w','w','w','w'],
                ['o','o','o','o','c','c','o','o','o','o'],
                ['/','/','/','t3','s','n','t4','/','/','/'],
                ['/','/','/','/','s','n','/','/','/','/'],
                ['/','/','/','/','s','n','/','/','/','/'],
                ['/','/','/','/','s','n','/','/','/','/']]

```

The characters t1, t2, t3 and t4 represent the traffic signals. In the code below i am looping trough the tile map.

```
def load_tiles(self):
    self.tiles = pygame.sprite.Group()
    self.trafficsignals = pygame.sprite.Group()
    type = ['c', 'n', 'w', 's', 'o']
    tsType = ['t1', 't2', 't3', 't4']

    x, y = 0, 0
    # iterate through the tile map list
    for row in self.map:
        x = 0
        for tile in row:
            if tile == '/':
                self.tiles.add(Tile((200, 200, 200), x * self.tile_size, y * self.tile_size, self.tile_size))
            elif tile in type: # add road tiles to tile sprite group
                self.tiles.add(Tile((100, 100, 100), x * self.tile_size, y * self.tile_size, self.tile_size))
            elif tile in tsType: # add trafficsignals to trafficsignal sprite group
                self.tiles.add(Tile((200, 200, 200), x * self.tile_size, y * self.tile_size, self.tile_size))
                self.trafficsignals.add(ts( x * self.tile_size, y * self.tile_size, tile, self.trafficsignals, self.screen))
            # Move to next tile in current row
            x += 1
        # Move to next row
        y += 1
    return

```

This function is being called once in the `init` function of my `main` class since the tiles only need to be drawn once, however i am not sure if this is the right approach since the traffic signals are supposed to change color. after drawing the sprite groups to my screen the image below is the result i get.

The black bars are where my traffic signals are supposed to go. These traffic signals are objects made using a separate class.

```
class Trafficsignal(pygame.sprite.Sprite):
    def __init__(self,  x, y, tile, signals, screen):
        super().__init__()

        self.screen = screen

        self.red = pygame.image.load('images/signals/red.png').convert_alpha
        self.yellow = pygame.image.load('images/signals/yellow.png').convert_alpha
        self.green = pygame.image.load('images/signals/green.png').convert_alpha

        self.noOfSignals = signals # number of traffic signals
        self.currentRed = 0        # Indicates which signal is red currently
        self.currentYellow = 0     # Indicates which signal is yellow currently
        self.currentGreen = 0      # Indicates which signal is green currently

        self.redTime = 100
        self.yellowTime = 5
        self.greenTime = 20

        self.image = pygame.Surface([15, 42])
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

        # rotate trafficsignal bar to corresponding angle
        if tile == 't1':
           self.image = pygame.transform.rotate(self.image, 180)
        if tile == 't2':
           self.image = pygame.transform.rotate(self.image, 90)
        if tile == 't3':
           self.image = pygame.transform.rotate(self.image, -90)

def update(self):
    pass

```

I am currently stuck on the logic of how a traffic signal changes color. I want the traffic signals to change color in a clockwise direction. Only one traffic signal is allowed to be green. I already made some variables like `currentGreen` to determine which color a traffic signal currently is, but i am not really sure on how to implement this logic since i'm still pretty new to game development.

# Answer
> 0 votes
You can use an array like this: `[2, 1, 1, 0]` and each number represents a color (in this example: `0` for red, `1` for yellow, `2` for green) and then increase all of the numbers every time you want the color to change (say, every turn or every 10 seconds), just remember to add a `%3` so the numbers won't get more than `2`.

> Only one traffic signal is allowed to be green.

Well, I don't see how this can happens since you have more than three traffic signals. If you look at my example, you will get two green lights in the next turn.

---
Tags: pygame, logic
---


# Question
Title: Godot KinematicBody2D Invisible After If Statement
The reason I address this question is because of the limited documentation and support for starting devs on Godot. I do not know what is wrong with this one if statement, but after I added it, my player was unusable and invisible.

```
var collision = move_and_collide(vel * delta)

if collision.collider.name == "Spikes Tilemap":
    print("collided")

```

Spikes Tilemap is a tilemap I set custom to collision detection for spikes.

If you need more information, ask me. Thank you for your patience.

# Answer
Based on the limited information you've provided, my guess is a null pointer exception in the script.

---

From the KinematicBody2D docs (assuming your player, and/or the script your showing us, is a KinematicBody2D):

> The body will stop if it collides. Returns a KinematicCollision2D, which contains information about the collision when stopped, or when touching another body along the motion.

From the KinematicCollision2D docs (discussing `move_and_collide` results):

> If a collision is detected, a KinematicCollision2D object is returned.

It seems `move_and_collide` doesn't always return a value, and will only actually give you an object if there is a collision. You should add a check that you actually got an object before trying to access that object's properties. If you got no result, assume there is no collision.

---

Based on your comment providing the error output, this is exactly the issue.

> It is a kinematic body 2d. the error is "Invalid get index 'collider' (on base: 'null instance')

The `move_and_collide` function only returns an object when there is a collision. Otherwise it returns null. It is called every frame, and there is not always a collision. You need to add a null check to verify it actually returned something before checking what kind of collision it was.

---

To fix avoid this particular error, change your if condition to the following, in order to make sure you only attempt to access properties on the collision object if it actually exists.

```
if collision != null:
    if collision.collider.name == "Spikes Tilemap":
        print("collided")

    # any other code that relies on using collision

```
> 2 votes

---
Tags: collision-detection, godot, collider
---


# Question
Title: Problem with bullet colliding with multiple enemies instead of one
I have a bullet script that trigger on collision with an enemy, problem is when two enemies colliders overlaps and trigger with bullet both disapear instead of one only. Is there any way to only trigger one?

```
private void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.GetComponent<Enemy>())
    {
        collision.GetComponent<Enemy>().DisableUnit();
        gameObject.SetActive(false);
    }
}

```

# Answer
> 2 votes
The docs note that: *Trigger events are sent to disabled MonoBehaviors*

So SetActive(false) probably isn't enough. Try a hitEnemy flag and only do something when it's false:

```
private bool hitEnemy = false;

private void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.GetComponent<Enemy>() && !hitEnemy)
    {
        hitEnemy = true;
        collision.GetComponent<Enemy>().DisableUnit();
        gameObject.SetActive(false);
    }
}

```

or simiply delete the bullet gameobject:

```
private void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.GetComponent<Enemy>())
    {
        collision.GetComponent<Enemy>().DisableUnit();
        Destroy(gameObject);
    }
}

```

---
Tags: unity, collision-detection
---


# Question
Title: More efficient/clean way of programmatically generating and customizing repetitive objects?
I am coding my UI in Unity C# with the UI Toolkit, and as I write more and more my code is getting quite annoying in terms of one particular issue.

I find myself repeating many similar lines of code but having to change the name of the VisualElement object I am referring to manually each time which is annoying and wasteful. If I change a VisualElement name, I also have to do a find/replace to get all the lines I described it and be sure I don't pick up anything else by mistake.

For example, if I'm putting together a few VisualElement objects, it might look like:

```
        VisualElement visualElement1 = new VisualElement();
        visualElement1.style.width = new Length(100, LengthUnit.Percent);
        visualElement1.style.height = 500;
        visualElement1.style.flexDirection = FlexDirection.Row;
        visualElement1.pickingMode = PickingMode.Ignore;
        visualElement1.style.position = Position.Absolute;
        visualElement1.style.bottom = 200;

        VisualElement visualElement2 = new VisualElement();
        visualElement2.style.width = visualElement2.style.height = 500;
        visualElement2.style.marginLeft = 150;
        visualElement2.style.backgroundColor = Color.white;
        visualElement2.style.opacity = 0.6f;
        visualElement2.style.borderBottomLeftRadius = visualElement2.style.borderBottomRightRadius = visualElement2.style.borderTopLeftRadius = visualElement2.style.borderTopRightRadius = 200;

        visualElement2.Add(visualElement1);

```

So much of the code becomes repetitive in style that it would be much faster to copy and paste some settings lines from one element to the next rather than having to change the names or type them from scratch.

For example, what I would like to do is this:

```
        VisualElement *vePtr;

        VisualElement visualElement1 = new VisualElement();
        *vePtr = &visualElement1;
        *vePtr.style.width = new Length(100, LengthUnit.Percent);
        *vePtr.style.height = 500;
        *vePtr.style.flexDirection = FlexDirection.Row;
        *vePtr.pickingMode = PickingMode.Ignore;
        *vePtr.style.position = Position.Absolute;
        *vePtr.style.bottom = 200;

        VisualElement visualElement2 = new VisualElement();
        *vePtr = &visualElement2;
        *vePtr.style.width = *vePtr.style.height = 500;
        *vePtr.style.marginLeft = 150;
        *vePtr.style.backgroundColor = Color.white;
        *vePtr.style.opacity = 0.6f;
        *vePtr.style.borderBottomLeftRadius = *vePtr.style.borderBottomRightRadius = *vePtr.style.borderTopLeftRadius = *vePtr.style.borderTopRightRadius = 200;

        visualElement2.Add(visualElement1);

```

If I could use a pointer like this and just reassign the pointer after creating each new element, then I can copy and paste my settings lines from one element to another very quickly and I don't have to re-write the whole line or change the name of the object it's referring to over over. If I change an object's name, I only have to do it once or twice as well.

For example, if I want the long border radius statement on Element2 to also apply to Element1, I can easily just copy and paste the line to where Element1 was created and change 200 to whatever I need, without having to rewrite or edit the whole line.

The problem is this doesn't actually work. I am told "Pointers and fixed size buffers can only be used in an unsafe context" and "Cannot take the address of, get the size of, or declare a pointer to a managed type."

Is there some way to accomplish what I am trying to do above and make my life a bit easier or more flexible?

Thanks for any ideas.

# Answer
First of all, you don't need a pointer here, because VisualElement is a `class`, which means that every variable of type `VisualElement` is already a reference. For example:

```
 VisualElement visualElement1 = new VisualElement();
 VisualElement visualElement2 = visualElement1;

```

Now both variables `visualElement1` and `visualElement2` point to the same object. When you make a change through one of those references, then the change will be visible in the other.

But this does not really solve the actual problem, which is a whole lot of redundant code.

When you have a lot of objects which you want to have the same style, then it is a good idea to use a `StyleSheet` for that purpose. Setting `visualElement.style.*` directly via code should only be done when you have a good reason to calculate that property at runtime.

The same applies to layouting. When you feel the need to do a lot of layouting by calculating positions and dimensions of UI elements via C# code, then that's usually a sign that you could benefit from learning more about the automatic layouting capabilities of UIElements. I have no idea what you are actually trying to achieve, but unless it's something really unusual, it probably can be done with the layout engine. When you have a specific use-case where you are unsure how it can be done automatically, please open a new question.

And if you want to define templates for certain repeating UI elements, but don't want to use the visual editor, then you can define the UI in XML code instead of C# code.

OK, but what if all of this fails and you really, really have to use C# to set certain UI properties on multiple elements? In that case it is a good way to do that via a helper-method:

```
public static void SetColorForTeam(VisualElement element, PlayerTeam team) {
    element.color = team.brightColor;
    element.backgroundColor = team.darkColor;
    element.borderLeftColor = team.brightColor;
    element.borderRightColor = team.brightColor;
    element.borderTopColor = team.brightColor;
    element.borderBottomColor = team.brightColor;
}

...
SetColorForTeam(nameTagLocal, localPlayer.team);
SetColorForTeam(scoreDisplayLocal, localPlayer.team);
SetColorForTeam(nameTagOpponent, opponentPlayer.team);
SetColorForTeam(scoreDisplayOpponent, opponentPlayer.team);

```
> 1 votes

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


# Question
Title: How to return an unknown amount of data from a parallel job? (C# Jobs + Burst)
Say we have a parallel job (implementing `IJobParallelFor`) which requires a large array (\>100,000 items) as an input to do some complicated processing. After said job is finished, I'd like to return a portion of those items that have passed certain checks.

Specifically, I'd like to check if \>100,000 Vector3's satisfy a certain criteria. If they do, I'd like to add them to a list so that I can continue operating on that data in the main thread (or in other jobs).

The issue is that we can't use a NativeList to call .Add() because that data structure doesn't support parallel writing. It is also not viable to use a NativeArray because it requires its size to be initialized ahead of time, and we don't know how many items we are going to return.

What is a good way to solve this problem?

# Answer
> 2 votes
Use `NativeQueue` for your results, then obtain a `NativeQueue<T>.ParallelWriter` for it using `results.AsParallelWriter()`. It exposes a method `Enqueue(T)` to add elements to the queue.

You can then later read from that queue by copying it to an array using `results.ToArray()` or by processing the queue using a `while(results.TryDequeue(out result)) {` loop.

The NativeList also offers a parallel writer, by the way, but that one does not offer operations which exceed the initial capacity.

# Answer
> 1 votes
You could use a `NativeArray<bool> IsValid` to indicate which items require some more processing.

Items can then be aggregated in one place (e.g. in another `IJob` in a loop); or the flag can be used in the followup method in the next job to quit early.

This has the advantage of fixed-size, low synchronization overhead. It requires a tiny bit more RAM. Cache locality is sometimes better, sometimes worse.

---
Tags: unity, c#, jobs, unity-job-system, burst
---


# Question
Title: How to scale all meshes of various scales to a unit scale
I have a few objects with different scales i want to make a scene where all objects are scaled proportionally to everything else, something like a normalize function for a mesh.

How would I go about doing this? I have thought about traversing all the vertices, finding the min and maximum and dividing all vertices by the maximum?

I have also thought of traversing all vertices and normalizing them one by one, but I'm not sure it would solve it?

Edit: to reword the question, I want a door and a cup to be the same size. obviously a door will be much bigger than a cup, but I want to scale both such that they fit within a unit cube or a unit sphere.

Edit2: I want to achieve exactly this effect from the Nvidia Omniverse demo at around 1:17 he talks about the mesh and then proceeds to say that they normalize it. how do they do it!

# Answer
This is just simple division.

```
public static void ScaleLongestAxis(MeshFilter filter, float targetSize = 1f) {
   var size = filter.sharedMesh.bounds.size;
   float longest = Mathf.Max(size.x, size.y, size.z);
   float scaleFactor = targetSize/longest;
   filter.transform.localScale = new Vector3(scaleFactor, scaleFactor, scaleFactor);
}

```
> 2 votes

---
Tags: unity, c#, 3d
---


# Question
Title: how do i still get a reference from the game object after it get destroyed?
This is the script from the game object that will be soon get deleted.

```
    public class Firstboss : MonoBehaviour
{
    public int healthPoints = 3;
    public bool firstTriggered;
    public bool Firstdied;
    Rigidbody2D rb;
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if(collision.gameObject.tag == "circle")
        {
            healthPoints--;
            if(healthPoints <= 2)
            {
                firstTriggered = true;
            }

            if(healthPoints <= 0)
            {
                Firstdied = true;
            }
        }
    }
}

```

But after "FirstDied = true" it will pass on to my other script

```
 [SerializeField] Firstboss _firstBossScipt;
[SerializeField] GameObject _firstBoss;
[SerializeField] GameObject _FirstFall;
[SerializeField] GameObject _FirstFelll_secondPhase;

 void FirstWave_Second()
{
    if(Time.time > _nextSpawnTime_First_SecondPhase)
    {
        _nextSpawnTime_First_SecondPhase = Time.time + SpawnBetween_First_SecondPhase;
        Vector2 SpawnPosFirst = new Vector2(Random.Range(-1.80f, 1.70f), cameraScreenWrap.y);
        Instantiate(_FirstFelll_secondPhase, SpawnPosFirst, Quaternion.identity);

        if (_firstBoss != null)
        {
            if (_firstBossScipt.firstTriggered == true)
            {
                _FirstFall.SetActive(false);
                _FirstFelll_secondPhase.SetActive(true);
                CancelInvoke("FirstWave");

            }
            if (_firstBossScipt.Firstdied == true)
            {
                _FirstFelll_secondPhase.SetActive(false);
                Invoke("SecondWaveLeft", 0f);
                Invoke("SecondWaveRight", 0f);
                Instantiate(_secondBoss, new Vector2(0.5764521f, -1.73f), Quaternion.identity);
                Destroy(_firstBoss.gameObject);
            }
        }
    }
}

```

But now my \_firstboss bool wont get called because I have destroyed my game object. Is there any other alternative for this?

# Answer
You will probably need another script to be your manager of this variable, like a "GameManager", and there you control if it is true or false.

```
using UnityEngine;

public class GameManager : MonoBehaviour
{
    public bool firstDied;

    void Start()
    {

    }

    void Update()
    {

    }
}

```

```
public GameManager gameManagerScript;

private void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.gameObject.tag == "circle")
    {
        healthPoints--;

        if (healthPoints <= 2)
        {
            firstTriggered = true;
        }

        if (healthPoints <= 0)
        {
            gameManagerScript.Firstdied = true;
        }
    }
}

```

That way you never lose the status of that variable, even if your object has been destroyed.

PS: To make it easier: you don't need to pull reference from the gameManager every time you need to use it, you can use a "Singleton" in it and just call it in every new script you have. (remembering that you can only have 1 gameObject containing the script that uses singleton in the scene)

**Singleton Tutorial:**

https://gamedevbeginner.com/singletons-in-unity-the-right-way/
> 0 votes

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


# Question
Title: Setting up sequential animation clips in Unity
I'm trying to play two animation clips sequentially using Unity 2D. I've been using Mecanim for this so I've imported the two clips in a newly created controller and connected the first one to the next one. I also want the last clip to be looping so I set that toggle in the settings of the clip.
Now for some reason the first clip is played just fine but the second one doesn't animate at runtime. It loops fine in the Animator window and the clip itself works in the preview window but not at runtime.

I've also tried setting it up using the Animation Component and use the PlayQueued method but this doesn't give any animation.

I'm kind of lost on what to try next

EDIT: This is to be used on a Canvas UI Image

# Answer
You can just setup a transition between the two animations like so:

So in this above example, once the RedBlink animation is done playing once, it will automatically start playing RedAngry animation.

Make sure to only set the Loop Time on the animation that you want to loop.
> 1 votes

# Answer
```
using UnityEngine;

[RequireComponent(typeof(Animation))]
public class VAB_AnimationTester : MonoBehaviour
{
    public AnimationClip[] clips;
    public bool loop = true;

    private Animation _anim = null;

    void Start()
    {
        _anim = gameObject.GetComponent<Animation>();

        QueueClips(clips);
    }

    void Update()
    {
        if (!_anim.isPlaying && loop)
            QueueClips(clips);
    }

    void QueueClips(AnimationClip[] animclips)
    {
        for (int i = 0; i < animclips.Length; i++)
        {
            _anim.AddClip(animclips[i], animclips[i].name);
            _anim.PlayQueued(animclips[i].name, i == 0 ? QueueMode.PlayNow : QueueMode.CompleteOthers);
        }
    }
}

enter code here

```
> 0 votes

---
Tags: unity, mecanim
---


# Question
Title: I'm trying to add gun shooting and cooldown into my 2d game
the problem i'm having with projectile is that it spawns on my cursor instead of my gunEnd, it also spawns with no force at all. I'm also having a problem implimenting a cooldown, I'm new to C# so this doesn't come naturally. this is the code for my gun.

As I said, I need help with both the projectile and the cooldown, Thanks.

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

public class shootBase : MonoBehaviour
{
    public float shootCooldown;
    public float force;
    public GameObject bulletPrefab;
    public GameObject gunEnd;
    private Vector3 aim;
    private bool canShoot;
    private float gunCooldown;

    void Start()
    {

    }

    void Update()
    {
        Vector3 mousePos = Input.mousePosition;
        //Shoot
        Camera cam = Camera.main;
        aim = cam.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, cam.nearClipPlane));
        if (Input.GetKey(KeyCode.Mouse0) && canShoot)
        {
            gunCooldown = Time.time + shootCooldown;
            GameObject bullet = Instantiate(bulletPrefab, aim, Quaternion.identity);
            Rigidbody b = bullet.GetComponent<Rigidbody>();
            b.AddRelativeForce(transform.forward*force);
            canShoot = false;
        }
        if (!canShoot && Time.time > gunCooldown)
            {
                canShoot = true;
            }
        if (gunCooldown < 0)
        {

        }
    }
}

```

Edit: I should add that this is my 1st ever project in C# except the basic stuff you do to learn the basics. Edit 2: My scripting seems to be fixed now, ill share the code i ended up with for my gun and bullet Gun Code

```
public class shootBase : MonoBehaviour
{
    public float shootCooldown;
    public float force;
    public GameObject bulletPrefab;
    public GameObject gunEnd;
    private Vector3 aim;
    private bool canShoot;
    private float gunCooldown;
    public long damage;
    public float lifeCycleEditor;
    public bool positive;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        positive = true;
        Vector3 mousePos = Input.mousePosition;
        //Shoot
        Camera cam = Camera.main;
        aim = cam.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, cam.nearClipPlane));
        if (Input.GetKey(KeyCode.Mouse0) && canShoot)
        {
            gunCooldown = Time.time + shootCooldown;
            GameObject bullet = Instantiate(bulletPrefab);
            bulletProperties.lifeCycle = lifeCycleEditor;
            bullet.AddComponent<bulletProperties>();
            bullet.transform.position = gunEnd.transform.position;
            var direction = aim - gunEnd.transform.position;
            Rigidbody b = bullet.GetComponent<Rigidbody>();
            b.AddRelativeForce(direction*force);
            canShoot = false;
        }
        if (!canShoot && Time.time > gunCooldown)
            {
                canShoot = true;
            }
    }
}

```

Script referenced in the code above in bullet.AddComponent.

```
public class bulletProperties : MonoBehaviour
{
    public static float lifeCycle;
    private float lifeCycleRemaining;

    // Start is called before the first frame update
    void Start()
    {
        lifeCycleRemaining = lifeCycle;
    }

    // Update is called once per frame
    void Update()
    {
        lifeCycleRemaining -= Time.deltaTime;
        if (lifeCycleRemaining <=0)
        {
            Destroy(gameObject);
        }
    }
}

```

# Answer
Check Unity API

>

```
Object.Instantiate

Declaration
public static Object Instantiate(Object original);
Declaration
public static Object Instantiate(Object original, Transform parent);
Declaration
public static Object Instantiate(Object original, Transform parent, bool instantiateInWorldSpace);
Declaration
public static Object Instantiate(Object original, Vector3 position, Quaternion rotation);
Declaration
public static Object Instantiate(Object original, Vector3 position, Quaternion rotation, Transform parent);

```

The second parameter is *position* rather than *direction*.

It might be code like:

>

```
GameObject bullet = Instantiate(bulletPrefab); //just create a GameObject instance
bullet.transform.position = gunEnd.transform.position; //set position
var direction = aim - gunEnd.transform.position; //get shoot direction
Rigidbody b = bullet.GetComponent<Rigidbody>();
b.AddRelativeForce(direction*force);

```

hope it helps :)

-----------Edit:

An example of destroying the bullet:

>

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

public class BulletScript : MonoBehaviour
{
    public float lifeTimeMax;
    private float lifeTimeRemaining;

    void Start() {
        lifeTimeRemaining = lifeTimeMax;
    }

    void Update() {
        lifeTimeRemaining -= Time.deltaTime;
        if (lifeTimeRemaining <= 0){
            Destroy(gameObject);
        }
    }
}

```

You can add it to your bulletPrefab :)
> 1 votes

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


# Question
Title: How to identify if entrace to HPA* cluster is faulty?
I have been working on my simple game where enemy would hunt me with A\* algo. But it was a bit slow so I found this thing called HPA\*. Someone who would decide to help me will probably know how it works but I shall explain how I wanted to do it until I found a limiting factor to my implementation.

First step would be to convert my map to certain sized clusers. For a 20*20 map I would have 4 10*10 clusers (trust me, the dimensions here are not to the scale, I just want to keep things simple while describing the problem).

For each cluser I would like to determine possible entrances. So if I was staring in the cluster where the blue circle is, I would:

1. check the edge that is shared by top left and top right cluster. Since top left cluster has that edge all blocked, then I would just return no position of entrance at all.
2. check the edge that is shared by top left and bottom left cluster. I would find that no point is blocked in top left cluster and 2 points are not blocked in bottom left cluster. These 2 points can serve as possible entrances to bottom left cluster. BUT one points is considered "faulty" and I want to know how to deal with this. I want to leave that entrance as valid, because someone might actually appear in that little hole but If my target was the red circle, I would want to dodge that "faulty" entrance.

My point is that I don't really know how to deal with HPA\* generally because I have 2 solutions in my mind. First solution would be to preprocess it and create an edge between all entrances and that would serve as my graph I could execute my A\* on. The second solution would be creating this abstract cluster grid, where each cluster would serve me as a node and I would firstly find my shortest path on this abstract layer before moving to another cluster. That would give me instructions like "execute A\* in the topleft cluster into botleft cluster because they are connected with entrances, then execute A\* in botleft cluster to botright cluster because they are connected with entrances." The problem is that if I would do that, the shortest path from botleft to botright cluster would lead me to the faulty entrance... Maybe I could floodfill the entrance and check if the floodfill hit the target. Or take all the entrances and execute A\* on every of them and check if it got me where I need to be.

# Answer
You have a set of entrances that define the connections between each map 'chunk'. These are the edges between the chunks.

You also need to keep track of the edges within each chunk (the intraedges) -- that is, all of the connections between the various entrance nodes of one given chunk. You can do this with regular A\* and cache the pathfinding cost, or make it infinite if there is no path between the entrances without leaving the current map chunk.

Once you have that, there is only one more obstacle: your destination node may not be an entrance, in which case you do not know the valid intraedges for that node. One solution is to use A\* to find the valid connections between your destination node and the other entrances of that chunk. Alternatively, you can run a depth first search in each map chunk to divide it into distinct disconnected 'regions' as part of your preprocessing. Then you simply compare the region ID of the destination node to the region IDs of each entrance in that chunk: different IDs means there is no path between them without leaving that chunk.

Example:

This is similar to the terrain in your question. I have added an additional set of obstacles in the upper right map chunk to demonstrate more clearly how you can mark connected regions.

This shows the entrances. Each entrance has an interedge to the adjacent entrance in the neighboring map chunk, and it also has a cache of all its intraedges to other entrances inside its own chunk.

This shows connected regions found by a depth first search. Notice the two islands in the upper right chunk that are surrounded by impassable nodes (the islands are regions '2' and '3' surrounded by the impassable region '0').

Pathfinding from the initial tile to the destination tile on the abstract layer. The entrances with white borders are the ones in the final path. Due to how we constructed the abstract representation of the map, we avoid falling into the dead-ends when we run A\* on the abstract layer.
> 0 votes

# Answer
During your pre-process step, pick a "center" point of each cluster (some non-obstacle point near the cluster center) and initialize its cluster ID to that cluster and its distance to zero. These tiles are your initial frontier. Every other tile gets initialized to a max or infinite distance.

Next, propagate distances outward from the previous frontier to adjacent reachable tiles. When a tile's distance decreases, add it to the frontier for the next iteration, and set its cluster ID to that of the tile it was reached from. Repeat until no further tiles get a decreased distance.

Now you have a cluster ID for each tile in the map that accounts for how that tile is actually connected to its parent cluster. So both sides of a "false entrance" should get assigned to the same cluster, and won't be regarded as a cluster-to-cluster connection at all.

(Here I use colour tint to indicate assigned cluster ID and brightness to indicate path distance from cluster center. Notice that the "false entrances" no longer bridge two different clusters)
> 0 votes

---
Tags: path-finding
---


# Question
Title: Can't select external script editor in Unity3D
in Unity3D 2020.3.32f1 when I try to select my external script editor via **Edit-\>Preferences-\>External Tools-\>External Script Editor** the file dialog opens and I try to select VSCode. So far so good.

Now the problem is that **I can't select any of the applications listed in the file-dialog window because all applications are greyed out!**

I have to mention that in my case Unity3D and Visual Studio Code are installed on an external SSD-drive on my Mac (using Big Sur 11.6.1). But this should be no problem at all.

My first thought was that the problem has to do with some file-permissions so I checked them but couldn't find something unusual. Also I checked the 'Security & Privacy'-prefPane and made sure that Unity3D has access to removable volumes.

Please, can someone help me out? TIA.

# Answer
> 3 votes
Actually, I just found an interesting (though cumbersome) workaround:

* Right click on the greyed file name
* Select "Quick Look"
* Close the "Quick Look" window
* Now the file will be highlighted and you can hit "open" (or double click).

---
Tags: unity, c#, visual-studio-code
---


# Question
Title: Is Quaternion math really practical knowledge for a graphics programmer?
I've recently had a graphics programmer interview and I was asked about math that is under the hood of quaternions. I briefly mentioned the formulas of using quaternions as rotations, but the interviewer was not satisfied and pushed me to tell more about complex numbers and other relevant stuff in order to reveal my understanding of this topic.

I should admit that my knowledge is mostly limited to linear algebra and I never really dug deep enough to feel confident about quaterions questions. On the other hand, however, after reading about it a bit, I couldn't see any practical sense in knowning how quaternions are defined, their algebraic properties, etc... So I wonder if in fact just memorizing formulas is more than enough (especially provided this whole topic is beyond linear algebra) or you really can be more effective at applying it if you get familiar with the quaternions math?

# Answer
> 2 votes
From my own experience, I've got 70 answers in the tag with 1350 total score, so to a first approximation, it looks like over 100 people (and their games) have benefited from me knowing something about the innards of quaternion math. (And that's not counting the other 143 answers that use quaternions without being so tagged)

Greatest hits include mapping 3D models from one coordinate system to a different coordinate system used in an engine, or using tricks to average multiple orientations, as well as working with IMU sensor inputs.

Anecdotally, I do observe a number of bugs arising from folks misunderstanding the components of a quaternion and using them in inappropriate ways - bugs I'm able to spot because I have a decent handle on the underlying math.

That I'd say is probably the main benefit of knowing the internals: instead of glazing over when you see some code doing quaternion math and just assuming they know what they're doing, your sniff test tells you "...wait a minute...!" and you spot things a more quaternion-phobic programmer might miss.

Quaternions are used for expressing and interpolating the poses of bones in animation and IK systems, and sometimes in orienting particles/ribbons in VFX systems, so it's reasonable to expect that as a graphics programmer you might occasionally touch code that works with quaternions in a low-level manner, manipulating imaginary numbers. Particularly in shader code, where you usually won't have a user-friendly library to abstract away the mathy details behind higher-level operations. Knowing tricks like the fact that a quaternion dot product gives a measure of similarity between two orientations can save you a pile of normalization and trig in performance-critical code.

So, I don't think it's unreasonable for an interviewer to ask a graphics programming candidate quaternion questions to gauge their confidence in this area. Or at least, no more unreasonable than tech interviews in general. Frankly, we have no idea how to interview candidates well in software generally, and games in particular. So, given that we have no idea what we're doing, I'd consider this line of questioning no worse than classics like "describe how to reverse a linked list". Is it an accurate guide to whether someone can do the job? No. Do we have a better filter? Unclear.

---
Tags: mathematics, quaternion
---


# Question
Title: How to replicate animated shader material from Maya in Unity without shader graphs?
I am new to shaders and experimenting with the free Unity shader forge plugin. Due to project limitations I am using Unity 2019.4 and cannot use Unity's shadergraph =(

I found this video, which exactly creates the effect that I am looking for. Unfortunately, it is done in Maya and I am quite lost how to replicate this effect, since I don't know how to integrate that noise. My shader works right to the point of the scrolling grid.

Any help would be appreciated, even if it's just a known name for this effect.

# Answer
> 1 votes
Well, the keyword here is *noise*. The person from the video is distorting the UVs from the mesh through a *noise field*. In your case, what you need is a **noise node**. I've never used Shader Forge before, but it should have a *gradient noise* or *noise* node.

This node should be mixed along the UVs from your mesh using an *Add node*, something like this:

The above example was done in Shader Graph, but should still work in Shader Forge. The premise is that the texture will follow the noise creating a distortion effect. This is a very common setup for creating caustics or water distortion shaders, of which there are many tutorials on the internet.

---
Tags: unity, shaders
---


title: Set Cell Not Creating Tiles in Godot

text:
# Question
Title: Set Cell Not Creating Tiles in Godot
I have a script in GDScript that contains a simple mouse position listener, and a `set_cell` function that sets a cell. For some reason, when I set the cell on my simulation, it doesn't spawn. The mouse position is set correctly, and the set cell position, when set to `(1, 1)`, works. But for some reason. This does not. Here is my code:

```
func _process(delta):
    var mouse_pos = get_viewport().get_mouse_position()
    var mx = mouse_pos.x
    var my = mouse_pos.y
    if Input.is_action_just_pressed("click"):
        set_cell(mouse_pos.x, mouse_pos.y, 0)

```

If you find a mistake, feel free to tell me, otherwise, have a nice day, and I appreciate your time.

# Answer
I'm going to bet it is creating them out of view.

---

First of all, you are getting the mouse position relative to the `Viewport`:

```
var mouse_pos := get_viewport().get_mouse_position()

```

And second `set_cell` wants map coordinates. We can convert local coordinates to map coordinates with `world_to_map`. But first we need to get the mouse position in local coordinates.

We can try getting it out of `get_viewport().get_mouse_position()`, which I believe would be like this:

```
var mouse_pos := make_canvas_position_local(get_viewport().get_mouse_position())

```

Or better yet, take the mouse position in local coordinates already:

```
var mouse_pos := get_local_mouse_position()

```

Once we have the local mouse position, we can convert local coordinates to map coordinates:

```
world_to_map(mouse_pos)

```

And since that is a vector, let us use `set_cellv`:

```
var mouse_pos := get_local_mouse_position()
# …
set_cellv(world_to_map(mouse_pos), 0)

```
> 1 votes

---
Tags: godot, gdscript
---


# Question
Title: How to generate reliable labels for game state using Python and Pygame
I've been looking into making a small game where you would walk around and do puzzles (perhaps do some combat if I can get the basic framework going). So far, Googling for general game patterns used in these types of situations produces an event-oriented approach, I.e, send an event every time the player moves / tries to interact with anything / does anything potentially of interest. This makes sense. What doesn't make sense is the storage of items / game state. I found a similar question concerning textual RPGs, but all the techniques seem to be inflexible. Suppose that I have two areas, a forest and a city. In the city, Bob wants you to go into the forest and find an apple or two to satisfy his hunger. He gives you two different responses (the first time he asks you for the above favor, and any other time he sorrowfully reminds you that he's slowly starving while you're doodling around). Here is my thought process.

1. Player enters area--load a Lua script pertaining to said area that registers necessary event hooks (hook like interact with bob)
2. When the player talks to Bob, assign a "tag" to the player.

Here is the issue: What should the tag be? I can't just do "talked\_with\_bob" because there may be multiple Bobs in the game. I can't assign a tag within the script that says "talk\_with\_bob\_at\_the\_city" because although there will be no map duplicates, what if the map names change? That would force me to go and reupdate my scripts. Almost done. I promise. Let's say that you do figure out your tag problem. You go into the forest, grab an apple, but as you were leaving you spot a chest. You open it, find some loot, and move on. My question is... should this also be tagged, and if so, how? A chest shouldn't magically refill every time you enter the map, so it must store its state somewhere, hence the tag idea, but then we're back to the problem of generating reliable names for the tag(s) and more importantly, constructing valid tag queries. As an aside, if I create a "tag" for every single event that has the possibility to be different, won't this grow huge, or should I not worry about memory constraints until it becomes a problem? The question I linked to above was the closest match to my query, but as you can see it doesn't entirely address it. I appreciate any insight

# Answer
> 0 votes
I think this issue is about *data persistence*. The point is how to organize the game save data.

There is no one-size-fits-all solution to this. But in this special case you could try an object oriented approach. It's easier to expand.

For example, you don't need a "tag" named *"talked\_with\_bob"* in player's save data , but a variable named *"is\_talked"* or *"talked\_times"* in Bob's.

If there is more advanced requirements(record talk times by different place), you can define some data structure else for Bob. Such as a dictionary "talk\_times\_map", the place you talk for the key and the times for the value.

---
Tags: python, pygame, game-state
---


# Question
Title: How to make object follow the mouse OpenGL?
I am trying to move an object on the 2D plane to follow the mouse position.

I converted the mouse's XY and depth buffer value to world space coordinates, but the problem is that when I run the program, the object is really far away. When I move the mouse, the object follows it, but also it is rotating on the Y and X axes.

What I want is for the object remain at its current Z coordinate and be able to move it up and down with mouse. Is my IDE incorrect or did I make a mistake in implementation?

I also know about this approach and I tried to implement it, but a few problems have occurred. I take mouse position X, Y and the depth buffer value and convert it to word space coords and then save those in the variables **position** and **last\_posiiton**. Now the problem is that I need a plane that is parallel to the near and far plane. To check if mouse "position" and mouse and "last\_position" intersect it I need its normal vector and it's origin. How do I get those two parameters?

Code I have so far:

```
#include <iostream>

#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/intersect.hpp>

#include "VBO.h"
#include "VAO.h"
#include "EBO.h"
#include "Camera.h"
#include "Shader.h"

#include "Cube.h"

void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void mouse_callback(GLFWwindow* window, double xpos, double ypos);
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset);
void processInput(GLFWwindow* window);

const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;

float getObjectsDephtValue(float zComponent);

Camera camera(glm::vec3(0.0f, 0.0f, 3.0f));
float lastX = SCR_WIDTH / 2.0f;
float lastY = SCR_HEIGHT / 2.0f;
bool firstMouse = true;

float deltaTime = 0.0f;
float lastFrame = 0.0f;

int main()
{
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    GLFWwindow* window = glfwCreateWindow(800, 600, "Hello Window!", NULL, NULL);
    if (window == NULL)
    {
        std::cout << "Failed to initialize GLFW" << std::endl;
        glfwTerminate();
        return -1;
    }

    glfwMakeContextCurrent(window);

    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
    {
        std::cout << "Failed to initialize GLAD" << std::endl;
        return -1;
    }

    glViewport(0, 0, 800, 600);
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
    glfwSetCursorPosCallback(window, mouse_callback);
    glfwSetScrollCallback(window, scroll_callback);

    //glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

    glEnable(GL_DEPTH_TEST);

    glm::mat4 projection = glm::mat4(1.0f);
    glm::mat4 view = glm::mat4(1.0f);
    glm::mat4 model = glm::mat4(1.0f);

    Cube cube1(1.0f, "D:/Textures for OpenGL/container.jpg", &view, &projection);
    Cube cube2(1.0f, "D:/Textures for OpenGL/grass.jpg", &view, &projection);

    glm::vec3 last_windows_coords(0.0f);

    while (!glfwWindowShouldClose(window))
    {
        float currentFrame = glfwGetTime();
        deltaTime = currentFrame - lastFrame;
        lastFrame = currentFrame;

        processInput(window);
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        projection = glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
        view = camera.GetViewMatrix();

        double xpos, ypos;
        glfwGetCursorPos(window, &xpos, &ypos);
        ypos = 600.0f - ypos;

        GLfloat depth_comp;
        glReadPixels((int)xpos, (int)ypos, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth_comp);

        glm::vec4 viewport = glm::vec4(0.0f, 0.0f, 800.0f, 600.0f);
        glm::vec3 windows_coords = glm::vec3(xpos, ypos, depth_comp);
        glm::vec3 last_position = glm::unProject(last_windows_coords, view * model, projection, viewport);
        glm::vec3 position = glm::unProject(windows_coords, view * model, projection, viewport);

        cube1.move(position);
        cube1.draw();

        cube2.setPosition(glm::vec3(0.0, 0.0, -3.0));
        cube2.draw();

        last_windows_coords = windows_coords;

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwTerminate();
}

```

# Answer
Since you are clearing the depth buffer at the beginning of each frame this call will always return the same value, so it's not clear to me why you are doing this:

```
glReadPixels((int)xpos, (int)ypos, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth_comp);

```

you are sampling an "empty" buffer.

To get the world position of a point that sits on a plane somewhere between the near and far plane you could do something like the following:

```
    // Projection of a point on a plane that sits halfway between near and far
    glm::vec4 myParallelPlaneProjection = (projection * glm::vec4(0, 0, -(near + (far - near)*0.5f), 1.0f));
    float myParallelPlaneDepth = myParallelPlaneProjection.z / myParallelPlaneProjection.w;

    glm::vec4 viewport = glm::vec4(0.0f, 0.0f, 800.0f, 600.0f);
    glm::vec3 windows_coords = glm::vec3(xpos, ypos, myParallelPlaneDepth);
    glm::vec3 position = glm::unProject(windows_coords, view * model, projection, viewport);

```

For the rotation issue I came up with this solution:

```
// Setting an appropriate model matrix for an object we want to keep "parallel" to the camera planes
cube1.Transform(glm::inverse(glm::lookAt(position, position + camera.Front, camera.Up)));

```

which is probably not ideal.

However, if this is the result you are looking for it should do the job (using a cone for a better reading of the scene):
> 2 votes

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


title: Disable spaces in InputField

text:
# Question
Title: Disable spaces in InputField
This is straight forward. I have an input field and I want to restrict the user of inputting any spaces. I was thinking to make a script that checks if the user typed in a space and then remove it, but is there a simpler way of doing this?

# Answer
> 2 votes
There is an easy solution IF you only require alphanumeric characters (alphanumeric characters include: a-z,A-Z,0-9). In the input field, change the content type to alphanumeric. This will only allow letters and numbers, not spaces.

You can also try out the other options too. Otherwise, if you require symbols too, you will have to use a script with a checking function that removes spaces. This would be initiated by the On Value Changed, which you can also se in the image.

I can quickly code an example script if you want me to.

EDIT: OK, I have made an example script and will show you how to use On Value Changed. Start by making a new c# script called 'UpdateInputField' and replace the text with this:

```
using UnityEngine;
using System.Collections;
using UnityEngine.UI;// this is needed to use the 'InputField'

public class UpdateInputField : MonoBehaviour
{
    InputField IF;
    void Start()
    {
        IF = GetComponent<InputField>();//get the input field
    }
    public void UpdateField()
    {
        string text = IF.text;//get text from input field
        text=text.Replace(" ","");//fliter spaces from text
        IF.text = text;//set the text in the input field to the filtered text
    }
}

```

Go and add this script to the input field object. Next, click on the + sign on 'On Value Changed': Then click on the bottom left box. In the window that appears, find the input field object in your scene and select it.

After that, click on the top right box and select UpdateInputField, UpdateField()

And that should be it! The OnValueChanged part automatically calls the UpdateField() function in the script whenever the input field is typed into. The UpdateField() function will then filter any spaces from the text and then set the text in the input field to the filtered text.

# Answer
> 2 votes
My solution to disable 'tab' symbol in input field. You can disable any other symbols

```
using UnityEngine;
using UnityEngine.UI;

public class ConsoleInputController : MonoBehaviour
{
    private InputField consoleInputField;

    // Start is called before the first frame update
    public void Start()
    {
        consoleInputField = GameObject.Find("ConsoleInputField").GetComponent<InputField>();
        // Sets the DisableTabValidate method to invoke after the input field's default input validation invoke (default validation happens every time a character is entered into the text field.)
        consoleInputField.onValidateInput += delegate(string input, int charIndex, char addedChar) { return DisableTabValidate(addedChar); };
    }

    private char DisableTabValidate(char charToValidate)
     {
         //Checks if a tab sign is entered....
         if (charToValidate == '\t')
         {
             // ... if it is change it to an empty character.
             charToValidate = '\0';
         }
         return charToValidate;
     }
}

```

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


# Question
Title: My Unity application is on the left side
Today I made a Unity 2D app with a square moving around and I wanted to know why is the alignment on the left.

Here are some screenshots:

# Answer
> 0 votes
I set my camera viewport viewport rect to W 0.5 and H 1.
I had to change the X to half of W.
So if you change the W then you need to change your X to half of W, and if you change the H then you need to change Y to half of H for the viewport to be aligned in the middle.

---
Tags: unity, 2d
---


# Question
Title: Unity seems to be stuck rendering through camera outside of play mode
This may or may not be a dumb question, as I am very new to Unity, but for some reason Unity is rendering through a camera after exiting play mode.

I had this issue with another project originally, so I created a new project to see if it was an error with my scripts or animations. However, even in a blank project with nothing but a square within the camera's FOV, I still can't edit my scene.

The same issue occurs with pause mode, as well. When I am playing my game, and want to test an adjustment, it just freezes my scripts and camera playback.

Help would be greatly appreciated! Thanks in advance!

# Answer
You're in the Game tab. Look at the top of the game view where you see the tabs "Scene", "Game", and "Asset Store". Click the Scene tab to go back to the scene view.

You can drag these tabs apart so each one has a separate place in your editor UI, so that one never hides the other.
> 0 votes

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


# Question
Title: Combining palette-swaps and smooth scaling in a pixel-art shader
I am creating a pixel-art game in MonoGame, and have written a shader to perform various effects on a sprite when rendering it, such as performing palette swaps, highlighting outlines, etc.. Most of these effects work by comparing the color of a texture coordinate with a reference color, and if they match then the color is swapped for another. Simple stuff as long as you use nearest-neighbor filtering on the texture. (These effects are used in a very dynamic way, which is why they are done using a shader instead of, say, a separate texture-atlas for each color palette).

However, in the game there is quite a lot of floating-point camera scaling and movement going on, resulting in choppy-looking visuals when using nearest-neighbor filtering. Luckily there is a way of scaling pixel-art that looks much smoother without taking away the crispness, which is to use a texture with bilinear filtering enabled but only use interpolated colors on the boundary between pixels. Here and here are a couple of open-source shaders using this technique.

The problem is of course that you cannot do palette-swaps on a texture with bilinear filtering because the colors are all blended together. In other words the two aforementioned techniques seem to be completely incompatible with one another, yet I really need both of them.

As far as I can tell the logical solution would be to perform the palette-swapping and similar effects on the texture before scaling and filtering it, however I have no idea of how to actually do this from within a shader, and what the performance implications of doing so would be.

I am still very much a novice when it comes to shaders, so any help here would be deeply appreciated!

# Answer
> 1 votes
*I'll be writing GLSL because I'm more familiar with it, and it is easier for me to test.*

This is what I have been able to come up with:

1. Split the `uv` coordinates into integer and fractional and pixels:

```
vec2 fuv = floor(uv / pixel_size);
vec2 wuv = fract(uv / pixel_size);

```

Here I'm assuming `uv` goes from `(0.0, 0.0)` to `(1.0, 1.0)`, and `pixel_size` is the inverse of the size of the texture in pixels.
2. We are going to query the four pixels around the `uv` and apply pallet swapping to the colors we get:

```
vec4 lox_loy = palette_swap(texture(TEXTURE, (fuv + vec2(0.0, 0.0)) * pixel_size));
vec4 lox_hiy = palette_swap(texture(TEXTURE, (fuv + vec2(0.0, 1.0)) * pixel_size));
vec4 hix_loy = palette_swap(texture(TEXTURE, (fuv + vec2(1.0, 0.0)) * pixel_size));
vec4 hix_hiy = palette_swap(texture(TEXTURE, (fuv + vec2(1.0, 1.0)) * pixel_size));

```

I'm, of course, assuming you have a `palette_swap` function that takes a `vec4` and outputs a `vec4`. This would allow you to keep the approach you are currently using, or change if you need.

I'm also assuming nearest-neighbor filtering. We are going to do bilinear filter later.

For reference, this is how you would query at `uv`:

```
vec4 color = palette_swap(texture(TEXTURE, uv));

```

And I'm making new coordinates to query the texture (i.e. to replace `uv` in the above statement). I start with `fuv`, but since `fuv` is in pixels we need to multiply by `pixel_size`:

```
fuv * pixel_size

```

And I want to offset it by whole pixels, so I would something like this:

```
fuv * pixel_size + vec2(off_x, off_y) * pixel_size

```

As you can see `pixel_size` is a common factor, so we rewrite that:

```
(fuv + vec2(off_x, off_y)) * pixel_size

```
3. Now we are going to apply the sharpen algorithm from Beefster09 that you linked, but only to the fractional part of the pixel coordinates:

```
vec2 norm = (wuv - 0.5);
vec2 norm2 = norm * norm;
wuv = norm * vec2(pow(norm2.x, sharpness), pow(norm2.y, sharpness)) + 0.5;

```

This code assumes `sharpness` is a `uniform float`, and I remind you that `wuv` is a `vec2`.
4. Then we apply simple bilinear interpolation using the result as weights:

```
vec4 output =  mix(mix(lox_loy, hix_loy, wuv.x), mix(lox_hiy, hix_hiy,
wuv.x), wuv.y);

```

Since we are interpolating the colors after the palette swap there should not introduce artifacts.

And that is our output color.

---

By the way, for testing this I came up with a different palette swap approach. I decided to use the corners of the RGB cube as reference (so, up to 8 colors), and apply a different color from the palette to each quadrant. Plus a cutoff for alpha. It looks like this:

```
vec3 hi = step(vec3(0.5), input.rgb);
vec3 lo = 1.0 - hi;
vec3 output = palette[0].rgb * lo.r * lo.g * lo.b
            + palette[1].rgb * lo.r * lo.g * hi.b
            + palette[2].rgb * lo.r * hi.g * lo.b
            + palette[3].rgb * lo.r * hi.g * hi.b
            + palette[4].rgb * hi.r * lo.g * lo.b
            + palette[5].rgb * hi.r * lo.g * hi.z
            + palette[6].rgb * hi.r * hi.g * lo.z
            + palette[7].rgb * hi.r * hi.g * hi.z;
return vec4(output.rgb, step(0.5, input.a));

```

Here `hi` will have components of value `0.0` or `1.0` depending if the components of `input` are lower or higher than `0.5`. And `lo` will be the opposite (`0.0` on the components where `hi` is `1.0`, and viceversa). The products of the components of `lo` and `hi` allow me to make factors that are `1.0` in only one quadrant of the RGB cube, and by doing that I'm giving a different color from the `palette` to each quadrant.

# Answer
> 1 votes
I had a few more hours to think about the problem before Theraot provided their excellent answer, and came up with a different (albeit much more naive) solution that may also be worth describing. The idea is to create a RenderTarget2D with a resolution large enough to fit all sprites drawn in a frame. Then draw each sprite onto the render target at a 1:1 scale, and at the same time apply the palette-swapping and similar pixel-effects (of course keeping track of where you place them). Afterwards you upscale them and render them onto the screen one-at-a-time.

When compared to Theraot’s solution this approach has one obvious downside, which is that you need to draw every sprite twice. However, you only need to apply the palette swap effect one time per pixel as opposed to four times per fragment, which might add up if the palette-swap (etc.) function is slow enough. Another downside with this approach is that, unless your sprites all have similar dimensions, it will be a challenge to find an efficient way of packing them onto the render target.

---
Tags: shaders, monogame, fragment-shader, pixel-art, palette-swapping
---


# Question
Title: Using perlin noise as a procedural voxel heightmap without a texture atlas in Unity
I was creating a heightmap for my procedural voxel world in Unity using 2D perlin noise. I don't want to use anything from a texture atlas, a brown Unity material is good enough for me. The issue is that I cannot seem to replace what would be "air blocks" by deleting voxels in the grid above a certain height threshold.

I have a function to check whether or not a voxel is above the heightmap, but when I play the scene I'm still left with large cube shaped chunks. Any idea why this isn't working? Thanks in advance and let me know if additional information is needed.

```
    bool CheckVoxel(Vector3 pos)
    {

        int x = Mathf.FloorToInt(pos.x);
        int y = Mathf.FloorToInt(pos.y);
        int z = Mathf.FloorToInt(pos.z);
        int terrainHeight = Mathf.FloorToInt(Noise.Get2DPerlin(new Vector2(pos.x, pos.z), 1.0f, 0.5f)) + 50;

        // If position is outside of this chunk...
        if (x < 0 || x > VoxelData.ChunkWidth - 1 || y < 0 || y > VoxelData.ChunkHeight - 1 || z < 0 || z > VoxelData.ChunkWidth - 1)
            return false;
        // If position is above the height map position...
        else if (y > terrainHeight)
            return false;
        else return true;
    }
    //now just check voxels and create our mesh
    void AddVoxelDataToChunk(Vector3 pos)
    {

        for (int p = 0; p < 6; p++)
        {

            if (!CheckVoxel(pos + VoxelData.faceChecks[p]))
            {

                vertices.Add(pos + VoxelData.voxelVerts[VoxelData.voxelTris[p, 0]]);
                vertices.Add(pos + VoxelData.voxelVerts[VoxelData.voxelTris[p, 1]]);
                vertices.Add(pos + VoxelData.voxelVerts[VoxelData.voxelTris[p, 2]]);
                vertices.Add(pos + VoxelData.voxelVerts[VoxelData.voxelTris[p, 3]]);

                triangles.Add(vertexIndex);
                triangles.Add(vertexIndex + 1);
                triangles.Add(vertexIndex + 2);
                triangles.Add(vertexIndex + 2);
                triangles.Add(vertexIndex + 1);
                triangles.Add(vertexIndex + 3);
                vertexIndex += 4;

            }
        }

    }

    public void CreateMesh()
    {

        Mesh mesh = new Mesh();
        mesh.vertices = vertices.ToArray();
        mesh.triangles = triangles.ToArray();
        mesh.uv = uvs.ToArray();

        mesh.RecalculateNormals();

        meshFilter.mesh = mesh;

    }

```

# Answer
> 0 votes
This was a bad question. I forgot a reference to my chunk height in the noise function, so it was just setting y to be between 0 and 1 until i multipled by chunk height.

---
Tags: unity, c#, procedural-generation, voxels, perlin-noise
---


# Question
Title: How to find "roll" relative to horizontal
To avoid gimbal lock, I use quaternions for my rotations. For example, to roll I use this function:

```
FQuat rollRot(float multiplier)
{
    return FQuat::FindBetweenVectors(mesh->GetUpVector(), mesh->GetRightVector() * multiplier + mesh->GetUpVector() );
}

```

It works fine as long as I don't need the current "roll" value.

I cannot just take the x Euler angle of my rotations. For example, in these cases I would expect roll value of 10, but it is 90 and 180:

# Answer
If you had no roll, your local right vector would point along \\$\text{world up} \times \text{local forward}\\$ (ie. flat along the horizontal plane, while staying perpendicular to your local forward vector)

So you can compute the angle between your actual local right vector and this one to get your roll angle. The z component of your local right vector gives you the sign of the angle.
> 1 votes

---
Tags: 3d, rotation, unreal-4, quaternion
---


title: Method of compressing tile data

text:
# Question
Title: Method of compressing tile data
I'm making a game in which a row of tiles may look something like this, in which each block is represented with a unicode char:

“gggggggggggggggggggggggggggggggggggtttttttttjjjjjjjjjjjjjjj”

So my method of compression shortens it to this (I may have the numbers wrong, it is just for demonstration):

“g23 t9 j17”

Seems fairly simple right?

My friend suggests to use an enum and represent each block with a number and work with bytes, reasoning that numbers are faster to compare

So it may look something like this 0001 0002 0004 0003 0034

I said that using this is pain, and saving a few ms isn't gonna help the pain I have to go through

I'm using C# and Unity, which method should I use for compressing world data?

# Answer
> 1 votes
> My friend suggests to use an enum and represent each block with a number and work with bytes, reasoning that numbers are faster to compare

If you write your files as utf8, then you are effectively doing this in your uncompressed method: each utf8 char is a number in the same range as a byte (8 bits). If you started doing bit packing, then number method would be more efficient: it would allow you to fit multiple blocks into a byte (depending on the number of block types). However, using `char` gives you the advantage of creating levels in a text editor and it's easier to understand the level data seen in your watch window.

The compression scheme you're describing is Run-length encoding. It would definitely be more efficient if you wrote your counts as numbers instead of strings.

However, for the compressed version you might be better off using an existing compression library instead of doing something painful. It's pretty simple to use SharpZipLib to decompress files. While you could likely get a higher compression ratio with a custom scheme, it's pain you could avoid and unlikely to be worthwhile unless your world data is measured in GB.

I'm assuming you're only concerned about the disk size of your world data since your runtime data will presumably be constructed world objects (tileset images, collision, etc) and you'll discard the level definition after load.

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


# Question
Title: How can I run a shader over the entire screen without interfering with other running programs?
How can I run a shader over the entire screen without interfering with other running programs? Specifically, I'd like to adjust the screen output with usability tweaks for my severely colorblind nephew. He has trouble playing certain games.

I'd like to avoid hooking into DirectX, and just run a shader over the entire screen. Is this something I can do in Windows without draining an unreasonable amount of resources?

I can use whatever language or tool is most practical for this, but I'm most comfortable with Java and HLSL.

# Answer
> 2 votes
if you are trying to make a screensaver for example, they most usually go with screen capturing one time, then create a fullscreen borderless window and draw over the picture they took. Some games where you "destroy your desktop" with a hammer and it breaks in glass fashion, or other effects, also works like that. Some virus/jokes, also do that.

If you want to apply a global effect that is always going to be there for all the session whatever the application, you would need to write a new window manager (dwm). Try linux first, probably easier. check xpenguins, or xsnow. (though they probably use lots of small windows).

# Answer
> 1 votes
For your specific use-case, Windows 10 actually has built in filters for the task. (I am fairly sure they would work on games as well).

This page has a quick tutorial: https://support.microsoft.com/en-us/windows/use-color-filters-in-windows-10-43893e44-b8b3-2e27-1a29-b0c15ef0e5ce

And this link should open settings to the correct page.

Or without clicking links: Go to Windows 10 Settings \> Ease of Access \> Color Filters

There are options for Deuteranopia, Protanopia, and Tritanopia.

# Answer
> 1 votes
You've got a few options. It might not be sufficient for your needs, but the simplest way to affect the Windows desktop's colors would be to use `MagSetFullscreenColorEffect`. It lets you apply a 5x5 color transformation matrix.

Specifically for games, ReShade lets you apply your own shaders to a game's output. It can hook into Direct3D, OpenGL and Vulkan applications.

Lastly, a true desktop-wide solution is also possible. This can be achieved by hooking into DWM, copying dirty rectangles from the back buffer to a separate texture, then sampling that texture in a pixel shader that writes to the back buffer again. The only applications this won't work for are exclusive fullscreen ones, as those bypass the compositor. I've implemented this myself here for the purpose of color correction.

# Answer
> 0 votes
I don't really understand what is it that you're trying to do, but as far as I know, no, you can't do that.

Oversimplifying, each window draws to a different texture, and the Desktop Window Manager (DWM) composes all of those textures into one big full screen texture, which is what you see.

Generally, the DWM composition pipeline is a core part of Windows, and there are no documented ways that I know of to hook into it to mess with the composition. I am pretty certain this part is extremely optimized to run as fast as possible, and allowing people to hook into it would certainly create performance and stability issues.

It may be possible for a specific graphics driver to allow you to hook into the pipeline after composition has finished, but first: I don't know of any driver that would let you do that; and second: any program you make would only work on computers with that specific driver.

Without understanding what is it that you're trying to do, it's very difficult to give you alternate solutions, but if you want to create effects as screensavers do, you could do as v.oddou says: take a screenshot, and apply any modifications you wish to it, and then drawing it full-screen. Obviously, the displayed windows won't be interactive, since you're just showing a modified screenshot.

What is it that you're trying to do?

# Answer
> -1 votes
Intel Solution: Open GfxUI/ Intel Graphics Command Centre Go to colours/colors set the option to rgb and slide the toggles to match what you want (less/more red blue & green)

Nvidia Solution: Open NVidia Control Panel Go to the colour/color/display section Set your theme/colours/colors (i cant guide you further as i only have experience with intel devices)

Was this helpful?

---
Tags: shaders, windows, usability
---


# Question
Title: How are transformation matrices usually represented?
I know the bare minimum to do matrix multiplication and have implemented them from scratch a few times for various purposes, but every time I do, I make sure to be very clear to myself about where are the basis vectors.

I dont think of matrices as big squares of numbers, but as arrays of vectors where each component is.. well, a basis component.

But as I have learned about matrices through alternate means, I have no idea of how this commonly used notation works, and if there's an implicit common sense way to distribute the basis vectors.

people usually write matrix multiplication in the following notation:

but its very ambiguous to me how to interpret it. my brain is drawn by the visual layout to interpret it as the following:

but most people seem to actually mean this:

so which is the correct way to interpret it?

# Answer
> 0 votes
Neither of the pictures you've shown corresponds to matrix multiplication, in which each row of the matrix is multiplied (as a dot product) with the full column of the input vector to produce one component of the output vector.

Your modified second drawing is closer, where you can think of the output as a linear combination of the columns of the matrix, with the components of the input forming the weights.

If you're wondering how to interpret the rows or columns of the matrix, then in the form you've shown, each column of the upper-left 3x3 submatrix is a basis vector of the destination space. So the left column is the image of (1, 0, 0) after multiplication, the middle column is the image of (0, 1, 0), etc. The fourth column is the translation: the image of (0, 0, 0).

I explain this interpretation in more detail in this older answer.

---
Tags: mathematics, matrix, projection-matrix
---


# Question
Title: Vertex Displacement Shader Graph With The Camera Moving Issue
I have a foliage sway shader, that works well.

But when the camera moves the vertex displacement stops:

And the weird thing also is that if I move the camera to the right nothing seems to happen, but moving the camera only to the left causes the issue.

Googling shows that the position node's world space takes camera position into account, and the presumed fix is to change all position nodes to absolute world space, and also make the transform node convert from absolute world to object space. But that didn't fix it sadly. Any ideas could help, thank you.

# Answer
> 0 votes
For anyone that has the same problem, you can replace the Position node that feeds the GradientNoise UVs with the UV node. You can find more details here.

---
Tags: unity, camera, movement, unity-shader-graph, vertex-shader
---