#archived-shaders

1 messages · Page 28 of 1

meager pelican
#

Hey, where did the question go?

hazy zinc
#

@grizzled boltcould you please give me a search direction? my render texture is flipped and showing not the area I need. I need to somehow match the camera and raw image, so that I would get an effect on area, not some other area... I'm stuck at this point.

modern tartan
#

Hi, can someone help me with custom node in shader graph please ?
I'm struggling on it for more than an hour when it seems to be just a missunderstanding of the naming convention

The image is my node setting
The file is :

void IsVertexInsideCollider_float4_float4_bool(float4 v, float4 colbounds, out bool Out)
{
    bool test = v.x >= colbounds.x && v.x <= colbounds.y && v.y >= colbounds.z && v.y <= colbounds.w && v.z >= colbounds.z && v.z <= colbounds.w;
    Out = test;
}

And the error is : undelcared identifier isVertexInsideCollider_float4_float4_bool_float

Whatever how i change the name it ALWAYS add an _float at the end in the error

grizzled bolt
hearty obsidian
#

Is there a way to say : If greater than 1, then 0, without a predicate AND preserve the original value if less than 1? e.g. I want to lerp something's alpha based on a normalized distance.
0 is transparent, 1 is fully opaque, greater than 1 is transparent.

I can use a predicate but I wanted to make sure there wasn't a way I was unaware of before I did

simple violet
#

Modulo

hearty obsidian
#

How so? It won't keep it at 0, it'll reset the 0-1 range ad infinitum, won't it?

simple violet
#

Oh

#

Idk then

hazy zinc
hazy zinc
hollow cargo
#

Yeah, I set it up using world position, but it was not looking correct. Not sure how to altering it to do so, but will try some more things. Mainly it went from the nice sun-wave effect to just a gritt look

meager pelican
lament karma
#

Trying to understand shaders a bit better. What I'm trying to do here is grab all the vertices of an object that align with the Direction variable and offset them in that direction. What ends up happening though is them being offset in a strange direction...
In the picture the Direction Vector3 is (0, 0.5, 0), but it doesn't offset straight up. Anyone able to see what I'm doing wrong here?

swift loom
#

Bit of a vague long shot but I'm trying to figure out how to allocate and utilize large amounts of volume data in compute shaders (meaning, reading and structuring voxel data for use on the GPU) for raycasting, and I'm wondering if anyone knows any resources to help me get past the initial bump. I'm having trouble figuring out how to structure large bitmasks (512 bits) and how to send them to the GPU via buffers properly and I am really having a hard time finding any information on this.

shadow locust
swift loom
#

Thanks this is exactly why I am asking because I don't have enough contextual knowledge to find the right things. This looks good.

Basically what I am trying to do, or my understanding of what I need to do, is that I need to create a voxel struct on the shader with the information I need it to contain, then upload that from the CPU via a structured buffer. Then I need to send my bitmasks and whatever indices and information I need to be able to set up either a sparse octree or a brickmap as a method to find the indices and as a method to skip empty space while raycasting in the compute shader. Does this make any sense?

onyx talon
#

Is there anyone know how to achieve this kind of refraction effect?

ripe magnet
#

Can you read last frame occlusion culling overdraw from a shader?

meager pelican
# ripe magnet Can you read last frame occlusion culling overdraw from a shader?

Not that I know of. OC is an optional CPU-side thing in the engine. The shaders, by definition, don't even get called for OC culled renderers.
Overdraw is a different matter for those renderers that aren't culled. The editor has a set of shaders for visualizing overdraw, so shaders can be used to collect that data and I suppose you could pass the result to the next frame. I haven't checked them out, but they appear to accumulate color (like a heat map) per pixel into a render texture. So every time a pixel is updated it adds to the heat map.

ripe magnet
#

Would it be better in terms of performance to do my own culling solution that is GPU-side?

meager pelican
#

Not usually. The fastest polygons are the ones you DON'T draw. 😉
So not submitting what you don't need to the GPU is the way to go. Your shaders should only "see" what they're supposed to draw, not what they aren't supposed to draw.

That said, there are use-cases for GPU geometry and culling of either whole meshes or individual polygons. This comes up in things like ray-tracing and procedural geometry generated on the GPU.

ripe magnet
#

okay thanks.

meager pelican
#

It all depends on your use case. But shipping the entire scene's geometry up to the GPU isn't for the faint of heart.

smoky vale
#

how does the shader graph work

tacit stream
#

it works good

olive junco
#

Does somebody know, how to achieve this vertices-stuttering effect like at the end of this game? https://www.youtube.com/watch?v=MEbJ71Ld_zY

Iketsuki - Atmosphärischer Plattformer
Deutsch/German Review - Iketsuki - Horrorgame Gameplay Playthrough + Ending
Iketsuki Download: https://modus-interactive.itch.io/iketsuki
——————————————————————————
▶Hier könnt ihr mich unterstützen!: ▶https://www.patreon.com/corrupty
——————————————————————————
▶Mehr Horror Einteiler:
https://www.youtube.c...

▶ Play video
#

Oh it's in the whole video but you can REALLY see it at the end

grizzled bolt
peak dagger
#

Is there any way I can use one material for a mesh with multiple colors. Except for the color all parts of the mesh have the same properties.

tacit stream
#

Are there any resources on DOTS_INSTANCING_ON?

meager pelican
# peak dagger Is there any way I can use one material for a mesh with multiple colors. Except ...

There are ways. May depend on what pipeline you're using.
Firstly, I assume you mean multiple instances of the same mesh, each instance having its own color attribute but otherwise all are the same material. If you mean vertex color on one mesh, that's a different answer than this.

You can look into GPU instancing. This uses Unity's Material Property Blocks (MPB's). You set each instance's color property on the renderer. More info here: https://docs.unity3d.com/ScriptReference/MaterialPropertyBlock.html and Google is your friend. I think it will also work in URP, if you use the proper property name, but generally instancing MBP's isn't up to snuff in URP...but color works IIRC. IDK about HDRP.

meager pelican
#

Pay attention to the SRP batcher thing.

#

There are other ways. But if you're using URP, you might just want to maintain batcher compatibility and use a different material for each instance. But that's the opposite of your question.

peak dagger
meager pelican
#

Oh.
I don't understand that statement.
If you only have one instance, set the color on that instance as you need it set.

#

If you have multiple instances of a mesh, and each has its own material, you can set each material's color directly. In that case don't use Renderer.sharedMaterial, set a new instance of the material on each renderer. This is done behind the scenes by Unity automatically, if you assign to Renderer.Material. It clones the material and make a unique copy of it for that renderer. @peak dagger

peak dagger
#

For instance, I would like to have the same material in the 6 slots on the right while maintaining the colors of the weapon.

tacit stream
#

is one way

peak dagger
karmic hatch
karmic coyote
#

How do I make a shader for a plasma cannon/gun

grizzled bolt
patent yoke
#

how can i access the scene's depth texture in HLSL? (urp shader code)

subtle granite
#

Guys guys I was doing an impostor using a octahedran, to be more exacly I have used indices of the uvs to get vertices of the mesh. In this way I can order texture in an atlas and finally I save the image

#

I have used uvs like indices of vértices and I have removed repeated indices yo use it like a posición of the camera

#

Now my problem is how to create a shader that use a piece of the texture atlas? Someone have a idea

#

;this is my atlas texture

#

This is my billboard

#

I don't know what to do anymore I need to find out how to get the small images inside atmas

mighty moon
#

Is anyone able to help me with my ring shader? I have it setup like this, and in the main preview it looks good, but in-game it looks like the 2nd pic and i'm not sure why, i think something is going wrong with the alpha but im not sure what

vocal narwhal
karmic hatch
#

^

mighty moon
#

When I give it a maintex it looks good in preview but off again in the editor

#

im not sure why theres such a difference between the two

karmic hatch
#

rather than using ddxy, use step

#

@mighty moon

#

(and then you don't need a divide either)

mighty moon
#

Thanks

#

It works now ^^

meager pelican
# peak dagger For instance, I would like to have the same material in the 6 slots on the right...

OK.
A material is just a shader reference and a bunch of property values.
So for your 6 elements, you can have 6 instances of material "foo", each with its own primary color assigned. You'd probably assign that to 6 meshes that all compose the gun parts. They would be "owned" by a parent object of "gun".

You can also assign multiple materials to a single mesh, and they overlay each other often with transparency for whatever parts that element doesn't apply to. But that's 6 draw calls of the entire mesh (redundant).

Another way would be to have a color array assigned to the shader, and have the shader use vertex colors to identify what parts of the mesh get what element.

GPU Instancing would be more about having 50 of those guns on a display rack, each slightly different.

quaint coyote
#

Hello everyone, wishing you all a happy new year 2023!
I am trying to render clouds on mobile devices and as far as I could do some research, I've been able to generate volumetric clouds nicely.
but they are "Expensive"

#

Would like to have your opinions or some resources someone can point at. But it has to be Mobile 😄

#

Thank you !

cosmic prairie
onyx talon
quaint coyote
# cosmic prairie Volumetrics are expensive no matter what, but if you provide the technique you a...

Thank you! the current technique that I am using is raymarching and using volumetric cloud textures. What I am looking out is this https://thatgamecompany.com
they have a game called sky

onyx talon
#

Applying the ray marching effect to 2d texture

quaint coyote
onyx talon
#

Use real volumetric cloud is very expensive on mobile, so just fake one.

quaint coyote
onyx talon
#

In order to fly through it, you can use particle to make a fake cloud and use custom light maps to make it looks real, or make the ray marching step lower and don't apply the anisotropy effect to the cloud.

amber saffron
#

Clouds in Sky don't look very transparent, except when intersecting the land, so I suspect they are made of meshes with a distance fade effect.

onyx talon
#

However, this does not solve the problem that the cloud looks fake.

#

depth fade is the fundamental part of cloud

#

The cheapest to do this is use a custom light map to make the cloud looks real.

cosmic prairie
onyx talon
#

Make the thing can be done in real-time on a pc be done in your hand.

cosmic prairie
#

And how do you want them to look like? Stylized, realistic, etc, a reference would be nice

quaint coyote
#

@amber saffron @onyx talon , I will try the 3d mesh for sure. It seems making a basic 3d mesh with a fractal transparency would work. Then blur it in a separate pass. Would have to give it a try... Pheww! Blender to help 😛

quaint coyote
# cosmic prairie What are your exact requirements, what kind of interactions will the player have...

Thank you once again, Ideally, the player doesn't have to go through the clouds much. But the expectation is good fractal clouds and decent amount of movement with some lighting and dramatic colors. Let me share an example:
https://www.youtube.com/watch?v=4QOcCGI6xOU

Clouds are lovely and fluffy and rather difficult to make.
In this video I attempt to create clouds from code in the Unity game engine.

Project source (Unity, HLSL, C#) is now out of early access:
https://github.com/SebLague/Clouds
If you'd like to support the creation of more videos like this, please consider becoming a patron:
https://www.pat...

▶ Play video
#

PS: I've done this already and is optimized as well. Just that It does not simply work as expected on mobile devices because of high rendering costs 😛

cosmic prairie
#

Yeah I know, I made my own raymarcher too for 3d volumes but it runs like crap on mobile, if you want to have something similar to that, easiest way would be with soft particles, they would have depth fade and they also fade near the camera

onyx talon
quaint coyote
quaint coyote
onyx talon
#

The whole point of this article is the six way lightmaps

quaint coyote
#

BTW, this is outta curiosity, do you guys often run into situations when you've to issue custom draw calls (Graphics.drawmesh..)

quaint coyote
cosmic prairie
#

why?

quaint coyote
# cosmic prairie why?

so I was thinking on the lines of optimisation. Using a mix of static batching and then gpu instancing right now. But would issuing custom draw calls really makes sense. For a fact, I know(while rendering in VR, performing a multi-threaded frustum and tree based culling on cpu does makes a lot of difference), which means you only render the meshes you require. It doubled up the FPS from 35 to 75+ and even 90 at times. Which is a huge deal. But that was done using a small trick of enabling and disabling mesh-renderers

#

so is there a custom render queuing and issuing of draw calls in those Big AAA games?

#

(not talking of those which have custom game engines)

cosmic prairie
#

I'm not sure about big AAA games, but you could for sure do some custom culling inside burst compiled jobs and the SRP if you want to make it cleaner than just disabling mesh renderers. But, most times I just do exactly that when I need a custom culling haha 😛 just disable the renderers, although I do not have millions of meshes, just a few with high vertex counts

#

I'm sure games like excape from tarkov probably has some custom culling system, unity's default culling does not cut it with scenes like that

quaint coyote
vast saddle
#

Is there any reason why the cut off isnt faded?

quaint coyote
vast saddle
#

No difference, I thought it was that too!

quaint coyote
#

also you dont need alpha clipping

#

and if you do, the threshold is too high

vast saddle
#

Oh yeah, that did it!

#

thank you

quaint coyote
#

🙂

gray panther
#

The texture is seamless, but you can clearly see the repetetivness, how can I fix it?

quaint coyote
#

as its not seamless...
There are techniques where you can add other textures on top of it, or use layered materials. I am curious to know how to make a texture look seamless which actually isnt seamless...

gray panther
#

But the further you go, the clearer is the repetative effect, which is common.

quaint coyote
copper falcon
#

Does anyone of the shaderexperts here have an Idea how to iterate over additional lights when using URP forwardPlus?

grizzled bolt
gray panther
#

What about texture rotation?

#

is there a way to do rotatre the texture by 90 degree without programming?

grizzled bolt
karmic hatch
subtle granite
#

Guys is there a way to send a vertex data and anything more across buffer, for example I have a button made in c# where every time that I press it I would like to create a vertex buffer of a octahedran and send it to my custom shader, is it possible?

shadow locust
#

maybe you want to just create a mesh?

subtle granite
#

No no, I have to created a impostor atlas using a octahedran, and a camera, so I have create a shader billboard, but I need that impostor change every image of atlas, when I see it of differents angle

#

But to do that I need vertices of octohedran in my shader to send a ray of my camera and calculate the position of this ray match with a face of octohedron

#

And use the vertex closest to use its image

knotty juniper
#

if the mesh never changes you could just hard code the data into the shader

burnt wigeon
#

Hi! I am wondering, my math is failling me right now I cant figure this out

#

I made a simple billboard shader

#

which works great in shadergraph

#

but only if the object's global rotation is equal to the identity (aka 0 0 0 euler)

#

if the object is rotated by any parent then the effect breaks

#

just a simple cross product with the camera direction

#

then multiplied with the object space position

#

can I tackle this entirely in shader or I have to make an script to compliment it?

#

the script solution is trivial lol


public class SetGlobalRotation : MonoBehaviour
{
    public Quaternion targetRotation = Quaternion.identity;
    
    
    void Update()
    {
        transform.rotation = targetRotation;
    }
}


#

but I wanna try to be as performant as possible with these lights

normal falcon
#

Hello, is there a way to override "render face" setting in a material that uses the shader? I REALLY don't want to make a duplicate of the entire thing just because I need a two-sided version.

dusk oracle
#

hey i have an error installing shadergraph

#

it gives me an error

#

Library\PackageCache\com.unity.shadergraph@12.1.8\Editor\Generation\Targets\BuiltIn\Editor\ShaderGUI\MaterialAssemblyReference\RawRenderQueue.cs(12,24): error CS1061: 'Material' does not contain a definition for 'rawRenderQueue' and no accessible extension method 'rawRenderQueue' accepting a first argument of type 'Material' could be found (are you missing a using directive or an assembly reference?)

shadow locust
dusk oracle
#

i am using version 2021.2.7f1 originally it didnt work then and still doesn't work whenm i upgrade to 2021.3.15f1

#

or 2021.3.16f1

shadow locust
#

try upgreading that too

#

Also you ideally should be on 2021.3 latest

dusk oracle
#

it said it was avaliable on 2021.3.16f1 but doiesnt appear in opackage manager i am on 12.1.8

#

i am using the most up to date 2021 version as well

#

after looking into it there is a file missing in the Library\PackageCache\com.unity.shadergraph@12.1.8\Editor\Generation\Targets\BuiltIn\Editor\ShaderGUI\MaterialAssemblyReference\ directroy

#

@shadow locust do you another solution

wary horizon
#

If i wanted to make an effect where for example:

A bullet hits a mesh with a collider, a completely transparent shader ripples from the impact origin? what would i need to research for this type of effect?

karmic hatch
# wary horizon If i wanted to make an effect where for example: A bullet hits a mesh with a co...

Unity Shader Graph - Shield Effect & Impact Detection Tutorial

In this Shader Graph tutorial we are going to see the steps I took to create an awesome Shield effect that detects hit collisions. The impact detection is done with a script that controls a property of a Sphere Mask in the shader.

***NEW SHIELD TUTORIAL: https://youtu.be/IZAzckJaSO...

▶ Play video
jovial rapids
#

trying to modify a bog standard unlit shader to multiply a texture with black for a shadow effect on a tilemap. was wondering if i could store the lerp value in texcoords0, so when I set UVs for the tilemap I could pass it a vector3 with the blend value in uv.z? or do I need to store it in texcoords1 and read from there

narrow iron
#

What are my options for defeating the 65535 thread group limit in compute shaders?
Somewhere I read that using DispatchIndirect would let me do something but I haven't tried it yet.

mossy crest
#

Anyone knows why Toon Shader (UTS3) failed to compile on fresh project (2021.3.16f1 URP)? works on editor but shows black on build.

quaint coyote
smoky vale
#

so im super new to shaders, like UNBELIEVABLY new, i just followed a tutorial on how to make a basic unlit albedo with modifiable color shader, and i dont understand what this error means

Shader "Lighting/Dither"
{
    Properties
    {
        _Albedo("Albedo", 2D) = "white" {}
        _Color("Color",Color) = (1,1,1,1)
    }
    SubShader
    {
        Pass
        {
            CGPROGRAM
            #pragma vertex Func1
            #pragma fragment Func2
            #include "UnityCG.cginc"
            struct appdata {
                float4 vert : POSITION;
                float2 uv : TEXCOORD0;
            }; 
            struct v2f {
                float4 vert : SV_POSITION;
                float2 uv : TEXCOORD0;
            };
            fixed4 _Color;
            sampler2D _Albedo;
            v2f Func1(appdata IN)
            {
                v2f OUT;
                OUT.position = UnityObjectToClipPos(IN.vert);
                OUT.uv = IN.uv;
                return OUT;
            }
            fixed4 Func2(v2f IN) : SV_Target
            {
                fixed4 = pixColor = tex2D(_Albedo, IN.uv);
                return pixColor*_Color;
            }
            ENDCG
        }
    }
}
quaint coyote
#

@smoky vale Check your v2f struct. Instead of vert it should be position.
Or on line 29, change out.position to put.vert

#

I am unsure, but are you new to peogramming as well? It’s not a shader error but a variable declaration in a struct 🥶

smoky vale
#

i suppose you could say im new to programming, i guess im just new to the language? is that dumb to say?

quaint coyote
#

No no, don’t take it otherwise. Just a small advice, try to understand how this shader thingy works haha

#

Didn’t mean to offend you man! You’re doing good 👍

smoky vale
#

i mean ive only worked in c#, lua, a little python, once tried html, so yeah im sorta new to programming

smoky vale
quaint coyote
#

Cools 👍

smoky vale
#

ok hold on

quaint coyote
#

Yes you’re passing on data from vertex to fragment. Your input structure has vert and uv. V2f has vert and uv. But you’re assigning position variable which is not present in the v2f struct

smoky vale
#

ok god it working, thanks

quaint coyote
#

👍👍👍

quaint coyote
#

Good luck and keep learning 👍

sullen topaz
#

hey, im wondering how to get a continuos texture, so its not stretched like it is down below:

#

is there an option for that

#

?

sullen topaz
#

nvm i got it, you can stop worrying guys

#

thanks for your help :)

quaint coyote
#

guys, how do I implement the queue control system in the material? Unity seems to have replaced it with a slider now in advanced options. But I'd like to put the queue manually

quaint coyote
prisma compass
sullen topaz
#

tiling

#

on the material i used

#

i have to do it manually for each object which sucks

prisma compass
#

You can create a script that change texture's tiling depending of the dimension of your gameobject tho

sullen topaz
#

oh, do you have an example script or something?

waxen totem
#

guys i use this shader but it got error

amber saffron
waxen totem
#

yeah

waxen totem
amber saffron
#

Sure ? Then maybe the shader is outdated and points to a no more existing file

#

Yes, this file doesn't exist

waxen totem
#

can i send error code here?

amber saffron
#

I don't think it will help, the file is not found, that's all

#

Ah, my bad, I was looking at the wrong folder, the file is still there, so it "should" work

#

Again, are you 100% sure URP is imported ?

waxen totem
#

i just grab folder and put inside that all

sleek kite
#

If I'm writing data to a compute buffer, is there a performance benefit to storing them as vector types or does it not matter?
e.g. 1 float4 vs 4 float

amber saffron
amber saffron
amber saffron
waxen totem
waxen totem
#

I follow YouTube tutorial but ...

amber saffron
#

First step : import the Universal Render Pipeline using unity's package manager : window -> package manager

waxen totem
#

Ohh

#

I see

#

I saw YouTube he just grab whole file put inside unity and then the shader show up

waxen totem
amber saffron
#

No

stray loom
#

what is a cause for a standard shader to not work in built in render pipeline?

#

I have a project in built in/standard rp, and the standard shader is pink

amber saffron
stray loom
#

no messages in concole just pink

amber saffron
#

Interestingly, there is some lighting on the sphere, it's not full "error pink".
Maybe the ambiant (sky) is broken and needs rebake ?

stray loom
#

in play mode everything is pink

#

its only in some areas and its weird, i made a empty scene and its pink, but the uma scene works fine

#

but all new materials i create using standard shows pink

#

i tried removing/reinstalling post processing didnt seem to effect

#

and no baking i dont know how to do that on a day/night cycle 😛 just using a directional light

amber saffron
stray loom
#

if add skybox to cam it shows in game view but editor mode still pink

amber saffron
#

Not on the camera, in the lighting settings

stray loom
regal stag
#

Window -> Rendering -> Lighting, iirc

stray loom
#

oh

regal stag
#

After changing skybox there may need to hit the Bake button to tell unity to change the ambient lighting

stray loom
#

trying to find sky setting, i only see Enviro Reflections Source - Skybox

regal stag
#

I think assigning a skybox material is the first thing under the Environment tab?

stray loom
#

maybe cause unity lost internet ? i cant connect the project package manager says error refreshing packages, was thinking maybe re-import enviro since handles sky and stuff

#

ok found it, so now in scene view shows skybox bg, but checker board is still pink

waxen totem
#

like this

#

@amber saffron

stray loom
#

so i created a new material, standard, shows 'ok' as jut grey

#

if i add a texture, it is grey but also pink tinted

amber saffron
stray loom
#

i dont have urp

amber saffron
# stray loom

Did you hit the "bake lighting" button in the lighting window ?

stray loom
#

its a standard 3d project not urp or hdrp

waxen totem
stray loom
#

i hit bake lighting did something for a quick second but since empty scene not much to do

shadow locust
amber saffron
stray loom
#

the shader name is standard

shadow locust
#

I think that's a different person...

shadow locust
stray loom
tame topaz
amber saffron
#

Yeah, sorry, misclicked the answer button

shadow locust
waxen totem
#

found it

stray loom
#

ummm it fixed

waxen totem
stray loom
#

so in the Scene info in lighting, i clicked new lighting settings and it works

#

so i iguess somehow my demo lighting settings are broke

waxen totem
amber saffron
# waxen totem

Shader compilation errors don't clear out automatically, they can stay in the console even when fixed.

waxen totem
#

so what should i do test it out first?

amber saffron
stray loom
#

yep that fixed it, all my pink materials now showing again, thanks for pointing to the lighting setting >.> had no clue but new settings over the demo settings seems to have fixed all the pink shaders i can see

sacred patio
#

Hey everyone, is there a way to stop the fresnel effect to fade based on the camera position?

#

So that it's equally distributed and fades every edge of the mesh

grizzled bolt
#

It doesn't do that, exactly
What you're seeing here is the effect of perspective, as the surface extends past the camera, their relative angle changes
For the angle to be uniform the camera would have to be orthographic

waxen totem
amber saffron
#

it needs to bet set up afterwards

amber saffron
#

Follow urp setup steps from the docs

waxen totem
#

where the docs?

waxen totem
#

but why i getting error

#

?

grizzled bolt
waxen totem
waxen totem
waxen totem
buoyant lily
#

Hey guys I'm trying to use unity's toon shader and it keeps randomly making some assets glow too much

#

anyone knows how to fix this?

sacred patio
glossy loom
#

Hey Guys.

As simple as it goes (hopefully): I'm wrapping a world grid functionality up. Which begs the question - would you happen to know of a shader (or of a way I could procedurally modify an existing shader - I'm writing a mod, the more I can do in pure code the better) that always remains unapologetically white despite lightning conditions (so also in the middle of the night), but itself doesn't emit white light on surrounding objects?

shadow locust
#

there's probably a built in one

#

in fact what you're describing is basically the "Hello World" of shaders

glossy loom
shadow locust
glossy loom
#

in fact what you're describing is basically the "Hello World" of shaders
I would expect so TBH. I never claimed to know the frist thing about shaders, and I would like to achieve this effect by not needing to learn much more than that 😉

shadow locust
#

it looks like parts of it is occluded by the grass

#

but not lit

#

It also looks like it's being affected somewhat by post processing

#

e.g. bloom

glossy loom
#

(The oclusions is a different problem that I would like to solve in it's own right. I tried using an additional camera which was ALMOST good enough, but it unfortunately also cut through the player character)

grizzled bolt
#

Bloom is dependent on the final brightness of the pixels, so it can't be controlled in shaders

glossy loom
#

However, I assume you might be right about the postprocessing kicking in.

shadow locust
#

yep, that's postprocessing

glossy loom
#

AFAIK Valheim uses the "Scriptable Render Pipeline". That's probably where my extremely simplistic shader gets hijacked?

low lichen
#

Bloom should always be used with HDR and the threshold set to 1 or higher, so you can still have full white pixels without them contributing to bloom, but not all developers do that, either for performance reasons or ignorance.

#

It's possible they are using the alpha channel to store how much each pixel contributes to bloom, like Beat Saber does. But most likely they have their bloom threshold set to lower than 1, which means it's impossible to have fully white pixels on screen without them glowing, unless you render it after post processing, but at that point the depth buffer is probably cleared so it would render on top of everything.

glossy loom
#

I'll check the alpha channel hypothesis.

#

How do I get it below the threshold? Do you mean Color(1, 1, 1)?

low lichen
#

Yeah, you can return a light grey

#

Won't be white, but like I said, that's impossible if they've set their threshold to less than 1

glossy loom
#

So theoretically (0.99..., 0.99..., 0.99...) should be enough? But in practice they probably set the thresh to something like (0.5, 0.5, 0.5) anyway?

#

But there probably IS a thresh somewhere?

low lichen
#

No, 0.99999 is likely not enough. I'd guess it's somewhere around 0.85 and 0.9.

glossy loom
#

I'll play around.

low lichen
#

That's the problem of using bloom without HDR, you have to set the threshold pretty close to 1, so not everything starts glowing, but then the spectrum of how "bloomy" a pixel is becomes close to binary.

glossy loom
#

In the meantime, any idea how could I avoid the terrain occlusion problem? In practical terms I need a specific layer (the one containing the lines) to ALWAYS "win" over a different specific layer (the one containing terrain) while obeying the depth of all other layer interactions. As far as I can tell from scouring the internet it seems kind of an "all or nothing" situation. Where I can easily draw my grid on top of everything (including the player and 100m tall buildings) or just suck up the occlusion. Which seems... difficult to believe to be the case (what about tactical/spy games from example).

grizzled bolt
#

Other post processing effects can change the brightness before bloom is applied, so you can't rely on material color alone anyhow
If the post processing changes per area you might never get a value that works absolutely

glossy loom
#

And how would the post processing be applied? What classes/calls should I look for in the original source code to try and deduce what's happening?

grizzled bolt
#

I have no idea how Valheim does this stuff but you could look into SRP Core or URP documentation

solid basin
#

could someone explain to me

#

why inverting that node twice

#

ends up with a different output than the first one?

karmic hatch
#
void Unity_InvertColors_float4(float4 In, float4 InvertColors, out float4 Out)
{
    Out = abs(InvertColors - In);
}
#

it does the abs() which is what makes it asymmetric

regal stag
# solid basin could someone explain to me

The code that Invert Colors uses here is basically abs(1 - x). While your subtract node looks black/white it contains negative values.
e.g. -1 → abs(1 - (-1))=2 → abs(1-2)=1
To prevent the negative input you'd use a Saturate node to clamp between 0 and 1.

solid basin
#

oh okay thanks much

glossy loom
low lichen
#

If the game is drawing the player and then the grass, there's no correct place to draw the lines. If you draw the lines first, then both the player and grass occlude it. If you draw it last, then the lines are drawn on top of everything. If you draw it in between the player and the grass, then it will be on top of the player, but occluded by the grass.

glossy loom
#

So basically in engineering terms you propose I set the "ZTest" to "Always" and than try to fiddle with the "redner queue".

#

?

low lichen
#

Yes

#

But not just the render queue of the lines. If the grass is drawn after the player, there's no way to render the lines correctly.

#

The dependency on the order can be somewhat avoided by using the stencil buffer, but that would require modifying the grass shader to have it write a particular stencil value.

glossy loom
#

So hypothetically if I already did this exercise before asking this question (😉) and even setting the "render queue" of my shader to one billion - doesn't result in it overlapping anything... Is it possible that the postprocessing is again somehow screwing me over, or am I doing something terribly wrong after all?

#

In other words - is it possible for post-processing/"render pipeline" (dunno, just throwing random gibberish around) to completely disregard my render queue value?

low lichen
glossy loom
# low lichen Do you mean you set ZTest to Always and the render queue to one billion, and tha...

I would like to think so. However since I have no experience doing what I'm doing - there is the likely probability that I'm doing something slightly off that destroys the whole approach (dunno, wrong caps on "_ZTest", it should be an int, not a float, I should be modifying the shader directly, not the material, the ZTest parameter should be somehow "nested", blah, blah, blah):

var material = new Material(Shader.Find("Sprites/Default"));
material.SetFloat("_ZTest", (int)CompareFunction.Always);
material.renderQueue = int.MaxValue;
material.mainTexture = texture;

return material;

And yes - this does literally nothing. The screenshot would remain virtually unchanged.

low lichen
glossy loom
#

I guess it's not like my whole approach is completely doomed. Since this similar approach for example achieves the purpose of forcing the shader to become transparent:

            material.SetColor("_Color", new Color(1, 1, 1, 0.1f));
            material.SetInt("_SrcBlend", (int)BlendMode.SrcAlpha);
            material.SetInt("_DstBlend", (int)BlendMode.OneMinusSrcAlpha);
            material.DisableKeyword("_ALPHATEST_ON");
            material.EnableKeyword("_ALPHABLEND_ON");
            material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
            material.renderQueue = (int)RenderQueue.Transparent;
glossy loom
low lichen
#

The sprite shader is always transparent. It doesn't use any of those properties or keywords.

glossy loom
#

Although I didn't check the code of these either to be honest.

low lichen
#

The only thing that matters is the render queue

glossy loom
#

Are you by chance aware from the top of your head of any built in shader that DOES take in the ZTest parameter?

glossy loom
#

Great idea.

#

You're much more helpful than I dared to hope I have to say Man.

#

So the standard shader should work if I understand correctly?

#

(this is the first time I'm seeing the domain language that Unity uses for shaders)

low lichen
#

No sorry, that's the display name

#

It's the same property names

#

And set the _EmissionMap instead of the main texture to make it look unlit.

#

And _EmissionColor to white

#

It will still calculate lighting, so it's more expensive than an actual unlit shader

glossy loom
#

Will do. But first let's sort out the occlusion, cause that's the thing that's bugging me the most and I would like to avoid releasing at this state at all cost.

#

To double check, this is the minimalistic code that for now should result in my gird occluding EVERYTHING regardless of depth:

            var material = new Material(Shader.Find("Standard"));
            material.SetFloat("_ZTest", (int)CompareFunction.Always);
            material.renderQueue = int.MaxValue;

correct?

low lichen
#

I think so. If that doesn't work, I would try using a more reasonable renderQueue value, like 3500.

glossy loom
#

I'll try 3,5k ;]

#

Same result unfortunately.

low lichen
#

How are you using this material?

glossy loom
#

uno secundo

#
        {
**            var shader = InitializeShader(texture);**
            for (var i = 0; i < GridLinesPerAxis * 2; i++)
            {
                var gridLineGO = new GameObject();
                gridLineGO.transform.parent = transform.parent;

                var gridLine = gridLineGO.AddComponent<LineRenderer>();
                gridLine.textureMode = LineTextureMode.RepeatPerSegment;
**                gridLine.material = shader;**

                gridLines.Add(gridLine);
            }
        }

Where initialize shader is our old buddy:

        private Material InitializeShader(Texture2D texture)
        {
            var material = new Material(Shader.Find("Standard"));
            material.SetFloat("_ZTest", (int)CompareFunction.Always);
            material.renderQueue = 3500;

            return material;
        }
#

Again - I would be very suspecting of this initialization (probably would be the main suspect) if not for the fact that it seems to correctly pass on the "transparency parameters".

#

So I understand that it's impossible for something outside of this shader to "override" the ZTest behaviour, and the problem MUST be somewhere between my ears?

low lichen
#

I always find it helpful to test my modding code inside Unity so I can more easily debug issues.

#

Oh, actually, the Standard shader doesn't have a _ZTest property.

#

I was wondering why I wasn't finding it in my search

copper falcon
#

@regal stag Hey. I know you made a great toon shader, so i assume you know quite a bit about custom lighting. Do you know how to get/iterate additional lights in forward+ mode?

low lichen
#

There's a possibility this shader isn't included in builds though, but worth a shot.

glossy loom
#

So "ZTest" needs to be in the "Properties" section of a shader for it to be "parametarizable"?

low lichen
#

Most importantly it needs ZTest [SomeProperty] in the SubShader or Pass

#

I don't think it has to be defined in the Properties section to work.

#

The only other built-in shaders that have a property assigned to ZTest are the UI shaders, which have it assigned to unity_GUIZTestMode, which is a global property assigned by the UI masking system.

#

I think technically you should be able to set that property from code and that should take priority over the global one.

#

But if the Hidden/Internal-Colored shader is available and you don't need texture support, that's a much simpler, cleaner shader.

glossy loom
#

I'll try that. Ignoring the built in shaders for a moment though.

low lichen
#

What do you mean? Are you including your own shaders?

glossy loom
#

Is there a way to broswse custom made shaders (I'm willing to pay for the sake of my mod) for those that support the ZTest parameter?

glossy loom
low lichen
#

I assumed you wanted to avoid custom shaders, because that will require building an asset bundle in Unity and loading it in your mod

glossy loom
#

I would rather not do that exactly for the reasons you mentioned.

#

But I'm starting to run out of rope 😉

low lichen
#

So you have tried the Hidden/Internal-Colored shader? Or is it not an option because you need texture support?

glossy loom
#

(I was for example hoping to use a "dashed" texture on additional grid lines of increased precision)

kind arch
#

How could I go about creating a shader that give a pixel art sprite soft edges? Like a falling off of alpha. Would that be too difficult?

glossy loom
#

I'm trying it out now regardeless.

#

First victory of the day.

#

It overrides EVERYTHING (as it should).

#

I'll try experimenting with the render queue value to try to force it in between the player and the terrain.

#

The texture issue remains though...

low lichen
#

Great. However, I loaded up Valheim in RenderDoc and the render order of the player, grass and terrain will not play nice

#

It's pretty random. The grass is in sections and some of them render before the player, some after.

glossy loom
#

❤️

low lichen
#

So you will need to override those render queues somehow

glossy loom
#

I don't mind the grass TBH as much as I mind the dirt patches on the ground itself.

low lichen
#

Ok I'll ignore the grass, but the terrain is drawn after the player, which is still problematic.

glossy loom
#

xD

#

xD

low lichen
#

Do I understand correctly that you only need it to be drawn on top of the terrain, but everything else in front of it can occlude it?

glossy loom
#

Yes. The reason for that is my mod adds arbitrary precision terraforming tools. While Valheim sprinkles the ground with random "dirt patches" to visually break the monotony even of perfectly "flat" ground (I think this is done via a shader, as they DON'T appear in the heightmap and they DON'T get hit by raycasting - as if they didnt' exist).

I want to "cut through" them with my lines as not to actively mislead the player that the ground could be leveled still. I literally don't care about covering up anything else with the lines.

#

Hope that makes sense.

low lichen
#

Sort of, but if the lines are always drawn on top of the terrain, won't it always look like there's nothing to level?

#

Or at least harder to tell than if the terrain occluded over the lines

#

Also, you don't have to use a shader with changeable ZTest value. There are also built-in shaders that are hardcoded to ZTest Always which you might be able to use.

glossy loom
#

That is correct.

#

Still I need to analyze if I'm able to somehow hack the render queue of the player to land above the render queue of the terrain and hope that doesn't break anything 😉

low lichen
#

There are other things that are also drawn before the terrain which will have the same problem

#

So what you need to do is change the render queue of the terrain to be super low (negative even), then your line material should be a bit above that, so it's drawn second, then everything else can be drawn.

glossy loom
#

Sounds extremely invasive. Isn't there any chance of that severly screwing up the visuals? Say improper shadows on the ground or something 😉

low lichen
#

The order of opaque objects will not affect visuals. Maybe performance a bit, it's generally better to draw things front-to-back

#

But Valheim uses deferred rendering, which doesn't suffer as much from opaque overdraw.

#

And it's already badly optimized anyway, so no one will notice 🤫

glossy loom
#

^^

#

While using "RenderDoc" were you perhaps able to establish the precise render queue values of the specific layers?

low lichen
#

Render Queue is a Unity concept which does not transfer to RenderDoc, which deals with DX11/Vulkan commands.

#

I only see the order that it ultimately resolves to

glossy loom
#

Makes sense.

#

Another surprising development that doesn't make sense though! 😛

This combination:

            var material = new Material(Shader.Find("Hidden/Internal-Colored"));
            material.SetFloat("_ZTest", (int)CompareFunction.Always);
            material.renderQueue = 1;

...results in my grid line being overdrawn on top of all other objects anyway.

#

It literally seems the "render queue" parameter doesn't matter.

low lichen
glossy loom
#

Current compiled state:

#
        private Material InitializeTransparentShader(Texture2D texture)
        {
            var material = new Material(Shader.Find("Hidden/Internal-Colored"));
            material.SetFloat("_ZTest", (int)CompareFunction.Always);
            material.renderQueue = 1;
            //material.color = new Color(0.6f, 0.6f, 0.6f, 0.6f);

            //material.SetColor("_Color", new Color(1, 1, 1, 0.1f));
            //material.SetInt("_SrcBlend", (int)BlendMode.SrcAlpha);
            //material.SetInt("_DstBlend", (int)BlendMode.OneMinusSrcAlpha);
            //material.DisableKeyword("_ALPHATEST_ON");
            //material.EnableKeyword("_ALPHABLEND_ON");
            //material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
            //material.renderQueue = (int)RenderQueue.Transparent;
            material.mainTexture = texture;

            return material;
        }
low lichen
#

That is unexpected. Just as a sanity check, try setting _ZWrite to 0, because it's defaulting to on, which isn't needed.

glossy loom
#

Will do, although I understand it shouldn't really matter for the purpose of our little experiment?

low lichen
#

It shouldn't, but this will eliminate one possibility, which is that render queue is working, but for some reason the shader is writing a depth value that is closer to the camera than all subsequent draws, so nothing is able to draw on top of it.

#

The other explanation is that it's always being drawn after everything else, regardless of the render queue, which I can't really explain.

glossy loom
#

If this line should add sanity: material.SetInt("_ZWrite", 0); then it didn't 😉

#

I'll try with one of the UI shaders that have hardcoded ZTest = Always. But that's not even grasping at straws anymore I'm afraid.

low lichen
#

Whenever I'm in a scenario like this when modding a game, that's when I open up Unity and test my code there.

glossy loom
#

Sounds reasonable. I however managed to somehow write ~5k of C# code for this mod without knowing the basics of the Unity Editor. If I were now to go there to investigate I would need to start from "what's the left mouse button" 😉

buoyant lily
#

I keep getting black parts of the material whenever I set the object as static

#

Anyone knows why?

#

Using URP and unity's toon shader

low lichen
buoyant lily
#

only when I go into play mode

low lichen
buoyant lily
#

I read I should set every object to static so it batches. Also I'm using navmesh agents so I need meshes to be static for baking the navmesh

low lichen
#

Well, your options are:

  • fix the shader so it supports batching, which requires some shader knowledge
  • find another toon shader that doesn't have this problem
  • don't use static batching for the objects using this shader. You can still keep navigation static on, if you press the arrow instead of the checkbox:
#

"Batching Static" is the only one you should have to keep disabled to avoid this issue

buoyant lily
#

Thank you very much! wouldn't it impact performance too much if I disable the "Batching Static" option? considering I have many objects in the map

low lichen
#

If all those objects are using the same material, then static batching can help reduce draw calls

buoyant lily
#

yes they are

#

is static batching the same as the gpu instancing option?

low lichen
#

Maybe before you go any further, could you just quickly check if disabling "Batching Static" actually fixes the problem?

buoyant lily
#

Yes it does fix it I already checked 😄

low lichen
#

GPU instancing is a different type of batching, which only works when you have multiple instances of the same mesh and material.

#

Static batching works with different meshes by combining them into one.

#

Could you link which shader you're using? Is it a free one?

buoyant lily
#

yes it's unity's toon shader

#

one sec

buoyant lily
low lichen
#

Yeah, it combines all of them into one mesh when you go into playmode, which is why you only see it happen in playmode

buoyant lily
#

hmm I thought about buying a shader from the asset store but how can I be sure that it won't be an issue there

low lichen
#

Which specific shader in the package are you using?

buoyant lily
#

0.8.2 preview

#

actually I was using 0.8.1

#

I'll update it now

#

Okay so the issue still occurs on 0.8.2

low lichen
#

Is there only one shader that you get with this package? I'm seeing some files like "Body" and "Head"

buoyant lily
#

I actually don't know I just imported it and change the materials to use the toon shader

low lichen
#

Are you using Universal Render Pipeline?

buoyant lily
#

yes

low lichen
#

So is this the shader you're using?

buoyant lily
#

even though according to the documentation I'm supposed to see the toon shader under urp

#

wth why don't I have that

low lichen
#

That's just a screenshot from the documentation, probably old

#

What's the name you see?

buoyant lily
#

oh okay

#

I just see toon but not inside urp

#

I don't have a toon inside the urp shaders

low lichen
#

So many properties in this shader 😵

buoyant lily
#

Haha I tried many shaders before finally landing on one that sort of works

glossy loom
#

@low lichen for whatever it's worth (perhaps unsuprisingly) the UI shaders also seem to ignore render queue.

I found this bit in the Unity documentation however:
Note: When Unity runs in batch mode, it does not load Scriptable Render Pipelines (SRPs) until the first time something renders. Loading an SRP modifies the sub-shader selected for a given material which can lead to the value this function returns being different than expected.

#

Since Valheim uses SRPs - wouldn't this mean that from my perspective whatever I put into the render queue property might be disregarded?

low lichen
#

Are you sure it uses an SRP? The Standard shader only works in the built-in render pipeline

low lichen
# buoyant lily

Can you share some more screenshots of the glitched parts? I'm trying to find some pattern to understand what it is in the shader that might be breaking.

#

It looks like everything is untextured. Are these meshes UV mapped at all?

buoyant lily
#

yea one sec, I actually don't know what uv mapped means but I downloaded these from the asset store

#

I can tell most of the black spots are in the darker part of the objects

low lichen
#

And can you post a screenshot of what it looks like without batching, so I know what it should look like?

buoyant lily
low lichen
#

Interesting, so that's actually the highlighted spot, that's facing the light

buoyant lily
#

I'm not sure because look at this

#

you can see the buildings I snipped are in the back to the left

#

but the shadow appears downwards to the right

low lichen
#

Hmm, could you try seeing what it looks like if you swap out the Toon shader with the default Lit shader? Just to confirm this is an issue only with the Toon shader.

buoyant lily
#

sure one sec

#

oh one sec

#

forgot to turn on batching

low lichen
#

The plot thickens

buoyant lily
#

the blacks you see on the top of the towers are still the same toon material

low lichen
#

Oh, okay

buoyant lily
#

but the walls are regular urp lit shaders

#

here it is with both ofem being urp lit

low lichen
#

Then this is an issue in the toon shader. It's not listed in their "Known Issues" page, but it's possible they don't intend static batching to work.

#

There might be some import setting on the model that will affect this somehow, but it's just a shot in the dark

buoyant lily
#

should I first try to import some other meshes and see if the issue continues before I buy a toon shader off the unity store?

low lichen
#

Yeah, that's a good idea.

#

You could also try changing some of these settings.

#

The settings that stick out to me as potentially having an effect on this are "Optimize Mesh", "Weld Vertices" and "Normals" (try Generate instead of Import)

buoyant lily
#

Do i copy what you checked or do I just play around with the settings?

low lichen
#

I just took the screenshot from the documentation

#

And "Index Format", maybe change that to 32 bits

buoyant lily
#

Nope doesn't seem to do anything

#

I'll try applying the shader to other meshes

low lichen
#

Also remember to have other meshes with the same material it can batch with, otherwise static batching won't do anything to it.

buoyant lily
#

this is what I see when looking at the meshes folder

glossy loom
#

On the same topic a Random Guy on the Internet says here: https://forum.unity.com/threads/material-renderqueue-or-tag-doesnt-seem-to-be-working.406870/

That:

Are you using the deferred rendering path? Anything deferred gets rendered first regardless of the queue, then forward rendered objects (anything using a transparent shader or something other than the standard lighting model) get rendered afterward with respect for the queue order.

You mentioned previously that Valheim uses deferred rendering? If the above statement is true, then to explain the behavior I'm experiencing -> it would need to defer basically everything.

low lichen
#

Oh, yeah good find. I have basically no experience with deferred rendering.

buoyant lily
#

so the mesh was the problem? god damnit

low lichen
low lichen
buoyant lily
glossy loom
#

And it still might probably not work 😉

low lichen
#

There's definitely no built-in shader like that.

#

There is one alternative, but complicates things a bit

glossy loom
#

Good. It was way to easy up until now 😉

low lichen
#

You can add a CommandBuffer to the main camera to draw the line renderers at a specific "camera event", in this case "CameraEvent.BeforeGBuffer".

#

But no, that would draw it before the terrain, which is no good

glossy loom
#

And a Stencil wouldn't work because I don't have access to the code of Valheim's own shaders which would then need to be modified as well r?

low lichen
#

So yeah it would have to either be exposed to properties or hardcoded, which it seems to be neither.

#

Also deferred uses stencils for other things, so that complicates it further

#

I don't like deferred

#

So I think the only option is a custom deferred shader. But I'm pretty confident that would work, assuming you're able to change the render queue of the terrain.

glossy loom
#

So getting back to my previous question from my never ending irritating litany of questions - is there some sort of central catalogue of shaders where I can easily filter what parameters they accept and quickly visualize how they would look?

#

Or do I Google and hope for the best?

low lichen
glossy loom
#

Welp. This was a traumatizing programming experience if I ever had one 😉 I'll probably end up giving up altogether and my mod isn't going to see another release in the end.

But that's none of your fault. You've been of tremendous help for no reason whatsoever. Thank you for all your time and patience with my ignorance.

#

So it seems the deferred shader wouldn't work either, and that's because:

Limitation 3: Okay, so you can't have multiple queues, or multiple deferred passes in a single shader. So the solution might seem like it would be to setup two separate materials. But that's where the third limitation comes in to bite you. The deferred rendering path ignores the material queue for sorting! Unity just checks to see if the queue is less than 3000, and if the material's shader has a deferred pass. Then it sorts everything front to back and ignores the queue! This means you can't force this material to render after everything else. You can't even guarantee the two separate materials will render in the correct order!

#

But wait for the punchline!

So what's the solution? The easiest "solution" is don't use the deferred rendering path.

#

I know next to nothing about rendering pipelines and yet I already hate the defered one 😛

low lichen
#

Then you'll be happy to know that basically all AAA games use it

#

Is this from a thread?

glossy loom
#

Knock yourself out:

low lichen
#

Gotta love undocumented behavior

#

Like a little easter egg waiting to be found to ruin someone's day

glossy loom
#

I have to say. Coming from the corporate server side programming world - the quantity and quality of materials regarding Unity is appalling.

#

For something that's supposingly so ubiquitously used I often times find myself baffled by having to Google like this for hours to find undocumented behaviour of core components.

low lichen
#

I'm testing in a new Unity project and I'm not able to recreate what bgolus says in that thread

#

Render queue is affecting the order

glossy loom
#

Could they... Have changed the behaviour between unity versions?

#

(for the matter I found several threads claiming that render queue doesn't affect deffered rendering)

low lichen
#

Maybe, but it's a recent thread and the built-in render pipeline is practically abandoned at this point so I wouldn't expect any recent changes of this magnitude.

glossy loom
#

If only one of Valheim's native shaders accepted ZTest - we would be home free to test out that hypothesis.

#

Just apply that to my material and change the queue order.

smoky vale
#

so quick question, im new to making shaders and i want to know if i can program in C# within the hlsl code or if i have to do everything in that language, or whatever language it uses

#

cuz i wanna do stuff with raycasts and the like but am finding it difficult to find doccumentation

low lichen
smoky vale
#

alright

smoky vale
low lichen
smoky vale
#

alright

low lichen
#

This isn't a standard thing that people do with shaders. It's technically possible, but usually completely unnecessary.

#

And difficult to optimize. You also have to remember that shaders run for each vertex and each pixel. Do you want to perform a raycast for each vertex or each pixel? If not, then you can't do this in a shader.

smoky vale
#

alright

#

ok wait so

#

im not really wrapping my head around how this all works

#

so is this like just general code that runs for each pixel?

#

like if i return the pixel color as a base color multiplied by something like blue, it will run the same way for every pixel?

low lichen
#

Yes

smoky vale
#

so then what is the whole vertex part for?

#

i mean i know its pretty much for mapping right

#

but how do you use it?

#

does it run the same way for each vertex or is it different in some way?

#

also whats a clip position?

low lichen
#

The purpose of the vertex shader is to calculate where each vertex of the mesh should appear on screen. To do this, Unity gives the shader information about where the transform is relative to the camera in the form of a matrix (UNITY_MATRIX_MVP).

#

Clip position can be considered as a sort of screen position

smoky vale
#

alright

smoky vale
low lichen
#

After the vertices have all been calculated, the GPU will then figure out which pixels on the screen those vertices and the triangles connected to them occupy. Then it will run the fragment/pixel shader for each of those pixels to calculate what color they should be.

low lichen
smoky vale
#

so it runs the vertex shader first, gets the general area onscreen, then colors that area with the fragment shader, correct?

low lichen
#

Yep

smoky vale
#

alright i get it now, thanks!

low lichen
#

That's the rasterization step, but that's something the GPU handles and can't be modified by developers.

smoky vale
#

yeah

#

oh and

#

one more question

#

wait nvm that was a dumb question

gusty horizon
#

hey guys, I might be being really daft but - is there an hlsl equivalent to UnityCG.cginc for use in URP? In the docs under "HLSL in Unity", they still point to using UnityCG. Is this still used in URP?

quaint coyote
#

hello everyone, just wondering if anyone could shed some light on making text glow, is it better done in shaders or as images?

simple violet
#

tmpro has lighting text

quaint coyote
#

so one way is to render it in a separate target and add a blur

simple violet
#

yeah

#

could also add it to the shader

#

I was able to add pixelation by editing the frag func

quaint coyote
simple violet
#

just have to go to assets > textmeshpro > shaders and copy and edit a shader add properties and edit the pixl shader then u can make a material from it and use it

#

bluring is simply moving pixels in outwards directions

#

so you can simply edit the output of the frag function with a blur algorith

quaint coyote
simple violet
#

It was urp

quaint coyote
sleek kite
#

@low lichen by the way something I found odd is that I didn't need to correct for gamma when writing the bit shifted index to the vertex color, I'm not sure why you had to do it

low lichen
#

Or vice versa, but pretty sure mine was in Linear

sleek kite
#

Ah, I thought I had to do it if it was in gamma space, then I just misunderstood

vital barn
#

Hi there, I have to use a double sided shader for a model I want to use. (Buildin renderpipeline). But light illuminates on the opposite side. Any idea how I can fix this. I have no experience in shaders. I used the provided one by unity. Any help is highly appreciated. thanks

low lichen
smoky vale
#

ok another stupid question about writng shaders, but does the shader language use half HLSL and half c#?

#

im noticing half the syntax is HLSL and half the syntax is C#

shadow locust
regal stag
smoky vale
#

alright

smoky vale
regal stag
#

If it's a vert/frag shader you'd use the NORMAL semantic in the vertex input struct

smoky vale
#

alright

#

so wait

#

actually nvm i can search that

#

oh also

#

nvm, i could probably search that too

#

so whats "o"

#

skimming over the input structure section i saw this note and figured i might be taking the wrong route

#

because apparently you cant use the normal semantic in surface shaders, and i believe im using a surface shader, although its unclear

#

because it does have a vertex and fragment function, so it might not be a surface shader, but when making the script i clicked standard surface shader

smoky vale
#

brb

regal stag
#

It's a vert/frag shader if you have #pragma vertex .. and #pragma fragment ..
It's a surface shader if you have a #pragma surface .. line. Surface shaders handle shading/lighting for you (assuming Built-in RP). o would be the surface shader output struct. You'd set o.Normal when sampling a normal map.

#

Further down that docs page it does also mention if you do write to o.Normal you can use float3 worldNormal; INTERNAL_DATA and WorldNormalVector (IN, o.Normal) to get the new worldNormal.

smoky vale
smoky vale
#

so i just write o.Normal to acess the normal then?

grizzled bolt
vital barn
regal stag
smoky vale
#

like if i have (1,3,2) and i want to get the second value (3) how do i go about doing that?

lean lotus
#

Is there any way to speed up the compilation of compute shaders or something I can do or arrange it to make it shorter? currently my compute shader takes about 2-4 minutes to compile every time I make a small change, and I cant deal with that anymore(its up to 6.1k lines now with 12 kernels)

smoky vale
#

alright

#

thanks

smoky vale
#
Shader "Lighting/Dither"
{
    Properties
    {
        _Albedo("Albedo", 2D) = "white" {}
        _Color("Color",Color) = (1,1,1,1)
    }
    SubShader
    {
        Pass
        {
            CGPROGRAM
            #pragma vertex Func1
            #pragma fragment Func2
            #include "UnityCG.cginc"
            struct appdata {
                float4 vert : POSITION;
                float2 uv : TEXCOORD0;
                float3 norm : NORMAL;
            }; 
            struct v2f {
                float4 vert : SV_POSITION;
                float2 uv : TEXCOORD0;
            };
            fixed4 _Color;
            sampler2D _Albedo;
            v2f Func1(appdata IN)
            {
                v2f OUT;
                OUT.vert = UnityObjectToClipPos(IN.vert);
                OUT.uv = IN.uv;
                return OUT;
            }
            fixed4 Func2(v2f IN, appdata IN2) : SV_Target
            {
                fixed4 pixColor = tex2D(_Albedo, IN.uv);
                
                return (pixColor*_Color)*IN2.norm.y;
            }
            ENDCG
        }
    }
}

So what do you think i did wrong? im not even sure how i can begin to debug this, as stated before, im fairly new to hlsl

#

from what i can guess based off "duplicate" "value" "semantic" and the two variables listed, i can assume that the two have either the same value or something and that somehow fails to compile

#

im not really sure

low lichen
smoky vale
#

alright

smoky vale
low lichen
#

Yeah, just remove the IN2 parameter in Func2

#

Also, I would recommend just calling them vert and frag

smoky vale
#

alright, thanks

smoky vale
#

ok i managed to get very basic and rigid lighting, id say its an alright beginning step

#

next step is making actual lighting..

low lichen
smoky vale
#

yeah thatd probably work better for organizing, thanks for the tip

#

uh ok so

#

how can i use common math functions when writing a shader?

low lichen
# smoky vale how can i use common math functions when writing a shader?

The common ones are global, so you can call those functions directly, like min, max, sin, cos. They are documented here:
https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-intrinsic-functions

smoky vale
#

alright, thanks

#

so what do you bet im doing wrong here?

#

i looked at the syntax on the link you provided and the "in"s fail to compile, same with the fvector before calling the method

low lichen
#

@smoky vale I've never seen or used the dst function. If you're looking for something like Vector3.Distance, you should use distance

#

The page I gave you is a comprehensive list, but I wouldn't be surprised if it also contained some old, obsolete functions.

#

Though to me it looks like you want dot, as that's usually how you calculate the light factor. "N dot L", or "dot(Normal, LightVector)"

smoky vale
smoky vale
#

ill look it up

low lichen
#

It's dot product. It can be used for various things, so the mathematical definition won't be super useful. In gamedev, it's most often used to compare how similar two directions are. If you pass in two normalized directions, you will get 1 if they are identical, -1 if they are opposite, 0 if they are parallel, and any number in between.

smoky vale
#

holy shit thats perfect

#

ok thanks

gusty horizon
smoky vale
#

if we are talking in just directions, shouldnt parallel be impossible? or am i missing something

#

cuz they all start at the origin unless specified otherwise

#

i think

low lichen
smoky vale
#

oh kk

low lichen
#

Both start with P 😓

smoky vale
#

yeah i mess that up too sometimes

#

also

#

is there a way i can print something into the output? i hate asking so many simple questions cuz i dont know how to debug in hlsl

low lichen
#

It's a fair question. The simplest way to debug something is to just return it in the fragment shader.

smoky vale
#

hm, alright, so just trial and error then or am i misinterpreting

gusty horizon
smoky vale
#

oh also, do shaders update in the viewport in realtime or what might i have to do to make them run in real time?

gusty horizon
low lichen
smoky vale
#

alright

#

oh yeah right right cuz without the albedo or color modifier itd just be a shade of grey

low lichen
#

URP might have some common files specific to URP, but those will probably be related to things like lighting.

smoky vale
#

well i know im doing something wrong, and its probably something really simple and stupid, but it appears that it isnt taking into account object rotation, and it shouldnt i dont believe, because object rotation isnt mesh rotation and it doesnt have much to do in relation to the workings of unitys gameobjects right?

low lichen
gusty horizon
smoky vale
#

i think i might be doing this part wrong

#

i mean it doesnt error

#

but its all black and it feels like im doing it wrong

low lichen
#

You might be confusing this with a surface shader. In a regular vert/frag shader, you have to calculate the world normal manually. Unity gives all shaders the localToWorld matrix which can be used to transform local positions and directions into world positions and directions.

smoky vale
#

oh, alright

low lichen
# smoky vale oh, alright

But there are also helper functions defined in UnityCG.cginc to make things easier. In this case, UnityObjectToWorldNormal

smoky vale
#

oh

low lichen
#

You just need to pass in the normal from appdata. The function is defined as:

// Transforms normal from object to world space
inline float3 UnityObjectToWorldNormal( in float3 norm )
{
#ifdef UNITY_ASSUME_UNIFORM_SCALING
    return UnityObjectToWorldDir(norm);
#else
    return normalize(mul(norm, (float3x3)unity_WorldToObject));
#endif
}
smoky vale
#

alright

#

ayy, thanks

#

really appreciate the help btw

low lichen
#

No problem, you're doing very well, considering you're not following a tutorial and just figuring things out on your own.

gusty horizon
#

what's an acceptable way to handle switching out specific-colors in a sprite, specifically for 2D? I've heard of lookup textures, but honestly, barely have a grasp on what TEXCOORD really even is, let alone how to use more than one texture in a shader. I'm effectively trying to exclude specific colors on a texture (in this case, black and white) from changing when the SpriteRenderer's color is changed. At the moment, my fragment function looks like this:

float4 frag(const v2f i) : SV_TARGET
{
    const half4 sample = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, i.uv);
    if (all(sample >= float4(0.99f, 0.99f, 0.99f, 0.99f)) || all(sample <= float4(0.01f, 0.01f, 0.01f, 0.99f)))
    {
        return sample;
    }

    return sample * i.color;
}

I'm sure I'm approaching this wrong!

#

for reference, the vert function:

v2f vert(appdata v)
{
    v2f output;

    output.position_cs = TransformObjectToHClip(v.positionOS);
    output.uv = v.uv;
    output.color = v.color;

    return output;
}
gusty horizon
# low lichen Does this code work?

no - can only assume the if statement never evaluates to true, since each pixel returns it's tinted color. sorry, should have said that from the get go

#

my teeny tiny C# brain cannot deal without breakpoints 🤒

#

Am I maybe handling colors wrong for how they are inputted to the pipeline? This is my struct:

struct appdata
{
    float3 positionOS : POSITION;
    float4 color : COLOR;
    half2 uv : TEXCOORD0;
};
low lichen
#

I personally haven't used all or any, so I don't know if you're using it correctly. In general, branches are discouraged in shaders, and there are often ways around it. Lookup textures is one such example. That's not to say you should never use branching; sometimes you have to.

#

One potential workaround is to use dot to compare sample with float4(1, 1, 1, 1). If the pixel is white, it will return 1. If the pixel is black, it will return 0. For any other color, it should be somewhere in between. Now at least the condition can be simplified to only compare one float, albeit still twice.

gusty horizon
#

Yeah, I'm sure it shouldn't be necessary here. I'm just a lot more comfortable with programming & I kind of wanted to just get something working before jumping deeper into anything I don't really understand 😮‍💨

low lichen
#

Well, the alpha channel might still mess things up. It's perhaps better to ignore it and just compare the first three channels. It doesn't make sense to me to allow half-transparent white and black pixels to be tinted.

gusty horizon
#

yeah, makes sense

#

this is a test sprite I threw together to work with:

#

dot(half3(1, 1, 1), sample) didn't change anything, so I just returned dot(half3(1, 1, 1), sample) and now I am baffled haha

low lichen
#

Ah, since the colors are normalized, the dot range is probably between -3 and 3.

#

So try dividing by 3 and things should look a bit better

#

The black pixels should be black, the white should be white and everything else should be some shade of gray.

gusty horizon
#

Pretty cool! I mean, the black pixels have still turned to grey, but nice to see something coming out a little more normal.

#

how did you get to the conclusion that the dot range is between -3 and 3? could you walk me through that a bit?

low lichen
#

Because a dot product is defined as:

float dot(float3 a, float3 b)
{
    return a.x * b.x + a.y * a.y + a.z * b.z;
}
#

Since it's a sum of each component multiplied, the highest number is 3

gusty horizon
#

Ah, I see

#

yeah that's clear

low lichen
gusty horizon
#

the world of shaders is dangerously low level for me. I work with C# all day and even the thought of having to deeply understand what I'm actually doing is terrifying, lol

low lichen
#

They are very low level, but at the same time they are so sandboxed and isolated from everything that it makes things a bit simpler.

gusty horizon
#

Thanks for all your help today! logging off for now but hope you have a fab day/evening/whatever timezone you're in 🙂

low lichen
#

Thanks, good night

smoky vale
#

sorry if im interrupting, but how can i get data from other objects in the shader automatically?

to clarify, i want to get data from a list of gameobjects, or more specifically their positions, to use as extra light sources

#

i can use practically the same math i did for the main sunlight, but im stumped on the part about getting data from anything that isnt automatically passed by unity

low lichen
smoky vale
#

i guess ill have to figure out a dif solution

low lichen
#

Unity gives you some information automatically, like the direction of the main light, the position of the camera and such, but to get information about the positions of objects, you will have to do that through C#.

smoky vale
#

my best guess is using a property to control lights, like a list of some sort, ill have to look into it

smoky vale
low lichen
#

Well if you're thinking about lights specifically, that is of course something that Unity does consider and in some cases passes information about automatically.

low lichen
smoky vale
#

im looking mainly to make my own

smoky vale
#

how can i pass info from a script to a shader?

low lichen
#

If you've ever worked with materials through script, then you've probably done it before. You use the material.SetX, where X is Float, Vector, etc...

#

You can also set global properties through Shader.SetX

smoky vale
#

ive never worked with materials before, but with that info i can research those things, thanks

low lichen
#

To access those properties in a shader, you just need to define a variable of that type and with the same name in the shader. The variable needs to be defined outside of a function, like a field:

float3 _SomePosition;
smoky vale
low lichen
#

Yep, if you want to pass a Vector3

smoky vale
low lichen
#

There isn't a specific SetVector3 method, just SetVector which accepts Vector4, but you can still use that and let it automatically convert the Vector3 to Vector4.

smoky vale
low lichen
smoky vale
#

so i just use SetFloat

smoky vale
#

thanks for the help!

#

and uh

#

one more thing

#

since i never worked with materials, or much at all with shaders, how do i acess them from the assets folder?

#

i ofc have them in a folder under the assets folder, but im not sure how i even acess those assets in the first plac

#

i know i can acess materials in the renderer components of the gameobjects but i believe those are seperately instanced

low lichen
#

I assume you mean accessing them from a C# script. You could access it through the Renderer component, and I would recommend that if you expect you'll need separate values for each game object.

#

But if you want each game object to share the same property values, then you can reference the material directly with a serialized field:

[SerializeField]
private Material material;
smoky vale
#

alright

low lichen
#

And then you can pick the material in the editor inspector

smoky vale
#

k

halcyon wedge
#

Anyone understand why this happens? I was using EmissionColor to tint enemies for when they're invincible/damaged, but only one part got tinted, all the rest looks like this below, somehow appearing normal ingame, am quite confused pls

#

Also another question is like, what is the most efficient way to tint every part of a model? I made mine mainly out of cubes, and there's quite a few cubes/creature, invincibility is supposed to flicker etc...

meager pelican
# halcyon wedge Anyone understand why this happens? I was using EmissionColor to tint enemies fo...

Emission color is additive. Normally to tint with a color you multiply the tint color and the pixel's color. So for the standard shader (which you show being used) you'd change that green color for "Albedo".

As to only parts having emission....I can't tell from what you've given us. Make sure you've not got multiple materials and/or multiple meshes. What you posted shows black emission (none).

"Tint every part"? It depends on the number of materials you have on the object, and whether or not the object is really composed of multiple meshes or not, and if so, what materials are assigned to what meshes. Shaders run per-mesh.

halcyon wedge
#

Apparently there is one difference

#

Didn't notice before

#

Model's literally made of a bunch of cubes, that's why I've got a issue for efficiency of tinting every piece

tacit parcel
#

combine those cubes into one material?

halcyon wedge
#

Ummm would be possible if I 3d modelled it, but no it's purely made of cubes

halcyon wedge
#

Ohhh nvm issue found

#

Extremely stupid, originally takehit anim tinted it, but it caused that issue xD

#

Ty, my bad

tiny quarry
#

is it possible to get tessellation in URP shader graph?

amber saffron
#

Maybe in latest versions ? I'm not sure

sullen delta
#

Hi everyone! Can someone tell me if it's possible to access unity's terrain alphamaps or colors within a surface shader?
And if not, would it be way too hacky to create a temporary material + set color maps within it?

amber saffron
mental bone
#

Why is my copute shader that is dispatched from a command buffer not showing up in RenderDoc or the frame debugger

amber saffron
mental bone
#

oh yes

#

Im using it to move things that are rendered by a BRG, and they indeed do move

#

if I comment out cmdBuffer.DispatchCompute(m_TransformUpdateCS, m_TransformUpdateKernel, (queueCount + 63) / 64, 1, 1); they stop moving

amber saffron
#

Hum, well, if it is executed, and the result is visible in RenderDoc, it should be there.
Tried to name the command to something particular and search it in the commands list of renderdoc ?

mental bone
#

doesnt show up at all

sullen delta
amber saffron
mental bone
#

I'm hella confused as well

amber saffron
mental bone
#

I'm not seeing the whole command buffer as well

#

not just the dispatch event

amber saffron
#

Ah, interesting. How are you executing it ?

mental bone
#

Graphics.ExecuteCommandBuffer(m_gpuCmdBuffer);

amber saffron
#

I'm not 100% sure, but maybe this is the source of it.
I think this is not captured by renderdoc, compared to adding the command buffer to camera events

mental bone
#

that could be it, but idk if renderdoc can even capture it

#

and I so dislike Nsight

golden flint
#

Can you please help me with putting a material on my terrain? I dont get it

grand jolt
grand jolt
#

There should be a layers bit in the terrain component

sick knot
golden flint
grand jolt
#

you're on Raise or Lower terrain

golden flint
grand jolt
#

change to paint texture

golden flint
#

didnt see it

#

thx

grand jolt
regal stag
opaque shoal
#

Hi, I recently started studying unity and have a question: Which is better to use your own shader (screenshot) or use secondary textures in sprite editor

golden flint
#

keyboard was in the backrooms

grand jolt
#

go to the newly created layer file and change the sliders

#

should be in the same folder as the terrain file iirc

#

or maybe the one you had open at the time of creating the layer, who knows

grand jolt
regal stag
sick knot
copper falcon
#

Question about URP forward+PLUS:
The unity hlsl code takes the keyword 'USE_FORWARD_PLUS' for the forward-plus path. Do i need to manually set that in my keywords or there a way to indicate to the shader, that the render settings are set to forward plus and this, USE_FORWARD_PLUS is set automatically?

regal stag
# copper falcon Question about URP forward+PLUS: The unity hlsl code takes the keyword 'USE_FORW...

I have no experience with Forward+, but looking at the ShaderLibrary, it seems Core.hlsl has :

#if defined(_FORWARD_PLUS)
#define _ADDITIONAL_LIGHTS 1
#undef _ADDITIONAL_LIGHTS_VERTEX
#define USE_FORWARD_PLUS 1
#else
#define USE_FORWARD_PLUS 0
#endif

And _FORWARD_PLUS is defined in shaders via a keyword, #pragma multi_compile _ _FORWARD_PLUS
Assuming the shader has that, it'll be set automatically by Unity

copper falcon
astral pecan
#

I have a problem with this shader.

float TOA(float opposite, float adjacent)
{
    return degrees(atan(opposite / adjacent));
}

void TrigBillboard_float(float3 VertexPosition, float3 ObjectScale, float3 ObjectPosition, float3 CameraPosition, float3 MinAngle, float3 MaxAngle, out float3 Out)
{
    float3 scaledVertexPosition = VertexPosition * ObjectScale;
    float3 deltaPos = ObjectPosition - CameraPosition;

    // Calculate X angle through YZ Axis.
    // Calculate Y Angle through XZ Axis.

    float angleX = TOA(deltaPos.y, deltaPos.z);
    float angleY = TOA(deltaPos.x, deltaPos.z);

    // Clamp the X & Y Angle with MinAngle & MaxAngle.

    float3 eulerDirection = float3(-angleX, angleY, 0);

    float4x4 constrainedDir = ToMatrix4x4(eulerDirection);

    float4 rotatedVertex = mul(constrainedDir, float4(scaledVertexPosition.x, scaledVertexPosition.y, scaledVertexPosition.z, 0));
    float3 finalPosition = rotatedVertex + ObjectPosition;

    Out = TransformWorldToObject(finalPosition);
}
#

When X or Z is close to 0, the billboard flips strangely

#

It lookat the camera properly, but not when X or Z is close to 0

kind arch
#

I'm trying to use the URP Unlit Sprite shader graph, but it seems to be missing an emission component from its master node

neat hamlet
#

unlit doesnt have lighting so no emission, its basically all emissive if you add post processing

kind arch
#

I remember using emission on an unlit graph a few years back, it seems that I simply added an emission map multiplied by hdr to the color node. Must've forgotten. Thanks

grizzled bolt
kind arch
compact willow
#

Heyo, i have a question. Is there any way or alternative to get the Camera Depth Normal Texture? I need a non script method as im making a shader in Amplify for VRChat and they dont allow any external scripts, im like 90% there i just need to mask my custom triplanar sample shader so it looks clean. > - < Version of unity: 2019, built-in pipeline

vital smelt
#

Does anyone here with a big brain know how I could add randomised patterns onto a shader graph?

#

Like, I have these mountains, but I want the mountains to feel more random.

rare wren
#

If they are all interactable, why don't you randomly place them with script?

Via shader graph I'd probably say:

  • use a noise texture
  • use step to make it lack and white
  • (optional) pixelize the shape to fit the pixel size of the piramid
  • have the piramid texture loop where the shape is white
  • put that into color @vital smelt
vital smelt
#

That's how it already generates the positions of the Pyramids

#

@rare wren

#

It just uses noise and where the noise is white? Pyramid

rare wren
#

Then use different noise?

vital smelt
#

I wanted to try making some of the pyramids overlap though, or even have some larger than others

rare wren
#

Change the values of the noise or maybe vernoi noise

rare wren
untold lava
#

Can anyone point me to a place where I can make a pixelate shader (in basic render pipeline)? I have a line renderer and want to make it pixelated

static meteor
#

for some reason my texture wrapping math acts differently out of a sub graph versus inside the main graph

rare wren
#

Like 2 in, 2 out

static meteor
#

cleaned up a little to show the top is just completely different

regal stag
untold lava
#

Can anyone point me to a place where I can make a pixelate shader (in basic render pipeline)? I have a line renderer and want to make it pixelated

static meteor
rare wren
#

Maybe make a bug report for it

untold lava
#

I have this shader code

Shader "Custom/Pixelate"
{
    Properties
    {
        _MainTex("Texture", 2D) = "white" {}
        _PixelSize("Pixel Size", float) = 10.0
    }

    SubShader
    {
        Tags { "Queue"="Transparent" }
        LOD 100

        Pass
        {
            CGPROGRAM
// Upgrade NOTE: excluded shader from DX11; has structs without semantics (struct v2f members pixelSize)
#pragma exclude_renderers d3d11
            #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;
                
            };

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

            sampler2D _MainTex;
            float _PixelSize;

            float4 frag(v2f i) : SV_Target
            {
                float2 pixelPos = i.uv * _PixelSize;
                pixelPos.x = floor(pixelPos.x);
                pixelPos.y = floor(pixelPos.y);
                pixelPos /= _PixelSize;
                return tex2D(_MainTex, pixelPos);
            }
            ENDCG
        }
    }
}

However it doesn't seem to do anything

neat hamlet
#

you had an error it in before and it added the "exclude_renderers" tag, take that out

static meteor
kind arch
#

Is there a node that will return 0 if below a certain X and return the original number if higher than X?

young rampart
#

custom code node with return x > limit ? x : 0;

#

Is there a way to pack float material properties into float4s ?

kind arch
lofty lodge
#

Anyone know how I could make it smooth all the way. Its multiple gameobjects stacked in a row, and you can clearly see where one ends

copper falcon
lofty lodge
#

hmm true

lean lotus
#

so unity has the ColorValue in the standard shader
this is the albedo
but does unity do anything to this value? like gamma correct it or whatever?
wondering because that albedo isnt matching with something im doing that is just raw outputting it

copper falcon
lean lotus
#

ahhh ok thanks

lofty lodge
copper falcon
lofty lodge
#

oh right, i'll try that. thanks

gusty horizon
#

Quick Q. I've seen various different functions being used in different tutorials to serve the same purpose. For example - for getting the pixel color of a texture in the fragment function, some tutorials use tex2D, and others use SAMPLE_TEXTURE2D.

In that specific example, what is the difference, and what is the standard that should be used? I see tex2D a lot, but it doesn't appear in Unity's Unlit shader, and I'm getting errors when trying to use tex2d(_MainTex, i.uv): no matching 2 parameter intrinsic function. (my UV coord is properly being set in vert)

sleek kite
#

It's mainly different styles of writing HLSL code

#

SAMPLE_TEXTURE2D is actually a macro for Texture2D.Sample(samplerstate, uv), which does the same thing as tex2D

#

iirc it does some additional checks to pick the correct way to sample depending on the platform

#

SAMPLE_TEXTURE2D / Texture2D.Sample is the "newer" way, but I still see a lot of shaders using tex2d

#

I also think your error is not from the function not existing, but from you passing in a texture instead of a samplerstate

gusty horizon
#

Ah

#

That makes a lot of sense! I still don't fully understand what a sampler of a texture really is, but I'm comfortable enough being able to pull one/the other out when needed.

#

I appreciate the breakdown & the link ❤️

astral pecan
#

Is there a way to use functions from another hlsl file?

#

I have a few functions that I want to reuse

#

Sorry for noob question

#

Just started

astral pecan
#

Nvm just found out #include <HelperLib.hlsl>

sage pelican
#

I have made a grid shader in world abosolute, but it doesn't extactly do as I expected it to

#

I'm trying to make a grid that is in a plane that follows the camera, but its an endless grid in world space.

sage pelican
#

Ping me if anyone can help out

copper falcon
oak aspen
#

What node would I use if i have a texture and i only want it visible in the darker parts of a gradient? maybe with a manually set threshold?

#

i basically have a simple noise and i want less noise in the lighter parts of the gradient vs the darker parts of the gradient

oak aspen
#

thank you 🙂

#

kinda does what i need but the texture now became very low as it's not taking into account the gradient of noise

#

and before the step

#

essentially, in the lighter parts of the gradient, i either want to fade the noise out or reduce the noise

dry solar
#

Dont know if this is the right place to ask but, I've made a little planet to walk on in my game but even an 8k texture is blurry up close. can I add tiling textures based off the colours? So like a grass texture for green parts and a snow one for white ones

copper falcon
karmic hatch
grizzled bolt
stark prairie
#

how can i fix my charachter being this deep in my interactive snow shared

gusty horizon
#

How do you guys handle noise textures? up until now I’ve just been downloading samples of different noise methods online. Is this fine? Should I be writing a script to create noise, and would this typically be a C# or a shader script?

I also want to learn more about different applications of different types of noise (e.g Perlin noise is often applied to procedural terrain), and how these types of noise can be generated using a shader.

oak aspen
#

is there anyway to remove this seam without using world space UV ?

#

with a noise using the triplanar node works well but the triplanar only accept a texture not a gradient (done with 2 colours and lerp)

void turret
low lichen
void turret
#

I have, and haven’t found much similar
Just trying to find a shader that just does that like merging effect

low lichen
void turret
#

Alright thank you!

sage pelican
swift loom
#

Can anyone tell me what I'm doing wrong? I'm trying to send an array of colors to the compute shader via a structured buffer but I can't get any data that seems readable...

copper falcon
# gusty horizon bumping if anyone knows!

GPUs can create different types of noise within shaders. If you search for 'shader graph noise' you will some content about how the noise nodes are used for things like flickering fire, pulsing energy shields etc.

gusty horizon
copper falcon
# gusty horizon I'm getting alot of content specific to using shader graph, but I'm looking to s...

You can look into the URP+HDRP shadercode.
https://github.com/Unity-Technologies/Graphics/tree/ce1905322722287c1420a6d85de14158c1648a84/Packages/com.unity.render-pipelines.universal/ShaderLibrary
Very helpful for writing hlsl and customFunctions for shadergraph.

GitHub

Unity Graphics - Including Scriptable Render Pipeline - Graphics/Packages/com.unity.render-pipelines.universal/ShaderLibrary at ce1905322722287c1420a6d85de14158c1648a84 · Unity-Technologies/Graphics

swift loom
tall pawn
#

Hey all!

I've been searching and digging trying to find examples of the vfx I'm hoping to achieve on my project! I've finally found it, a 'modern' ukiyo-e style represented beautifully by harry heath;

My issue is, I simply can't figure out how to recreate, has anyone worked on anything like this that could lend message to figure it out!

regal stag
#

For the third example, I know Harry Heath also posted a small breakdown : https://twitter.com/harryh___h/status/1297891009737654277

@weltraumimport Here's a little breakdown of the line rendering; the second image is an extra pass which is then used to determine where lines should be drawn and what colour the line should be. (here I'm using red and blue channels as coords for a LUT and green for inner detail)

Likes

156

tall pawn
low lichen
swift loom
#

I tried sending a simple Vector4 into a float4 StructuredBuffer but it didn't work either, so I guess the structs and datatypes are pretty strict when it comes to matching

lean lotus
#

will compile times of a compute shader be improved if I moved kernels into cginc files, or would it be much better to just make entire seperate compute shaders?

#

cuz these 4 minute compiles are getting to me

gusty horizon
wanton grove
#

How do I bake the diffuse result of shader on a mesh into a texture? For example, if I had a shader that converted the mesh's normals into diffuse colors, how would I then bake that color data into a Texture2D? I'm using shader graph btw.

lean lotus
#

Is there any downside to having 12 compute shaders with each 1 kernel vs having 1 compute shader with 12 kernels?

grand jolt
#

I applied this moss shader on my rock but its so pixeled

#

Not sure what's going on

wanton grove
grand jolt
wanton grove
regal stag
# wanton grove Can this be done at runtime?

The tool itself is editor-only, but the concept behind it could probably work at runtime. Rather than using vertex positions the shader needs to output in uv-space (there's a provided subgraph for that). You'd then draw that renderer to a render texture, (and optionally save that to a png).
I use this method : https://github.com/Cyanilux/BakeShader/blob/e2e61b3cc4ae99338899c50977f2932cfeb4f897/Editor/BakeShader.cs#L226, as it should work in any pipeline.

wanton grove
grand jolt
#

There's no PBR graph in URP?

regal stag
# wanton grove Awesome, thanks! I've tried baking render textures modified by a material alread...

Yes. With a blit you're basically rendering a fullscreen quad while with this you'd still be rendering whatever mesh you want. It's just using the mesh UVs to determine the position on screen (or render texture in this case), rather than the vertex positions. (and ignoring view/projection translations due to cmd.SetViewProjectionMatrices)

Since the graph requires overriding the Position port, you'd have to use a Custom Interpolator if you want to pass through the regular vertex position. (see example 1 here : https://www.cyanilux.com/tutorials/intro-to-shader-graph/#custom-interpolators)
Normals and other data should work fine as-is though.