#archived-shaders

1 messages · Page 30 of 1

shadow locust
acoustic agate
#

Thanks a lot! I will try it. Would you recommend any way to compare and benchmark the performance of both?

shadow locust
#

oh god benchmarking shaders 😅 i don't really know how to do it tbh

#

Use the frame debugger in Unity?

acoustic agate
#

Yeah, I can try to do it with 1000 samples and compare than 🙂

pure fulcrum
#

anyone able to help?

tight phoenix
#

I upgraded a nonURP project to URP and now all my default materials are pink.
I know this is a common problem but the common sollution isn't fixing it.

I already did Edit > Render Pipeline > URP > upgrade all, and this did not fix the pink

#

How do I fix the default material to not be pink?

tight phoenix
#

Is there an easy way to prevent moiré patterns from appearing in procedural textures?
Real textures use mip maps and antialiasing but neither of those can be done to procedural

#

hard nasty lines

#

as a result of this

low lichen
#

You can then use this value to blend in something that will minimize the aliasing, like to lerp to a solid color.

tight phoenix
# low lichen You can then use this value to blend in something that will minimize the aliasin...

https://forum.unity.com/threads/low-resolution-or-bad-anti-aliasing-on-normal-from-height.1051733/
I have found this person's sollution explaining DDXY whenver I google this problem but I've never been able to successfully impliment it

brave osprey
#

Im attempting to create a simple billboard shader, on a regular plane mesh. For some reason no matter what shadergraph I attempt, the planes wont look towards the camera

tight phoenix
# brave osprey Im attempting to create a simple billboard shader, on a regular plane mesh. For ...

I found a shader on unity forums that does that but its written cg HLSL and not a shadergraph. Do you want me to try to re-find it?
https://forum.unity.com/threads/problem-solving-2d-billboard-sprites-clipping-into-3d-environment.680374/ it is in here somewhere

brave osprey
#

Ive attempted to use this shader before and ran into some issues, but let me re attempt it and see what problems I ran into, as this is what i need 🙂

brave osprey
#

Worked out for me, thank you!

keen patio
#

if I set the type to normal map, what will Unity do?

#

does it change encoding? the pixel data ?

#

I use texture.GetRawTextureData(), can get different result

amber saffron
keen patio
#

I want to get the value as the default texture

#

but without change it to the normal type

tacit parcel
keen patio
#

how to do it ?

amber saffron
keen patio
#

keep the normal map type, but get the default value...

amber saffron
#

I honestly don't understand what you are trying to do.
What do you mean by "default value" ?

keen patio
#

default texture type

keen patio
#

I'm trying to do something like compress the texture

#

I need to know the default value

#

because unity compress the normal map, and I don't know how they compress it

tacit parcel
#

You'll need to either decode the sampled default normal map into normal value inside your shader, or decode the normal normal map into default value inside your code

amber saffron
#

@keen patio
You just have to sample the texture then, and you'll get the RGB value.
Unity doesn't do anything particular to the data, it just uses a dedicated format for normal map.
Like I said, normal map texture formats store the normal data in RG or GA channels.
It is then "unpacked" to convert to a vector3.

The unpack operation is relatively simple

normal.xy = sample.rg;
normal.x *= sample.a; // multiply r & a to accomodate to the different formats
normal.xy = normal.xy * 2.0 - 1.0; //remap from [0;1] to [-1;1]
normal.z = sqrt( 1.0 - dot(normal.xy, normal.xy)); // calculate the z value from xy, knowing that the normal vector length is 1

// you can now de-unpack if you want the texture original rgb color value : 
color.rgb = normal.xyz * 0.5 + 0.5;
keen patio
#

why, if I set it to default texture, then unchek sRGB, it get the same SAMPLE result?

#

how it recognizes it is or not a normal map?

amber saffron
keen patio
#

why they get the same result?

amber saffron
keen patio
#

UnityWebRequestTexture.GetTexture how to load linear texture?

amber saffron
half badger
#

the offset does nothing

#

wait

#

nvm it just randomly fixed itself

vague wolf
#

Hi! In un unlit shader, how can I save the effects of a fragment shader so that at the start of the next fragment shader it doesn't get reset? Let's say that in the first fragment I color a pixel green, in the second fragment I would like to see the same pixel colored green.

#

Thank you

regal stag
vague wolf
regal stag
vague wolf
regal stag
lean lotus
#

Why does it takes 4-5 times longer to read from a large rendertexture than it does to read from a large texture2d of the same size and file size and format in a compute shader?

fervent garnet
#

Hi, I'm getting some weird artifacts when using power on a gradient noise, even with low values like 2 any idea?

regal stag
fervent garnet
#

Ho these are negative values 🤦‍♂️ that makes so much sense now, thanks for the tip

tight phoenix
#

I am trying to achieve a sorta strata-fied look for a shader. Similar to 3D printed objects, or Topographical maps.
My question is - I want to keep the "edges" to be the same size no matter where they appear on the mesh, but I am not sure how to prevent the texture from stretching wildly across the gentle slope 🤔

#

Im currently using world position as UV coordinates similar to tri-planar shader, but I am not sure how to fix the problem of the texture stretching on gentle slopes

shadow locust
#

on a surface that is flat like the top there you should be using x and z as the uv coords for example

#

which is kinda where the "triplanar" in triplanar comes from, if I'm not mistaken

tight phoenix
#

Right sorry I misesxplained what I meant.
I am not looking to stretch a texture over it's top surface, I am looking to draw lines based on its Y height in the scene
There is no texture I can project onto it's top that will represent this data that im aware to make

#

I will try to find a better visual example where words fail

tight phoenix
#

I am trying to achieve a similar appearance - clearly separated steps of height on a slope, but without the line of each clear step stretching down the length of the slope the way it is in my above 3d render shader example

#

even better example

shadow locust
tight phoenix
#

I am not sure what you mean by this. A tall sheer cliff would look like this

#

That is easy to achieve though

#

the problem is not tall sheer cliffs, but wide gentle slopes

#

here is a good example that maybe is clearer

#

no matter what angle the slope is, the line delineating the edge of that height does not stretch

#

uniform line width

#

I am sorry if I am not clearly explaining what I mean

#

I want these two widths to not be different

tight phoenix
#

Googling a contour map is maybe what I am trying to get? But examples I am seeing are not able to solve the same problem im having: stretched contour lines

#

aaaaa the net says screenspace partial derivatives will solve this but that sounds like something infinitely beyond anything I can do

shadow locust
#

It seems... difficult to do without a geometry shader though

tight phoenix
#

Yeah I might be just SOL here and will have to explore other options

#

i will keep trying for now

#

searching contour is showing people doing it

#

so it can be done

#

I just need someone to tell me how they did it in stupid english for my dumb ape brain

#

I feel like there should be an answer somewhere in the world position and the normal of the surface

#

where somehow it's angle where like, flat is 1, and vertical is 0, gets added to the line to make it thinner

#

that sounds easy but how do I do it

#

I want... the object's... surface normal... but only from top down??

#

what projection is that?

#

ill take a break for now and try more later

tight phoenix
#

normal vector in world space Dot (0, 1, 0) gives 1 straight up and 0 perpendicular, it sorta works

#

I think the only problem right now is finding the right value that makes it look the most consistent

tacit parcel
#

What I have in mind is using a modulus of worldPos.y to make height based gradient, then using an edge detection which detect if the gradient changed direction, maybe using post process if a consistent line width is required

tacit parcel
tight phoenix
tight phoenix
tacit parcel
#

Yeah, using post process could add another complication in the future I guess...

tight phoenix
#

I was using sine instead of mod because mod was giving me super weird results I didnt know how to use

#

another problem with mine is that at distances, it looks pretty awful

#

lots of moiré

#

this stuff seems to have answers on how to fix it but im not alegebra enough to figure out how to use it

#

this might have the sollution for the anti aliasing

honest bison
#

How would I draw mesh instances in the scene editor?

swift loom
#

Can you pass a struct with a Vector3 var1; to an HLSL struct with a float3 var1; ??
or do I have to do float x, float y, float z on both sides
I just assume vector3 to float3 doesn't work in a compute shader
because Vector3 is a Unity type

low lichen
#

I'm assuming you're talking about in a ComputeBuffer, because you can't set struct properties directly.

swift loom
#

Yeah was gonna make a StructuredBuffer

#

Thanks for confirming

hybrid hawk
#

hello i am making a simple shader that takes a texture with two colors (R & G), split them up and then replaces them with other colors and then combines them with each other. the thing is i can't figure out a way to allow for the replaced color to have a alpha. is that possible in some way?

low lichen
hybrid hawk
#

i meant that each color that i choose to replace with can have their own alpha

#

i found the color mask node just now trying to figure something out whith that

low lichen
#

When I say "the original alpha", I mean the alpha of ColorR/ColorG.

#

The alpha of those colors are ignored now because the Replace Color node only reads the RGB channels and returns RGB.

hybrid hawk
#

when i do that the whole texture gets the alpha of the multiple of both colors, instead of being separated by color.

#

i figured out a way around this by using color mask

half sapphire
#

Hey all, possibly an odd question, but here goes.. I have a render texture that is applied to the default "Unlit" shader material. Is there a simple way to modify that texture/shader/material combo so that the texture is mirrored vertically?

inner coral
#

Why is Unity so stupid that it doesn't generate all the boilerplates shaders for URP?
But you have to add all the damn boilerplate manually.

I don't want to use Shader Graph 💢 😠

#

(╯°□°)╯︵ ┻━┻

amber saffron
amber saffron
amber saffron
tight phoenix
#

what could be the cause of these 1 px lines all over my mesh?

#

I've tried adjusting all the values but I cant seem to eliminate the pixel noise

#

it onyl shows up if the texture is not one complete solid color

#

so I assume the problem is related to the texture itself in some way

#

it shows up even if I set compression off

regal stag
half sapphire
tight phoenix
#

Ahh I see 🤔 I will read this,
XY problem ultimately, im really trying to wrap a texture around a contour

tight phoenix
# regal stag It's called by jumps in the UV + how mipmaps are sampled. See https://www.cyanil...
A better way to fix this is by using a Custom Function node with Out = SAMPLE_TEXTURE2D_GRAD(Texture, Texture.samplerstate, frac(UV), ddx(UV), ddy(UV)) with inputs “Texture” (Texture2D), “UV” (Vector2) and outputs “Out” (Vector4). No need to use the Fraction node here as it is handled in the code - but only on the coordinates used for sampling and not on the derivates!
``` Trying your solution now 👍
amber saffron
#

Why don't you directly use the texture built-in tiling ?

#

(in your case, directly connect the output of the multiply node to the uv of the sample)

tight phoenix
amber saffron
tight phoenix
#

It is set to repeat

amber saffron
#

Then, try what I said 🙂

regal stag
#

Then it should already repeat without needing the Fraction nodes

tight phoenix
#

oh huh yeah it does

#

without janky pixels either

regal stag
#

The fraction node would be more useful if you needed to say, repeat a section of a larger atlas. Then you'd want to use the SAMPLE_TEXTURE2D_GRAD.

tight phoenix
#

I think the reason why I was using fraction is because I need to make specific adjustments to it in the 0 to 1 range that I don't know if I can make as easily in the 0 to infinity range

#

But I dont know for certain if that will actually be a problem until I get to that step, which I am going to start on next

#

@regal stag "only on the coordinates used for sampling and not on the derivates!" In the fix for the fraction version, what does this mean?

#

if I end up needing it want to know what that means

amber saffron
regal stag
amber saffron
#

(I know I'm not clear in text, not easy to explain without showing in a graph)

tight phoenix
#

Im getting purple checkerbox, I think I messed up the formatting somehow

#

syntax error }

regal stag
#

Needs a ; at the end

tight phoenix
#

Yup that fixed it though 👍 If I end up needing to use the fract instead of the multiply directly

tight dagger
#

Hello everyone. I am looking into making a specific shader but with little to no shader experience. The effect I am wanting to achieve is taking in a 2D texture, extruding it out to cause it to have width, then mirror the texture on the other side. Any information on this kind of effect would help me out. Can this be done and what method(s) does it use?

amber saffron
tight dagger
#

For example, I am taking in a Minecraft sword as a place for me to start. I want to control how much of width the sword will have and have it extrude out.

amber saffron
# tight dagger Correct 🙂

Look into parallax (+occlusion) mapping for the "extrusion" part, and for the mirror : well, that's just the matter of disabling the culling on the shader 🙂

tight dagger
tight dagger
wet pagoda
#

hi neeed shader help

inner coral
#

Nobody can help you if you have not even asked a question

wet pagoda
#

sir i have shader the problem is titling is not working

inner coral
#

meaning, post your shader graph or code

#

Include details when you ask questions.

wet pagoda
#

this shader

#

with cginc file

#

all things working bus tiling and offset not working

fossil finch
#

Do you guys know how i can change the edges of a shader to move around smoothly kinda like this? 2D shaders. I haven't been able to find a tutorial online.

wet pagoda
fervent flare
#

Anyone know how to add lightprobe information to a shadergraph 👀

#

I cannot figure this thing out

wet pagoda
lament karma
fossil finch
wet pagoda
wet pagoda
#

please help me shader tiling and offset not working help please

tight dagger
hybrid hawk
#

oh i switched up where the Red and green should go

cobalt totem
#

I'm looking for some ideas on how to fix this: I've created a volumetric shader and a camera that renders it to a custom render texture at 1/8th resolution, I can then upscale this on a canvas:

#

I can also render the rest of the scene to a render texture as well:

#

However I'm not sure how to overlay the two, I need to access the scene's depth buffer, but from the camera that is rendering the tornado

#

For some reason when trying to overlay the RawImages, it does this:

tight phoenix
#

When I type in the full name of my subgraphs, the create node dialog doesnt show them, does anyone know why this is the case?

#

they show up when I type dice, but if I type the full diceshader, they wont show

#

Im trying to google the problem but I cant find the keywords to solve it

#

'shadergraph subgraph filter search not showing'

#

'shadergraph subgraph not showing when using create node filter'

#

i just keep finding results about outputs or inputs not showing up or connecting

#

but my problem is that the subgraph itself wont show up when I write its exact explicit name

#

Oh thats annoying, typing Dice (space) Shader works

#

even though there is no space.

sand widget
#

Any recommendations for this community? It’s been a blocker for our team since we upgraded versions of unity

meager pelican
# sand widget Any recommendations for this community? It’s been a blocker for our team since w...

No way to know, but since it is a Standard Shader, maybe check to see if there's lighting setting differences in your newer unity installation. Or throw some lights around that "grey" area and see if it lights up. Shadow mapping, or GI might be different between the two installations/versions.

Otherwise, since you're using BIRP, why not use either a custom vert/frag or a Surface Shader if you need lighting.

I've no other idea why a white object would end up grey.

cobalt totem
#

Is there an easy way to render only a camera's depth texture to a render texture?

#

I just need a way of passing the depth texture from one camera to a shader on a different camera

smoky vale
#

is there a way to add lighting to a vert/frag shader?

i have a basic sunlight set up, that is one vector that the shader uses to determine how models are lit, which works fine for now, but in the case that i want actual pointlights (without casting shadows, i dont really need it) or i need a light beaming down from the hole in the roof or something, i cant really use this singular sunlight model

#

ive considered making a pointlight script that will take every material in the scene using the shader and pass some information about how far away it is and the light color and light intensity and whatnot for use in the shaders calculation (it would be added to the sunlight) but i stress that it would not only be unoptimized but also messy

#

like how would i have 2 pointlights in the scene without a table to hold each light and all of its data

#

or how would i occlude objects that are far away without having to check the distance of that object every single frame

#

for a single light, these calculations are fine, for 15 lights coming from lamps around a room, these calculations could be devastating

#

the issue isnt so much with the shader as it is with the passing of information about lights from the game to the shader

#

because if i wanted unlit lighting, i could probably just pass a color value and multiply it with the new color value for each light in the scene, and calculate light info in-scene

#

but the thing is, you cant really multiply lights

#

because if you have 2 lights on opposite sides of the object, and you try to bundle their position into one variable, you would get a point inbetween the two points with blended together colors, which would make the object be directly inside of the object

tacit parcel
smoky vale
#

interesting, ill look into it, thanks

smoky vale
tacit parcel
#

according to this
https://docs.unity3d.com/Manual/SL-UnityShaderVariables.html

Light attenuation factors. x is cos(spotAngle/2) or –1 for non-Spot Lights; y is 1/cos(spotAngle/4) or 1 for non-Spot Lights; z is quadratic attenuation; w is squared light range.
LightAtten z seems to be the light strength when it reach the vertex.

#

I've never tried them my self :p it's just that I remembered reading them when I was looking for how to use lightmap in vert/frag shader

smoky vale
#

alright, thanks

somber slate
#

is it possible to make a shader that gets its points from two separate meshes and combines them

#

basically i have two cubes that touch each other and the default material makes it clear that there are two cubes but i want it to look like it's one long rectangular prism even though there are two separate cubes there behind the scenes

lunar valley
somber slate
#

like an outline for example

#

also if it's transparent you can see the inside edges of each cube

#

and i would like it to be transparent

lunar valley
#

ok good point

lunar valley
somber slate
#

ah smart smart ig i could have the meshes of each cube stored but not displayed and then have a parent mesh that gets updated when the cubes change

#

thanks i will try that

valid island
#

Hello, I'm having a little bit of trouble with my toon shader, when I use it I'm getting weird light banding like this, the yellow and red bands are unintentional

#

Here is part of my shadergraph for it at the moment

#

I'll admit I'm not much of a shadergraph person and this is one I've been using for months now and I'm sure it's not made very well

#

I think the bands are a recent thing and I'm not entirely sure why

#

I played around with it so it's not how it is normally but the problem is still there regardless

#

Things like the CalcAdditionalSpecular not being connected isn't normal lol

regal stag
valid island
#

It still does it even without that, I tried that from someone else having a banding issue and it helping them, but it didn't help it here

#

It still does it with this even

regal stag
valid island
#

I'll play around with it a little bit more, it wasn't the issue either though

#

But I'll see if I can get more information to go off of

lunar valley
#

Hello I have a question I would like to ask, Now this might be a stupid question but I couldn't find anything. I would like to render a specific Object to one of the cameras but not to the others, now usually I can just assign the layers but how can I achieve the same with indirect gpu instanced objects

regal stag
valid island
#

Okay thank you I'll try that tamamoSmile

#

Honestly

#

It might be something with just the GetMainLight idk, cause it's doing it for both my specular and diffuse

#

Unless I really am doing something silly

valid island
#

It's quite empty

regal stag
valid island
#

It'd be from the actual hlsl file if anything but I'm going to play around with the shadergraph for a bit first

lunar valley
#

thank you <3

regal stag
valid island
#

Yeah, I think I might be close to finding something

valid island
#

Okay I found the issue, it was the step as you were suggesting, but the way I fixed it was to convert it to HSV, step, and then convert back to RGB

swift loom
#

random question but is there a limit to how many structured buffers i can have in a compute shader other than memory? just hunting an unknown bug pensive

fair breach
#

Hey there im new looking to get into making 3d retro games ive hit my first road bump, when I try to texture a tree the area around edges are black and when i set alpha transparency the texture becomes a muddy mess.

gloomy gust
#

how can i make my player have an outline?

#

its a 2d game

#

pixel based

swift loom
#

@gloomy gust easiest way is to just make an extra sprite sheet for your sprites with just an outline and overlay it

gloomy gust
low lichen
swift loom
#

👍 lower than i expected but still not over any, thanks.... now to continue bug searching with a blindfold

gloomy gust
#

how do i apply shaders to things/

slender wren
valid island
#

Yeah idk I think I stole it from online

#

lol

#

I got it awhile ago

slender wren
#

are you sure it can have shadows cast on it?

slender wren
#

I'd like to see what you connected the attenuation to

valid island
#

I'm not at my pc anymore so unfortunately I can't show that, but yes it can have shadows cast on it

slender wren
#

mine doesn't :')

gloomy gust
#

why does my outline shader look like this?

#

why does the material do that

#

how can i fix it?

slender wren
gloomy gust
#

why does the material look like this, because it doesnt in the inpsector

#

okay for some reason it works in the build version

rose thicket
#

Is there any way to make a gameobject more transparent without changing its materials?

dry solar
#

you can disable its mesh renderer in code

rose thicket
dim yoke
#

Seems like lack of depth buffering/proper render ordering based on distance to camera (please use screenshots, not images taken with a potato

fair breach
#

Thanks

cobalt totem
#

I've managed to fix a lot of the issues I was having yesterday and can now composite a scene with a correctly rendered tornado:

#

However, for the camera rendering the tornado, I want to render at a lower resolution, and then upscale it back to the original resolution

#

I tried:

    private void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        RenderTexture r = RenderTexture.GetTemporary(source.width / 16, source.height / 16);
        Graphics.Blit(source, r);
        Graphics.Blit(r, destination);
        RenderTexture.ReleaseTemporary(r);
    }
#

But this just pixelated the entire screen

#

I also think it is applying the pixelation after the raymarching, instead of before it, which would improve performance

meager pelican
#

@cobalt totemCould you explain your code in more detail?

  1. You make a low res render texture
  2. Blit the tornado camera's RESULT AFTER RENDERING IT to the low res texture.
  3. Blit that low res texture to the final destination
  4. release it.

Well, the camera may have just rendered the full res image. All you're doing is copying that to low res and the low res to destination.

That doesn't make sense to me but I may be missing something. And IDK where the ray marching came in but probably in the shaders used to render the tornado during the camera.render() operation.

What I THINK you want to do is to assign a low res texture to the camera to begin with. But I'm unclear if you did that or not. That would certainly speed up any ray marching, but it can have problems matching back to higher res depth buffer...you have to make "smart" depth decisions for pixels that cover, say, 4 other high-res pixels.

cobalt totem
# meager pelican <@485472564991229952>Could you explain your code in more detail? 1) You make a l...

Thank you for your reply! I've now tried a script based on this: https://gist.github.com/snlehton/b015bd123c2dd1889b9c96edab40b8b6

However, it just renders at full resolution, here is the code:

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

[ExecuteInEditMode]
[RequireComponent(typeof(Camera))]
public class DownUpSample : MonoBehaviour
{
    [SerializeField] private float renderScale = 8.0f;
    [SerializeField] private Camera _camera;

    public FilterMode filterMode = FilterMode.Point;

    private RenderTexture rt;

    private void OnPreRender()
    {
        int width = Mathf.RoundToInt(Screen.width / renderScale);
        int height = Mathf.RoundToInt(Screen.height / renderScale);
        rt = RenderTexture.GetTemporary(width, height);
        _camera.targetTexture = rt;
    }

    private void OnPostRender()
    {
        _camera.targetTexture = null;
        RenderTexture.active = null;
    }

    private void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        source.filterMode = filterMode;
        Graphics.Blit(source, destination);
        RenderTexture.ReleaseTemporary(rt);
    }
}
#

From what I understand, before it renders, the render target is set to a low resolution render texture (rt), I'm not sure why the source is blit to the destination instead of the rt, then the camera's render texture is set to null so that it renders to screen

meager pelican
#

Double check the scale setting in Unity's inspector.

#

The source is the rt, because that's the camera's current output texture. So the camera rendered its scene using the low-res temporary rt.

cobalt totem
#

Hmm, it's definitely set to 8

#

If I do a Debug.Log(source.width) it outputs the screen's resolution

#

Also, destination is null

meager pelican
#

Put the/a debug in the OnPreRender() event see if it is called.

cobalt totem
#

It's definitely called:

meager pelican
#

Well, print something useful like rt.width.

#

But good to know it is called.

cobalt totem
meager pelican
#

OK, why is it showing twice? You don't have this on both cameras, do you?

cobalt totem
#

No, it's just called every frame

#

I wonder how 992 / 8 is coming out to 165

meager pelican
#

The docs for OnPreRender say:
When Unity calls OnPreRender, the Camera's render target and depth textures are not yet set up. If you need to access these, you can execute code later in the render loop using a CommandBuffer.
So it might be that Unity f-s over the render texture you set up. I doubt it, but I'm at a loss to explain what you're seeing.
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnPreRender.html

I suppose you could try creating a rt once, at the start of your program and assign it to the camera, and just let it be there for that camera's rendering. Rather than doing it every frame.

#

BB in a bit.

cobalt totem
#

Ah okay, that’s a good idea, thank you I will give that a go

meager pelican
#

IDK that it will work. I'm at a bit of a loss, admittedly.

#

You'll have to make sure the camera clears that render texture, but it's probably already set to do that.

#

That script from github must have worked for someone before.

#

So I'm lacking information somehow.

cobalt totem
#

Oh! The camera wasn't tagged as MainCamera

cobalt totem
#

Okay, I've got it rendering low res, but when I add an additional camera to render the rest of the scene, it goes to hi res again:

meager pelican
#

IDK, unless it is rendered twice, IDK how it would have gotten to the high res version. Unless the ray tracing is doing that at high res (e.g. using the low-res to merge into high-res so the result just looks high res). Check the frame debugger.

#

GTG for now, good luck tracking all this down. The frame debugger and any other C# debugger will help you track the order of events. 🙂

#

P.S. I like the effect so far. It's not done, but it's on the way!

smoky vale
#

so i was working on getting unity lighting to be compatable with my shader, and this is what i have currently,

float4 light = float4(1, 1, 1, 1);
                    for (int i = 0; i < 8; i++)
                    {
                        float lightVal = unity_LightColor[i] * unity_LightAtten[i];
                        if (lightVal != 0)
                        {
                            light *= lightVal;
                        }
                    }

what im trying to do for right now atleast is get the light to illuminate any area within its range, it doesnt have to have falloff but i will try to achieve it eventually, this is how it looks now, my question is, unity_LightAtten doesnt seem to be working properly, what i assume it does is returns the light attenuation list of the first 8 lights attenuation values, which seems to be partly true, because it will illuminate any object in its radius, but it will fully illuminate it and wont illuminate based off distance
https://gyazo.com/8f9be2c0f135b895b42e0add533e01f4

#

am i using these values wrong?

#

im using the vertex lightmode tag btw

smoky vale
#

well it appears discord doesnt like me posting the full code

sick pulsar
#

how would i get a camo effect using the shader graph

sick pulsar
#

how would i get rid of the green (going for a desert camo)

#

nvm just used the replace color node

grand jolt
#

Does anyone know why my shader isn't animating ?

#

cause somehow it's supposed to be animated but isn't

#

I mean dosen't look the same

#

at all

#

ok kinda work now

#

don't worry guys my skills are bad it's my first time using unity

vague wolf
#

Hi, this is a test of a shader for drawing on a material. I would like to save on the render texture the color of every point that users clicks, but I can't save the state of the render texture and every time I draw a new point, it overwrites the previous one. Any inputs? Thank you.

main night
#

After adding shaders to my game, my game no longer starts.
It stays stuck on this:

#

I tried using Adaptive Performance, but that didn't change anything

open cipher
#

if I have roughness map how do i apply it to smoothness in unity

vocal narwhal
#

Either use the alternate solution, or invert it, as mentioned

cosmic prairie
meager pelican
# smoky vale so i was working on getting unity lighting to be compatable with my shader, and ...

Not sure for all of your question, but you're not using the vector element as values. You're only using the red component/x-component in your equation.

The documentation explains the attenuation vector's elements:
Light attenuation factors. x is cos(spotAngle/2) or –1 for non-Spot Lights; y is 1/cos(spotAngle/4) or 1 for non-Spot Lights; z is quadratic attenuation; w is squared light range. https://docs.unity3d.com/Manual/SL-UnityShaderVariables.html
So since light drops off at the square of the distance, maybe you want to come up with a calc that uses the the pixel's squared distance and the .w component of attenuation.

Note that light types are also encoded in the .w component of the position...0 for directional, 1 for attenuated/positional.

The color you're saving should be a float3 (vectorName.rgb)....right now you're just hard-coding white. But light * lightVal works....each component will be multiplied by the float lightVal. So that will scale the color intensity if lightVal is in the 0 to 1 range.

So this means you're using vertexColor flag (as you said) and that you're in deferred rendering, yes?

regal stag
vague wolf
# regal stag In your shader you aren't setting the `uv`. You'd want `o.uv = v.uv;` in your ve...

Thank you. Sure it was an error, but It doesn't work by just add o.uv = v.uv;
I managed to save the render texture using a shader that receives the uv coordinates and not the world space coordinates. I don't know why it works and what changes between the two versions.

Shader "Unlit/Draw"
{
  Properties
  {
    _MainTex("Texture", 2D) = "white" {}
  }
    SubShader
    {
        Tags
        {
            "RenderType" = "Opaque"
            "RenderPipeline" = "UniversalRenderPipeline"
        }
      Pass
      {
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        #pragma multi_compile_fog

        #include "UnityCG.cginc"

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

        struct v2f
        {
          float2 uv : TEXCOORD0;
          UNITY_FOG_COORDS(1)
          float4 vertex : SV_POSITION;
        };

        sampler2D _MainTex;
        float4 _MainTex_ST;

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

        float _Hits[2];

        float mask(float2 position, float2 center, float radius, float hardness) {
                float m = distance(center, position);
                return 1 - smoothstep(radius * hardness, radius, m);
        }
        fixed4 frag(v2f i) : SV_Target
        {
            fixed4 col = tex2D(_MainTex, i.uv);
            float2 work_pt = float2(_Hits[0], _Hits[1]);
            float force = mask(work_pt ,  i.uv, 0.01, 1);
            return lerp(col, float4(0,1,0,1), force);
        }


        ENDCG
      }
    }
}
smoky vale
#

also why should i be saving a float3? isnt it rgba? or am i missing something?

#

oh wait you probably meant the lightval

#

ok yeah i see why

#

bit of a dumb mistake

main jay
#

Hey, y'all! I'm new to the server, so let me know if I'm asking in the wrong place. I'm getting started with the shader graph, working with 2D sprites. In this image, I have added a Texture2D with Reference set to _MainTex, and a Sample Texture 2D node. For some reason, the preview on the Sample Texture 2D is always blank/white no matter what I try. What am I missing?

regal stag
main jay
regal stag
#

The default values are used by previews yeah (as well as what the properties default to when a material is created)

main jay
#

That makes sense, thanks!

smoky vale
#

ok so

#

ive had this issue before, and im not sure why my shader is erroring without any error messages

meager pelican
smoky vale
#

cuz i was multiplying the light color by its attenuation

smoky vale
smoky vale
#

ok this is stressing me out, idek where to begin with this error, because my shader keeps randomly erroring (going pink) and then not returning an error that even indicates a line

#

even if i remove what i did, itl still be pink

flat ridge
#

Hi @regal stag, much respect for your work man!
Could you add me on discord so I can present you an offer, of course if you're interested, thank you!

meager pelican
# smoky vale lightval was intended to be a color i think

Nah, it's the color.
Maybe in your code, to make it clearer for you, you can change the variable name "light" to be "pixelColor" or perhaps just "color".
you set it to white to start with because you're not texturing it or grabbing some vertex color or something. But "light" is confusing. It's the starting color. Full intensity white, full opacity. That's why it's a float4(1,1,1,1)

#

"lightVal" is the intensity of the falloff of the light.

smoky vale
#

i might have to chop this up a bit cuz discord doesnt like me sending the full code for some odd reason

#

first bit

Shader "Materials/Splatter"
{
    Properties
    {
        _Albedo("Albedo", 2D) = "white" {}
        _Noise("NoiseMap", 2D) = "white" {}
        _Color("Color",Color) = (1,1,1,1)
    }
        SubShader
        {
            Pass
            {
                Tags { "LightMode" = "Vertex" }
                CGPROGRAM
                #pragma exclude_renderers d3d11
                #pragma vertex vert
                #pragma fragment frag
                #include "UnityCG.cginc"
                struct appdata {
                    float4 vert : POSITION;
                    float2 uv : TEXCOORD0;
                    float3 norm : NORMAL;
                    //float3 vpos : TEXCOORD2;
                };
                struct v2f {
                    float4 vert : SV_POSITION;
                    float2 uv : TEXCOORD0;
                    float3 norm : NORMAL;
                    //float3 vpos : TEXCOORD2;
                    
                };
                fixed4 _Color;
                sampler2D _Noise;
                sampler2D _Albedo;
#

second bit ```csharp
float random(v2f vert2f)
{
float rand = frac(sin(dot(vert2f.uv, float2(12.9898, 78.233))) * 43758.5453123);
float4 randMap = tex2D(_Noise,float2(vert2f.vert.x + rand5, vert2f.vert.y + rand5) / 50);
return randMap.r;
}
v2f vert(appdata IN)
{
v2f OUT;
OUT.vert = UnityObjectToClipPos(IN.vert);
OUT.uv = IN.uv;
OUT.norm = IN.norm;
//OUT.vpos = IN.vpos;
return OUT;
}
fixed4 frag(v2f IN) : SV_Target
{
fixed4 pixColor = tex2D(_Albedo, IN.uv);
//*float4 light = float4(1, 1, 1, 1);
//for (int i = 0; i < 8; i++)
//{
// float4 lightVal = unity_LightColor[i] * unity_LightAtten[i].w//( * 3 / distance(IN.vpos - unity_LightPosition));
// if (unity_LightAtten[i].w != 0)
// {
// light = lightVal;
// }
//}
return (pixColor * _Color);//
light;
}
ENDCG
}
}
}

#

commented stuff was me trying to backtrack cuz my shader randomly errored and i cant get it to not error

#

and it isnt telling me anything

#

and its pink as if it were erroring

#

but originally i was setting up a white color

#

then multiplying it by all the colors of all of the first 8 lights colors

#

and then multiplying my already existing texture and color by that light color

#

because if i added them, would it not just get lighter and lighter until it was full white?

smoky vale
#

its an iterration of the first 8 lights cuz i think it said it gives the first 8 lights from the scene

meager pelican
#

I see.
It's still basically a color (well, accumulated light mix, but that's where color comes from...light).

Yes, it would. (additive color might blow out, but might not depending on what you do).

Yes, you'd need at least a float3 or maybe float4 if you want to track something in alpha.

#

OK, let's take a look. IDK why discord isn't allowing your code post. You should be able to upload it as a text file too.

smoky vale
#

half4, actually

#

not sure what the fourth value is

#

cuz tbh this shader stuff is pretty new to me

#

wait wait

#

i dont think it was that hold on

#

oh wait it was

#

ok well apparently it can only use the forwardbase pass

#

wait no

#

ok theres one for the vertex pass so im good

#

still not sure why my shader is erroring without telling me stuff tho.. sorta annoying..

meager pelican
#

lol

smoky vale
#

and now my unity questions post about it is under moderation..

meager pelican
#

OK, 10 things at once is too much. 😉
So let's pare it down.

Firstly, are you in forward or deferred rendering path?

smoky vale
#

where can i check, and whats the difference

meager pelican
#

You're in BIRP, right? (built in, "old" style unity. Not URP or HDRP)

smoky vale
#

i seriously dont know, this is my first time working with unity shaders at all cuz i wanted more stylistic control over my game

meager pelican
#

Graphics settings.

#

Hang on, I'll have to fire up Unity. Takes a bit, unfortunately.

smoky vale
meager pelican
#

Yeah

smoky vale
#

in the graphics tab?

#

well

#

uhh

#

most of the stuff is set as "Built-in shader" if that helps

#

the scriptable rendering pipeline asset is set to none

meager pelican
#

Good.

#

BIRP

smoky vale
#

alright

meager pelican
#

We need to figure out forward vs deferred lighting path yet.

smoky vale
#

yeah, so where do i check that

meager pelican
#

Hang on, unity starting up.......
one moment please.

#

please stand by.

smoky vale
#

alright, take your time

meager pelican
#

We'll return you to regular programming shortly.

smoky vale
#

pun probably intended

#

hold on, im gunna take a walk

#

i havent gotten much fresh air today

meager pelican
#

OK, I have the answer for you.

#

In graphics settings, there's "tiers". most are probably default.

#

But you look in the tier's properties, there's a "rendering path" setting.
Also on the camera, there's a rendering path setting, but it might be set to use the default from the graphics settings.

meager pelican
#

Didn't you say you were using "VertexLit" pass tag?

#

Or was that someone else?

smoky vale
#

just vertex

#

capital V

meager pelican
#

Yeah, that.

#

That's a rendering path. So IF (big IF) you want to use vertex lighting, you use that pass and need to set the rendering path in the graphics settings for each tier to "vertex lit".

#

I'll be back in 10 minutes.

smoky vale
#

ill look it up actually

#

so if im understanding correctly, vertex lit is the simplest lighting and is based off per-vertex calculations?

#

with no support for hardly anything

#

cuz if im correct, thats what i want

#

only thing i dont exactly want is the per-vertex lighting

meager pelican
#

back now.

#

Uh, you use vertex lit path or you don't.

#

I mean, that's the top of the decision tree

smoky vale
#

thing is, i want the setting with the least built in options possible, but i dont want vertex based lighting

meager pelican
#

Then you use forward or deferred. And we'll throw out that code you're using and start over, because that code is for vetex lit path.

smoky vale
#

how much of it?

#

because i noticed on the api that there are similar options for deferred

meager pelican
#

Just the lighting part

#

Similar yes, not same though

#

There's 4 main lights for forward, with additional additive passes. Deferred is different, many lights.

#

I mean, hell, you can code your own lighting and only have one light if you want. But that's limiting.

smoky vale
#

so i just need to rethink it and recalculate it differently?

smoky vale
#

up until now

#

i was using a sun light approach where one light was cast from one direction in an orthographic style

#

but i realized i cant exactly do light coming in from a window or light emitting from a specific point that mixed with the sun light well

meager pelican
#

That says it is for deferred. So you'd be using deferred in that case.

smoky vale
#

so i decided to do my own lighting

#

then i had issues passing game data to the shader, yada yada, and now im using partly unity lighting

smoky vale
meager pelican
#

Oh god.
I'd say no. But I get confused as anyone on all these modes.

smoky vale
#

ok, ill start with standard more modern defferred and see from there

#

alright i set it up for defferred

#

but one thing before i begin rewriting this code

#

is there any way to re-enable errors in console before? i was getting shader errors just fine until recently, im not even sure what i did

meager pelican
#

Deferred is the most "expensive" and is used for lots of lights.
Forward is the middle ground and you have additive lights after the 1st 4.

smoky vale
smoky vale
#

because the shader is completely pink, even with all my latest code commented out, leaving only the basic unlit code i had that was working fine before

meager pelican
#

Change your last line to return fixed4(1,1,1,1);

regal stag
#

If there's no errors in the console you could try checking if there is any errors listed in the Inspector on the shader asset itself

smoky vale
#

if it isnt that, then i have no clue, but ill try to change that first

#

so i should be using this? im not seeing a pass type so i can assume so

#

ok now im a little confused

regal stag
#

What exactly are you trying to do? Add shading to an unlit shader? Is there a reason why you aren't using a surface shader?

meager pelican
#

We're going to change the code anyway....

smoky vale
meager pelican
#

I was about to get into that Surface shader issue too.

#

To do lighting.

#

Automatically.

smoky vale
#

well why would i want that

#

if i chose shaders specifically TO have control over things like lighting, i think ill stay away from surface shaders

meager pelican
#

So you're a masochist. Got it. 😉

smoky vale
#

sorta

meager pelican
#

lol

#

just kidding.

smoky vale
#

i just want to have a low level understanding of the lighting im using, to an extent atleast

meager pelican
#

But what you're asking isn't simple, but it's great for learning.

smoky vale
#

because i only really want simple lights with very basic falloff, and to go from there

#

i dont need all this next gen junk, or even really shadows

#

dont need emission either.. i dont need alot of stuff

#

i dont need reflections, i dont need ray tracing of any degree

#

all i need is very basic, almost cartoonish looking lights

meager pelican
#

Why not start, then, with the forward rendering path?

But let's talk for a second about forward vs deferred.

#

forward, you calc the first 4 lights for each pixel. So it is in the pixel shader.
Then, for more lights after that, you and up coding an additional "forward add" pass that uses additive color to add lights on top of that, one for each light in range.

#

In deferred, it is calculated for all lights by calling all objects in the rage of a light and adding in the light...so it is driven by a light list. That means for pixels not in range of a light, that light calc isn't needed. So if it only has one light, only one light calc is done, rather than at least 4 of them with forward (you still romp through that array and do if's and stuff in forward).

smoky vale
smoky vale
meager pelican
#

Well, yeah I guess.
But I'm talking about passes and loops more than pixel-color-math.

smoky vale
meager pelican
#

Deferred can be faster and supports a lot of lights, but OTOH, with real simple lighting it might actually be slower. There's overhead because it does a g-buffer pass first, n'stuff.

smoky vale
#

i can assume a loop is just a set of iterations (for every loop up to 5, add 10 to a variable, that sorta thing)

meager pelican
#

Pass tag.
Unity calls that "section" of the shader at a specific time. A pass.

#

On the other hand

smoky vale
meager pelican
#

Yeah, for each object in that frame in fact, that is lit by that material using that shader.

smoky vale
#

right

meager pelican
#

But in forward, it would call the forward-base pass once, and then forward-add pass for each additional light after the first 4.

smoky vale
#

in my game, i will have a variety of simple and complex lighting in one place at a time

#

for example

#

there might be a dark hallway at one part, only illuminated by a single flashlight spotlight

#

but in another place i might have a room with a row of windows each with light beaming through them

#

so i believe id want deferred

meager pelican
#

Do you want to support running your game on fancy calculators? (low end mobile?)

smoky vale
#

like most PCs

#

i dont plan to have it release on consoles, because striking a deal with them doesnt seem exactly realistic

#

so i mainly want mid to high end

#

i dont plan to sell this game for much money, rather to use this as a jumping off point, because i havent made any game before

#

well

#

made is the wrong word

#

published is more correct

#

ive made plenty of games that i backed out on, but i dont think itl be the same for this one

meager pelican
smoky vale
#

yup

meager pelican
#

It's hard for me to understand your use-case, or make any "real" recommendation, given that example with multiple windows. There's ways to fake that, though, and if it isn't the norm you probably don't need deferred. Forward has less overhead, but like that chart shows, doesn't get a "free" depth buffer and you'll want that if you intend to do volumetric lighting like light shafts "streaming through widows" or whatever.

#

You can force it on though, in forward.

#

So you get it either way.

smoky vale
#

like enemies that emit light passively, enemies that throw balls that emit light, ect ect

#

not in the emissive sense

meager pelican
#

Alright, so read that chart again, and if OK, go with deferred.

smoky vale
#

yeah im going with deferred

#

but my issue now is

#

actually

#

let me try the idea you mentioned of returning a basic white color before trying other solutions to fix my no-error problem

meager pelican
#

OK, so that's done/decided.
You can write shaders to support both, BTW.

smoky vale
#

its still pink, with no errors

#

closest thing i can get to an error is this

meager pelican
#

OK, let's look at how a deferred shader is set up, and get it working in most-simple mode.
Then you can work on the lighting part.

#

And add in the random number routine, etc.

#

Start with the basics, right?

smoky vale
#

right

#

but wait

#

before this, i just want to say

#

wait

#

let me test something

#

cuz i know it was set to SOMETHING before i changed it to vertex, that was working fine

#

ok so my shader must be written for forward rendering

#

or uh

#

maybe not

#

cuz setting it to that is still pink

#

ok well anyway

#

how is a deferred shader set up

#

im assuming ill be rewriting my entire shader, yes?

meager pelican
#

Meh, sort of. I mean, some code will copy over.

smoky vale
#

which parts

meager pelican
#

But you're going to hate me for this...

#

This is for forward rendering path though. But you can switch over to deferred later on.

#

This will give you the basics of a custom shader.

#

The reason I'm saying this is you're asking questions like "what is a pass?" and stuff.

smoky vale
smoky vale
meager pelican
#

Yeah, but work through it as a tutorial. Because the last 1/3 of that page is about lighting and passes.

smoky vale
smoky vale
#

so i scanned through it

#

and uhh

#

hold on let me look at the start a bit

meager pelican
#

So you end up supporting forward too, one way or another.

#

This shit gets complicated fast, unfortunately.

smoky vale
#

wait i think i get what you were trying to say earlier about forward lighting

#

that if i wanted the first 4 lights to respond to things like normal maps and whatnot, and if i wanted the rest of the lights to not respond to normal maps, as a performance measure, i should choose forward?

#

like i can program a different pass for the rest of the lights past the fourth one that take less calculations?

meager pelican
#

Yeah.

#

Sounds right to me

smoky vale
#

alright, in that case i want the forward path

meager pelican
#

but the cost is that for every pixel you render, you "romp" through 4 lights in your array for EVERY PIXEL.

#

Just for self lighting.

#

And deferred gets a "free" depth buffer and g-buffer before lighting is called and sometimes that's really convenient.

smoky vale
#

so with forward, i would have to run through calculations for all lights no matter if the object would even be visually affected

meager pelican
#

It all depends on if you want "normal lights" or some creating/weird "custom lighting".
Even then, in Surface Shaders you can create custom lighting models.

meager pelican
smoky vale
#

so wait

smoky vale
meager pelican
#

right

meager pelican
#

A memory buffer (think writable texture) that the camera/GPU/Shader stuffs the results into.

smoky vale
#

i believe i am using 1, but just to make sure, does this mean for example 4 screens of arcade machines that cameras render results to that is displayed ingame at realtime?

#

just any texture that a seperate camera must render into? (like double the rendering?)

meager pelican
#

Alright, uh, the results of rendering have to go somewhere.
It's either the GPU's own back-buffer, or in reality another memory buffer we call a render-target.
Multiple Render Targets (MRT) is a spec for the GPU hardware as to how many targets it can write to at one time.

For example, your shader could output an RGBA color to one render target, and a depth value to another render target, and a mask value to still a third render target IF YOU WRITE IT THAT WAY.

#

But GPU's have limitations, and some may not support 5 render targets at once, and that's what that write-up in the docs was saying and why it would fall back to forward rendering in some cases.

smoky vale
meager pelican
#

I just used that as examples. But those things exist on GPU's too.

I think you need a GPU overview, with full respect.
Do you know what the GPU depth buffer is and how it is used?
I suggest checking the pinned resources at the top of this page, including the tuts in "The book of shaders" and stuff.

smoky vale
#

alright

meager pelican
#

We probably should have made a thread for all this....

smoky vale
#

probably, but this is shader discussion

meager pelican
#

Sure enough 🙂

#

And it's fun. GPU's are cool. Takes some time, but you sound like the kind of person that will stick with it and dig in.

smoky vale
#

yeah, i know like nothing about hardware, so itl be neat to learn

meager pelican
#

Just remember that Surface Shaders are CODE GENERATORS. You can use them to examine lighting code even if you insist on writing it yourself. So it might be fun to dig into that to at some point.

smoky vale
#

hm

meager pelican
#

You're jumping into the deep end right off.
But the surface shader output can be a bit off-putting due to the 50 (ha) variants that get generated into a 2000 line output.

#

Or you can just use surface shaders and make your life easier, but you won't learn as much about the nitty gritty stuff like you want to, at first.

prime bison
#

Hi everyone! I have a shader related problem; I can't get an 8K image to 'wrap' around a ico-sphere properly, how do I fix this?

#

This is how the mesh looks like ish

white cypress
prime bison
#

Hm, how do I fix that?

#

(using blender for doing these models)

smoky vale
#

@meager pelican so i found out my issue.. #pragma exclude_renderers d3d11 was making my shader uncompatable somehow, ill have to look into what it does

#

also i read up a bit more on how a GPU works at a surface level atleast

smoky vale
#

it keeps ADDING THIS every time i save the script and open unity, im not sure why

cosmic prairie
#

make sure to look at it from the side to align the poles of the planet on the top and bottom

#

best use the numpad buttons

wet pagoda
#

hi everyone

#

need 1 help

#

i want to merge to 2 shader i am new in unity shader

#

help please

snow forge
#

Hi all, I'm going through Sebastian Lague's procedural landmass generation series and have hit a bit of a stumbling block when it comes to his terrain shader.

I'm taking it step by step and try to 'rebuild' it in HDRP's shader graph (full disclosure, I'm pretty new to the shader graph system, but have a basic understanding of how it works).

The two images show the 'original' shader, and where I'm at with the graph (apologies for the mess. lol.)

I'm struggling to see how I can 'attach' the inverse Lerp node to the 'saturate' node to follow on what's happening in the original shader.

Would anyone have any pointers please? 🙂

lunar valley
lunar valley
snow forge
#

Oh, I may have figured it out. Rookie mistake on my part, but 1 question, how can I 'split' a vector3's output to seperate x,y,z 'channels'

snow forge
#

It's basically a shader that changes texture based on the height of the mesh.

lunar valley
#

or seperatexyz not sure how it is called

snow forge
#

Ah okay, got confused cause it has rbga outputs. lol.

lunar valley
snow forge
#

Yeah, I forgot that part. lol.

snow forge
#

Gah, Shader Graph is so annoying.

Was hoping I could figure this out all by myself, but it's driving me nuts.

Would anyone be willing to help me out a little please. I don't want to be 'spoonfed' the whole solution, but a little nudge in the right direction would be very much appreciated.

If someone is willing, could you take a look at the attached shader (Unity Standard) and give me some pointers?

The problems I'm having are with the declarations of things (const int's and arrays and the like) The rest I think I can figure out for myself. But those declarations are annoying the crap out of me atm. 😦

#

Just to be clear, looking for help in converting to HDRP shader graph.

meager pelican
regal stag
snow forge
#

@regal stag Okay thanks. Will take a look and see if I can figure it out. lol.

regal stag
# snow forge Gah, Shader Graph is so annoying. Was hoping I could figure this out all by mys...

I'll also mention that macros used by URP/HDRP will be different.

UNITY_DECLARE_TEX2DARRAY(name) -> TEXTURE2D_ARRAY(name) SAMPLER(sampler_name)
UNITY_SAMPLE_TEX2DARRAY(...) -> SAMPLE_TEXTURE2D_ARRAY(textureName, samplerName, coord2, index)

Most of the common & texture ones are listed under : https://github.com/Unity-Technologies/Graphics/tree/master/Packages/com.unity.render-pipelines.core/ShaderLibrary/API

meager pelican
# snow forge Gah, Shader Graph is so annoying. Was hoping I could figure this out all by mys...

Also, (and I'm no HDRP expert nor SG expert, so grain of salt here) Unity is known to zero out declarations that have initializers on them. So they are zero rather than what you've declared their initial values to be. That would depend, of course, on the shader compiler and the type of declaration. A const static int like you have might just be substituted in directly by the compiler. But who knows?

It's best to use a MACRO imo, and let the constant be substituted in in-line. And for anything else, initialize it on the material instances.

regal stag
#

If it's static I think it shouldn't get zeroed out, but yeah defining your own macro for those static consts would work too.

meager pelican
#

It shouldn't, imo.
But I'm also unsure as to what their actual results are (the problem def).

snow forge
#

Not gonna lie, this is so frustrating. lol.

karmic hatch
# snow forge Not gonna lie, this is so frustrating. lol.

Iirc his shader is mostly just a gradient in height; you can take the height, invlerp between the min and max heights, saturate, and then plug that into a sample gradient (i think sample gradient saturates by default but no harm being safe)

snow forge
#

Yeah that's basically what he does, but it's the arrays he uses to hold the textures that's bugging me atm, and the mapping to the normals of the generated mesh I'm just trying a couple of different/simpler things to see if I can figure it all out.

smoky vale
cobalt totem
#

I thought this would be simple but I can't seem to figure it out: how do you get the current "frame number"? What I'm trying to do is split some operations across multiple frames, so on frame 1 I will calculate one quarter of what I need, then on frame 2 the next quarter and so on, so that the calculation is spread over 4 frames. I've tried using the time node, but I would rather do it on a per-frame basis

knotty juniper
prime bison
#

Hey everyone, I have a problem that I need to fix (might be a very dumb problem, sorry for that since I'm a newbie). I created a blank shader graph, and I'm not getting the template that I'd expect.

#

This is what I'm getting.

#

And the unity tutorials show this.

iron lodge
#

for alpha clipping and such, scroll down till you see a header named Universal and Visual Effects and it should have Alpha Clip and Alpha Clipping

#

checkmark those two.

prime bison
#

I think I found out what the issue is

#

I'm using the standard render pipeline instead of the URP or HDRP

iron lodge
#

Oh I see

grizzled bolt
prime bison
#

I don't unfortunately

iron lodge
#

I've put on a Material on my mesh and there seems to be some sort of line from going around the entire mesh in one motion, is this a mesh problem or can I fix it in unity?

grizzled bolt
iron lodge
dusky stirrup
#

Would someone be able to quickly explain to me why this doesn't work? I assume I'm misunderstanding how the vector3 node works?

slender wren
#

Can anyone please help my Toon Shader doesn't have shadows cast on it, even though I have done everything correctly

karmic hatch
slender wren
karmic hatch
dusky stirrup
#

ah that makes sense xd

karmic hatch
#

I assume you just want the position, in which case leave it and it'll do it by default

#

or put in the output of the position node, which is already a vector3

dusky stirrup
#

was just wondering why nothing with that was working

#

so ig I want a split node

karmic hatch
#

yellow = vector3, blue = float, green = vector2; where it's going from yellow to blue there means it's casting from vector3 to float which by default just takes the x component

dusky stirrup
#

yessir o7

slender wren
#

here is what's happening

#

no shadows cast onto the game object

regal stag
regal stag
#

Under the blackboard, Boolean Keyword

slender wren
#

Alright

#

I will see if it works

slender wren
regal stag
#

I prefer putting them in the graph's blackboard, but I think this works too.

slender wren
#

where is the graph's blackboard, how would I put it there?

#

since it seems it did not work

regal stag
slender wren
#

ohh alright

#

do I need to add the 3 separately or?

regal stag
#

Yea

slender wren
#

like this?

#

btw still no shadows

slender wren
regal stag
#

Hmm, try unticking the "Exposed" option on them

slender wren
#

nothing happened

#

they just disappeared from my inputs

regal stag
# slender wren nothing happened

Okay, I see the problem. In the code you have out float DistanceAtten, out float ShadowAtten but you swap the order in the graph. Make sure the order is the same.
Ideally you'd also multiply in the distance atten, as this will let you support the light's culling layers iirc.

slender wren
#

I did it

#

and

#

nothing

#

I am as shocked as you are

slender wren
#

and I am using URP if that makes any difference

regal stag
slender wren
#

I would if I wasn't trying to make this work on my own

#

I even tried chatgpt and it didn't work either

#

though there is a difference

#

the shadows go up by a bit

#

but it doesn't react to any shadows casting over it

slender wren
#

It was working

#

But I think that the multiplied values were

#

Affecting the output

queen lance
#

Hey there! I'm trying to make a triplanar terrain shader in shader graph, like in this picture. Basically, I want to apply a different texture to any point on the terrain that's steep enough. Any ideas for how I could find the steepness of a given point on the terrain?

regal stag
smoky vale
#

can somebody explain unity_4LightAtten0 to me

#

what i initially thought is that it was the factor of how strong the light would be when reaching a point on the mesh of the object, with or without normals taken into account (a distance calculation)

#

and that x,y,z,and w were the values for each of the 4 first lights in the forwardbase pass

#

so if i set up light 1 2 3 and 4, it would give me x for 1, y for 2, z for 3, and w for 4

#

but just having a single light in the scene and returning X to see how it looks, it seems to return 1 regardless of where the light is compared to the object

#

(i have objects on that cube that are out of the lights range, still 1)

#

i have my render pipeline set to forward, and i am using the forwardbase pass tag

tight phoenix
#

sometimes I need to sample a texture as a Texture2D, but othertimes I want to sample it as a cubemap.
So far I was forced to duplicate all the textures, one designated cube and the other texture2d within unity itself, but I'd like to not have to do that.

Am I correct in thinking that the solution is to write a custom node that replicates what sample 2d/cube does, where the UV input can take a Vec2 OR 3 to do cube vs. texture?

simple pagoda
#

I have this code:

[SerializeField] private RenderTexture special;
...
special = new RenderTexture(width, height, 2, GraphicsFormat.R32_SFloat); // width and height are 64, meaning this is 64x64x2
special.enableRandomWrite = true;
special.Create();
...
print(special.dimension); // Tex2D???
shader.SetTexture(0, "specialIn", special);

For some reason it prints "Text2D" instead of 3D despite having a depth of 2
Then it gives an error because the compute shader expected a 3D texture.

I tried using a Texture3D but that gives an error because I need to set the UAV flag but as far as I can tell there is no option for that.

The compute shader has RWTexture3D<float> specialIn;, which I am setting. Is something configured wrong? Thanks in advanced.

low lichen
simple pagoda
tight phoenix
#

I'm trying to resolve the need to duplicate every single texture in the game twice, ones as texture2d and once as a cubemap

#

what is different between this and this and how do I write shader code that can take in a texture2D but return it like a cube map?

lethal estuary
#

Does anyone know if it's possible to do something like this

var vertexGraphicsBuffer = mesh.GetVertexBuffer(0);
var sliceOfVertexGraphicsBuffer = ??? //The same vertexGraphicsBuffer, pointing at the same GPU memory, but starting from element of index 10000, and use the next 50000 after that element.

For cases in where the GraphicsBuffer is too big, and I don't really use all that data? Or it'd be pointless to do something like that if the data goes into a ComputeShader, since the data is already in the GPU?

low lichen
simple pagoda
shadow locust
#

2 is not a valid argument

#

and depth is not a number of pixels depth

simple pagoda
#

Yeah I fixed that.

#

The issue now is I need to use something I can set and read at specific pixels both in cs and in the compute shader.

shadow locust
#

a ComputeBuffer or GraphicsBuffer

simple pagoda
#

Would that work like a float[]?

shadow locust
#

if you want it to

cobalt totem
#

I've tried adding the following to the beginning of my hlsl code, it causes only a fraction of the pixels to be raymarched per frame, however I don't see an improvement in speed until I set the fraction to something large like 16:

    if (((int) frameNo) % 16 != (int) (sPos.x * sRes.x) % 16 || ((int) frameNo) % 16 != (int) (sPos.y * sRes.y) % 16)
    {
        numSteps = 0;
    }
regal stag
smoky vale
lethal estuary
low lichen
regal stag
tight phoenix
tight phoenix
#

I am trying to remove the need to have two separate instances of the same asset - sometimes I need to do things that require it to be sampled as a cubemap and other times as a 2D texture, but I cant figure out how to do that without copy and pasting every single texture in the entire game twice over and setting one to cube and the other not

regal stag
tight phoenix
#

all I know is that I need to fix it, I will try to find some use cases

tight phoenix
#

this isnt an xy problem

#

I just want to find a way to sample a texture2D as if it were a cube map

#

or the opposite, sample a cubemap as a texture 2D

#

either way works ultimately, so long as I can continue to do all the UV stuff im doing

#

yeah replacing the 2d version with the cubemap version completely fucks it

#

and its not enough to solve this one particlar instance

#

because there are hundreds of different one particular instances

tight phoenix
#

how do I fix this

#

the red ones are 2D texture sampled, the grey ones are 3D cube map sampled

#

both rely on extremely complex math that relies on extremely precise values

#

I cant just 'do it differently' because im not smart enougyh to solve all the problems

#

I HAVE to make this work

meager pelican
tight phoenix
#

the interior and exterior dont align at all

#

and I dont know why they dont align and I dont know how to fix it

smoky vale
#

i thought it was the first 4 of any lights, now im pretty sure its the first 4 directional lights only

#

or maybe just the first directional light

meager pelican
#

All that stuff got reworked in Unity 5.
So make sure you're looking at at least that version of docs.

#

There's macros for light attenuation, and they're aware of light type.

smoky vale
#

alright

#

im making good progress so far

meager pelican
#

You can always download the shader source from the repository for your version of Unity. Google is your friend.

prime bison
#

Hi everyone (yet again), I have some questions regarding shadows and textures.

I downloaded from github some assets from Sebastian Lague's terraforming video and deleted everything except the cloud part (since I want volumetric clouds that move around a central planet). The problem is that I want to modify the code in order for it to use a 'hybrid' method for generating the clouds (basically generate them trough a base 8K or 16K texture of clouds and then add worley noise on top to add some distortion), so how do I do this? (as well as adding scattering and shadows from the clouds to other objects) Any answers are welcome.

#

It is pretty complicated and I've tried multiple times to use a base texture to do it but to no avail.

tight phoenix
#

How do I mirror the result of a sample cube map? When I do one-minus the input, the result doesnt mirror, it completely breaks

#

I noticed I can swizzle the inputs to get weird stuff that is not a rotation, but also not completely broken

#

I cannot use the reflected cubemap in this circumstance either

#

it doesnt work, results are wrong

#

im having a hard time visualizing how you even 'mirror' a cube map

#

one minusing the inputs causes it to completely futz up

#

I dont know what math im supposed to do to get mirrored results

low lichen
#

You mean you want to get the opposite side of the cubemap for each direction?

tight phoenix
#

No I want to mirror the textures

#

the 3 inside should be backwards to the exterior one

odd pivot
#

Hi, I'm very new to using shader graphs and I'm trying to make a water texture. The UV is scaling when i scale up the object with the material, and I want it to tile proportionately. How do I fix it?

tight phoenix
#

it should also be behind the red 3 but thats a different problem I cant fix either

odd pivot
#

sorry, the above picture is innacurate and blurry heres what I mean

#

can anyone help?

tight phoenix
tight phoenix
tight phoenix
#

some of them are rotated, some of them are mirrored, some of them are mirrored AND rotated

#

maybe some combination of negate and swizzle will work?

#

I dont know how to solve that and brute force would tkae ages

#

since there is hundreds of possibilities

low lichen
#

Could you remind me why you need a cubemap (or why you need to sample a Texture2D as a cubemap)? Is the cube not UV mapped?

tight phoenix
#

there are two sets of UVs, one is the red exterior and the interior one grey one is constructed from object position math

#

red one is texture2D interior one is cubemap

#

I need them to align perfectly with one another, but they don't

#

as you can see, the back faces are not the same, expected is that every number would show itself but mirrored on the back

low lichen
#

But if you could figure out a way to use the same Texture2D for both, that would be better, right?

tight phoenix
#

yes

regal stag
tight phoenix
#

I dont want to have two completely separate methods but when i try to actually do stuff to the values, I need them to be in specific spaces

#

this here requires it to be a cube map to work like that

tight phoenix
tight phoenix
#

neither set of uvs worked, it turned into slavik pants

tight phoenix
#

im starting to think its just not possible to solve

#

and that I might have to author two textures per thing

regal stag
#

I'm using the Position node (object space)

regal stag
#

Basically, these give the same result for me. Though that does depend on the uvs the cube is using, and the layout of the texture

tight phoenix
#

even with a unity cube

#

did you send me a maybe out of date graph that wasnt saved?

#

I just noticed your inputs are opposite to mine

#

dir on bottom,. tex on top, mine is dir on top tex on bottom

regal stag
tight phoenix
regal stag
tight phoenix
#

oh my windows being fucky

#

wasnt the right file let me do that again

#

no difference

regal stag
#

I'm using this one

tight phoenix
#

ill try yours

regal stag
#

Don't really understand how this can be different

tight phoenix
#

yeah me either, this seems pretty impossible

regal stag
#

I'm using 2021.3.7f1

tight phoenix
#

is the math that different between versions?

regal stag
#

What does the Swizzle node look like in those versions?

tight phoenix
#

fucked, thats what

#

this is the version where swizzle needs you to open and close it to get options

#

😬

regal stag
#

Yeah thats why, I'm using the new one. You can swap them out for Split->Vector2 though

tight phoenix
#

what are your swizzles set to? Ill replace them with split-vector3

#

kk doing that

#

tada it was the swizzle

#

hey and it just works with the inside out uvs too

#

let me try using this in my over all graph

#

call up todd howard because it just works

#

How did you solve it?

regal stag
chilly robin
#

Hi all, I have a question. I'm creating a sub graph for specular lighting, it uses the Normal Vector node to calculate spec. Is there a way I can change to this work with a specific normal map instead of the object's normals?

regal stag
# tight phoenix How did you solve it?

Not too sure how well I can explain it, but in short, the direction ray is intersected with a unit cube. That's the first custom function - It's required as I realised the direction can be normalised, and we need the intersection point of that cube. (But technically if you just use the Position node this isn't required)
The point on that cube is swizzled and remapped to convert it to UV values per each cube face. The values used for remapping was really just trial and error. It's kinda similar to Triplanar - but as we don't need blending there's no need to sample the texture multiple times.
Instead I used another custom function to combine those UV coords. It also samples the texture, using SAMPLE_TEXTURE2D_GRAD (to prevent those pixellated lines, like the issue you had a few days ago)

smoky vale
#

how can i get the cameras forward vector in a shader, is there some public variable for it or do i have to pass it every frame?

odd pivot
regal stag
# chilly robin Hi all, I have a question. I'm creating a sub graph for specular lighting, it us...

To work with a normal map, you'd sample it (Sample Texture 2D, Normal mode) and use a Transform node (Direction mode) to convert from Tangent to World space. Replace the Normal Vector with that.

If you want to be able to use both options (normal map & mesh normals) you could add a Vector3 property/input and pass the normal in from the main graph.
If you're in 2021.2+ can even use a On Branch Input Connected to automatically use the Normal Vector node when the port is left empty. e.g. https://www.cyanilux.com/tutorials/intro-to-shader-graph/#sub-graph-branch

chilly robin
regal stag
odd pivot
regal stag
smoky vale
#

dont know much about matrix math but i should probably get learning

dark forge
#

So, I have this horizontally wrapping texture that i'm scrolling with an offset node

#

and what I want to do

#

is take the scrolling texture

#

and apply a different uv map to that output

#

(basically I'm trying to wobble the scrolling texture a little)

#

How do I take the output of sample texture2D and apply another UV map to it?

tiny lynx
#

I'm wanting to write a shader that takes a rendertexture, and whenever a certain color is on screen, it flips the normals of every tri on the mesh containing that color.

The goal of this, is to have a rectangular mesh made up of a bunch of triangles, and whenever an enemy appears, it procedurally hides it from view so you only see its triangulated sillohuete. My thought process for the 'certain color' part is bc im assuming it would be easier to detect

can this be done with the shader graph? or will I have to write it in HLSL? or is there a better approach to this overall?

brave osprey
#

Hey everyone, im in need of some help with I believe would be a stencil shader problem. I am using URP and have no idea where to start, this shader is a custom lit shader on a sprite render component.

How can I make it so the feet dont clip through the floor below? I would post the shader, but its a basic long code, so dont want to spam xD

ive attempted other ways of achieving this, but for the isometric style I believe I need stencils

lunar valley
meager pelican
# smoky vale how can i get the cameras forward vector in a shader, is there some public varia...

You can try

cameraForwardDir.xyz /= cameraForwardDir.w;
cameraForwardDir.xyz -= _WorldSpaceCameraPos;```
From here https://www.vertexfragment.com/ramblings/unity-deferred-post-processing/#calculating-the-view-direction
If you do that, you'd do it in the vert() function so you can pass it to the frag without having to calc it for every pixel. 
Might just be easier to pass it in from C# though, depends on how many material instances you need it on and also you could use a shader global variable to pass it to all of them.
#

You may want to normalize it.

pine willow
#

is there a reason to learn how to code shaders now days ? seems you can do almost everything with shader graph

hushed vigil
#

for when the thing you want to do isn't included in "almost everything"

digital gust
pine willow
digital gust
#

Besides that I had a lot of platform issues where shadergraph was not supported well and I had to simplify the shader a lot so it was working. But trying to find that one example that was super obvious

pine willow
digital gust
pine willow
digital gust
# pine willow thnx for the response. I guess ill have to learn it eventually

I would say, go with your known route until you really hit the issue, you can still learn shader coding the tbh. For most parts, you will get away with shadergraph. And if you step into the need of a super custom shader, you will have to give some time to it anyway. cause if you do not code shaders constantly, you might forget half of your knowledge over time anyway

pine willow
digital gust
glacial idol
#

hey guys sorry for asking, but im building a 2d game and wanted to add a fog, I did create and it did work, but it drops 10fps for some reason, can somebody pls tell me why it drops so much?

digital gust
glacial idol
digital gust
#

What are you using your shader for? Like where do you put it in?

glacial idol
#

Its 2d, so its pretty simple. but i guess ill need it to do through particle system, Thank you twentacle!

regal stag
#

How do I take the output of sample

glacial idol
digital gust
regal stag
glacial idol
digital gust
glacial idol
#

ive kept it at 1

digital gust
glacial idol
#

ive just removed the connection for the alpha

digital gust
#

Make your shader opaque

glacial idol
#

I did, i set in alpha 1

digital gust
#

No, thats not opqaue, thats just not transparent 😄

#

Surface Type

glacial idol
#

Im using 2d, so I dont have it

regal stag
#

If you want to avoid the overdraw, one way might be to move the fog calculation to the same shader(s) used by the rest of the sprites/scene. Assuming that's not the built-in ones.
You can sample the noise using Screen Position rather than UV0 to make sure it appears the same.

digital gust
#

Oh, okay you got sprite unlit shader here. Well I think its a bad idea to have a huge sprite all over the screen that keeps updating the whole rendering cycle. Try to use particles first, that might already give you what you want

glacial idol
glacial idol
digital gust
glacial idol
swift loom
#

Is simply popping my computebuffers into OnApplicationQuit() for .Release a good enough solution, or rather what I should be doing?

digital gust
swift loom
#

Well yea potentially that could be needed but i otherwise i only release them on level change.

#

you should release them to resize them right?

#

cause you have to remake the buffer

digital gust
#

Which will call OnDestroy too I think, so nthat could be a save place

#

You release them to free up memory, at least from my little knowledge about it

rapid galleon
#

Hey there. I have a shader-based system to procedurally instance large numbers of objects through Graphics.DrawMeshInstancedProcedural/Graphics.RenderMeshPrimitives. This currently works on Built-In and I'm now migrating it to URP. Anybody have any pointers/tutorials/sources on how to set up this kind of instancing on URP? Resources are pretty scant.

low lichen
rapid galleon
#

The code itself probably does, but given that the shaders themselves need to be migrated to URP there's different includes, etc.

#

For the record, the shaders is built with Amplify Shader Editor, but that doesn't matter too much, since it's mostly the right shader includes I'm after. 😛

low lichen
#

It seems to me that UnityInstancing.cginc and UnityInstancing.hlsl are very similar. I don't think there's anything different you need to do in the shader to support instancing.

rapid galleon
#

Yeah, I'm staring at those two right now too. Currently doing a quick test run with shadergraph. Do you happen to know if there's any setting to "get" it to include UnityInstancing.hlsl? It doesn't seem to do so by default.

#

Made a hand-written version of that shader and did include UnityInstancing.hlsl but the instancing id always seems to return 0, which implies the UNITY_ANY_INSTANCING_ENABLED keyword is false, which UnityInstancing should turn on, from the looks of it. Deep rabbit hole. XD

regal stag
# rapid galleon Hey there. I have a shader-based system to procedurally instance large numbers o...

I haven't used DrawMeshInstancedProcedural before, but have used DrawMeshInstancedIndirect which I think is basically the same thing? (specifically I used it to render quads for grass)
To get shader graph to support that I used a boolean keyword, PROCEDURAL_INSTANCING_ON and a custom function to add the instancing_options pragma. Have some info on it here : https://www.cyanilux.com/faq/#sg-drawmeshinstancedindirect

rapid galleon
#

Nice! Gonna check that out. Thanks! And yeah, this is a similar system for rendering grass and similar terrain details. To my knowledge, the difference DrawMeshInstancedIndirect and DrawMeshInstancedProcedural is that the former still allows you to pass data that the shader can use, whereas the latter is for cases where the shader can procedurally figure everything out without extra buffers.

#

In our case the data list for placement/rotation became so huge (file-size) that it became unwieldy to serialize in any "Unity-like" way and by far the most efficient storage on disk was as a data texture. And, you know, once it's a texture, might as well pass it to the material directly...

rapid galleon
#

Dang, just spent five minutes trying to discover where on earth to find those settings for that keyword. XD

jolly hatch
#

Hey guys
I made a water shader (URP) but I realized it is obstructing canvases (as shown in the screenshot)
(The canvas is set to World Space)

I googled the issue and found no help because the keywords are very similar to another issue that's completely unrelated to mine

#

Do I have to manually draw the canvas on top of my shader? or there's an option I'm missing

cobalt totem
#

I'm getting really close to achieving the effect I'm aiming for, I just need to figure out how to make the black pixels transparent?