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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
|
//Original Code from https://github.com/DarthShader/Kaj-Unity-Shaders
/**MIT License
Copyright (c) 2020 DarthShader
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.**/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Text;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;
using Object = UnityEngine.Object;
#if VRC_SDK_VRCSDK3
using VRC.SDKBase;
#endif
#if VRC_SDK_VRCSDK2
using VRCSDK2;
#endif
#if VRC_SDK_VRCSDK2 || VRC_SDK_VRCSDK3
using VRC.SDKBase.Editor.BuildPipeline;
#endif
#if VRC_SDK_VRCSDK3 && !UDON
using static VRC.SDK3.Avatars.Components.VRCAvatarDescriptor;
using VRC.SDK3.Avatars.Components;
using System.Reflection;
#endif
// v9
namespace Thry
{
public enum LightMode
{
Always=1,
ForwardBase=2,
ForwardAdd=4,
Deferred=8,
ShadowCaster=16,
MotionVectors=32,
PrepassBase=64,
PrepassFinal=128,
Vertex=256,
VertexLMRGBM=512,
VertexLM=1024
}
// Static methods to generate new shader files with in-place constants based on a material's properties
// and link that new shader to the material automatically
public class ShaderOptimizer
{
//When locking don't include code from define blocks that are not enabled
const bool REMOVE_UNUSED_IF_DEFS = true;
// For some reason, 'if' statements with replaced constant (literal) conditions cause some compilation error
// So until that is figured out, branches will be removed by default
// Set to false if you want to keep UNITY_BRANCH and [branch]
public static bool RemoveUnityBranches = true;
// LOD Crossfade Dithing doesn't have multi_compile keyword correctly toggled at build time (its always included) so
// this hard-coded material property will uncomment //#pragma multi_compile _ LOD_FADE_CROSSFADE in optimized .shader files
public static readonly string LODCrossFadePropertyName = "_LODCrossfade";
// IgnoreProjector and ForceNoShadowCasting don't work as override tags, so material properties by these names
// will determine whether or not //"IgnoreProjector"="True" etc. will be uncommented in optimized .shader files
public static readonly string IgnoreProjectorPropertyName = "_IgnoreProjector";
public static readonly string ForceNoShadowCastingPropertyName = "_ForceNoShadowCasting";
// Material property suffix that controls whether the property of the same name gets baked into the optimized shader
// e.g. if _Color exists and _ColorAnimated = 1, _Color will not be baked in
public static readonly string AnimatedPropertySuffix = "Animated";
public static readonly string AnimatedTagSuffix = "Animated";
// Currently, Material.SetShaderPassEnabled doesn't work on "ShadowCaster" lightmodes,
// and doesn't let "ForwardAdd" lights get turned into vertex lights if "ForwardAdd" is simply disabled
// vs. if the pases didn't exist at all in the shader.
// The Optimizer will take a mask property by this name and attempt to correct these issues
// by hard-removing the shadowcaster and fwdadd passes from the shader being optimized.
public static readonly string DisabledLightModesPropertyName = "_LightModes";
// Property that determines whether or not to evaluate KSOInlineSamplerState comments.
// Inline samplers can be used to get a wider variety of wrap/filter combinations at the cost
// of only having 1x anisotropic filtering on all textures
public static readonly string UseInlineSamplerStatesPropertyName = "_InlineSamplerStates";
private static bool UseInlineSamplerStates = true;
// Material properties are put into each CGPROGRAM as preprocessor defines when the optimizer is run.
// This is mainly targeted at culling interpolators and lines that rely on those interpolators.
// (The compiler is not smart enough to cull VS output that isn't used anywhere in the PS)
// Additionally, simply enabling the optimizer can define a keyword, whose name is stored here.
// This keyword is added to the beginning of all passes, right after CGPROGRAM
public static readonly string OptimizerEnabledKeyword = "OPTIMIZER_ENABLED";
// Mega shaders are expected to have geometry and tessellation shaders enabled by default,
// but with the ability to be disabled by convention property names when the optimizer is run.
// Additionally, they can be removed per-lightmode by the given property name plus
// the lightmode name as a suffix (e.g. group_toggle_GeometryShadowCaster)
// Geometry and Tessellation shaders are REMOVED by default, but if the main gorups
// are enabled certain pass types are assumed to be ENABLED
public static readonly string GeometryShaderEnabledPropertyName = "GeometryShader_Enabled";
public static readonly string TessellationEnabledPropertyName = "Tessellation_Enabled";
private static bool UseGeometry = false;
private static bool UseGeometryForwardBase = true;
private static bool UseGeometryForwardAdd = true;
private static bool UseGeometryShadowCaster = true;
private static bool UseGeometryMeta = true;
private static bool UseTessellation = false;
private static bool UseTessellationForwardBase = true;
private static bool UseTessellationForwardAdd = true;
private static bool UseTessellationShadowCaster = true;
private static bool UseTessellationMeta = false;
// Tessellation can be slightly optimized with a constant max tessellation factor attribute
// on the hull shader. A non-animated property by this name will replace the argument of said
// attribute if it exists.
public static readonly string TessellationMaxFactorPropertyName = "_TessellationFactorMax";
enum LightModeType { None, ForwardBase, ForwardAdd, ShadowCaster, Meta };
private static LightModeType CurrentLightmode = LightModeType.None;
// In-order list of inline sampler state names that will be replaced by InlineSamplerState() lines
public static readonly string[] InlineSamplerStateNames = new string[]
{
"_linear_repeat",
"_linear_clamp",
"_linear_mirror",
"_linear_mirroronce",
"_point_repeat",
"_point_clamp",
"_point_mirror",
"_point_mirroronce",
"_trilinear_repeat",
"_trilinear_clamp",
"_trilinear_mirror",
"_trilinear_mirroronce"
};
// Would be better to dynamically parse the "C:\Program Files\UnityXXXX\Editor\Data\CGIncludes\" folder
// to get version specific includes but eh
public static readonly HashSet<string> DefaultUnityShaderIncludes = new HashSet<string>()
{
"UnityUI.cginc",
"AutoLight.cginc",
"GLSLSupport.glslinc",
"HLSLSupport.cginc",
"Lighting.cginc",
"SpeedTreeBillboardCommon.cginc",
"SpeedTreeCommon.cginc",
"SpeedTreeVertex.cginc",
"SpeedTreeWind.cginc",
"TerrainEngine.cginc",
"TerrainSplatmapCommon.cginc",
"Tessellation.cginc",
"UnityBuiltin2xTreeLibrary.cginc",
"UnityBuiltin3xTreeLibrary.cginc",
"UnityCG.cginc",
"UnityCG.glslinc",
"UnityCustomRenderTexture.cginc",
"UnityDeferredLibrary.cginc",
"UnityDeprecated.cginc",
"UnityGBuffer.cginc",
"UnityGlobalIllumination.cginc",
"UnityImageBasedLighting.cginc",
"UnityInstancing.cginc",
"UnityLightingCommon.cginc",
"UnityMetaPass.cginc",
"UnityPBSLighting.cginc",
"UnityShaderUtilities.cginc",
"UnityShaderVariables.cginc",
"UnityShadowLibrary.cginc",
"UnitySprites.cginc",
"UnityStandardBRDF.cginc",
"UnityStandardConfig.cginc",
"UnityStandardCore.cginc",
"UnityStandardCoreForward.cginc",
"UnityStandardCoreForwardSimple.cginc",
"UnityStandardInput.cginc",
"UnityStandardMeta.cginc",
"UnityStandardParticleInstancing.cginc",
"UnityStandardParticles.cginc",
"UnityStandardParticleShadow.cginc",
"UnityStandardShadow.cginc",
"UnityStandardUtils.cginc"
};
public static readonly HashSet<char> ValidSeparators = new HashSet<char>() { ' ', '\t', '\r', '\n', ';', ',', '.', '(', ')', '[', ']', '{', '}', '>', '<', '=', '!', '&', '|', '^', '+', '-', '*', '/', '#' };
public static readonly HashSet<string> DontRemoveIfBranchesKeywords = new HashSet<string>() { "UNITY_SINGLE_PASS_STEREO", "FORWARD_BASE_PASS", "FORWARD_ADD_PASS", "POINT", "SPOT" };
public static readonly HashSet<string> KeywordsUsedByPragmas = new HashSet<string>() { };
public static readonly string[] ValidPropertyDataTypes = new string[]
{
"float",
"float2",
"float3",
"float4",
"half",
"half2",
"half3",
"half4",
"fixed",
"fixed2",
"fixed3",
"fixed4"
};
public static readonly HashSet<string> IllegalPropertyRenames = new HashSet<string>()
{
"_MainTex",
"_Color",
"_EmissionColor",
"_BumpScale",
"_Cutoff",
"_DetailNormalMapScale",
"_DstBlend",
"_GlossMapScale",
"_Glossiness",
"_GlossyReflections",
"_Metallic",
"_Mode",
"_OcclusionStrength",
"_Parallax",
"_SmoothnessTextureChannel",
"_SpecularHighlights",
"_SrcBlend",
"_UVSec",
"_ZWrite"
};
public static readonly HashSet<string> PropertiesToSkipInMaterialEquallityComparission = new HashSet<string>
{
"shader_master_label",
"shader_is_using_thry_editor"
};
public enum PropertyType
{
Vector,
Float
}
public class PropertyData
{
public PropertyType type;
public string name;
public Vector4 value;
}
public class Macro
{
public string name;
public string[] args;
public string contents;
}
public class ParsedShaderFile
{
public string filePath;
public string[] lines;
}
public class TextureProperty
{
public string name;
public Texture texture;
public int uv;
public Vector2 scale;
public Vector2 offset;
}
public class GrabPassReplacement
{
public string originalName;
public string newName;
}
public static void CopyAnimatedTagToMaterials(Material[] targets, MaterialProperty source)
{
string val = (source.targets[0] as Material).GetTag(source.name + AnimatedTagSuffix, false, "");
foreach (Material m in targets)
{
m.SetOverrideTag(source.name+ AnimatedTagSuffix, val);
}
}
public static void CopyAnimatedTagFromMaterial(Material source, MaterialProperty target)
{
string val = source.GetTag(target.name + AnimatedTagSuffix, false, "");
foreach (Material m in target.targets)
{
m.SetOverrideTag(target.name + AnimatedTagSuffix, val);
}
}
public static void CopyAnimatedTagFromProperty(MaterialProperty source, MaterialProperty target)
{
string val = (source.targets[0] as Material).GetTag(source.name + AnimatedTagSuffix, false, "");
foreach (Material m in target.targets)
{
m.SetOverrideTag(target.name + AnimatedTagSuffix, val);
}
}
public static void SetAnimatedTag(MaterialProperty prop, string value)
{
foreach (Material m in prop.targets)
{
m.SetOverrideTag(prop.name + AnimatedTagSuffix, value);
}
}
public static string GetAnimatedTag(MaterialProperty prop)
{
return (prop.targets[0] as Material).GetTag(prop.name + AnimatedTagSuffix, false, "");
}
public static string GetAnimatedTag(Material m, string prop)
{
return m.GetTag(prop + AnimatedTagSuffix, false, "");
}
public static string GetRenamedPropertySuffix(Material m)
{
string cleanedMaterialName = Regex.Replace(m.name.Trim(), @"[^0-9a-zA-Z_]+", string.Empty);
if (Config.Singleton.allowCustomLockingRenaming)
return m.GetTag("thry_rename_suffix", false, cleanedMaterialName);
return cleanedMaterialName;
}
struct RenamingProperty
{
public MaterialProperty Prop;
public string Keyword;
public string Replace;
public RenamingProperty(MaterialProperty prop, string keyword, string replace)
{
this.Prop = prop;
this.Keyword = keyword;
this.Replace = replace;
}
}
private static bool Lock(Material material, MaterialProperty[] props, bool applyShaderLater = false)
{
// File filepaths and names
Shader shader = material.shader;
string shaderFilePath = AssetDatabase.GetAssetPath(shader);
string materialFilePath = AssetDatabase.GetAssetPath(material);
string materialFolder = Path.GetDirectoryName(materialFilePath);
string guid = AssetDatabase.AssetPathToGUID(materialFilePath);
string newShaderName = "Hidden/Locked/" + shader.name + "/" + guid;
//string newShaderDirectory = materialFolder + "/OptimizedShaders/" + material.name + "-" + smallguid + "/";
string newShaderDirectory = materialFolder + "/OptimizedShaders/" + material.name + "/";
// suffix for animated properties when renaming is enabled
string animPropertySuffix = GetRenamedPropertySuffix(material);
// Get collection of all properties to replace
// Simultaneously build a string of #defines for each CGPROGRAM
StringBuilder definesSB = new StringBuilder();
// Append convention OPTIMIZER_ENABLED keyword
definesSB.Append(Environment.NewLine);
definesSB.Append("#define ");
definesSB.Append(OptimizerEnabledKeyword);
definesSB.Append(Environment.NewLine);
// Append all keywords active on the material
foreach (string keyword in material.shaderKeywords)
{
if (keyword == "") continue; // idk why but null keywords exist if _ keyword is used and not removed by the editor at some point
definesSB.Append("#define ");
definesSB.Append(keyword);
definesSB.Append(Environment.NewLine);
}
KeywordsUsedByPragmas.Clear();
Dictionary<string,bool> removeBetweenKeywords = new Dictionary<string,bool>();
List<PropertyData> constantProps = new List<PropertyData>();
List<RenamingProperty> animatedPropsToRename = new List<RenamingProperty>();
List<RenamingProperty> animatedPropsToDuplicate = new List<RenamingProperty>();
foreach (MaterialProperty prop in props)
{
if (prop == null) continue;
if (prop.name.Contains("_commentIf"))
{
if (Regex.IsMatch(prop.name, @".*_commentIfOne_(\d|\w)+") && prop.floatValue == 1)
{
string key = Regex.Match(prop.name, @"_commentIfOne_(\d|\w)+").Value.Replace("_commentIfOne_", "");
removeBetweenKeywords.Add(key, false);
}
if (Regex.IsMatch(prop.name, @".*_commentIfZero_(\d|\w)+") && prop.floatValue == 0)
{
string key = Regex.Match(prop.name, @"_commentIfZero_(\d|\w)+").Value.Replace("_commentIfZero_", "");
removeBetweenKeywords.Add(key, false);
}
}
// Every property gets turned into a preprocessor variable
switch (prop.type)
{
case MaterialProperty.PropType.Float:
case MaterialProperty.PropType.Range:
definesSB.Append("#define PROP");
definesSB.Append(prop.name.ToUpperInvariant());
definesSB.Append(' ');
definesSB.Append(prop.floatValue.ToString(CultureInfo.InvariantCulture));
definesSB.Append(Environment.NewLine);
break;
case MaterialProperty.PropType.Texture:
if (prop.textureValue != null)
{
definesSB.Append("#define PROP");
definesSB.Append(prop.name.ToUpperInvariant());
definesSB.Append(Environment.NewLine);
}
break;
}
if (prop.name.EndsWith(AnimatedPropertySuffix, StringComparison.Ordinal)) continue;
else if (prop.name == UseInlineSamplerStatesPropertyName)
{
UseInlineSamplerStates = (prop.floatValue == 1);
continue;
}
else if (prop.name.StartsWith(GeometryShaderEnabledPropertyName, StringComparison.Ordinal))
{
if (prop.name == GeometryShaderEnabledPropertyName)
UseGeometry = (prop.floatValue == 1);
else if (prop.name == GeometryShaderEnabledPropertyName + "ForwardBase")
UseGeometryForwardBase = (prop.floatValue == 1);
else if (prop.name == GeometryShaderEnabledPropertyName + "ForwardAdd")
UseGeometryForwardAdd = (prop.floatValue == 1);
else if (prop.name == GeometryShaderEnabledPropertyName + "ShadowCaster")
UseGeometryShadowCaster = (prop.floatValue == 1);
else if (prop.name == GeometryShaderEnabledPropertyName + "Meta")
UseGeometryMeta = (prop.floatValue == 1);
}
else if (prop.name.StartsWith(TessellationEnabledPropertyName, StringComparison.Ordinal))
{
if (prop.name == TessellationEnabledPropertyName)
UseTessellation = (prop.floatValue == 1);
else if (prop.name == TessellationEnabledPropertyName + "ForwardBase")
UseTessellationForwardBase = (prop.floatValue == 1);
else if (prop.name == TessellationEnabledPropertyName + "ForwardAdd")
UseTessellationForwardAdd = (prop.floatValue == 1);
else if (prop.name == TessellationEnabledPropertyName + "ShadowCaster")
UseTessellationShadowCaster = (prop.floatValue == 1);
else if (prop.name == TessellationEnabledPropertyName + "Meta")
UseTessellationMeta = (prop.floatValue == 1);
}
string animateTag = material.GetTag(prop.name + AnimatedTagSuffix, false, "");
if(string.IsNullOrEmpty(animateTag) == false)
{
// check if we're renaming the property as well
if (animateTag == "2")
{
if (!prop.name.EndsWith("UV", StringComparison.Ordinal) && !prop.name.EndsWith("Pan", StringComparison.Ordinal)) // this property might be animated, but we're not allowed to rename it. this will break things.
{
if (IllegalPropertyRenames.Contains(prop.name))
animatedPropsToDuplicate.Add(new RenamingProperty(prop, prop.name, prop.name + "_" + animPropertySuffix));
else
animatedPropsToRename.Add(new RenamingProperty(prop, prop.name, prop.name + "_" + animPropertySuffix));
if (prop.type == MaterialProperty.PropType.Texture)
{
animatedPropsToRename.Add(new RenamingProperty(prop, prop.name + "_ST", prop.name + "_" + animPropertySuffix + "_ST"));
animatedPropsToRename.Add(new RenamingProperty(prop, prop.name + "_TexelSize", prop.name + "_" + animPropertySuffix + "_TexelSize"));
}
}
}
continue;
}
if (prop.displayName.EndsWith("NL", StringComparison.Ordinal)) continue;
PropertyData propData;
switch(prop.type)
{
case MaterialProperty.PropType.Color:
propData = new PropertyData();
propData.type = PropertyType.Vector;
propData.name = prop.name;
if ((prop.flags & MaterialProperty.PropFlags.HDR) != 0)
{
if ((prop.flags & MaterialProperty.PropFlags.Gamma) != 0)
propData.value = prop.colorValue.linear;
else propData.value = prop.colorValue;
}
else if ((prop.flags & MaterialProperty.PropFlags.Gamma) != 0)
propData.value = prop.colorValue;
else propData.value = prop.colorValue.linear;
if (PlayerSettings.colorSpace == ColorSpace.Gamma) propData.value = prop.colorValue;
constantProps.Add(propData);
break;
case MaterialProperty.PropType.Vector:
propData = new PropertyData();
propData.type = PropertyType.Vector;
propData.name = prop.name;
propData.value = prop.vectorValue;
constantProps.Add(propData);
break;
case MaterialProperty.PropType.Float:
case MaterialProperty.PropType.Range:
propData = new PropertyData();
propData.type = PropertyType.Float;
propData.name = prop.name;
propData.value = new Vector4(prop.floatValue, 0, 0, 0);
constantProps.Add(propData);
break;
case MaterialProperty.PropType.Texture:
PropertyData ST = new PropertyData();
ST.type = PropertyType.Vector;
ST.name = prop.name + "_ST";
Vector2 offset = material.GetTextureOffset(prop.name);
Vector2 scale = material.GetTextureScale(prop.name);
ST.value = new Vector4(scale.x, scale.y, offset.x, offset.y);
constantProps.Add(ST);
PropertyData TexelSize = new PropertyData();
TexelSize.type = PropertyType.Vector;
TexelSize.name = prop.name + "_TexelSize";
Texture t = prop.textureValue;
if (t != null)
TexelSize.value = new Vector4(1.0f / t.width, 1.0f / t.height, t.width, t.height);
else TexelSize.value = new Vector4(1.0f, 1.0f, 1.0f, 1.0f);
constantProps.Add(TexelSize);
break;
}
}
string optimizerDefines = definesSB.ToString();
// Get list of lightmode passes to delete
List<string> disabledLightModes = new List<string>();
var disabledLightModesProperty = Array.Find(props, x => x.name == DisabledLightModesPropertyName);
if (disabledLightModesProperty != null)
{
int lightModesMask = (int)disabledLightModesProperty.floatValue;
if ((lightModesMask & (int)LightMode.ForwardAdd) != 0)
disabledLightModes.Add("ForwardAdd");
if ((lightModesMask & (int)LightMode.ShadowCaster) != 0)
disabledLightModes.Add("ShadowCaster");
}
// Parse shader and cginc files, also gets preprocessor macros
List<ParsedShaderFile> shaderFiles = new List<ParsedShaderFile>();
List<Macro> macros = new List<Macro>();
if (!ParseShaderFilesRecursive(shaderFiles, newShaderDirectory, shaderFilePath, macros, material, removeBetweenKeywords))
return false;
int commentKeywords = 0;
List<GrabPassReplacement> grabPassVariables = new List<GrabPassReplacement>();
// Loop back through and do macros, props, and all other things line by line as to save string ops
// Will still be a massive n2 operation from each line * each property
foreach (ParsedShaderFile psf in shaderFiles)
{
// replace property names when prop is animated
for (int i = 0; i < psf.lines.Length; i++)
{
foreach (var animProp in animatedPropsToRename)
{
// don't have to match if that prop does not even exist in that line
if (psf.lines[i].Contains(animProp.Keyword))
{
string pattern = animProp.Keyword + @"(?!(\w|\d))";
psf.lines[i] = Regex.Replace(psf.lines[i], pattern, animProp.Replace, RegexOptions.Multiline);
}
}
foreach (var animProp in animatedPropsToDuplicate)
{
if (psf.lines[i].Contains(animProp.Keyword))
{
//if Line is property definition duplicate it
bool isDefinition = Regex.Match(psf.lines[i], animProp.Keyword + @"\s*\(""[^""]+""\s*,\s*\w+\)\s*=").Success;
string og = null;
if (isDefinition)
og = psf.lines[i];
string pattern = animProp.Keyword + @"(?!(\w|\d))";
psf.lines[i] = Regex.Replace(psf.lines[i], pattern, animProp.Replace, RegexOptions.Multiline);
if (isDefinition)
psf.lines[i] = og + "\r\n" + psf.lines[i];
}
}
}
// Shader file specific stuff
if (psf.filePath.EndsWith(".shader", StringComparison.Ordinal))
{
for (int i=0; i<psf.lines.Length;i++)
{
string trimmedLine = psf.lines[i].TrimStart();
if (trimmedLine.StartsWith("Shader", StringComparison.Ordinal))
{
string originalSgaderName = psf.lines[i].Split('\"')[1];
psf.lines[i] = psf.lines[i].Replace(originalSgaderName, newShaderName);
}
else if (trimmedLine.StartsWith("//#pragmamulti_compile_LOD_FADE_CROSSFADE", StringComparison.Ordinal))
{
MaterialProperty crossfadeProp = Array.Find(props, x => x.name == LODCrossFadePropertyName);
if (crossfadeProp != null && crossfadeProp.floatValue == 1)
psf.lines[i] = psf.lines[i].Replace("//#pragma", "#pragma");
}
else if (trimmedLine.StartsWith("//\"IgnoreProjector\"=\"True\"", StringComparison.Ordinal))
{
MaterialProperty projProp = Array.Find(props, x => x.name == IgnoreProjectorPropertyName);
if (projProp != null && projProp.floatValue == 1)
psf.lines[i] = psf.lines[i].Replace("//\"IgnoreProjector", "\"IgnoreProjector");
}
else if (trimmedLine.StartsWith("//\"ForceNoShadowCasting\"=\"True\"", StringComparison.Ordinal))
{
MaterialProperty forceNoShadowsProp = Array.Find(props, x => x.name == ForceNoShadowCastingPropertyName);
if (forceNoShadowsProp != null && forceNoShadowsProp.floatValue == 1)
psf.lines[i] = psf.lines[i].Replace("//\"ForceNoShadowCasting", "\"ForceNoShadowCasting");
}
else if (trimmedLine.StartsWith("GrabPass {", StringComparison.Ordinal))
{
GrabPassReplacement gpr = new GrabPassReplacement();
string[] splitLine = trimmedLine.Split('\"');
if (splitLine.Length == 1)
gpr.originalName = "_GrabTexture";
else
gpr.originalName = splitLine[1];
gpr.newName = material.GetTag("GrabPass" + grabPassVariables.Count, false, "_GrabTexture");
psf.lines[i] = "GrabPass { \"" + gpr.newName + "\" }";
grabPassVariables.Add(gpr);
}
else if (trimmedLine.StartsWith("CGINCLUDE", StringComparison.Ordinal))
{
for (int j=i+1; j<psf.lines.Length;j++)
if (psf.lines[j].TrimStart().StartsWith("ENDCG", StringComparison.Ordinal))
{
ReplaceShaderValues(material, psf.lines, i+1, j, props, constantProps, macros, grabPassVariables);
break;
}
}
else if (trimmedLine.StartsWith("CGPROGRAM", StringComparison.Ordinal))
{
if(commentKeywords == 0)
psf.lines[i] += optimizerDefines;
for (int j=i+1; j<psf.lines.Length;j++)
if (psf.lines[j].TrimStart().StartsWith("ENDCG", StringComparison.Ordinal))
{
ReplaceShaderValues(material, psf.lines, i+1, j, props, constantProps, macros, grabPassVariables);
break;
}
}
// Lightmode based pass removal, requires strict formatting
else if (trimmedLine.StartsWith("Tags", StringComparison.Ordinal))
{
string lineFullyTrimmed = trimmedLine.Replace(" ", "").Replace("\t", "");
// expects lightmode tag to be on the same line like: Tags { "LightMode" = "ForwardAdd" }
if (lineFullyTrimmed.Contains("\"LightMode\"=\""))
{
string lightModeName = lineFullyTrimmed.Split('\"')[3];
// Store current lightmode name in a static, useful for per-pass geometry and tessellation removal
if (lightModeName == "ForwardBase") CurrentLightmode = LightModeType.ForwardBase;
else if (lightModeName == "ForwardAdd") CurrentLightmode = LightModeType.ForwardAdd;
else if (lightModeName == "ShadowCaster") CurrentLightmode = LightModeType.ShadowCaster;
else if (lightModeName == "Meta") CurrentLightmode = LightModeType.Meta;
else CurrentLightmode = LightModeType.None;
if (disabledLightModes.Contains(lightModeName))
{
// Loop up from psf.lines[i] until standalone "Pass" line is found, delete it
int j=i-1;
for (;j>=0;j--)
if (psf.lines[j].Replace(" ", "").Replace("\t", "") == "Pass")
break;
// then delete each line until a standalone ENDCG line is found
for (;j<psf.lines.Length;j++)
{
if (psf.lines[j].Replace(" ", "").Replace("\t", "") == "ENDCG")
break;
psf.lines[j] = "";
}
// then delete each line until a standalone '}' line is found
for (;j<psf.lines.Length;j++)
{
string temp = psf.lines[j];
psf.lines[j] = "";
if (temp.Replace(" ", "").Replace("\t", "") == "}")
break;
}
}
}
}
}
}
else // CGINC file
ReplaceShaderValues(material, psf.lines, 0, psf.lines.Length, props, constantProps, macros, grabPassVariables);
// Recombine file lines into a single string
int totalLen = psf.lines.Length*2; // extra space for newline chars
foreach (string line in psf.lines)
totalLen += line.Length;
StringBuilder sb = new StringBuilder(totalLen);
// This appendLine function is incompatible with the '\n's that are being added elsewhere
foreach (string line in psf.lines)
sb.AppendLine(line);
string output = sb.ToString();
//cull shader file path
string fileName = Path.GetFileName(psf.filePath);
// Write output to file
(new FileInfo(newShaderDirectory + fileName)).Directory.Create();
try
{
StreamWriter sw = new StreamWriter(newShaderDirectory + fileName);
sw.Write(output);
sw.Close();
}
catch (IOException e)
{
Debug.LogError("[Shader Optimizer] Processed shader file " + newShaderDirectory + fileName + " could not be written. " + e.ToString());
return false;
}
}
AssetDatabase.Refresh();
ApplyStruct applyStruct = new ApplyStruct();
applyStruct.material = material;
applyStruct.shader = shader;
applyStruct.smallguid = guid;
applyStruct.newShaderName = newShaderName;
applyStruct.animatedPropsToRename = animatedPropsToRename;
applyStruct.animatedPropsToDuplicate = animatedPropsToDuplicate;
applyStruct.animPropertySuffix = animPropertySuffix;
if (applyShaderLater)
{
//Debug.Log("Apply later: "+applyStructsLater.Count+ ", "+material.name);
applyStructsLater[material] = applyStruct;
return true;
}
return LockApplyShader(applyStruct);
}
private static Dictionary<Material, ApplyStruct> applyStructsLater = new Dictionary<Material, ApplyStruct>();
private struct ApplyStruct
{
public Material material;
public Shader shader;
public string smallguid;
public string newShaderName;
public List<RenamingProperty> animatedPropsToRename;
public List<RenamingProperty> animatedPropsToDuplicate;
public string animPropertySuffix;
public bool shared;
}
private static bool LockApplyShader(Material material)
{
if (applyStructsLater.ContainsKey(material) == false) return false;
ApplyStruct applyStruct = applyStructsLater[material];
if (applyStruct.shared)
{
material.shader = applyStruct.material.shader;
return true;
}
//applyStructsLater.Remove(material);
return LockApplyShader(applyStruct);
}
private static bool LockApplyShader(ApplyStruct applyStruct)
{
Material material = applyStruct.material;
Shader shader = applyStruct.shader;
string newShaderName = applyStruct.newShaderName;
List<RenamingProperty> animatedPropsToRename = applyStruct.animatedPropsToRename;
List<RenamingProperty> animatedPropsToDuplicate = applyStruct.animatedPropsToDuplicate;
string animPropertySuffix = applyStruct.animPropertySuffix;
// Write original shader to override tag
material.SetOverrideTag("OriginalShader", shader.name);
// Write the new shader folder name in an override tag so it will be deleted
// For some reason when shaders are swapped on a material the RenderType override tag gets completely deleted and render queue set back to -1
// So these are saved as temp values and reassigned after switching shaders
string renderType = material.GetTag("RenderType", false, "");
int renderQueue = material.renderQueue;
// Actually switch the shader
Shader newShader = Shader.Find(newShaderName);
if (newShader == null)
{
Debug.LogError("[Shader Optimizer] Generated shader " + newShaderName + " could not be found");
return false;
}
material.shader = newShader;
//ShaderEditor.reload();
material.SetOverrideTag("RenderType", renderType);
material.renderQueue = renderQueue;
// Remove ALL keywords
foreach (string keyword in material.shaderKeywords)
if(material.IsKeywordEnabled(keyword)) material.DisableKeyword(keyword);
foreach (var animProp in animatedPropsToRename)
{
var newName = animProp.Prop.name + "_" + animPropertySuffix;
switch (animProp.Prop.type)
{
case MaterialProperty.PropType.Color:
material.SetColor(newName, animProp.Prop.colorValue);
break;
case MaterialProperty.PropType.Vector:
material.SetVector(newName, animProp.Prop.vectorValue);
break;
case MaterialProperty.PropType.Float:
material.SetFloat(newName, animProp.Prop.floatValue);
break;
case MaterialProperty.PropType.Range:
material.SetFloat(newName, animProp.Prop.floatValue);
break;
case MaterialProperty.PropType.Texture:
material.SetTexture(newName, animProp.Prop.textureValue);
material.SetTextureScale(newName, new Vector2(animProp.Prop.textureScaleAndOffset.x, animProp.Prop.textureScaleAndOffset.y));
material.SetTextureOffset(newName, new Vector2(animProp.Prop.textureScaleAndOffset.z, animProp.Prop.textureScaleAndOffset.w));
break;
default:
throw new ArgumentOutOfRangeException(nameof(material), "This property type should not be renamed and can not be set.");
}
}
foreach (var animProp in animatedPropsToDuplicate)
{
var newName = animProp.Prop.name + "_" + animPropertySuffix;
switch (animProp.Prop.type)
{
case MaterialProperty.PropType.Color:
material.SetColor(newName, animProp.Prop.colorValue);
break;
case MaterialProperty.PropType.Vector:
material.SetVector(newName, animProp.Prop.vectorValue);
break;
case MaterialProperty.PropType.Float:
material.SetFloat(newName, animProp.Prop.floatValue);
break;
case MaterialProperty.PropType.Range:
material.SetFloat(newName, animProp.Prop.floatValue);
break;
case MaterialProperty.PropType.Texture:
material.SetTexture(newName, animProp.Prop.textureValue);
material.SetTextureScale(newName, new Vector2(animProp.Prop.textureScaleAndOffset.x, animProp.Prop.textureScaleAndOffset.y));
material.SetTextureOffset(newName, new Vector2(animProp.Prop.textureScaleAndOffset.z, animProp.Prop.textureScaleAndOffset.w));
break;
default:
throw new ArgumentOutOfRangeException(nameof(material), "This property type should not be renamed and can not be set.");
}
}
return true;
}
/** <summary>Find longest common directoy</summary> */
public static int GetLongestCommonDirectoryLength(string[] s)
{
int k = s[0].Length;
for (int i = 1; i < s.Length; i++)
{
k = Math.Min(k, s[i].Length);
for (int j = 0; j < k; j++)
if ( AreCharsInPathEqual(s[i][j] , s[0][j]) == false)
{
k = j;
break;
}
}
string p = s[0].Substring(0, k);
if (Directory.Exists(p)) return p.Length;
else return Path.GetDirectoryName(p).Length;
}
private static bool AreCharsInPathEqual(char c1, char c2)
{
return (c1 == c2) || ((c1 == '/' || c1 == '\\') && (c2 == '/' || c2 == '\\'));
}
// Preprocess each file for macros and includes
// Save each file as string[], parse each macro with //KSOEvaluateMacro
// Only editing done is replacing #include "X" filepaths where necessary
// most of these args could be private static members of the class
private static bool ParseShaderFilesRecursive(List<ParsedShaderFile> filesParsed, string newTopLevelDirectory, string filePath, List<Macro> macros, Material material, Dictionary<string,bool> removeBetweenKeywords)
{
// Infinite recursion check
if (filesParsed.Exists(x => x.filePath == filePath)) return true;
ParsedShaderFile psf = new ParsedShaderFile();
psf.filePath = filePath;
filesParsed.Add(psf);
// Read file
string fileContents = null;
try
{
StreamReader sr = new StreamReader(filePath);
fileContents = sr.ReadToEnd();
sr.Close();
}
catch (FileNotFoundException e)
{
Debug.LogError("[Shader Optimizer] Shader file " + filePath + " not found. " + e.ToString());
return false;
}
catch (IOException e)
{
Debug.LogError("[Shader Optimizer] Error reading shader file. " + e.ToString());
return false;
}
// Parse file line by line
List<String> macrosList = new List<string>();
string[] fileLines = fileContents.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
List<string> includedLines = new List<string>();
bool isIncluded = true;
int isNotIncludedAtDepth = 0;
int ifStacking = 0;
Stack<bool> removeEndifStack = new Stack<bool>();
bool isCommentedOut = false;
int removedViaKeyword = 0;
for (int i=0; i<fileLines.Length; i++)
{
string lineParsed = fileLines[i].TrimStart();
//Remove stuff between comment keywords
string trimmedForKeyword = lineParsed.TrimStart('/').TrimEnd();
if (removeBetweenKeywords.ContainsKey(trimmedForKeyword))
{
removeBetweenKeywords[trimmedForKeyword] = !removeBetweenKeywords[trimmedForKeyword];
if (removeBetweenKeywords[trimmedForKeyword])
removedViaKeyword++;
else
removedViaKeyword--;
}
if (removedViaKeyword > 0) continue;
//removes empty lines
if (lineParsed.Length == 0) continue;
//removes code that is commented
if (lineParsed== "*/")
{
isCommentedOut = false;
continue;
}
else if (lineParsed == "/*")
{
isCommentedOut = true;
continue;
}
else if (lineParsed.StartsWith("//", StringComparison.Ordinal))
{
continue;
}
if (isCommentedOut) continue;
//Removed code from defines blocks
if (REMOVE_UNUSED_IF_DEFS)
{
//Check if Line contains #ifs
if (lineParsed.StartsWith("#if", StringComparison.Ordinal))
{
bool hasMultiple = lineParsed.Contains('&') || lineParsed.Contains('|');
if (!hasMultiple && lineParsed.StartsWith("#ifdef", StringComparison.Ordinal))
{
string keyword = lineParsed.Substring(6).Trim().Split(' ')[0];
bool allowRemoveal = (DontRemoveIfBranchesKeywords.Contains(keyword) == false) && KeywordsUsedByPragmas.Contains(keyword);
bool isRemoved = false;
if (isIncluded && allowRemoveal)
{
if ((material.IsKeywordEnabled(keyword) == false))
{
isIncluded = false;
isNotIncludedAtDepth = ifStacking;
isRemoved = true;
}
}
ifStacking++;
removeEndifStack.Push(isRemoved);
if (isRemoved) continue;
}
else if (!hasMultiple && lineParsed.StartsWith("#ifndef", StringComparison.Ordinal))
{
string keyword = lineParsed.Substring(7).Trim().Split(' ')[0];
bool allowRemoveal = DontRemoveIfBranchesKeywords.Contains(keyword) == false && KeywordsUsedByPragmas.Contains(keyword);
bool isRemoved = false;
if (isIncluded && allowRemoveal)
{
if (material.IsKeywordEnabled(keyword) == true)
{
isIncluded = false;
isNotIncludedAtDepth = ifStacking;
isRemoved = true;
}
}
ifStacking++;
removeEndifStack.Push(isRemoved);
if (isRemoved) continue;
}
else
{
ifStacking++;
removeEndifStack.Push(false);
}
}
else if (lineParsed.StartsWith("#else"))
{
if (isIncluded && removeEndifStack.Peek()) isIncluded = false;
if (!isIncluded && ifStacking - 1 == isNotIncludedAtDepth) isIncluded = true;
if (removeEndifStack.Peek()) continue;
}
else if (lineParsed.StartsWith("#endif", StringComparison.Ordinal))
{
ifStacking--;
if (ifStacking == isNotIncludedAtDepth)
{
isIncluded = true;
}
if (removeEndifStack.Pop()) continue;
}
if (!isIncluded) continue;
}
//Remove pragmas
if (lineParsed.StartsWith("#pragma shader_feature", StringComparison.Ordinal))
{
string keyword = lineParsed.Split(' ')[2];
if (KeywordsUsedByPragmas.Contains(keyword) == false) KeywordsUsedByPragmas.Add(keyword);
continue;
}
// Specifically requires no whitespace between # and include, as it should be
if (lineParsed.StartsWith("#include", StringComparison.Ordinal))
{
int firstQuotation = lineParsed.IndexOf('\"',0);
int lastQuotation = lineParsed.IndexOf('\"',firstQuotation+1);
string includeFilename = lineParsed.Substring(firstQuotation+1, lastQuotation-firstQuotation-1);
// Skip default includes
if (DefaultUnityShaderIncludes.Contains(includeFilename) == false)
{
string includeFullpath = includeFilename;
if (includeFilename.StartsWith("Assets/", StringComparison.Ordinal) == false)//not absolute
{
includeFullpath = GetFullPath(includeFilename, Path.GetDirectoryName(filePath));
}
if (!ParseShaderFilesRecursive(filesParsed, newTopLevelDirectory, includeFullpath, macros, material, removeBetweenKeywords))
return false;
//Change include to be be ralative to only one directory up, because all files are moved into the same folder
fileLines[i] = fileLines[i].Replace(includeFilename, "/"+includeFilename.Split('/').Last());
}
}
// Specifically requires no whitespace between // and KSOEvaluateMacro
else if (lineParsed == "//KSOEvaluateMacro")
{
string macro = "";
string lineTrimmed = null;
do
{
i++;
lineTrimmed = fileLines[i].TrimEnd();
if (lineTrimmed.EndsWith("\\", StringComparison.Ordinal))
macro += lineTrimmed.TrimEnd('\\') + Environment.NewLine; // keep new lines in macro to make output more readable
else macro += lineTrimmed;
}
while (lineTrimmed.EndsWith("\\", StringComparison.Ordinal));
macrosList.Add(macro);
}
includedLines.Add(fileLines[i]);
}
// Prepare the macros list into pattern matchable structs
// Revise this later to not do so many string ops
foreach (string macroString in macrosList)
{
string m = macroString;
Macro macro = new Macro();
m = m.TrimStart();
if (m[0] != '#') continue;
m = m.Remove(0, "#".Length).TrimStart();
if (!m.StartsWith("define", StringComparison.Ordinal)) continue;
m = m.Remove(0, "define".Length).TrimStart();
int firstParenthesis = m.IndexOf('(');
macro.name = m.Substring(0, firstParenthesis);
m = m.Remove(0, firstParenthesis + "(".Length);
int lastParenthesis = m.IndexOf(')');
string allArgs = m.Substring(0, lastParenthesis).Remove(' ').Remove('\t');
macro.args = allArgs.Split(',');
m = m.Remove(0, lastParenthesis + ")".Length);
macro.contents = m;
macros.Add(macro);
}
// Save psf lines to list
psf.lines = includedLines.ToArray();
return true;
}
// error CS1501: No overload for method 'Path.GetFullPath' takes 2 arguments
// Thanks Unity
// Could be made more efficent with stringbuilder
public static string GetFullPath(string relativePath, string basePath)
{
while (relativePath.StartsWith("./"))
relativePath = relativePath.Remove(0, "./".Length);
while (relativePath.StartsWith("../"))
{
basePath = basePath.Remove(basePath.LastIndexOf(Path.DirectorySeparatorChar), basePath.Length - basePath.LastIndexOf(Path.DirectorySeparatorChar));
relativePath = relativePath.Remove(0, "../".Length);
}
return basePath + '/' + relativePath;
}
// Replace properties! The meat of the shader optimization process
// For each constantProp, pattern match and find each instance of the property that isn't a declaration
// most of these args could be private static members of the class
private static void ReplaceShaderValues(Material material, string[] lines, int startLine, int endLine,
MaterialProperty[] props, List<PropertyData> constants, List<Macro> macros, List<GrabPassReplacement> grabPassVariables)
{
List <TextureProperty> uniqueSampledTextures = new List<TextureProperty>();
// Outside loop is each line
for (int i=startLine;i<endLine;i++)
{
string lineTrimmed = lines[i].TrimStart();
if (lineTrimmed.StartsWith("#pragma geometry", StringComparison.Ordinal))
{
if (!UseGeometry)
lines[i] = "//" + lines[i];
else
{
switch (CurrentLightmode)
{
case LightModeType.ForwardBase:
if (!UseGeometryForwardBase)
lines[i] = "//" + lines[i];
break;
case LightModeType.ForwardAdd:
if (!UseGeometryForwardAdd)
lines[i] = "//" + lines[i];
break;
case LightModeType.ShadowCaster:
if (!UseGeometryShadowCaster)
lines[i] = "//" + lines[i];
break;
case LightModeType.Meta:
if (!UseGeometryMeta)
lines[i] = "//" + lines[i];
break;
}
}
}
else if (lineTrimmed.StartsWith("#pragma hull", StringComparison.Ordinal) || lineTrimmed.StartsWith("#pragma domain", StringComparison.Ordinal))
{
if (!UseTessellation)
lines[i] = "//" + lines[i];
else
{
switch (CurrentLightmode)
{
case LightModeType.ForwardBase:
if (!UseTessellationForwardBase)
lines[i] = "//" + lines[i];
break;
case LightModeType.ForwardAdd:
if (!UseTessellationForwardAdd)
lines[i] = "//" + lines[i];
break;
case LightModeType.ShadowCaster:
if (!UseTessellationShadowCaster)
lines[i] = "//" + lines[i];
break;
case LightModeType.Meta:
if (!UseTessellationMeta)
lines[i] = "//" + lines[i];
break;
}
}
}
// Replace inline smapler states
else if (UseInlineSamplerStates && lineTrimmed.StartsWith("//KSOInlineSamplerState", StringComparison.Ordinal))
{
string lineParsed = lineTrimmed.Remove(' ').Remove('\t');
// Remove all whitespace
int firstParenthesis = lineParsed.IndexOf('(');
int lastParenthesis = lineParsed.IndexOf(')');
string argsString = lineParsed.Substring(firstParenthesis+1, lastParenthesis - firstParenthesis-1);
string[] args = argsString.Split(',');
MaterialProperty texProp = Array.Find(props, x => x.name == args[1]);
if (texProp != null)
{
Texture t = texProp.textureValue;
int inlineSamplerIndex = 0;
if (t != null)
{
switch (t.filterMode)
{
case FilterMode.Bilinear:
break;
case FilterMode.Point:
inlineSamplerIndex += 1 * 4;
break;
case FilterMode.Trilinear:
inlineSamplerIndex += 2 * 4;
break;
}
switch (t.wrapMode)
{
case TextureWrapMode.Repeat:
break;
case TextureWrapMode.Clamp:
inlineSamplerIndex += 1;
break;
case TextureWrapMode.Mirror:
inlineSamplerIndex += 2;
break;
case TextureWrapMode.MirrorOnce:
inlineSamplerIndex += 3;
break;
}
}
// Replace the token on the following line
lines[i+1] = lines[i+1].Replace(args[0], InlineSamplerStateNames[inlineSamplerIndex]);
}
}
else if (lineTrimmed.StartsWith("//KSODuplicateTextureCheckStart", StringComparison.Ordinal))
{
// Since files are not fully parsed and instead loosely processed, each shader function needs to have
// its sampled texture list reset somewhere before KSODuplicateTextureChecks are made.
// As long as textures are sampled in-order inside a single function, this method will work.
uniqueSampledTextures = new List<TextureProperty>();
}
else if (lineTrimmed.StartsWith("//KSODuplicateTextureCheck", StringComparison.Ordinal))
{
// Each KSODuplicateTextureCheck line gets evaluated when the shader is optimized
// If the texture given has already been sampled as another texture (i.e. one texture is used in two slots)
// AND has been sampled with the same UV mode - as indicated by a convention UV property,
// AND has been sampled with the exact same Tiling/Offset values
// AND has been logged by KSODuplicateTextureCheck,
// then the variable corresponding to the first instance of that texture being
// sampled will be assigned to the variable corresponding to the given texture.
// The compiler will then skip the duplicate texture sample since its variable is overwritten before being used
// Parse line for argument texture property name
string lineParsed = lineTrimmed.Replace(" ", "").Replace("\t", "");
int firstParenthesis = lineParsed.IndexOf('(');
int lastParenthesis = lineParsed.IndexOf(')');
string argName = lineParsed.Substring(firstParenthesis+1, lastParenthesis-firstParenthesis-1);
// Check if texture property by argument name exists and has a texture assigned
if (Array.Exists(props, x => x.name == argName))
{
MaterialProperty argProp = Array.Find(props, x => x.name == argName);
if (argProp.textureValue != null)
{
// If no convention UV property exists, sampled UV mode is assumed to be 0
// Any UV enum or mode indicator can be used for this
int UV = 0;
if (Array.Exists(props, x => x.name == argName + "UV"))
UV = (int)(Array.Find(props, x => x.name == argName + "UV").floatValue);
Vector2 texScale = material.GetTextureScale(argName);
Vector2 texOffset = material.GetTextureOffset(argName);
// Check if this texture has already been sampled
if (uniqueSampledTextures.Exists(x => (x.texture == argProp.textureValue)
&& (x.uv == UV)
&& (x.scale == texScale)
&& x.offset == texOffset))
{
string texName = uniqueSampledTextures.Find(x => (x.texture == argProp.textureValue) && (x.uv == UV)).name;
// convention _var variables requried. i.e. _MainTex_var and _CoverageMap_var
lines[i] = argName + "_var = " + texName + "_var;";
}
else
{
// Texture/UV/ST combo hasn't been sampled yet, add it to the list
TextureProperty tp = new TextureProperty();
tp.name = argName;
tp.texture = argProp.textureValue;
tp.uv = UV;
tp.scale = texScale;
tp.offset = texOffset;
uniqueSampledTextures.Add(tp);
}
}
}
}
else if (lineTrimmed.StartsWith("[maxtessfactor(", StringComparison.Ordinal))
{
MaterialProperty maxTessFactorProperty = Array.Find(props, x => x.name == TessellationMaxFactorPropertyName);
if (maxTessFactorProperty != null)
{
float maxTessellation = maxTessFactorProperty.floatValue;
string animateTag = material.GetTag(TessellationMaxFactorPropertyName + AnimatedTagSuffix, false, "0");
if (animateTag != "" && animateTag == "1")
maxTessellation = 64.0f;
lines[i] = "[maxtessfactor(" + maxTessellation.ToString(".0######") + ")]";
}
}
// then replace macros
foreach (Macro macro in macros)
{
// Expects only one instance of a macro per line!
int macroIndex;
if ((macroIndex = lines[i].IndexOf(macro.name + "(", StringComparison.Ordinal)) != -1)
{
// Macro exists on this line, make sure its not the definition
string lineParsed = lineTrimmed.Remove(' ').Remove('\t');
if (lineParsed.StartsWith("#define", StringComparison.Ordinal)) continue;
// parse args between first '(' and first ')'
int firstParenthesis = macroIndex + macro.name.Length;
int lastParenthesis = lines[i].IndexOf(')', macroIndex + macro.name.Length+1);
string allArgs = lines[i].Substring(firstParenthesis+1, lastParenthesis-firstParenthesis-1);
string[] args = allArgs.Split(',');
// Replace macro parts
string newContents = macro.contents;
for (int j=0; j<args.Length;j++)
{
args[j] = args[j].Trim();
int argIndex;
int lastIndex = 0;
while ((argIndex = newContents.IndexOf(macro.args[j], lastIndex, StringComparison.Ordinal)) != -1)
{
lastIndex = argIndex+1;
char charLeft = ' ';
if (argIndex-1 >= 0)
charLeft = newContents[argIndex-1];
char charRight = ' ';
if (argIndex+macro.args[j].Length < newContents.Length)
charRight = newContents[argIndex+macro.args[j].Length];
if (ValidSeparators.Contains(charLeft) && ValidSeparators.Contains(charRight))
{
// Replcae the arg!
StringBuilder sbm = new StringBuilder(newContents.Length - macro.args[j].Length + args[j].Length);
sbm.Append(newContents, 0, argIndex);
sbm.Append(args[j]);
sbm.Append(newContents, argIndex + macro.args[j].Length, newContents.Length - argIndex - macro.args[j].Length);
newContents = sbm.ToString();
}
}
}
newContents = newContents.Replace("##", ""); // Remove token pasting separators
// Replace the line with the evaluated macro
StringBuilder sb = new StringBuilder(lines[i].Length + newContents.Length);
sb.Append(lines[i], 0, macroIndex);
sb.Append(newContents);
sb.Append(lines[i], lastParenthesis+1, lines[i].Length - lastParenthesis-1);
lines[i] = sb.ToString();
}
}
// then replace properties
foreach (PropertyData constant in constants)
{
int constantIndex;
int lastIndex = 0;
bool declarationFound = false;
while ((constantIndex = lines[i].IndexOf(constant.name, lastIndex, StringComparison.Ordinal)) != -1)
{
lastIndex = constantIndex+1;
char charLeft = ' ';
if (constantIndex-1 >= 0)
charLeft = lines[i][constantIndex-1];
char charRight = ' ';
if (constantIndex + constant.name.Length < lines[i].Length)
charRight = lines[i][constantIndex + constant.name.Length];
// Skip invalid matches (probably a subname of another symbol)
if (!(ValidSeparators.Contains(charLeft) && ValidSeparators.Contains(charRight)))
continue;
// Skip basic declarations of unity shader properties i.e. "uniform float4 _Color;"
if (!declarationFound)
{
string precedingText = lines[i].Substring(0, constantIndex-1).TrimEnd(); // whitespace removed string immediately to the left should be float or float4
string restOftheFile = lines[i].Substring(constantIndex + constant.name.Length).TrimStart(); // whitespace removed character immediately to the right should be ;
if (Array.Exists(ValidPropertyDataTypes, x => precedingText.EndsWith(x, StringComparison.Ordinal)) && restOftheFile.StartsWith(";", StringComparison.Ordinal))
{
declarationFound = true;
continue;
}
}
// Replace with constant!
// This could technically be more efficient by being outside the IndexOf loop
StringBuilder sb = new StringBuilder(lines[i].Length * 2);
sb.Append(lines[i], 0, constantIndex);
switch (constant.type)
{
case PropertyType.Float:
sb.Append("float(" + constant.value.x.ToString(CultureInfo.InvariantCulture) + ")");
break;
case PropertyType.Vector:
sb.Append("float4("+constant.value.x.ToString(CultureInfo.InvariantCulture)+","
+constant.value.y.ToString(CultureInfo.InvariantCulture)+","
+constant.value.z.ToString(CultureInfo.InvariantCulture)+","
+constant.value.w.ToString(CultureInfo.InvariantCulture)+")");
break;
}
sb.Append(lines[i], constantIndex+constant.name.Length, lines[i].Length-constantIndex-constant.name.Length);
lines[i] = sb.ToString();
// Check for Unity branches on previous line here?
}
}
// Then replace grabpass variable names
foreach (GrabPassReplacement gpr in grabPassVariables)
{
// find indexes of all instances of gpr.originalName that exist on this line
int lastIndex = 0;
int gbIndex;
while ((gbIndex = lines[i].IndexOf(gpr.originalName, lastIndex, StringComparison.Ordinal)) != -1)
{
lastIndex = gbIndex+1;
char charLeft = ' ';
if (gbIndex-1 >= 0)
charLeft = lines[i][gbIndex-1];
char charRight = ' ';
if (gbIndex + gpr.originalName.Length < lines[i].Length)
charRight = lines[i][gbIndex + gpr.originalName.Length];
// Skip invalid matches (probably a subname of another symbol)
if (!(ValidSeparators.Contains(charLeft) && ValidSeparators.Contains(charRight)))
continue;
// Replace with new variable name
// This could technically be more efficient by being outside the IndexOf loop
StringBuilder sb = new StringBuilder(lines[i].Length * 2);
sb.Append(lines[i], 0, gbIndex);
sb.Append(gpr.newName);
sb.Append(lines[i], gbIndex+gpr.originalName.Length, lines[i].Length-gbIndex-gpr.originalName.Length);
lines[i] = sb.ToString();
}
}
// Then remove Unity branches
if (RemoveUnityBranches)
lines[i] = lines[i].Replace("UNITY_BRANCH", "").Replace("[branch]", "");
}
}
public enum UnlockSuccess { hasNoSavedShader, wasNotLocked, couldNotFindOriginalShader, couldNotDeleteLockedShader,
success}
private static void Unlock(Material material, MaterialProperty shaderOptimizer = null)
{
//if unlock success set floats. not done for locking cause the sucess is checked later when applying the shaders
UnlockSuccess success = ShaderOptimizer.UnlockConcrete(material);
if (success == UnlockSuccess.success || success == UnlockSuccess.wasNotLocked
|| success == UnlockSuccess.couldNotDeleteLockedShader)
{
if (shaderOptimizer != null) shaderOptimizer.floatValue = 0;
else material.SetFloat(GetOptimizerPropertyName(material.shader), 0);
}
}
private static UnlockSuccess UnlockConcrete (Material material)
{
Shader lockedShader = material.shader;
// Revert to original shader
string originalShaderName = material.GetTag("OriginalShader", false, "");
if (originalShaderName == "")
{
if (material.shader.name.StartsWith("Hidden/"))
{
Debug.LogError("[Shader Optimizer] Original shader not saved to material, could not unlock shader");
return UnlockSuccess.hasNoSavedShader;
}
else
{
Debug.LogWarning("[Shader Optimizer] Original shader not saved to material, but material also doesnt seem to be locked.");
return UnlockSuccess.wasNotLocked;
}
}
Shader orignalShader = Shader.Find(originalShaderName);
if (orignalShader == null)
{
if (material.shader.name.StartsWith("Hidden/"))
{
Debug.LogError("[Shader Optimizer] Original shader " + originalShaderName + " could not be found");
return UnlockSuccess.couldNotFindOriginalShader;
}
else
{
Debug.LogWarning("[Shader Optimizer] Original shader not saved to material, but material also doesnt seem to be locked.");
return UnlockSuccess.wasNotLocked;
}
}
// For some reason when shaders are swapped on a material the RenderType override tag gets completely deleted and render queue set back to -1
// So these are saved as temp values and reassigned after switching shaders
string renderType = material.GetTag("RenderType", false, "");
int renderQueue = material.renderQueue;
material.shader = orignalShader;
material.SetOverrideTag("RenderType", renderType);
material.renderQueue = renderQueue;
// Delete the variants folder and all files in it, as to not orhpan files and inflate Unity project
bool isOtherShaderUsingLockedShader = AssetDatabase.FindAssets("t:material").Select(g => AssetDatabase.LoadAssetAtPath<Material>(AssetDatabase.GUIDToAssetPath(g))).
Any(m => m.shader == lockedShader && m != material);
if (!isOtherShaderUsingLockedShader)
{
string materialFilePath = AssetDatabase.GetAssetPath(lockedShader);
string lockedFolder = Path.GetDirectoryName(materialFilePath);
FileUtil.DeleteFileOrDirectory(lockedFolder);
FileUtil.DeleteFileOrDirectory(lockedFolder + ".meta");
}
//AssetDatabase.Refresh();
return UnlockSuccess.success;
}
public static void DeleteTags(Material[] materials)
{
foreach(Material m in materials)
{
var it = new SerializedObject(m).GetIterator();
while (it.Next(true))
{
if (it.name == "stringTagMap")
{
for (int i = 0; i < it.arraySize; i++)
{
string tagName = it.GetArrayElementAtIndex(i).displayName;
if (tagName.EndsWith(AnimatedTagSuffix))
{
m.SetOverrideTag(tagName, "");
}
}
}
}
}
}
#region Upgrade
public static void UpgradeAnimatedPropertiesToTagsOnAllMaterials()
{
IEnumerable<Material> materials = Resources.FindObjectsOfTypeAll<Material>();
UpgradeAnimatedPropertiesToTags(materials);
Debug.Log("[Thry][Optimizer] Update animated properties of all materials to tags.");
}
public static void UpgradeAnimatedPropertiesToTags(IEnumerable<Material> iMaterials)
{
IEnumerable<Material> materialsToChange = iMaterials.Where(m => m != null &&
string.IsNullOrEmpty(AssetDatabase.GetAssetPath(m)) == false && string.IsNullOrEmpty(AssetDatabase.GetAssetPath(m.shader)) == false
&& IsShaderUsingThryOptimizer(m.shader)).Distinct().OrderBy(m => m.shader.name);
int i = 0;
foreach (Material m in materialsToChange)
{
if(EditorUtility.DisplayCancelableProgressBar("Upgrading Materials", "Upgrading animated tags of " + m.name, (float)i / materialsToChange.Count()))
{
break;
}
string path = AssetDatabase.GetAssetPath(m);
StreamReader reader = new StreamReader(path);
string line;
while((line = reader.ReadLine()) != null)
{
if (line.Contains(AnimatedPropertySuffix) && line.Length > 6)
{
string[] parts = line.Substring(6, line.Length - 6).Split(':');
float f;
if (float.TryParse(parts[1], out f))
{
if( f != 0)
{
string name = parts[0].Substring(0, parts[0].Length - AnimatedPropertySuffix.Length);
m.SetOverrideTag(name + AnimatedTagSuffix, "" + f);
}
}
}
}
reader.Close();
i++;
}
EditorUtility.ClearProgressBar();
}
static void ClearConsole()
{
var logEntries = System.Type.GetType("UnityEditor.LogEntries, UnityEditor.dll");
var clearMethod = logEntries.GetMethod("Clear", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
clearMethod.Invoke(null, null);
}
#endregion
//---GameObject + Children Locking
[MenuItem("GameObject/Thry/Materials/Unlock All", false,0)]
static void UnlockAllChildren()
{
SetLockForAllChildren(Selection.gameObjects, 0, true);
}
[MenuItem("GameObject/Thry/Materials/Lock All", false,0)]
static void LockAllChildren()
{
SetLockForAllChildren(Selection.gameObjects, 1, true);
}
//---Asset Unlocking
[MenuItem("Assets/Thry/Materials/Unlock All", false, 303)]
static void UnlockAllMaterials()
{
IEnumerable<Material> mats = Selection.assetGUIDs.Select(g => AssetDatabase.LoadAssetAtPath<Material>(AssetDatabase.GUIDToAssetPath(g)));
SetLockedForAllMaterials(mats, 0, true);
}
[MenuItem("Assets/Thry/Materials/Unlock All", true)]
static bool UnlockAllMaterialsValidator()
{
return SelectedObjectsAreLockableMaterials();
}
//---Asset Locking
[MenuItem("Assets/Thry/Materials/Lock All", false, 303)]
static void LockAllMaterials()
{
IEnumerable<Material> mats = Selection.assetGUIDs.Select(g => AssetDatabase.LoadAssetAtPath<Material>(AssetDatabase.GUIDToAssetPath(g)));
SetLockedForAllMaterials(mats, 1, true);
}
[MenuItem("Assets/Thry/Materials/Lock All", true)]
static bool LockAllMaterialsValidator()
{
return SelectedObjectsAreLockableMaterials();
}
//----Folder Lock
//This does not work for folders on the left side of the project explorer, because they are not exposed to Selection
[MenuItem("Assets/Thry/Materials/Lock Folder", false, 303)]
static void LockFolder()
{
IEnumerable<string> folderPaths = Selection.objects.Select(o => AssetDatabase.GetAssetPath(o)).Where(p => Directory.Exists(p));
List<Material> materials = new List<Material>();
foreach (string f in folderPaths) FindMaterialsRecursive(f, materials);
SetLockedForAllMaterials(materials, 1, true);
}
[MenuItem("Assets/Thry/Materials/Lock Folder", true)]
static bool LockFolderValidator()
{
return Selection.objects.Select(o => AssetDatabase.GetAssetPath(o)).Where(p => Directory.Exists(p)).Count() == Selection.objects.Length;
}
//-----Folder Unlock
[MenuItem("Assets/Thry/Materials/Unlock Folder", false, 303)]
static void UnLockFolder()
{
IEnumerable<string> folderPaths = Selection.objects.Select(o => AssetDatabase.GetAssetPath(o)).Where(p => Directory.Exists(p));
List<Material> materials = new List<Material>();
foreach (string f in folderPaths) FindMaterialsRecursive(f, materials);
SetLockedForAllMaterials(materials, 0, true);
}
[MenuItem("Assets/Thry/Materials/Unlock Folder", true)]
static bool UnLockFolderValidator()
{
return Selection.objects.Select(o => AssetDatabase.GetAssetPath(o)).Where(p => Directory.Exists(p)).Count() == Selection.objects.Length;
}
private static void FindMaterialsRecursive(string folderPath, List<Material> materials)
{
foreach(string f in Directory.GetFiles(folderPath))
{
if(AssetDatabase.GetMainAssetTypeAtPath(f) == typeof(Material))
{
materials.Add(AssetDatabase.LoadAssetAtPath<Material>(f));
}
}
foreach(string f in Directory.GetDirectories(folderPath)){
FindMaterialsRecursive(f, materials);
}
}
//----Folder Unlock
static bool SelectedObjectsAreLockableMaterials()
{
if (Selection.assetGUIDs != null && Selection.assetGUIDs.Length > 0)
{
return Selection.assetGUIDs.All(g =>
{
if (AssetDatabase.GetMainAssetTypeAtPath(AssetDatabase.GUIDToAssetPath(g)) != typeof(Material))
return false;
Material m = AssetDatabase.LoadAssetAtPath<Material>(AssetDatabase.GUIDToAssetPath(g));
return IsShaderUsingThryOptimizer(m.shader);
});
}
return false;
}
//----VRChat Callback to force Locking on upload
#if VRC_SDK_VRCSDK2 || VRC_SDK_VRCSDK3
public class LockMaterialsOnUpload : IVRCSDKPreprocessAvatarCallback
{
public int callbackOrder => 100;
public bool OnPreprocessAvatar(GameObject avatarGameObject)
{
List<Material> materials = avatarGameObject.GetComponentsInChildren<Renderer>(true).SelectMany(r => r.sharedMaterials).ToList();
#if VRC_SDK_VRCSDK3 && !UDON
VRCAvatarDescriptor descriptor = avatarGameObject.GetComponent<VRCAvatarDescriptor>();
if(descriptor != null)
{
IEnumerable<AnimationClip> clips = descriptor.baseAnimationLayers.Select(l => l.animatorController).Where(a => a != null).SelectMany(a => a.animationClips).Distinct();
foreach (AnimationClip clip in clips)
{
IEnumerable<Material> clipMaterials = AnimationUtility.GetObjectReferenceCurveBindings(clip).Where(b => b.isPPtrCurve && b.type.IsSubclassOf(typeof(Renderer)) && b.propertyName.StartsWith("m_Materials"))
.SelectMany(b => AnimationUtility.GetObjectReferenceCurve(clip, b)).Select(r => r.value as Material);
materials.AddRange(clipMaterials);
}
}
#endif
SetLockedForAllMaterials(materials, 1, showProgressbar: true, showDialog: PersistentData.Get<bool>("ShowLockInDialog", true), allowCancel: false);
//returning true all the time, because build process cant be stopped it seems
return true;
}
}
#endif
#if VRC_SDK_VRCSDK2 || VRC_SDK_VRCSDK3
public class LockMaterialsOnWorldUpload : IVRCSDKBuildRequestedCallback
{
public int callbackOrder => 100;
bool IVRCSDKBuildRequestedCallback.OnBuildRequested(VRCSDKRequestedBuildType requestedBuildType)
{
List<Material> materials = new List<Material>();
if (requestedBuildType == VRCSDKRequestedBuildType.Scene)
{
if (UnityEngine.Object.FindObjectsOfType(typeof(VRC_SceneDescriptor)) is VRC_SceneDescriptor[] descriptors && descriptors.Length > 0){
var renderers = UnityEngine.Object.FindObjectsOfType<Renderer>();
foreach (var rend in renderers)
{
foreach (var mat in rend.sharedMaterials){
materials.Add(mat);
}
}
}
SetLockedForAllMaterials(materials, 1, showProgressbar: true, showDialog: PersistentData.Get<bool>("ShowLockInDialog", true), allowCancel: false);
}
return true;
}
}
#endif
static string MaterialToShaderPropertyHash(Material m)
{
StringBuilder stringBuilder = new StringBuilder(m.shader.name);
foreach (MaterialProperty prop in
MaterialEditor.GetMaterialProperties(new Object[] { m }))
{
string propName = prop.name;
if (PropertiesToSkipInMaterialEquallityComparission.Contains(propName)) continue;
string isAnimated = GetAnimatedTag(m, propName);
if (isAnimated == "1")
{
stringBuilder.Append(isAnimated);
}
else if(isAnimated == "2")
{
//This is because materials with renaming should not share shaders
stringBuilder.Append(m.name);
}
else
{
switch (prop.type)
{
case MaterialProperty.PropType.Color:
stringBuilder.Append(m.GetColor(propName).ToString());
break;
case MaterialProperty.PropType.Vector:
stringBuilder.Append(m.GetVector(propName).ToString());
break;
case MaterialProperty.PropType.Range:
case MaterialProperty.PropType.Float:
stringBuilder.Append(m.GetFloat(propName)
.ToString(CultureInfo.InvariantCulture));
break;
case MaterialProperty.PropType.Texture:
Texture t = m.GetTexture(propName);
Vector4 texelSize = new Vector4(1.0f, 1.0f, 1.0f, 1.0f);
if (t != null)
texelSize = new Vector4(1.0f / t.width, 1.0f / t.height, t.width, t.height);
stringBuilder.Append(m.GetTextureOffset(propName).ToString());
stringBuilder.Append(m.GetTextureScale(propName).ToString());
break;
}
}
}
// https://forum.unity.com/threads/hash-function-for-game.452779/
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] bytes = encoding.GetBytes(stringBuilder.ToString());
var sha = new MD5CryptoServiceProvider();
return BitConverter.ToString(sha.ComputeHash(bytes)).Replace("-", "").ToLower();
}
public static bool SetLockForAllChildren(GameObject[] objects, int lockState, bool showProgressbar = false, bool showDialog = false, bool allowCancel = true)
{
IEnumerable<Material> materials = objects.Select(o => o.GetComponentsInChildren<Renderer>(true)).SelectMany(rA => rA.SelectMany(r => r.sharedMaterials));
return SetLockedForAllMaterials(materials, lockState, showProgressbar, showDialog);
}
static Dictionary<string, Material> s_shaderPropertyCombinations = new Dictionary<string, Material>();
public static bool SetLockedForAllMaterials(IEnumerable<Material> materials, int lockState, bool showProgressbar = false, bool showDialog = false, bool allowCancel = true, MaterialProperty shaderOptimizer = null)
{
Helper.RegisterEditorUse();
//first the shaders are created. compiling is suppressed with start asset editing
AssetDatabase.StartAssetEditing();
//Get cleaned materia list
IEnumerable<Material> materialsToChangeLock = materials.Where(m => m != null &&
string.IsNullOrEmpty(AssetDatabase.GetAssetPath(m)) == false && string.IsNullOrEmpty(AssetDatabase.GetAssetPath(m.shader)) == false
&& IsShaderUsingThryOptimizer(m.shader) && m.GetFloat(GetOptimizerPropertyName(m.shader)) != lockState).Distinct();
float i = 0;
float length = materialsToChangeLock.Count();
//show popup dialog if defined
if (showDialog && length > 0)
{
if(EditorUtility.DisplayDialog("Locking Materials", Locale.editor.Get("auto_lock_dialog").ReplaceVariables(length), "More information","OK"))
{
Application.OpenURL("https://www.youtube.com/watch?v=asWeDJb5LAo");
}
PersistentData.Set("ShowLockInDialog", false);
}
//Create shader assets
foreach (Material m in materialsToChangeLock.ToList()) //have to call ToList() here otherwise the Unlock Shader button in the ShaderGUI doesn't work
{
//do progress bar
if (showProgressbar)
{
if (allowCancel)
{
if (EditorUtility.DisplayCancelableProgressBar((lockState == 1) ? "Locking Materials" : "Unlocking Materials", m.name, i / length)) break;
}
else
{
EditorUtility.DisplayProgressBar((lockState == 1) ? "Locking Materials" : "Unlocking Materials", m.name, i / length);
}
}
//create the assets
try
{
if (lockState == 1)
{
string hash = MaterialToShaderPropertyHash(m);
// Check that shader has already been created for this hash and still exists
if (s_shaderPropertyCombinations.ContainsKey(hash) && Shader.Find(applyStructsLater[s_shaderPropertyCombinations[hash]].newShaderName) != null)
{
// Reuse existing shader and struct
ApplyStruct applyStruct = applyStructsLater[s_shaderPropertyCombinations[hash]];
applyStruct.material = m;
applyStructsLater[m] = applyStruct;
//Disable shader keywords
foreach (string keyword in m.shaderKeywords)
if (m.IsKeywordEnabled(keyword)) m.DisableKeyword(keyword);
}
// Create new locked shader
else
{
ShaderOptimizer.Lock(m,
MaterialEditor.GetMaterialProperties(new UnityEngine.Object[] { m }),
applyShaderLater: true);
s_shaderPropertyCombinations.Add(hash, m);
}
}
else if (lockState == 0)
{
ShaderOptimizer.Unlock(m, shaderOptimizer);
}
}
catch (Exception e)
{
Debug.LogError("Could not un-/lock material " + m.name);
Debug.LogError(e);
}
i++;
}
EditorUtility.ClearProgressBar();
AssetDatabase.StopAssetEditing();
//unity now compiles all the shaders
//now all new shaders are applied. this has to happen after unity compiled the shaders
if (lockState == 1)
{
//Apply new shaders
foreach (Material m in materialsToChangeLock)
{
if (ShaderOptimizer.LockApplyShader(m))
{
m.SetFloat(GetOptimizerPropertyName(m.shader), 1);
}
}
if(ShaderEditor.Active != null && ShaderEditor.Active.IsDrawing)
{
GUIUtility.ExitGUI();
}
}
AssetDatabase.Refresh();
return true;
}
public static string GetOptimizerPropertyName(Shader shader)
{
if (isShaderUsingThryOptimizer.ContainsKey(shader))
{
if (isShaderUsingThryOptimizer[shader] == false) return null;
return shaderThryOptimizerPropertyName[shader];
}
else
{
if (IsShaderUsingThryOptimizer(shader) == false) return null;
return shaderThryOptimizerPropertyName[shader];
}
}
private static Dictionary<Shader, string> shaderThryOptimizerPropertyName = new Dictionary<Shader, string>();
private static Dictionary<Shader, bool> isShaderUsingThryOptimizer = new Dictionary<Shader, bool>();
public static bool IsShaderUsingThryOptimizer(Shader shader)
{
if (isShaderUsingThryOptimizer.ContainsKey(shader))
{
return isShaderUsingThryOptimizer[shader];
}
SerializedObject shaderObject = new SerializedObject(shader);
SerializedProperty props = shaderObject.FindProperty("m_ParsedForm.m_PropInfo.m_Props");
if (props != null)
{
foreach (SerializedProperty p in props)
{
SerializedProperty at = p.FindPropertyRelative("m_Attributes");
if (at.arraySize > 0)
{
if (at.GetArrayElementAtIndex(0).stringValue == "ThryShaderOptimizerLockButton")
{
//Debug.Log(shader.name + " found to use optimizer ");
isShaderUsingThryOptimizer[shader] = true;
shaderThryOptimizerPropertyName[shader] = p.displayName;
return true;
}
}
}
}
isShaderUsingThryOptimizer[shader] = false;
return false;
}
public static bool IsMaterialLocked(Material material)
{
return material.shader.name.StartsWith("Hidden/") && material.GetTag("OriginalShader", false, "") != "";
}
private static Dictionary<Shader, int> shaderUsedTextureReferencesCount = new Dictionary<Shader, int>();
public static int GetUsedTextureReferencesCount(Shader s)
{
//Shader.m_ParsedForm.m_SubShaders[i].m_Passes[j].m_Programs[k].m_SubPrograms[l].m_Parameters[m].m_TextureParams[n]
//m_Programs not avaiable in unity 2019
return 0;
/*if (shaderUsedTextureReferencesCount.ContainsKey(s)) return shaderUsedTextureReferencesCount[s];
SerializedObject shaderObject = new SerializedObject(s);
SerializedProperty m_SubShaders = shaderObject.FindProperty("m_ParsedForm.m_SubShaders");
for (int i_subShader = 0; i_subShader < m_SubShaders.arraySize; i_subShader++)
{
SerializedProperty m_Passes = m_SubShaders.GetArrayElementAtIndex(i_subShader).FindPropertyRelative("m_Passes");
for (int i_passes = 0; i_passes < m_Passes.arraySize; i_passes++)
{
SerializedProperty m_Programs = m_Passes.GetArrayElementAtIndex(i_passes);
foreach (SerializedProperty p in m_Programs) Debug.Log(p.displayName);
}
}
return 0;*/
}
}
public class UnlockedMaterialsList : EditorWindow
{
static Dictionary<Shader, List<Material>> unlockedMaterialsByShader = new Dictionary<Shader, List<Material>>();
private void OnEnable()
{
UpdateList();
}
void UpdateList()
{
unlockedMaterialsByShader.Clear();
List<Material> unlockedMaterials = new List<Material>();
string[] guids = AssetDatabase.FindAssets("t:material");
float step = 1.0f / guids.Length;
float f = 0;
EditorUtility.DisplayProgressBar("Searching materials...", "", f);
foreach (string g in guids)
{
Material m = AssetDatabase.LoadAssetAtPath<Material>(AssetDatabase.GUIDToAssetPath(g));
if (m != null && m.shader != null && ShaderOptimizer.IsShaderUsingThryOptimizer(m.shader) && ShaderOptimizer.IsMaterialLocked(m) == false)
{
unlockedMaterials.Add(m);
}
f = f + step;
EditorUtility.DisplayProgressBar("Searching materials...", m.name, f);
}
foreach (IGrouping<Shader, Material> materials in unlockedMaterials.GroupBy(m => m.shader))
{
unlockedMaterialsByShader.Add(materials.Key, materials.ToList());
}
EditorUtility.ClearProgressBar();
}
private void OnGUI()
{
EditorGUILayout.LabelField("Unlocked Materials", Styles.EDITOR_LABEL_HEADER);
if (GUILayout.Button("Update List")) UpdateList();
if (unlockedMaterialsByShader.Count == 0)
{
GUILayout.Label("All your materials are locked.", Styles.greenStyle);
}
foreach (KeyValuePair<Shader, List<Material>> shaderMaterials in unlockedMaterialsByShader)
{
EditorGUILayout.Space();
EditorGUILayout.LabelField(shaderMaterials.Key.name);
List<Material> lockedMaterials = new List<Material>();
foreach (Material m in shaderMaterials.Value)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.ObjectField(m, typeof(Material), false);
//EditorGUILayout.IntField(ShaderOptimizer.GetUsedTextureReferencesCount(m.shader));
if (GUILayout.Button("Lock"))
{
ShaderOptimizer.SetLockedForAllMaterials(new List<Material>() { m }, 1, true, false, true);
lockedMaterials.Add(m);
}
EditorGUILayout.EndHorizontal();
}
foreach (Material m in lockedMaterials)
shaderMaterials.Value.Remove(m);
}
EditorGUILayout.Space();
if (GUILayout.Button("Lock All"))
{
ShaderOptimizer.SetLockedForAllMaterials(unlockedMaterialsByShader.Values.SelectMany(col => col), 1, true, false, true);
UpdateList();
}
}
}
}
|