-
Notifications
You must be signed in to change notification settings - Fork 3
/
VRCBakeryAdapter.cs
1321 lines (1072 loc) · 52.5 KB
/
VRCBakeryAdapter.cs
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
/**
* MIT License
*
* Copyright (c) 2019 Merlin
*
* 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.
*/
/**
* A mostly self-contained script to handle replacing Bakery SH or RNM directional lightmap values so that VRC can support them.
* This is so long mostly because I'm paranoid about making the process somewhat robust and difficult to break to a point where you lose data. The original script was like 1/3 the length it is now.
* This script will go and automatically patch your Bakery shaders to support saving the directional lightmap properties into the material. This will not interfere with the usual behavior of Bakery.
*/
#if UNITY_EDITOR
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
namespace Merlin
{
[Serializable]
public class RendererMaterialList
{
public MeshRenderer renderer;
public Material[] materials;
public Material[] generatedMaterials;
};
// I'm sorry for these names, I made them when I was annoyed that I had to make them.
[Serializable]
public class SerializableRendererMaterialList
{
public long rendererLocalId;
public string[] materialAssetGUIDS;
}
[Serializable]
public class SerializableRendererMaterialLists
{
public SerializableRendererMaterialList[] list;
}
public enum ReplacementScope
{
Scene,
Children,
};
[ExecuteInEditMode]
[AddComponentMenu("Merlin/VRC Bakery Adapter")]
public class VRCBakeryAdapter : MonoBehaviour
{
private static readonly string savePath = "Assets/Bakery/generated/";
private static readonly string GeneratedMaterialPrefix = "generatedbakery_";
public static readonly string revertProfilePath = "Bakery/reversionProfiles/";
public RendererMaterialList[] OriginalRendererMaterials;
public int LightmapMode = -1; // Default to Auto which is -1
public ReplacementScope replacementScope = ReplacementScope.Scene;
public bool includeInactiveObjects = false;
public string currentRevertPath = "";
public bool compileKeywords = true;
// Utils vars
public bool showUtilsPane = false;
public bool replaceTransparentStandard = false;
private Dictionary<string, Shader> shaderHashToCompiledShaderMap = new Dictionary<string, Shader>();
private Material currentWorkingMaterial = null;
[Serializable]
struct KeyShaderPair
{
public string key;
public Shader shader;
}
[SerializeField]
private List<KeyShaderPair> serializedKeyShaderPairs = new List<KeyShaderPair>();
void OnDestroy()
{
if (!EditorApplication.isPlayingOrWillChangePlaymode && !EditorApplication.isPlaying)
{
// Don't cleanup the shaders when destroyed because OnDestroy will be called on application exit. I attempted to use the OnApplicationQuit event to detect this, but it does not seem to function.
// So here we are; for now you will get shaders lying around if you delete the component without reverting the materials...
RevertMaterials(false);
}
}
// https://forum.unity.com/threads/hash-function-for-game.452779/
private static string ComputeMD5(string str)
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] bytes = encoding.GetBytes(str);
var sha = new System.Security.Cryptography.MD5CryptoServiceProvider();
return BitConverter.ToString(sha.ComputeHash(bytes)).Replace("-", "").ToLower();
}
public void RevertMaterials(bool cleanupFiles = true)
{
if (OriginalRendererMaterials != null)
{
HashSet<Material> materialsToDelete = new HashSet<Material>();
for (int i = 0; i < OriginalRendererMaterials.Length; i++)
{
RendererMaterialList list = OriginalRendererMaterials[i];
if (list != null && list.renderer != null && list.materials != null)
{
if (list.generatedMaterials != null)
{
foreach (Material oldMat in list.generatedMaterials)
{
materialsToDelete.Add(oldMat);
}
}
list.renderer.sharedMaterials = list.materials;
OriginalRendererMaterials[i] = null; // Clear so we don't keep resetting the materials
}
}
OriginalRendererMaterials = null;
EditorSceneManager.MarkSceneDirty(gameObject.scene);
// Clean up old revert data since we just effectively used it.
if (currentRevertPath.Length > 0 && File.Exists(currentRevertPath))
{
File.Delete(currentRevertPath);
}
currentRevertPath = "";
// Cleanup generated shaders
if (cleanupFiles)
{
for (int i = 0; i < serializedKeyShaderPairs.Count; i++)
{
EditorUtility.DisplayProgressBar("Reverting Materials", "Cleaning up generated shaders", (i / (float)serializedKeyShaderPairs.Count) * 0.5f);
var hashShader = serializedKeyShaderPairs[i];
AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(hashShader.shader));
}
int matCounter = 0;
foreach (var oldMat in materialsToDelete)
{
EditorUtility.DisplayProgressBar("Reverting Materials", "Cleaning up generated materials", (matCounter++ / (float)materialsToDelete.Count) * 0.5f + 0.5f);
// Make sure we don't delete the original materials if someone manages to hit a really bad edge case.
if (Path.GetFileNameWithoutExtension(AssetDatabase.GetAssetPath(oldMat)).StartsWith(GeneratedMaterialPrefix))
{
AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(oldMat));
}
}
}
EditorUtility.ClearProgressBar();
shaderHashToCompiledShaderMap.Clear();
serializedKeyShaderPairs.Clear();
Debug.Log("Reverted Materials");
}
}
private List<MeshRenderer> GetAllMeshRenderers()
{
List<MeshRenderer> rendererList = new List<MeshRenderer>();
// Collect all mesh renderers in scope
if (replacementScope == ReplacementScope.Scene)
{
GameObject[] rootObjects = gameObject.scene.GetRootGameObjects();
foreach (GameObject gameObj in rootObjects)
{
rendererList.AddRange(gameObj.GetComponentsInChildren<MeshRenderer>(true));
}
}
else
{
rendererList.AddRange(GetComponentsInChildren<MeshRenderer>(true));
}
return rendererList;
}
private string StripComments(string srcStr)
{
// Be lazy and do a 2 pass removal of commented sections of code, first block comments, then line comments
int currentIdx = 0;
int copyRunLength = 0;
StringBuilder uncommentedStrBuilder = new StringBuilder();
// Remove block comments
// Copy entire runs of uncommented code at a time because appending to a string char-by-char is slow as heck
while (currentIdx + copyRunLength < srcStr.Length)
{
if (srcStr[currentIdx + copyRunLength] == '/' && currentIdx + copyRunLength + 1 < srcStr.Length && srcStr[currentIdx + copyRunLength + 1] == '*')
{
uncommentedStrBuilder.Append(srcStr.Substring(currentIdx, copyRunLength));
currentIdx += copyRunLength;
copyRunLength = 0;
// This logic for handling nested comments doesn't seem necessary since it's apparently not valid syntax but I'll keep it just in case ¯\_(ツ)_/¯
int depth = 0;
do
{
if (srcStr[currentIdx] == '/' && srcStr[currentIdx + 1] == '*')
depth++;
else if (srcStr[currentIdx] == '*' && srcStr[currentIdx + 1] == '/')
depth--;
currentIdx++;
} while (depth > 0 && currentIdx < srcStr.Length - 1);
currentIdx++;
}
else
{
copyRunLength++;
}
}
if (copyRunLength > 0)
{
uncommentedStrBuilder.Append(srcStr.Substring(currentIdx, copyRunLength));
}
string uncommentedString = uncommentedStrBuilder.ToString();
uncommentedStrBuilder = new StringBuilder();
// Remove line comments
StringReader reader = new StringReader(uncommentedString);
string line = "";
while ((line = reader.ReadLine()) != null)
{
int commentStartIdx = line.IndexOf("//");
if (commentStartIdx != -1)
line = line.Substring(0, commentStartIdx);
uncommentedStrBuilder.Append(line + "\r\n");
}
return uncommentedStrBuilder.ToString();
}
// Finds the end of the current scope beginning on the codeBlockStart '{' character
private int FindCodeBlockEnd(string srcStr, int codeBlockStart)
{
int blockEnd = codeBlockStart;
int depth = 0;
for (int i = codeBlockStart; i < srcStr.Length; i++)
{
if (srcStr[i] == '{')
depth++;
else if (srcStr[i] == '}')
depth--;
if (depth <= 0)
{
blockEnd = i;
break;
}
}
return blockEnd;
}
private bool IsValidKeyword(string keyword)
{
bool isValidKeyword = false;
foreach (char character in keyword)
{
// Cull keywords that end up being _, __, ___, etc since they are culled by Unity and not valid
if (character != '_' && character != ' ')
{
isValidKeyword = true;
break;
}
}
return isValidKeyword;
}
private int GetWhiteSpace(string line)
{
int whitespaceCount = 0;
for (int i = 0; i < line.Length; i++)
{
if (char.IsWhiteSpace(line[i]))
whitespaceCount++;
else
break;
}
return whitespaceCount;
}
private HashSet<string> ParseAvailablePassKeywords(string shaderText)
{
HashSet<string> availableKeywords = new HashSet<string>();
// Gather shader_feature and multi_compile's
StringReader lineReader = new StringReader(shaderText);
string line = "";
while ((line = lineReader.ReadLine()) != null)
{
int startIdx = line.IndexOf("#pragma multi_compile ");
if (startIdx >= 0)
{
startIdx = line.IndexOf("multi_compile", startIdx);
}
else if (startIdx == -1)
{
startIdx = line.IndexOf("#pragma shader_feature ");
if (startIdx >= 0)
startIdx = line.IndexOf("shader_feature", startIdx);
}
if (startIdx == -1)
continue;
// not needed anymore since comments are stripped as a pre-process step
//int commentIdx = line.IndexOf("//");
//if (commentIdx != -1 && commentIdx < startIdx)
// continue;
// Skip to beginning of keyword list
startIdx = line.IndexOf(" ", startIdx);
string[] keywords = line.Substring(startIdx).Split(' ');
foreach (string keyword in keywords)
{
if (IsValidKeyword(keyword))
availableKeywords.Add(keyword.Trim().ToUpper());
}
}
return availableKeywords;
}
private string ProcessPass(Material mat, string passCode)
{
HashSet<string> passKeywords = ParseAvailablePassKeywords(passCode);
HashSet<string> usedKeywords = new HashSet<string>();
foreach (string keyword in mat.shaderKeywords)
{
if (IsValidKeyword(keyword) && passKeywords.Contains(keyword))
usedKeywords.Add(keyword);
}
StringBuilder processedPassBuilder = new StringBuilder();
processedPassBuilder.Append("Pass ");
StringReader reader = new StringReader(passCode);
string line = "";
while ((line = reader.ReadLine()) != null)
{
// Insert the #defines for this variant
if (line.Contains("CGPROGRAM") || line.Contains("HLSLPROGRAM"))
{
processedPassBuilder.AppendFormat("{0}\r\n", line); // Add the CGPROGRAM line
int whitespaceCount = GetWhiteSpace(line);
foreach (string keyword in usedKeywords)
{
string defineStr = string.Format("#define {0} 1", keyword);
defineStr = defineStr.PadLeft(whitespaceCount + defineStr.Length);
processedPassBuilder.AppendFormat("{0}\r\n", defineStr);
}
}
else
{
processedPassBuilder.AppendFormat("{0}\r\n", line);
}
}
return processedPassBuilder.ToString();
}
private Shader GenerateShaderVariation(Material mat)
{
// We only care about Bakery shaders
if (!mat.shader.name.Contains("Bakery"))
return mat.shader;
Shader originalShader = mat.shader;
string shaderPath = AssetDatabase.GetAssetPath(originalShader);
string shaderDirectory = Path.GetDirectoryName(Path.GetFullPath(shaderPath));
string[] keywords = mat.shaderKeywords;
Array.Sort(keywords, (x, y) => string.Compare(x, y));
string hashStr = shaderPath;
foreach (string keyword in keywords)
hashStr += keyword;
string shaderHash = ComputeMD5(hashStr);
Shader compiledShader = null;
if (shaderHashToCompiledShaderMap.TryGetValue(shaderHash, out compiledShader))
{
return compiledShader;
}
string shaderText = "";
try
{
using (StreamReader shaderReader = new StreamReader(shaderPath))
{
shaderText = shaderReader.ReadToEnd();
}
}
catch (IOException)
{
Debug.LogError("Failed to open Bakery shader to compile!");
return mat.shader;
}
shaderText = StripComments(shaderText);
StringBuilder finalShaderCodeBuilder = new StringBuilder();
// Search for Passes to replace
int passIdx = 0;
int lastPassIdx = 0;
// Run through all the passes that need #define's inserted
while (true)
{
lastPassIdx = passIdx;
passIdx = shaderText.IndexOf("Pass", passIdx, StringComparison.CurrentCultureIgnoreCase);
if (passIdx == -1)
break;
// Splice in all sections in between passes
finalShaderCodeBuilder.Append(shaderText.Substring(lastPassIdx, passIdx - lastPassIdx));
int passStartIdx = passIdx + 4;
while (passStartIdx < shaderText.Length)
{
char currentChar = shaderText[passStartIdx];
if (currentChar == '{')
break;
else if (currentChar != ' ' && currentChar != '\n' && currentChar != '\r' && currentChar != '\t')
{
passStartIdx = -1;
break;
}
passStartIdx++;
}
// This isn't the pass we're looking for... It's some other piece of code that has the word 'pass' in it.
if (passStartIdx == -1)
{
finalShaderCodeBuilder.Append(shaderText.Substring(passIdx, 4));
passIdx += 4;
continue;
}
int passEndIdx = FindCodeBlockEnd(shaderText, passStartIdx) + 1;
finalShaderCodeBuilder.Append(ProcessPass(mat, shaderText.Substring(passStartIdx, passEndIdx - passStartIdx)));
passIdx = passEndIdx;
}
// Patch in the last bit of code after the last pass
if (lastPassIdx < shaderText.Length)
{
finalShaderCodeBuilder.Append(shaderText.Substring(lastPassIdx));
}
string finalShaderCode = finalShaderCodeBuilder.ToString();
// Give the shader a unique name under Hidden/<shader hash>
// In hindsight I probably should've just bit the bullet and did more of this using Regex
Regex shaderNameRegex = new Regex(@"Shader\s*""\w.+""\s*{", RegexOptions.IgnoreCase);
finalShaderCode = shaderNameRegex.Replace(finalShaderCode, "Shader \"Hidden/" + shaderHash + "\"\r\n{");
string savePath = Path.Combine(shaderDirectory, "generated_" + shaderHash + ".shader");
string savePathProject = Path.Combine(Path.GetDirectoryName(shaderPath), "generated_" + shaderHash + ".shader");
try
{
using (StreamWriter shaderWriter = new StreamWriter(savePath))
{
shaderWriter.Write(finalShaderCode);
}
}
catch (IOException)
{
Debug.LogError("Failed to write shader for variation " + mat.shader.name + " to " + savePath);
return mat.shader;
}
AssetDatabase.ImportAsset(savePathProject);
Shader generatedShader = AssetDatabase.LoadAssetAtPath<Shader>(savePathProject);
// Add to cache so we don't regenerate again
shaderHashToCompiledShaderMap.Add(shaderHash, generatedShader);
return generatedShader;
}
public void OnCollectMaterials()
{
// Make sure shaders have been patched
PatchShaderProperties();
List<MeshRenderer> rendererList = GetAllMeshRenderers();
MaterialPropertyBlock propertyBlock = new MaterialPropertyBlock();
// Revert materials before running again in case they haven't been cleaned up by the user
RevertMaterials();
OriginalRendererMaterials = new RendererMaterialList[rendererList.Count];
Dictionary<string, Material> generatedMaterialList = new Dictionary<string, Material>();
if (!Directory.Exists(savePath))
Directory.CreateDirectory(savePath);
for (int i = 0; i < rendererList.Count; i++)
{
EditorUtility.DisplayProgressBar("Conversion Progress", "Generating Bakery directional lightmap materials For VRChat...", i / (float)rendererList.Count);
MeshRenderer meshRenderer = rendererList[i];
bool skipRenderer = false;
bool hasBakeryShader = false;
foreach (Material mat in meshRenderer.sharedMaterials)
{
if (mat != null)
{
string materialFileName = Path.GetFileNameWithoutExtension(AssetDatabase.GetAssetPath(mat));
if (materialFileName.StartsWith(GeneratedMaterialPrefix))
{
// Prevent conflicts with other collectors that could make restoring materials a mess for the user.
skipRenderer = true;
break;
}
// Ignore renderers with no bakery shaders
if (mat.shader.name.Contains("Bakery"))
hasBakeryShader = true;
}
}
if (!skipRenderer && hasBakeryShader && (meshRenderer.gameObject.activeInHierarchy || includeInactiveObjects))
{
meshRenderer.GetPropertyBlock(propertyBlock);
// The property block will have these properties assigned by Bakery at runtime after directional lightmaps have been baked.
// If the bakery scripts were whitelisted, they would assign these properties at runtime in-game, but for the meantime we have to do this manually.
// The reason we need to generate new materials is that the mapping of property blocks and materials is not 1-to-1 you can have different property blocks set with different textures on 2 objects using the same material.
Texture RNM0 = propertyBlock.GetTexture("_RNM0");
Texture RNM1 = propertyBlock.GetTexture("_RNM1");
Texture RNM2 = propertyBlock.GetTexture("_RNM2");
int propertyLightmapMode = (int)propertyBlock.GetFloat("bakeryLightmapMode");
if (RNM0 && RNM1 && RNM2)
{
// Store original materials so we can restore them later
OriginalRendererMaterials[i] = new RendererMaterialList();
OriginalRendererMaterials[i].renderer = meshRenderer;
OriginalRendererMaterials[i].materials = meshRenderer.sharedMaterials;
string textureName = (AssetDatabase.GetAssetPath(RNM0) + "_" +
AssetDatabase.GetAssetPath(RNM1) + "_" +
AssetDatabase.GetAssetPath(RNM2));
Material[] newSharedMaterials = new Material[meshRenderer.sharedMaterials.Length];
for (int j = 0; j < meshRenderer.sharedMaterials.Length; j++)
{
Material material = meshRenderer.sharedMaterials[j];
string materialPath = AssetDatabase.GetAssetPath(material);
string materialFileName = Path.GetFileNameWithoutExtension(materialPath);
if (material != null && material.shader.name.Contains("Bakery"))
{
string matTexHash = ComputeMD5(materialPath + textureName);
Material newMaterial = null;
generatedMaterialList.TryGetValue(matTexHash, out newMaterial);
if (newMaterial == null)
{
newMaterial = new Material(material);
// Add a reference to the object outside the stack to hopefully prevent a very rare bug where the material gets destroyed after a shader variation is generated, but before the asset is created.
currentWorkingMaterial = newMaterial;
newMaterial.SetTexture("_RNM0", RNM0);
newMaterial.SetTexture("_RNM1", RNM1);
newMaterial.SetTexture("_RNM2", RNM2);
newMaterial.SetInt("bakeryLightmapMode", LightmapMode == -1 ? propertyLightmapMode : LightmapMode); // If -1 just get the lightmap mode from the property block
if (compileKeywords)
{
newMaterial.shader = GenerateShaderVariation(newMaterial);
// There's no real point to this right now since Unity will detect that this object is referencing the old materials and include them in the assetbundle regardless.
// The only half decent solution here is removing the keywords from the old materials temporarily as well which is pretty destructive and it's more work than I feel like at the moment to get it working and robust.
// Having missing keywords will also mess with the bakes since cutout and such is detected using keywords, even though people technically shouldn't be doing bakes with materials replaced we'll make an attempt to keep the bakes working.
//newMaterial.shaderKeywords = new string[0];
}
AssetDatabase.CreateAsset(newMaterial, savePath + GeneratedMaterialPrefix + materialFileName + "_" + matTexHash + ".mat");
generatedMaterialList.Add(matTexHash, newMaterial);
}
newSharedMaterials[j] = newMaterial;
}
else if (material != null)
{
newSharedMaterials[j] = material;
}
}
meshRenderer.sharedMaterials = newSharedMaterials;
OriginalRendererMaterials[i].generatedMaterials = meshRenderer.sharedMaterials;
}
}
}
AssetDatabase.SaveAssets();
EditorSceneManager.MarkSceneDirty(gameObject.scene);
// Backup revert settings
SaveReversionProfile();
// Be extra sure the materials are saved and such before the upload comes around.
AssetDatabase.SaveAssets();
EditorSceneManager.MarkSceneDirty(gameObject.scene);
AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport);
AssetDatabase.SaveAssets();
// Flatten out the dictionary to a list so that Unity can serialize it...
serializedKeyShaderPairs.Clear();
foreach (var keyshader in shaderHashToCompiledShaderMap)
{
serializedKeyShaderPairs.Add(new KeyShaderPair() { key = keyshader.Key, shader = keyshader.Value });
}
shaderHashToCompiledShaderMap.Clear();
currentWorkingMaterial = null;
EditorUtility.ClearProgressBar();
Debug.Log("Converted Bakery materials for VRChat");
}
// Just a debug thing if people want to see a list of the renderers affected for some reason.
public void OnPrintMaterials()
{
foreach (var rendererMat in OriginalRendererMaterials)
{
if (rendererMat != null && rendererMat.renderer != null && rendererMat.materials != null)
Debug.Log(rendererMat.renderer.ToString() + ": " + rendererMat.materials.Length);
}
}
// Inserts extra properties into the Properties block of the Bakery shaders so that they get serialized along with the materials
// The references in the shaders reference these properties and assume they are bound via Property Blocks
// This doesn't cause any interference with the usual behavior of the Bakery shaders since the Property Blocks take priority over these shader properties in editor.
private bool PatchShader(string shaderPath)
{
const string patchString =
"\r\n // Merlin Patch\r\n" +
" _RNM0(\"RNM0\", 2D) = \"black\" {}\r\n" +
" _RNM1(\"RNM1\", 2D) = \"black\" {}\r\n" +
" _RNM2(\"RNM2\", 2D) = \"black\" {}\r\n" +
" [Enum(DEFAULT, 0, VERTEXLM, 1, RNM, 2, SH, 3)] bakeryLightmapMode(\"Bakery Lightmap Mode\", Int) = 0\r\n" +
" // End Merlin patch\r\n\r\n ";
string shaderText = "";
try
{
using (StreamReader shaderReader = new StreamReader(shaderPath))
{
shaderText = shaderReader.ReadToEnd();
}
}
catch (IOException)
{
Debug.LogError("Failed to open Bakery shader to patch!");
return false;
}
if (shaderText.Contains("// Merlin Patch"))
{
Debug.Log("Bakery shader " + Path.GetFileNameWithoutExtension(shaderPath) + " has already been patched");
return true;
}
// Look for the beginning of the property list
int insertIdx = shaderText.IndexOf("_Color(\"Color\", Color)");
if (insertIdx < 0)
{
Debug.LogError("Failed to find insertion point for shader properties");
return false;
}
shaderText = shaderText.Insert(insertIdx, patchString);
// Now write patched file out
try
{
using (StreamWriter shaderWriter = new StreamWriter(shaderPath))
{
shaderWriter.Write(shaderText);
}
}
catch (IOException)
{
Debug.LogError("Failed to save patch to Bakery shader");
return false;
}
return true;
}
private void PatchShaderProperties()
{
const string standardPath = "Assets/Bakery/shader/BakeryStandard.shader";
const string standardSpecPath = "Assets/Bakery/shader/BakeryStandardSpecular.shader";
bool patchedStandard = PatchShader(standardPath);
bool patchedStandardSpec = PatchShader(standardSpecPath);
if (patchedStandard && patchedStandardSpec)
{
Debug.Log("Successfully patched Bakery shaders.");
}
}
private void SaveReversionProfile()
{
string fileName = gameObject.scene.name + "_" + gameObject.name + "_" + DateTime.Now.ToString("dd-mm-yy_HH-mm-ss", CultureInfo.InvariantCulture) + ".rev";
string savePath = Application.dataPath + "/" + revertProfilePath;
//string savePath = revertProfilePath;
string filePath = savePath + fileName;
if (!Directory.Exists(savePath))
Directory.CreateDirectory(savePath);
// Beware all ye who read the following code, Unity asset serialization is terrible.
// Soooo, we need to briefly re-implement the weak referencing for Mesh Renderers and Materials all over again here because Unity doesn't like serializing the mesh renderer references and just silently nulls them out like any respectable engine would do.
// If there is some poorly-documented -- proper way to do this that you can demonstrate working in this case, please submit a pull request to put this poor code out of its misery. Thanks!
// Yay reflection https://forum.unity.com/threads/how-to-get-the-local-identifier-in-file-for-scene-objects.265686/
// This is somewhat broken on prefabs in >5.x. Objects under the root of the prefab will not have a local file ID because Unity just saves the prefab references into the scene now.
// Though with testing it seems to work on most prefabs I can try for some reason...
// This sounds reasonable, except they left no decent way to uniquely identify components in prefabs now without dumb workarounds.
// There's a proper solution if we were using >=2018.1 https://docs.unity3d.com/ScriptReference/AssetDatabase.TryGetGUIDAndLocalFileIdentifier.html
PropertyInfo inspectorModeInfo = typeof(SerializedObject).GetProperty("inspectorMode", BindingFlags.NonPublic | BindingFlags.Instance);
List<SerializableRendererMaterialList> serializableLists = new List<SerializableRendererMaterialList>();
foreach (RendererMaterialList list in OriginalRendererMaterials)
{
if (list != null && list.renderer != null && list.materials != null)
{
SerializableRendererMaterialList newRendererMaterials = new SerializableRendererMaterialList();
newRendererMaterials.materialAssetGUIDS = new string[list.materials.Length];
for (int i = 0; i < list.materials.Length; i++)
{
Material mat = list.materials[i];
if (mat != null)
{
newRendererMaterials.materialAssetGUIDS[i] = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(mat));
}
else
{
newRendererMaterials.materialAssetGUIDS[i] = "";
}
}
SerializedObject serializedObject = new SerializedObject(list.renderer);
inspectorModeInfo.SetValue(serializedObject, InspectorMode.Debug, null);
SerializedProperty localIdProperty = serializedObject.FindProperty("m_LocalIdentfierInFile"); // Misspelled purposely
newRendererMaterials.rendererLocalId = localIdProperty.longValue;
if (newRendererMaterials.rendererLocalId == 0)
Debug.Log("ID: " + newRendererMaterials.rendererLocalId + ", name: " + list.renderer.gameObject.name);
if (newRendererMaterials.rendererLocalId != 0)
serializableLists.Add(newRendererMaterials);
//inspectorModeInfo.SetValue(serializedObject, InspectorMode.Normal, null); // Restore normal inspector mode
}
}
SerializableRendererMaterialLists serializableRendererMaterialLists = new SerializableRendererMaterialLists();
serializableRendererMaterialLists.list = serializableLists.ToArray();
// Now actually serialize the file as binary...
BinaryFormatter formatter = new BinaryFormatter();
using (FileStream dataFile = File.Create(filePath))
{
formatter.Serialize(dataFile, serializableRendererMaterialLists);
}
currentRevertPath = filePath;
}
public bool LoadReversionProfile(string path)
{
SerializableRendererMaterialLists lists;
try
{
using (FileStream file = File.Open(path, FileMode.Open))
{
BinaryFormatter formatter = new BinaryFormatter();
lists = (SerializableRendererMaterialLists)formatter.Deserialize(file);
}
}
catch (IOException)
{
Debug.LogError("Failed to read reversion profile");
return false;
}
PropertyInfo inspectorModeInfo = typeof(SerializedObject).GetProperty("inspectorMode", BindingFlags.NonPublic | BindingFlags.Instance);
Dictionary<long, MeshRenderer> meshIdMap = new Dictionary<long, MeshRenderer>();
GameObject[] sceneRootObjects = gameObject.scene.GetRootGameObjects();
foreach (GameObject rootObj in sceneRootObjects)
{
MeshRenderer[] meshRenderers = rootObj.GetComponentsInChildren<MeshRenderer>();
foreach (MeshRenderer sceneMeshRenderer in meshRenderers)
{
// Use same method as above to build a map of all mesh renderers in the scene to their IDs so we can easily remap them below.
SerializedObject serializedObject = new SerializedObject(sceneMeshRenderer);
inspectorModeInfo.SetValue(serializedObject, InspectorMode.Debug, null);
SerializedProperty localIdProperty = serializedObject.FindProperty("m_LocalIdentfierInFile"); // Misspelled purposely
long rendererId = localIdProperty.longValue;
if (rendererId != 0)
{
if (!meshIdMap.ContainsKey(rendererId))
{
meshIdMap.Add(rendererId, sceneMeshRenderer);
}
else
{
Debug.LogError("Duplicate ID " + rendererId + " found for renderer on " + sceneMeshRenderer.gameObject.name + ", belongs to renderer on " + meshIdMap[rendererId].gameObject.name);
}
}
}
}
List<RendererMaterialList> loadedRendererMaterialLists = new List<RendererMaterialList>();
// Remap the IDs and GUIDs back to asset references now.
foreach (SerializableRendererMaterialList list in lists.list)
{
RendererMaterialList newList = new RendererMaterialList();
newList.materials = new Material[list.materialAssetGUIDS.Length];
if (!meshIdMap.TryGetValue(list.rendererLocalId, out newList.renderer))
{
Debug.LogWarning("Unable to locate renderer for ID " + list.rendererLocalId);
continue;
}
for (int i = 0; i < list.materialAssetGUIDS.Length; i++)
{
string matGuid = list.materialAssetGUIDS[i];
Material loadedMat = null;
if (matGuid.Length > 0)
{
loadedMat = AssetDatabase.LoadAssetAtPath<Material>(AssetDatabase.GUIDToAssetPath(matGuid));
if (loadedMat == null)
{
Debug.LogWarning("Unable to load material with GUID " + matGuid);
}
}
newList.materials[i] = loadedMat;
}
loadedRendererMaterialLists.Add(newList);
}
OriginalRendererMaterials = loadedRendererMaterialLists.ToArray();
return true;
}
public void ConvertStandardToBakeryStandard(bool useLightmapSpecular, int lightmapModeReplacement)
{
Shader bakeryStandard = Shader.Find("Bakery/Standard");
Shader bakeryStandardSpec = Shader.Find("Bakery/Standard Specular");
if (!bakeryStandard || !bakeryStandardSpec)
{
Debug.LogError("Could not locate Bakery shaders");
return;
}
List<MeshRenderer> meshRenderers = GetAllMeshRenderers();
HashSet<Material> materialList = new HashSet<Material>();
foreach (MeshRenderer currentRenderer in meshRenderers)
{
foreach (Material currentMaterial in currentRenderer.sharedMaterials)
{
materialList.Add(currentMaterial);
}
}
if (materialList.Count == 0)
{
Debug.Log("No materials needed converting for Standard to Bakery Standard.");
return;
}
Material[] matArray = new Material[materialList.Count];
int idx = 0;
foreach (Material mat in materialList)
{
matArray[idx] = mat;
idx++;
}
// Make this operation undo-able
Undo.RecordObjects(matArray, "Standard -> Bakery Standard");
foreach (Material currentMaterial in matArray)
{
if (currentMaterial)
{
string shaderName = currentMaterial.shader.name;
bool isTransparentMaterial = currentMaterial.GetTag("RenderType", false) == "Transparent";
if (!isTransparentMaterial || replaceTransparentStandard)
{
if (shaderName == "Standard")
{
currentMaterial.shader = bakeryStandard;
}
else if (shaderName == "Standard (Specular setup)")
{
currentMaterial.shader = bakeryStandardSpec;