#archived-shaders

1 messages Β· Page 50 of 1

cosmic prairie
#

so sides point upwards

#

you could do the same check in shader graph to be sure

meager pelican
#

IIUC ....The standard is to orient the tangent in the same direction as the UV.x direction (red) and since the surface normal is oriented at that pixel in the z direction, the bitangent is orthogonal to them both and is the green value in the RGB order. Hence the oft-used TBN matrix...tangent, bitangent, normal. (RGB = TBN ish).
But like Peter226 said, there's a handedness to it and a multiplier in the .w component somewhere.
http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-13-normal-mapping/#tangent-and-bitangent
That's an openGL version, but nice graphics.

#

Every point on the surface has its own tangent space.

meager pelican
#

You'd have to pass the object's extents into the shader/material data. You could calculate such a position in the vertex stage relative to the object-space origin (0,0,0) and then transform them to whatever-space.

This is because, by default, you only get the current polygon's info (and really only the current vertex of that polygon at the vertex stage, when not using a geometry stage).

waxen raft
#

My custom shader doesnt care about enviromental lighting, like at all, could anyone point me in the right direction to make it affect it? πŸ˜„

cosmic prairie
#

there's a thing called block shaders the devs are working on, which will be kinda usable like surface shaders for builtin but with more control

waxen raft
worthy marsh
#

btw, thanks for the answer

cosmic prairie
#

and do they need to be different sizes later on

worthy marsh
#

they are mostly the same

#

with the exception of one or 2 maybe

cosmic prairie
#

can't you just add an offset to the object position?

#

could maybe have an exposed variable in the shader that sends the offset so you only need to calculate the offset once

#

and you can have it different for those two objects

worthy marsh
#

hmmm

#

that sounds like a good idea

weary plinth
#

ok tbh idk what i did but the lighting is fixed, the textures however arent

weary plinth
#

materials i mean*

cosmic prairie
#

can you post pictures?

weary plinth
#

yeah hold on one second

cosmic prairie
#

ty, how they look and how they are supposed to look

weary plinth
#

theyre meant to look like this:

#

wait nvm that scene works

#

theres one scene that doesnt work

#

this is what happens when the scene runs through the menu (not meant to happen):

cosmic prairie
weary plinth
#

yeah

cosmic prairie
#

in that case it still looks like a lighting issue to me

#

if you looks at it closely it has some kind of texture

#

just too dark

weary plinth
#

i may know the problem

#

actually idek

#

i'll figure it out

#

thanks though c:

cosmic prairie
#

np, maybe if you do have any light probes / baked lighting double check that, can't think of anything else that could cause it

weary plinth
#

ive fixed it

#

thank god

cosmic prairie
#

nice, gj!

brittle bolt
#

Hey all, I am working on converting a fog shader I wrote in unreal to unity shaderlab. I am running into a snag on one node in particular which is "TransformVector", which is taking View Space to World Space.

#

This is the function, and you can see there its transforming a 0,0,-1 vector.

#

This is the result of the function, and I am having a hard time getting the same behavior in unity. I am avoiding sampling the depth texture and this results in a close enough depth mask for me to use for fog.

meager pelican
brittle bolt
#

I’m writing it in hlsl and it’s hard to find documentation

tribal badger
#

I'm using URP and a vertex displacement shader, It was casting my vertices to a wide range, and I had the camera at (0, 0, 200) and no self casting shadows. I noticed if I move my camera closer to the origin the self shadows to appear. I can probably tweak my shader and scale everything down, but I'd like to understand what the default logic is for displaying self shadows, is it dependent on camera distance or is there something else going on?

amber saffron
tribal badger
ebon basin
#

https://glowfishinteractive.com/dissolving-the-world-part-1/
These devs had an interesting idea with how they dissolved walls, using a texture with world space uvs to create a mask that dissolved other compatible materials. If you want more of a 'global' rendering option, using renderer textures with a mask and sorting what gets rendered between the layers instead of relying on the object's material. There's also some nice tools outside of shaderlab called render objects, which are available on srps, that I found pretty easy to use for this type of stuff.

true wren
#

Hi, I made this simple dissolve shader but the problem I'm having is that it isn't affected by ambient lighting, it's pitch black if there's no directional light. Any idea on how to fix it?

worthy marsh
ebon basin
#

Yeah np, I do use the render objects for walls in my isometric game and they do work pretty well for that specific case

frosty linden
#

Hello, I'm trying to fix the transparency issue in my hair shader in HDRP. I've already tried to play with depth prepass, depth postpass and cutout value but I can't get a good feeling out of it. If I cut out too much, the hair becomes fully opaque which defeats the purpose of transparency.

#

Howver I noticed that if I simply duplicate the hair and stack it on top of itself, the transparency gets much better.

#

Is there a way to reproduce this stacking effect directly in shader graph? Maybe through postpass in some way? So that I don't have to duplicate the model?

meager pelican
# brittle bolt I’m writing it in hlsl and it’s hard to find documentation

But what pipeline? I assume one of the newer ones, as the BiRP has a bunch of HLSL doc, as that's how it is written.
Anyway, yeah, I can imagine it's tough.
Cyan has a site with docs. See stick pin above.
Also, you can use shader graph to generate the code for you and then examine what it generated. It's really a code generator anyway.
Then there's the unity source code for the shaders they use, in the code repository for your installed version.
And of course lastly there's the web and varied resources.

brittle bolt
#

Yeah I am using BiRP

#

I know it’s something simple it’s just hard to identify the right property to grab

meager pelican
#

The code to do the transformation that you asked about above is in the node example from the shader graph link I posted earlier if you want to do it that way.

queen vortex
#

Hey guys, can you help me with a question? I'm trying to make a tileable shader that sets textures based on position (or at least that's what I wanted to do) this is my graph:

Basically it works perfectly, exactly as I wanted when the object's scale is large, but when the scale is low, the texture is stretched instead of tiling correctly, is there any way to fix this so that the Atlas texture is always on top , the middle one always in the middle and the bottom one always on the bottom? without stretching of course

queen vortex
#

(effect of using a tileable UI panel with rect tool)

ebon basin
#

Neat, I'd assume you need some ratio between the tiling and the scale amount, but there's always some easier way to go about it

#

Check out wrapping mode maybe

queen vortex
#

Same results :/

ebon basin
#

x_x

ebon basin
#

So I've got shadow casters on my sprites, but it's a little iffy considering I also billboard them towards the camera and by not rotating the direction the shadows they cast. It creates problems such that the self shadowing darkens the sprite at specific viewing angles. Seems a little complicated to resolve, unless anyone has any ideas, otherwise I'd probably want to disable the self shadowing if that's possible at all with shadow casting. Actually doubting this is even that possible considering it's just a quad...

frosty linden
#

Does anybody know if there are any restrictions regarding texture channel packing? I have 4 greyscayle textures: two albedos, two masks. I want to merge them into one packed texture. red would be albedo1, green is mask1, blue is albedo2 and alpha is mask2.

#

Here is my custom sub graph to extract the channel dynamically (Can't use the buit in one since the channel can change depending on packing configuration) I want use a vector4 input. x would be red, y is green, z is blue and w is alpha.

#

The preview seems to work fine but the actual result is different than expected.

#

Here is when I use a texture where I packed albedo1 and mask1 into one single texture

#

And here is when I use a full packed texture.

#

Each are using the adequate channel but in the second picture, the alpha seems messed up.

#

is it not possible to pack a mask texture into something other than alpha channel or grayscale channel?

#

Here is a better comparison. Left is 4 packed channels, right is 2 packed channels

#

The left one has much more transparency than the right one despite both using the same mask. The difference is in left one, I packed the mask in the green channel and in the right one, I packed it in alpha channel.

#

Hm, after checking the preview in my custom sub graph, both channel do not render the same for some reason. I guess my packing script has some flaw. I'll investigate :x

#

That or my sub graph logic is flawed too.

#

Hm, I've checked my packing and both channels are exactly the same...

#

but the preview still shows different results

#

My logic seems flawed in the sub graph?

#

My idea is still to mask 3 channels and just keep 1 based on a Vector4 mask. I multiply each channel by the related mask channel and then take the max out of any of those to get the final result.

#

I tried to preview the green and alpha channel on each of the textures but I forgot alpha is ignored in preview node :/

#

But even like this, it seems my green channel preview is not the same as original.

#

Some semi transparency is lost on all edges

vocal narwhal
#

Have you tried looking at the compression settings of your texture, and if you're not importing it as Linear, switching to that?

frosty linden
#

Indeed, I thought about that. But both are using the same settings. I figured the main preview had alpha working so here is the difference. Straight from green in 4 packed and straight from alpha in 2 packed. Really strange

#

Both files have the same settings

vocal narwhal
frosty linden
#

Great, it's the same now

#

Thanks a lot for your help! So many settings to understand :x

frosty linden
vocal narwhal
frosty linden
#

Got it, thanks for the link!

worldly drift
#

How do I write a depth only shader with HLSL for URP? Everything I tried only works when I also output color.

regal stag
worldly drift
cosmic prairie
worldly drift
cosmic prairie
#

yep, render features are a very static thing

#

which I do not like 😠

#

πŸ˜‹

smoky widget
#

Hi! I need some help optimizing this shader i've ben working on

full kestrel
#

I wrote a fragment shader that returns .5 for RGB. But in the Unity color picker the color is not 128,128,128 for RGB. This is a clean new project using URP. Why?
fixed4 frag (v2f i) : SV_Target
{
fixed4 col = fixed4(.5,.5,.5,1);
return col;
}

brittle bolt
#

I mentioned the other day that I am working on converting a shader I had made in unreal for non-depth buffer accessing fog. It relies heavy on this vertex depth function. I am using BiRP, but have not been able to get it to function properly. I was able to make it in shadergraph, as you can see here, the math works, and the mask cascades into the distance. When trying to do this in hlsl, I cannot get proper results, its as if the worldPos, and cameraPos in Standard Surfac input are not correct.

full kestrel
#

@regal stag thanks I've been searching for hours to try to find out why this is happening

lament scarab
#

Is there a way to have a stencil shader ONLY RENDER what's inside it, and not other objects that are behind but don't have the material/shader applied?

#

Basically I would like this floor not to render through the stencil shader

#

source image

ebon basin
#

So, you want the windows to render through everything, along with any object the window itself is rendering?

#

ah, ok I see what youmean

ebon basin
#

Something like that?

#

I'm not sure what objects you're trying to render without the material, but you can instead just use render objects and do it by layer if you wish

meager pelican
leaden mist
#

I'm new to shading, and I have been stuck on this issue for a while now, but it seems really simple. How do I give the shader a vector2/float2? (writing a compute shader)

modest nimbus
#

Any idea why these Materials are not in sync with the textures?

regal stag
regal stag
modest nimbus
regal stag
#

That won't make URP run shaders that are made for built-in RP. They need different shaders

modest nimbus
#

the "MenuHome.glb" is imported through "GLB Importer"
using these 2

modest nimbus
#

@regal stag Could you please give me a hint where to search so I can import different shaders?
(like, what type of tutorials should I search for)

regal stag
# modest nimbus <@357936113983291393> Could you please give me a hint where to search so I can i...

Okay I see now, the GLTFUtility has shaders for both Built-in and URP. You need to use the ones under the GLTFUtility/URP heading. You can change the shader at the top of each material asset.

Though if these are embedded materials from import you might not be able to edit them directly. I'm not sure if there's a way to tell Unity to automatically use the URP ones... But should be able to create your own materials and assign it under the "remapped materials" in the model settings. https://docs.unity3d.com/Manual/FBXImporter-Materials.html

modest nimbus
#

UPDATE: It worked perfectly!
Thank you again for your help @regal stag !

lament scarab
#

Oh wait, is the texture applied to the object or is it something "inside it", not exactly that probably then.. I'll still look a bit into it though.
Also, are render objects URP? (I'm using built-in)

lament scarab
#

Here's the code I have if you don't mind directing me more:

        Pass
        {
            ZWrite [_ZWrite]
            ColorMask[_ColorMask]

            Stencil
            {
                Ref[_StencilReferenceID]
                Comp[_StencilComp] // always
                Pass[_StencilOp] // replace
                ReadMask[_StencilReadMask]
                WriteMask[_StencilWriteMask]
            }

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            fixed4 _Color;

            struct appdata
            {
                float4 vertex : POSITION;
            };

            struct v2f
            {
                float4 pos : SV_POSITION;
                float4 worldPos : TEXCOORD1; // fog
            };

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

            float _FogDensity, _FogOffset; // fog
            float4 _FogColor; // fog
            half4 frag(v2f i) : COLOR
            {
                /* Fog */
                float viewDistance = length(_WorldSpaceCameraPos - i.worldPos);
                float fogFactor = (_FogDensity / sqrt(log(2))) * (max(0.0f, viewDistance - _FogOffset));
                fogFactor = exp2(-fogFactor * fogFactor);


                return lerp(_FogColor, _Color, fogFactor);
                // return _Color;
            }
            ENDCG
regal stag
# lament scarab Basically I would like this floor not to render through the stencil shader

You'd need the render order to be stencil window -> then all other objects. Can force that by using the Queue tag or override the render queue on the material. Can then have those objects test against the stencil buffer. The white objects you have there are already doing that. You'd do the same for the floor but using a NotEqual comparsion.

If you're in URP, you can use RenderObjects features to override stencil values for an entire Layers of objects without needing custom shaders.

An alternative to stencils is to use an additional camera & render texture, similar to rendering "portals". Might be a bit more expensive though.

gritty rapids
#

ehm, there's no metalness when using SSS with the StandardLit ?

astral mason
#

What's wrong with the refraction?

dim yoke
#

Creating custom shadows is very tricky but when shadows are enabled for the shader, self shadowing should work automatically

ebon basin
#

How about, is there ways to remove self shadowing when casting shadows? ^^

toxic flume
#

Hey, my colleague has implemented cellular automata based water fluid simulation. (Compute shader)
I see in his implementation, an index can be changed/written in different threads. Is it OK?!
The operator is +=.

buffer[index]+= diff[index-1];
buffer[index]+= diff[index+1];
//...
cosmic prairie
#

when appropriate

#

looks like there's a diff buffer tho, I guess the diff buffer is calculated beforehand? if there's a memory barrier group sync after the diff buffer calculation then it's okay

toxic flume
#

I don't access his code but I can put it tomorrow, appreciated.

toxic flume
#
buffer[index-1]+= diff[index];
buffer[index+1]+= diff[index];
//...
cosmic prairie
toxic flume
#

It adds the current value to its neighbors

cosmic prairie
#

oh yeah that looks wrong

#

could write it like you had it first

toxic flume
#

He is intern and probably his code has a lot of bugs

cosmic prairie
toxic flume
#

but he said the cellular automata based water fluid simulation is not similar to standard cellular automata!
I try to convince him

cosmic prairie
cosmic prairie
#

"cellular automata" is very broad

toxic flume
cosmic prairie
#

ahh, yeah makes sense

#

needs a bit of tweaking then, but he's got the right spirit πŸ˜„

toxic flume
#

Each voxel injects some values to its neighbors.

#

The view (renderer) seems OK kekwait

cosmic prairie
cosmic prairie
#

does he not like the job?

toxic flume
cosmic prairie
#

Oh man, that would be a job I'd love to work on πŸ˜†

#

Guess some prefer normal gameplay programming

cosmic prairie
ebon basin
#

Ah, that's unfortunate. Trying to figure out some realtime shadows with sprites, but there's a large peter panning issue I'm having and I've no clue how some 2.5D games manage it all

#

doesn't help I've got full 3D camera rotation on the sprite which is a problem of its own

cosmic prairie
ebon basin
#

Easily solveable by just not allowing to recieve shadows, but I've spent a week to actually get that correct lol

#

my thinking is I need to reduce the bias (or offset?) of the shadow when the shadowing is behind the character

#

but then I would still run into the panning issue (shadow isn't completely under feet)

cosmic prairie
#

idea 2 is to write a custom shadow rendering pass where you also render the ID of the topmost object with it's depth value in the shadowmap

#

but it's REALLY time consuming

cosmic prairie
ebon basin
#

by more above, you mean that a shadow wont render on the sprite unless the depth of it all is at a specific height?

#

I was thinking of something like that if that's the case, but that would then affect the shadowing of the geometry of the level (on the sprite)

cosmic prairie
#

that's "easier"

#

you need to copy the lit shader's code, and re-define the part in the shadow calculation code after importing it, where it reads the shadow map

#

OR the value of the depth bias global variable πŸ€”

#

that may be easier now that I think about it

ebon basin
#

Yeah, more technical then I thought it all would be. Really would have loved to do something with just light layers, but that doesn't seem possible.

cosmic prairie
#

yeah, shadows are kinda their own species

ebon basin
#

I'll look into your suggestions, but if it comes to this maybe I should look into just making my own silhouette and rendering that on the ground of sorts.

#

another sprite ;p

cosmic prairie
#

oh yeah that would work too πŸ˜„

ebon basin
#

ty though

cosmic prairie
#

np

feral quest
#

I don't have any shadow on builtin unity, on urp i had them, how can it be?

stoic roost
#

So i have a problem and a question at the same
I have a image with sprit renderer in a 3d project
I have also List of points of vector3
I wanna make of that image a heatmap where it is full of green and on those given points
does it get red and you know orange yellow

#

any way how to do it?

toxic flume
#

How can I handle it?
I want to use sprite renderer with order + cutout shader.

royal pier
#

Anyone who can possibly help me out with a shader issue? I feel like I am really far, may just be moving things around, but I can't seem to get there.

#

I have a shader in which I'm trying to add a cutoff, where the top part doesn't get rendered based on an Ycutoff float. Right now it's just making things white within or the whole top white.

#

If you join Unite in Amsterdam, I can offer you a beer for this sadok

regal stag
royal pier
#

Yeah, struggling with it. It's shader code and shaders are really not my expertise

#

It's just a pass I added at the bottom, but its just making things white

Pass
{
Name "CutOff"

        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        #include "UnityCG.cginc"

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

        struct v2f
        {
            float2 uv : TEXCOORD0;
            float4 vertex : SV_POSITION;
            float3 worldPos : TEXCOORD1; // added this line
        };

        sampler2D _MainTex;
        float _CutoffValue;
        float4 _ObjectBounds; // add this line to get the object bounds

        v2f vert(appdata v)
        {
            v2f o;
            o.vertex = UnityObjectToClipPos(v.vertex);
            o.worldPos = mul(unity_ObjectToWorld, v.vertex).xyz; // added this line
            o.uv = v.uv;
            return o;
        }

        fixed4 _TopColor;

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

            float relativeHeight = (i.worldPos.y - _ObjectBounds.y) / (_ObjectBounds.w - _ObjectBounds.y);
            if (relativeHeight < _CutoffValue)
                discard;

            return _TopColor;
        }
        ENDCG
    }
#

Just a copy of the default unity "Standard (Specular setup)" with this pass added at the bottom

regal stag
#

You can't add it as a separate pass, that renders the mesh twice. You need to alter the main pass

royal pier
#

Ahh, makes sense. I assume the main pass is in this case the "FORWARD"

regal stag
royal pier
#

I added it above ENDCG on every pass. Issue might be the frag

#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;
            float3 worldPos : TEXCOORD1; // added this line
        };

        float _CutoffValue;
        float4 _ObjectBounds; // add this line to get the object bounds

        v2f vert(appdata v)
        {
            v2f o;
            o.vertex = UnityObjectToClipPos(v.vertex);
            o.worldPos = mul(unity_ObjectToWorld, v.vertex).xyz; // added this line
            o.uv = v.uv;
            return o;
        }

        fixed4 _TopColor;

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

            float relativeHeight = (i.worldPos.y - _ObjectBounds.y) / (_ObjectBounds.w - _ObjectBounds.y);
            if (relativeHeight < _CutoffValue)
                discard;

            return _TopColor;
        }
#

Thank you so much though @regal stag I can play around a bit more with this, don't want to take up too much of your time ❀️

regal stag
#

The passes already have their own vert/frag shaders in the include files (UnityStandardCoreForward, UnityStandardShadow, UnityStandardCore, etc.), you'd need to copy & edit those. But if you're in the built-in RP it might be easier to look into writing a Surface Shader instead.

royal pier
#

Been messing around with it for 2 days now, even bought gpt4 to no prevail

#

I should learn Shaders a bit more properly at some point, this is just donig random things you don't fully understand and hope it works

#

I managed to get a cutoff working in the shader editor, but can't seem to add the texture and holes to it notlikethis

waxen verge
#

Hi everyone :),

I'm trying to do a tornado shader for my study project but there is a line on the side of my tornado and it's ugly πŸ₯²

I don't know if this problem coming from my blender model or if it can be solve somewhere with unity somewhere.

It's maybe appear because i'm using noise but i'm not sure :/ I'm in URP.

Some help please ^^'

grizzled bolt
waxen verge
#

There is no wind texture, it's a noise with twirl and a dissolve, but i'm going to try to switch my noise by a repeating noise texture.

warm rapids
#

does anyone have any feedback on how i could improve the look of this water shader? It moves and the colours are quite nice but I think the normals look quite flat. It would be nice if the waves were more promenant

dense forge
#

hey guys, i have a simple question: why can't i multiply these two?

warm rapids
#

You can't use sample texture 2d going in the vertex space

#

swap it out for a Sample Texture 2D LOD node, i had this issue

#

i think that's the right explanation

cosmic prairie
#

Yeah, in the vertex function you need to choose the LOD level yourself, so you need that node

warm swallow
#

Hey.
Hoping someone can help me out with a shader problem.
Might be trying to do too many things in one shader but lets see.
Currently using built-in rendering.

I just want a standard shader that can clip up to a certain worldPos.y on the second camera (minimap) using plane clipping. I couldnt find the code for the current Unity standard shader so using: https://github.com/TwoTailsGames/Unity-Built-in-Shaders/blob/master/DefaultResourcesExtra/Standard.shader...it might be the current, not sure but it does the job.

Then tried to implement: https://www.ronja-tutorials.com/post/021-plane-clipping/ on top of it (but editing for the second cam) and mash them together.
Got mixed results lol.

I can get it clipping well or rendering well, but it messes up when trying to do both.
Code: https://gist.github.com/Unrelentless/cb8f1d7ae771838ea16562843a8fc346

What am I missing in the clipping subshader to get it rendering those leaves nicer? Or do those two methods just not mesh well together?

Gist

Standard Shader + Clipping. GitHub Gist: instantly share code, notes, and snippets.

warm rapids
#

yeah he's an explanation of using Sample Texture 2D vs Sample Texture 2D LOD

dense forge
#

Thank you guys! That makes sense :) (btw, am I allowed to say thanks in this chat?)

warm rapids
#

of course!

royal pier
#

I gave up πŸ™ƒ

lunar valley
warm rapids
#

there is vertex displacement when the scene is played

#

I agree though

#

I've tried some new normal maps

#

i'll take a video

#

this is the new normal maps. think it looks better though i have set it quite strong at the moment

quiet osprey
#

I'm going insane due to something strange with transparent materials in stand-alone builds.. By using RenderDoc it looks as if my UV coordinates gets messed up in the fragment shader somehow... This is my issue

#

Its so simple its stupid.. Switching the shader to opaque instead of transparent and everything works as intended.

#

RenderDoc also tells me that the UVs are OK both pre and post the vertex shader step.. (I'm rendering a simple quad here, so its quite easy to verify)

dapper canopy
#

I try to use a render texture that uses a camera that can only see a layer with these ball things then I made a material with this render texture and I put the material in a flat quad but for some reason the quad is darker then the camera and I don’t know how to fix this issue

echo tusk
#

Hello there, I have encountered a grabpass issue on built-in rp

#

Recently, I've been working on a large project involving the Pixel Perfect Camera and Canvas space effect. Specifically, I applied a grab pass shader to a full-screen image component for filtering purposes. However, I discovered that when the pixel perfect camera is set to the mode {Pixel Snapping, CropFrameXY, Stretch Fill}, the grab pass effect (material attached to the UI image component) appears stretched.

To provide a clearer demonstration, I have attached a simple project that you can open and follow these steps to reproduce the issue:

` - Open the project and adjust the resolution setting in the game view to "Free Aspect."

  • Click the Play button and resize the game view to different aspect ratios.
  • You will observe that the game view displays the stretching problem.
  • To resolve the issue, disable the image component under the canvas, and the stretching will no longer be visible.`

Please note that in this project, the included shader merely captures the image behind it and renders it directly. In the actual project, there are several shaders based on this one, and they function correctly when attached to the sprite renderer.

#

(From Unity Forum

cosmic prairie
dusty creek
#

huh.... I was told this was supposed to make the plane invisible, did I do something wrong?

#

figured it out UnityChanOops

regal stag
dusty creek
#

yep

#

thanks xD

raw frigate
#

hey

#

im stupid but

#

how do i rotate the step

#

so that the whites at bottom

dark mural
#

what is the step node coming from?

raw frigate
dark mural
#

I meant split

#

thanks

#

swap the r for the g

raw frigate
#

alr thanks i will try

#

Ah awesome, close enough thanks :P

dark mural
#

np

ebon basin
#

Looks fine to me

#

Some custom rendering stuff you got going on in the pipeline?

dark mural
#

fresh project with that shader

#

is works with the prebuilt shaders and shader graph shaders though

ebon basin
#

And you're using URP? Maybe try removing the constraint urp tag from it

dark mural
#

I am using urp, and nothing changes if I remove the tag

ebon basin
dark mural
#

I'll try changing the unity version

#

nope

#

I'll just restart my computer

#

maybe I'll just use shader graph but write the entire thing in a custom function node

#

thanks though

#

seems to work after switch to an even newer one

lilac mist
#

What's the right way to set material properties for individual objects? If I apply the same material to 10 objects, but want them to behave differently depending on object properties? (As an example, a material that is more red if the character's HP is low)

regal stag
lilac mist
#

I've heard if you set material properties directly you either make new materials or alter the material for all objects using it

regal stag
# lilac mist What's the right way to set material properties for individual objects? If I app...

From a C# script, if you use GetComponent<Renderer>().material it'll create a clone of the material so .SetColor/SetFloat/SetVector/(etc) methods will only affect that object.
While renderer.sharedMaterial or a serialised reference to the Material asset would indeed affect all objects using that material.

You can also set properties on a MaterialPropertyBlock, passed to the renderer via renderer.SetPropertyBlock. (That's okay for Built-in RP, but would avoid that in URP/HDRP when working with MeshRenderers, as it breaks the SRP batcher compatibility)

lilac mist
#

I'm using a 2d renderer, URP. Does that affect your suggestion about MaterialPropertyBlocks?

#

Basically mostly sprites

#

Also, would using material property blocks even once completely turn off SRP batching, or is it a "The more you use it the worse it gets" type situation?

regal stag
# lilac mist I'm using a 2d renderer, URP. Does that affect your suggestion about MaterialPro...

I don't typically work in 2D so not sure. I don't think sprites use the SRP batcher (yet) so it might be fine to use MPBs there over material instances. But either way it'll still break the dynamic sprite batching (unless the shader also supports GPU instancing). For only 10 or so objects that may not be a big deal anyway.

If you just want to make a character more red, you could use the SpriteRenderer.color field which uses vertex colours so doesn't need separate materials.

regal stag
lilac mist
#

It was just an example. Don't actually want them to be red, but do kind of want to set shader properties based on buffs etc on my units

#

like, intensity of effects

regal stag
#

Another option could be to render effects with an additional transparent sprite over the top of the regular one.

lilac mist
#

I remember I came across a tutorial on grass that moved when the player got close, so I knew there was a way to do it reasonably.

lilac mist
#

Would work for stuff like glow

regal stag
lilac mist
#

So the player can move grass but enemies can not, for example

#

because it's just a vec3 of the player position as a global property?

regal stag
#

Similar sort of idea for leaving trails in snow

dark mural
lilac mist
#

Right, thanks for the info. I'll take a look at render textures and global material properties

quick sonnet
#

I am trying to use a transparent material on my model in unity but you can see the back side throught the front of it? I don't know why

#

It's on the bottom face of the arrow. The face should be hidden from this angle, so I don't know why I am seeing it here. This issue doesn't happen if I have the material as opaque

regal stag
quick sonnet
regal stag
quick sonnet
regal stag
quick sonnet
valid badger
#

Hey there, I purchased a Polygon food pack recently, and I've just tried to import it into a URP project, and the shaders are all broken.
Is there a way to convert them to URP, or do I need to have a non-URP project?

lunar valley
valid badger
#

Edit ^ Actually they're not custom

lunar valley
#

if thats the case you can just use the auto convert button

valid badger
lunar valley
#

yeah

tight phoenix
#

Does anyone have an example of the correct syntax to sample a texture inside of a custom node of shadergraph?

#

I am struggling to find on google the correct variables to pass in and the syntax to then sample it

#

sampler, samplerstate, unitysampler, others

#

Tex2D, texture2D, UnityTexture2D, I'm not finding the correct syntax on google

#
void SampleTex_float (UnityTexture2D _tex, UnitySamplerState ss, float2 UV, out float4 sampledtexture)
{
    sampledtexture = SAMPLE_TEXTURE2D(_tex, ss, UV);
}```
#

Does this look right?

#

yay it worked

tight phoenix
#

trying to convert a shadertoy to hlsl, what is an ichannel and where do I plug the SS?

#

im not sure why there is a random , in the method, im assuming the ichannel is the texture, then the UV, but whats that third value

supple leaf
#

i would like to create a outline shader for a plane without doing fancy depth stuff. just a simple plane with a boarder. i currently have this which is working ok:
but as soon as i change the scale of my plane the outline width changes. does anyone know how to fix that?

tight phoenix
#

The width changes because the UV channel in that direction is getting squished when you scale it. To fix this you'll have to take the object's scale and multiply the UV by that axis in some way

#

I dont know the exact steps to solve it, but that's the problem at least

amber saffron
tight phoenix
#

I'm trying to port a shadertoy glsl to hlsl but not having much luck

amber saffron
#

Creating a vector 2 with X = cos(d), and Y = sin(d)

#

glsl vec2 = hlsl float2

tight phoenix
#

OH its uv + vec2(params)

#

I was having difficult parsing it visually

#

https://www.shadertoy.com/view/Xltfzj

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    float Pi = 6.28318530718; // Pi*2
    
    // GAUSSIAN BLUR SETTINGS {{{
    float Directions = 16.0; // BLUR DIRECTIONS (Default 16.0 - More is better but slower)
    float Quality = 3.0; // BLUR QUALITY (Default 4.0 - More is better but slower)
    float Size = 8.0; // BLUR SIZE (Radius)
    // GAUSSIAN BLUR SETTINGS }}}
   
    vec2 Radius = Size/iResolution.xy;
    
    // Normalized pixel coordinates (from 0 to 1)
    vec2 uv = fragCoord/iResolution.xy;
    // Pixel colour
    vec4 Color = texture(iChannel0, uv);
    
    // Blur calculations
    for( float d=0.0; d<Pi; d+=Pi/Directions)
    {
        for(float i=1.0/Quality; i<=1.0; i+=1.0/Quality)
        {
            Color += texture( iChannel0, uv+vec2(cos(d),sin(d))*Radius*i);        
        }
    }
    
    // Output to screen
    Color /= Quality * Directions - 15.0;
    fragColor =  Color;
}```
The shadertoy

```csharp
void GaussianBlur_float(float Directions, float Quality, float Size, float Radius, UnityTexture2D _tex, UnitySamplerState ss, float2 UV, out float4 outColor)
{
    float Pi = 6.28318530718;
    float4 sampledtexture = SAMPLE_TEXTURE2D(_tex, ss, UV);


    // Guassian Blur
    for (float d = 0.0; d < Pi; d += Pi / Directions)
    {
        for (float i = 1.0 / Quality; i <= 1.0; i += 1.0 / Quality)
        {
            //sampledtexture += SAMPLE_TEXTURE2D(_tex, uv + float2(cos(d), sin(d)) * Radius * i);
            sampledtexture += SAMPLE_TEXTURE2D(_tex, ss, UV + float2(cos(d), sin(d)) * Radius * i);
            //sampledtexture += SAMPLE_TEXTURE2D(_tex, ss, UV);
        }
    }

    sampledtexture /= Quality * Directions - 15.0;
    outColor = sampledtexture;
}```

My port of it
#

Im making mistakes in my port though because the output looks wrong

#

instead of gaussian blur it just looks.. wrong, and im not sure why

#

I assume the problem is I've made mistakes in porting it, but I can't find my mistake πŸ€”

#

vec2 Radius = Size/iResolution.xy;
this line I didnt know what to replace it with because I dont know what iResolution is or what it should be for me

lunar valley
tight phoenix
tight phoenix
#

position is 0,0 at center whereas UVs are 0,0 at the bottom left corner

#

so you'd need to offset it to account for that

supple leaf
#

mh doesnt work. tried both -0.5 and 0.5. both doesnt work

tight phoenix
#

its working but you can't see it off the edges of the sphere most likely

#

i fixed some of my mistakes but im still not getting the expected result from this

#

hm its almost working if I set size to be extremely small, but I dont know why this is the case

supple leaf
amber saffron
tight phoenix
#

the shadertoy has 'iResolution' google says that value was the height/width of the screen itself

amber saffron
#

Look at those two lines from the original code :

    vec2 Radius = Size/iResolution.xy;
    
    vec2 uv = fragCoord/iResolution.xy;
#

First is used to define the blur radius based on the size, second are for UV coordinates

#

And the radius is 2D

tight phoenix
#

my understanding of that is that iResolution is the size of the viewport on shadertoy. So to get UVs they have to take those values and make them a range of 0 to 1, but a UV map already does that for me in Unity
Where am I incorrect?

amber saffron
#

iResolution.xy is the shadertoy rendering resolution => your texture resolution in shadergraph

tight phoenix
#

I critically am not understanding why its my texture resolution

#

I dont want to just go 'okay ill just assign it the texture res' because I dont feel like I am learning why its wrong, and wont be able to fix any future problems because I dont understand the fundamentals

amber saffron
#

Neither is your code posted here : #archived-shaders message
nor your last screenshot shwong where the radius value is comming from, this is probably the error that make it "work" when size is very small

tight phoenix
#

Neither is your code posted here
I am not sure what you mean by this, could you clarify, neither what?

#

the test texture is a crate thats 512 512 so Ill try passing in 512 as the iResolution?

#

not that I understand why at all

amber saffron
amber saffron
amber saffron
amber saffron
#

Yes, than you , I saw the original code, I was talking from your code

tight phoenix
#

it didnt make any sense to me so I failed to translate it properly because I have no comprehension

#

which is why I dont want the answer but the understanding of why and how it works because I lack the comprehension

amber saffron
#

The code you shared seems to have Radius as an argument of the function, but it was not visible as input of the node after, so I don't get it.

tight phoenix
#

here is my untested code as of right now

#

I probably changed something in my attempts to fix it and didnt screenshot the inbetween

amber saffron
#

Also, just for facts, you can also do a cheat blur effect by sampling a lower LOD of the texture.

vapid sapphire
#

Hey, I am new to unity and I need help. I can't really turn off the unity filters off or find where it was. Do you guys have any solution?

amber saffron
vapid sapphire
#

Like this

#

I don't know how to turn it off😭

tight phoenix
vapid sapphire
amber saffron
amber saffron
amber saffron
tight phoenix
#

I crashed unity by giving it a negative number accidentally so currently reimporting

amber saffron
#

Ok, so while it is restarting :
The line float2 adjustedUV = uv / resolution is useless.
in shadertoy, there is no UV input, that's why they do fragCoord / resolution it's the pixel coordinate (+1 per each pixel) / the resolution => the UV

Since you are already passing the correct UV to the function, no need to correct it.

tight phoenix
#

Okay so I understood that shadertoy has no UV, but I misunderstood that the -other- use of iResolution was not related to UVs but to the texture resolution

vapid sapphire
#

I found it in here

amber saffron
tight phoenix
#

@amber saffron its working-ish. Currently the texture is very bright but when you rotate the preview, it flickers to the correct lightness sporatically.
I am guessing the problem has something to do with floats?

#
void GaussianBlur_float(float Directions, float Quality, float Size, float resolution, UnityTexture2D _tex, UnitySamplerState ss, float2 UV, out float4 outColor)
{
    float Pi = 6.28318530718;

    float2 Radius = Size / resolution;
    //float2 adjustedUV = UV / resolution;

     float4 sampledtexture = SAMPLE_TEXTURE2D(_tex, ss, UV);

    // Guassian Blur
    for (float d = 0.0; d < Pi; d += Pi / Directions)
    {
        for (float i = 1.0 / Quality; i <= 1.0; i += 1.0 / Quality)
        {
            //sampledtexture += SAMPLE_TEXTURE2D(_tex, uv + float2(cos(d), sin(d)) * Radius * i);
            sampledtexture += SAMPLE_TEXTURE2D(_tex, ss, UV + float2(cos(d), sin(d)) * Radius * i);
            //sampledtexture += SAMPLE_TEXTURE2D(_tex, ss, UV);
        }
    }
    sampledtexture /= Quality * Directions - 15.0;
    outColor = sampledtexture;
}```
#

Im not sure what that magic - 15 number is or if its related to the problem

amber saffron
#

I think that 15 is a hard coded value that the person forgot.
The idea is just to get the average value for all the pixel samples, so divide Color by the number of samples

tight phoenix
amber saffron
#

If you don't want to calculate them, you could just add a counter πŸ˜„

amber saffron
#

Yep, but it should start at 1, as you have one sample out of the loops

tight phoenix
#

Oh good point

amber saffron
#

and at the end, just /= samples

tight phoenix
#

Hey that worked AND it fixed the flicker problem

#

so it was the magic 15, huzzah

#
void GaussianBlur_float(float Directions, float Quality, float Size, float resolution, UnityTexture2D _tex, UnitySamplerState ss, float2 UV, out float4 outColor)
{
  // directions = 16
  // quality = 3
  // size = 8
  // resolution = input texture resolution
    float samples = 1;
    float Pi = 6.28318530718;

    float2 Radius = Size / resolution;
     float4 sampledtexture = SAMPLE_TEXTURE2D(_tex, ss, UV);

    // Guassian Blur
    for (float d = 0.0; d < Pi; d += Pi / Directions)
    {
        for (float i = 1.0 / Quality; i <= 1.0; i += 1.0 / Quality)
        {
            sampledtexture += SAMPLE_TEXTURE2D(_tex, ss, UV + float2(cos(d), sin(d)) * Radius * i);
            samples++;
        }
    }
    sampledtexture /= samples;
    outColor = sampledtexture;
}```
#

working guassian blur for anyone who wants it

amber saffron
#

Now remove the resolution input and use GetDimensions πŸ™‚

tight phoenix
#

float resolution = _tex.GetDimensions().x; wasnt a thing

#

maybe width or height, ill try that

#

invalid subscript 'width'

amber saffron
tight phoenix
#

oh I dont have a Texture2D though, I have a UnityTexture2D

amber saffron
#

_tex is not a hlsl texture object, but a UnityTexture.
You can get the underlying texture using _tex.t iirc

tight phoenix
#

invalid subscript t, trying to google it

tight phoenix
#

now getdimensions wants parameters, reading that method now

#

it returns nothing?

amber saffron
#

Nope, it has out arguments

tight phoenix
#

oh

amber saffron
#

Just like your custom function πŸ™‚

tight phoenix
#

collosal error

#

I wish I was smarter and could understand how to find the answer without so much handholding sadok

amber saffron
#

You need to provide the 4 required arguments of the syntax

tight phoenix
#

this is beytond anything ive ever done, how will it know which OUT to pull from?

``` is this right? I dont know what miplevel I want, 1? 0?
tight phoenix
#

How do I cast the uint to a float, will that implicitly just work in shader?

#

isually it gets mad like "cannot convert uint to float"

amber saffron
#

You can cast explicitely like this : float width_f = (float) Width;

tight phoenix
#

the out makes Width exist, its being defined in there if I understand correctly?

amber saffron
#

Yes, you are defining it at the same time you are calling the function here, but you can as well define it outside

tight phoenix
#

I still get the error above, no matching 0 parameter instrinisc method

#

even though I'm not passing any zero methods

#

so ive made a mistake for sure

#

this seems like a huge painful run around just to get width

regal stag
#

If you want the dimensions of a UnityTexture2D, can't you use _tex.texelSize.zw?

amber saffron
#

Ah, yes .. true

regal stag
#

Or if you're doing / texelSize.zw, doing * texelSize.xy should be slightly cheaper

tight phoenix
#

@amber saffron sorry for dropping off on replies I had an hour apointment, reading your and cyan's messages now

tight phoenix
tight phoenix
wraith path
#

i have a problem with a 3d masking shader im using, im trying to mask a door that slides up and down and before it was clipping through a wall so i decided to add a mask above it. here's how it looks (LEFT) what it's supposed to look like (RIGHT)

#

so for some reason it just got rid of the texture

#

(this is using a mask shader)

#

and the mask isn't working at all

#

shader code```c
Shader "Custom/Mask"
{

SubShader
{
Tags {"Queue" = "Transparent+1"}

Pass
{
Blend Zero One
}
}

}

#

masking code```c
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MaskObject : MonoBehaviour
{
public GameObject[] ObjMasked;
void Start()
{
for (int i = 0; i < ObjMasked.Length; i++)
{
ObjMasked[i].GetComponent<MeshRenderer>().material.renderQueue = 3002;
}
}

void Update()
{
    Vector3 mouse = Input.mousePosition;
    Ray castPoint = Camera.main.ScreenPointToRay(mouse);
    RaycastHit hit;
    if (Physics.Raycast(castPoint, out hit, Mathf.Infinity))
    {
        transform.position = hit.point;
    }
}

}

gaunt bluff
#

(ping me pls)

karmic hatch
gaunt bluff
#

ye i only got it

#

thx anyway

hearty obsidian
#

when I use fresnel on a 2 sided transparent shader, the entire mesh looks uniformly/heavily affected by the fresnel effect. I think it's the backface causing this. Why? and can I resolve this?

hearty obsidian
#

@regal stag shader graph

regal stag
hearty obsidian
#

Works flawlessly, thank you. Does this mean that whenever rendering backfaces for whatever reason, flipping the normals will always give me the proper normal for the given backface? @regal stag

#

I guess so actually, it'd make sense. Forget I asked

tight phoenix
#

Does anyone have a detailed explination of HDR color intensity math?

#

For example in this picture I am writing those cubes to a 32bit texture and multiplying by 0.2, I would expect the 10 Intensity block to resemble a 2 intensity block but that's clearly not how this math functions πŸ€”

#

so Intensity must be something other than just color+++

regal stag
#

I think HDR colour is rgb * 2^intensity

tight phoenix
#

Oh a power πŸ‘€

tight phoenix
#

the XY goal I am seeking is just better control over the output

#

trying to go from "that looks nice/right" to "I have exact control over all of this"

#

hm, multiplying the output by ANY value seems to completely ignore the higher intensity cubes

#

they all get darker/lighter perfectly identically, expected output would be the far left one would get darker faster than the far right

#

maybe my problem is in the render texture itself

#

Bloom post proccessing gets brighter the higher the intensity is as expected πŸ€”

#

Ill do more googling

#

πŸ€”

tight phoenix
#

float intensity = Mathf.log(factor) / Mathf.log(2);

#

I'm obviously making a mistake because of my lack of comprehension

#

what values should I be logging in? The log function doesnt say what base

#

doesnt clarify it to my comprehension

#

if I dont add that tiny ammount it also blows up completely

tight phoenix
#

How do I debug a shader when I have no idea what of the 1000s of things could be going wrong and all I have is a texture that i cant even eyedrop a value to find out what it is

#

this HDR texture thing isnt working and I have no idea why or how to determine why

karmic hatch
tight phoenix
#

the values in this texture SHOULD be HDR values

#

but my output is not HDR (I think) because it wont behave like other HDR values

#

and I dont know why or how to make it be HDR

#

which of these 600 formats is right, because I googled it and tried the ones who said they encode HDR values, and they dont for me

#

or maybe the problem is the shadergraph, or URP itsself, or literally anything

#

no way to debug because you cant debug shaders

#

if it was encoding correctly, I would expect the value under the glowing cube to be glowing just as brightly

#

because that is bloom on an HDR color

#

so because its not glowing, then there's no way that encoded value is in the HDR range

karmic hatch
#

I'm just guessing here but it might be that the R32G32B32 colours are still normalized (0-1), and that the texture itself is saved in a way that clamps all the values

tight phoenix
#

IF that even is the case?

karmic hatch
#

I would guess the way to do it is to use some higher-precision texture format but have all the colors divided by e.g. 1024 or something, then you multiply by 1024 in the shader but again just guessing

tight phoenix
#

NOW its glowing when I set it to this but it definitely wasnt before

karmic hatch
#

in the actual image i mean

#

oh nice

tight phoenix
#

I was multiplying it by 0.2, that last cube is Inensity 10

#

but the output wasnt intensity 2

#

instead it was 0.2, as if clipped to 1 before mult

#

Like why

#

as I multiply it, the expected is the far left one would get darker first, and the glowing one last

#

but that is not at all what I am getting

#

its 100% being clamped somewhere somehow but how do I stop that

#
#

this persons sollution doesnt work

#

anything wrong in here?

#

how do I get a reference to a render texture to run this method on it?

#

its not a thing I can assign to

#

I am so stuck and so lost

#

why does it feel like everything I try to ever do something no one has ever done before ever

#

can't find a droplet of answers on google

#

my head is so deep in the forest I can no longer see any trees, putting this to rest for tonight

#

if the render texture / shader / camera / anything was displaying an HDR value, that purple would be glowing like the purple on the left

#

its not glowing so its clearly not HDR

#

its picking up the HD glow values but its clamping them to 0-1

#

and I dont know how to stop that πŸ€”

#

maybe the problem isnt the texture but the sampling of it

regal stag
# tight phoenix

If there's post processing enabled on this camera, the resulting texture could have tonemapping or something applied, which would convert the HDR values to SDR

tight phoenix
#

I was sampling it with sampletexture2D

#

now im trying to sample it some other was in case that was clamping it

#

except im getting the error no matching 3 parameter function

#

even though its right there and its 3 parameter

#

and that exact syntax worked in other shaders

regal stag
#

Hmm, I think SAMPLE_TEXTURE2D should be fine

tight phoenix
#

so once again Im doing something wrong and dont know what

#

im getting too worked up to solve effectively because I desperately want this to be overwith solved

#

I know I used lesser methods in shaders in other projects, ill open one and search the codebase

tight phoenix
#

I need to replace sample texture 2D with DecodeHDR

#

but I dont know how

#

its what I must do but I cant find the answer on how to do it

#

nothing makes any sense

#

just going to give up and close up

manic frost
#

Hey, I'm trying to make a simple vertex rotation shader, but my mesh is also skinned to a parent bone. When I use a position node as my input on the rotate about axis node, it's taking the position of the bone the mesh is skinned to, not the mesh itself. Is there a way to change the position pivot to local to the mesh/object, not the bone it's skinned to?

floral barn
#

i made a shader that simulate the heat distortion

#

and i wanna use it for other reasons, so how can i make it on the screen like a canva

#

the shader is applied to a quad

misty cargo
#

What is Unity calling PBR Graph Shadder now?

lunar valley
#

not in built in I think you will need to write your own

ebon basin
#

If you go through the shader graph docs, or by right clicking on the nodes you can grab the generated code unity puts into them

lunar valley
fresh leaf
#

Hey, how should I go about making an animated shader graph that flickers the emission like a candle?

*I know that the below screenshot is completely wrong I was just testing stuff out

frosty linden
#

Hello, I read some time ago that branch nodes should be avoided since they are not that optimized? Could someone give me more details please?

lunar valley
meager pelican
# frosty linden Hello, I read some time ago that branch nodes should be avoided since they are n...

It's a bit of a large discussion.
It's not that bad if you're branching based on a uniform value (one passed in that is constant for all pixels in the frame for that shader).
The problem comes when you have a situation where the condition is different for different pixels in the same work group. Remember that GPUs are massively multi-threaded...so you could have 64, 128, etc. threads in a group running IN PARALLEL at once...all sharing the same instruction/program counter.

So what happens is that if thread 32 has to take the top part of an "if" condition, and thread 33 has to take the "else" part of the condition, ALL 128 THREADS have to "march" through BOTH sides of the conditional. So you incur the performance penalty of executing BOTH sides of the condition and you don't save anything.

This isn't too bad if your condition is something like "if (foo) then blue else red". Two small statements...meh. Unless you're real tight on your rendering budget it probably won't matter much. And using a ternary operator IS a conditional, just like an "if".

Sometimes you can get around it with math, but often "jr." programmers end up using a conditional in the math to get to a 0 or 1 value to multiply by!

All you can really do is try things and benchmark your specific set of conditions. Big flags should go off in your head if you have a conditional where (A) it isn't a uniform value and (B) you have a big block of code for the "true" side and another big block of code for the "false" side. Or really any big block of code that isn't based on a uniform....know that you'll likely get the performance cost of ALL the code.

But if ALL threads can skip a chunk of code, they should.
There's also dangers of disabling some optimizations if certain code is embedded in a conditional, like I think some texture reads that are dependent on something, particularly bad are texture reads dependent on other prior texture reads (DTR).

frosty linden
#

I see. So as long as both sides are quite small, it shouldn't matter too much then? I'm trying to optimize my game and use channel packing technique where albedo (grayscaled), bump and alpha are all merged into the same image, 3 different channels, and I might pack another image. Sometimes, I might not need an alpha channel, so I can pack 2 albedos and 2 bumps in the same images. Meaning alpha might not always be in the image alpha layer. And I'd like my shader to be flexible: All textures will have an albedo, but might not have an alpha or bump. And sometimes, the bump or alpha might come from another image too. So I was thinking of having 3 texture inputs for my shader and use branching to determine if alpha and bump have been filled. By using a Vector4 mask on the RGBA then getting the max value out of the mask, I get a single float which would be grayscale value of albedo, alpha or bump. My issue is how to determine which input will give me the bump and alpha. Could be coming from the main albedo texture or from another texture. That's where I was thinking of using branching.

#

But I'm thinking maybe it would be easier to simply feed the same texture to both inputs? Though it would be sampled twice for nothing? Is sampling an image a heavy operation if it's the same image ?

meager pelican
#

GPU's are built for sampling but it isn't free. They are time offset. When a sample is pending, the thread is assigned other work and it comes back to it later, kind of.

#

But

#

What you MAY want is shader variants. Depends on your use case.

#

How many variations you have on a theme. For each binary-thing..."has ALPHA" or not...you get a variant.
So if you have one keyword for "HAS_ALPHA" and another for "HAS_BUMP" you'd end up with 4 variants...2 squared.
00, 01, 10, and 11 in a truth table. Each time you add a variant keyword, you double the number you had before. This also incurs a penalty for the executable code size and memory footprint as each shader variant is just that...another copy of the shader.

But things not used are compiled out...saving execution time.

frosty linden
#

Ok. I thought about it too but I was worried about the number of variants it adds. I know Unity strips them on build but it already builds so many shader variants i'd rather not add more if I can avoid it.

#

I'm thinking I might simply add 3 masks (albedo_albedo, albedo_bump, albedo_alpha), on the main albedo, 1 mask on the bump (bump_bump) and one mask on the alpha (alpha_alpha) inputs. This way, if I have the bump texture on the main albedo green channel, I could set albedo_bump to 0,1,0,0 and the bump_bump to 0,0,0,0 then get the max out of each float?

#

I still use sampler nodes for bump and alpha but I'm guessing if I don't fill the texture slot and leave a black color input, than no sampling occur in GPU?

#

And I would avoid using branches or variants.

#

Would this solution be more efficient than branching or variants? I have no clue

#

I do have 5 Vector4 masks information to fill each time but that might give me the flexibility I want while keeping the shader optimized?

meager pelican
#

Make a test project, and some different shaders, and test it out in isolation. Benchmark, basically.
GTG, good luck, maybe others will have more input.

fathom cypress
#

Im trying to make my own shadergraph so the player can customize their color, with an option for gradients in different directions. Currently it does make a gradient if the user chooses updown, leftright, or frontback but it also lerps the red, green, and blue value. I understood why it does this, but I dont know what to do.
How can I get this so the player can choose red/green, and then LeftRight, UpDown, or FrontBack so the red to green gradient happens in that direction?

#

theres more to the graph thats unrelated, but this output goes straight to Base color and alpha

regal stag
fathom cypress
#

I was considering allowing multiple at once if it just worked, but ill try that rn ty

regal stag
#

Might also want to add an option to offset/remap the value & Saturate before connecting to the lerp too

fathom cypress
#

I will attempt to understand what that means, im just a dev who cant afford an artist :p

regal stag
#

And adding an Inverse Lerp or Remap (from MinMax property to 0,1) would let you choose where the gradient should start and end across the mesh
Saturate will clamp the values between 0 and 1, as currently the position can be negative or higher than 1 and the lerp will continue to extrapolate the colours, might be a bit odd.

fathom cypress
fathom cypress
regal stag
fathom cypress
#

ah yea thats what i thought

#

thanks a lot! ive been stuck on this for the day lol

frosty linden
#

I'm having an issue with the normal from height node in shader graph

#

I get a lot of flickering over the face

#

If I use a normal map texture, I don't get this flickering

#

What could cause this flickering?

#

I can't figure out what's the problem. It's as simple bump map with a simple normal from height node.

polar relic
#

I have an old 3D vertex-painted mesh whose color data are in UVW.
Is there any way to get that W in Unity? Look like it's stripping that value no matter what and only keep UV.

vocal narwhal
polar relic
#

With custom in-house tools from the PSX era (Spyro the Dragon's skyboxes, to be precise).

#

The .obj must contain that W since I have a viewer tool who does display them correctly.

vocal narwhal
#

well, you're going to have to re-author it externally so it's normal afaik. Unity's mesh representation does not have a W coordinate, and I doubt it's interpreted by the OBJ importer. I see that the w coordinate is for nurbs geometry, which is not supported.

polar relic
#

Crap. Well, time to see if Blender can save the day then.
Thanks for the answer.

floral barn
#

can i use a shader on ui ?

buoyant oriole
#

Does anyone know why this shader would be invisible? Using URP
Thanks πŸ™‚

lunar valley
buoyant oriole
#

ill have a look into it
thanks for the help πŸ™‚

karmic hatch
#

when sampling the texture, try multiplying by some very small number and seeing if that improves things

buoyant oriole
#

also of note: the shader works in the material preview

regal stag
#

Might also be easier to use Shader Graph

buoyant oriole
#

i have been considering shader graph but I want to try out writing shader code as generating noise in the shader graph might be a bit difficult
but thanks for the help πŸ™‚

#

also gotta say your site is very useful ive used it for a fair while now

regal stag
buoyant oriole
#

true that

buoyant oriole
flint zephyr
#

Is anyone familar with .shaders in SRP and URP? I am trying to convert this .shader to work in URP that was original made for SRP.

If anyone thinks they can help, feel free to make a thread on this message πŸ™‚

tight phoenix
#

How can I make a render texture an HDR texture? How can I debug where in the following flow that the HDR values get stripped out?

URP 2022.2.17f1
I have a cube with a high intensity HDR color value material on it. This value is HDR.
I have a camera pointing at it that outputs to a render texture. The color format is RGB32SFLOAT so it supports the HDR range of values
I have a plane that displays the render texture.
I have a global post processing volume with bloom.

The problem is somewhere along that line the color values get clamped to 0-1, the plane doesn't bloom glow and all that extra data is stripped out. Is there some way I can force or bypass the problem to be sure 100% the HDR values are getting encoded?

tight phoenix
#

here is a version I faked that I am not happy with - this was done by lowering all the colors into non-HDR value ranges then multiplied back up again

#

while this 'works', its very not WYSWIG and just adds an extra layer of spahgetti to break making controlling the desired output look that much harder

frosty linden
# frosty linden It's more visible in this one

Would anybody have some insights regarding this issue? A bump map with a normal from height node flickers like crazy for unknown reasons. Using a real normal map without the node doesn't have this issue

tight phoenix
#

vs all the same length because the HDR isnt being encoded while WYSWIG correct HDR material colors

grand jolt
#

guys, im working on the sprite of capsule, I want to make it have two colors, one on the outside and one on the inside, how do I do that?

#

the way i am thinking about it, it should be copying the UV and scaling it, (that's the step that i can't do the rest is easy)

low lichen
tight phoenix
karmic hatch
tight phoenix
tight phoenix
#

How do you write a sampler yourself in the shader? I googled and couldnt find, and GPT doesn't know what it's talking about when I ask it

#

I am thinking my problem is the normal sampling method is returning SRGB and I am trying to return its true linear values

#

so I am trying to write acustom function node that will use a Texture2D<float4> and sample that to get the real values

#

this is xy - how do I sample a unitytexture2D and get its linear values without converting to SRGB? for this specific texture, not the entire project

#

The texture is not a texture, its a Render Texture, so I can't simply 'set it to linear' or do anything related to texture import settings

regal stag
#

I'm also not convinced that tex.Sample is the problem

tight phoenix
#

Neither am I but I am just exploring every possible thing I can explore, because I am completely utterly blind with no means to determine what's wrong, I just have to keep trying every possible thing until I stumble into the answer

#

Someone mentioned a RenderDoc thing Ill look at that again

regal stag
#

Is post processing still enabled on the camera rendering to the render texture?

regal stag
#

Disable it, you don't want it enabled

tight phoenix
#

jfc πŸ‘€

#

unchecking post proccess fixed it

#

the HDR values are sustained

#

I have no words but gratitude

regal stag
#

The post processing likely includes tonemapping which is what is converting the HDR->SDR. You typically want that for the final image, but not for intermediate render textures

humble robin
#

How can i get multiple fragment shader outputs using blit in a renderer feature pass? My frag shader outputs a color and a depth map and i need to use both of them in another pass. But blit only has 1 target to copy to.

tight phoenix
#

@regal stag Thank you endlessly from the bottom of my heart, it's been about a week of chasing ghosts trying to figure out where my HDR values were being eaten and likely wouldn't have figured this out on my own.

#

now I can resume actually working on the thing that I needed to make use of the HDR values in the first place πŸ‘€

regal stag
humble robin
regal stag
# frosty linden Would anybody have some insights regarding this issue? A bump map with a normal ...

Normal From Height node uses screen space derivatives (the difference between neighbouring pixels). It's only an approximation and doesn't work that well in all cases. Sometimes lowering the strength of the noise based on distance from the camera can help.
But as you've found out, an actual normal map is usually better and can have mipmaps to automatically look better when viewed from a distance.

tight phoenix
#

hype that this is finally working and working the exact way I pictured it would πŸ‘€

#

HDR intensity values being used to write temporal positional data for further shader effects

ebon basin
#

neato

misty cargo
misty crown
#

Hi there,
Would anyone know why the same material / shader could like entirely different in two seperate unity projects, if they are both using the same shadergraph shader and referencing the same exact textures for the surface inputs. Here are the two different outputs. Maybe there is something in settings I don't have enabled? Would appricaite any help here. thank you!

misty crown
# misty crown Hi there, Would anyone know why the same material / shader could like entirely ...

~~Here's a better image - looking to replicate the one on the left, settings and shader is the same, but it has a lot more more shine and brightness--Additionally, The shader with out any surface inputs looks like the same. Thank you!

Update: Looks like biggest difference occcurs when adding rim color - its almost like the rim color is much brighter in one of them even though they are using same shader, and inputs, how could that be~~

Ok i figured it out, both projects were using different color spaces, one linear, one gamma.

Thank you

rancid wharf
#

could anyone pls help me understand why the result there isnt blue borders?

#

as far as i understand, black is 0, and so since the top image has black borders to the circles, and the bottom one only has those borders colors, adding should just make the borders blue no?

regal stag
rancid wharf
#

ooo i just assumed the substract defaults to 0 if it goes under

#

works now, thanks a lot

pale python
#

Hi,
im working on HLSL shader, and I wanted to make Blend mode dynamic but I realized I cant use (If-else) statements under SubShader>pass and also cant use Toggle switches , how do I make blend mode dynamic ?

pale python
low lichen
frosty linden
#

Hello, I'm a bit confused by the HDRP cotton/wool shader. Aren't normals supposed to be using 3 channels? How come it only uses 2 channels in this shader?

vocal narwhal
# frosty linden Hello, I'm a bit confused by the HDRP cotton/wool shader. Aren't normals suppose...

Normal maps contain XY directional lighting information, picture it as a 2D vector that describes how the surface faces, (0.5, 0.5) being straight up, (1, 0.5) being to the right, etc. The third channel can be blank/grey.
It depends on the format though, it's just something you can compress down to, typically the third channel is just so you can get a normalised vector without doing extra maths.

frosty linden
#

OK, thanks. I also noticed there is a shader graph node to reconstruct the Z axis from X and Y. Might be the solution to pack my textures while keeping the normal map quality. A converted height map really can't fill the role properly. I'll test it. Thanks again.

frosty linden
#

I'm having some issue with the normal reconstruct z node in shader graph

#

I've packed my normal into the G and B channels of my textures and I'm trying to generate a normal map from those two channels.

#

From my understanding, I first need to combine those 2 channels into a new one using R and G, then feed that to the z reconstruct then I should have a normal map which strength I can control through a float. But at the moment, it only makes the normal map whiter instead of increasing strength

#

What am I missing?

fathom cypress
#

I realized that my gradient shader for the player really messes up when the player bends over. the players head will change colors (because of the drastic change in position)
my character is a ragdoll, so it can bend a lot. Is there any way I can still have a gradient in any direction, but maybe not using the position? Or maybe by having it calculated off position and never changed after?

frosty linden
# frosty linden What am I missing?

Looking into it more, it appears to be a colorspace issue. My packed image is sRGB (Gamma) but normal maps are supposed to be RGB (linear). My texture are loaded dynamically from the streamingassets folder so I can't use the default unity textureimporter checkbox

#

I can't figure out how to convert from linear to gamma in my shader.

#

I read you're simply supposed to raise the color by power of 2.2 to transform from gamma to linear but after adding a power node after my combine, it's still not working.

frosty linden
#

So to answer my own question, since I was creating texture at runtime, the texture class has a linear parameter when creating the texture to choose linear colorspace...

#

BUT! I was loading my textures using UnityWebRequestTexture.GetTexture which offers no options for linear... Luckily, the Unity documentation gave the answer. Need to use ImageConversion.LoadImage(tex, tex.GetRawTextureData()); to convert from gamma to linear after loading

#

Now my normal map works fine. 4 hours spent just to figure this out... I love coding lol

grand jolt
#

guys how do I change the intensity of an HDR color if that color is a property in the shader graph from script

dim yoke
# rancid wharf ooo i just assumed the substract defaults to 0 if it goes under

Usually things doesnt happen by itself. It would be really really odd if subtraction was clamped to always give positive results, it would result in lot of confusion as thats not how math works and it would even make some things impossible/really tricky to implement because usually negatives are really useful on calculations

karmic hatch
fathom cypress
#

I thought UV was something for like world position

karmic hatch
#

UVs are attached to your mesh, they basically tell the shader what part of the mesh it's looking at.

#

There might be some way to get what the position was before it's deformed by whatever ragdoll action but UVs would serve that purpose well

fathom cypress
#

hm ill try to experiment with it, although when i tried just replacing position with UV, it didnt really work

karmic hatch
#

You need to have UVs set up on your mesh

#

The UVs basically tell you how to transform from a point on your mesh to a point on a 2D texture

fathom cypress
#

i believe my character mesh doesnt have that at the moment, not entirely sure. I was told its just a bunch of vertices. I tried even getting the UV mapping in blender (had no clue what i was doing) and the option was greyed out

#

Maybe ill come back to this then when I get a different model, because this model has some weird Plane thing that i really dont like as well

#

Yea i plugged in UV to base color and i see this, so imma assume the character doesnt have it.
Thanks anyways! ill be sure to use your advice when i come back to this

leaden mist
#

I am trying to draw a line from ray values, so all I have is a starting point and a normalized direction. this is my line code:

float Line(float2 p, float2 a, float2 b)
{
    float2 pa = p - a, ba = b - a;
    float h = saturate(dot(pa, ba) / dot(ba, ba));
    float2 d = pa - ba * h;
    return dot(d, d);
}

p is the current pixel, a is the starting point, b is the end point. so to make this show the ray I do this float RayLine = Line(id, ray.position, ray.direction*200.0) but I get the attached image. I used shader doc to find what the float2 was for direction and it's been normalized it seems, (I'm passing the float2 in just as (200,200) at the moment for debug sake). so I don't know what's going on there but if I swap ray.direction*200.0 to float2(200,200) it works normally.
Here is how I'm passing in the variables in a c# script:

shader.SetVector("RayDir", RayDir);```
I could try passing the rays in as a buffer but I don't know if that would help
frosty linden
#

Quick question regarding how shader graph casts types. If I have a float with value 0.3f and I connect it to a Vector4 input node, the generated Vector4 will be [0.3f, 0.3f, 0.3f, 0.3f], correct?

regal stag
frosty linden
#

Thanks!

plain sinew
#

I'm attempting to create an underwater game which needs fog that blends in with the skybox but Unity's fog only allows for a single colour. How can I go about this?

brazen furnace
#

Hi. I am using the Lit Shader graph, and every time I make a change, it turns the main preview into cyan. But if I just change the base color on the master node to whatever, even one % difference, it autoupdates correctly. So a sort of visual bug. Anyone who knows why?

brazen furnace
#

Resizing the unity window also seems to "fix it"... but now I realized the shader only works in preview but not in the scene at all.. what the

regal stag
brazen furnace
#

Thank you, that was it. facepalm

#

How do I remove the bottom right shine from the light? I tried removing smoothness, tried different shaders, nothing seems to work+

#

Apparently it was the transparent shader I have on top, that is like this. But still I removed the smoothness and all, so why is it reflecting light?

grizzled bolt
#

Though it looks like the part that's reflecting is not your shader, but the surface that's behind it

brazen furnace
#

I see thanks. Last question. How do I invert this effect? Like an inverse fresnel. So the black part is on the edges, and the yellow in middle and orange between. I tried doing one minus, invert colors etc but nothing really works?

grizzled bolt
#

Unless you've got negative values or the color gradient is severly weighted towards one end of the 0-1 range

brazen furnace
#

as you can see it turns blue with one minus, but what negative values do you mean?

grizzled bolt
brazen furnace
#

ahaa

#

sorry I thought the last thing was also considered fresnel, will try now!

grizzled bolt
brazen furnace
#

Here is the full stack with the minus

grizzled bolt
#

It doesn't look like those nodes have any effect on alpha transparency

brazen furnace
grizzled bolt
brazen furnace
#

I randomly clicked some nodes and actually kinda got the effect I wanted, by chance xD so it is resolved, but thanks for the input, I learned a lot

worn harbor
#

Hey, can someone please help me ?
i'm trying to make a water shadergraph in unity. It's almost done, the last thing missing is a black outline arround the foam in the water (because since it's an unlit shader, my postprocess outline doesn't work on the foam). I was thinking i could just duplicate the way the foam is done, but scale it up a bit and change the color to black, so that it does a black outline, but i don't know how to scale up and i don't even know if it's a good idea. (PS: i'm a newbie)

tropic badger
#

- Can i configure transparency in a way that two sequential objects do not affect each other, i.e. two transparent objects don't blend?

regal stag
regal stag
tropic badger
worn harbor
regal stag
#

Would also be a much smaller value than 0.5, something like 0.02 probably, depends how thick you want the outline

worn harbor
#

ooohhhh

#

thank you so much πŸ₯Ή

worn harbor
humble robin
#

is using material.SetTexture() inside of a renderer feature pass execute function fine?

#
            outlineMaterial.SetTexture("_DepthTex", depthRenderTexture);
            outlineMaterial.SetTexture("_MainTex", colorRenderTexture);
            commandBuffer.Blit(null, source, outlineMaterial);

this seems to give blackscreen so i thought the source being null also sets _MainTex property to null so i changed it to

            outlineMaterial.SetTexture("_DepthTex", depthRenderTexture);
            commandBuffer.Blit(colorRenderTexture, source, outlineMaterial);

this solved the blackscreen, however the depth texture seems to be 1 frame late, my guess is that it sets it 1 frame later or something somehow (im not sure) is this approach fine, what is the correct approach?

coarse gate
#

why does shader code that works in 3D core not work in URP 3D

misty cargo
#

Shouldn't part of this texture use the grass texture?

regal stag
regal stag
misty cargo
#

I'm following this video and its using absolute position at the 4:50 mark:
https://www.youtube.com/watch?v=eZqd68YaY2U&t=89s

In this video, we'll take a look at how you can simulate a triplanar effect in the Universal Render Pipeline using Shader Graph.

Get the Boat Attack Demo here!
https://on.unity.com/3fIw3QV

Learn more about Universal Render Pipeline here!
https://on.unity.com/38WY7NH

Get more information on Shader Graph here!
https://on.unity.com/3fwXyg7

β–Ά Play video
coarse gate
#

oh thanks

regal stag
misty cargo
regal stag
# humble robin is using material.SetTexture() inside of a renderer feature pass execute functio...

Kinda depends. material.SetTexture will occur instantly, but the blit doesn't, all these commands are queued up and executed later by URP.
If there's only one camera that the feature is running on, then it should be fine. But multiple cameras might interfere with each other. It's usually better to use CommandBuffer.SetGlobalTexture to set a global texture property instead, as that will be queued up to happen right before the blit.

As for why the depth texture may be a frame late, might be related to when the feature/pass is occurring (set by renderPassEvent, usually in the feature's Create method). Maybe check Frame Debugger too.

dusty creek
#

I'm thinking of a shader that I want to make that changes the texture along the arm, starting from the hand. to control it I'm just gonna use an exposed float between 0 and 1 and have it linked to an animation curve in a script. but how do I target a specific part of a mesh in shadergraph?

regal stag
dusty creek
#

sorry didn't see the ping, how do you do that?
the idea btw is to limit this shader to only the arm
https://www.youtube.com/watch?v=jLUGRGdji2o

Unity Shader Graph - Galaxy Effect Shader Tutorial

The Galaxy Shader can be used in different objects, it’s even used in skins for champions, weapons or even potions, why not? And accompanied with a few particle systems it can look pretty interesting, specially with a simple Plexus effect going on.

Enjoy!

------------------------------------...

β–Ά Play video
pale python
pale python
#

the whole point of the question is how i just use any conditional statement under pass because it raises errors
if i use it before CGPROGRAM it gives an error and after it also raises an error : unexpected token 'if'

#

if im not wrong , blend mode should be defined before CGPROGRAM , how could I make a toggle or if statement before CGPROGRAM ???? anyone ???

dusty creek
pale python
#

is there is maybe another way to use blend that doesnt need to be before CGPROGRAM ??

regal stag
# pale python sorry for late response , but yes I have done this to many things but it just do...

You misunderstand what MentallyStable is referring to. There's an example at the bottom of the docs page they mentioned, but here's an example specifically for Blend :

// under Properties
[Enum(UnityEngine.Rendering.BlendMode)] _BlendSrc ("Blend Src Factor", Float) = 1 // "One"
[Enum(UnityEngine.Rendering.BlendMode)] _BlendDst ("Blend Dst Factor", Float) = 0 // "Zero"

// under Pass
Blend [_BlendSrc] [_BlendDst]

This will expose dropdowns, allowing you to set the blend mode factors from the material.
I've got more examples listed here : https://www.cyanilux.com/faq/#shaderlab-operation-properties

regal stag
# dusty creek ok I thought I knew what to do but I doubt it's correct. I was going to create a...

I mean, that might work but if the circle gets too large it might overlap with nearby UV islands from other parts of the model. It really depends how the model is unwrapped. You can also have multiple UV maps if necessary.

The way I'd probably handle it is have a second UV map, unwrap the arm with Blender's "Project from View", rotate the UV island so it's perfectly horizontal. In the shader the UV1.x would then be a value from 0-1 along the arm so you can use that in calculations to mask and animate effects on it.

dusty creek
#

you can make multiple UV maps for a model?

#

or would I have to seperate the arm from the rest?

regal stag
#

Yes a model can have multiple UV maps

dusty creek
#

how do I know which UV map I am using with the material?

slender wren
#

Does anyone know how to use textures in HLSL when using a custom function from shadergraph?

regal stag
dusty creek
regal stag
dusty creek
#

in what case would it matter? just thinking about the future. going to spend my summer holiday learning more about shaders and vfx so

regal stag
regal stag
dusty creek
#

is there a way to unwrap it in a way that it wouldn't do that?

#

but still work for this arm shader ofcourse

regal stag
#

Probably. I'm not an expert in UV unwrapping πŸ˜…

dusty creek
#

I'll give it a shot. thanks a lot for the help UnityChanThumbsUp

slender wren
#

Can I assign it to a float?

regal stag
slender wren
#

it's giving me this error

#

this is the line that I changed

#

what the

#

wtf

#

nevermind

#

it works now

#

tho thanks to you

misty cargo
#

I wasn't really expecting the resulting preview to be black. Does any have any idea here?

misty cargo
regal stag
slender wren
#

like the node

slender birch
#

1 - value

#

lol

slender wren
#

I tried that but at the time of doing it the result was kinda wrong

#

so I wondered if I got it right

slender birch
#

the problem must be somewhere else

slender birch
#

is your value clamped between 0 and 1? or how hlsl calls it "saturated"?

slender wren
#

I am trying to use oneminus on the scene depth

#

I want to one minus

#

this

#

since I am using a function instead of raw code for this shader I am making

#

this basically

regal stag
# slender wren I want to one minus

This macro likely gives the same as the "raw" mode on the SceneDepth node. You'd need to put the result through the Linear01Depth function.
Specifically, float linearDepth = Linear01Depth(rawDepth, _ZBufferParams);

slender birch
#

when in doubt

#

return it as a color

#

or return frac(value) as a color

slender wren
#

alright

#

thank you

misty cargo
#

Any one have any idea why the preview here is black? Could this be correct...

pale python
pale python
#

hey,
in the old versions Blend Off turns off the blending effect, but in the newer versions, it's not an option
how could we turn off blend ?

low lichen
deft frost
#

I'm trying to do a dissolve effect in Unity, but when I use grab pass to display the dissolved part, it interferes with postprocessing. [I'm using ShaderLab, not Shadergraph, and I'm in Built-In]

vocal narwhal
deft frost
#

Clipping just shows the pass I'm using from my main shader.

#

IE: The undissolved portion

vocal narwhal
#

Why would it do that...

#

Alpha clipping would clip it so there's nothing rendered, like it wasn't there

deft frost
#

I think how it's set up is that it uses the pass from my main shader first, and then it applies the dissolve effect.

vocal narwhal
#

This just seems like a bad way to set this up. The problem is likely that that portion is rendering to depth still, and you won't be able to fix that using this setup

deft frost
#

Mind if I send you my shader code via DMs?

vocal narwhal
#

Just post it here so other people can help. I don't really have more to add

deft frost
deft frost
#

Man... if only there was a way to inherit functions from other shaders...

ebon basin
#

Copy paste :)

#

I've recently been editing and stuffing a lot of Unity's helper functions into my utility script

dusk sky
ebon basin
#

Is your project URP?

dusk sky
#

yes

#

and I used the URP template project so there should not be errors on configuration.

dusk sky
#

The problem that has been bothering me for half an afternoon has finally been solved!!!!!! thank you very much!!!!!

haughty siren
#

i'm drawing a quad with unity's GL library using a shader that has these lines of codes in it, as far as i understand this code makes it so that frags never pass the stencil test and therefore don't get rendered, however my quad is still visible.
i tried copying the whole code onto a new shader and assigning that to a 3d cube instead of a GL quad and it works as it should. idk what to do??

#

the only difference between those 2 objects is that the quad i render onto a different rendertexture, but that rendertexture has all the default values in it the only thing i change is height and width

deft frost
# ebon basin Copy paste :)

That's so lame. What if you update the source shader, but want those changes to automatically apply to the other variants without copy pasting?

vocal narwhal
#

If you've seen .cginc files, that's a include file

deft frost
#

So if I put all the original shader code into a function, and use the #include tag to reference it, I can discard the "UsePass" command entirely?

vocal narwhal
#

I don't know the exact restrictions of what you can and can't put in include files, I just use them for common functions and structures. I think you can put anything in there though and it'll just be as if it was shoved inline in the shader that included it

ebon basin
#

Problem with some unity libraries is that their functions sometimes have some global properties which you may not have included in your shader, and some seem to templated to the point where you're better off making your own and editing its functions.

#

Mostly a problem I've encountered using the sprite renderer because in URP it still requires the property to be passed as _MainTex and not _BaseMap

#

Unless there's something I'm not aware of, because the majority of these new functions dont bold well with it lol

deft frost
#

Oh man. Vertx. I think you're a genius. I think the #include system in Unity might just save my bacon.

humble robin
#

my compiler(visual studio) doesn't autocomplete or show errors in shader code. Does it just not exist or is there a way?

frosty linden
#

Hi everybody, working on a shader and packing my textures in channels and I was wondering what was the best image format to pack images ? Currently I use jpg when I have only 3 channels packed and PNG when 4. Usually, textures are 4K and JPG seems to handle that quite well with max 5Mo in size but PNG are reaching 20Mo+ each. When unpacked in GPU with mip maps on, the image is about 21Mo so I'm surprised the PNG format can't shrink its size more.

#

Is there a better image format for such case? I'd like to reduce the game download size as much as possible since I'll be updating regularily

#

I just tried tga and tiff and it ended up bigger than png

#

So the best image format for packed images is png I assume ?

grizzled bolt
#

When the project is built they get converted to internal formats anyway

meager pelican
frosty linden
frosty linden
meager pelican
#

The thing with jpg is that it's a lossy compression method. So you're screwing up your texture data at the input/source side.

frosty linden
#

Oh, I was forgot about this detail. Got it, thanks for the reminder.

brazen furnace
#

What is this error? I followed a youtube tut but I get an error for some reason

regal stag
brazen furnace
#

Thank you xD, had no idea they had to match

tropic badger
#

- I have a single object with sprite and trail renderers, both use exactly the same material and so shader. Rn the trail appears on top which i want to change, but all solutions on the internet tell me to duplicate the material and change the render queue for one of them. It's not an option for me since that material is modified at runtime and this change has to be reflected on both renderers. Order layers also seem not to work. Here's configuration of the shader

Tags
{
    "RenderType"="Transparent"
    "Queue"="Transparent"
    "PreviewType"="Plane"
}

Cull Off
Lighting Off
ZWrite Off
Blend SrcAlpha OneMinusSrcAlpha

Stencil
{
    Comp Equal
    Pass IncrSat
}
regal stag
tropic badger
#

- I definitely can do that, but that would require quite a bit of rewriting. Is there any other alternative?

regal stag
humble robin
#

I have a simple light that i got from creating a mesh and doing calculations in frag, how can i get rendertextures of each light object in the scene? I need to have an array/list of light textures so i can use them for shading. How is this usually done?

#

cmd.DrawRenderer did the trick

tropic badger
cosmic prairie
placid vortex
#

having some math difficulties here, setting up a heightmap-blended vertex paint shader and wanted to do it additively
the three nodes at the top all add to 1 unless the original vertex color had a hsv value below 1

the end goal is for each channel to still end up like the combined node on the right when added together, but the values for each would be shifted around based on the heightmaps (left)

lunar valley
tropic badger
#

- Can i configure shader to exclude/include some code based on a parameter? If so, does it impact performance? And if so, should i make different shaders for different configurations?

regal stag
regal stag
cosmic prairie
placid vortex
#

i did it with lerping two channels fine but had issues expanding it out to three, so i wanted to do it additively to also allow a texture on the bottom

brazen furnace
#

Uhm so I am wondering something extremely basic here, I have a material that has a texture, and I want to use a shader to kinda do some glow on/around the texture, but I forgot how to do that.

So what I did was set the shader in the material Shader dropdown menu, but then the original material disappears completely, so I am wondering how to kinda blend the original material texture and look, with the shader thing? Like having the shader set at 50% opacity or smth

But I dont wanna use sample texture 2d because I wanna be able to apply this shader to several materials without having to specify the already existing textures ya know?

humble robin
#
Shader "Custom/AdditiveBlendShader"
{
    Properties
    {
        _MainTex("Main Texture", 2D) = "white" {}
        //_BlendTex("Blend Texture", 2D) = "white" {}
    }

        SubShader
    {
        Tags { "RenderType" = "Opaque" }
        LOD 200

        CGPROGRAM
        #pragma surface surf Lambert

        sampler2D _MainTex;
        sampler2D _BlendTex;

        struct Input
        {
            float2 uv_MainTex;
            float2 uv_BlendTex;
        };

        void surf(Input IN, inout SurfaceOutput o)
        {
            fixed4 colMain = tex2D(_MainTex, IN.uv_MainTex);
            fixed4 colBlend = tex2D(_BlendTex, IN.uv_BlendTex);
            o.Albedo = colMain.rgb + colBlend.rgb;
            o.Alpha = 1;
        }
        ENDCG
    }

        FallBack "Diffuse"
}

this texture adding shader first works in the DEFERRED pass of surface shader, and then becomes completely black in the META pass. Why could it be? I use it in a renderer feature like this:

            cmd.SetGlobalTexture("_BlendTex", source);
            cmd.Blit(source, colorRenderTexture.Identifier(), addTextureMat);
            cmd.Blit(colorRenderTexture.Identifier(), source);

It is supposed to add source to itself as a test of shader. I am not sure if the problem is blit or the shader.

regal stag
# humble robin ``` Shader "Custom/AdditiveBlendShader" { Properties { _MainTex(...

Usually with a blit you only want to run the main forward pass, not any others. You can specify the pass index (probably 0) as a forth parameter to cmd.Blit
You mention this is a renderer feature too, which suggests URP so I would avoid using surface shaders there as they aren't properly supported. Use a unlit vert/frag style shader or Shader Graph instead.

regal stag
# brazen furnace Uhm so I am wondering something extremely basic here, I have a material that has...

Currently shaders don't have a good way to stack/combine. That might change a bit when "block shaders" become a thing as they are designed to be extendable, but until then you'd either need to create a shader that combines the effects, or sometimes you can get away with rendering a transparent effect over another by using two objects/materials (and adjusting the render queue / sorting priority). Though that option is more overdraw.

Unsure what you're referring to with the last part about SampleTexture2D, but if you create a shader using the same property names as the original, when switching the shader on the material it'll keep any references to textures/vectors/floats/etc. If it's for a sprite, you'd also use _MainTex to obtain the texture from the sprite automatically.

errant flower
#

Hey guys! A small shader question.

I have a vertex function where I set UV.
That UV goes to the fragment function.

The question:
I'm reading a book where it says "vertex function data goes straight into the fragment function".

Is it really true? Why, then, in the fragment function I get hundreds of different UV values for each pixel, while having just 3 vertices (meaning I set UV data just 3 times in the vertex function).

Some interpolation happens in-between to get per-pixel UV and probably some other calculations.
Where can I read about what happens in-between vertex and fragment functions?

regal stag
humble robin
deft frost
#

@vocal narwhal you crazy son of a b-!! Thank you so much for the suggestion!! It worked!! Thank you!!

wintry geyser
#

Hey, with Unitys shader graph editor, how can I achieve this waving effect within a circle?
Or is this too complex? I have no point of reference, no idea how hard this might be to achieve, or if the shader graph is the correct tool for it, etc.
So some feedback could very much help me out

nimble dirge
#

How can i crate the red that fades to 0 opacity?

shell wing
brazen furnace
#

Where can I find this setting in universal? I wanna make brushed metal according to a youtube tutorial

grizzled bolt
humble robin
#
            cmd.Blit(source, colorRenderTexture);
            cmd.SetRenderTarget(lightRenderTexture);
            cmd.SetGlobalTexture("_ColorBuffer", colorRenderTexture);
            foreach (MeshRenderer light in LightScript.lights)
            {
                cmd.Blit(lightRenderTexture, prevLightRenderTexture);
                cmd.ClearRenderTarget(true, true, Color.clear);
                cmd.DrawRenderer(light, light.material);
                cmd.SetGlobalTexture("_BlendTex", lightRenderTexture);
                cmd.Blit(prevLightRenderTexture, lightRenderTexture, addTextureMat,3);
                
            }

In this loop, (which is in Execute function of a renderer feature pass) i fail to set prevLightRenderTexture correctly. When i check it in frame debugger it is set to _CameraColorTexture which is fine for the first iteration. However it should be set to previous lightRenderTexture after the first iteration. Why could this be even though i am blitting from light rt to prev rt

lament scarab
frosty linden
#

In shader graph does a texture2d sampler cost the same if the input texture is null or not GPU wise?

rare wren
regal stag
gritty rapids
#

Is it possible to make compiled shaders with ShaderGrpah ?
I mean not be obligated to download ShaderGraph to use a shader made with it.

regal stag
# humble robin ```csharp cmd.Blit(source, colorRenderTexture); cmd.SetR...

I don't like that final blit as you use cmd.SetGlobalTexture to set a property to lightRenderTexture while that being the the destination target. You aren't supposed to read and write to the same one, should always use a temporary inbetween.

But I'm also not sure you even need these blits? Could you not render all the lights into their own buffer using Blend One One in the light.material. Then one blit at the end outside the loop to combine that with the camera source.

regal stag
gritty rapids
#

hmmm Okay good to know, thanks !

humble robin
humble robin
#

Also, now i understand the problem. I thought SetGlobalTexture was creating an instance of the texture or something. Really, thanks so much i looked around all internet and couldn't find a solution.

regal stag
humble robin
#

Thanks! I will.

#

What is the usual way of creating a gbuffer by the way, i guess it is using SetGlobalTexturefor color, normal, depth etc. in a pass but i am not really sure at all.

fallen cypress
regal stag
# humble robin What is the usual way of creating a gbuffer by the way, i guess it is using SetG...

SetGlobalTexture is just passing in a texture to shaders, it's not creating anything. There's multiple ways to create a buffer but it depends somewhat on the URP version.
If you're in 2022.2+, that introduced RTHandle which is what you should use. I have some info here : https://www.cyanilux.com/tutorials/custom-renderer-features/#rthandle
Older versons used RenderTextureHandle, might be able to find some examples of that in other Custom Renderer Features online. There's also Render Texture assets, RenderTexture class and cmd.GetTemporaryRT.

regal stag
fallen cypress
#

depth buffer

regal stag
#

There's also a Scene Depth node then.

#

For URP, the Depth Texture and Opaque Texture needs to be enabled on the URP asset for those to work. You'd also only use them in a Transparent shader.

shell wing
humble robin
fallen cypress
#

I want to compose different custom post processing effect in the final image

nimble dirge
fallen cypress
#

there's some workarounds but it seems involving writing some advanced shader which I'm not experienced on

regal stag
regal stag
shell wing
fallen cypress
#

there's some effect which require either [position texture] or the not yet implemented post processing composition using camera stacking ( different layers for some custom post processing effect )
Post Processing composition here in https://forum.unity.com/threads/post-processing-with-multiple-cameras-is-currently-very-problematic.1028533/

some ppl suggest to get the camera depth buffer and reconstruing the world position aka ( DepthInverseProjection)
the effect explained here
https://halisavakis.com/my-take-on-shaders-spherical-mask-post-processing-effect/

forest tinsel
#

Hey, I have a problem with a water shader graph I made following a tutorial. It works great in most cases, but I've built my game to be tilable, and I've rotated the tiles. However the water shader doesn't really respect the rotation and keeps the light reflections local, so that rotation is not really respected. It sort of "rotates" the reflections as well, which looks very bad. The color in the screenshot shows that some tiles are much darker than others, because they're rotated by 90, 180, or 270 degrees. How can I fix this?

rare wren
fallen cypress
forest tinsel
#

Thanks though!

waxen verge
#

Hello everyone !

I'm in URP and i'm currently have this result which corresponds to a tutorial on creating a portal shader. The circle shrinks over time and the cross rotates. I would like to distort this texture to make it a base for my shader on which I will add noise and a step. However I don't know how to deform this texture, I tried using another texture but it just overlaps.

Does anyone have an idea of ​​what node to use? I have already tried add and multiply with a texture.

is my general method correct?

shell wing
# waxen verge Hello everyone ! I'm in URP and i'm currently have this result which correspond...

I was just trying to remember how I did it (after my no backups bluescreen yesterday xd) and this is what I landed on:
Regular tiling&offset node goes into lerp A, the same node with a 'normal from texture' node added on top of it goes into lerp B, finally connect a 0-1 float to the T value to control how much distortion you want.
Not sure if this is the way to go, but as far as I can see it worked for me 😁

edit - you would probably want to implement this where you use the rotate uv (I'm using tiling&offset in my example)

regal stag
waxen verge
regal stag
waxen verge
#

I already tried the Polar coordinates nodes but in the video, are they using a grid as texture with a polar coordinates nodes ? or it's just a mathematic explanation ? or both ? because i tried to use a grid as texture and it was weird x) I will look at it !

regal stag
waxen verge
#

ok that's helpfull ! thanks a lot πŸ™‚

solid bison
#

it's possible that this approach would also give you a pixel-width line artifact at the point the texture wraps; if so, one easy solution would be to use SampleTexture2DLOD as this artifact is cause because Unity can't determine what mips to use at that edge

regal stag
# fallen cypress sorry for the mention , can you explain how to do that sorta effect (NPCs part) ...

There's an effect I did recently which is somewhat similar. The foldouts here show the renderer feature, shaders & result. https://www.cyanilux.com/tutorials/custom-renderer-features/#full-example

Though that's a fullscreen pass and for a single character it might be better to spawn particles (or use a Capsule mesh or something) around the character with a shader/material that uses the Scene Color node 3 times with offsets to split the RGB.
Assuming the "shards"/triangles of the character are opaque geometry, they'll appear in the Opaque Color texture used by the Scene Color node.

There's also an additional blur to the chromatic abberation in the video which might mean a few more blits. It's all very custom, URP doesn't have a way to handle post-process locally like that.

Goes through examples of Renderer Features and explains how to write Custom Renderer Features and Scriptable Render Passes for Universal RP

thorn vault
#

I need help with my shader.

#

The kyle robot is pink.

#

and the shader for robot2 is hidden/internalerrorshader

#

idk what to do

#

pls help

regal stag
# thorn vault

Is there a Material assigned under the SkinnedMeshRenderer component?

thorn vault
#

wait

#

lol

regal stag
#

Oh I guess it's the Robot_Color one.

thorn vault
#

materials isnt open

#

the robot color has an error

#

@regal stag what do i do?

regal stag
#

Can probably change the shader on the dropdown. I'm not sure why it's using the error one.

thorn vault
#

im trying to make a gorilla tag fan game, and the kyles robot was said to be the best model for it

#

how do i change the shader?

regal stag
#

Probably want the Standard one

thorn vault
#

ok

#

how do i change? im a newbie at unity

shell wing
#

could be the material just needs some encouragement to work in your enviroment

thorn vault
#

rendering isnt in edit

#

what about window?

shell wing
#

probably not the case then, ignore me 😁

thorn vault
#

ok

#

ur good lol

#

idk how to change T_T

#

ok nvm

#

ty!

#

thx for helping me!

#

bye