#archived-shaders
1 messages · Page 48 of 1
so i have a really newbie question about shaders. i don't know the first thing about programming them yet but i picked up a shader asset that lets me palette swap my sprites by changing the material. i got it working just fine in a 2d urp project but now im' trying to use it on a spriterenderer in a 3d urp project and it's not changing the colors with material. i'm pretty sure i set it up right, do some 2d shaders not work in 3d even on 2d assets like spriterenderers?
@regal stag I can reproduce my refraction problem on a simple 3D URP project. I have only one plane with the refraction shader, and the skybox shader on the scene.
Are you sure the shader/material is set to Transparent?
Unfortunately Yes...
Probably depends on the asset, but yes some shaders if they're written with the 2D Renderer in mind, won't necessarily work correctly in 3D (even on sprites)
If they're lit for example the 2D and 3D lighting systems are completely different.
Material & Shader
Are you sure what you're seeing is the refraction/scene color? With the material being specular it might be the environmental reflections cubemap, which is indeed baked.
A way around that might be to use a Realtime Reflection Probe, though that might not perform well?
thank you, i was afraid of that
My skybox shader and my refraction shader (named WaterNew)
Here, in this test project, my skybox is a simple cubemap but in my main project, I can move it dynamically.
How can it be backed if it can dynamically move ?
If the skybox isn't moving here how do you know there's a problem?
I press play in editor and I change the cubemap texture of the skybox. The skybox is updated but the refraction not. The previous cubemap is refracted
Can you show a screenshot?
That's not the refraction, that's reflection.
Game playing cubemap changed:
Ah ok sorry because it's named refraction in the unity water shader example.
The material looks grey, which also means the Opaque Texture is disabled on the URP asset
it's enabled on the main project, I try to enable on the test project too
The problem isn't the refraction / Scene Color, it's the reflection cubemap sampled by the Lit Graph - visible when the Smoothness is larger than 0.
Is there a way to solve that ?
Placing a Reflection Probe in the scene set to Realtime could work. If you just want the skybox in it, remove all layers from Culling Mask.
I need to run on very low performance devices, is it ok to use reflexion probes ? In fact i'm trying to create a water shader and I have several water spots in the scene.
Idk, might be expensive there. Could also set the probe to custom and bake from script every so often, but not every frame. Might perform better.
https://docs.unity3d.com/ScriptReference/ReflectionProbe.RenderProbe.html
mmh well thank you very much for your time. I have a last question, I have other objects in the scene and they are not reflected by the plane. When you talk about " it's the reflection cubemap sampled by the Lit Graph", you talked about the shader applied on the plane material ?
Which shader backed something ? The skybox shader or the plane shader ?
Hey
I don't know if it's the right chat
But...
Someone know how can I export shading nodes from Blender to unity or compact nodes into an image/file .png?
.
I tried something called "baking" but it turns my glass texture into a non-transparent texture with very bad color instead of the original.
At the same time I found another video where they use a Blender extension called "nodes exporter" which copy and paste the nodes as they are from Blender to Unity, but I can't find it online to download it
Hey, I've been trying to work on recreating t3ssel8r's famous pixel art style in unity 3d. I created a pixelation effect but it doesn't look nearly as good.
``
Shader "Hidden/NewImageEffectShader"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_pixels("Resolution", int) = 512
_pw("Pixel Width", float) = 64
_ph("Pixel Height", float) = 64
}
SubShader
{
// No culling or depth
Cull Off ZWrite Off ZTest Always
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
float _pixels;
float _pw;
float _ph;
sampler2D _MainTex;
fixed4 frag (v2f i) : SV_Target
{
float _dx = _pw * (1 / _pixels);
float _dy = _ph * (1 / _pixels);
float2 coord = float2(_dx * floor(i.uv.x / _dx), _dy * floor(i.uv.y / _dy));
fixed4 col = tex2D(_MainTex, coord);
return col;
}
ENDCG
}
}
}
``
Does anyone know how i can create his shader?
I do not know such an extension, you cannot bake glass into a texture because its transparent and it refracts and reflects and does other things with your lighting. I would just remake the glass shader in unity
I do not know how yours looks like so its hard to say what to improve uppon
You could also try to progressivelly down and then upscale your renderTexture, but make sure you do it with point filtering
I think t3ssel8er doesn't decrease the resolution with shader - he just decreases the real game resolution. You can see in his editor window that the selected resolution is just small (e.g. 640x360 or 960x540). In shaders, he mostly adjusts the color so the color palette is reduced to a small number of choices. He is either rounding those up to certain thresholds or using some kind of look-up-table.
Is there a way to work with nodes on unity as well?
yeah shader graf
Is a plugin that I need to install, or is it something that is already on unity?
If you use urp or hdrp it's already installed as a package
BiRP can be used, but not all features might work iirc
Ok
Can’t speak for his methods but I’ve had some success in this way:
-Sample the region of pixels you’re going to downscale to a single pixel
-Calculate the average color in the region
-Paint in the closest sampled color to the average
It’s heavier than traditional downsampling but it has a lot of benefits in clarity
You’ll get a similar level of smoothness to bilinear filtering while retaining an accurate color palette like you would in point filtering
What is the fastest/most efficient way to create a water with reflection shader ?
there is none, you will need to specify your needs so that we can answer properly, these are the ways you can do reflections tho: reflection probe, planar reflection, screen space reflections, raytracing
I'm trying to render as best as possible water spots (drawn using a water shader on a plane) in a golf terrain. Constraint, this must run on mobile devices. If reflection is possible without eating all the gpu then I will use that. Currently I'm using the Scene color node in my shader, the problem is that the reflected image is not dynamic (you can see my previous discussion, yesterday with @regal stag)
I would really not do reflections for a mobile game even on low end pc devices the mirrors are often dirty or not reflecting. I would rather go with something stylized with simple lighting and do refraction only. But if you want to have reflection the probably cheapest way is parallax corrected reflection probes(cubemaps)
Ok @lunar valley thanks for your help 🙂
[numthreads(10,10,10)]
void NoiseMain (uint3 id : SV_DispatchThreadID)
{
Density[ id.x, id.y, id.z] = 5;
}
This shader creates an array of floats, but only the very bottom layer is '5' the rest are '0'. I don't understand, the buffer is sized correctly. I don't see any reason for this to be happening, although I'm new to compute shaders.
This can happen when numthreads and the thread counts used in the Dispatch call aren't valid together.
They're both 10x10x10
Is there a thread limit?
I didn't imagine it would be this easy to hit
But it still sets some values so...
If numthread is 10x10x10 and the dispatch count is 10x10x10, that means the thread count will be 100x100x100, since they are multiplied together. Is Density 100x100x100?
no, lol
I'll look into .Dispatch and numthreads promptly
Huh...
I changed the dispatch threads to 1x1x1 and now I only get a single row of 5s along the x axis.
This is very confusing
densityShader.Dispatch(noiseKernel, 1, 1, 1);
[numthreads(10, 10, 10)]
void NoiseMain (uint3 id : SV_DispatchThreadID)
{
Density[ id.x, id.y, id.z] = 5;
}
Really not sure what else to share, it's outputting a row of 5s on the x axis among many 0s, but it was outputting a whole plane of them when dispatched with 10 x 10 x 10.
Now it only does the x axis row, even if I change it back
I've been fiddling with dispatch and numthreads and I see no rhyme nor reason to what make what work how. I've gotten a bunch of solid planes to render again, but I still can't get a solid cube
I couldn't really say with only the numthreads and dispatch count in mind. I am not sure what Density is doing.
I just made the kernel a single dimension
so its fixed now?
Practically, yes. Optimally? probably not.
I want to use vertex weights in my shadergraph but idk how, what's the input called?
I'm writing a transparent fog shader, the shader needs to be in a non-transparent render queue so that i can receive shadows
The issue is that when i enable any sort of alpha blending in the shader, the render order is broken and the fog renders behind everything else
alpha blending on
alpha blending off
all i changed between the two screenshots was this:
before: #pragma surface surf BackFace keepalpha decal:blend
after: #pragma surface surf BackFace keepalpha //decal:blend
what could be causing this, and is there any way around it?
the tilesets in the image are in the geometry queue, the fog is in the alphatest queue
interestingly the fog does blend over the character model, the rest of the environment is (tilemap) sprite renderers and the fog itself is a quad mesh renderer
the sprite renderers here have a custom shader that's setting them to be in the geometry queue, though
turns out i had manually set the sorting layer of my tilemap shader in the material, it was ignoring the shader
though it seems im still unable to make the shader recieve shadows
the renderers are set to recieve shadows, the object im using to create those shadows is in the light's culling mask, and the light is set to hard shadows but im getting nothing
even if i disable the alpha blending on the fog shader, still nothing
is there something specific i'd need to do with this shader to make it recieve shadows?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
the relevant shader code
Have you tried increasing your shadow distance in your Project Settings?
yes! thank you this worked
somewhere in the internet, maybe...
what is the PBR graph in URP?
So, let's say I want characters in my game to have faces, which is a bit of a radical idea, but I've got a vision.
What's a good practice for making animated 2D faces on 3D models? Right now, my ideas are to have a texture which has all the different face sprites on it, and swap between them using UVs, but I'm torn between using Decals to project it directly onto the model, or using an invisible copy of the head, which has the face rendered onto it.
I don't want the faces to be a part of the skin texture/material itself, since that feels like it would make it harder to edit freely, and wouldn't let me have the faces be transparent as easily.
Is there some resources I can look into for this kind of "2D face on a 3D model" thing?
I have a quick question on texture arrays. Is it possible to tile the textures in a grid? What I'm trying to achieve is a shader that let's me move around a grid of images generated by loading many tiles into a texture array but I'm having serious difficulties with the second axis. Right now I'm able to do this
but what i'm trying to achieve is this
{
v2f o;
o.vertex = UnityObjectToClipPos(vertex);
o.uv.xy = ((vertex.xy) * 8 + float2(_UVOffsetX,_UVOffsetY)) * _UVScale;
o.uv.z = ((floor(vertex.x*8) + _UVOffsetX )*_UVScale) + 3.5;
return o;
} ```
with this code
has anyone else had experience with this? thanks in advance
Is there a way to access unity's SSAO Texture in a custom renderer feature, or access the texture in an HLSL file for use in shadergraph?
or make a custom one from the depth texture or whatnot
hey
I was following this tutorial to have an energy shield
his results are like this
but this is my result...
I have an almost 1 to 1 shader graph, but we use different unity versions so I can't copy exactly
for some reason the color is not being applied
You probably want to set the alpha clip value to 0 or a very small value like 0.0001
What is the emission color value ?
check it idk what's wrong
it's like this now
I think emissions are disabled in my scene... because I tried adding fire from particle pack and it looked very bland
What if you just disable alpha clip ?
The example you shared uses bloom in addition to emission
I've got this project to make an outdoor scene with a set amount of deliverables. One of the deliverables is 3 Shaders/Materials made within Unity. I've been working on one that will let me add moving grass to the scene, but I am not sure what I could do for the other two. If anyone has any suggestions or resources for any shaders I could use to enhance this scene, that would be great.
Maybe a clouds shader and a pulse shader emitting from the artefact?
how do I add bloom only to the object in question, I am kinda stuck even after looking online
it's either all bloom or no bloom
That's correct
how do I make only the object emit then?
You can see here there is bloom on the beams in the back as well
So for a clouds shader, I would make the clouds material in shadergraph and then apply that to a skybox right?
You can use the bloom threshold to limit it
you need bloom post processing to look like that
oh nv
Yeah for example, there are different ways to do it from simple to advanced. But you should be able to find a tutorial for it :)
m
yeah but I only want my object to glow, not the rest
the stronger the emission the stronger the bloom
enable hdr in camera
give your object a lot of emission
and crank up the threshold
@indigo citrus Like I said, what does it look like if you disable alpha clip on the material ?
I'm not sure but it looks like emission is ignoring alpha.
One other option would be to use unlit transparent, with additive blending
without clipping
looks like the alpha is ignored
not sure why
multiply emission with the value u use for alpha
I think the shader itself still has some problem
There's no gradient from the edge of the sphere to center, and the sphere doesnt seem to react/intersect with the level
Maybe you need to activate some depth buffer or something
it does work for him
alpha clip shows that it uses the depth buffer correctly
at least it glows now
do this @indigo citrus
1 sec
Because you are only using emission and don't care about the surface color, I'd really recommand giving a try to the unlit method
same thing
eh
unlit graph you mean?
Yes
For example, unlit with alpha blend, and plug what is currently emission into the color output
well it works now, so I won't complain, thanks anyways
You could leave alpha cliping, but set the clip value to 0 or very low
It will not render pixels where alpha is bellow the clip value, reducing a bit the cost of the shader
I see
how do I make the power of the fresnel go from 4 to 6 and back over time
also I want to be able to increase the power property by code
does it actually reduce the cost? only ever saw people complaining about clipping opaque objects messing with optimization decreasing performace, never saw the opposite said for transparents
If you want to control it from code, use the Material.SetFloat api
yeah but I want a breathing animation in the shader itself, where the intensity can be scaled by code
The performance of clipping is very dependent of the use case :/
let's say I have a fullscreen quad, rendered in the transparent queue, half of it is clipped, does the clipped half cost less? If I were to dither the clipping to the whole quad so it's still half, but every second pixel is clipped the performance will be less?
Then for example, instead of the power input, use an other time sin, remapped from -1;1 to minPower;maxPower
Theorically, if the clipping operation is done before the shading, it will indeed cost less.
Now, if you clip half the pixels dithered, I think that the shading operation is still done for discarded pixels, because visible and discarded ones are still in the same thread group
so per thread group it can sometimes optimize? is this gpu / graphics api dependent?
I don't get it
When talking of opaques, for example in HDRP there is a depth prepass, and opaque objects are rendered afterwards with a equal depth test.
So the clipping is done early on in the depth only pass, and cost is reduced but the ztest in the subsequent passes
Can someone help me with a small code🥹
no, use the remap node
time.sin -> in
-1 ; 1 -> range in
power min ; power max -> range out
Ask your question, don't ask for permission 🙂
Remap node
It will do exactly what it sounds like, remap a value from an input range to an output range
This is script, for #archived-code-general , not shader code
Okay
thanks remy
Is there a way that I can apply a Gaussian blur effect to the lighting and shadows applied to a surface shader?
Trying to get a pseudo volumetric lighting sort of effect, but the hard shadows being cast on the fog doesn’t look great
Then you shouldn't be in that class or should have started learning it when you had time
the texture is not being emitted
(I'm using URP)
I want the orb to have a texture with the provided pattern
put it into the base color then instead of the alpha
then it's not transparent, and the pattern is still not there
I want the pattern on the energy sphere
look why are you multiplying your texture with a color when alpha is a float and not a vector that makes no sense
Let's learn how to make an awesome force field with Unity Shader Graph!
● Check out Skillshare! http://skl.sh/brackeys15
● Support us on Patreon: https://www.patreon.com/brackeys
● Project Files: https://github.com/Brackeys/Force-Field
● Water Shader shown in intro: https://youtu.be/jBmBb-je4Lg
● Setting up Lightweight: https://bit.ly/2W0AY...
Is the texture assigned on the Material?
Would be the material asset assigned to your sphere. Will be listed under the MeshRenderer component.
if the material with the shader on it exists before you assign a texture as default in shader graph it won't be overwritten automatically
I see
Be aware that as Let'sBlend is hinting at, using a Vector4->Alpha will take the red component so this will only work provided the Color has some red values.
I tend to keep Color and Alpha calculations with separate chains as it makes things clearer.
yeah I see
Would probably multiply these ports instead
yeah I see
So I have a simple parallax shader using shader graph, and I have artifacts at the corner that I don't know how to handle
You can't do anything "easy" to fix this, it's just how parallax occlusion mapping works
Got it, I was looking at research articles on POM, and everything was way over my head 😅
A common way to work with it is to use a trim, literally covering it with another mesh 😆
Yes, indeed, because you usually apply POM to flat surface, you can hide the end of it with a mesh 🙂
Got it lol
Out of curiosity, what are some techniques that people use?
Is this effect basically why Parallax isn't used in games very frequently?
It's also because it's a bit costly, and works only for flat-ish surfaces
I didn't find proper explanations on how it's done, but the method is named "silhouette correction" or "silhouette parallax occlusion mapping".
So, same a POM but you need to find a way to also pass the geometry shape to the POM loop and check if the raytrace goes out of it to discard pixels.
That makes sense, thanks for the explanation!
Yeah... That's complicated lol
I would have to rewrite this using a shader, not a shadergraph, and the research papers AMD released years ago are gone, so that's unfortunate
The Tatarchuk paper on POM i mean
The only implementation I found is in the unity core HDRP shaders and a forum post & video from 2009
I might try my hand at tessellation as well, that seems quite useful
You don't need to do a full hand written shader, you can do it with a custom function node in shadergraph
HDRP implements the depth offset for POM, which allows to accomodate with mesh intersections and shadowing, but not silhouette.
At least I think thats what it is doing
Oh yeah! I forgot about those!
Also, thanks for finding it! I was searching all over google at couldn't find it
hello! is there a good terrain shader for webGL?
that usees splatmaps or paintable layers
never mind
Can I have a cut out shader for sprites? I mean with sprite renderer with sort order like standard sprites
Sprite renderers by themselves don't have to use transparent shaders, opaque cutout will work too
Sprite graphs in the 2D URP specifically don't expose that option, though
I see z-fighting when they are overlapped
They both have sprite renderer with sprite and a cutout shader
Solved, I should have added
ZTest Always
ZWrite Off
Properties
{
[PerRenderData]
_MainTex ("Texture", 2D) = "white" {}
_CutoutValue("Cutout Value",Float) = 0.5
}
SubShader
{
Tags
{
"RenderType" = "TransparentCutout" "Queue" = "AlphaTest"
}
LOD 100
Cull OFF
ZTest Always
ZWrite Off
In my experience opaques must be sorted by position or with render queue
Does ztest always actually work? I'm not sure if I understand what it does but it seems to make it ambiguous which one is drawn first
Hello there, How can I make a specular lighting effect into a sprite shadergraph ? I though of using the dot product between the world position and directional light but it doesnt show the result, also I noticed that using a standard Vector3 instead of ligh direction still does get displayed into my sprite, what could I be doing wrong?
Here is how my graph looks
You'd want to use normal direction, not geometry position
Thanks for your response, sadly it still doesnt work
Is this how the graph should look like based on what you said?
Looks right
Are you using the 2D renderer? That one doesn't support any of the usual light functions
Yeah, Im using it, so if it doesnt work on 2D renderer, I guess I will use an external script for getting light dir.
But the thing here is that this still does not work even by using a standard Vector3
Is the normal vector inside the functions 2D renderer doesnt support?
I noticed that by setting the Z value of my vector to be 1 instead of 0, now I get color on my material, but it covers the whole sprite
like it goes from gray to black on the whole sprite
this is the current result
Zero vectors don't have a direction so dot product doesn't work with them
Ohh, okay
That's expected with "N dot L" lighting *and flat quad geometry, but I assume that's not what you want after all
Maybe "fragment distance to light position" is more what you're after
Yeah, what I need in this case is to simulate a highligh over a sprite, I guess the problem right now is that I am not controlling the "size" of the highlight
Unclear what "highlight" means exactly
Pretty much a specular over my sprite; My goal is to make a metallic shader for my sprite, toon looking and not reflective but rather can simulate the specular / shining of the metal
Something like the white spots here for example
You'll need also a normal map for that
I'm using one but certainly there is a very weird behaviour with it and my scene
I am using shadows with a shape light and the normal seems to be projected onto the background of my scene as I move
I assume I need to ignore background to receive shadows somehow to fix that
You'd have to implement normal mapping manually to your custom lighting
Not sure what kind of issue this is but it sounds like a separate one, related to 2D lighting / shadow casting
Is this the correct channel for that? or is it #archived-lighting ?
#🖼️┃2d-tools is most likely to have people familiar with 2D renderer's lighting
Alright, thanks I will ask for that there
But I still need to figure this highlight thingy out, I thought of another solution but not sure on how to implement it
I don't need my specular to be highly accurate or realistic, I just need some sort of visual indicator of the metal shining, it can be a simple shape over the sprite
I thought of using a sphere mask and map it over the sprite, and set its offset based on the direction of the light / a specified vector
Does that sound suitable? or is it an overly complicated idea?
I can't quite visualize that in my mind
Metallic and specular looks are quite easy to get wrong when you can't rely on 3D shading, I recommend doing a lot testing
Alright, I will give it a try then, thanks for your time
how do i increase shadows render distance
in the project settings (in the quality tab I think)
yeah there is something but how do i use the tier that i want and choose the shadow render distance
quality, not graphics
Hey guys. I'm working on a 2D over-world map that needs to have Fog of War on it to hide the areas of the map that haven't been explored. What I'm thinking as of now is to have the map as a seperate Layer under the fog then having a shader where I can define coordinates where the fog shows through. I'm not really well versed in shaders so anyone who can give me some advice on this would be appreciated.
I would like to make fog of war like this.
Hello guys, any idea how I can avoid this on my line renderer :
have you tried FXAA ,https://assetstore.unity.com/packages/vfx/shaders/fullscreen-camera-effects/fxaa-fast-approximate-anti-aliasing-3590
Is there any feasible way to apply blur to a shader's lighting model? I'd like to soften the lighting and shadows on my fog shader, but it doesn't seem like unity supports this in any way with the built in render pipeline
{
half NdotL = abs(dot(s.Normal, lightDir));
half4 color;
color.rgb = s.Albedo * _LightColor0.rgb * (NdotL * atten);
color.a = s.Alpha;
return color;
}``` This is the current lighting model im using for this, but it doesn't seem like theres any way to sample neighboring positions to average the lighting or whatever
if this isn't feasible, could it be done in the finalcolor function?
Okay, how can I blur the background and foreground in my shader graph?
This is making me lose my fucking mind, I cannot figure it out, the edges are to hard, and I know there is a node I can use
can't speak for shader graph but in a traditional shader you'd either implement a guassian blur function or just sample neighboring texcoords and average the color
if nothing else i'd imagine you can make a custom node that implements this or something
yeah, feels a bit overkill though since I just need to soften the edges on a rgb
fundamentally that's how blurring works, you average to nearby colors
there might be some fancy edge softening thing im not aware of
Filled Font Shader?
there is wrap diffuse gives a softer lighting cs float wrap_diffuse = saturate((dot(L, N) + wrap) / (1 + wrap));
hi,
is it possible to make a sample2D from float3 or float4/fixed4 ?
I mean can we reverse this
float3 color = tex2D(_tex, uv); ... instead of outputting float3 from tex2D , we output tex2D from a float3 , is it possible ?
On the face of it, your question makes no sense. Do you mean you want to write to a texture from a shader?
well, let me put it this way.
i have a complex shader, that does what its supposed to do , I need to convert it to sample2D for the next step
A shader cannot create anything. You can create a RenderTexture from script and pass it to the shader so it can write to it, or just render directly to the texture so whatever the shader returns gets written to it.
This can be done with a Blit.
fixed4 main(v2f i) : SV_Target
{
// Sample the main texture.
fixed4 color = tex2D(_MainTex, i.uv);
// some other code that changes the value of "color" and makes it a completely different thing
....
// for this step , I need the sample2D from the final value of "color" ( if possible ) to be able to move on the next step
// Return the final color.
return color;
}
@low lichen that is what i meant 😄 , I think its gonna be expensive to go bk to c# then shader again
But why do you need to convert it to a sample2D if you already have the modified color right there? Is it because you need to sample colors from different pixels than the current one?
yea , i need sample the current value of "color" to be able to use it in the next step, is that possible ?
But what do you mean by "current" value? You already have code that is modifying color. You already have color. Why do you want to put it in a texture just so you can sample it again and get the same color?
not the same color, i have other functions that uses the sample of the current state and make it right
Still doesn't make sense to me. Are you going to sample it with a different UV value?
Are you going to sample it multiple times to calculate some average?
is it possible to extract the sample from color ?
What you're saying makes no sense. sampler2D represents a texture object, with a resolution, texture format, filtering options. What kind of texture would you expect if I tried to convert a float4(0, 0, 0, 0) to a sampler2D? What would its resolution be?
i dont know , we can convert sample2D to float4 , how come we cant reverse the function somehow using uv or something else , to get the current updated sample values ?
tex2D(sample2D,uv) ===> float4
That function is the equivalent of saying readTexture(texture, uv) => color
yea I dont know what is happening there but I think maybe we could somehow reverse it
im new to shader so I dont know
or how would anyone sample the updated color value ?
A 2D texture is a grid of pixels, where each pixel has a color. tex2D lets you read from that grid of pixels. You're not sampling a color, you're sampling a texture.
Maybe it's best if you explain from a high level what you're trying to do.
And disregard how you were planning to do it for now
honestly dont know , im still learning and I think i am gonna waste ur time 😄 , but thanks for explaining what tex2D does , coz I didnt think of it that way at all , this makes a lot of sense.
Is it possible to make a shader that only lets the game display colors from a color palette of my choosing? I'm making a game using graphics based on the NES and I'd like to limit the game to only display the colors from the NES palette.
This sounds perfect, can’t believe i missed this in the surface shader examples doc, thanks
It might be simplest to just use a LUT. See "LUT" in the article linked below:
https://www.nesdev.org/wiki/PPU_palettes#LUT_approach
The NES has a limited selection of color outputs. A 6-bit value in the palette memory area corresponds to one of 64 outputs. The emphasis bits of the PPUMASK register ($2001) provide an additional color modifier.
For more information on how the colors are generated on an NTSC NES, see: NTSC video
You can use your color texture as the UV of your gradient's sample texture
A LUT works for the whole screen but it's got its own quirks
- Can i iterate through a passed texture to get every pixel's value? My texture is 1xN, where N is defined at runtime. Every pixel represents a world-space position, and i need to retrieve this data from the texture
I suppose if you wanted to reconvert a float4 to a texture2d you can look into blitting
@low lichen
Thats peobably the closest you might get
Thanks a lot 🙂
but let me ask you this before I jump into something new
in this example , i used uv coord as 0.7,1
one thing I notice with your problems is that you seem to treat the GPU almost like another CPU in that you play hot potato with data all the time
lmao
going back and fourth constantly
anyways
my first question with this though
i really dont know the difference , iam really new
whats the frame of referneces?
in the sense that I'm assuming with the screen
you want to get the final values from a shader right
you can only do that "blit" operation on the CPU
so my question is
do you want to know what the value of the pixel is on the CPU side? or the GPU side?
gpu side
my advice, I would treat the GPU almost like a fire and forget, its meant to perform a task that you give it in BULK
i actually know the value on both
what do you mean?
like the pixel coordinate?
yes
like i know the x value would be 0.7 and y is 1
well for the sake of simplicity, because your problems tend to be very confusing
say you wanted to display the exact value at a certain pixel coordinate
it will be something like that , cpu and gpu will have the same data
on the shader side
so you have a texture2D that you are sampling that has your final colors within it
and to display the specific value on that texture2D across all pixels
or effectively get the color value from that single pixel
its as simple as
yeah but that wont work tex2D(_MainTex, i.uv)
tex2D(myFinalTexWithColorSampler, float2(0.7, 1))
how do i get myFinalTexWithColorSampler ?
not in that case if i.uv is defined like it normally is, because normally i.uv would have a different value per pixel
but in my code snippet
you instead input a CONSTANT
and thats how you have consistency
myFinalTexWithColorSampler is just another texture2D sampler
do you mean how would you get your final color from a shader onto a texture2D?
no , that is actually what i was asking about lol
i was trying to reverse tex2D(_MainTex, i.uv) ==> float3 to float3 ==> tex
but I learned that tex2D only reads pixel from MainTex , it's not really converting
true
its a texture sampler
it only samples from a texture
a texture which is made up of a bunch of float4s in an array
its only reading though, it doesn't convert
if you want to convert that is a different story, and that goes back to what I suggested earlier which is that if you wanted to sort of do something like reconverting, you will need to use a Graphic.Blit
which is a bit involved
tex2D also doesn't read just from MainTex, it reads from any texture that you feed it
thanks for explaining that , so u are suggesting that i create texture using graphic.blit then read from it using tex2D ?
yes
so say that you have a shader pass
that computes like a crazy rainbow that changes across many pixels
and you want to convert basically that float4 into a texture2D
yes? @pale python
reading back above looks like @low lichen was on the money with suggesting blit, but you confused the hell out of him
so whoops
looks like you disapeared for a bit @pale python but I'll continue with the explanation
but like I said, you have a pass that does this in a shader
and you want to convert that into a texture2D, in that case you would use a blit
so in the C# side
you have to write a section of code that creates a render texture at a set resolution
so you can use something like rendertexture.gettemporary
then use
Graphics.Blit(sourceRT, myTempRT, myMaterialObject, 0);
so sourceRT is the original texture that your screen is currently seeing basically
myTempRT is the render texture that will obtain the colors
myMaterialObject is a material that has your shader on it
and then 0 is the pass index, for the pass that you want to compute the color from
after that blit operation, myTempRT is the texture that you are looking for
and in the next pass (or another shader), you can create another sampler2D _MyTexture field, and on the C# side you'll have to use Material.SetTexture("_MyTexture", myTempRT)
and then of course you would use tex2D(_MyTexture, i.uv) or tex2D(_MyTexture, float2(0.7, 1) to sample colors from it
and that is how you would effectively convert a
float4 > tex2D
this is also a core concept used in post processing effects, since often they are multipass and need to retain computed color values from previous passes
thank you so much , yes, my connection is currently unstable ,but I managed to read everything ❤️ ❤️ thank you
I think its also important to mention honestly that if you are doing this, but only care about a single pixel then your probably best doing all of this on the CPU
and it'd likely be faster and much easier
but other than that I have no idea why you'd want to be converting it back into a texture
anybody use shader graph that knows why this could be happening or how to fix it? i'm using urp and i changed a few values on the shader graph but now it's just flickering between the old version and the new one. i couldnt find anything online after a quick google
i can post my graph if necessary
Hi All
Any tips for updating a shader I created in ShaderGraph in 2019 to 2021 Unity? Half of the windows are 'greyed out' and I don't know where to start...
I followed a tutorial (https://www.youtube.com/watch?v=WvvvzupH18s&t=1491s) but now I'm guessing I'll have to learn about shaders to build it again from scratch. Any starting points you can recommend to help me learn this simple transition shader I created? 🙏
Learn how to create a simple shader to switch between scenes in interesting ways using just a gradient image!
Get the files to follow along at https://drive.google.com/file/d/1DkK85TqgAMLqtc45L_DnhApcPcQ8WVi5/view?usp=sharing
Wishlist 'Scoot Kaboom and the Tomb of Doom' right now at http://bit.ly/scootkaboom !
Get my new Udemy course 'Learn T...
They are greyed out because SpriteColor is not used
Instead, plug your W component into Alpha and the remaining vector3 into BaseColor
- I've passed a texture to a shader. Its dimension is Nx1. Now i need to iterate through this texture and get every pixel's XY values. Is there any alternative to the c# method GetPixel()? I use integer coordinates for this, which are constant 0 for Y and 0-N for X
I don't understand.
Its an Nx1 texture. Each pixel's position is (x, .05) if you want the pixel center on the Y axis. Where x = the pixel offset divided by N-1.
If you want it in UV coordinates.
- I didn't even think about converting integer coordinates into uv ones
Well, in the shader, sure.
In C# probably not. Not sure what you're doing.
- It's in cg, yes. What i'm doing is just passing data to the shader. I was told to use textures for this, since there are no arrays or collections in general
But samplers work with UV's which are % of the width/height. This makes them resolution agnostic.
And given the various sampler states that can average out samples....you get sampling by %.
You CAN pass an array to a shader. But may not want to. What is the use-case?
- I have a player that may fly near obstacles. When it gets closer to them than a certain threshold, it starts blending with the obstacle's color. This would have never been a problem if i had only one obstacle, but player will almost always be near at least 2 of them
How many of them on screen at one time (max)?
- But i will cull those that are further away than this "certain threshold" anyway. So i think it won't get higher than 50 in the worst scenario
- because when there are 50 obstacles around the player, they're 99% dead
You probably want an acceleration structure around this scene data, and a radius to search. Iterating through that many scene items, even once, might be impractical per frame. If you have several 100 K of them.
Although that sounds a bit unweildly. I mean, 100K of them? Really?
Besides, human perception is probably not going to notice the difference if you have a "lag" time for the color change of a few frames.
If you're at, say, 30 fps.
- Just as i mentioned, i don't throw all obstacles into the shader. Only those near enough. I've already taken care of this bottleneck
well, OK, I was going to say more, but nm.
Can you support structured buffers on all your target platforms?
- I'm afraid i don't even know what it is. You can call it my first "real" experience with shaders
Are you targeting older mobile?
- I may sacrifice them if absolutely necessary, but preferably yes
A structured buffer would work well.
https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-object-structuredbuffer
You need SM 5 support/DX11 (or I guess on some cards, DX11 running on 10 level hardware, sm 4.5).
But you could also pass two arrays, one for positions, one for colors
You'd set them each frame
- Will look into it, thank you. Can i ask you for an "in a nutshell" version of what it is and how it works?
A StructuredBuffer is similar to an array, but it has elements that are a struct. So for the relevant data types that are common across C# and shaders, you can use a struct to hold the data and access the elements of the struct at each array element. An array of structs, basically.
So you can define
float4 WSlocation;
float4 Color;
}```
And create a structured buffer in C# (they're called compute buffers in Unity, but are not limited to compute shaders only).
https://docs.unity3d.com/ScriptReference/ComputeBuffer-ctor.html
I used float4 rather than float3 because GPU's like things aligned on a float4 boundary. And you can use the .w component to pass additional data if you wish. But you could also break that out into a float3 followed by a float, but you may as well read all 4 floats at once for efficiency.
You can then access elements by index. In the shader you define the buffer
StructuredBuffer<MyObsitcle> obsticles;
and then you'd access them in the vertex shader I'd suppose (faster than per pixel).
if (obsticles[i].location - myLocation) > threshold) {
accumulate color change, blah, blah
}
end loop stuff```
And you'd pass that accumulated color change to the fragment stage in an interpolator perhaps.
- I see. Awesome, thank you a whole bunch
One more thought.
If you need the color changes per pixel or per polygon, what we discussed makes sense.
But if you want it per-mesh, you'd only have to pass the net-color change to the object, since you're passing the entire dataset in C# anyway.
In that case, no reason to burden the shader with the overhead.
- It's per pixel for sprites. I originally thought to pass colors to vertices and let the interpolators do the job, but as more and more implementation details appeared i decided to go with fragments instead
Up to you. It's similar to pixel-lighting vs vertex lighting, I'd suppose.
Vertex would be faster if you can pull it off
And yet...another thought....just for fun. 😉
So there is a possible implementation difference between arrays and structured buffers in that you probably get better cache coherence by breaking out the positions into their own array (packs all the locations together in memory)...and having another array to just hold the color or whatever else. @tropic badger I doubt it will make much difference in your implementation since you have one player object that you need to do this for. But if you were shading everything in the scene this way, having the location accessed faster in your conditional would be an advantage.
hi, in the newest unity version there isn't a PBR graph option when creating a shader anymore, what is the equivalent now?
You mean like "lit graph"?
yes
You're not the first. See post #5, and really the whole post
https://forum.unity.com/threads/pbr-shader-doesnt-show-up-in-the-shader-graph.1030996/
ok thanks
Could anyone tell me why my triplanar shader does this when i input object space into the position node?
its like it works on surfaces that are horizontal, but not vertical
Triplanar mapping works by projecting the texture from each axis, blending based on the normal vectors. You'd need to set that Normal Vector to object space as well so it blends correctly.
Thanks for this 🙂
I did notice that now in order to get this shader compatible, I had to change the Canvas to Screen Space - Camera and drag my main camera in. Thing is, I switch cameras using this transition and now its acting a bit weird...
Is there a way to use this shader with Screen Space - Overlay istead of Screen Space - Camera like I could in 2019 Unity?
It's a UI shader? I don't know anything about how those need to be made but they're not as straightforward as other shaders apparently
Thanks now I understand! What would be the best way to do that? 🤔
Ah fair enough...Might just need to figure out how to change the camera at the precise time then. Thanks though
Nevermind I figured it out, thanks!
okay i think it's because of the fact that i'm using an outside variable as a seed for the random number generator. is this related to using urp or the math i'm doing on the seed? does anybody know a workaround for this or how possibly to fix it at all?
here's my graph and you can see the texture flickering still in the preview
@meager pelican hey, may i borrow you if you still recall the problem of mine?
- I did the buffer thing and double checked that the data is passed correctly (see screenshot), so the fault must be on the shader's side. In a nutshell, i define a float4 that defaults to the player color, and in case distance from the fragment's world position to any value in the buffer is less than something, i set the float4 value to the obstacle color. The code is below
- Setting world position of a fragment
o.worldPos = mul (unity_ObjectToWorld, v.vertex);
- And the actual code
// sample the texture
float4 col = _PlayerColor;
int width = buffer[0].x; // 0th element contains the buffer's length
for (int index = 0; index < width; index++)
{
float dist = distance(i.worldPos.xy, buffer[index + 1]);
if (dist <= _BlendignRadius)
{
col = _ObstacleColor;
break;
}
}
return col;
- OMG. All this it was a tiny typo in "_BlendingRadius"
- I hate it
- But now it does the opposite. As if the player is always near an obstacle
- Turned out to be another type, damn it. Fixed, sorry for disturbing
Hello! anyone familiar with this kernel error: "unity kernel keyehistogramclear error"
occurred when I switched build platform to WebGL 2.0
From my understanding its probably an incompatible post processing effect but no Idea how to fix
- I've got a blending problem. On the screenshot, you can see "lines" between the circles which i want to avoid. I don't know why do they appear. My shader algorithm is as follows:
Before drawing a blended color, check if distance from this fragment to the new circle's center is lower than distance to the last circle's center;
Upon drawing, return a lerped color and update the last distance info;
- On paper it should work, but in reality it doesn't. How else can i blend these circles, or change in the current approach to make it work?
- Afaik webgl 2 doesn't support compute shaders. Does your game use any?
I have a toggle in my shader, [Toggle(DO_REFLECTIONS)] _DoReflections("Enable Surface Reflections", int) = 0 and it's included in my shader_feature pragma, #pragma shader_feature _PALTYPE_NONE _PALTYPE_INDEX _PALTYPE_MAP DO_REFLECTIONS
despite this, toggling this on and off has no effect on my shader,
#ifdef DO_REFLECTIONS
float2 morph = tan(pow(o.Normal, 5)) * 0.1;
float2 reflUV = _ScreenParams.xy * _ReflTex_TexelSize.xy * (IN.screenPos.xy / IN.screenPos.w);
float2 bgUV = _ScreenParams.xy * _ReflBG_TexelSize.xy * (IN.screenPos.xy / IN.screenPos.w);
float2 reflOffset = _ReflTex_TexelSize.xy;
float2 bgOffset = _WorldSpaceCameraPos.xy * _ReflScroll * _ReflBG_TexelSize.xy;
reflUV = reflUV + reflOffset + morph;
bgUV = bgUV + bgOffset + morph;
fixed4 refl = (tex2D(_ReflTex, reflUV ) + tex2D(_ReflBG, bgUV )) * tex2D(_ReflMap, IN.uv_MainTex).a;
o.Albedo += refl;
#endif
this code never runs regardless of if the property is toggled
any idea why this could be happening? Something im overlooking maybe?
Maybe not the fix, but you should use a float property with the Toggle drawer : https://docs.unity3d.com/ScriptReference/MaterialPropertyDrawer.html
tried switching back between float and int with no difference
ill leave it back on float though
Have you tried with #pragma multi_compile __ DO_REFLECTIONS ?
that fixed it, perfect
mind if i ask what that does exactly? Does it compile a second shader for the reflections on/off, and the toggle just changes between them?
Basically yeah
I'd guess that it didn't work before with multiple keywords being specified (_PALTYPE_NONE _PALTYPE_INDEX _PALTYPE_MAP) as one of those might have been enabled, so took priority over DO_REFLECTIONS maybe
https://docs.unity3d.com/Manual/SL-MultipleProgramVariants.html
shader_feature is to declare "sets" of keywords, that are mutually exclusive (only one is enabled at the same time)
multi_compile is to compile the shader once for each of the keywords in the list
right, i have an enum type with some logic running before the reflection check to change the way the colors are processed
i see, so should i remove the toggle from the shader_feature pragma and just leave it on multi compile?
There's also a [KeywordEnum] drawer which might work better with multiple keywords on the shader_feature. It's in that same docs page Remy linked
yup, that's what im using for the palette property
i just needed a seperate toggle for reflections
You could also use a dedicated line for #pragma shader_feature __ DO_REFLECTIONS
Ah okay. If you need each of those palette shader variants to include the option to toggle the reflection it would need to be specified under a different shader_feature/multi_compile
so every seperate property would need it's own line for that, i get it
#pragma shader_feature DO_REFLECTIONS should even be enough
The biggest difference is that shader_feature will compile only the required variants (depending on the materials that are rendering), when multi_compile will compile all possible combinations
Basically use shader_feature wherever possible except if you need to adjust keywords at runtime, then use multi_compile
Hey @regal stag , while you're around, I'm a bit curious.
Have you worked a bit with shadergraph and the built-in pipeline ?
The scene color node doesn't work there, and I kind of need it.
The workaround I have in mind would be to use a commandbuffer on the cameras to copy the backbuffer to a RT and assign it to the _cameraOpaqueTexture shader variable.
What do you think ?
I've mostly stuck to URP, but am aware the SceneColor doesn't work in built-in. Afaik the code sampling _CameraOpaqueTexture is still there, so if you can generate the texture through the command buffer it should work
I guess try and see XD
Yea, guess it's just a cmd.Blit and cmd.SetGlobalTexture right?
That's the idea yes. Maybe with some more optimisations accomodate multiple camera and share a common texture between the blits.
Bump
Could you paste here your code ?
I'm a bit confused by the text explanation 🤔
- The entire shader file or just the blending part?
Maybe just the blending part to start with
- Sure, let me turn on my laptop. Will laste it here in a minute
The result here looks similar voronoi/worley noise. I guess you could instead calculate the circles w/ falloff then combine them by taking the maximum, or add & saturate?
float4 col = _PlayerColor;
// this buffer contains red circles positions
// 0th element contains the buffer's length
int width = buffer[0].x;
// anything closer than _BlendingRadius is solid _ObstacleColor
// anything between upperBlendingRadius and _BlendingRadius is lerped
float upperBlendingRadius = _BlendingRadius + _BlendingLength;
float lastDist = upperBlendingRadius + 1;
for (int index = 0; index < width; index++)
{
int i2 = index + 1;
float dist = distance(i.worldPos.xy, buffer[i2]);
if (dist <= _BlendingRadius)
{
col = _ObstacleColor; // solid color
break;
}
if (dist <= upperBlendingRadius && dist < lastDist)
{
float blend = (dist \- _BlendingRadius) / (upperBlendingRadius \- _BlendingRadius);
col = lerp(_ObstacleColor, _PlayerColor, blend);
lastDist = dist;
}
}
- This is basically what i'm doing. But i can't take max/min of color, so i take it by the distance. You can see it in the code above as lastDist
Just loop for all elements with
lastDist = min(lastDist, dist)
And calculate the color after the loop ?
- Isn't it just a shorter version of my messy code? I also pick the smallest dist and do the calculations only after the smallest one is found
blind coding :
for (int index = 1 ; index < width ; index++)
{
float dist = distance(i.worldPos.xy, buffer[index]);
lastDist = min(lastDist, dist);
}
float blend = ( lastDist - _BlendingRadius ) / (upperBlendingRadius - _BlendingRadius );
blend = saturate(blend);
col = lerp(_ObstacleColor, _PlayerColor, blend);
You are always blending with dist I don't see any usage of lastDist here.
If min works the same, could maybe try the opSmoothUnion function from IQ's distance fields page - https://iquilezles.org/articles/distfunctions/#:~:text=float-,opSmoothUnion,-(%20float%20d1
- I read dist only when it's less than lastDist, so they're equal here. Now that i moved it outside the loop, it suddenly stopped working at all. And rider complains about not being able to undo
- This actually worked like a charm lol. But just as i was guessing, it's completely identical. Circles are still visually separated
Im starting to think it's some perceptual contrast brain issue ^^
- Is k a 0-1 value, as in lerp? I didn't find any explanation after a cursory review
iirc, it can go out of this range, in that case the operation will extrapolate the values
Can you try to output
col = frac(blend*10);
just for couriosity
- Sure
The values seem correct, so I'm really thinking that the issue is from how our brain percieves gradients
I'm not sure what the range is exactly. Likely controls how smooth the result is but you'll have to test some values.
- Alr then how do i fix people's brains
Oh sh*** I've that quesiton to fast and though k with the last lerp argument 😅
I have some ideas, but they are not ethically accepted.
- I need them
- Wait, can it be filtering mode?
- Like bileniar or what is it by default
No, you're not doing any texture sampling here
I wonder if some gamma correction might help.
like doing
blend = pow(blend, 2.2)
or
blend = pow(blend, 0.4545)
(one is linear to gamma, the other is gamma to linear, and I can't for the sake of me remember which is which)
- Will try this and cyan's suggestion right after i finish eating. Sry
- Unfortunately neither removed this separation. pow 2.2 seemed to make things better, but didn't help much. Thank you for your effort anyway
Technically you could blend those colors additively, but I suppose it would miss the point of the shader. 🤔 Alternatively, you could blend the whole texture again.
Our brain sees it like this mostly because our perception is based on contrasts. When going away from the center of the circle the color becomes weaker and weaker, and then BOOM, it's increasing again. It creates an illusion of some concave gap.
- I doubt that it's an illusion, because i clearly can shot it wiht whatever screenshot tool, pick colors and make sure that they differ. And they do
- But as i zoom in, it disappears. Okay, it is
Well, the edge definitely exists. But our brains kinda exaggerate about it. It could be seen as 2 circles cut on the edges and placed next to each other, but our brain interprets the edge as some sort of whitish line.
Hello there, I am using full screen shadergraphs for the first time, and I am wondering how can I tile a texture according to the screen width and height so It doesn`t streetch irrregularly?
Does anyone know how to get the UV center in shader graph when working with sprite atlases? I've looked online and cant seem to find a solution besides passing metadata through a custom property.
you need to tile the x and y components the same so that it doesn't stretch
the uvs center is always 0.5, 0.5
what if you change the colorspace of the texture from linear?
just as an idea
- I don't have any, i guess. It's a default sprite with default square
oh I thought you were rendering to a render texture, maybe try switching to gamma colorspace in the project, but that wrecks every color
Is there any way to render a Shadergraph always behind another shadergraph?
They are both set to opaque at the moment.
I have tried adjusting the Render Queue on the materials but it does not seem to change anything.
Any idea?
Render Queue is something completely else
hi ,
how do I save shader with frag function like this on a png file ?
fixed4 frag(v2f i) : SV_Target
{
half4 color = half4(i.uv, 0, 1);
return color;
}
Do you want to have it outside of unity?
I want to save it in the asset / save , directory
but I dont know how to tell c# to capture the entire output of the shader , its not a texture
then you should use a renderTexture
could you please give me a code example ?
its exactly what you have above but the output is not the object but a renderTexture instead
I havent uesed renderTexture before , is it something like that ?
fixed4 frag(v2f i) : SV_Target
{
half4 color = half4(i.uv, 0, 1);
return renderTexture (color);
}
no
it seems to be part of c# rather than shader
https://docs.unity3d.com/ScriptReference/RenderTexture.Create.html
well yes also I guess, but there he is only creating a render texture not writing to one. You can create a renderTexture in the project tab or inside of c#, but then to write to a renderTexture I would use a compute shader
its weird, not sure how to connect both words together , how do i even mention the created renderTexture in compute shader ? , i will keep googleing for an example coz I cant quite understand how connectiong between those two works
Here watch this, here he is writing to a renderTexture inside of a compute shader. https://www.youtube.com/watch?v=BrZ4pWwkpto&t=253s
i created grass in unity . this grass has shader in it just for texture rendering. i placed the grass over terrain with unity terrain trees. But when i run the game fps drops from 300 to 10 fps. the grass has lod system and doesnt take much tris or verts. i think the shader running all at once overiding the culling from lod system. what to do
how much grass in it, is it bilboard grass or individual grass? How many vertecies does each grass blade have.
are you painting your grass on unitys terrain?
placed around 100000 grass using mass place trees. grass is billboard and have around 6 verts.
The object is not actually behind in 3D space, so that's why I want to force it to be rendered behind, regardless of depth. I have tried all depth test settings, I can't get the result I'm looking for
you shouldn't use that for grass
Grass should be painted in the details tab
even when i painted grass using trees tab . the perfomance reduce
not tree, details tab
wow. its worked . very much thanks. thank you
thanks a lot , but is it possible to do the same in fragment shader ?
im still learning , i still dont know the difference
i didnt even know that there are types
When using a sprite atlas UVs don't use the full 0-1 range for individual sprites, so the center is different
compute shader would be most efficient and would give you most control.. maybe you could also do it with graphics.blit but with that you are copying a texture to another as well, so not sure how you could do it properly and as well as with a compute shader
yeha i tried with graphics.blit the other day but I couldnt as the output is just a color, mainTex is always null, i didnt know how I could convert the whole to texture and save it somewhere so i can copy it
Alright... managed to make a basic water shader...
a shader by default does not really output a texture. if you supply the gpu with a 3d model, a target texture, a shader, and resources for the shader (such as textures, matrices etc..) it will first transform the model into camera space then rasterize it. when the gpu rasterizes a certain amount of pixels will be calculated and written to target depending on the triangles size and position. You are assuming the gpu just magically spits out pixels from a fragment shader into a texture without any or minimal input data
so, when you are writing a fragment shader you are not outputting pixels or their position, only calculating their color depending on the already assigned pixel position when the fragment function starts executing
what Graphics.Blit does, is it renders a fullscreen quad 3d model with the shader you supply, thats how you get the texture
when you create the RenderTexture or Texture you need to assign the size of it, the gpu cannot change the width and height
also remember to copy your render texture to a texture2d if u r using that, and also call ReadPixels on Texture2d to copy back to cpu memory from gpu memory (so you can save it as a file, the gpu and it's memory is fast but you can't do IO things there)
I have made a shader but the shader dosnt run in editor mode, only when i play the shader runs
how do i make sure it always runs
it usually always runs please be more specific what have you done?
its a nice start
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
its not animating
it won't animate by default
you have to turn it on, there's an answer in what I linked
yeah thanks got it
btw if u end up with the compute shader route I have a full blown image editor using Unity and compute shaders, you can steal code from there if u want https://github.com/Peter226/HueHades
Just wanted to add since it is a fullscreen qaud some
transformation matrecies are skipped, so its a allready transformed clip space quad.
Awesome , thanks a lot 🙂
Technically it depends on the shader. I believe Graphics.Blit overrides the model/view/projection matrices (to identity matrices), so any shader that uses the object->clip transformation still works.
But ideally yes, you'd use a shader that outputs the vertex positions directly to clip space though to avoid those unnecessary calculations. Newer blitting functions also require that.
Can someone please help me why I can not put Out from Branch node into Alpha clip threshold node and how to fix this?
Vertex ID can only be used in the vertex stage. Perhaps you want to pass the result through a Custom Interpolator block first?
(This shows how to set one up if you aren't familiar : https://www.cyanilux.com/tutorials/intro-to-shader-graph/#custom-interpolators)
Thank you, I will have a look at it now
Did they ever add Stencil to shadergraph URP?
thank you very much, it really helped me
how do i randomly generate a number from 1 and 0, in shader graph
There is a Random Range node, but you'll need something to use as the seed, depending on if you want a random value per vertex, fragment/pixel (such as Position or UV), or just a random value for the entire object (i.e. float property, or based on pivot position from Object node)
yeah ive seen that but never figured out the seed thing. i just need something that changes to a one or a zero with a random interval
Sounds like you want to use time as the seed, and map that to 0 and 1
How can I get a shader to change the colors of different parts of the surface? I want to be able to apply this effect but not just between objects, but between each pixel of every object.
Sorry, I bet it would help if they were the same color and I exaggerated the effect
is it possible to include a hlsl file from a package
i can't seem to correctly get the right directive location
How should that even look like then? Like stripes?
EXACTLY
YES YES
ANY IDEA HOW I'D DO THAT
and the colors should change depending on the world space position of you player?
Not really. The colors in the video are changing because of the player's closing velocity towards those objects.
I mean this is gonna give you your stripes: ```cs
float stripe = (1+(sin(i.uv.x)) / 2;
How would I apply that? This is just a single float, so do I apply that to whichever section in the shader's _BaseColor's RGB?
You can apply it however you want to
Right, but I don't understand what exactly I'm supposed to do with it
well I am still a bit unsure what exactly you want to do. So just put it into the base color, see what happens and then do the adjustments you need to make.
Ok. Thank you very much, I'll see
Sorry, I should have specified that I'm using the Universal Render Pipeline, so there is no i.uv in there.
That was just a code snipped/example adjust it to work for any pipeline you are working with
If UV's are the positions of textures, then what is i? The mesh?
How are you making your shader hlsl or shadergraf?
I'm using the Universal Render Pipeline, so I'm editing it by adding the _BaseColor to a percentage to get the effect in that video. So, I think I'm using hlsl.
rend.material.SetVector("_BaseColor", new Vector4(originalColor.x + redShift, originalColor.y, originalColor.z - redShift, originalColor.w))
thanks
can anyone help with the shader graph thingy? so basically i wanted to recreate this reflection effect https://www.youtube.com/watch?v=ym1K3of3pys and in minute 6:15 he talks about the "sprite unlit master"... now where the hell is the sprite unlit master?
Learn how to create a water refelction effect in Unity
Download the project starting files at https://drive.google.com/open?id=1OUOcx75_fm-1yZb6rSt8siWEYWJrdUe-
Inspired by Binary Lunar: https://www.youtube.com/watch?v=O1lRGKfCi9o
Get my latest Udemy course 'Learn To Code By Making a 2D Platformer in Unity & C#' at https://www.udemy.com/cours...
and whats the difference between lit and unlit, and should i use lit because i use light in my game?
you just said it yourself lit has built in lighting unlit doesn't
alright
but then where is the sprite unlit master or in case it exists i assume there is also a sprite lit master
where is it?
are you refering to that node? When you create a shader graf shader it will automatically have an output node.
its not there
yeah thats your output node, they have changed it up a bit, in the past it looked like above in the video but now it looks like this, but it is the exact same thing
but it doesnt do the same thing
yes it does
but according to the video this should give me a mirrored thing
this is in lit
i can try it out in unlit too just to see if im just horribly stupid xD
you need to put it into the base color not the sprite mask
well thats how he is doing it and I do not have more info than what you have provided me
yeah i dont know, i did it exactly like he did, but for me its not even showing in the preview
Does your object have uvs, does your renderTexture actually have content, what is showing just a simple white quad or?
aaah i got it
the problem was acually the difference between unlit and lit
i suck T-T
lmao but thank you for the help
but now its still not showing the thing in the editor, it just shows the thing in the prebview
hello, i am new to shader graph.
I have a grass patch that I want to color with a gradient, which I do via lerp, working fine. I have the vertex color going from 0 to 1 at the top, which I use to interpolate. I also want to add some manual AO / specular highlights, by defining a threshold percentage for each. If AO is set to 15%, I would like to multiplicatively add some color to all pixels that have a vertex color of < 0.15. How would I achieve this?
(custom lighting)
how would i turn on shadows for point/spot/... lights? (shadows for main directional light work, but for the rest they dont)
shouldnt the selected pragma do that?
You also need to use a function which calculates the shadows.
GetAdditionalLight(uint i, float3 positionWS, half4 shadowMask) rather than the version without the shadowMask parameter. If you don't need to actually support the ShadowMask baked GI mode, can just use half4(1,1,1,1) for that param.
And obviously make sure you're using light.shadowAttenuation in your calculations.
yes i am doing that in a loop of GetAdditionalLightsCount()
okay i uncommented the main lighting so everything is there
Would probably involve a Comparison & Branch node
i use the same function for main as for additional, so i use their attenuations too, but there arent shadows in additional lights
thank you so much, i just needed a nudge in the right direction, which is all i needed. thabnks again!
Is shadows for additional lights enabled on the URP Asset? Do you get shadows with the regular URP/Lit or SimpleLit shaders?
okay i got it
yes they are enabled and visible
oh, but the light gameobjects themselves didnt have shadows on (didnt know each light needs shadows turned on, thought that would be on by default)
works now, thanks!
i want my reflection to keep looping all the time, but its not doing that. https://www.youtube.com/watch?v=ym1K3of3pys in this tutorial in about 17:30 minutes in he does a water ripple effect. but for him the texture keeps looping but for me it doesnt
Learn how to create a water refelction effect in Unity
Download the project starting files at https://drive.google.com/open?id=1OUOcx75_fm-1yZb6rSt8siWEYWJrdUe-
Inspired by Binary Lunar: https://www.youtube.com/watch?v=O1lRGKfCi9o
Get my latest Udemy course 'Learn To Code By Making a 2D Platformer in Unity & C#' at https://www.udemy.com/cours...
Do you mean the texture needs to repeat? You can set the Wrap Mode in the texture import settings to Repeat rather than Clamp.
excuse me where are those texture import settings?
a+#
got it
In the Inspector when the texture asset is selected
thank you very much
is there a node that i can use to make the reflection darker than the thing that is being reflected?
Offset the effect by the UV coordinates
does anyone know where i can learn shader code from?
(not talking about shadergraph)
Watch this video in context on the official Unity learn pages -
http://www.unity3d.com/learn/tutorials/topics/graphics/session-introduction
In this live training session we will learn the fundamentals of authoring shaders for Unity and you will learn how to write your very first shader. No prior knowledge of authoring shaders is required. In th...
someone else might have some more resources but as far as I know there isn't really too much
thanks
I would suggest though
learning some tutorials perhaps from places like open GL or places that might teach GLSL
sure a bit different shading languages, but they aren't too different and all of the concepts are the same
Free tutorials for modern Opengl (3.3 and later) in C/C++
for example this is an open GL tutorial that teaches you about doing basic shading
If you are a beginner I can recommend you freya holmier for writting shader in hlsl, or ben cloward if you are writting shaders with shadergraf
you mean the 4 hour video from freya?
yeah
i was watching it before i started watching the current tutorial (the one provided by unity)
problem was that i didn't know that i should tackle introductions to shaders like that
i didn't want to get stuck in tutorial hell
again
if you don't want to get stuck you need to learn how shaders work and not how to write specific things, which I think she does quite nicely
Hi! Is there a road map for shadergraph URP? Quite a lot of basics are still missing and would like to know when to expect them 😁
does anyone know how i can "unpack" a float4 ?
See links in pinned messages
like i wanna get the individual float values of a float4
You can reference them with .x, .y, .z and .w (or r,g,b,a)
I think [index] (0-3) also works (but only for reading, can't set that way?)
that is what i am trying the whole time
wait
nvm
i had the wrong variable name this whole time
capitalization mistake
sorry xD
anyone know why my material's variable is not changing at runtime>?
void Start()
{
Renderer renderer = GetComponent<Renderer>();
crossHairMaterial = Instantiate(renderer.sharedMaterial);
renderer.material = crossHairMaterial;
}
void Update()
{
Debug.Log(crossHairMaterial.HasFloat(this.outlineThicknessUniformName));
Debug.Log(crossHairMaterial.GetFloat(this.outlineThicknessUniformName));
crossHairMaterial.SetFloat(outlineThicknessUniformName, outLineThickness);
}
so like i think i am changing the uniform of some shader but i am not sure its the exact on attached to object? idk
Maybe because you are setting renderer.material rather than renderer.sharedMaterial. Not sure.
But you shouldn't need to clone the material, just accessing renderer.material will create a instance of that material for you.
i've made my own vertex color blending shader. now i want to control the alpha through script. is there something i need to add to that shader to make it work?
The alpha of the vertex colours? Or the whole material?
here an example of what im trying to do, i can hide floors by enabling/ disabling the mesh. but it does not play nice with the tiles ive already hidden. so my idea is to lower the alpha instead. so i guess for the material
forgot to tag
hmm didnt work but thanks for the suggestion anway :p
if I want to do a shader that goes from invisible to red to invisible for damage, should I just create the shader and add it to a material and use that material on the enemy that already has a material?
you will need to reaplace the previous material to the material which uses the shader
am i dumb or is this wrong
im trying to flip it so the bottom half is black top half is white
but one minus seems to make most of it white
Looks correct to me. But that's the linear interpretation of the colours. Perhaps you expect a gamma corrected one, could put it through a Colorspace Conversion node with Linear/RGB inputs. or use a Power node.
are you sure that looks correct
i was expecting a mirror image
why does it look so different by simplying inverting it
Perhaps you want a Negate then before the Saturate, not One Minus
As in Dot Product -> Negate -> Saturate
doesnt work for me you can still see it showing on the dark side of the sphere
trying to get that backside much darker because its too blue from the atmosphere so was applying dot product as part of the alpha
weird
shader graph really needs to show us the rgba values when we mouse over pixels in the preview windows
that would be a god send for debugging
this is my alpha input
and this is what i get
i don't get it
it should be only half a sphere
What blend mode is being used?
unlit transparent and alpha blending
Can you show the whole graph?
What result do you get if you disconnect the alpha and put the Saturate result into the Base Color?
If you rotate around the object, is half of it white pointing in the main light direction?
Is there even a directional light in the scene?
ok it looks more correct rotating the camera
yeh its got a dir light
oh there we go it is working
seems the camera was in a weird position that was tricking my eyes
i thought it was perpendicular to light direction
@regal stag works now, thanks 🙂
how would you set a shader to work specifically for a camera?
like
i have some overlay effects on my 2d game, so things like water makes the background wavey and stuff.
but now that im trying to put together splitscreen, those shader effects will only show only on one screen, and all other screens will still show the same first screen, instead of their own individual screen
do you mean post processing?
because that is what your describing pretty much
yeah, sorry, i'm not too familiar with the terminology 😅
but yeah, was hoping to get post processing effects to be different between the splitscreen camera.
i think because of it, the other players will get the same exact render as the 1st screen. so it ends up not looking through the other camera
at least, that's what i suspect
Hiya!
I want to make an uber shader for my game. I want to use this shader for every single material in my game and I only have two necessities other than PBR rendering: emissive fresnel and dither-based transparency (material is opaque, alpha cutoff on dither)
I know how to implement the entire shader but I'm wondering- is it better to use keywords to disable dither transparency and fresnel emission (but lose SRP batching due to keywords) or keep it all enabled all the time and gain full SRP batching?
I think someone will have an answer but I say do some experiments to test it
I would think the SRP batching would be important to keep, but enabling all of the keywords can and might lead to performance degredation down the line with features that you might not be using but are enabled anyway
Gotcha.
I'll prep the uber shader and start replacing the shader in my materials in the meantime.
Sorry for bringing this up again, but I still haven't found a solution. Does anyone know how to deal with sprite atlas UVs?
sorry, i don't know
i think i might have something from a previous project, gimme a tic
Any luck?
you multiply by -1 lol, if you do oneminus 1 - (-1)=2
oh nvm
if you saturate to 0-1 then one minus you get 1-0 which is surely the same
i got it working in the end anyway
how is "1-clamp01(x)" and "-x" the same?
i didnt say they were you didnt read what i said
i cant have negatives so i have to saturate
negative alpha has no meaning
I don't feel any irony
what?
saturating first as suppose to second makes no difference
order of operations wont change much
but then you misread what I wrote
what you wrote was not relevant to the conversation your comparisons are not equal
you were trying to flip this with 1-x
which is not just flipping it but adding one
I wrote nvm when I saw cyan recommended -x too instead of 1-x
saturate then one minus vs one minus then saturate is the same is what im trying to say
but how is that relevant? did I say that's not it? you wanted to achieve this by your description
I don't understand you
but -x is just flipping things how does that fix the problem
i can do that just by swapping the dot product inputs
"im trying to flip it so the bottom half is black top half is white"
literally what you said
yes which means 0 and 1 not -1 and 1
Okay I'm just giving this conversation up, no point
its not hard to udnerstand that one minus maps -1,1 to 0,1
-x doesnt change anything
substract by -.5 and then flip it with -
OK, so a sprite atlas is "just" rectangles within a rectangle.
So compute the size of the single-sprite triangle. Then, to get UV's for it, figure out the % thru that you want for that range. In either direction. So if the sprite ranges from pixel/% of (0.5 - 0.75, .5. - 0.75) of the sheet, you can compute a UV by taking the range of values (0.75-0.5 = 0.25) in X and Y and then deciding how to map that to your 0 - 1 range you want for a logical-UV. Or vice versa.
Like @prime shalewisely said, bench-marking is the way to go here. I mean you're making a decision early on that will impact all shader calls in your game, so testing is paramount.
That said, if your "switches" are uniform, you probably won't have many problems. There are some tricks. Try to avoid shrouding texture reads inside an IF (but definitely benchmark this both ways) usually you'd put them as close to the "top" as possible.
The switch IFs will be uniform if they're even needed, so it should cause no to little divergence in the execution path of ALL threads on that mesh, so there won't be much performance hit as compared to divergent paths.
Use the [branch] attribute, although modern compilers probably ignore it in most cases.
Best to test on a range of platforms, not all shader compilers/platforms handle things the same way, particularly between desktop and mobile.
I would think you want SRP batching. In your case, though, you'd only have two switches and 4 variants, If F is fresnel and D is dither, you only have F-D-, F+D-, F-D+ and F+D+, maybe not too much of a maintenance nightmare, particularly if you use includes. You can then swap the shader in and object/material at runtime. No ifs or switches necessary, and you'd keep batching of the 4 groups at least.
Or, it might work out that you don't need any IFs at all!!!!! Just let "the math" do it, and calc all attributes but in some cases the fresnel % will be 0 and the alpha will be 1 so solid dither. The real trick isn't the fresnel, it's the dither, since you MIGHT use a dither texture. But in reality you should be using an array to hold the dither cut offs, not a texture. That reduces sampler needs too, and avoids any dependent texture reads. This gives you the math at all pixels, but these days simple math might not be too bad.
/ramble
-2cents-
You can just use remap node if you are using shadergraph
where can enable this option for Mask Mode on local volumetric fog? I'm watching a video where it's visible in the inspector, but not in mine
Maybe it's a newer version? check if you have any updates for hdrp, in the documentation it mentions the feature starting from the 14.x.x versions https://docs.unity3d.com/Packages/com.unity.render-pipelines.high-definition@14.0/manual/Local-Volumetric-Fog.html
oh yeah that'll be it
would something similar be possible in a previous version? i'm not sure how practical changing versions would be currently
You could use a 3D render texture and render something to it using a compute shader, but that requires scripts and HLSL code
But I'd say create a backup of the project, test out the newest available version, and see if everything works
That would be the easiest and probably the best thing to do as you are getting other new features and improvements
Actually I was just wondering how the material is rendered in 3D, and found a 3D Blit function, you could use this to render the mask material to a 3d render texture https://answers.unity.com/questions/1431871/graphicsblit-with-a-3d-texture.html
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
I guess it's just rendering a quad for each layer
you need to do this every frame, as that's how the material mask type is done too
i recently switched from standard RP to HDRP and i'm trying to update my shaders, but no matter what i can't seem to refrence HDRP at all
for example i'm getting an error that looks like this: Couldn't open include file 'Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPass.hlsl'. at line 24
does anyone know if they changed or what is happening because ive tried every possible pathway
hi , quick question
how do I add header on the variable like in c# ?
// [Header("title")] <======================== ???
_MainTex ("mainTex", 2D) = "blue" {}
All the attributes you can add are listed here:
https://docs.unity3d.com/Manual/SL-Properties.html
ShaderLab doesn't have an attribute like Header.
Sorry, that's wrong. There is one, but not listed on that page.
[Header(A group of things)] _Prop1 ("Prop1", Float) = 0
It's listed here, alongside [Space]:
https://docs.unity3d.com/ScriptReference/MaterialPropertyDrawer.html
Thank you ❤️ ❤️
Hey guys, I need help with a water shader here.
This block is meant to move a normal map along the sprite to simulate light movement
However when I change Normal direction in the editor the texture gets all streched out
So I got confirmation that the new Adaptive Probe Volume system was integrated into the "Baked GI" node in shader graph, but if I do a simple passthrough of the Baked GI node to the emissive value of the right sphere, its clearly not showing any APV data unlike the generic sphere on the left. They said its in versions 2022+, and I'm on the latest 2023 release.
Is the normal texture set to clamp maybe ?
Also, to controll the normal influence, use the "normal strength" node instead of multiply
Well that's just nice. Now's fixed thx
Is it possible to let a triplanar worldspace texture drive vertex displacement? I would like to create an array of cubes that change their height depending on a worldspace texture.
sample the texture with the vertex position as input
Not sure if I understand. The Triplanar node provides the texture in world space. But I cannot drag the color values into the vertex position input. Unity doesn't allow that.
Oh I was thinking of using world position as input to this:
https://docs.unity3d.com/Packages/com.unity.shadergraph@16.0/manual/Sample-Texture-2D-LOD-Node.html
Or this:
https://docs.unity3d.com/Packages/com.unity.shadergraph@16.0/manual/Sample-Texture-3D-Node.html
the first one I know is in the vertex stage
I think the triplanar node might only operate in the fragment stage
Can you plug the output of this into the triplanar node?
https://docs.unity3d.com/Packages/com.unity.shadergraph@16.0/manual/Sample-Texture-2D-LOD-Node.html
not sure how the triplanar node works exactly
Hello, I am trying to Lerp vertex position from TapPosition to the origin vertex position over time(TimeElapsed updated in code). TapPosition is initialized in code to the tap.transform.position. I don't understand why during runtime(and preview) starting position of the Lerp is not where Tap is. I have tried different space options Object/World configs but it didn't help. Any idea?
That doesn't seem to work. The Triplanar node only outputs a color.
I would have to get some sort of "world space UV" for the Sample Texture2D LOD node.
Yeah it outputs a color but I'm saying using the sample texture2d lod node as the sampler input for it
If you only need the heights of the cubes (y axis) to change you should be able to use the Position node (World) -> Swizzle "xz" into the UV port on the Sample Texture 2D LOD.
Triplanar is only needed if you need to project the texture from each axis.
Just to clarify what I want. I'd like to create a Pin Art effect.
the point of Sample Texture2D lod is it samples a texture in the vertex stage
there's no actual difference between "colors" and "positions/directions" btw
they're all just numbers
the issue is whether the various nodes are allowed to live in the vertex stage or not
tap.transform.position would be in World space not Object. Either use the Transform node to convert it, or convert it in C# first.
I'm going to try this.
Thank you, it helped ❤️
Thank you! That worked!
Here's the graph. For some reason I cannot use the same Texture as input for vertex and color.
Could you please suggest how to Interpolate it so it is fully interpolated after e.g. 1 second? So the timer works separately for each vertex
Hello there,
I got this problem, when I upgraded my universal render pipeline, all my UI components with the shader UniversalRenderPipeline/Particles/Lit literally disappeared from my camera due to the distance.
It's like now there is a distance component in the shader that fade away the particles with this built in shader.
So here is an example with the scene camera next to a star made of this shader on my UI.
And there is at the bottom the game camera that i'm dragging forward. We can see that when it's very very close the particle effect appear again.
However I need this camera very far, and it worked properly before.
Do you have any idea of what URP broke in the shader and how to make it work properly again ?
Nevermind, got it, I had to deactivate the fog in Lighting/Environment
You can but you have to use the LOD version of the sample texture node for the vertex stage because partial derivatives wont work there meaning they cannot be used to figure out the LOD level automatically I think
how do you make one specific object in the scene glow in post processing
use bloom
right but bloom applies to the whole scene
so wasnt sure if there was another way without post processing
you can make an object with a material that has a high emissive intensity (and a bloom with a high threshold, and that object can exceed that threshold intensity wise)
beyond that you'll have to look into a more custom way
Hey everyone 2D sprites arent affected by lighting in the URP. Im not very familar with shader graph/code if theres anything out there that could help... please point me to it.It would be much appreciated
hm i see ill look into it
anyone got any ideas on this?
hi,
i wonder if it's bad to have 20-30 [Toggle(KEYWORD)] in one shader , isnt it better than if - else ?
it can be bad
and yes it would be better than if else
because if-else is dynamic branching
keywords are static
but
with those keywords you are effectively forcing unity to compile MANY variants of that same shader
I would first ask, what the hell are you doing if you need to have 20 - 30 togglable keywords? @pale python
with the math I think its like to calculate permutations it would be 2^(amount of togglable keywords that you are compiling)
so i.e. you have 30 shader keywords compiled
2^30 = 1,073,741,824 variants
or
2^20 = 1,048,576 variants
well , its a shader but with lots and lots of options , each option gives a completely different result and really creative but im concerned about the performance of the shader after using 30 keywards
that doesn't really answer my question though, what shader is this?
like I said, with all of those keywords if your compiling them using the shader_feature_local pragma is a ton of variants
surely with whatever you are doing you can cut down on those variants
oh , i dont really know the difference but the example i saw online was #pragma so i used it
well either way it needs to create a variant
it will bog down your build times and have a memory cost (if I recall?)
#pragma shader_feature_local NAME
oh , but not to much i suppose , right ?
also if it's not bogging down the runtime performance , i guess that is ok , correct ?
ehhh I wish I knew the numbers but I have a feeling it would also incurr a potential runtime cost as well
because a different shader variant is basically a completely different shader, which I think can increase draw calls
but again, what shader is this that would require this large amount of keywords?
surely whatever the heck your trying to achieve there are plenty of ways one can optimize and cut down on the amount of variants you would need to compile
from the unity docs
well , it's a shader with lots of options , like it can achieve results like gas, liquid solid and even tentacle , but i guess i could use it as a drawing tool than a shader and as soon as i make my decisions for the shader , i could just duplicat it and delete all the extra keywords and all other if-else statements.
yup!
double checking myself with the docs I geuss yes runtime costs will be minimal - none with the keywords, but you will increase memory usage and loading times having to load all of those MANY shader variants
I would try to break up your shader perhaps in different shader types to reduce the amount of variants
for example with whatever the heck you are doing, you could have a "gas" shader that is specific to rendering this gas and has features specific to it
and same for the other kinds
rather than one massive "ubershader"
i love the fact that i can change some values and make a much different results but now I understand the cost of that
I will take ur advice , but I'll keep all the keywords in the original shader only just to help me imagine and duplicate and clean up the shader as I make a decsition
sure yeah, but for the final results I'd advise you to avoid going crazy with the amount of keywords and features you can toggle because it will come back to bite you
Thank you so much !! ❤️ ❤️
I think that _LightColor0 gives you the light color premultuplied with the intensity.
or if not you can get it through c# and then pass it over to you shader manually
I think so
im new to shadergraphs and wanted to apply a dither to my character. I have it working but how come the docs say its commonly applied to the Alpha Clip Threshold?
https://docs.unity3d.com/Packages/com.unity.shadergraph@6.9/manual/Dither-Node.html
I plugged it into the alpha before reading the docs and it seemed to work fine. Is this just a performance difference?
if you use alpha clip your object doesn't need to be transparent type.
this is useful if you want your object to write to depth
When using a custom shader for instanced rendering, is it possible to not pass a list of matrices, but instead calculate the matrices in the vertex shader (using positions etc)?
Thanks in advance guys
are you using drawmeshInstanced? also why?
- Yes
- I need to calculate 10's of thousands of them, and I would do a prepass in a compute shader, but it needs to run on the web (as far as I know Unity WebGL does not support compute)
@lunar valley
hm i dont fully understand, because my object is set to opaque and it works when its in alpha or when its alpha clip threshhold
Does webgl support compute buffers? Because in any case I would recommend you using DrawMeshInstancedIndirekt since it is a lot faster.
Not sure, would that make a difference?
yeah it would be wrong putting it into the alpha clip threshold this should simply be a parameter that you can define freely
well instead of matrecies positions would be stored inside of computebuffers
- its like way faster so
For an opaque graph, should be fine putting it in either. Clipping is done if the alpha is below the threshold, so something like alpha - dither < threshold and alpha > threshold + dither should be equivalent.
With a transparent graph, having it in alpha would also affect the alpha blending, so more common to have it in the threshold port.
i actually am learning all this because setting the alpha on a transparent material was causing weird rendering issues. I posted it in #archived-urp but yea i dont see a difference in game by putting it in either
@lunar valley You mean instead of in a texture or what?
And my problem right now is to get the data in the buffer itself, without compute
when was I talking about textures? Also in c# you can use computeBuffer.SetData to feed it an array. This way you don't need a compute shader
You werent, I was just confused what else I would use to feed the data.
I know I can set buffer data from the CPU, however I need to do this in real time for a lot of matrices, so that is not really an option
so the matrecies need to be updated? Well if so and you can't use a compute shader I have bad news for you.
haha I know, that is why i asked if I could do this in the vertex shader using a positional buffer. So without passing the matrices into the function call
what exactly do you want to do, what do you mean with this
If the platform doesn't support compute shaders, I don't think it'll support compute buffers either, those come under the same target. But you can probably use arrays instead (though limited to 1023 elements per call? DrawMeshInstanced has the same limit anyway)
Okay, so lets say I have a buffer with positions and I need to calculate a list of transformation matrices from those positions in order to use it for instance rendering.
So I cannot use compute shaders since it is not supported on the web.
Now, my plan was to calculate the matrices itself in the vertex shader (since the matrices are not needed before the vertex stage in the pipeline), and that way still do it on the GPU
to make a full transformation matrix you also need rotation and scale position is not enougth
I know... However that is not my question. I do not care about scale and rotation for now
I see, the matrecies you use with DrawMeshInstanced cannot be updated on the gpu(vertex shader) do you want these objects move in the vertex shader?
That could work, if I just pass in identity matrices to the Instanced call and then move them in the vertex shader
I was actually asking if you want these instanced objects to move around over time
yes, they need to update in real time
If you don't need to pass in matrices from script, there are instanced draw methods that don't need them
really? Can you link them?
Both do the same thing, the latter is just newer and recommended
thank you
I thought you specifically needed matrecies
hello there, i added block node but it seems inactive guys can you help please
Enable "Alpha Clipping" under the Graph Settings (tab of Graph Inspector window, toggled with button in top right of the shadergraph window)
hello, changing an exposed variable changes all of the materials with the same material as well (the variable has override enabled and hybrid per instance)
so i found out that gameobjects need to have it as an (Instance) like this
but how do i do that? for now i made a workaround script that turns a material into an instance so it can have its own local variables, but im sure i should do that trough the editor somehow
why are your node holes all over the place? 
Pretty sure it's just bugged though I've never seen it myself.
You can create/duplicate the Material asset, but not really possible to create an instance from the editor - that usually only happens at runtime.
oh okay, well i will stick to 1 material and this for gameobjects i want to change separately
I'm pretty sure this will only work until the scene is reloaded (then it'll have no material reference). The problem is that those material instances aren't serialised anywhere.
hm makes sense, i will choose a different approach later, for now i just have one scene while prototyping, but thanks!
I mean that even if you reload the project those materials should be lost. It's not just a problem when switching scenes.
tried closing and reopening unity, they stayed instanced (2021.3.25f1)
Hm okay, maybe they are being saved with the scene 🤔
That would be cool if its the case 