[Unity] URP x Jewel Shader
I've uploaded the sample to the repository below. It's URP on Unity 2022.3.69f1.
GitHub - takumifukasawa/UnityURPJewerlyShader
The shader in this article is built on the asset below, and I'm grateful for it. I'll go into the details
later.
[Unity] Akane-style Jewel Shader (akanevrc_JewelShader) [VRChat compatible] - Akane's Tool Shop - BOOTH
Introduction
In real-time rendering, drawing objects that need refraction is a pain. If something just needs to be "see-through", you can use the GPU's transparency and blending features, but how you implement a look where light "bends", as with refraction, depends on the case.
First, consider drawing a water surface. When underwater objects near the surface sway or look bent, I think that reads as water. In other words, a single refraction should get you close to a watery look. One way to implement it is to draw everything except the water first and the water surface mesh after it, pass a texture of the already-drawn scene to the shader that draws the water surface, and offset the position where that texture is sampled using normals, a noise map and so on. It isn't a perfect simulation of refraction, but things look bent, so it's convincing enough.
However, when you want to reproduce a complex look with two or three rounds of reflection and refraction, as in a jewel, an image of only what's behind the object, like that already-drawn scene, doesn't hold enough information, because a real jewel takes in light from all around it.
Path tracing would get you closer to a fundamental solution, but it's very heavy. And for a mobile game aimed at users all over the world, like a hyper-casual game, a light load matters all the more.
While I was looking into this, I found the asset I introduced at the beginning.
It said it "draws in one pass", and when I looked inside, it really did solve the problem with a per-object shader, with no path tracing or anything like it. In terms of load, it was exactly the ideal approach. The reference asset is implemented for the Built-in Pipeline and intended for VRChat. Its license is CC0, so I used its contents as a reference to implement it for URP, and added some modifications of my own.
I'll explain the idea behind how it achieves multiple reflections, and how I implemented and modified it.
Implementation approach
First, let's look at the overall flow of multiple reflections. What we do is "create a ray and, once it has entered the object, loop until it either hits the maximum number of reflections or exits". This is because the Fresnel calculation decides whether light that has entered the object reflects back inside again or leaves the object.
// pseudo-code
float3 color;
Ray ray;
float isReflect = 1.;
for(int i = 0; i < iterateNum; i++) {
if(isReflect) {
color += CastRay(ray, isReflect); // compute the reflection; also decide between reflection and refraction according to Fresnel
}
}
In the reference asset, the multiple-reflection process breaks down roughly into four steps.
- Create, in advance, a CubeMap that stores the mesh's normal information
- In the pixel shader, create a ray from the viewpoint that enters the object
- Determine the ray's internal reflection and exit. Read the CubeMap from step 1 and find "the approximate coordinates and normal of the reflection/exit point"
- Based on the normal from step 3, read the scene's environment map and add it. If it's an internal reflection, repeat 3 and 4
Steps 3 and 4 are what CastRay does in the loop above. Let's look at them one by one.
1. Generating a CubeMap that stores the mesh's normal information
The reference asset provides a tool that generates a CubeMap with the mesh's normal information baked into it. It
bakes the CubeMap with a shader like the one below.
Since it bakes into the RGBA8 format, the normal is multiplied by 0.5 and offset by 0.5, remapping it from -1..1 to
0..1 before it's stored. A float texture wouldn't need this conversion, but it would be larger.
v2f vert(appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.normal = UnityObjectToWorldNormal(v.normal);
return o;
}
fixed4 frag(v2f i) : SV_Target
{
return saturate(fixed4(i.normal, 1) * 0.5 + 0.5);
}
This screenshot shows a CubeMap made from Unity's standard Box.

2. Creating the ray that enters the mesh from the viewpoint
This is the vector from the camera position to the position of the mesh's pixel.
float3 E = _WorldSpaceCameraPos;
float3 inP = input.positionWS; // entry position
float3 N = normalize(input.normalWS);
float3 PtoE = normalize(E - inP);
float3 inDir = -PtoE; // incident vector
3. Determining the ray's internal reflection and exit
This is the heart of the implementation. The idea is "if you find the vector reflected at the center of the object, you get the approximate exit position/normal".
- Choose a center position as you see fit (the center the CubeMap was baked around; if you placed the mesh at the origin when creating the CubeMap, it's 0,0,0)
- From the ray's incident vector, the entry position and the center position, determine the approximate exit position
- From the approximate position and the center, compute the vector for looking up the CubeMap (the normal baked into the CubeMap)
Here's the pseudo-code.
float3 outP = dot(center - inP) * 2 * inDir; // approximate exit position
float3 cubeDir = normalize(outP - center); // vector for looking up the Cubemap
float3 outNormal = texCube(bakedCubemap, cubeDir).xyz * 2. - 1.; // normal: stored converted from -1~1 to 0~1, so convert back to -1~1

This method seems especially suited to meshes with shapes that tend to be symmetrical, like jewels.
4. Reading the scene's environment map based on the normal and adding it. Repeating 3 and 4.
Sample the environment map with the normal found in step 3 and use that as the color for this reflection. Then compute the vector reflected inward and repeat steps 3 and 4, accumulating the colors.
At each reflection, Fresnel's law splits the light into the part that reflects back inside the object and the part
that exits it, so weighting the added color by that ratio expresses how light attenuates through reflection.
Below, the number of reflections goes from 0 to 8. Each additional reflection adds more color.

That's how the look of multiple internal reflections is achieved.
Since this method adds the color of the scene's environment map at each reflection, for objects that don't move you could probably get a richer look by baking the lighting and putting more information into the scene's environment map.
Dispersion
This reproduces the way color components split apart, as in a rainbow or a prism. Each color component of light has a different wavelength, and that changes how much it bends. From red to violet, wavelengths go from long to short, and red, with its longer wavelength, tends to travel straight and bends less.
In the shader, the light path is computed separately for R, G and B, and the results are combined at the end. Slightly offsetting the IOR (index of refraction) passed to refract, the function that refracts a vector, for each of R, G and B changes how much each one bends. The sampled colors then drift apart slightly per channel, which produces a dispersion-like effect.
ex)
Red: refract(dir, normal, ior + .01);
Green: refract(dir, normal, ior);
Blue: refract(dir, normal, ior - .01);
Parameters per color component

The trade-off is that the path calculation triples, so by simple arithmetic the load triples too.
// 3x, because a loop of the search count runs for each color component
float colorR = CastRayIterate(ray, IOR + 0.01);
float colorG = CastRayIterate(ray, IOR);
float colorB = CastRayIterate(ray, IOR - 0.01);
Below, I vary how much the IOR is offset.

Absorption
Jewels differ in color because each one absorbs the color components at different rates. The lower a color component's absorption rate, the more strongly it shows up in the jewel's color. Ruby, for example, is red, so its absorption rate for the red component is low.
In the shader, exp(-kx) is computed as the amount of attenuation. The color is computed for each of R, G and B as
color component * exp(- absorption rate * distance).
The lower the absorption rate, the weaker the attenuation, so that color component comes out more easily.
Parameters per color component

Graph of exp(-kx)

Graph created with Desmos. Licensed under CC BY-SA 4.0
Here, the absorption rate of the red component is lowered to give a ruby-like look.

I also tried adding colors like sapphire and emerald.

Conversely, making the absorption rate negative amplifies the light, so the jewel glows on its own. To make it shine, I also turn on post-processing bloom. Real jewels don't glow on their own, but that's the beauty of CG. Because it glows, though, the refraction inevitably becomes harder to make out.

Graph created with Desmos. Licensed under CC BY-SA 4.0

Dummy light sources
As mentioned above, the jewel itself doesn't emit light, so I add dummy light sources to bring in extra light.
The reference asset allows up to four dummy light sources. In my implementation I cut that to two, and at each
reflection I compute the diffuse component for each light source and add it.
Here I'm moving the red dummy light source and changing the color of the second dummy light source from white to blue.

Modifying the CubeMap generation
I tried storing in the generated CubeMap not only the normal information but also the distance from the center.
The main purpose is to use it as a parameter for the distance attenuation of light.
I changed the baked parameters as follows. xy holds the normal, z holds the distance from the center divided by the
size of the bounds, and w holds the reciprocal of the size of the bounds.
The distance from the center itself is the length of the vector in local coordinates, but since the texture format is
RGBA8, the values have to fit in 0-1, so z and w are used to restore the distance from the center when reading them
back.
// changes to the code that bakes into the CubeMap
// xy: pack only the xy of the normal
float2 xy = saturate(i.normal.xy * .5 + .5);
// z: distance from the center
float z = length(i.vertex.xyz) / _BoundsScale;
// w: reciprocal of bounds. bounds is restricted to a uniform size
float w = 1. / _BoundsScale;
return fixed4(xy, z, w);
Given two axes of a normal, you can compute the remaining one. However, this adds the cost of restoring the normal on every loop iteration.
// restore the normal from a vector that only has xy components
float2 decodedNormalXY = cubeColor.xy * 2. - 1.;
float decodedZ = sqrt(max(0., 1. - dot(decodedNormalXY, decodedNormalXY)));
float3 localOutNormal = normalize(float3(decodedNormalXY, decodedZ));
When I applied it to the distance attenuation of the added color, the result with this mesh's shape was only slightly brighter. The difference is easiest to see on the faces with strong highlights toward the bottom right.

In closing
I learned a lot from the reference asset, and I'm very grateful for it. Once again, here is the repository with the implementation.
GitHub - takumifukasawa/UnityURPJewerlyShader
