aboutsummaryrefslogtreecommitdiff
path: root/assets/shaders/sphere.slang
blob: e37700dac86cebad16f3e2cefbcb13ab16d91138 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Lit sphere (Blinn-Phong + HDRI ambient + selection rim). Uniforms in a
// ConstantBuffer (UBO, binding 0) so both backends drive it through the RHI;
// the environment cubemap is a separate sampler at binding 1.
struct SphereU
{
    float4x4 u_ViewProjection;
    float4x4 u_Transform;
    float3   u_Color;
    float    u_Specular;
    float    u_Emission;
    float3   u_LightPos;
    float3   u_CameraPos;
    int      u_IsSelected;
    float3   u_OutlineColor;
    float    u_OutlineWidth;
};
ConstantBuffer<SphereU> su;

struct VSInput
{
    float3 position : POSITION;
    float3 normal   : NORMAL;
};

struct VSOutput
{
    float4 position : SV_Position;
    float3 normal   : TEXCOORD0;
    float3 worldPos : TEXCOORD1;
};

[shader("vertex")]
VSOutput vertexMain(VSInput input)
{
    VSOutput output;
    output.worldPos = mul(su.u_Transform, float4(input.position, 1.0)).xyz;
    float3x3 normalMatrix = (float3x3)su.u_Transform;
    output.normal   = mul(normalMatrix, input.normal);
    output.position = mul(su.u_ViewProjection, float4(output.worldPos, 1.0));
    return output;
}

SamplerCube u_HDRIEnvironment;

[shader("fragment")]
float4 fragmentMain(VSOutput input) : SV_Target
{
    float3 normal     = normalize(input.normal);
    float3 lightDir   = normalize(su.u_LightPos - input.worldPos);
    float3 viewDir    = normalize(su.u_CameraPos - input.worldPos);
    float3 reflectDir = reflect(-lightDir, normal);

    float3 hdriLight     = u_HDRIEnvironment.Sample(normal).rgb;
    float  hdriIntensity = 0.3;

    float diff = max(dot(normal, lightDir), 0.0);
    float spec = pow(max(dot(viewDir, reflectDir), 0.0), 32.0);

    float3 diffuse  = su.u_Color * (diff + hdriIntensity * hdriLight);
    float3 specular = float3(su.u_Specular, su.u_Specular, su.u_Specular) * spec;
    float3 emission = su.u_Color * su.u_Emission;

    float3 result = diffuse + specular + emission;

    if (su.u_IsSelected > 0)
    {
        float ndotv       = max(dot(normal, viewDir), 0.0);
        float rim         = 1.0 - ndotv;
        float outlineMask = step(1.0 - su.u_OutlineWidth, rim);
        result = lerp(result, su.u_OutlineColor, outlineMask);
    }

    return float4(result, 1.0);
}