summaryrefslogtreecommitdiff
path: root/VRCSDK3Worlds/Assets/VRCSDK/SDK3/Editor/VRCSdkControlPanelWorldBuilder3.cs
blob: ded4df748eba5b2d999a00251d7ddd6ea70ef0c2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;
using VRC.SDK3.Editor;
using VRC.SDKBase.Editor;
using VRC.SDKBase.Editor.BuildPipeline;
using VRC.Udon;
using VRC.Udon.Common.Interfaces;
using Object = UnityEngine.Object;

[assembly: VRCSdkControlPanelBuilder(typeof(VRCSdkControlPanelWorldBuilder3))]

namespace VRC.SDK3.Editor
{
    public class VRCSdkControlPanelWorldBuilder3 : VRCSdkControlPanelWorldBuilder
    {
        #region IVRCSdkControlPanelBuilder implementation
        public override bool IsValidBuilder(out string message)
        {
            bool result = base.IsValidBuilder(out message);
            message = "A VRCSceneDescriptor or VRCAvatarDescriptor\nis required to build VRChat SDK Content";
            return result;
        }

        public override void ShowBuilder()
        {
            List<UdonBehaviour> failedBehaviours = ShouldShowPrimitivesWarning();
            if (failedBehaviours.Count > 0)
            {
                _builder.OnGUIWarning(null,
                    "Udon Objects reference builtin Unity mesh assets, this won't work. Consider making a copy of the mesh to use instead.",
                    () =>
                    {
                        Selection.objects = failedBehaviours.Select(s => s.gameObject).Cast<Object>().ToArray();
                    }, FixPrimitivesWarning);
            }
            base.ShowBuilder();
        }

        public override void SelectAllComponents()
        {
            Debug.Log("SelectAllComponents");
        }

        protected override bool IsSDK3Scene()
        {
            return true;
        }

        protected override void OnGUISceneCheck(VRC.SDKBase.VRC_SceneDescriptor scene)
        {
            base.OnGUISceneCheck(scene);
            
            var resyncNotEnabled = Object.FindObjectsOfType<VRC.SDK3.Video.Components.Base.BaseVRCVideoPlayer>().Where(vp => !vp.EnableAutomaticResync).ToArray();
            if (resyncNotEnabled.Length > 0)
            {
                _builder.OnGUIWarning(null,
                "Video Players do not have automatic resync enabled; audio may become desynchronized from video during low performance.", 
                () =>
                {
                    Selection.objects = resyncNotEnabled.Select(s => s.gameObject).Cast<Object>().ToArray();
                },
                () =>
                {
                    foreach (var vp in resyncNotEnabled)
                        vp.EnableAutomaticResync = true;
                });
            }
            
            foreach (VRC.SDK3.Components.VRCObjectSync os in Object.FindObjectsOfType<VRC.SDK3.Components.VRCObjectSync>())
            {
                if (os.GetComponents<VRC.Udon.UdonBehaviour>().Any((ub) => ub.SyncIsManual))
                    _builder.OnGUIError(scene, "Object Sync cannot share an object with a manually synchronized Udon Behaviour",
                        delegate { Selection.activeObject = os.gameObject; }, null);
                if (os.GetComponent<VRC.SDK3.Components.VRCObjectPool>() != null)
                    _builder.OnGUIError(scene, "Object Sync cannot share an object with an object pool",
                        delegate { Selection.activeObject = os.gameObject; }, null);
            }
        } 

        #endregion

        public override void OnGUIScene()
        {
                 GUILayout.Label("", VRCSdkControlPanel.scrollViewSeparatorStyle);

            _builderScrollPos = GUILayout.BeginScrollView(_builderScrollPos, false, false, GUIStyle.none,
                GUI.skin.verticalScrollbar, GUILayout.Width(VRCSdkControlPanel.SdkWindowWidth),
                GUILayout.MinHeight(217));

            GUILayout.BeginVertical(VRCSdkControlPanel.boxGuiStyle, GUILayout.Width(VRCSdkControlPanel.SdkWindowWidth));
            GUILayout.BeginHorizontal();
            GUILayout.BeginVertical(GUILayout.Width(300));
            EditorGUILayout.Space();
            GUILayout.Label("Local Testing", VRCSdkControlPanel.infoGuiStyle);
            GUILayout.Label(
                "Before uploading your world you may build and test it in the VRChat client. You won't be able to invite anyone from online but you can launch multiple of your own clients.",
                VRCSdkControlPanel.infoGuiStyle);
            GUILayout.EndVertical();
            GUILayout.BeginVertical(GUILayout.Width(200));
            EditorGUILayout.Space();
            VRCSettings.NumClients = EditorGUILayout.IntField("Number of Clients", VRCSettings.NumClients, GUILayout.MaxWidth(190));
            EditorGUILayout.Space();
            VRCSettings.ForceNoVR = EditorGUILayout.Toggle("Force Non-VR", VRCSettings.ForceNoVR, GUILayout.MaxWidth(190));
            EditorGUILayout.Space();
            if (VRCSettings.DisplayAdvancedSettings)
            {
                VRCSettings.WatchWorlds =
                    EditorGUILayout.Toggle("Enable World Reload", VRCSettings.WatchWorlds, GUILayout.MaxWidth(190));
                EditorGUILayout.Space();
            }

            GUI.enabled = _builder.NoGuiErrorsOrIssues();

            string lastUrl = VRC_SdkBuilder.GetLastUrl();

            bool doReload = VRCSettings.WatchWorlds && VRCSettings.NumClients == 0;
            
            bool lastBuildPresent = lastUrl != null;
            if (lastBuildPresent == false)
                GUI.enabled = false;
            if (VRCSettings.DisplayAdvancedSettings)
            {
                string lastBuildLabel = doReload ? "Reload Last Build" : "Last Build";
                if (GUILayout.Button(lastBuildLabel))
                {
                    if (doReload)
                    {
                        // Todo: get this from settings or make key a const
                        string path = EditorPrefs.GetString("lastVRCPath");
                        if (File.Exists(path))
                        {
                            File.SetLastWriteTimeUtc(path, DateTime.Now);
                        }
                        else
                        {
                            Debug.LogWarning($"Cannot find last built scene, please Rebuild.");
                        }
                    }
                    else
                    {
                        VRC_SdkBuilder.shouldBuildUnityPackage = false;
                        VRC_SdkBuilder.RunLastExportedSceneResource();
                    }
                }

                if (Core.APIUser.CurrentUser.hasSuperPowers)
                {
                    if (GUILayout.Button("Copy Test URL"))
                    {
                        TextEditor te = new TextEditor {text = lastUrl};
                        te.SelectAll();
                        te.Copy();
                    }
                }
            }

            GUI.enabled = _builder.NoGuiErrorsOrIssues() ||
                          Core.APIUser.CurrentUser.developerType == Core.APIUser.DeveloperType.Internal;

#if UNITY_ANDROID
        EditorGUI.BeginDisabledGroup(true);
#endif
            string buildLabel = doReload ? "Build & Reload" : "Build & Test";
            if (GUILayout.Button(buildLabel))
            {
                bool buildTestBlocked = !VRCBuildPipelineCallbacks.OnVRCSDKBuildRequested(VRCSDKRequestedBuildType.Scene);
                if (!buildTestBlocked)
                {
                    EnvConfig.ConfigurePlayerSettings();
                    VRC_SdkBuilder.shouldBuildUnityPackage = false;
                    AssetExporter.CleanupUnityPackageExport(); // force unity package rebuild on next publish
                    VRC_SdkBuilder.PreBuildBehaviourPackaging();
                    if (doReload)
                    {
                        VRC_SdkBuilder.ExportSceneResource();
                    }
                    else
                    {
                        VRC_SdkBuilder.ExportSceneResourceAndRun();
                    }
                }
            }
#if UNITY_ANDROID
        EditorGUI.EndDisabledGroup();
#endif

            GUILayout.EndVertical();

            if (Event.current.type != EventType.Used)
            {
                GUILayout.EndHorizontal();
                EditorGUILayout.Space();
                GUILayout.EndVertical();
            }

            EditorGUILayout.Space();

            GUILayout.BeginVertical(VRCSdkControlPanel.boxGuiStyle, GUILayout.Width(VRCSdkControlPanel.SdkWindowWidth));

            GUILayout.BeginHorizontal();
            GUILayout.BeginVertical(GUILayout.Width(300));
            EditorGUILayout.Space();
            GUILayout.Label("Online Publishing", VRCSdkControlPanel.infoGuiStyle);
            GUILayout.Label(
                "In order for other people to enter your world in VRChat it must be built and published to our game servers.",
                VRCSdkControlPanel.infoGuiStyle);
            EditorGUILayout.Space();
            GUILayout.EndVertical();
            GUILayout.BeginVertical(GUILayout.Width(200));
            EditorGUILayout.Space();

            if (lastBuildPresent == false)
                GUI.enabled = false;
            if (VRCSettings.DisplayAdvancedSettings)
            {
                if (GUILayout.Button("Last Build"))
                {
                    if (Core.APIUser.CurrentUser.canPublishWorlds)
                    {
                        EditorPrefs.SetBool("VRC.SDKBase_StripAllShaders", false);
                        VRC_SdkBuilder.shouldBuildUnityPackage = VRCSdkControlPanel.FutureProofPublishEnabled;
                        VRC_SdkBuilder.UploadLastExportedSceneBlueprint();
                    }
                    else
                    {
                        VRCSdkControlPanel.ShowContentPublishPermissionsDialog();
                    }
                }
            }

            GUI.enabled = _builder.NoGuiErrorsOrIssues() ||
                          Core.APIUser.CurrentUser.developerType == Core.APIUser.DeveloperType.Internal;
            if (GUILayout.Button(VRCSdkControlPanel.GetBuildAndPublishButtonString()))
            {
                bool buildBlocked = !VRCBuildPipelineCallbacks.OnVRCSDKBuildRequested(VRCSDKRequestedBuildType.Scene);
                if (!buildBlocked)
                {
                    if (Core.APIUser.CurrentUser.canPublishWorlds)
                    {
                        EnvConfig.ConfigurePlayerSettings();
                        EditorPrefs.SetBool("VRC.SDKBase_StripAllShaders", false);
                        
                        VRC_SdkBuilder.shouldBuildUnityPackage = VRCSdkControlPanel.FutureProofPublishEnabled;
                        VRC_SdkBuilder.PreBuildBehaviourPackaging();
                        VRC_SdkBuilder.ExportAndUploadSceneBlueprint();
                    }
                    else
                    {
                        VRCSdkControlPanel.ShowContentPublishPermissionsDialog();
                    }
                }
            }

            GUILayout.EndVertical();
            GUI.enabled = true;

            if (Event.current.type == EventType.Used) return;
            GUILayout.EndHorizontal();
            GUILayout.EndVertical();
            GUILayout.EndScrollView();
        }

        private static Mesh[] _primitiveMeshes;

        private static List<UdonBehaviour> ShouldShowPrimitivesWarning()
        {
            if (_primitiveMeshes == null)
            {
                PrimitiveType[] primitiveTypes = (PrimitiveType[]) System.Enum.GetValues(typeof(PrimitiveType));
                _primitiveMeshes = new Mesh[primitiveTypes.Length];

                for (int i = 0; i < primitiveTypes.Length; i++)
                {
                    PrimitiveType primitiveType = primitiveTypes[i];
                    GameObject go = GameObject.CreatePrimitive(primitiveType);
                    _primitiveMeshes[i] = go.GetComponent<MeshFilter>().sharedMesh;
                    Object.DestroyImmediate(go);
                }
            }

            UdonBehaviour[] allBehaviours = Object.FindObjectsOfType<UdonBehaviour>();
            List<UdonBehaviour> failedBehaviours = new List<UdonBehaviour>(allBehaviours.Length);
            foreach (UdonBehaviour behaviour in allBehaviours)
            {
                IUdonVariableTable publicVariables = behaviour.publicVariables;
                foreach (string symbol in publicVariables.VariableSymbols)
                {
                    if (!publicVariables.TryGetVariableValue(symbol, out Mesh mesh))
                    {
                        continue;
                    }

                    if (mesh == null)
                    {
                        continue;
                    }

                    bool all = true;
                    foreach (Mesh primitiveMesh in _primitiveMeshes)
                    {
                        if (mesh != primitiveMesh)
                        {
                            continue;
                        }

                        all = false;
                        break;
                    }

                    if (all)
                    {
                        continue;
                    }

                    failedBehaviours.Add(behaviour);
                }
            }

            return failedBehaviours;
        }

        private void FixPrimitivesWarning()
        {
            UdonBehaviour[] allObjects = Object.FindObjectsOfType<UdonBehaviour>();
            foreach (UdonBehaviour behaviour in allObjects)
            {
                IUdonVariableTable publicVariables = behaviour.publicVariables;
                foreach (string symbol in publicVariables.VariableSymbols)
                {
                    if (!publicVariables.TryGetVariableValue(symbol, out Mesh mesh))
                    {
                        continue;
                    }

                    if (mesh == null)
                    {
                        continue;
                    }

                    bool all = true;
                    foreach (Mesh primitiveMesh in _primitiveMeshes)
                    {
                        if (mesh != primitiveMesh)
                        {
                            continue;
                        }

                        all = false;
                        break;
                    }

                    if (all)
                    {
                        continue;
                    }

                    Mesh clone = Object.Instantiate(mesh);

                    Scene scene = behaviour.gameObject.scene;
                    string scenePath = Path.GetDirectoryName(scene.path) ?? "Assets";

                    string folderName = $"{scene.name}_MeshClones";
                    string folderPath = Path.Combine(scenePath, folderName);

                    if (!AssetDatabase.IsValidFolder(folderPath))
                    {
                        AssetDatabase.CreateFolder(scenePath, folderName);
                    }

                    string assetPath = Path.Combine(folderPath, $"{clone.name}.asset");

                    Mesh existingClone = AssetDatabase.LoadAssetAtPath<Mesh>(assetPath);
                    if (existingClone == null)
                    {
                        AssetDatabase.CreateAsset(clone, assetPath);
                        AssetDatabase.Refresh();
                    }
                    else
                    {
                        clone = existingClone;
                    }

                    publicVariables.TrySetVariableValue(symbol, clone);
                    EditorSceneManager.MarkSceneDirty(behaviour.gameObject.scene);
                }
            }
        }
    }
}