#archived-shaders
1 messages · Page 87 of 1
There is no difference between one sample of 4x4 and 4Kx4K texture. But for pixel shader that covers multiple pixels there is a difference, because in case of 4x4 texture each pixel shader invocation (each pixel) will read almost the same memory location (4x4 pixel texture easily fits in texture sample cache). In case 4K texture there is a lot more memory to read and will be slower in general.
That makes sense. Thank you
I was mostly confused on the sampling process as I was unsure if a 4k texture would be more expensive to sample over a smaller texture. Memory differences aside of course.
Is there a way to get the main camera's up vector in shader graph?
Actually I can just convert Vector3(0,1,0) from view space to world space right?
Sounds like it should work. Pretty sure you can extract it directly from the inverse view matrix too, but not sure off the top of my head
I think it's the second column... so UNITY_MATRIX_I_V._m01_m11_m21?
Hi all, I'm having a bit of a brain fart moment (for a change :-P)
I'm building up a shader graph.......
I'm trying to 'overlay' the orange colour by using the noise as a mask, but for the life of me I can't remember how to get it so that the black doesn't affect the underlying texture.
Could anyone point me in the right direction please?
Result
What the 'rock' should look like.
Lerp is correct but while the mask looks black in the preview, there are negative values, resulting in the blue. You need a Saturate node before connecting to the T port to clamp the value between 0 and 1
Ah, yeah that's the one. As soon as I read that word I remembered. lol. Thank you 🙂
@dim yoke
i got this
my lighting is buggin tho
when i blend it
also thats now how a skybox should work lmao
Looks really cool to me. You could obviously add other siybox textures in it but if you only need to blend between two skyboxes at any given time, I’d just change the textures in a C# script to support more skyboxes. When it comes to the clouds, maybe the easiest solution would be to add completely separate mesh on top of everything else and add the clouds there so you wouldn’t need to add those to the same skybox shader
Did you use the default skybox shader as a reference?
it works now
Cool
That shader you linked is so cheap it definitely won’t make a difference. I think the laggy feeling might be due to the same effect you showed here which has something to do with the envirnoment reflection probe and how it updates to keep it up to date with the skybox. I don’t really know how that goes so I’m not able to help you more on that regard. It will likely depend on the render pipeline in use too. People on #archived-lighting might know more about that
alright
i had enviroment lighting source on skybox
so the color of the skybox was updating color of shadows
alright looks good to me for now
i'll try to figure something out with clouds
and find actual good skyboxes
If you dont, the skybox doesn’t change the shadows so it wouldn’t get dark enough at nights for example. You could maybe use gradient for example and lerp between different gradient profiles according to the skybox in C# but haven’t done that myself. There might be some way to update the environment probe fast enough but I’m not aware of that
i am truly at a loss on what to do... i have no idea whats causing my builds to take so long and this happens on every one of my projects
its always my shaders that take tons of time to compute and ive tried creating an asset variant but that didnt help at all
never has this problem with Built in Pipeline, but I've heard that this is common with URP (or maybe shadergraph?)
any ideas on how to fix this? i feel like ive tried everything
including this?
https://docs.unity.cn/Packages/com.unity.render-pipelines.universal@12.1/manual/shader-stripping.html
Note that I dont use urp
yeah, ive stripped my shader list down to 3 but it still takes so long
and i cant see what shaders are used during runtime because i cant even get a build to start running
Well... I think it's the price of being 'Universal' 😅
Hello I had a question, I don't use shaders but I know VERY light knowledge and I've made a couple, can someone please help me or guide me on how to make a triplaner TERRAIN shader for URP? (I've been looking for this FOREVER)
Shader cache should save you from compiling shaders again after the first build. But I think you've been told that already?🤔
Did you not find anything online?
No not really the only thing I found doesn't work for URP.
i was under the impression that the shader cache was saved automatically upon building for the first time, but i believe its getting reset after each restart plus why the hell does my first build take hours anyways?
Must be many and/or complex shaders in your project. SSD/HDD and CPU would affect the time as well. So if you're compiling a lot of complex shaders on an hdd with a weak CPU it could take ages potentially.
i have SSD and a decent CPU so i doubt thats the issue
Then you might need to improvise. Look up how to create a terrain shader on urp. Then how to make a triplanar shader in urp and combine the knowledge.
Then you simply have complex shaders and maybe scene setup too.
Yeah as soon as I typed my first message I found out you can make a terrain shader in the shadergraph now I'm working on combining them.
im pretty ignorant when it comes to shader mechanics so i do not know complex from simple
Maybe try excluding custom shaders from your project and test the build time. Then compare and think from there.
Hey, I have a 2D top down game on a grid based system. It is divided into chunks of 32x32 tiles.
Depending on the chunks type (pure, impure), if it is "impure" I want to render a basic, half transparent texture on which I later want to apply a shader. If it is "pure" then just make it transparent.
I was wondering how to do this optimally? Cuz my map is really huge and I'm not sure if making a huge texture and applying some shader on it wont be laggy
unfortunately, it's "common" when you use URP
||or so I've heard||
Hey ! Its me again ! I asked yesterday about how to use lightmaps infos in the shader and it works pretty nice (thanks again eheh) !
Now I'm wondering if there's a way in shader graph to modify the lightmap ? I could do that through code but I wanted to have the option to do a transition (could be a simple fade or a complex distorted weirdo transition, who knows !) through SG as it's easier for me ngl. If it's not possible, is there a way to combine some simple HLSL code to have a custom node that act kinda like a lerp but that actually can update the lightmap ?
Would be awesome if someone has infos about that ! Thanks in advance as always ! 🌺
You could use this API to strip all the unnecessary variants containing features you don't use: https://docs.unity3d.com/ScriptReference/Build.IPreprocessShaders.OnProcessShader.html
I tried that for HDRP a couple of years ago, I was only able to get the first splatmap to work. So I had only 3 or 4 terrain layers to work with. Later realized that it should probably use multiple passes, one for each splatmap. But yeah this seems hard to find info about, you'd probably need to be pretty decent at shaders, and also examine the existing terrain shader and its material properties.
I ended up just rolling out my own terrain system completely...
If you dont need terrain layers then you can use any regular or custom shader
It actually wasnt so hard once i found out how to recreate thr terrain shader in shadergraph
Got it to work with all 4 layers too 👍
So your question is just about how to make it triplanar?
Well i know how to do that in shader graph but not traditional code shaders
4 layers was not enough for me, thats what I mean
Might depend on the render pipeline
Yeah I looked it up and hdrp has 8 while the rest have 4
Alright you might wanna check this out:
https://catlikecoding.com/unity/tutorials/advanced-rendering/triplanar-mapping/
Yeah while searching I found that website, because of my very limited knowledge on shaders I dont know how to apply this to a terrain shader
I just dont know the code language
So you are not asking how to make a triplanar shader, but how to learn HLSL instead
Worth pointing out, that tutorial has some fluff in it since it predates URP. Section 1.5 onwards should be what you need for triplanar
Well thanks for the help but I did already find a way to do it.
As stated earlier
This implied that you are still looking for help but alright.
My bad
Glad you figured it out
Is there any reason why this seam is appearing? what you are seeing is the material attached to an image that's stretched across the screen, with 1 camera in the scene that's rendering with a solid color background
Make sure you use Pass 0 : Draw Procedural on the Fullscreen Pass Renderer Feature
my renderer wasn't using that feature beforehand, so I added it, and referenced the shader. It seems to change very little, and doesn't remove the unwanted effect
It only changed at all because I accidentally left an unwanted pp Volume in the scene, which I deleted
I seriously can't imagine why this would be happening. I even implemented my own distance function to replace the distance node here, but I suspect that the problem is with the screen position node?
from what I see, when screen.x > screen.y, the distance being returned is decreased by some factor
Wait how were you applying the shader before if not using the feature?
Oh a UI image? Should be able to remove that now
You use that feature to apply the fullscreen graph. It's not suitable for UI
noted
can someone help me get the textures back? I went into rendering > pipeline converter and converted it, and now I get pink everywhere, any way to fix this?
What shaders are those pink objects using?
It cant auto convert custom shaders. You likely need to remake them
Is there still no way to pass in float/vector arrays into shader graph?
You can use a Custom Function node (specifically with hlsl file, as the array needs to be defined outside the function body)
I'm wondering whether it's easier to just squash it in a texture2d
Any quick insights as to how expensive it is to make a roughly 128x128 texture and pass it as opposing to just passing a bunch of 2D vectors directly into a shader?
No idea really, might need to try both and profile if performance is a concern
Can I make light exposure affect the color/alpha of an object? So like on areas that are brightly lit its color in those areas is set to white but on areas without light it becomes black.
Like this
Hello,
how can i make this scrolling effect with shader?
I want to do it with shader in terms of optimization, but I couldnt find an idea how to do it because there is Text and Font.
more of a post processing thing
🌍 Bundle MASSIVE Discount 98% OFF! https://cmonkey.co/humblebundle
✅ Get FREE Assets https://assetstore.unity.com/?on_sale=true&aid=1101l96nj&pubref=unityglow
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
👍 Learn to make awesome games step-by-step from start to finish.
🎮 Get my Steam Games https://unitycodemonkey.com/gamebundl...
for example
Can anyone give me some hints for shader graph on how to make it so that i can adjust the speed, and then the offset of a Tiling and Offset node scrolls slower or faster, but without jerking or going backwards?
I'm trying to make a simple rain effect in a full screen shader, where i can control the speed of the drops falling down.
So for this the rain drops animate by scrolling the Y offset in the Tiling and Offset node. It works with just multiplying time and a speed parameter.
But the problem comes when increasing or decreasing speed. This makes if stutter up/down and/or play it backwards.
I tried sending a custom time, like suggested in some threads, and also lerping the strength (which is 0-1 that will control the size, speed etc) like this:
strength = Mathf.Lerp(strength, strengthTarget, Time.deltaTime * lerpSpeed);
But even if i do that, it animates weirdly, and the rain goes backwards as the strengthTarget goes down. And kinda fast forwards as the target goes up.
Any idea how i should set this up?
If you need to be able to change the speed, you need to do this calculation on the cpu/C# side (e.g. offset += deltaTime * speed in Update()) and pass that to the shader
Thanks, i will test this, that's basically what CustomTime does, but i guess i mess it up with the time node
Then yeah you'd use that CustomTime straight as the offset, without adding to the original time and no Speed property since that's controlled from c#
Ok cool, thanks! 🙂
Shaders are so annoying, seemingly simple things are either pretty hard or impossible to achieve because of how gpus work 😒
I'm guessing I'll be feeling a lot of this as I continue to get into shader programming
You might but also as you learn more, you will start to realize the tools that you have available and the different workarounds to common issues
It reminds me to when I started learning dots
Seemingly simple things turned out to be really complicated and you needed to shift the way you think about achieving stuff in order for it to work
That is the reality of extreme parallelism. Luckily there's quite much resources available for everyting shader related
The worst thing about parallelism is that it's pretty common for stuff needing to know about other stuff, which is pretty common in games down to the visuals level
"I need the mesh to be emissive..." Ok, fairly simple
"...but brighter when near vertices" Literally no idea
Assuming you mean vertices other than the ones forming the triangle being rendered, those are the kind of problems that can be really hard to implement
Yep, I mean exactly that. Default linear interpolation gpus do is very ugly, so in order to do something like this you need to either bake it using runtime texture manipulations or somethings similar
I'm currently in a process of doing some seriously unholy things
Can you do bitwise (left right shifting) in shaders?
Yes you can I found it
im still stuck on my arm problem
i need to make a shader in which i have two floats
start - how far up the arm from hand the fade starts
end - how far up the arm from hand the fade ends
can someone help me make this?
i also want to be able to choose a color
of the arms
Calculate the distance between the position node (world space) and the camera and then use that to lerp colors, right?@royal bloom
What did you try and where are ya stuck
I'm going insane. Why doesn't my property work in the ease function here? Is there a precision mismatch? Something with the references?
If I manually supply 5.0, it works as expected. If I pass the literal same value of 5.0 through inspector via a property it doesn't. Crazy stuff
And it's not an isolated problem, it's tied to the ScreenBlend function somehow
If I use both it just stops working with a property
Is it something caused by loop unrolling?
No, I just tried
float result = ease(sides[0]);
result = ScreenBlend(result, ease(sides[1]));
result = ScreenBlend(result, ease(sides[2]));
result = ScreenBlend(result, ease(sides[3]));
result = ScreenBlend(result, ease(sides[4]));
result = ScreenBlend(result, ease(sides[5]));
result = ScreenBlend(result, ease(sides[6]));
result = ScreenBlend(result, ease(sides[7]));
return result;
To the same result
Ok something really weird is going on with contsnats in hlsl
Or I suspect arrays
In shader graph, can I somehow detect the edge of a masked sprite?
That is, the point where the sprite and the mask intersects
For example, sprite outlines shaders don't look right when the sprite is partially hidden by a mask
someone suggested this
and i tried it
but didnt know how to make the shader
Somebody please explain
Explain what part
Isn't one minus supposed to invert colors?
it does
Is there some other inversion method that produces what's on the right picture and not the middle?
Because I have no idea why I'm getting the middle one
UVs are correct (default unity plane)
I mean it should... It could be a display thing?
like the preview isn't displaying it the way you expect
That's a Linear vs Gamma colorspace thing
So I can achieve the right one with quadratic falloff?
I think it's quadratic
Or is there an automatic switch for that somewhere
There are functions to convert between them. I think UnityCG.cginc has LinearToGammaSpace(v) and GammaToLinearSpace(v)
or Colorspace Conversion node if working in graphs
Uh, I think all this does is pow(2) it
GammaToLinearSpaceExact seems to do something
Not super accurate and still looks off if you look close enough, but it's something
Hmm, there's no "distance to sprite edge" node or anything like that, is there
Imagine you have a sprite with alpha like this
and you want to apply an effect to this area
so, I have a minimap which is an orthagonal camera, passing it's position, 1/orthographicSize, and rotation in radians into a shadergraph.
I am trying to overlay a grid texture to it, and edit it's UVs so that they actually scroll with the camera/rendertexture. I've tried how I thought it should work, and it didnt... then how chatgpt said, which was similar, and didn't, then tried ot get gpt to write a custom hlsl function, which also is not.... What is happening at the moment is that the speed of translation of the grid texture is not in sync with the camera scale, it's moving very fast. secondly, rotation seems to start rotating, then slows down and reverses. I've checked the input values and they are all good. Here's what I have:
If I had a distance to edge node that would be great, but I can't find anything like it. Heck if I could even just blur in the shader graph that too would be alright...
You would need to pass a texture of that in
I guess the easiest way is to just make it myself
But what if that area changes like if I want it to pulse
make a gradient that stretches off and animate a subtract float on it or something?
like if it was one central object I could pulse it, but because I have two objects the only way I could pulse the gradient would be knowing the distance to the edge
You'd want to precalculate the distances (commonly referred to as "signed distance field") and store that in a texture passed into the shader
If I had access to a blur node or something similar then I could increase or decrease the blur intensity to pulse it
Catlikecoding has a tool which can generate this too
https://assetstore.unity.com/packages/tools/utilities/sdf-toolkit-free-50191
hmm, when I think about it my gradient is technically representative of the distance to the edge, right?
the manually made one, I mean
if crude compared to an actually calculated one
Yes, it may be better if it didn't go to black/0 so quickly. Depends what effect you are trying to make though
To make it pulse you can remap the distance from that texture. Probably using sin(_Time.y)
That's true, it was just a crude manual photoshop thing to show like, the concept
Yeah
Hmm, so if I have a gradient as source data and I want to use that gradient to create a pulse that starts on the bright area and moves towards the darker area
I use a sine wave, but I'm not sure how to attach it to the gradient
Probably something like sin(_Time.y * speed + gradient * freq) * amplitude if you want lines to move along the gradient and * gradient again so it fades as it gets further away
In graph is similar to this
For simplicity I'll start with just a normal gradient and try to pulse across it
I keep hitting the weirdest issues. Does this also have something to do with linear/gamma thing?
No in this case you have been cursed
actually what is probably happening is that your "Base" is not just black but darker than black
I'm seriously starting to entertain this possibility but no, that's normal just shader programming
we have been cursed to do shader programming
Actually wait let me do a max real quick
But I'm guessing your "base" actually produces numbers below zero
Nope, return max(base, 0.0f) + max(blend, 0.0f); same result
to satisfy curiosity, what happens if you add 0.1f to the result
if you get more gradient on the right side then the bottom right part of the texture is negative
sorry, add +0.1f to the base, not the result
return max(base + 0.1f, 0.0f) + max(blend, 0.0f);
Ok, but why tho
What's so special about this triangle
Your gradient starts at the top left corner and presumably approaches zero at the center
Wait but that doesn't make sense
Here's blend top right corner is white
And slightly lower it's grey
Here's base, entire right side is black
0+1 will still be 1 and 0+.8 will still be .8
Why does it jump straight to 0
It depends on how "base" is calculated but
Shouldn't max make this irrelevant?
I dunno how shaders respond to NaN issues for example
like if you're dividing by zero for the whole bottom right part, how does that show up in the render
But I can't see any other way you're adding two numbers together and getting a lower result than you started with
If you try to add to a broken calculation it's still broken
Yeah I'm reading through it seeing if I missed something
Ok, wrapping the blend function return in saturate seems to fix it
So somewhere, my values are off the limits
limit breaker
And I'm starting to think it's the >1 value issue, not <0
But the blend looks fine though
Yeah, no idea. Maybe hlsl does some clamping when compiling
Like it's not gonna let the value be out of 1 >= x >= 0
I butchered that expression but you get the idea
But "base" produces positive numbers from the top left...
What if it's like, 2.0?
So whiter than white
Should that have caused a purple pixel?
Then the pattern doesn't make sense given the colors
the bottom right isn't above 2.0 because it's black + black
it would be broken on the top left corner instead
If your base calculation is:
1 - (uv.x + uv.y)
Then anywhere past the halfway point would be a negative number
that is, that straight diagonal line you see
Yes, I should've divided it by 2 for diagonal checks
that line denotes the line where uv.x is 0.5 and uv.y is 0.5 and 1-(0.5+0.5f) is zero
(Is this the only place you're using base and blend?)
like, what is blend a blend of
Wait a second I'm checking something
started again from scratch and it works finally
Yes, it's working (almost) as I intended >:D
The issue really was forgetting to divide by 2 when doing diagonal gradients (i.uv.x + i.uv.y)
Now I just need to firgure out what to do with outwards corners
Hey folks. I have been searching for a couple of days and trying different approaches but nothing seems to work.
I currently have an inverted sphere that mirrors the x,y and z position of the camera but not its rotation. The first part of the shader is setting a Color/Texture and the second part is a reticle that I created using the Sphere Mask that should always remain in the center of the users view.
I tried to input the Camera Nodes > Direction into the Center of the SphereMask node and I set the Coordinates to World Space via a position Node but that doesn't work. View Space kinda work but its way off and seems broken.
Is this the way to get the forward gaze point of the user to use for placing the SphereMask correctly?
Wait, you made this. I've been reading your breakdown here on your site and didn't realize I was talking to the guy himself
very useful guide, I appreciate it a lot
Here is a visual of what I currently have the only issue is that The transparent cutout is not always at the center of the cameras view when I look around
Actually this setup does work with object space.
I'm really damn close to getting what I had in mind but still there's one thing that's bugging me. You see those seams around the center cube?
Or am I tripping
That's using screen blending. When using lightening same happens to inwards corners
I'm also confused as to how you're supposed to grab scene color (with screen position, to get whatever's been rendered underneath)
You can in shader graph easily with a node but I can't find a way to do the same in hlsl
It's using some "SHADERGRAPH_SAMPLE_SCENE_COLOR" and I have no idea how
Ok there's _CameraOpaqueTexture
Make sure you save the graph, using Save Asset in top left
Also check the texture is assigned on the material
oh i didnt apply the material, for some reasons the color was changing when i used as a input a RGB node
thanks
i want to animate that parameter on the right , why is it not controllable and how do i keyframe it?
You're likely trying to edit the shader's default material rather than creating a new one
Facing a dilemma
Cram a transparent overlay as pass into one shader or create a separate material
Shouldn't be any different in terms of performance right?
Not to the point of being of matter
Also while we're at it is messing with texels expensive?
There's no easy way to tell whether your shader sucks like with Unreal's shader debugger view so I could be creating the most abominable shader in existence without even knowing
Hey, new to shaders in general, still learning. Would cell shaded be the appropriate term to describe what's being done to these 3d characters?
In the end they both end up as separate draw calls, so there's probably not much difference.
Depends on how you're messing with them.
Unity doesn't have a shader debugger, but you could use a native profiling tool, like PIX, or, perhaps, renderDoc.
Yes, though there's probably more than just cell shading.
I'm all ears if you have more directions to point me in
Well, I'm not much of a technical artist, but there's probably at least color replacement/grading or whatever it's called as well.
We can't avoid branching in fragment shader if we need to conditionally discard pixel, right? Or there is some magic trick
Shouldn't be a big deal anyways
Best I can think of is multiplying it by 0
It will make it black, but still drawn
Relatively big deal, not in the grand scheme of things
Could put it in transparent queue and return alpha 0? If possible
I think in my case a branch will be more efficient. It's instancing shader with up to 40k instances, and I use alpha value as "brightness" multiplier for XYZ rest of a color
As I've heard transparent is ok for not too many objects especially on mobile
Honestly when it comes to performance of Unity shaders I'm clueless myself
The most tedious approach would be to make one shader that uses branching and another that uses transparency and manually check the performance
Probably yes but that would mean I will have to redefine layout of structured buffers 😅 I'd prefer just don't use discard feature for this material if performance cost will be to big
Still would be glad to know about that branch thing
At first I thought that for instanced mesh it will always take the same path no matter of the instance, but it was stupid assumption that even AI proved wrong
All these wavefronts are still a great mystery for me
Actually, now that I think about it, how expensive is transparency, really?
Cause I'm relying on it as well 🤔
Afaik they're rendered back to front then re-rendered front to back, so you can forget about culling.
Just tested. There isnt noticeable difference on PC, but on low-end android device fps drops like crazy. Culling backfaces help a bit, but probably all i can do now is to reduce number of instances
I searched a bit and apparently it's heavily hardware dependent
Some hardware can chew through it and most likely has some optimizations built-in, but most mobile ones do not
so I just had a little play with putting slope based blending of textures on my terrain mesh (it's in a custom shader on a mesh not unity terrain system) and it looks pretty, though does obvs have a performance impact... I guess I should use a greyscale blend texture instead? Anyone know of a tool within unity that you can provide it a mesh and it could bake a steepness texture?
Yeah. A branch itself isn't probably such heavy, but discarding pixels mean that it sometimes has to render 1000 instances through each one discarded holes
Strange though, I was almost sure that some pro mentioned that rendermeshprimitives() doesn't cull instances
I'm assuming the holes are dynamically created and unique per instance?
Shader random() function taking instanceID as a seed for a bw mask "threshold"
And bw mask is per material constant texture sampled with also randomized uv
But randomization and sampling does not introduce any overhead. Without discard it runs smooth, that's why I think this is the reason
How do I blend Texture 2D colors using a shader graph? more information regarding the question at: https://discussions.unity.com/t/how-to-blend-texture2d-colors-using-shader-graph/1527958/1
I think what you want is to sample a gradient texture with the height/position.G
hey i subdivided a plane in blender and exported it to unity
now when i modify the vertexs it doesnt really work as intended
for example when i change the y coordinate of the vertex the z coordinate of the subdivided plane changes.
How could I accomplish that? Mainly talking about the gradient texture.
this probably indicates that you exported subdivided plane with different Fwd and Up axis than the others, also mind the scale
Either draw/create it manually in photoshop/GiMP/etc or use a tool in unity to generate one, e.g. https://assetstore.unity.com/packages/tools/utilities/gradient-texture-generator-216180
Okay I will look into it, thanks.
Haven't tried it yet, will do later. But would it work with biomes, using the gradient?
Would need some adjusting but a similar technique could work. Assuming a separate gradient per biome, if you stack those gradients vertically in a texture you can sample with something like float2(position.G, biomeID/biomeCount) as the uv. Or use a Texture2DArray instead with the biomeID as the index.
Would probably get that biomeID from another texture sampled with regular uv coords.
Do you think there is an easier way to handle this or might this be one of them? Games like Valheim handles this extraordinary well (Of course, that is way beyond my knowledge).
In short, I generate a 2D color map onto a material with colors and different biomes, then I apply that to a 3d mesh with a Texture2D. I am just looking for a way to blend the pixels.
I have a custom shader being drawn in a command buffer (with commandBuffer.DrawRenderer(renderer, overrideMaterial);)
shader has #pragma multi_compile_instancing
and UNITY_VERTEX_INPUT_INSTANCE_ID
but framedebugger is showing it as 6 draw calls (with "reason unknown" ) , they also have static batching on and are marked static.... In the main render thread they are all batched together with another shadergraph shader.... Anyone know what I'm missing?
If there's a particular pass you want to render you should include the shaderPass param (likely pass 0? It defaults to -1 so renders all passes in the shader)
https://docs.unity3d.com/ScriptReference/Rendering.CommandBuffer.DrawRenderer.html
it's a single pass, I've updated it to commandBuffer.DrawRenderer(renderer, overrideMaterial, 0 , 0 );)
visually the same, though still at 6 draw calls. Thanks for the suggestion!
If you just want a transition between the biomes, perhaps you could find a way to generate that color map with the blending already applied? It's not really something you'd want to do in the terrain shader afterwards. I guess it would be similar to blurring which is expensive
they all have the same values in them and clicking on each call shows the same thing so not visibly differentiable
Is it only one renderer? Maybe there's 6 sub-meshes? Or that code is being executed multiple times. I'm not sure why else there would be 6 draw calls
it's six renderers, it's all the same mesh and material, with static batching on
it is indeed looping through the renderers here
(my first time using a command buffer, is it that there are multiple calls to drawrenderer then rather than that somehow being mashed into one?)
If using multiple DrawRenderer calls I don't think it will batch
Is this for URP though? That has DrawRendererList instead
For the color map, I am using noise and a heightmap. I think games like Muck use shader graphs, not to sure.
yes this is URP, interesting.
I'm trying to get holes in objects working in a nice way with URP. I'd essentially like to just cull front faces that appear through back faces. I've accomplished this somewhat by drawing a stencil with front faces culled and making my mesh respect that stencil. This works well for simple object as seen above but for more complicated objects I notice that back faces will hide front faces even if they are occluded by a front face closer to the camera, which leads to very strange behavior. Any ideas on how to fix this? Here are some pictures of the setup and the misbehaving object
why does my surface look like pixelated , im pretty sure i used shade smooth on blender before exporting
Are those "pixels" all individual faces?
no , its a .blend file
a normal circle with uvs
i tried smooth shading it still looks like that
so this is very interesting and I've been looking into moving that way but failing so far, are you able to point me to how to create a rendererlist ?
I may be going about this all wrong, I'm struggling to find a good reference, if you know of any for URP 14?
You create the renderer list through the ScriptableRenderContext. See https://docs.unity3d.com/ScriptReference/Rendering.ScriptableRenderContext.CreateRendererList.html
For URP 14 / 2022 versions there's also context.DrawRenderers (is obsolete in favour of renderer lists in 2023+). I have an example of that here (via custom renderer pass/feature) : https://www.cyanilux.com/tutorials/custom-renderer-features/#drawrenderers
also super interesting. seems i've slipped into the cracks between versions. Do you know if there's a way to take a list of renderers and make it fit into a cullResults? I'm not using a camera, and everything I've tried so far has been a fail
I think using the CreateRendererList overload that has RendererListParams instead of the RendererListDesc, as that contains cullingResults
hey ive been using custom function nodes in shader graph, but whenever i use more than 1 in the graph, it breaks
using just 1 of either works fine, and they arent linked at all
anyone familiar with this problem?
File mode? If the functions are in the same file it'll be included multiple times. You need to surround the contents of the file in something like
#ifndef MYHLSLINCLUDE_INCLUDED
#define MYHLSLINCLUDE_INCLUDED
...
#endif
so they are in seperate files, and i solved it by removing exactly this in one of them
Each file needs a different keyword there. If they are the same it'll conflict
If you know the file will only be included once (one Custom Function node) then leaving it out too also works
Yes, though I'd keep the _INCLUDED suffix so it's clearer what it does (and maybe help avoid it being the same as another keyword/macro elsewhere)
do you use height to normal node?
That because stencils mask work in screen space, you might have better luck using render to texture and camera layers instead
What's the best way to made a grid of scalable 3d blocks where there are no block faces, just the outlines? Like if Tetris Blocks were only outlines.
I'm using this shader asset, but the outlines that touch each other don't get rendered. I tried pushing back the shader's rendering order to Queue: Overlay, which almost works, but the lines in the back get rendered instead of the front, making it look "open"
https://assetstore.unity.com/packages/tools/particles-effects/quick-outline-115488
Does anyone know if it would be possible to use a tilemap as a heightmap for a shader?
I'm trying to handpaint a heightmap for a water shader. If theres another option out there then let me know.
isn't #pragma once more convenient? Afaik traditional header guards are relics of the past
Ofc there isn't much difference for compiler. Pretty sure my IDE showed that this directive is supported as well (or it was unity docs, not sure)
btw how to make ///<summary> in hlsl? i'd like to have something like this for my custom utils
My guess is you're using normal from height node which is resolution limited due to the way it works
Sure, I was going by the documentation. I think that pragma is only supported in Unity 2020+ so wouldn't exactly consider it "relics of the past" though, maybe for other languages sure
Yeah, I based my statement on C++ knowledge which is quite poor tbh. Good to know it's not supported before 2020, thx for pointing that
Hello, I am trying to make a shader in shadergraph that emulates the rifts from zelda echoes of wisdom. Right now I am doing it by only rendering the back faces of a cube and inverting the order of the deph buffer, so it only shows the faces that are covered. This almost does it but there is a portion of the cube that I don't want to be visible but with this method it is, Is there a way to fix this in shadergraph? Or should I switch off this method completely?
Rather than changing ZTest you probably want something closer to a decal. If using URP it has a Decal Graph which might work?
Im making a simple blur shader that offsets four copies of a sprite in opposite directions. I'm using it on a render texture placed in Image component on a canvas that is stretched to fill out the entire screen. It's working great but the screen ratio is 16:9 and the blur is inconsistant. If I plug ~1.7 multiplier (16/9) to the vertical offset it looks as intended. How can I get the correct aspect ratio using nodes so it always matches the screen size? I could expose a float param for the vertical multiplier and update it via script, but it would be great to have it in a shader itself
I tried using the object node like shown in the picture, but it doesnt seem to work properly in this screnario
I just found the screen node with width and height :)
A thing that comes up often in my work but never in tutorials is re-using timed materials for many objects which doesn't really work.
As an example there's the "dissolve" shader tutorial on youtube where a sprite dissolves into nothing over time. As the objects share a material they also share the effect and once the first object is dissolved they all are. How are people applying shaders like these to many objects?
Are people using one material per object?
Like, making a new material instance every time they want to restart the effect?
Usually yes. For URP/HDRP there's the SRP Batcher so it optimises setup between draw calls even if they share different materials (provided they are still the same shader, and using same shader keywords)
Though sprites only use SRP batching in 2023, for earlier versions it may be better to use MaterialPropertyBlocks. (Same for any version in Built-in RP)
You don't need to create the material instances yourself though, when setting a property through code using renderer.material.SetFloat(..) automatically creates an instance
I've been told making new materials on runtime is bad because they are "new assets" and aren't deleted properly
is that not correct?
You are supposed to handle cleanup when the materials are no longer needed. Usually in the OnDestroy() method of the script
Though I think it might also happen automatically when switching scenes, not sure
Right so I have to manually clean up the material on delete of the gameobject
Or indeed when whatever effect I wanted is over
I can't use material property blocks in URP without messing up my performance?
Or does it not matter for sprites because they're already not batched in my 2022 LTS version
Correct. You can still use MPBs there. But for MeshRenderers/SkinnedMeshRenderers you would avoid them, as MPBs aren't compatible with SRP Batching
My instincts tell me the system I'm imagining for stuff like this is bad, but I'm not usually the one to work with materials so I'm unsure
But you're saying even if I duplicated materials every time say, an enemy took damage, as long as I deleted the materal afterwards that would be okay?
Why not pool these mats instead of cleanup btw
Because the primary concern is the "time" variable
Is the damage effect different from the regular material/shader in this example?
In this theoretical example the take damage effect would be a fire-once effect not achievable by something like replacing the material with pure white for one frame
I'm not actually making a take damage effect though so it's just an example so I can understand
Well you'd probably still only need a separate material per enemy, and only need to destroy it when the enemy is killed
But the effect is fire once, right? So taking the material away and putting it back mean the second time I show the material the effect has already fired?
For example the tutorial dissolve effect only appears when time is less than say 5 seconds so if the material has lived for more than 5 seconds the effect doesn't occur
The time in shaders is since the level started, so how does the effect know when to begin? Is there a float property as an offset? Or is a custom time property used?
Either way those can be reset via SetFloat on the material
Wait, really? thought it was time since instantiation
That would mean a separate time for each object, but it's a global property
no I meant like, material instantiation
That's why asked about polling. Simply reset float on GetFromPool or smth
Yes, pooling is still useful if materials need to be reused often
I see
Oh, also you said if I use "setfloat" then a new instance is automatically created for me
This only happens the first time I use setfloat, right?
It's the renderer.material part that creates the material, but yea
So getting the material creates a new material
So this line would make a new material instance
Can see an example on this page
https://docs.unity3d.com/ScriptReference/Renderer-material.html
I have no idea how to really describe this, is there a term for this type of "shine" effect? Id like to try and build it in ShaderGraph - every few seconds theres this... Reflective "shine"? Effect that scrolls across the weapon like in Overwatch, or in games like GTA to indicate you can pickup or interact with some specific item, id like to research how to do that kind of effect but I dont know how to describe that to google
https://pa1.aminoapps.com/6570/a215f17c72c938860cd75da9cfd15ae5f4b2ff27_00.gif
It's a frensel glow that includes normal maps, there should be a bunch of guides about those
It's also masked by a wave which is animated to move
Most likely a distance to a position on one axis in object space in OW's case
Ah, ill try that out, thanks for the terms to search up, that gives me a point to start researching
The wave could be moving along UVs since it wraps around the box after it passes the muzzle
It could, although they likely are separate objects as they're detachable
Making UVs that allow for scrolling textures is very tricky if they also need to work for the base maps
If they were on a second channel that'd be easy and give you quite a bit of control over how the wave should traverse
They are not compatible, and must be recreated in Unity's shader format/language, or most commonly baked into texture maps if the type of shader allows for it
Is there any way to create a shader graph that does one thing when doing shadows, and another when doing a normal render?
Or to be more specific, get the direction of the light source when doing shadows, and get the direction of the camera when doing a normal render
Im not sure if there's a variable that changes in those cases that i can use to represent the direction that I said
The reason for this, Im working on an Impostor shader, and they should be looking at the camera on the render pas, but if it's the shadows, to create a semi acurate shadow, the impostor should be looking a the light source
You can use a custom function. In URP it's
#ifdef SHADERGRAPH_PREVIEW
Out = 1;
#else
// For URP this is needed :
#include "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/ShaderPass.hlsl"
// Test if we are in the SHADOWCASTER pass
#if (SHADERPASS == SHADERPASS_SHADOWCASTER)
Out = 1;
#else
Out = 0;
#endif
#endif
Would replace 0/1 with the directions
Not sure about Built-in, it might be similar to URPs but a different include.
I think HDRP already does the include automatically, but the keyword is SHADERPASS_SHADOWS instead
I'll also mention that when rendering the shadow passes it's usually from the light source, so depending on how you calculate these directions they might already be towards the light
yeah! that's what I would like to happen
half3 objectSpaceCameraPos = mul( unity_WorldToObject, float4(_WorldSpaceCameraPos.xyz,1) ).xyz;
float3 pivotToCameraRay = normalize(objectSpaceCameraPos.xyz-imposterPivotOffset.xyz);
basically if I could change that _WorldSpaceCameraPos into something more generic that would include both passes, it would be great
I guess I need a reference to the Virtual Camera?
I think you should be able to extract the position from the inverse view matrix (UNITY_MATRIX_I_V._m03_m13_m23), that should be equivalent to _WorldSpaceCameraPos in the main pass but be the light position in the shadowcaster pass (since that's where it's rendering from)
lets see
oh wow
it works!
These are impostors :))
THere's still some issue with the light, but I will figure it out
Thanks!
okay it seems that because now the plane of the impostor is aligne with the light, it's casting a self shadow. Any idea if it's even posible to disable this?
Hmm, maybe by changing the depth/z of the fragments in the shadow caster pass if they are infront of the camera-aligned one. Not sure on the exact setup though, or if it's even possible in shader graph
For nodes that are not already basic math operations :
Gradient Noise: Use Mathf.PerlinNoise,
Tiling and offset : The doc can help you here : Out = UV * Tiling + Offset;
Remap : since your remap to the 0;1 range, you can simply use Mathf.InverseLerp
I'm curious about applying a LUT directly into all of my shaders to avoid doing anything in post as on Quest... I am currently trying
I put in that arbitrary float to try and debug... something is happening... but things generally are coming out greener than I'd expect
also this, better, but still greeny
Hello people, the shader in the video below works great with sprites, but looks very wrong on UI Images. I'm trying to figure it out, but in the meantime, I'd love your ideas.
https://www.youtube.com/watch?v=ajbNS8mncRo
In this video, you will learn how to create a 2D ripple distortion effect Shader Graph in Unity engine.
Project Files Download (Patrons only): https://www.patreon.com/BinaryLunar
The Ultimate 2D & 3D Shader Graph VFX Unity Course:
https://www.udemy.com/course/the-ultimate-2d-3d-shader-graph-vfx-unity-course/?couponCode=008A797D623D6F0E6941
00:...
Canvas shader graphs require Unity 6 or at least 2023.2.
https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@16.0/manual/canvas-shader.html
The easiest way to apply lut is to use a 3D LUT texture, with the input color as 3D uvw sampling coordinates, and the output is the lut applied result
Thanks, I think 3d LUTs don't work in mobile/URP or not performant or something though?
You might need also to apply gamma correction to the input uv
I saw that using a 2d unfolded lut was better for that stuff somewhere
It's nothing more than a 3D texture, it should work.
You could get away with the 2D one, but unless you sample it twice, you might end up with banding in the blue channel
Why sampling twice?
Why are you avoiding post? It will likely cost more, not less, to do all those extra LUT corrections in every pixel shader
Oculus quest post is prohibitively expensive
Only if done poorly
You are doing exactly the same amount of math if you recolour every single pixel in a surface shader vs. in a post-pro effect
(in a best-case scenario)
As Remy said, you should use 3D textures as LUTs once you get to the GPU. 2D textures are mainly for ease of authoring in CPU-side programs, you typically convert them to 3D before sending to your shader.
Unless things have very recently changed, you lose about 30% of your frames budget going back for a second pass on quest. There is a very new way of pushing lut processing into the forward buffer in unreal but hasn’t been made for Unity yet
Yes, the trick is to not go in for a second pass but do 100% of your post in a single pass
I haven't done Quest dev but exact same principle applies in mobile. Uber Post = better.
Isn’t post instantly a second pass? I have done a lot of quest dev and any application of post processing has been crippling
Open up your frame debugger and see what's happening after rendering the scene - I would be very surprised if there isn't at least 1 Post pass by default if you're using URP.
I don’t believe there is but I’m just heading out to the shops
Np, but yeah if there is legit 0 post going on then yes, different story
One of the earliest effects I implemented for The Last Clockwinder was HDR Tonemapping and Color Grading. We had decided from an early stage that the game was going to be lit entirely with static lightmapping The entire environment is lit with a single, massive bounced area light! , and post process
I don't think this is a prerequisite, since you can still make shaders for sprite materials used in canvas as it is. I've already made a pixelating and twirl distortion shader which works fine, but there is something in the specifics of this particular shader which makes it a bit more complicated to make it work in canvas properly. So far I had little luck, though.
Non-sprite shaders also work for sprites but have unexpected errors and limitations, I assume non-canvas shaders for canvas renderers is the same deal
I don't know what the limitations precisely are
You could try isolating the exact problematic part of the shader by process of elimination
Since the texture is "flatten", each slice can interpolate R & G, but not B, so you'd need to sample two slices and blend.
Might just be easier to do with a tex3D
I introduced the philosophy from another video on some aspects and combining some elements already helped move on the right path
https://www.youtube.com/watch?v=dFDAwT5iozo
A shockwave shader graph (or shock wave shader graph) is a relatively simple effect, that can add a lot of pop to actions in your game.
Shockwave updated for 3D in my timeline video here: https://youtu.be/A5jl5RVEjqE
The reason I'm doing this tutorial at all is because someone commented on one of my YouTube videos requesting it. I bring this...
hi i'm new here, can i post wip shaders here or is there a different channel for showcasing stuff?
In unity, are you theoretically capable of applying an additional shader to an object irrespective to what it already has?
For instance, I wanted to make it so that hovering over an object with a mouse applies a fresnel shader, and I come from a TModloader background where you can just slap a screen shader on top of everything
but idk how to apply a shader without completely replacing the material in unity
Hey guys, I was wondering if anyone knows how to effectively draw a lot of different meshes indirectly using the same material efficiently. Graphics.RenderPrimitivesIndirect seems to issue 1 draw call for every draw command no matter if it's a consecutive command or a seperate call to the function. I'm hoping for a functionality similar to glMultiDrawArrays in GLSL, which isn't supported for compatibility reasons(or so I'm told).
For now, I'm getting much better performance readingback to a mesh and allowing unity's built-in mesh-renderer to kick in. But if the data's already on the GPU it doesn't make sense to read it back to the CPU only to put it back if I can just manipulate the data with compute shaders. Also I would very much like to still be able to access the mesh information on my buffer for storage optimization. Does anyone have any insight?
I think DrawMeshInstanced/Indirect is what you're looking for.
You mention that you want to "still be able to access the mesh information". Do you mean on the CPU side? In this case you'll need to read it back regardless.
On the GPU side, I don't want it on the CPU otherwise I would readback obviously
Wait so I'm confused, on the documentation for RenderMeshInstanced(which the API says replaces DrawMeshInstanced), it takes a Mesh object which I believe holds the data on the CPU side(?) I'm not sure do you have an example of how you can use it to draw geometry on a compute/graphics buffer?
A mesh doesn't have to hold it's data on the CPU side. It can just be holding an address of the data on the GPU.
Huh interesting, I'll see what I can do thanks!
How would you set a mesh to point to some geometry in a compute buffer? I'm not seeing any methods in the documentation
Something like this I guess:
https://docs.unity3d.com/ScriptReference/Mesh.GetVertexBuffer.html?utm_source=perplexity
I don't know the details, as I've never done that in unity.
Maybe Google on how to generate a mesh entirely on the GPU side
Hmm... I'm not sure that's what I want. I believe that route would need me to readback the size of the mesh from the GPU and then copy the contents into the buffer location the mesh desires.
My goal is to keep the geometry where it is in my original compute shader because it's very accessible that way. RenderMeshIndirect, from what I'm getting, is for rendering multiple instances of a mesh whose geometry you can get from the CPU(or originally) and which the amount of instances and their positions is known by the GPU.
If a Mesh object has vertex and index data on the CPU, it must copy it to a gpu buffer to render(always), but my goal is to have it point into a buffer I manage.
No, that should be possible. You just need to research it.
You need to pass the vertex and index buffers to your compute shader to fill them. Then assign the same buffers to the mesh and use it for whatever rendering you need.
Try asking this in perplexity. It provided a great answer for me, although it's too big to share here.
perplexity?
Ai search tool
oh ok, thanks
I’ve done some research and I don’t think it’s possible. Meshes do own a separate gpu buffer for vertex and index data to be rendered, but I can’t find any information on assigning the location of this buffer to point into a different compute buffer. The documentation only lists ways to set this data with a copy on the cpu, its overrides being an array, list, and native array. I can’t assign the address this buffer points at. The method, Graphics.RenderMeshIndirect, is for instancing large amounts of the same mesh geometry, where the amount and visual information about each instance can exist on the GPU. Say if you had a grass instance and you wanted to render a lot of them for very cheap. If we want to generate different geometry indirectly from the GPU, Graphics.RenderPrimitivesIndirect is used, which has a SV_VertexIndex semantic to differentiate vertices allowing us to find them in our own managed buffers.
What I believe is happening in the background with meshes is Unity’s performing some complex batching that combines the meshes physically since they all have the same material. When I call Graphics.RenderPrimitivesIndirect, I’m not performing any batching so I guess that’s why it’s slower. If that’s the case, I could customly batch them in a compute shader, though I’m not confident enough that this is the bottleneck to try this.
What’s interesting is how in the documentation, Graphics.RenderPrimitivesIndirect has an option for command count which suggests I can issue one call to the function and create multiple meshes with different geometry by making the command count equivalent to the number of unique meshes I want to render. So rather than N calls to Graphics.RenderPrimitivesIndirect, I could have 1 call to it with a command count of N. However when I try this, I’m not getting better performance, rather, my performance is bad even when all the commands are blank(instanceCount = 0, vertexCount = 0) which should cull all the geometry.
I honestly don’t know where to go from here; it feels like my options are to readback and accept the unnecessary bandwidth occupancy, or to abandon unity and recreate the project in OpenGL.
Only gonna comment on the mesh buffers. Indeed you can't make it point to an arbitrary compute buffer, but you shouldn't need to. Try approaching the problem from the other direction: pass the mesh buffers into your compute shader and fill them in it instead.
Regarding the indirect rendering, it is basically passing some overhead from CPU to GPU side, so it wouldn't necessarily improve performance, especially if the bottleneck is on the GPU. Though, it is weird indeed that if you set the instance count to 0, it doesn't affect performance.
Might want to have a look at the frame debugger, profiler or some native GPU profiling tools like PIX for more info.
That's what I said in the beginning of this message. To copy the data into the mesh's buffer, I would need to know how big to make the mesh's buffer. To know how big to make the mesh's buffer I would need to readback the amount of geometry. And in any case it would be twice the memory usage.
Yeah I'll see if I can uncover something with instance count = 0 not effecting performance
So you don't know the vertex count of the generated mesh?🤔
How are preparing the compute buffer then? I think it needs to have a predetermined size, no?
Surely you have some of this info on the CPU side?
Ah so I have a very big compute buffer that uses a shader based malloc function to allocate portions of it for different generated geometry. That way I can render and store the information the frame it’s generated without stalling either processor.
So no I don’t know the size on the CPU
That’s why I’m using indirect functions to render it as well, because I don’t know the info directly
I see.
There are many ways to re-render a mesh on top of itself with a different shader, to override its shader or to render a full screen shader
The methods to do that depend on what render pipeline your project is using
There is no way to "mix" two different shaders at runtime, though rendering the object twice can let you do a sort of an overlay if the second material is transparent
A typical method is to include the highlight effects in the shader of all meshes that need it so it can be turned on or off, as long as the effect isn't too expensive
Or alternatively swap to a different shader that does support the highlight and copy all the material properties to the new material instance to keep the shaders separate
How can I test ShaderGraph Shaders?
Use them🤷♂️
Or what do you mean by "test"?
I am already using. "test" means performance.
So investigate performance? Well, for something simple, you could use the unity profiler gpu module. For a more detailed analysis you'll need to use native gpu profiling tools, like PIX or Nvidia Nsight.
Thanks for sharing this information. Will Pix and Nvidia Nsight will work for mobile?
And is it good to use ShaderGraph for mobile? I am using it in mobile but some of Dev not suggest SG for mobile I don't know why.
No. Mobile has it's own tools depending on the device.
It's okay to use the ShaderGraph. It depends how optimized you need the shaders to be. Manually written shaders could be more optimized then the ones generated by shader graph.
oh! okay
Thank you 😀
I'd suggest to test and profile your game with shader graph and only worry about it if you actually have performance issues
Yes, you are right. Profiling is necessary to inspect the performance. I will do.
sing an asset, one of the shaders doesnt compile in unity 6 and im trying to figure out how to fix it myself , any advice?
there is no "," on line 209 in that file, what is there is
nvm fixed it by reimporting the shader lol what the actual
so can I just keep lerping textures to plug into one vertex color channel? What would happen? Would the blend work worse? Or would it not work somehow at all?
Wdym? What are you trying to do?
Plugging textures into vertex color channel doesn't make much sense.
Clumsy wording
Making a vertex paint shader
But using more than 5 colors
I meant could I fit multiple lerps into one vertex color, what would happen
But at that point I could just make a splatmap I guess
Hello, how can i use SetInputAttachment in SRP RenderGraph (AddRasterRenderPath)? How to use LOAD_FRAMEBUFFER_INPUT in shaders (HLSL for dx)
Is there any way to have a sort of ambient occlusion effect with 2D sprites? Just something to create contrast between the subject and background.
does anyone know why my directional lights dont seem to be affecting my shader graph shaders that use main light? I'm using URP. it seems like the skybox is the only thing that matters
Hey I managed to fix it by changing my shaders from unlit to lit and then back to unlit, does anyone know why this solved it?
How exactly does unity determine the render order for opaque objects? I'd expect it to be exactly front to back based on origin positions, but according to the frame debugger this isn't consistently true. there's no funny business with batching or instancing going on here... I'm not sure what's up. any ideas? I'm on the built-in pipeline if that makes a difference
(I'm trying to get some fun masking to work with the stencil buffer, which means that my render order matters quite a lot)
For opaque objects, front to back is preferred to reduce overdraw, but ordering objects strictly like that can break batching opportunities, such as when you have two objects sharing the same material, but not next to each other in the depth sorting order. So the batcher always prioritizes dynamic batching, static batching, GPU instancing, etc., over maintaining the sort order.
This is not the case for transparent objects, where a back to front sort order must be strictly maintained for correct blending, which means losing out on batching opportunities.
That makes sense! In my little test case these are three separate draw calls with different materials, so there's no batching going on -- but for some reason the render order changes when I change the distances between them (without changing the z order)
If I switch to a transparent shader it works exactly as you'd expect (strictly back to front)
Is there somewhere I could see the source for how they're determining render order? or anywhere the algorithm is explained?
No, that's all implemented in native code.
I'm able to observe the same thing. My guess is that Unity's internal culling and batching system works similar to their CullingGroupAPI.
https://docs.unity3d.com/Manual/CullingGroupAPI.html
Importantly, it has a certain number of distance bands, so maybe it's only sorting the distance bands, but the order within each band is somewhat undefined.
Aha interesting! Okay, that's very useful... thanks!
For more control over order for stencil operations, you can use the render queue property in the material.
There is also a sorting order in Renderer, which is only exposed in the inspector for SpriteRenderer but can be changed in any renderer from script.
https://docs.unity3d.com/ScriptReference/Renderer-sortingOrder.html
Lovely, I'll take a look at that! much appreciated
I think ultimately I might have to just make my own batcher and use Graphics.DrawMesh for this. annoying but will probably end up more performant anyway, since I can make some special assumptions
is there a way to trigger any kind of function or event from a shader?
not exactly! Since shaders run on the GPU, they can't communicate easily with stuff on the CPU. what are you trying to do?
i have an interactive gras shader (from the internet) and im trying to detect when the player touches the grass
yeah that's tricky. You'll probably have to figure that out separately on the cpu, probably with physics or distance checks or whatever
ok, well I dont really know how to do this since im not really into shaders or physics stuff
do you think it would be smart to learn shaders and make a custom one special for this use case?
I always recommend learning shaders just cause they're super useful & I think they're cool -- but I'm not sure a special shader will help here, since you're not realistically gonna be able to send info back to the CPU anyway. Hard to say without more details though
what detail do you need, the code?
Well like what exactly are you trying to do? What does the grass look like? how is it getting placed? is there a gameobject "grass clump" or is everything instanced? stuff like that
So im trying to count how often the player touches the grass with his hands, its in Vr. I think the grass is instanced and the grass is placed with a tool in the editor
Huh okay. well if you can get the data about where the grass is from the editor tool, you should be able to test if the player's hand is close enough that they're touching it. But if the shader itself is moving the grass around a lot, you're going to have a very hard time determining where it is
so what you are trying to say is that there isnt really a way
is there maybe a better way to do this without shaders?
it's not impossible but any way you could move data back to the cpu (like by rendering a depth map from the hands for example) is going to be impractical and almost definitely not fast enough for VR
yeah you could move the vertices of the grass mesh from a script! but if you have a lot of grass, that's going to be extremely slow
You could probably use a compute shader for this but if you can't write shaders at all yet, I think that's probably too advanced
depends on hardware though. Not sure a meta quest could handle a particularly complicated compute shader
Anybody knows how to implement custom blend modes (or disable blending) for ShaderGraph shaders? Basically the same question found here: https://discussions.unity.com/t/how-to-specify-blend-mode-and-operation-in-shadergraph/1496127
Specifically I need an "Add" op for color and "Multiply" for alpha. This is easy to do with ShaderLab which also allows you to change modes via script, but on ShaderGraph, I don't see the option.
I am using ShaderGraph to render transparent objects onto a render texture. Default blending modes provided by ShaderGraph don't work well for this so I need to specify the blending op/mode. If I can't do this, then disabling it and calculating the color blending manually is fine too but even this seems impossible with ShaderGraph.
The last thing I want to do is to not use ShaderGraph and rewrite all shaders and subgraphs I have as ShaderLab shaders. This would be very dissapointing
Is there any better solutions than these ideas that I have?
- Write single shadergraph output to black/transparent texture, then use another ShaderLab to blend results with others
- Use asmrefs to access shadergraph internals to see if this can somehow be changed
- Try to mess around with asset importer or ShaderGraph editor API to somehow change this
You could convert the graphs to code (via button in inspector when graph asset is selected) then edit and save that as a shader file to use on your materials. That separates it from shader graph, but at least it's not a whole rewrite
If you're rendering these objects via a custom renderer feature you can also override the blend/blendops in that by passing a RenderStateBlock into the DrawRenderers/CreateRendererList params.
bump, still no success unfortunately. I am still unsure as to why the "clear" is not even updating the color, I assume "RT_GroundMask" isn't properly being assigned to my "RT_GroundMask_GLOBAL" texture.
Thanks so much for this. I don't think I like the convert graphs to code since that requires a lot of work on updates (unless this can be done programatically). But the RenderStateBlock will probably be perfect since I am using a custom feature. I'll try it out now
ive created a shader but it is purple the whole time, does someone know what i should look at?
i have no idea
thats how
uh if you want i know a place you can learn tho
Might be errors in console. But likely that #if needs changing to #ifdef in newer versions when using SHADERGRAPH_PREVIEW
i use Unity 2021.3.38f1
Shader error in 'Master': 'LightDirection_float': output parameter 'Direction' not completely initialized at line 246 (on d3d11)
Compiling Subshader: 0, Pass: Pass, Fragment program with DIRECTIONAL
Platform defines: SHADER_API_DESKTOP UNITY_ENABLE_DETAIL_NORMALMAP UNITY_ENABLE_REFLECTION_BUFFERS UNITY_LIGHTMAP_FULL_HDR UNITY_LIGHT_PROBE_PROXY_VOLUME UNITY_PASS_FORWARDBASE UNITY_PBS_USE_BRDF1 UNITY_SPECCUBE_BLENDING UNITY_SPECCUBE_BOX_PROJECTION UNITY_UNIFIED_SHADER_PRECISION_MODEL UNITY_USE_DITHER_MASK_FOR_ALPHABLENDED_SHADOWS
Disabled keywords: DIRLIGHTMAP_COMBINED DYNAMICLIGHTMAP_ON FOG_EXP FOG_EXP2 FOG_LINEAR INSTANCING_ON LIGHTMAP_ON LIGHTMAP_SHADOW_MIXING LIGHTPROBE_SH SHADER_API_GLES30 SHADOWS_SCREEN SHADOWS_SHADOWMASK UNITY_ASTC_NORMALMAP_ENCODING UNITY_COLORSPACE_GAMMA UNITY_ENABLE_NATIVE_SHADOW_LOOKUPS UNITY_FRAMEBUFFER_FETCH_AVAILABLE UNITY_HALF_PRECISION_FRAGMENT_SHADER_REGISTERS UNITY_HARDWARE_TIER1 UNITY_HARDWARE_TIER2 UNITY_HARDWARE_TIER3 UNITY_LIGHTMAP_DLDR_ENCODING UNITY_LIGHTMAP_RGBM_ENCODING UNITY_METAL_SHADOWS_USE_POINT_FILTERING UNITY_NO_DXT5nm UNITY_NO_FULL_STANDARD_SHADER UNITY_NO_SCREENSPACE_SHADOWS UNITY_PBS_USE_BRDF2 UNITY_PBS_USE_BRDF3 UNITY_PRETRANSFORM_TO_DISPLAY_ORIENTATION UNITY_VIRTUAL_TEXTURING
Probably still applies, I can't remember the version when it changed
you right there was an error in the console
hmm does anyone know why my sprites renderers vanish when i change their shader? only happens on some levels and not others?
So, to add tessellation to a vertex blend shader, I assume adding heightmaps to textures is the only thing that matters for the fragment shader part
Adding tessellattion and displacement to the vertex shader is a separate action that will displace according to the height map blend, yea?
Hey all! I'm currently having a little trouble masking out a Tilemap using a LayerMask, unfortunately my "RT_GroundMask" is always outputting a full black texture, I have logged and double checked my LayerMask is propertly set. And checked similar approaches however, everything I seem to try doesn't seem to work.
public override void OnCameraSetup(CommandBuffer cmd, ref RenderingData renderingData)
{
var colorDesc = renderingData.cameraData.cameraTargetDescriptor;
// Create Blank "RT_GroundMask", and set it to be the current target.
RenderingUtils.ReAllocateIfNeeded(ref RT_GroundMask, colorDesc, name: "RT_GroundMask");
// Set our context "target" to the "RT_GroundMask".
ConfigureTarget(RT_GroundMask);
// Set the Blank "RT_GroundMask" to be black.
ConfigureClear(ClearFlag.Color, Color.black);
}
// Draw the mask of our "Ground" tag to our "RT_GroundMask".
public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
{
CommandBuffer cmd = CommandBufferPool.Get();
using (new ProfilingScope(cmd, _profilingSampler))
{
SortingCriteria sortingCriteria = SortingCriteria.CommonTransparent;
DrawingSettings drawingSettings = CreateDrawingSettings(shaderTagsList, ref renderingData, sortingCriteria);
context.DrawRenderers(renderingData.cullResults, ref drawingSettings, ref filteringSettings);
// Set a Global RenderTexture for our local RenderTexture of our mask. ( To be used in other passes. )
cmd.SetGlobalTexture("RT_GroundMask_GLOBAL", RT_GroundMask);
}
context.ExecuteCommandBuffer(cmd);
cmd.Clear();
CommandBufferPool.Release(cmd);
}
public override void OnCameraCleanup(CommandBuffer cmd) { }
}
One thing that is a little confusing is my:
filteringSettings = new FilteringSettings(RenderQueueRange.all, settings.layerMask.value);
Debug.Log(LayerMask.LayerToName(settings.layerMask.value));
is returning "Deployable" which is not the LayerMask I have set in my renderer feature, however I have set my Tilemap to "Deployable" to match, I assume that is a part of the problem, additionally I have set ConfigureClear as so:
ConfigureClear(ClearFlag.Color, Color.red);
however, it is still logging a black screen. If anyone has any idea what could be causing it any help would be amazing! Thanks all.
With the descriptor, you should do colorDesc.depthBufferBits = 0;, otherwise you may be allocating a depth target instead
Hmm, upon trying it I still seem to get a black output, what's particularly strange is even when changing my
"ConfigureClear(ClearFlag.Color, Color.black);
to something like "Color.red". The "blank" output still seems to stay as black.
Frame Debugger window might give some clues
I'm currently trying to use that, the way I am monitoring my global texture is by using a square sprite using a test material that is referencing the global texture, which exposes it to my frame debugger, but I can't seem to find much insight as to why unfortunately.
Here's how it is displayed:
I meant the feature itself should be listed under the frame debugger, with the clear and object rendering commands. If not it might not be enqueued correctly, maybe check the AddRenderPasses function?
If you're in Unity 6 note that features have changed a lot and use RenderGraph APIs (RecordRenderGraph function) rather than Execute. Unless you set it to compatibilty mode (not sure where that setting is though).
Oh I see, you're totally right. I don't even see the rendering feature itself I don't believe.
which I also think may be worth nothing that my "Layer Mask" is set to be "Ground" however, when logging it's value is actually searching for Deployable, I have tried setting both my tilemap to be "Ground" as-well as "Deployable".
public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData renderingData)
{
renderer.EnqueuePass(P_GroundPass);
}
could it be that my renderer is bugged itself?
hello shader gods, are there any good resources one may refer me to when making impact frames?
Would anyone happen to know why or how my custom renderer feature attached to my 2D URP asset renderer wouldn't be displaying in my frame debugger? I'm currently on Unity 2022.3.25f1, which I have had it function properly before. Everything should be propertly attached and I appear to be Enqueuing it properly as-well. Any ideas?
It's also probably worth noting that log statements inside the renderer feature are firing, specifically a log inside the pass constructor
out of what is seemingly absolutely no-where changing my
ConfigureClear(ClearFlag.Color, Color.red);
``` seems to have somewhat magnically started working, so I am now getting a blank red screen which is definitely progress!
Again for seemingly no reason my entire renderer pass has started working, I believe I reset my 2D URP asset which seems to have fixed everything, it isn't defining my pass in the frame debugger still however, my masking script is working as intended!
Hey, does anyone know if using the boolean node in the URP shader graph makes the shader calculate both branches or not, even tho one of them will not be used based on the branch value ?
"Both sides of the branch will be calculated in the shader, even if one is never output."
https://docs.unity3d.com/Packages/com.unity.shadergraph@6.9/manual/Branch-Node.html
So if you want to do any sort of true branching, your best bet is to write a bit of custom hlsl and [branch] an if statement manually
Does tessellation have overhead compared to just a high poly version of a mesh?
It does
So, theoretically, if I can't see shit in my game and objects are culled after 10 meters, it would be better yo just use high poly objects, yea?
So i got this outline shader working using Custom Pass, but it sticks into the skybox like an old windows xp bug. Is there an easy way to fix this
IIRC, depth is not cleared by defaut in between frames, I think this is what is happening. I don't remember if there is a setting to force it somewhere.
is there a way to just exclude the sky and fog volume from the custom pass
does the SRP batcher basically replace the need for enabling GPU instancing on a material ?
SRP is just another form of batching which is considered superior on most cases. GPU instancing might still be faster in some cases which I'm not entirely sure what that would look like but if I had to guess, one with a ton of the same mesh might be faster with GPU instancing
is there any way i can use the same gradient noise map( the shader graph is for a water plane, and c# script there to float objects in the same way the water plane bends)
So after digging, the bottem half of my shader graph is fine, but its the HD Sample Buffer that is doing the weird glitch, but if i remove the Buffer, i dont get half the detail in the outline. I have little to no clue what im doing with shader graphs, so i dont know if that helps
also, if i change these float values at the top to be a greater value, it lessens the effect of the glitch, but it also lessens the detail aswell.
importing a shader graph and its failing to compile is there any way to fix this
failing inside the editor not just the build
Hi! Is there a way to "grow" a texture mask via shader graph? I've created a texture that draws points corresponding where the player has passed in the terrain. I'd like to "grow" the points to use them as a mask for a map and create a fog of war
that's the texture
the only method I know right now is by directly creating a green circle where the player passes with a longer diameter, but this creates many optimization problems (I'd have to call it on nearby map chunks since the map is splitted in chunks, and it would be computationally heavier than calculating that on the gpu side)
what I'd like to obtain is a "larger" circle where now there's a green line, as if I increased a stencil width with a painting program
Maybe a compute shader where you loop pixels in a radius to paint them
To answer your question, no, you can't do that in a shader graph.
Either what dlich said or jump flood algo to compute a distance field to the thin line. The former would likely be faster and easier to implement. Luckily there's resources out there for doing drawing app using compute shaders which essentially do the same thing as you want to https://bronsonzgeb.com/index.php/2021/07/03/a-simple-gpu-based-drawing-app-in-unity/
Well, if you look at the gradient noise node implementation, you'll find the noise generating code.
You could try to re-do it in c#. I'm unsure though if it will give the exact same results.
The other option is to have a single hlsl with the noise logic, call it from a custom function in shadergraph, and a compute shader to read the value in c#.
yeah it said that it was one possible implementation so wasn't sure. ill look into the hlsl with noise logic thnx
Thanks, I've basically done the same but via CPU, I'll move my code later into a compute shader 🙂
I once did a simple drawing program in Unity using only CPU too and it was surprisingly fast. I'd still definitely prefer compute shader for better performance, it's also exactly the same idea so not too hard to convert
can I use a simple unlit shader (from shader graph) for a UI element?
seems like transparency is not working with sprite unlit in a raw image
You kinda can but it will break some things, masking at least and might break ordering too to some degree. Looks like 2023.2 onwards UI shaders have been added. Unlit shader might work well enough too but it's not really recommended
would anyone know if there is a recommended way to convert this to a black/white mask? I am currently trying to create a mask using a custom renderer feature, I understand that when masking it shouldn't matter but I worry that if I am masking a black texture it may not mask property, would I need to convert this to black/white?
I assume a one-minus node may just do that if I pass in the alpha?
Is it possible that a texture is getting compressed (and so colors are different) when I create a texture via code and pass it to the shader?
I've created this system to filter out colors in a map and apply an image instead of that color (with a similar color in this case)
It works well for every color except the second one in the image, the light green. It's not detecting that no matter what I do
I'm pretty sure the color is correct: both via code and with color picker the color is the same (8FD900)
That's the result... the green color is the only one not matched
"Comparsion" nodes only work with floats (you can see the inputs are light blue / (1)), so I'm not sure this graph is really working as you expect
What can I use instead of this?
it's also working almost well with other colors 😦 can't find any other shader node useful for this
There's Color Mask / Replace Color nodes which may work. But with each added colour it gets more expensive...
If your aim is to swap colours, it could be cheaper to have the texture as specific greyscale (or red) values that map to the X coordinate of a palette texture, similar to this example : https://www.cyanilux.com/tutorials/color-swap/#palette-texture
Anyone know why i get all pink material after downloading Stylized particle effect from unity asset store
The shaders used by the package are not compatible with the render pipeline you are currently using.
Check the doc of the package if they provide some way to convert them, the most usual way is to have an embed .unitypackage per pipeline that will import the necessary shaders and convert the materials.
Wild guess : look into that "URP" folder (if you are using URP though)
Well, i think im using built in render pipeline, so my objective now is to change it to urp?
It worked, and it's currently not impacting performance, ty 😄
Anyone know why this issue occurring? Some times its visible some times not.
the operations are causing certain elements to be ignored
due to dimension mismatch
like passing a vec4 into a vec3 function (the last element of the input will be ignored)
Here is the Graph could you please let me know where I am doing mistake?
passing vec4 into vec3 input
for example.
Its only a warning, you could choose to ignore it, but know that parts of your inputs are being ignored
Afaik SG nodes handles truncation automatically. Connecting a Vector4 to a Vector3 port shouldn't create warnings. But there may be mistakes in the generated code which you can't fix. Just have to ignore it
Why would they not create warnings, even if the truncations are handled automatically?
It's for the developer to know that information is being ignored
That might be what you want, and it's just there to inform you
because this could be a mistake and could cause unwanted behaviour
Thanks I will try to fix it.
The shader will handle it, and you should be aware that it is happening.
And you could choose to be explicit by truncating the vector manually, to get rid of the warning.
I currently have this shader above which is being utilized in my custom renderer feature, which is supposed to mask out all of the "Light Texture"(TOP) where there isn't any alpha on my "GroundMask" (BOTTOM), with the intended result being a texture containing light only in the blank spaces between my tiles shown in the bottom image, currently this outputs a fully black image when placed as seen in the shader graph with a one minus node. Without the one minus node the output is instead identical to my light texture (TOP). When using other channels other than alpha I get a pretty weird result which sort of obfuscates my "GroundMask" (BOTTOM), mostly darkening it. If anyone knows what I could be doing wrong any help would be very appreciated! 
I think that your ground mask RT doesn't have any alpha channel. (so defaults to 1)
That is almost certainly the problem, I appreciate that. I hadn't even considered it!
Yep, B10G11R11 format, no alpha 🙂
Would there be an easy way to configure my renderer feature to support an alpha channel?
ConfigureClear(ClearFlag.Color, Color.black);
currently this is how I am creating the blank space with the "ConfigureClear" function, do you know any way natively to just assign a "0" alpha instead?
Or if it would be easier just mask the cleared area another way that might be more easily supported if alphas aren't ideal.
You can use Color.zero . But to have alpha in the RT, you need to create the RT with a format that does support alpha.
Else , since it looks like the background is black, you could simply do a color mask
Ah I see, alright! Thank you very much, I'll try that now.
Also by "Color.zero" do you possibly mean "Color.clear"? It states the RGBA would be 0,0,0,0 meaning zero alpha. Does that sound correct?
Ah, yes, this one. On top of my head, I though "zero" was there.
Ahh I see haha, I really appreciate it!
would you happen to know the name of a recommended color format for supporting "RGBA" would the format be "RenderTextureFormat.RGBAUShort"?
*I am quite unfamilliar on the subject but does the "Short" suggest the existence of a "Normal" or "Long"?
ARGBFloat should be good 🙂
"RenderTextureFormat.Default" worked and outputted the expected render texture, however it appears to still be "B10G11R11" which is a little strange.
That's not the ground mask ?
Upon further inspection this was a dumb observation haha.
that's my bad.
does anyone happen to know of a way to directly save a png of the previewed render texture in the frame debugger?
The ReadPixels doc has an example you can take inspiration of.
Asign RT as active, readpixels to a texture, save to disk.
Is there any way directly from the inspector to download the previewed image directly?
Else, if you use a CustomRenderTexture, it has a built-in "save as png" option 🙂 (in the inspector menu)
Okay, appreciate all the help!
Windows snipping tool 🤷♂️
Haha this is going to be the solution, I think adding a copy texture could be a nice inspector addition which would just format to png and save to the clipboard.
I'm sure this is somewhere in the absurdly long list of "nice to have" low hanging fruits.
Hi, I’m trying to create a shader that animates only once. It would be a transition from one texture to another when a condition is met. Here I’ve used a bool, but eventually this effect will be for a hover effect on an apple vision UI.
The idea is to have a texture that animates when the shader is in Activate, that resets to its initial state when the bool is unchecked, and that the animation resumes when the shader is reactivated.
The problem is that the Time value doesn’t reset to 0 when I reactivate the bool…
I’ll leave a photo of my shader as is and a video of what I’ve got so far.
Does anyone know the best way to pass an RTHandle between two different passes? For example if in my first pass I have an RTHandle named "Pass1RT" and I am trying to use "Pass1RT" in my second pass, how would I send "Pass1RT" to be used in my second pass?
You should probably manually pass in the time as a parameter from C#
shaders never work and i cant figure out the fix for it
ive imported a lot of shaders and they always end up like this
If you're using URP you have to upgrade your project to the Universal Render Pipeline or whatever pipeline that shader is made for!
After you've done that you have to convert the materials to use URP as-well. IIRC it should be in "Edit -> Rendering -> Materials -> Upgrade to..." if I'm not mistaken.
this? because its already installed
Have you assigned a URP asset?
in Edit -> Project Settings -> Graphics -> Scriptable Render Pipeline Settings
I believe if you don't have one there should be a button to create one? If not, right click in your assets folder, click create, scroll all the way down (you may need to click the arrow at the bottom to scroll further) go to rendering, and create a suitable URP Asset.
More than likely you'll need to be creating the top option, but I believe there is a 2D specific one as-well.
Have you tried this?
it seemed to do nothing
is the material selected when you click the button?
yep
It should take a sec to load and fix itself, what is the material for if you know?
Is it a URP material, or would it possibly be HDRP?
Hmm, maybe double check that everything in the material is property assigned, if it is I can really only recommend recreating the material by right clicking the shader (not material) in the inspector and clicking Create -> Material which will auto assign the shader to a new material which may work?
Sometimes Unity also likes to turn shaders pink if they are using HLSL directly, but should still work fine if used.
Does it give more errors in the console window?
It could very well be an old hlsl shader which uses something deprecated.
Do you know what kind of shader it is possibly?
Yeah, HLSL is fine but some old shaders to my knowledge need to be updated or they'll sometimes throw errors. I'd try finding a newer shader possibly in some sort of tutorial if you aren't familiar with HLSL. I'm sure there are LOTS of BOTW inspired toon shaders for Unity!
whats weird though is that it happens to almost every shader i import
not just this one
ive tried plenty of other botw shaders
Do you have a specific place you get them from?
the botw ones i just find from github but also other shaders ive purchased and/or gotten from the asset store do the same
Asset store shaders will usually be updated or provide the way to update the shader if they break, maybe try checking the store page and see if there's anything. If I were you I'd maybe try to find a youtube video or guide that has comments you can cross reference from in-case anything breaks.
However, if you do believe it might be a problem with unity, you can always create a new project and try installing URP from scratch to see if there's something wrong with your current project.
just did that a minute ago im importing the shader rn
It could also be possible to just download a matching version of Unity that the shader was made for if you don't need any of the updated features.
it works fine in the new project. weird
Yeah, that's the beauty of Unity :D
It could really be a lot of things, I'd try to delete and recreate a new URP asset in your old project to see if that fixes things.
do i have to restart unity or anything when i change the urp asset?
You shouldn't but it wouldn't hurt. You may have to upgrade your materials again though.
whats also weird is that one of the shaders used to work on the old project but now it doesnt so im not sure what changed with it
Hmm, strange. Did it stop working after adding the URP asset?
no, that happened awhile ago i havent messed with anything urp up until i need help
Sorry I meant in the new project!
the new project doesnt have any issues with shaders
Oh sorry I for some reason assumed you were talking about the new project.
Absolutely worst case you could migrate everything to the new project, not sure if that's an option for you but it could save you some headache.
yea, thank you for your help though!
Of course, good luck!
@hexed sorrel i dont know what changed maybe restarting but it suddenly works now haha
Oh, amazing! Yeah, sometimes Unity just needs to reload everything. Happy it all worked it!
So is it possible to create a sort of curvature map with shader graph, like you would with a curvature generator in substance painter?
Like, I want to apply a texture along the curves of a mesh
Could you send a visual example of what you mean?
Or, even better, if I have baked a curvature map using substance painter, could I use it?
even simpler I guess
If you could generate a baked Texture, displacement map, etc. you could easily use it in Unity.
Hmmm....it's a mesh map within painter...but if I could bake it into a texture....
Shaders are generally used for effects that are affected by a Runtime-specific element, it can take advantage of time, location, scene elements etc.
But if you have a 3d object you're creating in substance painter, very likely you could import it directly to Unity.
I don't know what you're trying to tell me with this
yes I'm exporting substance meshes and textures into unity
maybe I should specify what I'm trying to do
Right, but if I am understanding your objective you could use a displacement map in a material to get your desired effect.
You shouldn't need a shader to do that to my knowledge.
I am tessellating and displacing as a separate thing
ok I need to tell you my idea
so I'm making rocks for my game
I changed around whether I wanna uv map and paint them all or if I wanna use a triplanar texture bla bla
I've been bouncing around how to do them
it looks the best if I UV paint them in substance painter. One thing I do there that looks good is using a curvature generator which is like a mask which is applied to the curves of a mesh
so I make a smoother texture along the curves and make rougher, more displaced textures in the middles
that looks good to me
so I had an idea
rather than UV mapping each rock individually (unfortunately atlases are low res for me, don't ask), I can somehow achieve that curvature generator with a shader in unity
so that I can use one single material as triplanar to apply to all my rocks
for performance reasons is the idea...and build size
does any of what I said make sense?
So, sorry I'm still a little confused here. Are you trying to procedurally randomize a "rock-like" texture based on parameters which can be dynamically randomized in Unity to create "procedurally" textured rocks? Or are you just trying to save space by utilizing your substance painter curvature generator directly on Unity.
More like the latter, but it doesn't need to be directly applying my curvature mesh map
It could be finding it with shader graph
Or something with the nodes
Also are these rocks very prominent in your project? Generally rocks will use a couple precreated materials which will be unwrapped onto the meshes, and a shader will be applied to add moss or greenery to the tops/polish if that is preferred.
Like I would provide a base texture, possibly a noise mask secondary texture and the "curvature" texture
Whoch I would provide, not generate procedurally
Yes, very prominent
Do you know what this "curvature" texture actually is?
It's a cave game...rocks are literally all I have
It would be a texture of my choosing
Okay, is this a mobile or browser project that needs to be very concerned about storage?
Because by far your easiest option from what I understand is going to be unwrapping everything, which will really not be as large as I assume you think it will be.
I would recommend trying out different rock materials and maybe looking into "polish" shaders that can work with them to make them fit better into the scene if you are really concerned about optimizing.
oh I've tried a lot of different stuff, including texture atlases but they are too low res in the end, even at 8k
Sure, but I really wouldn't be too concerned about optimizing too much until you've got performance problems.
Strange, I'm not really too sure why that would be.
Do you have a preview of what your game actually is supposed to look like to maybe give me a better idea of a direction you may want to go?
yea
here's a preview of my textures
some wall textures
Here's a test rock which I don't like
I see, those look pretty high res to me what specifically are you trying to change about them?
yes lol
they look a bit bland
they ARE high res
everything is 4k
but I'll try to dig out a photo of my texture atlas if I have it somewhere
Sure, I assume you've looked into megascans?
I feel like they might be exactly what you're looking for asset wise.
I know of them
They've also got extremely high resolution materials you could try alongside your own meshes.
I'm ok with the resolution of my stuff
I use sbsar material
and mix and mash them
they have an infinite resolution, so it's not a problem
I see, so what are you looking to change about the rocks that can be done in substance painter (using the curvature generator)?
I'm trying to find the photo
I can almost guarantee with enough time and effort you can pretty much create anything in theory using shaders, it's just the complexity in how worth while it is to do. Shaders can get pretty laggy quickly especially if you don't know what you're doing. Most of the time I'd say especially in your use-case it's best to stick with finding materials and assets that look good together, and maybe polishing with a shader afterward if you feel inclined to.
anyway, it doesn't really matter
the rock I showed I know how to fix
with the curvature map
or rather, the texture used for the curvature is so heightmappy that it looks like nothing
I know how to fix what I want to fix with the textures
I was just wondering
whether using one material for all the rocks would be better
than just manually painting and exporting textures of each one
it really doesn't affect much, generally projects will use a variety of unique materials scattered across their projects. The amount of different materials really doesn't affect performance much unless they are using a shader, if it's just a texture, and a bunch of maps it's really only the tris that are going to be your issue.
I found a picture
The amount of materials will really only increase project size.
basically this is the 8k ''low res'' texture from the atlas
you can see another rock in the background from the same atlas
you see the texture applies round the curves
and then a rougher texture inside
Ah, I see!
I will redo that just with heightmap displacement and higher detail
it will look good
If you have the heightmap it's definitely possible in unity.
that must have been the build in pipeline then
or something...I know that amount of materials increases draw calls but might not be the case in hdrp
I mean generally yes reducing the amount of different materials will create some difference I really don't think the difference is very noticeable at all.
But with today's hardware and the scope of most indie projects, unless you've got an insanely poorly optimized project performance should usually be pretty stable. If when you've got it looking good you notice it's not performant it's generally better to optimize from my experience and not give myself a headache trying to make sure everything is perfect during the process.
But to answer your initial question yes, using a heightmap texture you could create a similar effect to that of the "curvature generator" in substance painter (if I am understanding that correctly), but I think to get the level of precision I think you're looking for I think you're likely better off creating a handful of really good looking rocks/materials with substance painter and scattering them around your scene. Then after you've got everything to your liking you could fiddle around with using a shader to diversify them even more.
Yeah thanks I'll do that then
I don't need that many rocks tbh
As you can rotate them any which way
Makes them seem diverse
Also might create a planar sand effect on some etc
Besides
You can't see shit in my game, I'm culling everything beyond 12 meters so I shouldn't worry about draw calls I guess
Yeah, that is another thing. Fog is really good at allowing super concentrated detail around the player, so as long as you aren't forcing them to render the entire scene at all times. Performance is really not going to be an issue.
ok thx
I should stop overthinking
I always do that
Haha, don't worry we all do. That's part of the fun, I hope your project goes well!
Remember to make threads for big or long discussion topics
That's the issue, I can't use scripts.
As I'll eventually be triggering the shader animation via the Apple Vision headset hover, I can't use it to trigger scripts. Only texture or color switching via a shader.
Hey everyone, I made this simple shader to create a ripple effect. At the moment it simply takes a textures a distorts it but what I want is to have it affect all background elements while being independent from them if that makes sense? I'm just not sure how to do that so if someone can point me toward a tutorial or documentation I would appreciate that :D
You'll need to use scene color, or whatever the node is called, basically, the main render target, instead of a texture. Then you'll also need to make sure that this shader/material renders after the rest of the geometry.
Gotcha, I'll look into that, thank you 🫡
At a high level, what's the best way to approach culling/chunking grass instanced via compute shader? Passing data to the GPU every frame, assuming the camera moves, does not seem like a good idea, but I'm blanking.
oh hmmm, i guess I don't need to pass any data to the GPU, the calculations for what to cull could technically all be done in the shader. But then with a large enough map/enough grass to cull, running those calcs becomes its own issue.
in which case, you'd have to cull the culling.... via chunking???
You need to decide where the position data comes from, of course. Textures or meshs are probably going to be the best source.
My terrain is divided up into chunks. I compute the grass positions from the terrain meshs which has the benefit that those are already on the GPU anyway. So all I have to do is dispatch a compute shader per terrain mesh that is visible every frame
Is it possible to obtain such patern using only nodes in Shader graph?
Not with the built-in voronoi, but you can use a custom function. See lower sections of this older article of mine : https://cyangamedev.wordpress.com/2019/07/16/voronoi/
thanks
(so, not only nodes ^^ )
I m currently reworking my 2D-game and some of its systems.
I made a shader for the player (switch colors, invert colors, glow, etc). Nothing really fancy.
Is it a bad idea to use the same shader for other things (NPCs, objects, etc) too, even if they wont use most of the shaders functionality? Or would this affect performance too much?
It helps for batching, but indeed will increase global shader cost.
Note that you can disable some features with toggles and "if"s in the code/graph.
If done per material/object, it comes basically for free.
I already use branches in shadergraph to turn off features when not needed.
And I m doing this for each object differently (because not every enemy should also turn red, if my player gets hit)
this is my shader I want to use for my enemies and objects. I dont know if I will ever use the color-swap for grass or pots or something.
Is it static (keyword) branches or dynamic branches ?
keyword I guess... I dont really know ^^
Well, you can see it from the blackboard ^^
The difference is that the keyword version will generate shader variants, so each combination of those toggles is virtually a different shader, and can not be batched.
The non keyword boolean on the other side, doesn't create variants. But since it is constant over the whole object, at execution the unused branch will just be skipped, while objects can still be batched together.
Total 3d noob, can someone tell why this in blender becomes this in Unity? Shader issue?
I m using non keyword
Missing lighting ? What type of shader/material are you using in unity ?
Is there emission enabled when using Lit ? Do you have a light in the scene ?
Emission seems to have no effect, yes there is light
🤔
Can you post screenshots of :
- the model import settings
- the inspector of the material
- the scene hierarchy
Does anyone know any way for me too get "rid of the material inside of the ship? I am using shader graph and I dont know if there is some sort of setting for it or something. Basically I want my material to behave like water so that means it cant be seen "inside" of the ship
Oh I think it might because I messed something up with the render pipeline, actually nothing 3-dimensional shows any shadows
I originally created the project with SRP but I might have done something wrong since I needed the shader graphs
That's trickier than it sounds like. You want to use Renderer features and stencil to mask out the inside of the ship, and not render water there.
I'll just create a new project honestly, seems the quickest fix since it's so early
Ah i see thanks for pointing me in the right direction. I will see if I can do some research on it. Just a question, is there perhaps some kind of name for it? Like the name of the feature just so I know what am I even searching lol 😅
Hello, I'm working with Stencil on a custom Shader on my VR Project.
The material where is applied the material it visible only one one eye, how can I fix it?
In the image you can see a Door that make a hole in a invisible plane and you can see through
"Render Objects Renderer Feature" ^^ https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@13.1/manual/renderer-features/how-to-custom-effect-render-objects.html
Appreciate it a lot!
I think the issue is that the shader is missing informations for stereo instancing to work.
It would probably be easier to use a shader made with shadergraph.
If you are using stencil for masking, you might also want to user a RendererObject Render Feature.
@amber saffron Sorry for bothering but you mentioned renderer feature and stencil before and I feel like I am on the right path, just need some extra help to get there. So I have done my research on what stencil buffers are and renderer features and so on, and I feel like what I have done is correct(in the image) because I want to render the water layer only when stencil value is not equal to 1. Which is what the ship layer is set to. In my mind this should work but as you can see I still have the problem. And I have been stuck on this for a long time, testing different pass/fail operations but no fix. I have my ship / water set to the correct layers
In shader graph, is there a way to have random values generated only once, every time an instance of shader is refreshed, using only nodes?
For example, I have a sampled gradient of a rainbow and I want to make it so every time I refresh shader it will have a random color from the gradient
Not sure about doing it in the shader but you could pass the random values from C# into the material/shader
Or a seed that the shader uses to generate the randomness
that is an option, but I was wondering if it is possible to do purely in the nodes
I assume it would also be possible by writing a custom node for generating random number but not sure about that
It would still regenerate each frame, unless you add som weird branching I guess
@slender ore I have wondered about the exact same thing earlier and I haven't yet found any run dependent random seed to be used. C# definitely works but if there is something that works with only nodes, I haven't found one at least
Water Mask
In VFX graph there was something like that built-in if I remember correctly
yes, there is normally functioning random number node
Either way you'd need to somehow capture a seed for RNG just once. So you need a property that is set ad not changed. Doing this by shader feels kinda hacky compared to pretty straightforward Osmal's solution. Idk about VFX graph, but I think it works different to the shaders, which are basically doing Execute() functions each frame
alright, thanks for all the answers
Is it possible to add an equivalent to texelFetch(...) in a Unity Shader, such that it can still compile to WebGL2.0? (ideally it actually uses texelFetch in the output code...)
Isn't that the same as a sample operation 🤔 ?
texelFetch is (as far as I can tell) equivalent to texture.Load(...).
It specifically grabs a single texel from a specified LOD (using integer pixel coordinates).
This behavior does not depend on if the texture normally samples bilinearly.
From what I see here, if the texture does sample bilinearly, you can specify the sampled pixel in the group.
Else, indeed, texture.Load seems to be the closest thing. Not compiling for WebGL2.0 ?
texture.Load seems to require shader model 4.1, which only supports transpiling to GLES3.1+ (whereas WebGL is GLES3.0)
on the other hand, this functionality is available since OpenGL1.3
Well, texture.Sample is also since shader model 4, but I'm pretty sure WebGL2 can sample textures.
I think the underlying cross compiler has matching functions in that cases, for example the equivalent to texture.Sample in SM3 is tex2D.
Now, need to find the equivalent to Load
I'll try to find one. If not, I guess I'll just hope Unity is lenient about using modern syntax with legacy targets (I don't have a DirectX machine on hand to test).
Did you try already with texture.Load, it didn't compile ?
Worst case, you can use texture.Sample, but calculate the UV of the center of a pixel using the texture dimentions 🤷♂️
What is the use case btw ?
It seems to work fine when compiling to OpenGL. Not 100% on whether it'll work on Windows, but the internals of the core SRP package seem to suggest it all uses shader model 4 internally.
Yo, using URP shader graph, is there a way to tile a shape, like you tile a texture?
The one on the top tiles, but the one in the bottom only scales down, but never repeats
so i'm left with a lot of dots and a single, lonely square
Use a Fraction node between the Tiling And Offset and Rectangle nodes
It worked! tysm
I am trying to make multiple color palettes for my characters. I want to be able to change them via code. I have multiple sprite sheets per character. Can someone help me out?
Not exactly sure which channel to use for this question but here goes,
I have a render texture on my camera that is then assigned to a canvas image to give a cool retro feel to my game with large black bars on each side of the screen. Further in development I decided I wanted to add in some pixel art, but heres the problem, the pixelization of the render makes the sprites almost unrecognizable to the way that I originally created them. I want these sprites to either have a material that doesnt get affected by my render texture. Best way of going about this?
What's wrong with my UI gradient shader?
It seems like where it ends, it's actually lighter than the actual screen color (see image below), it's supposed to be a simple transparency gradient from left to right
We can see a line where it ends somehow
Shader "Custom/UIOpacityGradient"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_Color ("Color", Color) = (1, 1, 1, 1)
}
SubShader
{
Tags { "RenderType" = "Transparent" }
Blend SrcAlpha OneMinusSrcAlpha
ZWrite Off
Cull Off
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata_t
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
sampler2D _MainTex;
float4 _MainTex_ST;
fixed4 _Color;
v2f vert (appdata_t v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
fixed4 texColor = tex2D(_MainTex, i.uv);
float alpha = 1.0 - i.uv.x;
texColor.a *= alpha;
fixed4 finalColor = texColor * _Color;
return finalColor;
}
ENDCG
}
}
FallBack "Diffuse"
}
is it possible to have an object effect the picture behind it with a shader graph?
im p sure but idk what its called and i cant figure it out myself soooooo
(pic is example mockup)
Scene color node or something loo Iike that.
Is there a way to turn a shader\material around?
I have this liquid shader I got from github and as yyou can see its vertical and moves when the model moves, but I would like it to be horezintal (2nd pic, had to flip model foward for this)
Basically just flip the shader 90 degrees foward while still keeping the liquid effect
The code you pasted is c# responsible for wobbling, not actual orientation of the liquid, maybe paste actual shader code
But imo these screenshots are alright. I mean I'm not sure what you want to achieve. Flipping liquid surface around 90degrees will give you not natural results, unless that's what you re looking for
Oh okay I will look for it, really new to these things so forgive me >.<
Uhh I mean more like the liquid to bend in relation to the bottle mesh and not in general
But now that I think of it all of the bottles are as one big mesh so that could be the issue
Probably, yeah. It looks like the angle is based on world orientation so ig it would be easier to make a new shader for your specific needs
Alright thank you^^
Hey folks, fairly new to Unity, and hoping I'm going in the right direction here. I have a render texture I'm generating, and then sending out via a plugin as a network stream. However, for some hardware reasons, I need to send a different resolution over the stream, so I need to scale the texture. What I'm looking at doing, and want to confirm I'm understanding correctly, is that I should be able to use Blit to copy from one render texture to a new render texture, the new one being scaled. Just want to make sure I'm chasing the right rabbit before going fully into the rabbit hole 🙂
Looks like this works! But I guess I'm not cleaning up my textures properly, because I very quickly burn up memory. Close though!
My shadergraph shader stops working when I enable a second camera. I assume it's because the Screen Position node either doesn't know which camera to use or uses both of them. Any ideas on how to fix this?
The shader still works in the scene view with both cameras enabled and in play mode. Just not not in the game view.
So I just used a technique called "Change random settings until it works"
The problem got fixed when I disabled the depth texture and opaque texture on the second camera.
This probably wouldn't be a good solution if you wanted the second camera to render the scene the same way the main camera does but fortunately for me the second camera is just part of another shadergraph and doesn't need to render the scene.
Hello, I am trying to create an inky blob effect for the background of the items in my game.
This shader is added to a material which is added to the Image component of a gameobject which lives on a canvas.
The sahder is Sprite Unlit.
The problem: It looks perfect in the Main Preview window of the shader graph.
When applied to my Image component / canvas element though, it looks like there is no gradual transparency, but a clear cutoff. I can modify the alpha clipping threshold in the shader as I wish, it makes no difference.
Any ideas why?
This is how I add my material with the shader, and this is how the shader itself looks like:
The alpha doesn't work because Canvases don't support sprite shaders
Canvas type shader graph should be used
https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@16.0/manual/canvas-shader.html
if you think about a game like command and conquer, where you have fields of resources that collectors go and get... I assume back then this stuff was held in tile properties or something, for how much, collectors decision making and stuff, could it be worth figuring out a way to do all of that kind of stuff in compute shaders somehow? like... would there be a tangible enough speed benefit there or would it all just clog up and be unhelpful.. like a procedural texture2d could represent distribution and quantities in a 'grid', perhaps checking that data to determine where to mine, adding and removing pixels etc. without managing thousands of gameobjects
I dont think you actually need to manage thousands of gameobjects, except, maybe the unit.
the field resource are treated as tiles just like you said, and the resource collection only change the tile data, which doesnt need to be changed often, and that usually only change at limited number of tiles. Now using compute shader might indeed will clog up the system, as shader will always get executed, for every texel drawn.
right... it's just a 2d array of data... I guess in my head i've been thinking a bit about visual representation as well, and projecting a data texture through the shader could visually blend resources in and stuff, but there'd be better ways to do that I'm sure
Visuals are a separate part of it, you'd be rendering them with some kind of shader no matter how the data is handled
Such arrays can be optimized in many ways even without getting into compute shaders, but I think it fits the task
C&C games didn't need anything so fancy, you can get quite far just by separating arrays into chunks to narrow down the get/set operations
Techniques like compute shaders and multithreading are leagues ahead of that both in efficiency but also in complexity so to utilize them well it's important to understand what's possible without them
And so, if it’s a 2d grid / array that represents the resources, how about when it’s on 3d terrain? It’s an array of 2d objects and the resource quantity and height are each stored each object? (I guess i was thinking that the rgba of a pixel would nicely store x y z quantity)
Thank you so much!
hey! im not sure if this is the right place to ask but here i go, my friend made me a shader graph for a meteor effect, it seems to work just fine in the shader preview and when looking at the material icons it looks fine, but when put into the scene its just all blacked out, its just the base colour and none of the emission from the custom shader graph is being applied, any idea why, been stuck on this for ages.
here's what im using if important:
Windows 11, HDRP, Unity 2022.3.9f1 (need to be on this version for this project) and whatever <DX11> means
what i mean by working in material previeew but not in scene
I am using unity 2022, it seems like canvas shaders are not supported there. is there any workaround I can try?
The generated shader code can be modified manually to include the code canvas shaders require, but I'm not familiar with any specifics