yum-archive/Tooner

A toon shader for Unity's BIRP.

git clone https://git.yummers.dev/yum-archive/Tooner

yumMake flat normals adjustable47d32c9

v0.0.0
13.6 KiB408 linesraw
1#ifndef LTCGI_INCLUDED
2#define LTCGI_INCLUDED
3
4#include "LTCGI_config.cginc"
5
6#ifdef LTCGI_AVATAR_MODE
7    #undef LTCGI_STATIC_UNIFORMS
8    #undef LTCGI_BICUBIC_LIGHTMAP
9    #define LTCGI_ALWAYS_LTC_DIFFUSE
10    // for perf and locality don't allow cylinders on avatars for now (it probably would be misdetected anyway)
11    #undef LTCGI_CYLINDER
12#endif
13
14#ifdef LTCGI_TOGGLEABLE_SPEC_DIFF_OFF
15    #undef LTCGI_DIFFUSE_OFF
16    #undef LTCGI_SPECULAR_OFF
17#endif
18
19#if defined(LTCGI_V2_CUSTOM_INPUT) || defined(LTCGI_V2_DIFFUSE_CALLBACK) || defined(LTCGI_V2_SPECULAR_CALLBACK)
20    #define LTCGI_API_V2
21#endif
22
23#include "LTCGI_structs.cginc"
24#include "LTCGI_uniform.cginc"
25#include "LTCGI_functions.cginc"
26#include "LTCGI_shadowmap.cginc"
27
28#ifdef SHADER_TARGET_SURFACE_ANALYSIS
29#define const  
30#endif
31
32// Main function - this calculates the approximated model for one pixel and one light
33void LTCGI_Evaluate(ltcgi_input input, float3 worldNorm, float3 viewDir, float3x3 Minv, float roughness, const bool diffuse, out ltcgi_output output) {
34    output.input = input;
35    output.color = input.rawColor; // copy for colormode static
36    output.intensity = 0;
37
38    // diffuse distance fade
39    #ifdef LTCGI_DISTANCE_FADE_APPROX
40        if (diffuse) // static branch, specular does not directly fade with distance
41        {
42            if (!input.flags.lmdOnly) {
43                // very approximate lol
44                float3 ctr = (input.Lw[0] + input.Lw[1])/2;
45                float dist = length(ctr);
46                if (dist > LTCGI_DISTANCE_FADE_APPROX_MULT)
47                {
48                    return;
49                }
50            }
51        }
52    #endif
53
54    #define RET1_IF_LMDIFF [branch] if (/*const*/ diffuse && input.flags.diffFromLm) { output.intensity = 1.0f; return; }
55
56    if (input.flags.colormode == LTCGI_COLORMODE_SINGLEUV) {
57        float2 uv = input.uvStart;
58        if (uv.x < 0) uv.xy = uv.yx;
59        // TODO: make more configurable?
60        #ifdef LTCGI_VISUALIZE_SAMPLE_UV
61            output.color = float3(uv.xy, 0);
62        #elif !defined(SHADER_TARGET_SURFACE_ANALYSIS)
63            // sample video texture directly for accuracy
64            float3 sampled = _Udon_LTCGI_Texture_LOD0.SampleLevel(LTCGI_SAMPLER, uv.xy, 0).rgb;
65            output.color *= sampled;
66        #endif
67
68        RET1_IF_LMDIFF
69    }
70
71    #ifdef LTCGI_AUDIOLINK
72        if (input.flags.colormode == LTCGI_COLORMODE_AUDIOLINK) {
73            float al = AudioLinkData(ALPASS_AUDIOLINK + uint2(0, input.flags.alBand)).r;
74            output.color *= al;
75
76            RET1_IF_LMDIFF
77        }
78    #endif
79
80    // create LTC polygon array
81    // note the order of source verts (keyword: winding order)
82    float3 L[5];
83    L[0] = mul(Minv, input.Lw[0]);
84    L[1] = mul(Minv, input.Lw[1]);
85    L[2] = input.isTri ? L[1] : mul(Minv, input.Lw[3]);
86    L[3] = mul(Minv, input.Lw[2]);
87    L[4] = 0;
88
89    // get texture coords (before clipping!)
90    [branch]
91    if (input.flags.colormode == LTCGI_COLORMODE_TEXTURE) {
92        float3 RN;
93        float2 uv = LTCGI_calculateUV(input.i, input.flags, L, input.isTri, input.uvStart, input.uvEnd, RN);
94        float planeAreaSquared = dot(RN, RN);
95        float planeDistxPlaneArea = dot(RN, L[0]);
96
97        float3 sampled;
98        [branch]
99        if (diffuse) { // static branch
100            #ifdef LTCGI_BLENDED_DIFFUSE_SAMPLING
101                float3 sampled1;
102                LTCGI_sample(uv, 3, input.flags.texindex, 10, sampled1);
103                float3 sampled2;
104                LTCGI_sample(uv, 3, input.flags.texindex, 100, sampled2);
105                sampled =
106                    sampled1 * 0.75 +
107                    sampled2 * 0.25;
108            #else
109                LTCGI_sample(uv, 3, input.flags.texindex, 10, sampled);
110            #endif
111        } else {
112            float d = abs(planeDistxPlaneArea) / planeAreaSquared;
113            d *= LTCGI_UV_BLUR_DISTANCE;
114            d = log(d) / log(3.0);
115
116            // a rough material must never show a perfect reflection,
117            // since our LOD0 texture is not prefiltered (and thus cannot
118            // depict any blur correctly) - without this there is artifacting
119            // on the border of LOD0 and LOD1
120            d = clamp(d, saturate(roughness * 5.75), 1000);
121
122            LTCGI_trilinear(uv, d, input.flags.texindex, sampled);
123        }
124
125        // colorize output
126        output.color *= sampled;
127    }
128
129    RET1_IF_LMDIFF
130    #undef RET1_IF_LMDIFF
131
132    int n;
133    LTCGI_ClipQuadToHorizon(L, n);
134
135    // early out if everything was clipped below horizon
136    if (n == 0)
137        return;
138
139    L[0] = normalize(L[0]);
140    L[1] = normalize(L[1]);
141    L[2] = normalize(L[2]);
142    L[3] = normalize(L[3]);
143    L[4] = normalize(L[4]);
144
145    // integrate (and pray that constant folding works well)
146    float sum = 0;
147    [unroll(5)]
148    for (uint v = 0; v < max(3, (uint)n); v++) {
149        float3 a = L[v];
150        float3 b = L[(v + 1) % 5];
151        sum += LTCGI_IntegrateEdge(a, b).z;
152    }
153
154    // doublesided is accounted for with optimization at the start, so return abs
155    output.intensity = abs(sum);
156    return;
157}
158
159// Calculate light contribution for all lights,
160// call this from your shader and use the "diffuse" and "specular" outputs
161// lmuv is the raw lightmap UV coordinate (e.g. UV1)
162void LTCGI_Contribution(
163#ifdef LTCGI_API_V2
164    inout LTCGI_V2_CUSTOM_INPUT data,
165#endif
166    float3 worldPos, float3 worldNorm, float3 viewDir, float roughness, float2 lmuv
167#ifndef LTCGI_API_V2
168    , inout half3 diffuse, inout half3 specular, out float totalSpecularIntensity, out float totalDiffuseIntensity
169#endif
170) {
171    #ifndef LTCGI_API_V2
172        totalSpecularIntensity = 0;
173        totalDiffuseIntensity = 0;
174    #endif
175    if (_Udon_LTCGI_GlobalEnable == 0.0f) {
176        return;
177    }
178
179    // sample lookup tables
180    float theta = LTCGI_acos_fast(dot(worldNorm, viewDir));
181    float2 uv = float2(roughness, theta/(0.5*UNITY_PI));
182    uv = uv*LUT_SCALE + LUT_BIAS;
183
184    #ifndef UNITY_UV_STARTS_AT_TOP
185        uv.y = 1 - uv.y;
186    #endif
187
188    // calculate LTCGI custom lightmap UV and sample
189    float3 lms = LTCGI_SampleShadowmap(lmuv);
190
191    #ifndef SHADER_TARGET_SURFACE_ANALYSIS_MOJOSHADER
192    // sample BDRF approximation from lookup texture
193    float4 t = _Udon_LTCGI_lut1.SampleLevel(LTCGI_SAMPLER, uv, 0);
194    #endif
195    float3x3 Minv = float3x3(
196        float3(  1,   0, t.w),
197        float3(  0, t.z,   0),
198        float3(t.y,   0, t.x)
199    );
200
201    // construct orthonormal basis around N
202    float3 T1, T2;
203    T1 = normalize(viewDir - worldNorm*dot(viewDir, worldNorm));
204    T2 = cross(worldNorm, T1);
205
206    // for diffuse lighting we assume the identity matrix as BDRF, so the
207    // LTC approximation is directly equivalent to the orthonormal rotation matrix
208    float3x3 identityBrdf = float3x3(float3(T1), float3(T2), float3(worldNorm));
209    // rotate area light in (T1, T2, N) basis for actual BRDF matrix as well
210    Minv = mul(Minv, identityBrdf);
211
212    // specular brightness
213    #ifndef LTCGI_SPECULAR_OFF
214    #ifndef SHADER_TARGET_SURFACE_ANALYSIS_MOJOSHADER
215        float spec_amp = _Udon_LTCGI_lut2.SampleLevel(LTCGI_SAMPLER, uv, 0).x;
216    #endif
217    #endif
218
219    bool noLm = false;
220    #ifdef LTCGI_LTC_DIFFUSE_FALLBACK
221    #ifndef LTCGI_ALWAYS_LTC_DIFFUSE
222    #ifndef SHADER_TARGET_SURFACE_ANALYSIS
223        float2 lmSize;
224        _Udon_LTCGI_Lightmap.GetDimensions(lmSize.x, lmSize.y);
225        noLm = lmSize.x == 1;
226    #endif
227    #endif
228    #endif
229    #ifdef LTCGI_ALWAYS_LTC_DIFFUSE
230        noLm = true;
231    #endif
232
233    // loop through all lights and add them to the output
234    uint count = min(_Udon_LTCGI_ScreenCount, MAX_SOURCES);
235    [loop]
236    for (uint i = 0; i < count; i++) {
237        // skip masked and black lights
238        if (_Udon_LTCGI_Mask[i]) continue;
239        float4 extra = _Udon_LTCGI_ExtraData[i];
240        float3 color = extra.rgb;
241        if (!any(color)) continue;
242
243        ltcgi_flags flags = ltcgi_parse_flags(asuint(extra.w), noLm);
244        
245        #ifdef LTCGI_ALWAYS_LTC_DIFFUSE
246            // can't honor a lightmap-only light in this mode
247            if (flags.lmdOnly) continue;
248        #endif
249
250        #ifdef LTCGI_TOGGLEABLE_SPEC_DIFF_OFF
251            // compile branches below away statically
252            flags.diffuse = flags.specular = true;
253        #endif
254
255        // calculate (shifted) world space positions
256        float3 Lw[4];
257        float4 uvStart = (float4)0, uvEnd = (float4)0;
258        bool isTri = false;
259        if (flags.lmdOnly) {
260            Lw[0] = Lw[1] = Lw[2] = Lw[3] = (float3)0;
261        } else {
262            LTCGI_GetLw(i, flags, worldPos, Lw, uvStart, uvEnd, isTri);
263        }
264
265        // skip single-sided lights that face the other way
266        float3 screenNorm = cross(Lw[1] - Lw[0], Lw[2] - Lw[0]);
267        if (!flags.doublesided) {
268            if (dot(screenNorm, Lw[0]) < 0)
269                continue;
270        }
271
272        float lm = 1;
273        if (flags.lmch) {
274            lm = lms[flags.lmch - 1];
275            if (lm < 0.001) continue;
276        }
277
278        ltcgi_input input;
279        input.i = i;
280        input.Lw = Lw;
281        input.isTri = isTri;
282        input.uvStart = uvStart;
283        input.uvEnd = uvEnd;
284        input.rawColor = color;
285        input.flags = flags;
286        input.screenNormal = screenNorm;
287
288        // diffuse lighting
289        #ifndef LTCGI_DIFFUSE_OFF
290            [branch]
291            if (flags.diffuse)
292            {
293                float lmd = lm;
294                if (flags.lmch) {
295                    if (flags.diffFromLm)
296                        lmd *= _Udon_LTCGI_LightmapMult[flags.lmch - 1];
297                    else
298                        lmd = smoothstep(0.0, LTCGI_SPECULAR_LIGHTMAP_STEP, saturate(lm - LTCGI_LIGHTMAP_CUTOFF));
299                }
300                ltcgi_output diff;
301                LTCGI_Evaluate(input, worldNorm, viewDir, identityBrdf, roughness, true, diff);
302                diff.intensity *= lmd;
303
304                #ifdef LTCGI_API_V2
305                    LTCGI_V2_DIFFUSE_CALLBACK(data, diff);
306                #else
307                    // simply accumulate all lights
308                    diffuse += (diff.intensity * diff.color);
309                    totalDiffuseIntensity += diff.intensity;
310                #endif
311            }
312        #endif
313
314        // specular lighting
315        #ifndef LTCGI_SPECULAR_OFF
316            [branch]
317            if (flags.specular)
318            {
319                ltcgi_output spec;
320                LTCGI_Evaluate(input, worldNorm, viewDir, Minv, roughness, false, spec);
321                spec.intensity *= spec_amp * smoothstep(0.0, LTCGI_SPECULAR_LIGHTMAP_STEP, saturate(lm - LTCGI_LIGHTMAP_CUTOFF));
322
323                #ifdef LTCGI_API_V2
324                    LTCGI_V2_SPECULAR_CALLBACK(data, spec);
325                #else
326                    // simply accumulate all lights
327                    specular += spec.intensity * spec.color;
328                    totalSpecularIntensity += spec.intensity;
329                #endif
330            }
331        #endif
332    }
333}
334
335// COMPATIBILITY FALLBACKS
336
337#ifndef LTCGI_API_V2
338
339void LTCGI_Contribution(
340    float3 worldPos, float3 worldNorm, float3 viewDir, float roughness, float2 lmuv, inout half3 diffuse
341) {
342    half3 _u1;
343    float _u2, _u3;
344    LTCGI_Contribution(worldPos, worldNorm, viewDir, roughness, lmuv, diffuse, _u1, _u2, _u3);
345}
346
347void LTCGI_Contribution(
348    float3 worldPos, float3 worldNorm, float3 viewDir, float roughness, float2 lmuv, inout half3 diffuse, inout half3 specular
349) {
350    float _u1, _u2;
351    LTCGI_Contribution(worldPos, worldNorm, viewDir, roughness, lmuv, diffuse, specular, _u1, _u2);
352}
353
354void LTCGI_Contribution(
355    float3 worldPos, float3 worldNorm, float3 viewDir, float roughness, float2 lmuv, inout half3 diffuse, inout half3 specular, out float totalSpecularIntensity
356) {
357    float _u1;
358    LTCGI_Contribution(worldPos, worldNorm, viewDir, roughness, lmuv, diffuse, specular, totalSpecularIntensity, _u1);
359}
360
361#endif
362
363/*
364
365Parts of the code in this file are adapted from the example code found here:
366  
367  https://github.com/selfshadow/ltc_code
368
369Modifications by _pi_ (@pimaker on GitHub), licensed under the terms of the
370MIT license as far as applicable.
371
372Original copyright notice:
373
374Copyright (c) 2017, Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt.
375All rights reserved.
376
377Redistribution and use in source and binary forms, with or without
378modification, are permitted provided that the following conditions are met:
379
380* If you use (or adapt) the source code in your own work, please include a 
381  reference to the paper:
382
383  Real-Time Polygonal-Light Shading with Linearly Transformed Cosines.
384  Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt.
385  ACM Transactions on Graphics (Proceedings of ACM SIGGRAPH 2016) 35(4), 2016.
386  Project page: https://eheitzresearch.wordpress.com/415-2/
387
388* Redistributions of source code must retain the above copyright notice, this
389  list of conditions and the following disclaimer.
390
391* Redistributions in binary form must reproduce the above copyright notice,
392  this list of conditions and the following disclaimer in the documentation
393  and/or other materials provided with the distribution.
394
395THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
396AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
397IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
398DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
399FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
400DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
401SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
402CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
403OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
404OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
405
406*/
407
408#endif