summaryrefslogtreecommitdiffstats
path: root/decal.cginc
blob: 8492c74e5bdcf720f4832bf7d254dd02061728aa (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
75
76
77
78
79
80
81
82
83
#ifndef __DECAL_INC
#define __DECAL_INC

#include "globals.cginc"
#include "pbr.cginc"
#include "interpolators.cginc"
#include "texture_utils.cginc"

float4 decal_sample(texture2D tex, float2 uv, int uv_mode) {
  [forcecase]
  switch (uv_mode) {
    case DECAL_UV_MODE_REPEAT:
      return tex.Sample(aniso4_trilinear_repeat_s, uv);
    case DECAL_UV_MODE_MIRROR:
      return tex.Sample(aniso4_trilinear_mirror_s, uv);
    case DECAL_UV_MODE_CLAMP:
      return tex.Sample(aniso4_trilinear_clamp_s, uv);
    default:
      return 0;
  }
}

float2 decal_rotate(float2 uv, float rotation) {
  float s, c;
  sincos(rotation * TAU, s, c);
  float2 d = uv - 0.5;
  return float2(d.x * c - d.y * s, d.x * s + d.y * c) + 0.5;
}

void applyDecals(v2f i, inout Pbr pbr) {
#if defined(_DECAL0)
  {
    float2 uv = get_uv_by_channel(i, _Decal0_UV_Channel);
    uv -= _Decal0_MainTex_ST.zw;
    uv *= _Decal0_MainTex_ST.xy;
#if defined(_DECAL0_ROTATION)
    uv = decal_rotate(uv, _Decal0_Rotation);
#endif
    float4 albedo = decal_sample(_Decal0_MainTex, uv, _Decal0_UV_Mode);
    albedo *= _Decal0_Color;
    albedo.a *= _Decal0_Opacity;

#if defined(_DECAL0_MASK)
    float2 mask_uv = get_uv_by_channel(i, _Decal0_Mask_UV_Channel);
    mask_uv -= _Decal0_Mask_ST.zw;
    mask_uv *= _Decal0_Mask_ST.xy;
    // For now, mask gets the same sampling mode as the decal.
    float mask = decal_sample(_Decal0_Mask, mask_uv, _Decal0_UV_Mode);
#if defined(_DECAL0_MASK_INVERT)
    mask = 1 - mask;
#endif  // _DECAL0_MASK_INVERT
    albedo.a *= mask;
#endif  // _DECAL0_MASK

#if defined(_DECAL0_ALBEDO_CLAMP)
    albedo.rgb = saturate(albedo.rgb);
#endif  // _DECAL0_ALBEDO_CLAMP

    [forcecase]
    switch (_Decal0_Mix_Mode) {
      case DECAL_MIX_MODE_ALPHA_BLEND:
        pbr.albedo = alpha_blend(albedo, pbr.albedo);
        break;
      case DECAL_MIX_MODE_MULTIPLY:
        pbr.albedo.rgb *= lerp(1, albedo.rgb, albedo.a);
        break;
      case DECAL_MIX_MODE_ADD_PRODUCT:
        pbr.albedo.rgb += lerp(0, albedo.rgb * pbr.albedo.rgb, albedo.a);
        break;
    }

#if defined(_DECAL0_METALLIC_GLOSS)
    float4 mg = decal_sample(_Decal0_Metallic_Gloss, uv, _Decal0_UV_Mode);
    pbr.metallic = lerp(pbr.metallic, mg.r, albedo.a);
    pbr.smoothness = lerp(pbr.smoothness, mg.a, albedo.a);
    pbr.roughness_perceptual = clamp(1 - pbr.smoothness, MIN_PERCEPTUAL_ROUGHNESS, 1);
    pbr.roughness = clamp(pbr.roughness_perceptual * pbr.roughness_perceptual, MIN_ROUGHNESS, 1);
#endif  // _DECAL0_METALLIC_GLOSS
  }
#endif
}

#endif  // __DECAL_INC