#archived-shaders
1 messages Β· Page 8 of 1
A quick way to figure that out?
I think checking if "_StencilComp" == 3 would work
Hey! I have 2 game objects sharing same shader, is it possible to make surface inputs independent? Right now when i change for example float "Tint" same value automatically is changed in another object. Shader shares same material. Do I have to make 2 materials or there is another way?
You need two materials
But that would be on the material, not the component. Oh material != materialToRender while maskable is on might be an approximation
i really don't know anything about shaders but i tried to do double sided material and it always sets the color of mesh to white, even when i change it in material properties to any other color
Shader "DoubleSided/DoubleSided" {
Properties {
_Color ("Color", Color) = (1,1,1,1)
}
SubShader {
Cull off
Pass {
ColorMaterial AmbientAndDiffuse
}
}
}
``` can someone help?
anyone know how to have a 2d int array (int[,]) in a compute shader?
i cant figure out how to define one
https://www.youtube.com/watch?v=ERA7-I5nPAU In this video there are a bunch of shaders that emulate pixel art. I am not very shader savvy, so is there somebody who can deconstruct this?
Date of Recording: 2020-11-14
I took a bit of a break from the usual tech updates this week to record a making-of video detailing what it's like to create a scene from start to finish in the Unity-based pixel art game engine I've been developing.
I found some neat modifier stack tricks in Blender for creating procedural, non-destructive detail...
the problem with this is that the size of the array in the shader is compiled, is there a way to set it dynamically as my array size is relative to the texture resolution
???
Thats pretty simple in reality : he uses a "cartoon" shader to have this lighting, and then he is rendering the whole screen in a low res texture, than he displays this texture using UI image on the screen
That's called a render texture : you put this in your camera output and you reduce the resolution
Hi, I'm very confused on what's going on
How do I properly sample _mainTex using the thread id?
I'm getting a Shader error in 'Test': cannot map expression to cs_5_0 instruction set at kernel CSMain at Test.compute(14) (on d3d11) at the moment
What about the trees though? Towards the end of the video you can see in unity that each object has an individual shader, so how can it be one thing applied to the camera?
I'm pretty sure he does not uses an other shader for trees, seems like he just applied a very strong noise to the leaves to have this effect
You can see when he is in scene mode he does not have the pixelated effect
Uh huh. So each material is just toon lighting with different colors, and the pixilation is added to the camera?
And he may have some noise distortion on his shader for leaves
I guess yes
You can see he has a material for each thing in his scene
It's a tad more complicated than reducing the render resolution and upscaling it, note the flat colours and lightened outlining in the mesh geometry
The tree leaf meshes could be the basis for a point cloud. The actual rendering isn't well explored in that video
the outlines look like they are baked on the rocks and stairs
looks like curvature data
Yep thats true
Would love to see his shaders for this
more or less a convexity map in addative
Date of Recording: 2020-10-05
For typical isometric pixel art blocks, shading is performed with a color ramp filter on a standard BRDF. To get the edge highlight and shadow effects, the depth buffer is sampled for adjacent points, and the pixel is brightened or dimmed based on whether it is closer or further to the camera than its neighbors.
G...
I'm asking because I'd like to translate this kinda style from a sort of orthographic perspective to full 3D. Would that work?
Explanation and link to the shader in the description
That might work yes, would be interesting to see
Reading through it, seems like it should work fine from a first person perspective
I'd be having a 3rd person perspective. The project is along the lines of p5 or FE3H. Half social, half combat. The camera would be panned a lot closer, and the scale would be larger. It wouldn't really be a diorama as seen here
Either way it's perspective rather than orthographic, post what you come up with π
Alright will do
that is if I'm able to come with something...
Ofc you'll be able ;)
Oh uh one more thing. For more detailed things like houses, or maybe a sign with text, I'll obviously have to texture that manually. But won't that stick out like a sore thumb?
Edited the code a little, but still, all I'm getting is a black square...
Mh, maybe you could do a custom shader using the texture but still having the toon shading ?
The texture will be pixel art still, so would the toon shader do anything?
hi, I would need some help to understand a shader
I'm trying to convert it for URP with shader graph
Toon shader is more about how the light and shadows are working, so i guess yes
Never did toon shading on unity so I cant tell you much more about that
Yes, what' s the problem ?
Ah alright. Well thanks a lot for the help. I'll see what I can come up with
I don't understand this line
float2 uv_Texture = i.uv_texcoord * _Texture_ST.xy + _Texture_ST.zw;
I'd rather the font separately from everything else but still do depth checks
It applies the texture tiling and offset to the UVs
_Texture_ST is populated by Unity maybe? it's only declared
Yes
ok, cool. but this job is basically what a Sampler2D does...right? in shader graph
No, a sampler2D just samples a texture
Now, depending on the version of shadergraph, the texture object can contain the tiling and offset value, and pass it to the sampler automatically
is this the case?
Does seem so
Are you able to use the "split texture transform" node ?
Or do you have a "use tilings and offset" toggle on the texture properties ?
"use tilings and offset" is unchecked
I can use that node
never used before
Ok, so if you check "use tiling and offset", you don't have to manually calculate it in shadergraph, and can just connect the texture property to the sampler to use it
Yeah, it does. I have a fix. I can access the material through materialForRendering but that has a bit more overhead than accessing the local materail so now I do this:
Not sure if GetFloat is better than .materialForRendering, tbh though
what if I want to use the node? maybe tiling is xy from the starting example line?
Then use the "split texture transform" node, apply tiling and offset to the UV with the "tiling and offset" node, and connect the texture from split node + manually tiled UVs to the sample node
I'm missing something π
is its possible to make Depth of field auto focus from depth texture ?
well in case i can't do auto focus with RayCast hit to mesh collider instead read Grayscale value from depth texture
relate unity Forums // Its same Idea btw
How can i apply a top texture and a bottom texture with a shader graph
Is there a node to merge 2 textures
Lerp, or Blend
How can i apply this?
In this case you'd probably sample both textures with separate Sample Texture 2D nodes.
Then blend/lerp between them based on the Y axis of the Normal Vector.
What's wrong?
there is no hard cut, the textures get mixed
Nvm i got it
You have to use Lerp
I don't think the preview displays the timing and offset, you need to apply this to a material
It is technically possible.
The best way is probably to come use a compute shader to get the focused depth, and pass it to the DoF effect
How could I modify this shader so that there is no horizon (grey part). I know for a fact that it's something in the shader code that does it, since it's not the default behaviour but I can't understand shader code well enough to fix it.
https://github.com/n-yoda/unity-skybox-shaders/blob/master/Assets/SkyboxShaders/Skybox-StarrySky.shader
how can i make a shader not overwrite the default texture of my mesh?
In what context?
on the left is the default texture, the right is my shader. I want to get the texture from the mesh and apply a simple animation to it
you see, sampletexture 2d and manually setting the texture isn't an option here....
Not sure what I'm looking at here, why's there so many of the same texture?
Anyway, when you switch material for the effect I assume you would be able to grab the texture reference property and pass it onto the effect material at runtime
i found a way i think. I can set 2 materials in the mesh renderer.
Will compute shaders written with legacy RP work in URP/HDRP?
does anyone know why the result of this graph tiles across 4 of the faces continuously, but is split separate on the front/back on one side? Is it a UV thing?
is it supposed to do that?
I would expect it to not tile across all 6 faces, or tile across all 6 faces, but not tile across some faces but not others
because its doing that, my end result looks bad
Yeah I think this would be the UVs (well, the mesh tangent vectors are aligned to the X axis of the UV coordinates). The cube is probably unwrapped using a "lying down cross" shaped net, which might explain why 4 of the faces look similar
as far as I can tell two of the six faces are just backwards for no reason and I cant move forward until I can fix it
if that is the case, where can I replace in the graph to counteract this? At no point in the graph is the UV sampled which confuses me
the out is plugged into the albedo directly atm
Ive tried removing and switching different pieces but it never removes that 2/6 faces weird brokenness
I'm not too sure. You could just use a Vector3 node rather than the Tangent Vector, but then you won't get the gradient wrapping around the edges of the cube...
Might just need to unwrap the cube mesh differently. Maybe having all faces in a line next to eachother.
to the best of my knowledge the default cube maps its UV on all 6 faces copy paste over eachother
like its not a long line
I will try making a new mesh like that real fast to see if that fixes it, but if it does, I dont know how I can use that fix because that will mess up a lot of other things
I dont understand how the UV is affecting it
because the UV is never sampled
shouldnt UV only affect it if it samples the UV?
none of the nodes pass in its UV channel 0, 1, 2, any
if it never samples the UV, how does it know?
As I mentioned above, the Tangent Vectors stored in the mesh are aligned to the X direction of the UV coordinates.
(And it's aligned like that, because that's basically the purpose of the tangents - to allow converting between World and UV space, mostly for normal mapping)
hm so you're saying like, two of the 6 faces are rotated wrong?
Am wondering if using the Normal Vectors instead would produce better results
ill try exporting after rotating two of the faces, and then try that
Yeah, I would assume two of the faces are turned 90 deg in the UVs
hmm, rotating two of them didnt change a single thing
ill try rotating another two in case I just coincidentally didnt do it right??
okay the first time must have been coincidence that it kept working
the second time affected it
hrmgh im not sure whats the better sollution now though, because its a cube, wont it be impossible to make it tile across all faces?
right now it tiles across no faces π€
and im not sure if thats better
@tight phoenix We don't need the monologue
Last few days as well
im not really surprised
i have nothing so its not like I can go any lower
this is the usual reponse to someone who is in crisis, tell them to fuck off because no one wants to see someone struggling
I mean, this is a dev server. Not a crisis server.
everyone i reach out to does this, so i never get any support, its always people brushing me off because its not their fault or responsbility or whatever
yeah i know that
then go get help in the appropriate places
amyways talking to you isnt helping so im closing discord
see ya man, get help
perhaps you don't get support because the last 75 messages, cannot be helped with
π’
@tight phoenix This isn't a mental health or crisis support community and we're not equipped to be one. If you need help, please seek it, but otherwise please keep this channel on topic to shaders and shaders only.
I think the tangent vector and UVs may be related to some extent (one as the derivative of position wrt the other perhaps) but the main thing is you either want to switch from diffracting lines to a grid of diffracting elements (just copy again, but this time with normal cross tangent vector as your input), or you could switch from tangent vector to 1/2 (reflect(vec3(1,1,1), normal) + vec3(1,1,1)) which should be continuous (though diagonal across cube faces)
anyway, it's very often that code does something wacky you don't expect, and often shaders are a pain to debug because you can't get out numbers easily. It happens to everyone.
I use this method, but i dont have a rectangle
I need to change a fragment colour based on the central view direction and the normal of the fragment. How would I go about doing this?
I have a gradient, I'd like for it that any normal facing left to be t=0 and any normal facing right be t=1. where both left and right here mean perpendicular to the view direction and surface normal
project the normal onto the plane perpendicular to the view
then just check the x direciton of the projected vector
Get the normal in view space, and then return the x component (will need a remap too)
This is what I have thus far, I hope this screenshot is legible
I'm aware that sharing screenshots isn't usually helpful as it requires the recipient to parse what's going on. Shaders are not my fortΓ© and I'm fairly lost when it comes to graphics programming
I'm hoping to achieve a sort of pearlescent/iridescent effect using the pastel blue and pink
I think you can cut out a lot of it by using a Normals From Height node
Plug in the gradient noise and you can remove everything up to and including the Normal Strength node
it doesn't quite give the same result
Looks like it's just a difference of normal strength
you should be able to pick it so they're the same
One is stronger than the other but if you change the value going into normal strength you should be able to get them identical
I did change the strength here to be roughly the same
it's probably the same under the hood, just one saves space on the graph and is clearer imo
yeah
The implementations might be slightly different so the same value input for strength yields different results, but it's probably just a factor of 2 or sqrt2 or whatever off
so if you just take the value in one of them and change it you could get it to look identical to the other
sure, this is good to know
Anyway once you get the normal, put it through a transform node to take it from tangent space to view space. Then remap the r value from (-1, 1) to (0, 1) and that's your gradient input
bizarre
drew such a rectangle, but now how to make smooth for the edges of the rectangle through smoothstep, please tell me
like this
Rather than using an if and bools, use a distance function (Inigo Quilez is the go-to for basically any distance function; he's got them all). Then plug in the distance function to your smoothstep (i would also put a remap in between so you can change how smooth/sharp and rounded it is)
@wicked niche
i have a colour as a float4
how do i set a specific pixel using x,y on a RWTexture2D to that colour?
TheTexture[int2(x, y)] = whatever i think
i am developing a game for mobile and i am using a "Mobile/Particle/AlphaBlend for trees and fence but it show object trough each other?
and the textures is a PNG
use alpha cutout for fence
are the trees baked into a single mesh?
i have created the level in blender and trees are all one object
but the texture is same for both fence and trees
Are the fences a single big object ?
If yes, what you are seeing is transparent rendering order making that the fences are drawn after the trees, when the pivot of the object is closer to the camera.
Either split the fences into smaller sections, or like mentioned before, switch to alpha clip opaque
Same can happen if the trees are a single big object of course
so if i separate trees into single object and divide fence into smaller piece will this solve the issue?
Likely
ok, what function can be used for a rectangle, so that later it can be correctly used with the smoothstep function
Hi, is there a way in the shadow graph URP to receive shadows for an unlit shader?
I'm trying to create a grass shader, and if I use a lit shader type only one side of the plane that represent grass reflects the sun, the other side don't, so the unlit shader has the best effect since it has uniform colors for all the grass
But it doesn't receive shadows..
Inigo Quilez has a distance function online
how would I do the texture projection described at 38:34 https://www.gdcvault.com/play/1012264/Shading-a-Bigger-Better-Sequel in shadergraph ?
Another solution could be using a lit shader and receiving light from both sides. Can I do that? Is there a way?
I don't know why a plane with rendering face set as both would reflect light only from one side...
Depending on the rotation, as you can see from the different color on the left in the same mesh, it reacts to light differently...
The matrix (or perhaps just an offset) defining the ellipsoid would be sent into the shader. You'd use the fragment position (Position node (object) space) and transform that using that matrix (Multiply). Or in the case of an offset just Add/Subtract.
Then Swizzle (e.g. "xy", but depends on which axis you want to project from) and sample using that.
It's not too far off the "worldspace planar mapping" idea, (e.g. https://www.cyanilux.com/faq/#sg-planar-mapping) but in this case it's just object space (or "ellipsoid space"). You'd also want to make sure the texture is set to Clamp rather than repeat, and the edges of the texture should be black/transparent to avoid clamping colours at those edges.
Shadows in unlit graph : https://www.cyanilux.com/faq/#sg-unlit-shadows
Shading back faces in Lit graph: https://www.cyanilux.com/faq/#sg-two-sided-shading
Another common method for grass is to override the normal vectors to only point upwards, (0, 1, 0) in world space
How could I do that?
As in, connect a Vector3 node with those values to the Normal port in the vertex stage.
Or the one in the fragment stage, if you change the "Fragment Normal Space" in graph settings to use World space.
Like that?
It didn't work
As you can see from the left plane that's light green and the right that's dark green, one of the sides is still getting light
Oh right, the vertex port is in Object space, I forgot. You'd also need to use a Transform node from World to Object (Direction mode) for that port
Well, you sir have resolved in a moment what many guys that tried to help me could not
Thank you so much
If you combine the planes in a single mesh you could also continue using (0,1,0) - or whatever axis is up - in object space so that rotating still affects the lighting of the whole object
But since grass tends to point upwards in world space, this works too
I recreated this in SG. Seems to be what you are talking about but the texcoords simply color my entire model they dont seem to project the texture at all
It should never point in any other direction so that should be ok
I've got another question, probably a bit harder
another of the ones where noone could help π
I looked for a custom biome shader solution for my terrain (subdivided in chunks) for a lot of time. In the end I found nothing and created my custom shader: it takes a texture mask as an input, a texture that will be applied where the green part of the mask is and it lerps this with all the biomes.
So that's the single biome node:
And repeated and lerped 4 times, I get my shader:
It works kinda well, but I've got a bug and something I'd like to change, if you can help me... The bug is, borders of the biomes, if seen from far away, are black
Personally I would convert all these Vector3 inputs and Dot Products into a Matrix4 and Multiply, as it'll make the graph much simpler. If the ellipsoid is controlled via a GameObject/Transform can just use the transform.localToWorldMatrix for it.
You also aren't sampling a texture with these coords yet
That's what is happening
if you look where the biome changes (from grass to forest grass) you'll notice a black line...
Another example in a beach, where it's easier to be seen:
Unrelated to the problem, but assuming that Color Mask node is using green (0,1,0) you could remove that node and just use the G output from the texture sample. Would be cheaper.
(there are two lines because the sand is actually two biomes, seafloor is the one close to the water and the other is normal sand, close to the land)
Yeah, right. Removed that, gonna test it soon
I feel like for the first texture you don't need to do the biome masking. You're lerping from (0,0,0,0) which is probably where the black is coming from.
ok it worked perfectly well
I am sampling a texture with the interpolated coords down the shader. The texture is set to clamp as well. I'm just plugin them into the UV of the texture sampler. Should I be doing something mroe with them ?
What could I use instead of lerp? Multiply?
I'm a real noob to shaders (your website seems like a paradise to begin experimenting with it)
I copied the code from the presentation
The lerps are fine, I just think for the first one you could skip that and put the texture sample result straight into the A input on the next lerp. Assuming you only have 4 biomes?
Yes
Every time I need another I just copy and paste it
the mask is then rendered via c# code, and that's what I wanted
Then yeah, try skipping this first one. If all the other biomes are masked on top you don't need to mask this one too.
I'm trying to test what you suggested, editor is stuck into importing π
8 gb ram is not enough for unity
You could also look into combining the masks into one texture and use the other outputs rather than just the G channel. Would use less texture samples that way. It's similar to how terrains handle splatmaps.
Okay, didn't see that in the graph you shared above but afaik it should work then. Maybe check your Vector3 inputs are being set properly
I'm manually setting them as exposed properties
the cliping part seems to be working, this is the whole graph at the moment
Combining it via shader? With a ..combine node?
No, I mean in C# or however you create the masks (hand drawn?)
C#
(It's a procedural world)
So I create a big texture, or a texture array, and feed it to the shader?
Anyway optimizing it is probably something I'm gonna do in the future, right now it works pretty well and I don't even know why ahah
If I can, I'd like to ask the final and probably hardest question π one that has bothered me for about two weeks before just giving up
The texture can stay the same size, just use the other colour channels. Red, green, blue, alpha, for different masks
Ah, right, I tried it
but I'm gonna need many more biomes, currently there's four but probably they're gonna be around 10/15 with Version 1
Thats also why I didn't use vertex colors, iirc (I coded this shader three months ago)
I might filter colors...
not sure about that
My biggest failure with my project are the biome edges, I spent so much time trying to get a system that "smooths" those edges, but I never found any way to do it
Hey, anyone here know anything about compute shaders?
My main goal was to use some sort of lerp between them to get a value of how much close the point was to the edge of the biome, and then use a noise map to do some sort of biome-crossing effect
Difficult to debug this. What is the splat texture like? Is it greyscale or transparent? If it's transparent you might need to use the A output from the texture sample instead
A bit like that, but at a very small scale (smaller than a "block" that you can see in the image, so each block would be clearly one biome or another)
I guess the mask textures are using Point filtering? Could use Linear to get a bit of a transition.
Maybe also upsampled/downsampled to adjust that, or use a smoothstep in the shader after sampling the mask
I gave up after a week since I couldn't even get close to something like that π¦ then I tried to have a "smooth" biome change, where edges were a bit less hard and more rounded.... Gave up on this too
Yes
I tried that - but I don't remember why it didn't work. I'm gonna do that again and see why I didn't use this solution
It is indeed transperat, using the alpha turns the entire model black, so the problem is with the uv's I think
It might be the alpha clipping part is hiding the texture now?
Maybe adjust the value in the Alpha Clip Threshold port
hold on I'm seeing something, It might turn out that my elipsoid was badly defined
I need a way to visualize it heh
Well it simply didn't work, I've set it both to bilinear and trilinear and nothing changed
Oh, you have a SamplerState node in the shader, did you change that? Or the settings on the texture?
I'm processing a big image in my compute shader and I want to count how many white pixels it has. I've tried making a RWStructuredBuffer<int> and in the CS incrementing the first index if pixel == 1, but after reading the data the values are in the 50-64 range, seems like the thread groups overwrite eachother. What'd be the best way to do this?
Settings on the texture, via script
second line
Okay then yeah, you'd also want to remove those SamplerState nodes, as it'll override it
Ok this simply works and I'm astonished because I tried the same thing that you made me do over and over without success
BUT there's a bug π
It always belnds every biome with the first biome on the shader, the one where I removed the lerp
This thread might help, answer uses InterlockedAdd
https://forum.unity.com/threads/solved-how-can-i-count-the-number-of-pixels-above-a-threshold-with-a-shader.763232/
So for example between those two biomes (sand and seafloor, I use it to not spawn beach objects too close to the sea) the blending has grass in between
Oh hell! Big thanks let me try it out
Also, I recalled the reason why I didn't use this solution: sometimes behaviour between chunks is weird
like there, you can see an hard edge in the center, where two chunks touches
Mmmmmm yeah. This is where combining the masks into each colour channel would really help π
Worked like an absolute charm, tysm
if I can fix this I'll probably maintain this solution, since it's better than hard edged biomes
Ah yeah, that's also going to happen unless the mask is also padded with values from neighbouring chunks. Would then need to scale the UVs a bit so you aren't sampling those parts
but if you have any suggestion... Or if you know how to make a "blending" effect with the noise, as mentioned above π
So I'd have to give my mask a +2 on size (one left and one right), and then scale it until those two are hidden?
Yep
That's pretty hard because biomes can be modified from the player (and saved in a file), so I'd have to load neighborhood chunks data to get what biome is the closest one.. And chunk data loading takes a lot of time π¦
Blending with noise is also doable. Can distort the uvs used to sample the mask.
Would probably use Gradient Noise node (or a seamless noise texture) with worldspace planar projection (https://www.cyanilux.com/faq/#sg-planar-mapping) - this'll make sure the noise doesn't cause seams over each chunk
Subtract 0.5 to "center it", Multiply by a small value (e.g. 0.02), then put this into the Offset port on a Tiling And Offset node, which would go into the UV port on the mask sample.
Can I do fresnel based on the normal map?
Sure. Sample the normal map, then use a Transform node to transform it from Tangent to World space (Direction mode), for the Normal input on the Fresnel Effect node.
iiiinteresting. I think this will hopefully give me iridescent effect I'm hoping for
its sorta working, but turns out I have to idea how to define a elipsoid
Well.. Without the worldpace planar projection, this has an interesting effect, but that's not quite what I was looking for...
I hoped to have an effect more like this, or at least with borders not so squared (round borders with this would be ok, I think)
So, using gimp and a lot of shame for the quality of what I did, the output would be something like that...
no hard edges
is it actually possible?
I think the noise scale here is just too small
But adjusting the scale is unlikely to give this result. It'll still look blocky, just... a bit wiggly too
To make it look like that you'd probably need a higher resolution mask texture.
Or at least something with more of a gradient in the masking. With linear filtering and a step, that can produce nice results. Same idea used in SDF textures. (e.g. https://twitter.com/cyanilux/status/1188793223029886976)
Might be hard to get that gradient though, without applying blur operations or jump flood algorithm to generate the sdf.
I tried to increase the mask texture, computation time went really high. Anyway I need to have a "block" about this size, for gameplay purposes
Gonna try that.
so im learning compute shaders, and as i understand the goal is to divide the task between the threads of the shader, so with 8,8,1 numthreads you divide the task 64 ways.
is that understanding correct?
if it is im wondering a few questions
are the threads 0-7 or 1-8 and
how do i devide a for loop between the threads correctly?
Have you got a tutorial about linear filtering?
Using steps and trilineal filtering has an effect really close to what I'd like to have π
@regal stag I tried the matrix approach you suggest, I fill it from a helper object like this renderer.material.SetMatrix("_ElipsoidMatrix", transform.localToWorldMatrix); but it does not work as expected, it only works if I scale the objec to something very big like 40
Ok so fresnel will give me a gradient effect but I need something directional relative to world directions
ignore me, just came up with an idea
Using steps also fixed the in-between biomes grass.
I'm going to see how it goes between chunks, and with single square biomes (e.g. when the player modifies the terrain manually, you could have a single squared biome)
Maybe that's because the model it's being applied to has some weird scaling?
if that works, I'm probably gonna cry lol
nope its scaled 1,1,1
Hmm maybe localToWorld isn't what you need. I guess it needs to be relative to the parent object...
Maybe enemy.worldToLocalMatrix * ellipsoid.localToWorldMatrix ?
renderer.material.SetMatrix("_ElipsoidMatrix", renderer.transform.parent.transform.worldToLocalMatrix * transform.localToWorldMatrix); it seems to be inverted ?
afaik yes that is correct.
I believe threads are 0-7
Give each element in the loop its own thread, then store the result back in the buffer. It doesn't work if the loop is sequential though, it has to be parallelisable.
its a 2 dimensional for loop over a RWTexture2D
or a buffer
Hello guys, I have run into a problem, so I followed carlikecoding's tutorial on compute shaders and I'm pretty sure I did everything properly but when I entered play mode it said that I was giving very expensive calls to the gpu
Here is the compute shader:
RWStructuredBuffer<float3> _Positions;
uint _Resolution;
float _Step, _Time;
float2 GetUV (uint3 id)
{
return (id.xy + 0.5) * _Step - 1.0;
}
void SetPosition(uint3 id, float3 position){
if(id.x < _Resolution && id.y < _Resolution)
_Positions[id.x + id.y * _Resolution] = position;
}
#define PI 3.14159265358979323846
float3 Wave(float u, float v, float t)
{
float3 p;
p.x = u;
p.y = sin(PI * (u + v + t));
p.z = v;
return p;
}
[numthreads(8,8,1)]
void FunctionKernel(uint3 id: SV_DispatchThreadID)
{
float2 uv = GetUV(id);
SetPosition(id, Wave(uv.x, uv.y, _Time));
}
And here's the script responsible for the graph: https://pastebin.com/RC9JP5yZ
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
It should show a lot of cubes in the center
It works so, so good! I'm really really happy. The only bug I found is in between chunks
As you can see it applies the grass texture even there
This is the error I get
for(int x = floor(Size / id.x); x < floor(Size / (id.x + 1)); x++)
{
for(int y = floor(Size / id.y); y < floor(Size / (id.y + 1)); y++)
{
does this look right?
size being the texture resolution
Sometimes it simply spawns green grass (forest grass) where probably the mask doesn't reach one or another. Those dark green spots are from the grass texture, the one without the lerp
is this in the shader?
In the shader you get a single id(x,y,z), and that's your int x, int y, and int z (if you use one)
yep
Don't loop over everything bc then you're telling the shader to, for every element in the array, loop over every element in the array again
which is going to be very expensive indeed
unless I'm misunderstanding what that loop is for
each thread should do 1 64th of the loop?
i think
im still really new to multithreading
Basically, on the CPU you'd have a loop over x, and inside, a loop over y.
The GPU already gives each thread a value for x and y (id.x, id.y) and then you use those values to calculate whatever you needed to calculate, put it into its slot on some big array, then hand it back at the end
// for(int i = 0; i < Size; i++){
// for(int j = 0; j < Size; j++){
// if(pow(i - PixelCoords.x, 2) + pow(j - PixelCoords.y, 2) < pow(SplashSize, 2)){
// //splatMapData[i, j] = team;
// if(Team == 1){
// InkTexture[int2(i,j)] = AlphaColor;
// }
// if(Team == 2){
// InkTexture[int2(i,j)] = BetaColor;
// }
// }
// }
// }
this is what im trying to implement properly
it renders a circle of radius SplashSize, around PixelCoords
So on the CPU, it'd be
Vector3 SomeFunction(int x, int y)
{
// stuff
}
for (int x = 0; x < numX, x++)
{
for (int y = 0; y < numY; y++}
{
bigArray[x, y] = SomeFunction(x,y);
}
}
On the GPU, it gives you x and y - you can think of it as already doing the looping for you - so you just need
Vector3 SomeFunction(int x, int y)
{
// stuff
}
bigArray[id.x, id.y] = SomeFunction(id.x, id.y);
obviously I'm bastardising the code a lot here but the point is the looping is done for you and you get id.x, id.y as your x and y equivalents, so you now just need to run whatever function with them as inputs
[numthreads(8,8,1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
InkTexture[ int2(id.x, id.y)] = GetColor(id.x, id.y);
}
float4 GetColor(int2 PixelCoords){
if(pow(x - PixelCoords.x, 2) + pow(y - PixelCoords.y, 2) < pow(SplashSize, 2)){
if(Team == 1){ return AlphaColor; }
if(Team == 2){ return BetaColor; }
}
}
so like this?
yes
Each thread group will contain an 8x8 block of threads, and when you set it off, you tell it how many thread groups it needs to generate and run
So it'll run the right number of times
You tell it how many groups to create in the Shader.Dispatch() on the c# side
yes
ok
uhh
wait
its now rendering a quarter of the circle
does that mean my Dispatch size is wrong?
I think so, what dispatch size did you give it and how many pixels is your texture?
8 * 256
texture is 256
wait
Is the texture 256x256 or 16x16?
yes for a 256x256 texture with 8x8 threads, you should need 256/8x256/8 thread groups, or 32x32
so uint3(32,32,1)
still getting quarters
oh pow() doesn't like negative numbers
abs the input
or better yet just multiply things by themselves instead of using pow bc iirc it's slightly faster that way
now its not rendering anything
what did you change it to
ayy nice!
alr how do i make it not overlap or clear the last render
What's the shader displaying the texture?
[numthreads(8,8,1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
InkTexture[int2(id.x, id.y)] += GetColor(PixelCoords, id, SplashSize);
}
The texture goes onto a quad though right?
Transparent, right?
cutout
Wait, there are multiple circles per quad?
yea, the circles should add to the texture, but not stack
Swap it from += GetColor to = GetColor
that clears it when adding a new circle
ah right
= Max(InkTexture[], GetColor())?
or GetColor.a == 0 ? InkTexture[] : GetColor
(assuming you're using the alpha channel for transparency)
i want my effect to fill the image what node i must input before it?
i made it pass the old colour through GetColour and return it if it didnt need to update
Nice
Thank you soo much
np :)
tried various methods to calculate tangent vector but none of them duplicated the unity tangent node
trying to copy what you said to do in this post now
this is all x/y, all I really want to do is fix my cube so that all the anisotropic lines go in the same direction
normal cross tangent doesnt fix.
your second suggestion 1/2 (reflect(vec3(1,1,1), normal) + vec3(1,1,1)) also does not work, they all go in different directions
it would help if you can clarify these two formulas, ive implimented them as written to the extend of my understanding of them
If you combine it (blend, add, whatever) with the original effect (just using the tangent vector), the combination should be face-independent again (or so I think)
you're running up against the Hairy Ball theorem, which basically states that on a strictly convex shape, you can't have a vector parallel to the surface everywhere that's also continuous everywhere. You have to have a pole where something either points up/down, or swirls in a spiral (discontinuity). On a cube, you could hide it by putting the discontinuity/sticking up at a corner (which is what I was thinking of with the vec3(1,1,1) thing)
hmm hairy ball theory, I see after googling it. So I was trying to fix something unfixable
Hello guys, I'm following this tutorial and when I get to the end of 2.1, if I do a high value in the resolution (like 200) Unity crashes for me
Ill try your fixes here to run it into a corner
I don't know why it does that, I've literally copied every single line of code
Anyone?
this is sorta working, except that some of the faces are super washed out bright while others are double dark π€ still trying to normalize that
oh right, normalize will literally do that
i guess this is as good as it can get, since hairy ball theorem is unsolvable
do you think this is fixable? straight on from certain faces, its dark, while others are bright
how hard would it be to aim all the same corner instead of arbitrary corners?
I do have set of UVWs that point from one corner to the other, could they be used in some way?
certain faces are very bright and others are very dark
I cannot solve this on my own so Im going to drop it now
Looks cool
Thanks, I am not satisfied with it, it looks 80-90% of the way there but its still not quite 100%
Keep going
through experimenting realized that is the bitangent
Sry I mean combine the result from putting in tangent vector, and putting in (tangent vector cross normal)
Not just the vectors
Im not sure I understand, are you saying to duplicate the entire graph?
Yes
Indeed
I think a real diffraction grating would be multiply, add could correspond to two mostly transparent gratings or something
Though it depends how expensive the original is
I think there's probably a way to align it diagonally and have it all work the first tims
funnily enough the result of the above seems to be exactly the same as https://cdn.discordapp.com/attachments/497874081329184799/1014574164457308260/unknown.png using the combined thing at the start
well not exactly but visually hard to tell a difference
I do have UVs https://cdn.discordapp.com/attachments/497874081329184799/1014565037748273272/cornerUVs.gif from one pole to the other
but I was not able to figure out where to input them to get the result desired
maybe this is good enough and I should stop sweating it
I think its the inclusion of the main light direction that is causing my grief
its trying to simulate brightness but that brightness is going to come from being a lit shader
removed the main light portion and let the actual main light light those surfaces
I am not happy with it and would prefer it to be perfect though
it looks fine but its not perfect, and i struggle to accept anything less than perfect, but I don't have the ability to obtain perfect
its traumatic for me to give up, I can't give up, I don't want to give up, my anguish comes from chasing the perfect appearance, and my inability to achieve that look
im already falling into the same crisis as yestrerday openly admitting this so I am going to shut off my pc now
Oh goody, anywhere to report this?
so im having trouble with a mesh
and i cant find a thread for those things
where would i put it
Mesh? Procedurally generated? What trouble? (Doesnt sound shader related atleast, you can ask on #π»βunity-talk if you dont know any better channel)
How can I make a Util class that I can use from .shader?
Can make a .hlsl (or .cginc, more common in built-in rp) file. Include it in the shader via #include "Assets/PathToFile/Name.hlsl"
Don't think it matters really, they are the same thing
Oh my gosh, that was easy!! Thank you again!!!
Is this right? I'm sort of losing the lavender colour
Then either on one of the coding channels beginner/general/etc. or #π»βunity-talk depending on the nature of the question
its always nice when two ppl tell me to talk to the other one
I'm not sure you should even have the lavender colour when using the Normal Blend node. If they're normal maps should sample using the Normal mode to convert it to an actual vector (like -1 to 1 range). Or use Normal Unpack.
The shader graph doesn't seem to like using -1
Hopefully it's roughly clear what I have going on here
I've separated the edge bevels out but need to do the normals for them. What's the proper wait to detail them?
Hmm. I'd probably do something like right - left and top - bottom (referring to the edge bevels here), and put them into the X and Y inputs on a Vector3 node. Z of 1. Then Normalize.
It needs that sort of base to subtract from otherwise it ends up like this
That might be okay? The previews don't show negative values so hard to tell. Should connect it to the Normal (Tangent) port on the master stack fragment and see what it looks like when shaded
Hi! I tried to add foam to my water. In the scene view, it's perfect, but in the play view I see nothing. Any clue why?
Scene:
Game:
The camera renders to a render texture and not to a display. Might it be it?
Depth Texture is probably not enabled on URP Asset
It was, I enabled it but nothing changed
Camera is also set to get this option from urp asset
Might have multiple URP assets per quality setting?
has anyone done a water shader in built in unity 3D before (not urp/hdrp)
I have (all the different quality urp settings), but I double clicked the right one from the quality panel so I'm pretty sure that it's the correct one
Idk, I'd try enabling it on all of them
If that doesn't work then maybe the Frame Debugger window can give some hints
What's the difference between square and circle previews?
It's kind of annoying not being able to use raw colour for normals
Well I've recreated urp settings with the render pipeline converter, create again the same shader, created a new test shader, tested in build and nothing seems to work π¦
In the editor this shader works pretty well, but in the build or playmode it doesn't... Not even in new cameras, or with all the settings changed
What do I have to look for in the frame debugger?
The tutorial I was following also said that opaque texture had to be activated, and I did it, but nothing changed...
in the image you posted, opaque textures is turned off
I know, I turned it on after that
why "ultra"?
Why not?
check your camera object's settings
It has the default pipeline
And both forced to "On"
And I've set both settings on in all the settings, just to be sure
Maybe something's wrong with the depth fade subgraph...
Hey, I have been trying to find the answer for this for a long while. I am trying to figure out a way to utilize a shader that is exactly like the Standard shader, but that it inverts reflection probes (including inverting their box projection) so an object appears see-through.
I have a Problem
I baked a Emission map but it still does not glow
Make sure its emission level is greater than 0
@regal stag Thankyou for your help earlier. I'm liking the look of this so far
Anything you think I could improve?
Yeah I set both to higher than zero but I want it to like Illuminate glowing
Ill show an example
I want it like that
yknow what this is just a prototype to make sure the core game play works
I dont need this YET
But I would still like an anwser for later
So I have a problem hopefully I can have it fixed. On my project I have a geometric shader that creates grass, the problem is it doesn't render on my pc, but it does work on other pc's, can anyone help me? If you are wondering I have tried other shaders that are similar but they do the same thing, that they do not render in both the project window and folder.
Unless you're using HDRP, materials don't project light even if they're emissive. At least not in real time. They should light other object if you bake the lights.
A more straightforward approach would be to just add a point light source to the object.
are you know how to make black to transparent?
select alpha source/from gray scale in texture settings?
or you could select rgb black (0, 0, 0) areas and set them to alpha input
Ok this is insane. Getting Alpha value from Color is impossible? π While getting it directly from A output connector is very much ok.
Am I missing something here? Or is this a bug? I need a sanity check, pls π
What do you mean?
Getting A from color is equal to getting Alpha value from color
Exactly... so why does SG show different results?
The Multiply node on the top is used to extract A from the color. Does not work.
you want split, not multiply
While the bottom Multiply node is just used as a preview proxy. Works
Maybe it's only the breview bugged
*preview
math should work
Yep, it's a bug in the preview. Oh god, SG is so annoying.
As a guy who's begun with SG, I could do nothing without it ahah
Shader code for me is dark magic
wait thats more a limitation of the preview, not a bug, its trying to show a color texture but you set rgb to 0, theres no preview for only alpha channel
I very much prefer Amplify Shader Editor. Using it for everything. Except for VFX Graph custom shaders, these must be made in SG only. And it is a pain π Even making a basic shader is pain.
so it's supposed to skip alpha?
it just doesnt show it in previews
But why no checkerboard?
I dont know, ask unity π
does it normally do that? I don't use shader graph much, also prefer code
No idea, I use SG only rarely as I used to write shaders manually back in built-in RP days. Now I use ASE.
But Unity is forcing me to use SG for VFX Graph now.
What an awful experience.
Yooo Joyce, I love your work
It's the main reason I've been learning shaders and rendering.
I would be too, but we have started a new project where we needed many HDRP features.
Hi there, not sure if it's specifically in shaders. But how would I go about rendering a buffer of object IDs on the screen?
With the various GUI systems. For example https://docs.unity3d.com/ScriptReference/GUILayout.Label.html
I mean, translated into colors. Like id of each object on each pixel of the screen
Thatβs just an algorithm you have to implement yourself in a shader then
what mean rgb black its node?
hey guys, I really hate do be pedantic but I've lost so many hours on that and I still can't find a solution T.T seems like everyone that has this problem on the internet has just depth texture disabled, and mine is activated... but it still doesn't work π¦
I've also upgraded unity in a new version, just to be sure.. nothing changed
if anyone has any suggestion.. it would be really appreciated
have you tried turning off the pixel effect?
just to see if its the rendertexture causing the issue somehow
kinda looks like its there in your pixellized version, just mostly gone becauseo f the averaging of colors
Yes, even with a freshly new camera...
Btw the pixel effect is just a camera rendering in a small scaled render image, and a canvas shows it
it should not break anything anyway
It's like that even in full resolution cameras π¦
Is post processing disabled on the full resolution camera? (I assume you wouldn't want to apply it twice - but this might also be turning off the CopyDepth / DepthPrepass)
Might be better to have it on, but remove all layers from the Volume Mask
..it worked, seems like having more than one camera creates problems
once again, thanks
however it doesn't actually work in the same way as the scene view, seems like distance is a bit different
but i'm gonna adjust settings in a different way, so it will work anyway i thin
Does anyone now how possible it would be to have a "fake edge" on an area with cutout?
example, a wall with an alpha circle in the middle with alpha clip enabled. this would make a circle, but make it look like it has thickness in the hole instead of just a sharp flat circle
hey, does any one know what im supposed to connect the Instanced ID node in shader graph to get value of the properties i set in DrawMeshInstanced call?
okay, so guys, this is a custom shader and this is pretty performance heavy, i was thinking if there is any way to turn this into texture map? like i dont have any interaction with it, its a static shader but it has this sort of height which gives off the depth feel, any way to turn this into texture which retains all these details?
Put a light in the center of the cube? (you can set its parameters from a script)
Is there any difference in the building in 3D URM projects? or is it just 3D Base except with better graphics?
Could use some parallax to do this
holy, that's exactly what I want! thanks! I'll check that out
wait are you the one who did the pumpkin thing? I found that while searching for info on this!
Personally I haven't used the Instance ID node, but I have used a Custom Function to handle instanced properties. https://www.cyanilux.com/faq/#sg-gpu-instancing
Maybe, I did some pumpkin stuff with parallax a while ago
yes, it was you! what a coincidence! I'm totally new to shaders, is there some way to add this to URP lit? I can't seem to find a shader graph template for urp lit or anything
You'd need to recreate it. It's mostly setting up properties in the Blackboard and a few Sample Texture 2D nodes connected to the various ports on the Lit graph master stack.
In the case of the Albedo and Normal map you'd swap out the A inputs to those Lerp nodes in the graph I posted above.
Supporting Height Map is a little different. Would use Parallax Mapping node in UV ports
thanks for all the help, very useful. Will need to learn how to use this info!
@hot scaffold I should also mention that if any objects need to interact with the hole the effect kinda breaks down.
This technically could be fixed by adjusting the depth of fragment output (SV_Depth), but Shader Graph doesn't expose this (in URP at least)
nope. it's going to be purely for visuals. will it work on geometry that isnt flat?
that is good to know though, thanks!
Eh, I think it should work. Though for very curved surfaces it might look a bit strange
I will definitely have it a lot thinner then that. will see, thanks!
FIxed the glowing problem
I just needed to ditch the Built in renderer
Anyone ever encountered an error like that at compute shader compilation?π§
Shader error in 'TerrainBaseGenerator': Compilation failed for kernel 'CSMain' [0x80004005 - unknown error] 'internal error: compilation aborted unexpectedly
' at kernel CSMain
Seems to be the macro...
#define Splatmap(i) Splatmap##i
Any clue what's wrong with the macro?
Ok, it's not the macro. The error is thrown even if I write down the variables manually.π€
Ok, the problem seems to be with using an indexer to set a float4 texture2d value as float.
Like this
Splatmap0[id][channel] = value;
damn. The compiler really doesn't like me using indexers for vector types. xD
Hey, I have been trying to find the answer for this for a long while. I am trying to figure out a way to utilize a shader that is exactly like the Standard shader, but that it inverts reflection probes (including inverting their box projection) so an object appears see-through.
I feel like this should be easy, but everything I have found online has not done what I want to do and doesn't look right.
Hey everyone. I'm using the Ellipse node in Shadr Graph. Is there a way to blur it?
is there any way to get the UV tiling value as a vector2? I need it for doing some vertex math but it seems to be factoring in offset as well
ass you can see the preview on the bottom isn't the same output as the vector2 on the top, despite the UV having the same tiling values
No, but you can do something like one of these, if you need a gradient falloff.
Top one is closer to what the Ellipse node does, allowing for different width/height.
Bottom one is more compact if you just need a circle.
These aren't the same thing.
The top is just (1, 1)
But the bottom here is equivalent to UV * (UV * 1 + 0) + 0, simplifying to UV * UV
It's a bit unclear what you are trying to do
I need to offset my vertex based on the tiling value of the UV
I'm scaling up my vertex output based on the texel size so I don't need to adjust my quads manually for each differently sized sprite
but if my material is only using a tiling value of .5, I need to halve my texel size(in my math)
There's a Split Texture Transform node you can use on the Texture2D property
In v12 / Unity 2021.2 at least
awesome, thank you!
You da man. Thanks very much!
With the shader graph, how would I go about going from local UV space to world space, as seen in material B? Thanks.
The most straightforward way is to divide and floor(or truncate) the world position by a certain "scale" value.
You'd need to then decide how to swizzle the vector3 into vector2
Using the surface normal is probably the most appropriate way
Triplanar node works also, but with less control
https://github.com/yumayanagisawa/Unity-Thin-Film-Interference/blob/master/Assets/Interference.shader
Can anyone tell me what 'rd' stands for in the context of this shader? Reflected/Refracted Direction maybe?
im struggling to reproduce this shader in shadergraph because a lot of the shader is them manually calculating things that shadergraph does automatically, like sampling cubemaps or fresnel
Is there more to Thin Film Interference than just lerping a rainbow gradient across a fresnel? Am I going through all this work/steps for something that can ultimately be done much simpler?
I am not skilled enough to tell which parts I need to reproduce and which parts I don't, for example tons of this code is all about reflection and refraction and sampling colors, but shader graph to my knowledge does most of that for me, but here they have to do it manually such as setting up an SDF for a sphere, when I just have a sphere
As far as I understand surface viewing angle, film thickness and light bounce angle are all factors in the color effect, and to simulate it perfectly it'd be necessary to simulate photons of different wavelengths
I think most games don't bother putting more effort into it than at most sampling a fresnel and a thickness texture for a gradient as the specular tint color
Yeah, I do like the look of their end result though. I want to reproduce their work, and then downsize to most likely a fresnel + gradient after I have a stronger understanding of the 'real world' physics version
Following a different tutorial on the same effect, they define "cosI" as 'the cosine of the incident angle, that is, cos0 = dot(view angle, normal)'
but they also have cosT but dont define what it is
I assume something to do with cosines and tangents?
float rs(float n1, float n2, float cosI, float cosT) {
return (n1 * cosI - n2 * cosT) / (n1 * cosI + n2 * cosT);
}```
What would cosT be in this context?
following these people's shader work is obnoxious because every variable has some two letter name that I lack the knowledge to intuit its meaning
what's a more performant manner of making scene props have an idle animation similar to trees swaying - i dont need very fancy "wind direction" computations, even just a looped light sway (similar to idle breathing) movement would be good enough. is shaders the way to go? or something pre-baked? animations? other?
or if using dots/ecs then perhaps a system which performs the sway movement?
cosT as cosine of angle of transmitted ray?
vertex shaders will be pretty damn good
@shadow locust oh i forgot to mention - i'm targeting mobile devices, and even hoping to support older/lower end OpenGLES 2 devices. does that affect your answer?
not really
but idk that much about low end android devices
so I might not be the best resource.
does it make sense that a vertex shader will be just as performance-intensive (or not) as a pre-made movement loop or animation or some other solution?
You will need a vertex shader to render the trees anyway. An additional sine wave or two to displace the vertices will not affect performance greatly.
@low lichen can you please explain why i need a vertex shader anyway? i thought i just have a tree model and place it in the scene with a material or 2
To render anything on screen, you need a vertex shader and a fragment/pixel shader. That's just how GPUs work.
so i guess you mean any shader i'm using (standard shader or other) all already have vertex shader parts to it ?
Yes
And you won't be able to use the Standard shader, unless you modify its vertex shader to include the wind animation.
i see.. so even for some older Android 5 or android 6 device, chances are it would be similar performance "cost" if i make the tree sway based on some animation or other solution, or if i code it into the vertex shader?
Doing it directly in the vertex shader is going to be much cheaper than a skinned mesh renderer animation.
ah ok even better then
Especially if you implement the animation with some basic math and not some huge pre-baked animation
Anyway, if you're targeting low-end mobile, you should be using lower quality shaders than the Standard shader.
i see ok
If you want to squeeze out as much performance as possible, it's always best to write your own that is tailored and optimized for your game and not a general purpose one like Standard.
assuming sufficient knowledge of shader & trig & GPU concepts etc....
The reason you're having a hard time is that it isn't that easy to do what you want.
I mean you want to EXACTLY match the standard shader, except for one thing where you essentially want to reverse a vector for a cubemap and that supposedly gives you "see through" effect.
This is confusing to me, as compared to making a transparent "see through" object, but OK, let's go with that.
So what you'd have to do is to clone the standard shader. They give you source. It's got a ton of includes, and it is a beast because it is an "uber" shader of sorts. If you get lucky, you can isolate everything you need to change to just one include file or something. There's a ton of variants, and I can't point you at the proper place to get to the cube map reflection calcs, but you'll find it.
I wish I had an easy answer for you, but you're in for some work IMO unless you get lucky and can just copy it over and change one include file or redefine a macro. I can't tell you the answer off the top of my head, and it would cost me hours to dig through it.
But, grain of salt, that's my 2 cents.
If you're on URP or HDRP, IDK what to tell you other than finding examples where someone did their own lighting. But I'm assuming BiRP since you discuss the "Standard Shader".
Will this work for converting between roughness to smoothness?
You would want to use a Sample Texture 2D node, not the Gather one
But yes, One Minus should be what you need for converting between roughness and smoothness.
Awesome, Thank you!
Ill try sending that in π€
Is height map supported in shader graph?
I found a 3D model online that has both a Normal map and a height map.
are they the same? I don't think Unity has a way to apply them both to a material
You can apply a height map using parallax I think? (I haven't used it myself though)
Depends if the features are big enough that you'd notice parallax though; if they're small then you might only need a normal map.
ignoring the color, how can I reproduce this curveature of light to dark values?
I almost sorta have it at the power node, but its backwards, I got the curvature in black and in the wrong corner
I cant figure out how to make the black part white and the white part black and also change the bottom right to top left
oh might have gotten it π€
not making much headway on thin-film interference
I have a ton of really great mathematical dissertations on it, but I can't comprehend most of the mathematics within
as usual, I wont be able to make any progress on this until someone solves the hard parts for me πΏ
https://www.shadertoy.com/view/ld3SDl
https://github.com/yumayanagisawa/Unity-Thin-Film-Interference/blob/master/Assets/Interference.shader
very complicated shader toy and unity shader implimentation of it, problem is they also do 500 other things and I cant separate just the part I need
mood. Definitely worth familiarising yourself with the maths imo
I have been trying, but I don't have a university degree in mathematics, so translating this into code is basically impossible for me
not only can I not translate that into code, I can't even be sure if any of it is actually the thing I am seeking/need to solve thin film intereference
the math seems less intimidating here
but maybe its not showing the full story
embed you coward
I opened the link either way
summation of... symbols
fancy A fancy E to the power of fancy I and fancy P
brackets to the power of K
Maths likes to use single characters for variables in order to be more elegant for some reason. If it helps just swap them out for whatever they're saying it is
so are those just A, E ,I and P? Not special constants?
like how the pi symbol is 3.14
is it this one?
another one of the many pages I have open on this topic
It doesnt super matter which one because I have no idea what any of them are calculating, helping me understand that one alone is less useful than telling me what I should be looking for π€
Fun fact about the use of pie to mean that irrational constant. When Archimedes was writing it he used the value to refer to any value, he just used it to mean that constant more often and people adopted it as such
gross
In some of his works it's written "Let 'pi' be equal to..." rather than a specific thing
Thats interesting and extremely confusing
What is the relation between Wavelength and Refractive index
It's the same way it is today, every symbol here except infinity has a defined value
For example alpha and beta are defined above
does anything in that link refer to thin film intereference in any way?
I assume fancy P and fancy T are defined even higher as well?
Phi and Theta I suppose
ah
I dont feel like this is useful knowledge, short of going back to university for several years, I'm not about to start to comprehend this kind of advanced math
smarter people than I have already written thin film iridescence formulas
I just have to translate their work into shadergraph
like its completely done here
but its also doing so many other things that it becomes useless to me
you don't need to understand the implicit meanings, choices, or workings of the formulae. Only that symbols are defined as some value or the result of some function and that it's all translatable to code
In fact the initial paper here provides an implementation at the bottom of the paper
are you talking about the COLLOSAL block of unbroken red text?
I have zero ability to parse that yeah
i guess i can try copying it into nodepad and linebreaking every semicolon
gimme a sec
thankfully I (think) I have already the BDSF formula
oh wait they want BRDF, this is BSDR
not that I have ANY idea what either of those things are
i google it, i found picture, i remade picture
// cosI is the cosine of the incident angle, that is, cos0 = dot(view angle, normal)
// lambda is the wavelength of the incident light (e.g. lambda = 510 for green)
float ThinFilmReflectance(float cos0, float lambda) {
const float thickness;
// the thin film thickness
const float n0, n1, n2;
// the refractive indices
// compute the phase change term (constant)
const float d10 = (n1 > n0) ? 0 : PI;
const float d12 = (n1 > n2) ? 0 : PI;
const float delta = d10 + d12;
// now, compute cos1, the cosine of the reflected angle
float sin1 = pow(n0 / n1, 2) * (1 - pow(cos0, 2));
if (sin1 > 1) return 1.0f;
// total internal reflection
float cos1 = sqrt(1 - sin1);
// compute cos2, the cosine of the final transmitted angle, i.e. cos(theta_2)
// we need this angle for the Fresnel terms at the bottom interface
float sin2 = pow(n0 / n2, 2) * (1 - pow(cos0, 2));
if (sin2 > 1) return 1.0f;
// total internal reflection
float cos2 = sqrt(1 - sin2);
// get the reflection transmission amplitude Fresnel coefficients
float alpha_s = rs(n1, n0, cos1, cos0) * rs(n1, n2, cos1, cos2);
// rho_10 * rho_12 (s-polarized)
float alpha_p = rp(n1, n0, cos1, cos0) * rp(n1, n2, cos1, cos2);
// rho_10 * rho_12 (p-polarized)
float beta_s = ts(n0, n1, cos0, cos1) * ts(n1, n2, cos1, cos2);
// tau_01 * tau_12 (s-polarized)
float beta_p = tp(n0, n1, cos0, cos1) * tp(n1, n2, cos1, cos2);
// tau_01 * tau_12 (p-polarized)
// compute the phase term (phi)
float phi = (2 * PI / lambda) * (2 * n1 * thickness * cos1) + delta;
// finally, evaluate the transmitted intensity for the two possible polarizations
float ts = pow(beta_s) / (pow(alpha_s, 2) - 2 * alpha_s * cos(phi) + 1);
float tp = pow(beta_p) / (pow(alpha_p, 2) - 2 * alpha_p * cos(phi) + 1);
// we need to take into account conservation of energy for transmission
float beamRatio = (n2 * cos2) / (n0 * cos0);
// calculate the average transmitted intensity (if you know the polarization distribution of your
// light source, you should specify it here. if you don't, a 50%/50% average is generally used)
float t = beamRatio * (ts + tp) / 2;
// and finally, derive the reflected intensity
return 1 - t;
}```
oh when its formatted nicely its much more clear, they even commented it
I believe so
I see π€
Ill try to repro the above code now.
I also had this link where they put the code fairly sensibly, but I wasnt able to deduce what all the random letter variables were supposed to be, like cosT
https://docs.chaos.com/display/OSLShaders/Thin+Film+Shader
Yeah
The wave amplitude calculations you'll need to write yourself. Just implement them as called following the middle image here
that explains why some of the shaders I looked at were calling things 'rs'
people copying people copying people
r = reflection,
t = transmission
s = s-polarised
p = p-polarised
now to google all of those things
The Fresnel equations (or Fresnel coefficients) describe the reflection and transmission of light (or electromagnetic radiation in general) when incident on an interface between different optical media. They were deduced by Augustin-Jean Fresnel () who was the first to understand that light is a transverse wave, even though no one realized that ...
how much of all these incredibly deep mathematics are being hand-waved/solved by this node by itself
it gets a bit physics heavy here on in lol
yeah π€
An incredible amount
I wish I could tell which parts I can safely drop/subtitute for pre-existing nodes
this is getting pushed up more and more, starting on implimenting it now before its lost
want me to DM it you so it doesn't get lost?
Im saving it into a .shader file in my project now
// cosI is the cosine of the incident angle, that is, cos0 = dot(view angle, normal)
that part is the 'fresnel' bit, if I did that right?
Discussion of the difference between S and P polarized ilght
this isn't important to know for this but I got curious since wikipedia's article demands a certain level of prerequisite knowledge to learn
I think it's meant to the cos Theta but they chose 0 for some reason
this is all branching logic, can that even be done in shader?
unless its not branching logic at all
my translation of that is "if n1 larger than n0, true = 0, false = Pi
that's correct
you can do logical branching in shader graph, I've not touched it myself however
googled it
this feels dirty, everything ive ever been taught about shaders is no branching logic
The problem with conditionals is branch prediction. That's why tricks like multiplying is preferred
thankfully it converges pretty fast
btw they're set as constant floats with no initial values there but the paper defines them as follows:
Consider a light wave incident to a thin layer of depth \deltaΞ΄ and real refractive index n_1n 1. The external medium has refractive index n_0n 0 and the internal medium has refractive index n_2n 2. The incident angle made by the incident light wave and the film's surface normal is \theta_0ΞΈ 0, the angle inside the layer is \theta_1ΞΈ 1 and the refracted angle (inside the internal medium) is denoted \theta_2ΞΈ 2 . We will also give numbers to each of the three media: medium 0 is the external medium, medium 1 is the layer, and medium 2 is the internal medium. Also, naturally, medium 0 has to have a different refractive index than medium 1, and the same goes for medium 1 and medium 2. Media 0 and 2 can be the same, of course.```
First paragraph under the heading derivation
This site is terrible at formatting
sooo they're saying n0,1,2 are values of 0, 2, and theta?
yeah the formatting makes it nearly unreadable
I think layer one is the thin film thickness? Near the end they state if you set that to 0 it plays out like regular fresnel
I feel in my heart at the end of this the end result is going to be 'throw all of this out and just use fresnel on a color gradient π₯
but its the learning that matters, not the result
sure but bubble dragon
hell yeah bubble dragon
okay contining onto the next nodes
at least when I am done it will be easy to tell what can be replaced for what
if (sin1 > 1) return 1.0f;
Saturate and Clamp both do values 0 to 1 right?
Normalize rescales its values to be between 0 and 1, but saturate is what they're doing here?
Normalise scales to 1
// rho_10 * rho_12 (s-polarized)
float alpha_p = rp(n1, n0, cos1, cos0) * rp(n1, n2, cos1, cos2);
// rho_10 * rho_12 (p-polarized)
float beta_s = ts(n0, n1, cos0, cos1) * ts(n1, n2, cos1, cos2);
// tau_01 * tau_12 (s-polarized)
float beta_p = tp(n0, n1, cos0, cos1) * tp(n1, n2, cos1, cos2);````
Ive gotten this far now
all four of those are functions right?
im guessing those functions maybe are elsewhere on that page?
yup as defined here
π°
rs = n1 cos theta lower case i minus n0, cos theta lower case j
divided by.. the exact same values?
oh but plus instead of minus
Im going to have to make a subgraph for this
uhh there's no symbol between Ni and cos0
is it multiplying?
yep
is I some kind of function? oh okay
no operator between values means multiply
I guess I knew that somehow but couldnt remember why
btw i think you can drop the conditionals and subtract and pull the sign
Ill update mine to that
So you are saying these are equivalent?
I believe so
Ill keep the original off to the side just in case
if n1 is greater than n0 then the result of subtracting them should result in a positive number, which sign returns as 1, otherwise it should result in a negative number, giving us -1
on that note I'm adding a max after the result of sign with 0 as B since we want to use that multiplier to determine whether we want 0 or pi
where can i find this setting
then the result of that into the multiply
its starting to get messy and involve a lot of subgraphs but progress is being made
ikr lol
oh god I just saw how many times these polarizing function things happen
eight of them
I can no longer keep track of it and im 100% sure im making a fuckload of mistakes
I know im not going to be able to finish thsi tonight
im trying to carefully re-create this
but I think its too complicated
when this doesnt work because ive made tones of mistakes, its going to be hell to find them all
screw it I say
Thats a good idea
_out = (ni*cosi-nj*cosj)/(ni*cosi+nj*cosj);
_out = (2*ni*cosi)/(ni*cosi+nj*cosj);
_out = (nj*cosi-ni*cosj)/(ni*cosj+nj*cosi);
_out = (2*nj*cosj)/(ni*cosj+nj*cosi);```
for rs, ts, rp, and tp respectively
thanks, I just finished typing the first one from your text, copying will be faster
I need to know what that shader is right now
its the one im trying to write as we speak
Thin Film Interference
Thank you good sirs
if you finish it before I do, pls share your work because its far from easy π₯
I will do the same of course
oh no I will just see skim the article, I am far from this level
good luck!
totally not spahgetti
float phi = (2 * PI / lambda) * (2 * n1 * thickness * cos1) + delta;
// lambda is the wavelength of the incident light (e.g. lambda = 510 for green)
how do I know what the light's wavelength is?
I have the main light's direction
I honestly have no idea, for now I'm setting it as a property
I will do the same
I will be amazed if this does anything at the end
right now it looks like nothing but tons of white circles
same lol
float tp = pow(beta_p) / (pow(alpha_p, 2) - 2 * alpha_p * cos(phi) + 1);```
to the power of what?
Sounds good to me
like no symbol means assume multiply
I've been using mul instead of pow for those
and just passing the same value in both A and B since n*n == n^2
I see π€
wait hold on
the next one says 2 yheah
I guess its both two???? but it feels really wrong to just assume that
it is rather annoying
making up stuff that isnt in the source is how you get end results that dont work
Ill make a note of this in case its not working to check here first
float ts = pow(beta_s) / (pow(alpha_s, 2) - 2 * alpha_s * cos(phi) + 1);
im pretty sure im fucking up the PEMDAS of this
I knwo you do all mults/divides before addition
but im not sure where the addition goes after the mults/divides resolve
also is there missing brackets?
nah it's BIDMAS
because there's a ) at the end, but it has no start
Ill have to google both bidmas and ltr
when I select this final bracket, it has no opening bracket
im hoping this is just a mistake on their part
it's the bracket before the second pow
my Ns are not zero
allegedly this is done, now I just have to trace the purple
alpha P is zero
okay whty is alpha p zero becomes the question
alpha S is also zero
are yours zero?
what values are you using?
I have no idea, no ability what so ever, to diagnose what is wrong here
its just too big
and too much mess
these things return zero but I dont know why they return zero or how to fix it
my anxiety is spiking
that I did all this work for nothing
my mistake was hoping that if I just copied it exactly that it would work
but that was not a realistic goal
nothing ever works when you copy it exactly becaue I'm a stupid human being who didnt copy it excvtly
Mine isn't working either, dwai
i just have to redo the entire thing from scratch step by step
until I find the mistake
these things are all returning zero
the mistake must be in here
maybe this is NOT representitive of the text code block???
that could be wrong, I did it rather fast and didn't double check everything
ill ready it very very carefully
especially given both i and j look exactly the same in their dog shit font
n is referring to the nth index and i/j are referring to the set of parameters
oh I found a mistake
ts and tp have a different formula
but in yours its all the same formula in all 4
oh wait no
its me
the mistake is that I didnt copy the right things into the right custom nodes
ill fix that now
well its still purple at the end but at least that part is now showing something

hmm problem appears to be only in beta S and alpha s
at least its not purple!
these are all returning zero
but its identical to the code
float alpha_s = rs(n1, n0, cos1, cos0) * rs(n1, n2, cos1, cos2);
this is that right???
and RS is Out = (ni*cosi-nj*cosj)/(ni*cosi+nj*cosj);
that's what I have yeah
does your return zero though?
this area is the problem area
im positive i pemdas'd this wrong
thats the only thing I can see that could be causin this
that I can see
with my stupid inexperienced eyes that see nothing
lol
π±
my beta s is zero, this is a problem
maybe its a values problem
might be something to do with the values
maybe it needs very specific values to work???
I have mine set to 0.1, 0.2, 0.1
praise be the eldritch lords that preside over precision
im going to go ahead and say i have no idea whats wrong, and no idea how to fix it
and probably i should just cut my losses and move onto to adampting another person's version
like this persons's
this oen actually talks about RGB colors so that already feels more like it might work???
I think this guy is doing the exact same math
oh I missed something
because he's got n0, 1, 2, he calls cos0 eta0, and delta is there too
Oh? π
We can now sample this function at red, green, and blue wavelengths (650, 510, 475 nanometers, respectively) and substitute the RGB reflectance obtained into the Fresnel term of the BRDF
yeah this is definitely the same math, he has delta10 and delta12
oh dear god are they saying to run that gigantic mess three times
yup
this is starting to look more and more appealing
lol