#archived-shaders

1 messages · Page 45 of 1

regal stag
#

Hmm well, the bias should more be on the Position used to sample the shadows, not on the attenuation value after it

regal stag
#

Hm no, that looks okay

tight phoenix
#

That's the inside of the 'Mesh Depth' node pictured above

regal stag
#

Ah I see

tight phoenix
#

the full flow ignoring other stuff unrelated going on bellow

regal stag
#

Those bias are applied during the ShadowCaster pass, which is used when rendering objects into the shadowmap. So there isn't a way around it that I can think of, apart from the offset we're doing.

#

Provided that offset is larger than the normal bias it should look fine though?

tight phoenix
#

doing a gif capture of what different values do

#

changing the bias to be any larger than 0.05 produces jank

#

I am going to try to frame debugger step by step a scene with just this one mesh and nothing else in it

#

nuts, debugger didnt show anything useful

#

the first time you can see the mesh the problem is already there

#

the output of Mesh Depth with and without Normal Bias from the URP renderer

#

maybe the problem is that the bias we're applying isnt biasing it in the same direction that the normal bias that unity is using does 🤔

#

adding bias healed SOME of the jank but not all

midnight wren
#

mm, there is no ComputeShader.SetUInt, how do you set unsigned ints?

tight phoenix
regal stag
tight phoenix
regal stag
#

I'm not sure why my code block isn't formatting properly

tight phoenix
#

oh link is good

tight phoenix
# tight phoenix

this is me trying to fill in all the values, still getting pink atm only half done

#

hm it seems pissed about the names but wont let me change the names

regal stag
#

Gotta sleep so good luck. If you post any more messages may want to move into the #1099329453106143242 thread or make another so you don't fill up the chat here

midnight wren
#

Does Compute Shader has a PI constant?

prime shale
#

no

midnight wren
#

Oh

full loom
#

can somebody explain the difference between the scene depth sampling modes. I've looked at the api and don't really understand them

lunar valley
lunar valley
#

the vertecies the material is assigned to

umbral hemlock
# full loom can somebody explain the difference between the scene depth sampling modes. I've...

I’m not really sure but my guess is that “Eye” is for VR applications (so maybe it gets two values, one for each eye). Linear01 returns the depth value as a linear value where 0 is closest to the camera and 1 is max distance from camera (the camera’s far plane). Raw probably returns the raw depth value, which is not guaranteed to be linear. I’m not sure if you’re familiar with how depth values are stored, but you can read the “Using depth textures” page on the docs for more info. Lmk if you want more detail. (I’m guessing you’ll most likely want to use Linear01)

lunar valley
#

eye depth or view depth is the to the cameras perpendicular distance between the near clipping plane of the camera and some position in the scene

umbral hemlock
full loom
#

I don't know if anybody has ever had this specific issue and I don't really know how to explain it, but I have the artifact that always appears from depth based outlines, so I fixed it using a fresnel, but adding fresnel causes it to erase the outlines on objects in front of where the fresnel would normally be applied. Does anyone know any other ways to fix the first artifact that doesn't cause the second?

#

The first artifact is the black face on the left and the second are the missing parts of the outline by the way

full loom
lunar valley
full loom
# lunar valley hard to say, we don't know how you did your outline, we only know that you used ...

I'm basically just checking a 3x3 radius around each pixel, and then if the depth increases by a certain threshold, it will draw an outline. The way that I fix the artifact is by removing parts of the outline where the faces of the object they are on are at a steep angle relative to the camera view. This makes it so that the object behind can remove an outline of the object in front if it is steep which causes the second artifact.

lunar valley
#

it depends...

meager pelican
calm citrus
#

So I have this water shader

#

yet when im in play mode

#

it is invisible

#

URP project

#

Any ideas?

umbral hemlock
sweet burrow
#

Is there a property a script could use to check if a material/shader has shadowcasting enabled?

serene stream
#

Hi, I am using Shadergraph and URP, for some reason my material always mixes to one solid color when I apply it to my sphere (not the usual sphere but a code-generated one)
Is there any settings or anything I need to change in order to make it work?
P.S.: when I apply that same material to a unity sphere it shows the texture just fine, so it is the generated spheres fault, but no clue why)

The left one is the usual unity sphere, the right one my generated sphere made of 6 meshes

lunar valley
serene stream
serene stream
lunar valley
lunar valley
regal stag
regal stag
# calm citrus it is invisible

If the water shader uses the Scene Depth node, make sure the Depth Texture setting is enabled on the URP Asset. Same goes for Scene Color node and Opaque Texture setting.
I'd also double check the water plane even has a draw call by using the Frame Debugger window too. Perhaps something is culling it? Culling Mask on camera?

calm citrus
calm forge
#

I'm trying to displace the vertex position on the edges only, is this possible?

worldly path
#

Hi everyone, I'm working on a project for my masters thesis, and I've got a seemingly simple problem that I just can't solve.
I'm trying to put a texture on a terrain, however, I've got a picture that I want to use as a texture for the entire terrain, and not as paint as the terrain tools provide.
I'm sorry if this is in the wrong channel.

full loom
misty crown
#

Hey there! Question… I am using Unity URP, and I am wondering how to use a roughness map in the metallic map surface input? Can I simply inverse the colors of the roughness map in Photoshop – Or is it more involved? Thank you!

spring fox
misty crown
spring fox
#

It works for all render pipelines

spring fox
#

When your putting your roughness map in, enable import as roughness

#

Unity uses smoothness which is roughness inverted

misty crown
#

Awesome thanks @spring fox

silk wharf
#

Hello there, I want to start learning compute shaders for processing large data, but I cant seem to find a guide or tutorial that covers my needs; all the things I have seen use a Texture as tutorial and what I need is just pass and retrieve data, specifically I need to output float or int values (I want to do perlin noise calculation in a compute shader) does anyone know any guide for this?

#

not for perlin noise itself but for processing data different to textures in compute shaders

silk wharf
hot wedge
#

Hi im creating basic forest but im having some white things problems on shaders/materials
could anyone explain me what could that possible been the cause of this problem / URP

midnight wren
# lunar valley it depends...

I know it depends of each function. But I can't find any guide which explains how do you determines that.
I only found that 32 and 64 are minimum preferential numbers used by AMD and NVIDIA, so 64 is usually the minimum used. Apart for that, you should always use multiples of that number to avoid wasting threads... but no guide tells you when is good idea have more than that, like 128 or 256.

lunar valley
#

when to use single thread groups, when to use two thread groups when to use large once and so on

next solstice
#

I'm trying to make a scrolling / paralax background for my game. I want to have multiple layers that scroll at different speeds. I'm able to move the uv of my sprite renderer like sprite.material.SetTextureOffset("_MainTex", camera.transform.position * s.damping);
but it seems that unity is slicing up the image into many smaller meshes so it only has to render the non-alpha parts. Is there a way to disable this behavior so that the sprite renderer mesh remains intact?

#

Here is an image of a star before the image has been scrolled at all, and another when it has scrolled slightly. As you can see, there appears to be an edge of the mesh on which the star is drawn. If I scroll further the star will disappear completely until it appears on a place where there was another star drawn.

mental bone
warm pulsar
#

I am getting a very unexpected result when trying to use a URP Unlit Shader Graph shader for an Image

echo flare
#

Anyone know if you can use triplanar texture sampling but with a randomized rotation for each tile?

warm pulsar
#

this looks like UV coordinates

#

it looks normal in the scene view, but it shows up like this in the game view

#

turning off "Cast Shadows" makes it turn a dark reddish color; it's busted either way

#

neither case seems to care about the actual base color

#

this might be a gross mis-use of the shader graph 🫠

#

d'oh! i just needed to change this

#

Is there an "in range" node?

#

that tells you if a float is between two other floats

#

i can just slap together some comparison nodes with an And

#

but it'd be nice to cut down on the clutter

stable palm
#

why is it pink

#

i followed a tutorial

#

✅ Get the Project files and Utilities at https://unitycodemonkey.com/video.php?v=IC5JoS0wX0s
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
👇
👍 Learn to make awesome games step-by-step from start to finish.
🎮 Get my Steam Games https://unitycodemonkey.com/gamebundle

🔴 RELATED VIDEOS 🔴
3 Ways for a Scope Zoom Effect (Unity Tuto...

▶ Play video
quartz wasp
#

does unity have any sort of glsl support

#

or is it all hlsl

inner coral
#

Somehow the shader go invisible after restarting Unity what
And there after

#

Unity version: 2022.2.1f1

Is this a bug or have I forked up something?

#

Attached inspector for said trail renderer

#

Ah, confirmed bug.
Of course, what else..

I deleted the meta file and now it works.

regal stag
inner coral
#

This is what I had before

grizzled bolt
inner coral
#

Fair enough.

I had to go with this one because UI Toolkit is insanely bad in Unity 2021 and below

dim yoke
quartz wasp
#

(im adverse to the shader graph because it doesn't really work with my workflow)

dim yoke
dim yoke
quartz wasp
#

how about an easy way to port GLSL code to HLSL? Even something that automatically converts simple syntax differences (like texture2d to tex2d and vec to float) would be good

tight phoenix
#

is there any way in shader to detect how much of a mesh is in shadow vs how much is in light?

#

I dont mean x is in shadow and y is in light, I mean a single value summed % of surface area in light

#

I know in code I could fire raycasts and see if they collide with anything but that sounds really unoptimal

dim yoke
tight phoenix
#

my xy use case is when an object with high internal light scatter is partially in light, the parts in shadow get emissive luminated 🤔 like an orange slice or a gummi candi

quartz wasp
#

i do that, but it's quite tedious to do find and replace for every difference

dim yoke
tight phoenix
#

nuts, good to know though

dim yoke
#

Youd need to render some sort of light map for the object and count the pixels on shadows which is not going to be cheap anyway so atleast for me it seems like the factual persentage is not available in any reasonable way but you could probably approximate it in some way

tight phoenix
#

is there any way to solve shadow acne that DOES NOT use normal bias?

#

I have a shader that completelt breaks if normal bias is above 0

#

but inversely shadows look bad if normal bias is 0

#

and I want both UnityChanThink

dim yoke
tight phoenix
#

also normal bias is creating janked up holes in shadows for unknown reasons as well

#

those same holes are the problem breaking my shader, but the mesh has no holes

#

googling it seems to have something to do with smoothing groups

dim yoke
#

Making the shadows render both sides can make most of the edges disappear

tight phoenix
tight phoenix
#

but wasnt a magic bullet UnityChanThink

#

am i going to have to author bespoke normal maps for every single 'low poly' mesh if I dont want the shadows to have seams like this

dim yoke
tight phoenix
#

capping the bottom in 3d modeling software easy to do
two-sided mostly fixes it save for on narrow edges, I can just rotate the mesh so its less noticable but that doesnt feel like a 'sollution' as much a bandaid, plus the sun moves

#

I guess the 'perfect' sollution is to make it all one smoothing group and then author a normal map from the lowpoly

#

which requires an UV unwrap thus erasing the benefits of the 'low poly' look

dim yoke
tight phoenix
#

I would like it to look like the mesh on the right, but to cast shadows as if it were smooth

#

hrm how hideously unperformant would it be to hide the smooth mesh inside the poly mesh

#

that would be doubling the geometry for every mesh where I did this, that sounds terrible and not something I should doUnityChanThink

#

smooth mesh set to cast shadow only inside of poly mesh set to not cast shadows at all

#

this definitely feels like a bad idea

dim yoke
tight phoenix
#

That might be just what I am looking for, and doesnt involve terrible double mesh hacks UnityChanThink Thanks for the link Ill try this out

dim yoke
#

Sorry, its 3am here so maybe I should go get some sleep now 😅. Ill be back tomorrow

midnight wren
#

Is something like this a good parallel reduction function? Not sure about the loop. (Compute Shader)

RWStructuredBuffer<GridAllocationInfo> gridAllocationInfos;
groupshared GridAllocationInfo gridAllocationInfosShared[128];

[numthreads(128, 1, 1)]
void PrepareGridAllocationInfo(uint3 dtId : SV_DispatchThreadID, uint3 gId : SV_GroupID, uint gI : SV_GroupIndex)
{
    int from = dtId.x * 64;
    int to = min((dtId.x + 1) * 64, particlesDataCount);

    GridAllocationInfo info;
    info.Count = 0;
    info.Radius = 0;
    info.Min = positiveInfinite;
    info.Max = negativeInfinite;

    [unroll(64)]
    for (int i = from; i < to; i++)
    {
        ParticleData particleData = particlesData[i];
        if (particleData.Radius == -1)
            continue;

        info.Count++;
        info.Radius = max(info.Radius, particleData.Radius);
        info.Max = max(info.Max, particleData.Position);
        info.Min = min(info.Min, particleData.Position);
    }
    gridAllocationInfosShared[gI] = info;

    GroupMemoryBarrierWithGroupSync();

    SubPrepareGridAllocationInfo(gI, 128);
    SubPrepareGridAllocationInfo(gI, 64);
    SubPrepareGridAllocationInfo(gI, 32);
    SubPrepareGridAllocationInfo(gI, 16);
    SubPrepareGridAllocationInfo(gI, 8);
    SubPrepareGridAllocationInfo(gI, 4);
    SubPrepareGridAllocationInfo(gI, 2);
    SubPrepareGridAllocationInfo(gI, 1);

    if (gI == 0)
    {
        gridAllocationInfos[gId.x] = gridAllocationInfosShared[0];
    }
}

void SubPrepareGridAllocationInfo(uint gI, uint threshold)
{
    if (gI < threshold)
    {
        GridAllocationInfo info = gridAllocationInfosShared[gI];
        GridAllocationInfo other = gridAllocationInfosShared[gI + threshold];
        info.Count += other.Count;
        info.Radius = max(info.Radius, other.Radius);
        info.Max = max(info.Max, other.Max);
        info.Min = min(info.Min, other.Min);
        gridAllocationInfosShared[gI] = info;
    }
    GroupMemoryBarrierWithGroupSync();
}
tight phoenix
#

im beginning to wonder if my render pipeline settings or project settings or shadow settings or some setting buried somewhere is bad and I'm trying to 'fix' it at the wrong place 🤔

#

getting acne even with normal bias

midnight wren
dim yoke
# tight phoenix getting acne even with normal bias

Does anything change when you move the normal bias slider? Could it just be that you are modifying a wrong URP asset? Second thing that I am thinking is that maybe your meshs normals are messed up somehow, atleast it looks like it. Those edges seems very hard for smooth shaded. Any clue why would that be?

dry hull
#

Hello, I'm looking to make a mirror room in unity
so basically the character is transparent so it would just mirror the rest of the map
but I got no idea how do I go about making a shader for it in an optimized way
because I'm gonna have hundreds of mirrors going in at the same time

#

and mirrors can also face eachother too

#

which is a headache

#

there's one more thing which is the fact that I'm gonna give the mirrors a water-like effect but I found a tutorial on that on yt so no issues there

low lichen
dry hull
#

yes

#

mainly just cubes

#

basically the rooms contain the 3D mesh of the room itself, cubes, the player which has no visible mesh and ofc many mirrors

low lichen
#

Mirrors == portals in graphics

dry hull
#

ah I see

#

well actually I was going to use the mirror for a portal

#

so in the end it is a portal nonetheless

#

using the stencil portals method would you be able to let's say draw at least 20 of them in the same room (not level)

#

cuz if so then I might just be going with this and see what I can do

low lichen
# dry hull using the stencil portals method would you be able to let's say draw at least 20...

The portals themselves are pretty minimal cost. It's more of a question of what needs to get rendered in the portals. If you have a room with 20 objects and you have one mirror covering a wall of the room, then you need to draw up to 40 objects (some of them may not be visible from both perspectives and can be culled). With every new portal, you have to render the scene again from that perspective.

#

But for portals facing each other, you have to fake it at some point, because they will be infinitely recursive.

dry hull
#

oh I see

low lichen
# dry hull oh I see

You can hear a Portal 2 developer talk about their rendering technique in this talk. He starts with comparing textures vs stencils and then goes through all the problems they had to solve:
https://youtu.be/riijspB9DIQ?t=281

Developers who created the game Portal discuss problems they faced and how they solved them.

This beginner's course teaches the foundations of game development. This video is lecture 11 of CS50's Intro to Game Development from Harvard University.

Check out the full course playlist: https://www.youtube.com/playlist?list=PLWKjhJtqVAbluXJKKbCIb4x...

▶ Play video
dry hull
#

thank you very much

zenith apex
#

Hello! Sorry if this is basic, but I haven't been able to find a solution for this. I am currently trying to create a custom render texture with a camera. I have the texture and the camera configured and working but now I want to apply a shader to said render texture. The shader is a simple fog post processing effect. The problem is I have no idea how to make the shader work properly, nor how to apply it. I am a bit lost, I have tried making a Custom Render Texture Shader and applying it using a material but I don't seem to be able to get it to work. How could I do it?

swift loom
#

Any idea how this error is possible in this scenario?

low lichen
# swift loom Any idea how this error is possible in this scenario?

This is because the third parameter which you have set to 255 is not the z dimension of a 3D texture. It is the bits assigned for the depth buffer of the texture. To make a 3D RenderTexture, you have to change its dimension to Tex3D and then assign the z dimension through volumeDepth.

#

Both of these are not in the constructor, so you have to set them after the constructor and before .Create()

swift loom
#

oh now that is sneaky

#

thanks i'll try that

lunar valley
swift loom
#

Yes it's sneaky that it uses a variable name that is easily confused with something else.

tight phoenix
#

it looks like its not receiving any shadows or something

dim yoke
tight phoenix
#

the website shows Vertex Color plugged into base color but that doesnt make it look any better

#

anything obviously wrong in here?

#

oh I think I found it

#

I was doing DDX on top and DDY on the bottom

#

turns out order mattered UnityChanThink

#

working as desired 👍

lunar valley
dim yoke
dim yoke
#

you can use the right hand rule to figure out the cross product input order although in this case I'm confused myself of why the vertical derivative must go first 🤔

dry hull
#

that solves one problem

low lichen
#

But with enough distortion, you may not be able to tell.

dry hull
#

do I have to use a different camera for each portal?

dire cedar
#

I have been working on making my cloud system less symmetrical, and the main issue I am running into is I can't get my whorly based fBm noise to tile. The whorly noise part tiles, but the moment I add more than 1 octave I get results like the one above. Any idea what the issue might be? I have attached the computer shader I used to generate the noise for context

tulip grove
#

im trying to make a edge line like this output of the add, lerps with sample texture and goes to base color any helpfull idea ?

tulip grove
#

sorry the like the red drawing, i mean trying to make a linear line at the edges while disolving, but now im blending them wrong

#

in here im trying to limit blue noise edge

pale python
#

hi ,
im self learning shaders and i was wondering if shaders could send to a regular c# script some data like an array or a list of world position points ?

lunar valley
low lichen
pale python
lunar valley
pale python
pale python
low lichen
lunar valley
pale python
low lichen
pale python
pale python
low lichen
#

So that's why you don't commonly see shaders outputting data other than the color on the screen.

pale python
lunar valley
pale python
median valley
#

Ah and as a side note instead of SetData you should always use Begin\EndWrite API, it's always faster, even on hardware that doesn't support "direct" GPU memory pointer.

sweet burrow
#

In shadergraph, how do I get access to matrix4x3?
I can't declare them in the editor, and not sure if there is a way to get them in a custom node without something ugly like declaring 3 separate Vector4.
I can send them easily via BatchRendererGroup, but don't see how to read them directly.
There must be a way since "unity_ObjectToWorld" and other root transform properties are matrix4x3.

regal stag
mortal arrow
#

Hi everyone
Im stuck in this problem: can't figure out how i can make it possible
so i made shader like in this tutorial: https://youtu.be/5dzGj9k8Qy8?list=LL
and i want make is pixelated. I did pixelated UV and dont know how i can put position node and my pixelization node together.(1pic)
Position node i need because noise is stretched along sprite sheet, because it have animation and i need it
Result i want is on second pic

near robin
#

I'm trying to write a shader however something with the URP is giving me trouble I believe, even following an online tutorial for a super simple shader results in nothing showing up unless I set to the render queue to transparent for some reason (nothing about this shader should be transparent) I'm reaching my wits end with this. Also please do not suggest using shader graph, I have 0 desire or inclination to play with spaghetti.

Shader "Unlit/SLit"
{
 
    Properties
    {
        [Header(Surface options)] // Creates a text header
        // [MainTexture] and [MainColor] allow Material.mainTexture and Material.color to use the correct properties
        [MainTexture] _ColorMap("Color", 2D) = "white" {}
        [MainColor] _ColorTint("Tint", Color) = (1, 1, 1, 1)
    }

    SubShader
    {
        Tags{"RenderPipeline" = "UniversalPipeline" "RenderType" = "Opaque"}

        Pass
        {
            Name "LightForward"
            Tags{"LightMode" = "UniversalForward"}

            HLSLPROGRAM
            
            #pragma vertex Vertex
            #pragma fragment Fragment

            #include "SLitLightForwardPass.hlsl"
            ENDHLSL
        }
    }
}
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"
        
TEXTURE2D(_ColorMap); SAMPLER(sampler_ColorMap);
    
float4 _ColorMap_ST;
float4 _ColoTint;

struct Data
{
    float3 positionOS : POSITION;
    float2 uv : TEXCOORD0;
};

struct v2f
{
    float4 positionCS : SV_POSITION;
    float2 uv : TEXCOORD0;
};
 
v2f Vertex(Data input)
{
    v2f output;
    VertexPositionInputs posnInputs = GetVertexPositionInputs(input.positionOS);
    output.positionCS = posnInputs.positionCS;
    output.uv = TRANSFORM_TEX(input.uv, _ColorMap);

    return output;
}

float4 Fragment(v2f input) : SV_TARGET
{
    float2 uv = input.uv;
    // Sample the color map
    float4 colorSample = SAMPLE_TEXTURE2D(_ColorMap, sampler_ColorMap, uv);
    float4 ColorTint = (1, 1, 1, 1);
    return (colorSample * ColorTint);
}
regal stag
regal stag
vast tiger
#

Is it possible to replicate how unity blends vertex colors in shader graph?

regal stag
vast tiger
#

except I select the colors at each vertex myself

#

I'm aware that I can change the vertex colors of a mesh but when multiple triangles share a vertex it yields results that I don't want

#

I could separate the vertices when creating the mesh but then I'd end up with more vertices

regal stag
vast tiger
#

Unfortunate

gusty marten
#

Hello Folks! Can somebody tell me what this means? What is UNITY_SHOULD_SAMPLE_SH?

fervent flare
#

Anyone got any hot tips for why this is not working?

#

I figured this was a way to get multiply blended decals in urp but I guess not ?

kind juniper
kind juniper
midnight wren
#

How can I set data to a ComputeBuffer in a background thread?
It takes a lot of ms to do it in the main thread 🥺

mortal arrow
lunar valley
mental bone
mortal arrow
bright drum
#

Hello! I'm working on a script that overrides the textures of a specific terrain layer at runtime. While the diffuse and normals are stored in their own Texture2DArray's, the Height/Smoothness/AO are stored within the green channel of the diffuse/normal textures (not sure how that works). However, those textures can also be accessed through a struct that's found within the subshader of the shader I'm using for this (MicroSplat). Is there a way to access the struct through code to override these textures?

#

My script:

    {
        StartCoroutine(ReplaceTexture());
    }

    IEnumerator ReplaceTexture()
    {

        yield return new WaitForSeconds(1);

        Debug.Log("10 seconds waited");

        myTerrain.materialType = Terrain.MaterialType.Custom;

        Material terrainMat = myTerrain.materialTemplate;
        Shader shader = terrainMat.shader;

        Texture2DArray diffuseArray = terrainMat.GetTexture("_Diffuse") as Texture2DArray;
        Texture2DArray normalArray = terrainMat.GetTexture("_NormalSAO") as Texture2DArray;

        Debug.Log("Array depths:" + diffuseArray.depth + " " + normalArray.depth);

        Texture2DArray newDifArray = new Texture2DArray(diffuseArray.width, diffuseArray.height, diffuseArray.depth, TextureFormat.DXT1, 11, false);
        Texture2DArray newNormArray = new Texture2DArray(normalArray.width, normalArray.height, normalArray.depth, TextureFormat.DXT5, 11, false);

        for (int x = 0; x < diffuseArray.depth; x++)
        {
            for (int y = 0; y < diffuseArray.mipmapCount; y++)
            {
                if (x == 1)
                {
                    Graphics.CopyTexture(diffuse, 0, y, newDifArray, x, y);
                    Graphics.CopyTexture(normal, 0, y, newNormArray, x, y);
                    Debug.Log("Custom layer replaced");
                }
                else
                {
                    Graphics.CopyTexture(diffuseArray, x, y, newDifArray, x, y);
                    Graphics.CopyTexture(normalArray, x, y, newNormArray, x, y);

                    Debug.Log("Texture copied");
                }
            }
        }

        terrainMat.SetTexture("_Diffuse", diffuseArray);
        terrainMat.SetTexture("_NormalSAO", newNormArray);

        Debug.Log("Textures set");
    }

}```
next cove
#

Can we convert custom shader into urp lit shader

wheat scroll
#

Hey, any idea how to create a shader which duplicates the rendering of a mesh ? (I want to simulate a crowd with any a few animators& skinned meshes).

lunar valley
#

Or do gpu instancing if it is a lot of people and they don't need to exist on the cpu

wheat scroll
lunar valley
#

you want to use a shader to save animation data??? why? purpose??

umbral hemlock
# wheat scroll I would like to save the calculation of the animators and skinned mesh renderer ...

What do you mean by calculation of the animators? Like a baked mesh per frame? (Otherwise as far as I can tell I agree that gpu instancing is the solution). You could also limit bone influences from 4 to 2 or 1 per vertex to increase performance slightly. Also these pages might help: https://github.com/chengkehan/GPUSkinning and https://forum.unity.com/threads/experiments-with-instancing-and-other-methods-to-render-massive-numbers-of-skinned-meshes.447749/

GitHub

Contribute to chengkehan/GPUSkinning development by creating an account on GitHub.

midnight wren
midnight wren
#

I guess there is no other option, right?

lunar valley
midnight wren
#

Once per physics update, which means several times per frame

lunar valley
#

why

midnight wren
#

Because I must copy the position and velocity of my entities each time they are updated.
I'm trying to make a Smoother Particles Hydrodynamics which can interact with rigidbodies.
So each particle is an entity with LocalTransform, PhysicsMass, PhysicsVelocity, PhysicsCollider (Spherical).
Which means, each time position or velocity updates in Unity side, I must send that info to the GPU, compute particle/particle collision, and send it back to Unity.

mental bone
#

@midnight wren End write taking 1.4ms is strange

#

I use it on a 100mb compute buffer that stores rendering info and haven’t seen a hitch

#

Ah but I see you are doing it even multiple times per frame

#
GitHub

[Mirrored from UPM, not affiliated with Unity Technologies.] 📦 The Entities Graphics package provides systems and components for drawing meshes using DOTS, including support for instanced mesh rend...

livid flame
#

How do I obtain Texel Size for a sprite in an atlas?

smoky widget
#

Hi

#

I have a compute shader that sets a bunch of points into a scene, but I would like it so that if there's one that doesn't pass a certain criteria, a single bool is passed back to the cpu telling me that at least one is not passing, how could I do that?

lunar valley
smoky widget
#

I was hoping to have another option, but otherwise I will continue with compute buffers

hearty obsidian
#

I have a shader that needs to read from scene depth/color. Is there any benefit to making it an opaque shader and changing the render queue to transparents, or is it the same as if it was transparent?

regal stag
hearty obsidian
#

@regal stag Ah, yeah I can see it 2021.3 -- super, thank you for the runthrough

meager pelican
#

There's a node in shader graph for that too.

livid flame
#

yea but my textures are in atlases so it doesnt give me the correct texel size or something. Effectively when we moved them to Atlases the shader stopped working properly

meager pelican
#

Well then you'd have to adjust the math to divide by # of tiles x and # tiles Y. But atlas use also needs to compute the starting offsets.

#

All depends on how you use it. I mean, it gives the right value for the atlas as a whole, but not for a tile.

#

And you'll probably have to pass that info in somehow.

outer lake
#

What's the shader graph equivalent to blender's generated input coordinates? It seems like it's still using badly unwrapped UVs still

daring olive
#

im noob, in tactics games, is the grid showing movement range a shader?

scarlet plover
#

Hey guys, Im new on unity, how I can do to make a shadow to my sprite, Idk how I can proceed

sweet inlet
#

Hello! I'm struggling with shader graph and was hoping someone could help. I have a tiling and offset node, and a sample texture 2d node. I would like to add padding or spacing between each tiling of the image. Any advice?

regal stag
# sweet inlet Hello! I'm struggling with shader graph and was hoping someone could help. I hav...

The easiest and cheapest way would be manually editing the texture to have that padding.

But you can also do it with maths, (see image).
One problem here though, is if the texture has mipmaps enabled you'll get pixellated seams. Either disable mipmaps or swap it out for a Custom Function so you can use SAMPLE_TEXTURE2D_GRAD(Texture, Texture.samplerstate, TiledUV, ddx(UV), ddy(UV)); where TiledUV is the result of the group, and UV is the result before the Fraction node.
https://www.cyanilux.com/faq/#sg-pixellated-seams

outer lake
#

Idk why the noise isn't 3D using world space

sweet inlet
#

been trying to do this for hours 😅

regal stag
outer lake
#

This is my setup

tight phoenix
#

I am trying to simulate backscatter and to that effect I need to mask out a specific range of values (only the backscatter)
Picture 1 you can see that range's mask working well. there is some falloff onto an adjacent object but that's acceptable, they both use the same material so there's no way to fully mask that one's object but not the other's
The problem

#

the problem is the method I got this mask creates this white band and I can't figure out how to get the mask I need without this band forming

#

means of generating the data

#

everything pure white needs to be masked out , but without generating that white line

#

and anything that is not pure white should not be masked out at all

#

the problem is probably that im using a sine to get the range I want

#

but i am not sure how to get the range i want without it

#

is there a node or a formula that will isolate a specific band of values

#

for example this method to isolate a specific band of values

#

still generates 'the line'

#

yeah every combination of values creates this line

#

and I need it to not

#

somehow masked it from just the front, but how to also do the back

#

it might be impossible because the value range I want to mask out is the exact same values on both objects, and there is no data available to me that only one of these two instances of that material shares

grand jolt
#

how do I make screen space reflections in URP shader graph

#

so I don't have to use reflection probes

tight phoenix
#

yeah i think im just going to abandon this entire attempt, its not giving me the results i need

#

time to start from scratch again for the 100th time 😿

grand jolt
#

oof

grand jolt
#

but like accurate

balmy lark
#

What's this funny effect called so I can google it, and how can I get rid of it in my CRT shader? I'm really wondering about the funny lines. They seem to result whenever I have something that's pixelated (this shader or otherwise)
I'm wondering if I should like blur / feather the output or something to try and get rid of it

echo flare
# balmy lark What's this funny effect called so I can google it, and how can I get rid of it ...

In mathematics, physics, and art, moiré patterns (UK: MWAR-ay, US: mwar-AY, French: [mwaʁe] (listen)) or moiré fringes are large-scale interference patterns that can be produced when a partially opaque ruled pattern with transparent gaps is overlaid on another similar pattern. For the moiré interference pattern to appear, the two patterns must...

amber cobalt
dark garden
#

Does anyone know what happened? i just installed urp and now when i bake lighting its all weird. help

dark garden
#

Whenever i bake something it turns pink... maybe a light?

grizzled bolt
#

@dark garden Check scene debug views for texel invalidity and lightmap UV overlap after baking and continue the topic in #archived-lighting

sweet burrow
#

Is there a way for a script to tell if a shader/material has shadow casting enabled?

meager pelican
# sweet burrow Is there a way for a script to tell if a shader/material has shadow casting enab...

Shadow casting is done in the ShadowCaster pass in a shader. I suppose you could check for that pass type on the shader:
https://docs.unity3d.com/ScriptReference/Rendering.PassType.html


To access the name of a Pass from C# scripts
, you can use APIs such as Material.FindPass, Material.GetPassName, or ShaderData.Pass.Name.

Note: Material.GetShaderPassEnabled and Material.SetShaderPassEnabled do not reference Passes by name; instead, they reference Passes using the value of the LightMode tag.``` 
^  from https://docs.unity3d.com/Manual/SL-Name.html
sweet burrow
#

Thanks, I will try with this then.

solemn stag
#

Hi, is it possible in shader graph to feed generated RGBA heightmap to parallax node? It needs Texture2D input so i'm kind of lost.

regal stag
# solemn stag Hi, is it possible in shader graph to feed generated RGBA heightmap to parallax ...

Can copy the code for the Parallax Mapping node but swap the texture sample out (line 41 in ParallaxMapping.hlsl)
https://docs.unity3d.com/Packages/com.unity.shadergraph@10.2/manual/Parallax-Mapping-Node.html
https://github.com/Unity-Technologies/Graphics/blob/master/Packages/com.unity.render-pipelines.core/ShaderLibrary/ParallaxMapping.hlsl

Try something like this in a Custom Function node

Out = UV + ParallaxOffset1Step(Height, Amplitude * 0.01, TangentSpaceViewDirection);

Could also replicate it in nodes. See ParallaxMapping.hlsl for what the ParallaxOffset1Step function is doing.

grand jolt
#

Hello! I have a question about filtering/bluring textures.
In my top down tile based game every tile has a light level.
I want to blend light levels smoothly, but I don't know how.

1st image is raw light texture.
2nd image is light texture with biliniear filtering.

But as you can see blinear filtering is not enough, it looks werid.
I have tried the bicubic filtering (through the shader), but it does not look much better than bilinear.

Please help me to find the way to make smooth transition between light levels!

low lichen
grand jolt
#

Yes, it's possible I guess. Will it affect the result?

grand jolt
#

But I guess it will make the light circle either really big or with hard edges between light circle edge and complete darkness

#

If I got it correct

low lichen
grand jolt
#

So the light texture is rendered on top of the world. It's completely black, only alpha values change

low lichen
#

Do you know what texture format you are using? Is it compressed? Some texture formats and many compression methods use fewer bits for alpha, which can lead to this sort of issue.

grand jolt
#

Here is the example texture

#

It's PNG

low lichen
grand jolt
#

I don't think it's compressed.

low lichen
#

All imported textures are compressed unless you specify otherwise.

#

Also, PNG is compressed already, but Unity compressed on top of that.

grand jolt
low lichen
#

I would recommend against using the alpha channel for this. Instead, I would use RGB. White pixels can be the same as 100% alpha and black pixels the same as 0% alpha.

grand jolt
#

But how can I render it on top of the world in that situation?

#

Blend it in shader?

low lichen
#

With additive transparency/blending. Which is more accurate to how light works anyway.

#

Many shaders that support transparency will also have the option to use Additive blending, but otherwise you need to make a shader with additive blending.

#

In Shader Graph, it should look something like this, but it's probably outdated because they're always updating the UI

grand jolt
#

Thanks, I will try to figure out!

#

Also some guy advised gaussian blur the texture

low lichen
#

no

grand jolt
#

Expensive?

low lichen
#

Expensive to do at runtime, and unnecessary since the root problem can be solved.

grand jolt
#

So you think I should use bilinear filtering + additive blending instead of alpha blending?

#

To combine the world and light texture

#

And avoid using alpha for the light texture

#

And that could heal the artifcats?

low lichen
#

This could be caused by the PNG compression when you exported the texture.

grand jolt
#

Yes, really looks weird, haha

low lichen
#

Compression algorithms often don't put as much priority on alpha as they do for RGB. So using RGB instead of alpha should be more resilient against compression, but you could also continue using alpha and be more careful about what compression you use.

grand jolt
#

Well, it looks much better

#

The smoothing

#

Thanks!

low lichen
#

No problem. Actually, multiplicative blending makes more sense here, since your texture is storing darkness instead of lightness.

grand jolt
#

Yes, thanks!

#

But also I calculate light levels on CPU

#

And I need to somehow create such light textures on the fly

#

I mean light spread on tiles is calculated on cpu

#

And I want to convert light level on cpu to pixel darkness on the texture

low lichen
#

How complicated is the light spread going to be? More complicated than just a smooth radial gradient from points of light?

grand jolt
#

Like in minecarft but simpler, because it's 2d only.
Light flows from the sources and loses levels in process.

#

So light loses levels when it avoids obstacles

#

Example in 3d

#

Light spread is calculated on cpu

low lichen
#

Well, you won't have to worry about compression if you're generating the texture at runtime, but I think moving to RGB was still a good move because now you can do colored lights properly.

grand jolt
#

And not on the second part 🙂

low lichen
#

Well, most screens are only capable of displaying 256 different light levels (unless it's HDR) and it just so happens that the smallest texture formats supported by GPUs, and by extension Unity, are 8-bit, meaning 256 different levels.

#

So while you could artificially choose a number below 256, you'd be forced to use textures that are capable of storing at least 256 shades.

grand jolt
#

Thank you! I was looking in a completely wrong direction to solve that problem

tawdry peak
#

Hi! I'm learning unity for VRChat and I'm wondering if anybody knows a method or shader that makes the 2D object looks like the same in every angle of sight.
I can't find any information through my googling 😦

lunar valley
#

I do not quite know what you want exactly....

regal stag
#

Sounds like a "billboard" shader

tender edge
#

i want to learn more about shaders/ shadergraph, are there any good tutorial series you guys recommend?

#

also, ive found ben clowards tutorial series which looked interesting. but its for unreal. does that translate to unity?

tight phoenix
#

At a glance is there an obvious reason why this shader is affected by scene viewport size?

tawdry peak
low lichen
tight phoenix
low lichen
tight phoenix
#

Yes that node's output is what is shown there and nothing else

lunar valley
tight phoenix
lunar valley
#

Yes I doubt that anything else is directly related to that

low lichen
tender edge
tight phoenix
#

as in a single float that says 'this much thick'

#

for Transmission

tight phoenix
tender edge
tight phoenix
#

and its not about depth from eye to mesh through mesh, its depth from Main Light to mesh to beyond

low lichen
#

I can't think of anything else that would be affected by viewport size in your shader.

tight phoenix
tight phoenix
tight phoenix
#

let me get you a screenshot of what I see, I might be blind thats also likely

low lichen
#

One thing you could check is if you notice the shadow map changing at all at different viewport sizes, in the Frame Debugger for example. I don't know enough about URP shadow map rendering to know if there is any connection there. I suppose it might mess with the cascades, sort of like mip mapping at different screen resolutions.

worn harbor
#

Hi, I don't know if someone can help me but i'll try :)
So i followed this tutorial https://www.youtube.com/watch?v=RMt6DcaMxcE&t=128s to add post process outlines to my game. Now i'd like the line to be "wiggly" so that it looks kinda like the line is drawn by hand. I know i may have to add perlin noise to the graph, but i have no idea where to add it :(
(If you can't see the graph properly, it is litteraly the one from the video)
Can someone help ?

tight phoenix
#

google search says its bugged and never fixed?

#

fiddling with the debugger options makes no difference in the appearance

#

I plugged an override material into the URP renderer to render everything as the shadow texture

#

you can see clearly at the edge between cascades it does something jank 🤔

#

i think maybe the cascades are happening in a sphere around the view point? meaning they change at the edges before anything else maybe?

#

or maybe my copy/version/thing of the shadow texture itself is the problem?

tight phoenix
merry rose
#

not junk but a transition from one size to another, making the transition less distant from each other can make it a bit less noticeable, or you can make a soft transition yourself, which is a bit of hackle and havent found any info online for one yet

#

you can test if its transition to just change it while debugging the effect, the cascades should be in URP asset settings

tight phoenix
#

the method being used to get that data

tight phoenix
tight phoenix
#

should the edges be that hard?

#

soft shadows are on UnityChanThink

merry rose
#

soft shadows only mean that you sample shadows multiple times at one point but only on XY axis, the depth Z axis stays the same, so it wont smooth the transition between two cascades.

tight phoenix
#

I have read that blur methods are generally slow to do at runtime, I don't know if there is some form of blur I could apply that is dead simple, an ugly result is probably still good enough UnityChanThink

merry rose
#

putting the first splits way closer, so they dont do big texel size jumps, it can hide itself in a scene then

tight phoenix
merry rose
#

yea like 5/10/20 o smth

tight phoenix
#

hmm all it seems to do is change 'when' the jank transition occurs, there's no perfect set of values because the camera /object can move and when it hits the cascade point, jank happens

merry rose
#

yeah currently there is no clean solution done I can see :/

tight phoenix
#

raw shadows and default lit texture's use of them

tight phoenix
#

reading about how cascades work interally 🤔

#

from here

meager pelican
# worn harbor Hi, I don't know if someone can help me but i'll try :) So i followed this tutor...

Hmmm....
OK, I'll bite (Byte)...

Because you're using a post processing screen pass, you can't change the current pixel's location. But you CAN change where you sample from in the opaque, depth and possibly depth-normals textures. So what you'd do is to sample a bit left/right/up/down based on some offset selected by noise. And you'd want that consistent for all sampling that you're combining so you don't get diverging lines for each sample type. By varying that noise over time somehow, things would "wiggle" where you draw the line color. I suppose you'd want to be careful not to wiggle where there's no line.

worn harbor
#

@meager pelican Ok, I'm so sorry, i'm kinda a newbie on unity 🥲 So this is what i have to modify, the subgraph ? The way i am sampling is here right ?

tight phoenix
#

how does anyone even use unity urp shadow cascades

#

the more I poke and prod to try to make it look even remotely usable, it just gets worse and worse

#

and now im at the point where it looks like complete dogshit and I dont know how to disentangle myself from how compeltely uselessly broken this is

#

shadow resolution was set to 256

#

as usual the problem was between monitor and chair

meager pelican
cinder rampart
#

im new to unity so excuse me, when i drag my skybox in i cant see it being there, what do i do?

dense bane
#

you guys know why HDRP looks so much better than BRP? I'm thinking it's the tone mapping more than the shader light math

mental bone
#

Its the shader light math

night linden
#

hey all, sorry for really newbie questions but i am using cyanilux's toon shader. i'm wondering where in the shadergraph would i be able to make an adjustment to make the overall shadows brighter, including the cast shadows? very unfamiliar with shader graph and unity in general. hoping that i can just make all shadows lighter and not just having cast shadows and form shadows multiplying over each other (my attempt did this.) blobbowing

worn harbor
night linden
#

i did try that, and the cast shadows ended up looking like this:

worn harbor
#

what are the dimensions on your img ? Can you link me to the tutorial you used ?

night linden
#

so i thought maybe there is a spot in the graph that would adjust ALL the shadows to be lighter? thinkDerp i'm terrible at reading this.

worn harbor
#

If your ramp texture has 3 steps, why does your on scene object has 4 ?

night linden
#

i was assuming maybe the cast shadow is multiplying over the top of the form shadows and making it look like a 4th step in "combine ramp with shadows" but it's also being used for a culling mask (i don't know what this does.) i tried putting an add node and just testing some stuff there, but the cast shadows were still multiplying on top

worn harbor
#

Ahah sorry I'm not that good either, still a newbie , hopefully more experienced person will answer 😅
Personally I know that when I wanted to change the colour of the shadows and add more steps, I just modified the ramp texture
I personally used this tutorial https://youtu.be/RC91uxRTId8

✔️ Works in 2020.1 ➕ 2020.2 ➕ 2020.3 🩹 For 2020.2 and .3:
► When you create a shader graph, set the material setting to "Unlit"
► The gear menu on Custom Function nodes is now in the graph inspector
► Editing properties must be done in the graph inspector instead of the blackboard
► In Lighting.hlsl, change the line "if SHADERGRAPH_PREVIEW" to "...

▶ Play video
night linden
#

thank you i will look at that too, i did try another tutorial by him that the code was just not working in this version of unity i think? or else user error, wouldn't really be surprised. 😭

worn harbor
night linden
#

well thanks for taking a look, i will try to poke at this a bit more since i like how the rest of this shader looks a lot before i give up on it. appreciate the link a lot!

regal stag
night linden
tender edge
#

just started learning about shaders, why is my preview not updating to green?

worn harbor
#

Save the asset

tender edge
# worn harbor Save the asset

didnt work, i was messing with a vector 2 node connected to the base color earlier and then i did see the preview update live

#

i deleted that node and just changed the box next to the base color and now it doesnt work

worn harbor
#

Is it just the preview ? Is your material green ? If so then I think it is just unity editor that need to be restarted

tender edge
#

does it need to be connected to a material first?

#

ill try restarting aswell

worn harbor
#

You don't need to connect it to anything rn, it'll work just fine once you do

#

If you really want to see the preview, try to connect the base color to a color node

tender edge
worn harbor
# tender edge thanks, restarting seems to have fixed it

Perfect 👍
Just so you know the main preview sometimes doesn't update well until you connect new nodes to it but it doesn't mean your material (if connected to a material) hasn't updated it's just the preview that isn't working properly when nothing is connected

worn harbor
#

@meager pelican
Ah yes sorry I lost track 😅
So I need to modify the hlsl file that is sampling where to put the line ?

And so how to do that ? If I understood properly, I need to add a Noise float parameter to both ColorSobel and DepthSobel and then add that to where i sample (i don't know how to add the noise to the sampling :/ ) or generate the noise directly in the hlsl (but i don't know how to do that :/). And inside the shadergraph plug in the noise to the custom function and also make it so that the noise texture moves according to time ? And use that noise to offset the sampling points ?
I can get around on how to do the noise (even if all help is appreciated ahah)
But I have no idea how to offset the sampling points using the noise :/
(If anyone also has an answer, your help is greatly appreciated ahah :)

tender edge
#

i got another shader related question

#

im also working on a procedurally generated terrain, but im not happy with the uv coords ive set there. is it possible to overwrite those uv coords with a shader based on world position?

#

ive seen some videos where the shader seems to correct uv values based on world position or other conditions but i got no clue how it works under the hood yet, basically i want to know if i have to fix the uv coords on the mesh first to get something like that to work, or the shader will just dictate over the mesh and i dont have to bother fixing them now

worn harbor
tender edge
meager pelican
# worn harbor <@573586703202254878> Ah yes sorry I lost track 😅 So I need to modify the hls...

It's up to you, that's you programming.
I'd sample the noise (whatever one you use) at the same UV offset you're sampling the other textures at, plus some wiggle offset to "distort" it, You may just want to pass that in as uniform value, but maybe not. Up to you.
That result gives you an offset in both X and Y.
You can scale that too by some passed-in value.
And THAT end result, the offset and the original UV added, is what you use to sample the depth texture and the color textures. These offsets are likely to be pretty small float values, since the entire UV range is 0-1.
Basically what you're generating is a wiggle-offset over time.

I guess another way to say it is to...wiggle the distortion/noise sampling, and use that result to offset the line sampling.

In the end, all you're doing is modifying the UV sample location a tiny bit with some maths that vary over time.

#

You'll have to dig in, as I'm not set to write it or demo it for you.

worn harbor
forest wave
#

Yo, is it possible to render both low quality and high quality things in the same game view? Basically, I have like an overlay that covers the screen. It displays by having a certain script on the main camera which controls a shader that creates this overlay. I want that overlay to be high quality. But then I also have the game itself, and I want that to be really low quality. Is there any way to achieve this?

Currently I have 2 cameras with one having a low quality render texture, but they only work individually, not together.

Thanks.

#

Idk if that makes sense lol

lunar valley
# forest wave Idk if that makes sense lol

no it doesn't at least I do not know what you mean. Because what I am understanding is that you want a high quality overlay but not a low quality one and you want a low quality one but not a high quality one everything everywhere all at once or something idk. I don't get it

regal stag
forest wave
# lunar valley no it doesn't at least I do not know what you mean. Because what I am understand...

okay ill try to be more clear, im really bad at explaining things lol

Basically imagine you are looking at your monitor and are playing a low res game. Your monitor is high quality because ofc it is, its in real life, but the game is low quality because its on your screen.

In my case, the shader is kinda like the look of the monitor, with the edges and overlay and stuff

Idk if that makes more sense lol

forest wave
regal stag
forest wave
regal stag
#

What Unity version?

forest wave
regal stag
# forest wave Hmm okay, a little confused tho, mind explaining further? Thanks

Should be able to use this - https://github.com/Cyanilux/URP_BlitRenderFeature

Create a second Forward/Universal Renderer asset and add the feature to it. Add the renderer asset to the list on the URP Asset. Set that Renderer field on the Main Camera.

On the feature, use source as RenderTextureObject, drag the low res Render Texture asset used by the camera into that. Will also need to create a shader/material that just samples _MainTex and outputs it. The Unlit Shader template might work, or create an Unlit Graph.

forest wave
grand jolt
prime shale
#

probably here @grand jolt

#

given that its compute "shaders"

grand jolt
#

Alright xp

#

I have an issue with Compute Shader IDs acting weird, or rather me just not properly understanding them.
I made a mesher (Dual Contouring) for my voxel engine and I'm now trying to program it into a Compute Shader for massive performance gains.

Here's the plan:

  1. Construct chunks one after another on the CPU.
  2. For each Chunk one after the other: Dispatch the compute shader to calculate the vertices and other relevant information for each voxel on a chunk, store them in a buffer, access that buffer on the CPU again.
  3. Format the data from a raw one-dimensional array to a nice list of structs.
  4. Finalise the algorithm by winding together triangles, creating the vertex array and forming it into a mesh.
#

It's all done now, but, of course, it doesn't work. I've been debugging it line by line, fixing various issues, and it's time to test if the algorithm can even properly assign vertices, nevermind the actual computation for them. So, in the shader, just to see if the connection between shader and C# script works properly, I wrote this, leaving what I've had behind a return line:

#

It takes the unsigned integer id and converts it to the id I'm using, which is basically just shifted so that 0, 0, 0 is the center of the chunk. (this is idSigned)

#

Then, in the vertices buffer, which is a RWStructuredBuffer of float3x2s, it writes the computed vertex (for now just (0, 0, 0)) and after that the id of the voxel in the chunk

#

In the C# script, this is the method the voxel engine goes into when executing the meshing algorithm:

#

Everything other than the two circled bits are irrelevant.
We declare the two buffers that will store our results, and enter the method preparing and executing the compute. Afterwards, I want to simply see in visualisation through cubes what the actual voxel IDs are that it computes. Voxel IDs are really just identifiers for each voxel in a Chunk.

#

This is the struct in which we get the most important info; the vertex of a voxel, and the voxel's unique identifier.

#

Now, in executeCompute:

#

In prepareCompute we simply set everything for the buffers. I've tested it, that bit works.
Directly afterwards we dispatch the compute to the main kernel and the given 3D resolutions

#

At the end of executeCompute is this; we get the buffers and read them into arrays (the get methods) and then we format them into structs (the format methods). Notice that these two variables, winders and voxelData, are the important list of structs we iterated at the second photo.

#

I'm only going to show the two methods for the voxelData, as that's the only thing we're testing right now:

#

Notice that in formatVoxelData() we read from the one-dimensional array based on the elements of the float3x2, which if we remember is as follows: vertex.x, vertex.y, vertex.z, id.x, id.y, id.z .

#

Okay, so what are we doing, or at least, trying to do?

  1. We are dispatching a compute shader that simply writes an ID, signedID, to the buffer, on the address of its own id, so that for buffer(threadID (which is the voxel's id but usigned)) we should get the voxel's signedID.
#
  1. The buffers come and we read them into arrays, which we then format into lists of structs to organise our data.
#
  1. We iterate through these lists and spawn a cube at the position at which our voxel claims would be its ID.
#

When we hit play, we should expect a nice big cube of smaller white cubes. They are not at the real-world positions of the voxels, but instead, at the abstract ID position inside a chunk. Something like a local position, so to say.

#

Now, what do we see? :D

#

Bummer....

#

Okay, so apparently, it managed to write and correctly read the Y and Z coordinates, but every voxel whose X is not 0, it... failed?

#

Not quite, the voxels are spawned, but their X coordinate was not set. (I clicked on one at saw that there are many in one spot, probably as many as there are X layers)

#

So... the entire Chunk was simply... squashed.

#

Typically, this is an issue of an X coordinate just being not set properly, but looking through the code with pinched eyes, I'm pretty sure I set X properly wherever it had to be set...

grand jolt
# grand jolt

Seeing this, we can conclude that voxel.voxelCoordinate must be set improperly, as that's where we read all coordinates. Y and Z work properly, but X... apparently bricked.

grand jolt
# grand jolt

This is where VoxelData.voxelCoordinate is set. I don't see anything wrong here, the pattern by which we set the info (first 3 elements are x, y, z of vertex, last 3 are x, y, z of ID) is the same by which we set it in the compute.

#

Hm, maybe VoxelDataRaw (should prolly rename it to voxelDataRaw) is at fault? But, all the other info comes back correctly, so it cannot be the fault of the buffer being read into an array (which is a method Unity gives anyways)

#

So therefore I say that the issue must be directly in the compute shader. (One sec)

#

Hmmm... I wrote something to spew out VoxelDataRaw and enumerate the variables x1, y1, z1 (it's just prefixes to the Debug.Log) to give some organisation.

#

Apparently no, x is indeed set correctly....

#

So, the error is not at the compute shader, it must be somewhere in the pieces of code I've shared...

#

Okay this is weird. If you didn't notice yet, my debug buffer recorded just the ID, that is, it's a float3. Recording the very same thing the vertices buffer is written to, we see this:

#

Notice something about the red circles?

#

We expect three zeros, and three signed integers, which can be zero.

#

Well...

#

Turns out z1 and x2 are swapped.

#

But this just makes no sense

#

I'm iterating every element one after the other, so the order in the very buffer must be wrong. How could that be?

#

Or, the Unity method that writes the buffer's contents to an array is bricked

#

It could be that the matrix type itself in HLSL is a little tricky.
I just noticed, there's a real difference between float3x2 and float2x3. However, switching didn't help. It simply made it mix up y1 and y2, instead of z1 and x2.

#

float2x3 is defined as m11, m12, m13, m21, m22, m23, aka two float3 in two different rows

#

this should be exactly it, but... still not working

grand jolt
# grand jolt

(remember: x1, y1 and z1 should all be 0, and x2, y2, z2 should be some signed integer value, as seen here)

regal stag
#

I'd probably try ditching the matrix type and use a float3 array/buffer

grand jolt
#

Honestly, I think I agree.

#

I'll try it out

#

Yep, the debug buffer works. Let's translate it over to the vertices buffer and see if we finally get our cute cube of white mini cubes

#

If so, well... don't use matrices in buffers.

#

Kinda sucks if you have to use things like float4x4, but... eh, sometimes it is like that.

#

At least nothing on the C# side has to change, as it formats an expected one-dimensional array anyways.

#

There it is! :)

#

Alright, for anyone in future: Don't use matrix types in RWStructuredBuffers. Use vector types stored one after the other. (At least if you use the ComputeBuffer.GetData(Array data) (data being one-dimensional) method to retrieve its contents)

#

@regal stag Thanks for the tip ^^

#

Huh, maybe if I had put a multi-dimensional array in the ComputeBuffer.GetData() method it would've worked properly?

#

Something to test.

pale python
#

hey,
i wanna draw a gradient on one section of x axis not the whole shader , i usually use something like lerp(float4(0, 1, 0, 0), float4(1, 0, 1, 1), uv.y); to make a gradient but that changes the whole shader

how do i limit this to be something like this

#

how do I limit the gradient effect to be on a small section of the shader?

regal stag
#

Otherwise if you need more control, can do 2 inverse lerps (Out = (T - A)/(B - A)), saturate and multiply them together

#

In shader graph they'd look like this

pale python
last loom
#

Hello 🙂
My extremely simple shader that pretty much only samples a texture shows up fine in the inspector preview, but renders as a white square in the editor view. Any idea what's happening?
Shader:

Shader "Unlit/ClosedSpriteEdge"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
    }
    SubShader
    {
        Tags { "Queue"="Transparent" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

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

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;
            float4 _RendererColor;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col = tex2D(_MainTex, i.uv);
                return col;
            }
            ENDCG
        }
    }
}
#

(the material is properly assigned to the square's SpriteRenderer)

#

Note that this is 2D, sorry for not including it in the original message. Also, built-in renderer

#

The weird thing is that if I return something that's not the sampled texture, it works 🤔

#

All in all I think the tex2D function always returns white for some reason. But only in scene/game view, since inspector's preview shows up as fine 🤷‍♀️

regal stag
last loom
#

Hey thanks for the answer 🙂 Though I'm not sure I understand @regal stag, in my shader I'm already sampling _MainTex

last loom
#

Yes, I'm guessing this is only relevant when you're using the defaut material?

regal stag
#

I imagine you'd want to import the grass block as a sprite and use that there, rather than Square.

hot python
#

would you please pass the jelly

regal stag
last loom
regal stag
regal stag
hot python
regal stag
#

Try adjusting the camera settings. There's a button in the top right as I mentioned

tropic field
#

As soon as I create a new shader file. I get thrown these errors

#

Why is that??

#

There are plenty of other shader files existing in my game

#

imported through assets

#

Why do it throw THESE many

#

they all seem unrelated too...

hot python
tropic field
#

I get this error...

#

But

#

Line 2 in this file is a damn comment

#

I am so stumped.

#

I even tried REMOVING TMP

#

my shader is empty

proper cradle
#

Hey guys ! I am using compute shaders, and i create a file .compute, that contains only arrays. No kernels at all. When I include It to my main compute shader, i can access the data of the arrays, but if I change the data (manually), the editor will not recompile it.
Futhermore I have this error displayed :
Compute shader Table.compute was not imported correctly. UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
But i didn't find documentation to find how to import it correctly.
Can you help me ?

#

// ============== THIS CODE IS AUTO GENERATED =====================//
#include "UnityCG.cginc"

static const int triTable[64][37] = {
    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
 -1},
    ...
};

static const int3 offsetForVertex[6] = {
    int3(0, 0, 1),
    ...
};

static const float3 verticesForEdge[8] = {
    float3(-0.5, 0.125, 0.5),
    ...
};

#

it's only that. And in my main compute shader I did this : ```cpp

#include "Table.compute"```

grand jolt
#

Wait, you mean access the data through intellisense? As in, it shows you that it found the tables? Or in runtime?

#

And change during runtime or in the editor? And where?

proper cradle
#

No I only write these arrays then lunch my game. But unity do not recompile the Table.compute

#

The data change only in the editor manually, in Table.compute

#

When i am trying to access the data, i only get the old data

grand jolt
#

When access? What old data? You're saying you change it in the editor, then you hit play, and when you read it during runtime, it retrieves the data before you changed it in the editor?

proper cradle
#

And in unity the compute shader is display differently

proper cradle
#

Sorry if my english is bad

grand jolt
#

It's okay, don't worry ;)

#

That's very weird.. if I were you I'd have everything in one big compute file. It isn't pretty, but shaders are barely my province (maybe isn't yours either). Just include them at the very top.

#

Not the best advice, but if you can't get it to work another way...

#

How many tables do you have?

#
// Each #kernel tells which function to compile; you can have many kernels
#pragma kernel CSMain


//8, 3
static const float corners[] = 
{
    -1.0, -1.0, -1.0,
    -1.0, 1.0,  -1.0,
    1.0,  1.0,  -1.0,
    1.0,  -1.0, -1.0,
    -1.0, -1.0, 1.0,
    -1.0, 1.0,  1.0,
    1.0,  1.0,  1.0,
    1.0,  -1.0, 1.0,
};

//12, 2
static const int edges[] =
{
    0, 4,
    1, 5,
    2, 6,
    3, 7,
    0, 1,
    4, 5,
    7, 6,
    3, 2,
    4, 7,
    5, 6,
    1, 2,
    0, 3
};

//12, 4, 3
static const int crossingEdgeVoxelIndexDifferences[] = 
{
    -1, -1, 0, -1, 0, 0, 0, 0, 0, 0, -1, 0,
    -1, 0, 0, -1, 1, 0, 0, 1, 0, 0, 0, 0,
    0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0,
    0, -1, 0, 0, 0, 0, 1, 0, 0, 1, -1, 0,
    -1, 0, 0, -1, 0, -1, 0, 0, -1, 0, 0, 0,
    -1, 0, 1, -1, 0, 0, 0, 0, 0, 0, 0, 1,
    0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1,
    0, 0, 0, 0, 0, -1, 1, 0, -1, 1, 0, 0,
    0, -1, 1, 0, 0, 1, 0, 0, 0, 0, -1, 0,
    0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0,
    0, 0, 0, 0, 1, 0, 0, 1, -1, 0, 0, -1,
    0, -1, 0, 0, 0, 0, 0, 0, -1, 0, -1, -1,
};
//12, 3
static const int edgeCoordinatesVoxelCenterOffset[] = {
    -1, -1, 0,
    -1, 1, 0,
    1, 1, 0,
    1, -1, 0,
    -1, 0, -1,
    -1, 0, 1,
    1, 0, 1,
    1, 0, -1,
    0, -1, 1,
    0, 1, 1,
    0, 1, -1,
    0, -1, -1,
};


float noiseThreshold;
float noiseScale;


... rest of the code
#

This is how I've done it.

proper cradle
#

Imagine my code was that :

    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
 -1},```
And i change it to that :
```static const int triTable[64][37] = {
    {6, 8, 10, 5, 6, 5, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
 -1},```
The editor will display the triangles like if the data  was that :
```static const int triTable[64][37] = {
    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
 -1},```
#

You advise me to delete my Table.compute, and put the arrays at the top of my main code ?

grand jolt
#

-1 is generally reserved for when memory is allocated to a wavefront but is not used. At least that's what I've seen...
Maybe your code never even read from triTable to begin with, and defaults with -1 no matter what...

proper cradle
#

Hahaha, it's not my field yeah 😢
But okay i will do that, and wait to find a cleaner way.

grand jolt
proper cradle
#
  0,  4,  6,  0,  6,  2,  0,  2,  3,  0,  3,  1,  4,  5,  7,  4,  7,  6,
 -1},```
To that
```  {0,  1,  5,  0,  5,  4,  2,  7,  6,  3,  2,  6,  1,  3,  7,  1,  7,  5,
  0,  4,  6,  0,  6,  2,  0,  2,  3,  0,  3,  1,  4,  5,  7,  4,  7,  6,
 -1},```
grand jolt
#

Aaaah I see...

#

I have no idea; debugging shaders is hellish, there's barely any documentation, I suppose there are times you just have to write a little dirtier, just because the environment you're coding in.... isn't that clean to begin with xP

#

That's what I think at least

proper cradle
#

OMG I found the practices !

#

@grand jolt Okay so, i was on github and searching a people who was splitting their code in different files. I find out that is pretty simple.
You just need to create a folder and name it : "Includes"
Then put the Table.compute in it.
then write in the main compute shader : #include "/Includes/Table.compute" instead of #include "Table.compute"
And TADAAAAA

grand jolt
#

Could someone with a solid understanding of Compute shaders help me?

#

I've stumbled across a true witch bug

#

Nvm. Out of bound memory accesses screw up everything. This isn't C# XDDD

#

Man, I'll never get the guts to program in C

tropic badger
#
  • My first time trying shaders. I tried to do a basic "if visible, return this color, else if behind opaque meshes return this color". My attempt is to create 2 passes with different ztest values, gequal and less, where i will return respective colors. This didn't work however, and i would like to ask am i in the right direction at all?
regal stag
# tropic badger - My first time trying shaders. I tried to do a basic "if visible, return this c...

Assuming both passes have ZWrite Off & in Transparent queue, and it's for the Built-in RP that should work.

For URP, multi-pass shaders aren't supported. But you could split it into two separate shaders/materials. Either apply it as a second material or use the RenderObjects feature to re-render a layer with an override material. There's an example in docs : https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@16.0/manual/renderer-features/how-to-custom-effect-render-objects.html

tropic badger
pale python
#

hi ,
im trying to learn shader make something a bit complicated as gradient color between multiple colors , but I basically suck at this.

i couldnt even mix 2 colors together!

i know the easiest way to mix two colors is to just lerp but when it it's more than 2 colors, things get way complex.

in this case i tried to create alpha for the first 2 colors c1 and c2 then somehow add them together , i was able to do so, sort of but i think it ended up horribly wrong as they sorta mixed together with very little grey area between them

float4 mixColors(float2 uv) {
    float4 color = float4(1, 0, 0, 1);

    float4 c1 = float4 (1, 0, 0, 0.5);
    float4 c2 = float4 (0, 1, 0, 0.5);
    float4 c3 = float4 (0, 0, 1, 0.5);
    float4 c4 = float4 (1, 1, 0, 0.5);
    float4 c5 = float4 (0, 1, 1, 0.5);
 
    float3 a1 = 1-saturate((abs(uv.x - 1)) * 1) - 1;
    float3 a2 = 1-saturate((abs(uv.x - 0.1)) * 1) - 1;

    c1.a *= a1;
    c2.a *= a2;

    color = color*c1 + color*c2;
    color.a *= a1 + a2 ;


    return color;
}

my end goal was to create something like this , if someone knows any tutorial or tell me how i could achieve something like that , that would be greatly appreciated it !

#

the corrent result i have is , the part marked on the far left is just a hight concetration of red , but the rest are relatavely the same grey/alpha value

lunar valley
#

I would still use lerp tbh. but haven't done something like this so idk

pale python
regal stag
lunar valley
regal stag
#

The alternative is applying a gradient texture instead which may give more control

pale python
pale python
pale python
#

also i was afraid of shaders and kept ignoring it since I started learning unity, its time to face it , i dont wanna run away from it anymore 😄

regal stag
pale python
regal stag
#

Hmm, well you can generate textures in C# and pass them to the material. That would work unless the colours need to change over time.

pale python
regal stag
#

The calculations in the shader also happen every frame. But the GPU is usually good at that.
With a texture there's still a cost of uploading & reading that from memory so it might even end up being slightly more expensive... but could also more flexible as you can then pass any gradient texture in. And might batch better (especially with URP/HDRP where different materials can srp-batch if they use the same shader)

tropic badger
regal stag
pale python
regal stag
pale python
#

i applied both of them with offset value 0 and 1 , and both of them didnt do anything

#

the square's color was completely unchanged

regal stag
#

If you're using the Degrees, try testing it with a higher offset, like 60. Or with normalised use something like 0.2

#

Or input an offset of UV.x * 360 or UV.x to actually see the gradient

pale python
#

and yes uv.x returns a nice gradient between black and white but i think if i just return uv.x or uv.y i would still get the same results without passing it to the function at all

#

is there is a way to use this function to just make it color 1 potion of the item like a line ? then maybe color another portion with a different color to make the gradient effect ?

regal stag
#

I mean using the UV as the offset, not the In param. Unity_Hue_Degrees_float(float3(1,0,0), UV.x * 360, out color); should produce a rainbow, as you're shifting red through all the other hues.

pale python
#

is it possible to rearrange colors though ?

#

like make a mix between blue, red and green in that order ?

#

just those 3

#

maybe by limiting the offset values ?

#

like only output between ( 30-60 ) and ( 90-120) ?

regal stag
#

If you just want blue/red/green it might be easier to ditch the hue-shift and use multiple lerps

pale python
#

oh not always, that was just an example, at some point i would go with rainbow others just 3-5 different colors that can be completely random

regal stag
#

Hmm for that I think you'd still need lerps rather than the hue-shift - that only really works for that specific rainbow result. You can limit the colours but it would just jump between hues rather than be a gradient then.

#

You'd basically want to use the line or inverse lerps I mentioned earlier (#archived-shaders message) to get a mask of where the colours should blend together. Then lerp to apply that.

pale python
# regal stag You'd basically want to use the line or inverse lerps I mentioned earlier (https...

i did try it ended up horribly wrong , here is the code

float4 mixColors(float2 uv) {
    float4 color = float4(1, 0, 0, 1);

    float4 c1 = float4 (1, 0, 0, 0.5);
    float4 c2 = float4 (0, 1, 0, 0.5);
    float4 c3 = float4 (0, 0, 1, 0.5);
    float4 c4 = float4 (1, 1, 0, 0.5);
    float4 c5 = float4 (0, 1, 1, 0.5);
 
    float3 a1 = 1-saturate((abs(uv.x - 1)) * 1) - 1;
    float3 a2 = 1-saturate((abs(uv.x - 0.1)) * 1) - 1;

    c1.a *= a1;
    c2.a *= a2;

    color = color*c1 + color*c2;
    color.a *= a1 + a2 ;


    return color;
}

where should I learp and how do i lerp with more than 2 colors? for example 5 ?

#

i tried to mix the alpha but that didnt work

#

i've also tried this

 float4 lerp1 = lerp(c1, c2, 0.5);
    float4 lerp2 = lerp(c3, c4, 0.5);
    color = lerp(lerp1, lerp2, 0.5);

that gave me a constant bronze color

#

i think it was a mix between blue ,red , green ,yellow

regal stag
#

To apply multiple colours you'd want something like

float4 color = lerp(_Color1, _Color2, mask1);
color = lerp(color, _Color3, mask2);
color = lerp(color, _Color4, mask3);
#

So chaining the result of the lerp with another, using a different t/mask value

#

In shader graph it would look something like this, if that helps for visuals

pale python
#

like i could try something simple like mask1 = from left to right , mask2 = from right to left ?
or is it supposed to be more like mask1 has a width of x.1;, mask2 has a width of x.2 (since 2 colors are supposed to be mixed) ?

regal stag
#

For the above graph (3 colour gradient), It should be equivalent to :

float inverseLerp(float A, float B, float T){
  return (T - A)/(B - A);
}

float4 Cyan = float4(0,1,1,1);
float4 White = float4(1,1,1,1);
float4 Blue = float4(0,0,1,1);

float mask1 = saturate(inverseLerp(0.5, 1, UV.y));
float mask2 = saturate(inverseLerp(0, 0.5, UV.y));
float4 color = lerp(Cyan, White, mask1.xxxx);
color = lerp(Blue, color, mask2.xxxx);
pale python
left basin
#

Is there a way to have a field that references a GameObject's transform in ShaderGraph?
I would like to make a Shader that switches between 2 Textures as an object passes over them. So that I can have some sort of sweeping effect over multiple objects sharing the same shader.

#

Either that, or a way to sync all my object with the same shader to the same variable

slow pilot
#

Is there a way to prevent my skybox from distorting at the very top and bottom of my skybox?

#

Left being the view looking forward. Right being the view when looking straight up

ocean garnet
midnight pasture
#

Hey all. I'm working on a volumetric ray marched clouds shader and I've run into a weird issue where the self-shadowing (light-marching) lights don't seem to be in the same direction as the sun. Two sides that should have the same brightness don't, and when I rotate the directional light on the x-axis, nothing seems to happen. I've stepped through it so many times now but can't figure out what is wrong. I was wondering if anyone who's worked on this stuff before can take a look? Here is the snippet and image:

{
    float3 sRayDir = normalize(_WorldSpaceLightPos0);
    int sStepCount = _SunMarchSteps;
    float sStepSize = _SunMarchStepSize;
    float sStepVector = sStepSize * sRayDir;
    
    float3 cPos = _WorldSpaceCameraPos + (cRayDir * distToNearPlane) - cStepVector; 
    float cTransmittance = 1;
    float lightEnergy = 0;

    for (int cStep = 0; cStep < cMaxSteps; cStep++)
    {
        cPos += cStepVector;
        float cDensity = SampleDensity(cPos);
        
        if (cDensity > 0.001)
        {
            // Sun Ray Marching (Cloud Point to Sun)
            float3 sPos = cPos - sStepVector;
            float sAccumulatedDensity = 0;
            ...
        }
    }

    float3 radiance = (tex2D(_MainTex, i.uv) * cTransmittance) + (_LightColor0 * lightEnergy);
    return float4(radiance, cTransmittance);
}```

Edit: Found the issue. sStepVector is initialized as a float, when really it represents a vector in 3d space so should be float3.
hot kelp
#

Then to reference it in the shader you'd write "fixed4 _yourtransform" in the pass

sweet burrow
#

I'm trying to make a script that can filter materials depending on whether they cast shadows or not.
Tried to use Material.GetPassName/FindPass/etc, but impossible to get a positive for "ShadowCaster". Those materials are all using URP shaders made in ShaderGraph.
GetPassCount return only 1 pass and calling GetPassName(0) return "<Unnamed Pass 0>". Best info I can get is with GetTag("RenderType") which correctly return Opaque/Cutout/etc, but that doesn't tell me much about shadows.
Is this normal behavior, a bug, or I'm doing something wrong?

patent vector
#

Hi! Having a very odd (at least to me) shader-related problem. I've followed a tutorial on making water in unity, and everything seems to work just fine except one thing - my water is ... gray?

#

I can control the shallow water tint, it is fine

#

but whats funnier than rest of it being gray

#

is this:

#

Its blue as it should be, but only when placed below terrain?????

#

Is this some project settings specific problem?

#

Because same rules apply to fresh spawned cube and plane

#

Below terrain - blue

#

above, gray

#

Or is this something with skybox? I have no idea at this point

lunar valley
# patent vector

looks like maybe the shadows are blue, which tints the rest of the objects?

patent vector
#

Although the lighting is pretty weird in some situations

#

for example my character is unlit

#

guess I need to dig some more into the topic

regal stag
still shuttle
regal stag
still shuttle
#

I see, now I only have to figure out how to do that efficiently 🙂

#

Thanks

tender edge
#

started making my own polybrush shader, but when i select grass it paints stones and vice versa, what am i doing wrong?

#

ah never mind, seems flipping the channels around fixed it

sour imp
#

Trying to make a shader that can do this in urp anyone have any ideas or can point me in the right direction

cosmic prairie
# sour imp Trying to make a shader that can do this in urp anyone have any ideas or can poi...

my quick idea would be to make it transparent, have the paper rendered just regularly lit, as it should be, and add emission to it, which could be calculated from the opaque buffer and a bit of blurring (multiple samples scattered a bit). I guess some light also gets through from the paper getting lit itself, so calculate the lighting of the other side and add some as emission to it too.

#

a bit of faking here and a bit of faking there

#

(the self-lit part would be from subsurface scattering)

#

best way to look at it I think, is just get a piece of paper, hold it at a bright surface and put something in front, see how it reacts etc.. experiment irl 😉

tender edge
#

in shadergraph, is there a performance difference between placing the same node multiple times or dragging the output from just one node multiple times?

elfin dust
#

I made this model and downloaded it (every part seperate) as a .STL then I converted to .fbx because the program could not download as .fbx and then I imported it into Unity. Now, I can add materials but when I add textures it just becomes white or dark colour. How do I fix this?

grizzled bolt
#

Could probably use something like this

#

Though I have no idea how exactly the material works both ways here

#

When I tried it the material was either only showing on both sides the lighting hitting the true front face, or always show only lights hitting the face away from camera

#

In addition to showing shadows through the paper screen you might also be able to utilize scene color and depth to show objects through it in a fuzzy way, and to make them darker closer to the surface to simulate ambient occlusion seen in the reference

limpid orchid
#

hi

#

could anyone guide me on how to learn shader scripting

tender edge
# limpid orchid hi

im very new aswell, but im currently watching ben clowards tutorial series on youtube. it seems very good so far if youre looking for a more proffesional tone

#

is there an easy way to edit this so vertical faces also take world position into account?

lunar valley
tender edge
lunar valley
lunar valley
tender edge
#

im guessing the shader i posted above only works in 2d?

lunar valley
tender edge
#

thanks, ill start looking into triplanar

grizzled bolt
tender edge
#

another question, here im blending 2 pixel art textures with just the albedo as an heightmap, would it be beneficial to create a heightmap for better blending if the textures are so simple? or would it be better to modify the albedo to look more like an heightmap?

grizzled bolt
tender edge
tender edge
# lunar valley not sure what you mean

im also not sure how to word it better, im just wondering if it impacts performance if i place the same node multiple times simply to keep the graph more organized. as opposed to just drawing lines from the same node over and over

grizzled bolt
tender edge
#

i basically make sprites in aseprite, load those into laigter and play with the sliders till i like the result

grizzled bolt
tender edge
#

ah yes, we got a bit offtopic

lunar valley
# tender edge im also not sure how to word it better, im just wondering if it impacts performa...

ah I think I know what you mean, and well it depends. If you are putting a precomputed node like the Position node then it doesn't matter. But if you are calculating things over and over again just to keep you shader graf clean then yes its more costly. For example this is now not shader graf but I hope you still get the idea: cs float a = 1 + 2; float b = a + 2; float c = a + 2; float d = a + 2; // and then for each different input you use b, c, d. Instead of always just using b then yes it is gonna be more expensive

tender edge
tropic badger
#
  • Hello. My second time trying shaders, and this time i achieved a world position of a fragment as a uv coordinate to sample a texture. The problem is, world position and uv are different dimensions, so i have to project them onto each other. I can do this in c#, but i'm utterly helpless when it comes to cg. While i was testing this thing with top-down quads it was as simple as frag.WorldPos.xz, but it doesn't work on anything else. So how can i project vectors in cg?
lunar valley
tropic badger
#
  • A 3d space position of a fragment to uv coordinates
regal stag
tropic badger
regal stag
meager marten
#

hello, i am making a grass shader (shadergraph), and i am curious on how id make the grass in the red circle be as bright as the one in the blue circle? im using render face both, and i imagine it has something to do with the normals, but i am confused on how id go about fixing it? thank you

tropic field
#

that should fix your issue

tropic badger
# regal stag If you use the worldPos, it'll be global axis. It might work with objectPos too,...
  • After i read the article and played around with the included shader, it turns out that it's not what i'm after. Or at least, not always. After i place a perfectly axis-aligned cube and stretch it, it works as expected. But as soon i start to rotate the object, it neither follows its rotation nor tiles properly. I already tried using local coordinates, and this doesn't seem to have any effect
meager marten
tropic field
tender edge
#

i tried adding my base tile node (float) directly to the uv, but it seems that broke the shader. i want to try this material with the uv's ive set on the mesh myself but how can i add a simple slider for tile size?

regal stag
tender edge
#

would using triplanar make all the different faces allign? and would triplanar be feasable if im aiming for a switch release?

lunar valley
warm pulsar
#

I want to make a shader that makes an object "shatter". Each face should move off in a random direction.

It's easy to randomly move each vertex, but that turns the object into spaghetti. I'm trying to think of a way to figure out which face a vertex belongs to (i'm exporting from blender with flat shading, so the faces are already disconnected)

#

maybe i'll just need to bake this into a texture or something?

#

or do something funny with UV1

lunar valley
# tender edge would using triplanar make all the different faces allign? and would triplanar b...

and about the alligning it would be yes and no, so on each side everything is gonna be perfectly alligned but one the transitions if you have like a brick pattern it won't be 100% alligned because you can imagine it how it works by having 6 textures on for each side of a cube and then the texture will be projected onto the geometry you have, so at the transitions between the sides of the textures you will blend between the two textures or not its optional but if not you will have a noticible seam

lunar valley
warm pulsar
#

Yeah.

#

I just need to get a consistent random value for each vertex on the same face.

#

i'll probably blend the normal with the random value to make it explode outwards

tender edge
lunar valley
warm pulsar
#

I don't need interactions or anything

#

particles would be cool, I guess

#

this will be a very fast 'shattering' effect

lunar valley
#

i see

warm pulsar
#

one amusing problem i've had so far; my test object is a cube

#

all of the UV coords are 0 or 1

#

so gradient noise doesn't work

#

since it produces the same value at every position

lunar valley
#

you could just use white noise, that returns pretty random results

warm pulsar
#

well, that'd jitter all over

#

the main issue is still that I can't get all of the vertices from the same face to move together

lunar valley
#

that would be what I wouldn't really know how to do, I mean how would you check which vertex belongs to which face

warm pulsar
#

yeah

#

i might just go with another solution instead, since I did just realize this will make enemies look hollow

lunar valley
#

well gl then

warm pulsar
#

thanks :p

#

this has to be some kind of rubber ducking

#

"this was a bad idea all along"

pale python
#

hi , is it possible to pass a list or an array to shaders ?

warm pulsar
#

they're a little weird, aren't they?

#

they don't show up in the inspector

pale python
pale python
#

?

lunar valley
#

its c syntax

#

float floatArray[];

pale python
#

ah ok , so float4 colorsArray[]; ?

lunar valley
pale python
#

well at most 12

#

how do i specify it ? like this ? float4 colorsArray[12];

lunar valley
#

yes

pale python
#

cool! thanks ❤️

lunar valley
#

I need someones opinion, how should I make scene reflections? Should I use light probes which saves the scene into a cubemap which I could sample from. Or should I do screen space reflections for my water

pale python
#

wait , why does this break everything float4 function(float4 colors[], float value[]){}
as soon as i wrote that line mentioned above in shader , the entire shader went purple even after removeing the line , it stayed purple

#

i hade to hit undo multiple times

#

that was the only way to fix it

#

no errors in the console.

lunar valley
#

so what exactly is your problem now, is it fixed or...?

pale python
#

yeah , i fixed it by adding number to the array i changed this float4 function(float4 colors[], float value[]){} to this float4 function(float4 colors[3], float value[3]){}

#

without the number in the array, the array turns purple without an error , even deleting the function doesnt fix it , i had to undo and redo

#

its so weird!!

lunar valley
#

yeah in shaders you can't have dynamic arrays

pale python
#

so if i wanted to give option for 3 and 6 arrays , i have to make a function for each ?

tropic field
lunar valley
warm pulsar
tropic field
#

you can then try adding the normal vector to the vertex position

#

both in world space

pale python
#

thanks so much ❤️ !

lunar valley
#

np

umbral hemlock
umbral hemlock
warm pulsar
#

i didn't see a node named "Face ID"

umbral hemlock
#

As long as you have a list of faces/triangles, you can pass the index of the face. So each one will be unique.

warm pulsar
#

ah, so i'd need to grab the mesh data and write the vertex colors

proper cradle
#

Hey guys ! I am making a voxel game using marching cubes,
I succeed ! 🥳

BUT, i noticed that when i am upscaling my chunk, i have weird shading issue, and some part of the mesh arrent visible / generated.
How come ?

prime shale
#

technically you can use light probes as reflections, since technically with light probes they are a representation of an enviorment at a given location. But they are sampled at most using 3rd order spherical harmonics so the results are VERY blurry and low frequency. and are primarily used for diffuse lighting

meager pelican
prime shale
#

so yeah both are a typical combo

#

if your absolutely broke I suppose one could use light probes to get a semblance of reflections lmao

meager pelican
#

I think they just meant to type "reflection probes"...

prime shale
#

yep ik

#

but just saying technically you could

#

but its definitely not desirable especially since a better alternative already exists

#

this was a test I did recently actually, top using reflection probes, bottom using light probes sampled with 3rd order SH (highest quality that unity has by default) as a proxy for reflections

#

in a pinch, could work, but definetly better off sticking with reflection probes/cubemaps if you can

mental lake
#

Just upgraded from 2021.3 to 2023.1, and one weird thing that happened is that my blit isn't working anymore? When looking the same renderer feature in the rendering debugger, it looks like it's not drawing a quad (4 vertices) anymore.

#

Renderer feature in 2021.3:

#

What it looks like now in 2023.1:

#

And the blit command:

#

Basically, no matter what I output in the shader, the render texture stays black. I assume it's because a quad isn't even being rendered

warm gate
#

I’m not sure where to ask this tbh.
I have been working on a character customization system for my RPG game for some time now. And so far, the character entire body shape can be customized, and the next thing to do is to allow players to customize colors on different parts of their characters, like lip color, body color, eyes color, etc. One way I know of to achieve this is using multiple materials, but I read that it isn’t good for performance. So what do you suggest?

tame ingot
#

Hi. I have a cube using default lit material, and a slightly bigger cube in the same position using my custom shader.(image 1, bigger cube is slected)
This shader is very simple. It just uses a main color and changes ZTest to GEqual.

    Properties
    {
        _MainColor("Color", Color) = (0,0,0,0) 
    }
    SubShader
    {
        ZTest GEqual
        Tags {             
            "RenderType" = "Opaque"
            "Queue" = "Geometry+1"
            "RenderPipeline" = "UniversalPipeline" 
        }
    ...
    }

I dont' know why the bigger cube is not showing anything.
There are three faces of the bigger cube behind the smaller one(back left, back right, and bottom). Why did they not pass ZTest?

I've created a quad using the same shader, and place it behind the smaller cube. And it behaves as expected.
So what I'm missing here?

lunar valley
cosmic prairie
# proper cradle

That's not marching cubes and that's not a shading issue, you are messing up your mesh somewhere

#

make sure to clear the mesh and your buffers before regenerating it

meager pelican
tame ingot
# meager pelican Did you try LEqual?

But isn't LEqual the default of ZTest? I change to LEqual and the smaller cube is occluded. Well, since the smaller is inside the bigger one, this is expected and makes sense to me.

lyric vortex
#

Hello I'm trying to create a procedural skybox. I would like to render a cubemap from my shadergraph. I have added a cubemap asset node, then a sample cubemap and the output of the sample cubemap is put into the fragment base color. It doesn't work, it's like if only the Front face is rendered. Could you please tell me what is wrong ?

lunar valley
#

is your hdr or exr texture you are using set to cube in the import settings(not sure if thats the correct name I kinda forgot it)

regal stag
# mental lake Just upgraded from 2021.3 to 2023.1, and one weird thing that happened is that m...

Newer versions should use RTHandle and Blitter API. The Blit function itself may already be doing this behind the scenes now. Should use _BlitTexture instead of _MainTex and it needs a specific vertex shader. Can use the Fullscreen graph type, or a shader similar to this : https://github.com/Unity-Technologies/Graphics/blob/master/Packages/com.unity.render-pipelines.universal/Shaders/Utils/Blit.shader

regal stag
lyric vortex
#

Cyan, what do you mean ?

regal stag
lyric vortex
#

Cyan, currently my skybox shader works properly. I would like to add a cubemap texture into it. But this texture is not rendered correctly. Is "World Space" is the correct Dir for a sample cubemap in a skybox context ?

regal stag
#

It might help if you show an image of what is wrong with it. " it's like if only the Front face is rendered" isn't very clear.

lyric vortex
#

ok I'll show you

#

This is my test cubemap texture:
Only the Gray is rendered on sceen

#

And this is my shader graph:

regal stag
lyric vortex
#

And this is my cubmap texture import settings:

tame ingot
regal stag
regal stag
regal stag
# warm gate I’m not sure where to ask this tbh. I have been working on a character customiza...

Multiple materials isn't that bad in URP due to the srp batcher, which batches materials as long as they share the same shader.

But you could also create a texture palette (Point filter mode) that is passed into the shader. Each pixel could correspond with a different body part, and the mesh would be UV mapped to match that. To allow for customisation, can regenerate that texture at runtime (e.g. via SetPixels method in Texture2D class) and pass into Renderer.sharedMaterial. (Only generate the texture when changes are made that is, not every frame)

lyric vortex
tame ingot
tame ingot
#

If I adjust their positions, not making them overlap and make the smaller in front of the bigger one, I can actually see the larger cube which means ZTest GEqual is working.

regal stag
lyric vortex
lunar valley
tame ingot
#

I would like to know normally is it supposed to behave like this? When they overlap, the overlap face of the larger cube is visible from left side, but not from right. But I think no matter from which side, the overlap face of the larger cube should pass ZTest GEqual.

regal stag
#

Perhaps you want Cull Front so you're rendering with the cube's back faces instead

regal stag
lyric vortex
regal stag
#

Yeah I left it at 1. I think it just needs to not write to the depth buffer as that seemed to break the skybox rendering in URP

tame ingot
regal stag
#

Yea, I missed that earlier

tame ingot
cunning herald
#

Hey everyone. In my game I use URP and standard toon shader made by Unity. I've bumped into a problem where decals do not project onto objects with toon shader. Is there a fix for this or a workaround? Maybe I need to make a special shader for this or scrap the idea of using decals

lunar valley
regal stag
cunning herald
lunar valley
vivid marten
#

is split the only way to do this? I want to grab the output from the x and y coordinates separately but Split gives me too much

regal stag
#

There is also a Swizzle node that can grab components, if you prefer that

vivid marten
#

hmm swizzle only has one output tho?

#

collapsing works but it feels like a hacky solution cuz it gets me RGBA values instead of x and y 😂

regal stag
#

RGBA=XYZW, they're the same thing just different labels

vivid marten
#

oh

#

so then it's a proper solution lul

#

so in this case Split acts like a vector 4?

regal stag
#

Split always assumes 4 components yeah. Even though the input is a Vector2. The BA/ZW components likely default to 0 and 1.

vivid marten
#

aha

tender edge
#

updated my shader to now use triplanar, i couldnt work out what the blend mode does on the triplanar node, could i use it for blending vertex colors?

tender edge
#

also made a heightmap for blending but didnt really notice a difference, think its not really necesarry when the textures are so low res

lunar valley
#

I have a bit of any issue, I am doing some reflection by rendering the scene twice using the camera setup shown in the second picture, the second camera which is flipped is being rendered into a render Texture which then is displayed on the flat plane you can see there. The issue is that when the cube is about-to-go/is below my plane the reflection on the plane still exists. How can I prevent that?

young fog
#

Hi Cyan I'm using your Blit Render Feature, all I want to do is reveal the scene on the black part, how would I do that?

lunar valley
#

check if the pixel is black if so render your game else not

pale python
#

hi ,
how do we add items to an array in shader?
float4 array[2]; , how do i add float4 to it ?

#

i think shader is written in c not c# right ?

lunar valley
#

I said c syntax before because this: float array[]; is also c syntax

#

but in the frag function you can set the element of an array just like in c# by doing array[0] = float4(1, 1, 1, 1);

young fog
lunar valley
young fog
lunar valley
young fog
#

It's on the camera through URP, I used Cyan's Blit feature to do that

lunar valley
young fog
#

I've never used a branch node tbh

lunar valley
young fog
#

I just gotta do the opposite of this and I think it's ok

#

there's definitely a simpler version but whatever

#

actually, that's right

#

thanks