Tanoda
RuntimeTriLibLoader.cs
Go to the documentation of this file.
1using System;
2using System.Collections;
3using System.Collections.Generic;
4using System.Threading;
5using Es.InkPainter;
6using GILES;
7using GILES.Interface;
8using NaughtyAttributes;
9using UnityEngine;
10using UnityEngine.Networking;
11#if TRILIB_2
12using System.IO;
13using TriLibCore;
14using TriLibCore.General;
15using AssetLoaderContext = TriLibCore.AssetLoaderContext;
16#else
17using TriLib;
18#endif
19
20public class RuntimeTriLibLoader : MonoBehaviour
21{
22 public bool useAdvancedColliderGeneration = false;
23
24 public void ModelFromURL(string url, bool modelEditor = false)
25 {
26#if UNITY_WEBGL && TRILIB_2
27 LoadingManager.instance.SetLoading();
28 LoadingManager.instance.ShowWindow();
29 LoadingManager.instance.timeout += 5f;
30 StartCoroutine(NetworkManager.instance.GetFile(url, (data) =>
31 {
32 var assetLoaderOptions = AssetLoader.CreateDefaultLoaderOptions();
33
34 var extension = url.Substring(url.LastIndexOf('.') + 1).ToLower();
35
36 if (extension == "zip")
37 {
38 AssetLoaderZip.LoadModelFromZipStream(new MemoryStream(data), assetLoaderOptions: assetLoaderOptions,
39 fileExtension: url.Substring(url.LastIndexOf('.') + 1).ToLower(), onLoad:
40 delegate(AssetLoaderContext alc)
41 {
42 var mr = alc.RootGameObject.GetComponentInChildren<MeshRenderer>();
43 Vector3 objectSizes = mr.bounds.max - mr.bounds.min;
44 float objectSize = Mathf.Max(objectSizes.x, objectSizes.y, objectSizes.z);
45 float cameraView = 2.0f * Mathf.Tan(0.5f * Mathf.Deg2Rad * Camera.main.fieldOfView); // Visible height 1 meter in front
46 float distance = 2.0f * objectSize / cameraView; // Combined wanted distance from the object
47 distance += 0.5f * objectSize; // Estimated offset from the center to the outside of the object
48 //Camera.main.transform.position = mr.bounds.center - distance * Camera.main.transform.forward;
49 //Camera.main.transform.rotation = Quaternion.Euler(new Vector3(0, 0, 0));
50 pb_SceneCamera.Focus(alc.RootGameObject.transform.position,distance);
51 if (modelEditor)
52 {
53 mr.gameObject.AddComponent<MeshInfo>();
54 }
55 LoadingManager.instance.HideWindow();
56 }, onError: OnError, onMaterialsLoad: delegate(AssetLoaderContext alc) { }, onProgress: delegate(AssetLoaderContext alc, float progress) { });
57 }
58 else
59 {
60 AssetLoader.LoadModelFromStream(new MemoryStream(data), assetLoaderOptions: assetLoaderOptions,
61 fileExtension: url.Substring(url.LastIndexOf('.') + 1).ToLower(), onLoad:
62 delegate(AssetLoaderContext alc)
63 {
64 var mr = alc.RootGameObject.GetComponentInChildren<MeshRenderer>();
65 Vector3 objectSizes = mr.bounds.max - mr.bounds.min;
66 float objectSize = Mathf.Max(objectSizes.x, objectSizes.y, objectSizes.z);
67 float cameraView = 2.0f * Mathf.Tan(0.5f * Mathf.Deg2Rad * Camera.main.fieldOfView); // Visible height 1 meter in front
68 float distance = 2.0f * objectSize / cameraView; // Combined wanted distance from the object
69 distance += 0.5f * objectSize; // Estimated offset from the center to the outside of the object
70 //Camera.main.transform.position = mr.bounds.center - distance * Camera.main.transform.forward;
71 //Camera.main.transform.rotation = Quaternion.Euler(new Vector3(0, 0, 0));
72 pb_SceneCamera.Focus(alc.RootGameObject.transform.position,distance);
73 if (modelEditor)
74 {
75 mr.gameObject.AddComponent<MeshInfo>();
76 }
77 LoadingManager.instance.HideWindow();
78 }, onError: OnError);
79 }
80 }));
81#endif
82 }
83
84 public void LoadFromMemory(byte[] data, string filename, GameObject wrapper = null, bool singleModel = false, bool global = false)
85 {
86 //Debug.Log($"Loading model '{filename}' now!");
87 var parent = pb_Scene.instance.gameObject;
88 if (wrapper)
89 parent = wrapper;
90
91#if TRILIB_2
92
93#else
94
95#endif
96
97#if !TRILIB_2
98 using (var assetLoader = new AssetLoader())
99#endif
100 {
101#if TRILIB_2
102 var assetLoaderOptions = AssetLoader.CreateDefaultLoaderOptions();
103#else
104 var assetLoaderOptions = AssetLoaderOptions.CreateInstance();
105 assetLoaderOptions.MaterialTransparencyMode = MaterialTransparencyMode.Cutout;
106 //assetLoaderOptions.MaterialTransparencyMode = MaterialTransparencyMode.Alpha;
107 //assetLoaderOptions.UseOriginalPositionRotationAndScale = true;
108 //assetLoaderOptions.DontLoadMaterials = MiscLogicManager.instance.LowMemoryMode;
109 assetLoaderOptions.AdvancedConfigs.Add(AssetAdvancedConfig.CreateConfig(AssetAdvancedPropertyClassNames.FBXImportPreservePivots, false));
110#endif
111 GameObject tea = null;
112 try
113 {
114#if TRILIB_2
115#if THREADEDLOADING
116 AssetLoader.LoadModelFromStream(new MemoryStream(data), assetLoaderOptions: assetLoaderOptions, wrapperGameObject: parent,
117 fileExtension: filename.Substring(filename.LastIndexOf('.') + 1).ToLower(), onLoad:
118 delegate(AssetLoaderContext alc)
119 {
120 tea = alc.RootGameObject;
121 //tea.transform.localScale *= 100;
122 try
123 {
124 tea.name = filename.Remove(0, filename.LastIndexOf("\\") + 1);
125 }
126 catch (Exception)
127 {
128 tea.name = filename;
129 }
130
131 var tc = tea.AddComponent<TagCloud>();
132 tc.filePath = filename;
133 tc.TryLoad();
134
135 ComponentAdder(tea);
136
137 var uf = tea.AddComponent<UploadedFile>();
138 uf.modelData = data;
139 uf.fileName = filename;
140
142 if (singleModel)
143 {
145 StartCoroutine(pb_PrefabBrowser.instance.RefreshPanel());
146 }
147 }, onError: OnError);
148#else
149
150 //Debug.Log("start loading data: " + data.Length);
151 var extension = filename.Substring(filename.LastIndexOf('.') + 1).ToLower();
152 AssetLoaderContext alc;
153
154 if (extension == "zip")
155 {
156 alc = AssetLoaderZip.LoadModelFromZipStreamNoThread(new MemoryStream(data), assetLoaderOptions: assetLoaderOptions, wrapperGameObject: parent,
157 fileExtension: extension, onError: OnError);
158 }
159 else
160 {
161 alc = AssetLoader.LoadModelFromStreamNoThread(new MemoryStream(data), assetLoaderOptions: assetLoaderOptions, wrapperGameObject: parent,
162 fileExtension: extension, onError: OnError, filename: filename);
163 }
164
165 tea = alc.RootGameObject;
166 //tea.transform.localScale *= 100;
167
168 //Debug.Log("load success: " + (tea != null).ToString());
169 if (!tea)
170 return;
171 //Debug.Log("load success: very true");
172
173 try
174 {
175 tea.name = filename.Remove(0, filename.LastIndexOf("\\") + 1);
176 }
177 catch (Exception)
178 {
179 tea.name = filename;
180 }
181
182 var tc = tea.AddComponent<TagCloud>();
183 tc.filePath = filename;
184 tc.TryLoad();
185
186 tea.AddComponent<RenameObject>();
187
188 ComponentAdder(tea);
189
190 var uf = tea.AddComponent<UploadedFile>();
191 uf.modelData = data;
192 uf.fileName = filename;
193 uf.global = global;
194
195 if (singleModel)
196 {
198 StartCoroutine(pb_PrefabBrowser.instance.RefreshPanel());
199 YesNoPopupManager.instance.ShowPopup("GLOBAL_UPLOAD", "GLOBAL_UPLOAD_TEXT", "GLOBAL", "LOCAL");
200 YesNoPopupManager.instance.InvokeOnNo(() =>
201 {
202 uf.global = false;
205
206 });
207 YesNoPopupManager.instance.InvokeOnYes(() =>
208 {
209 uf.global = true;
212 });
213 }
214 else
215 {
216 pb_PrefabBrowser.instance?.AddGameObject(tea, pb_PrefabBrowser.LoadPanel.Models, filename, global);
217 }
218#endif
219
220#else
221 //tea = assetLoader.LoadFromMemoryWithTextures(data, filename, assetLoaderOptions, parent);
222 tea = assetLoader.LoadFromMemory(data, filename, assetLoaderOptions, parent);
223#endif
224 }
225 catch (Exception e)
226 {
227 PopupManager.instance.ShowPopup("Error loading file", e.Message);
228 return;
229 }
230
231#if !TRILIB_2
232 try
233 {
234 tea.name = filename.Remove(0, filename.LastIndexOf("\\") + 1);
235 }
236 catch (Exception)
237 {
238 tea.name = filename;
239 }
240
241 var tc = tea.AddComponent<TagCloud>();
242 tc.filePath = filename;
243 tc.TryLoad();
244
245 if (Macro.IsInChild(tea.transform, "ForceDoubleSided"))
246 {
247 ShaderChanger.Change(GetComponentsInChildren<MeshRenderer>(), "Ciconia Studio/Double Sided/Standard/Diffuse Bump");
248 }
249
250 ComponentAdder(tea);
251
252 tea.AddComponent<RenameObject>();
253
255#endif
256 }
257 }
258
259#if TRILIB_2
260 private void OnError(IContextualizedError contextualizedError)
261 {
262 if (!LoadingManager.instance.MainLoading)
263 {
264 PopupManager.instance.ShowPopup("Error loading file", contextualizedError.GetInnerException().Message);
265 LoadingManager.instance.HideWindow();
266 }
267 }
268#endif
269 readonly List<Thread> workerThreads = new List<Thread>();
270
271 void ComponentAdder(GameObject go)
272 {
273 //go.isStatic = true; //Spawn as static
274 if (useAdvancedColliderGeneration)
275 {
276 if (go.GetComponent<MeshFilter>() && !go.GetComponent<Collider>())
277 {
278 var vhacd = go.AddComponent<VHACD>();
279 vhacd.m_parameters.InitFast();
280 Thread worker = new Thread(vhacd.GenerateConvexMeshes);
281 workerThreads.Add(worker);
282 worker.IsBackground = true;
283 worker.Start();
284 //vhacd.GenerateConvexMeshes();
285 }
286 }
287 else
288 {
289 if (go.GetComponent<MeshFilter>() && !go.GetComponent<Collider>())
290 {
291 var coll = go.AddComponent<MeshCollider>();
292 coll.convex = true;
293 }
294 if (go.GetComponent<MeshRenderer>()/* && !MiscLogicManager.instance.LowMemoryMode*/)
295 {
296 var mr = go.GetComponent<MeshRenderer>();
297 foreach (var material in mr.materials)
298 {
299 if (material.mainTexture == null)
300 {
301 material.mainTexture = Resources.Load<Texture>("2k_white");
302 }
303 if (material.HasProperty("_Glossiness"))
304 {
305 var smoothness = material.GetFloat("_Glossiness");
306 material.SetFloat("_Glossiness", Macro.MinMaxClamp(smoothness, 0f, 1f));
307 }
308 if (material.HasProperty("_Metallic"))
309 {
310 var smoothness = material.GetFloat("_Metallic");
311 material.SetFloat("_Metallic", Macro.MinMaxClamp(smoothness, 0f, 1f));
312 }
313 }
314 //var inkCanvas = go.AddComponent<InkCanvas>();
315 //BUG: memory leak lényegében túl sokat zabál
316 //TODO: csinálni egy Paintable flag-et, és/vagy fixelni a irdatlan memória használatát
317 }
318 }
319
320 for (int i = 0; i < go.transform.childCount; i++)
321 {
322 ComponentAdder(go.transform.GetChild(i).gameObject);
323 }
324 }
325
326 private void OnDestroy()
327 {
328 foreach (var thread in workerThreads)
329 {
330 try
331 {
332 thread.Abort();
333 }
334 catch (Exception)
335 {
336 // ignored
337 }
338 }
339 }
340
341 //[Button]
342 //void TestLoad1()
343 //{
344 // var parent = pb_Scene.instance.gameObject;
345 // using (var assetLoader = new AssetLoader())
346 // {
347 // var assetLoaderOptions = AssetLoaderOptions.CreateInstance(); //Creates the AssetLoaderOptions instance.
348 //
349 // var tea = assetLoader.LoadFromFile(@"E:\miniweb\htdocs\Halcon_Milenario.fbx", assetLoaderOptions, parent);
350 // pb?.AddGameObject(tea, pb_PrefabBrowser.LoadPanel.Models);
351 // }
352 //}
353}
TriLibCore.AssetLoaderOptions AssetLoaderOptions
Definition: TriLibLoader.cs:9
void StartLateRebuild(bool force=false)
static FileDragAndDrop instance
void AddGameObject(GameObject gobject, LoadPanel panel=LoadPanel.None, string filePath="", bool global=false)
static pb_PrefabBrowser instance
Definition: Macro.cs:12
static float MinMaxClamp(float value, float min, float max)
Definition: Macro.cs:337
static bool IsInChild(Transform t, string childName)
Definition: Macro.cs:552
void ModelFromURL(string url, bool modelEditor=false)
void LoadFromMemory(byte[] data, string filename, GameObject wrapper=null, bool singleModel=false, bool global=false)
static void Change(Material mat, string shaderName)
Definition: ShaderChanger.cs:7
string filePath
Definition: TagCloud.cs:11
byte[] modelData
Definition: UploadedFile.cs:7
Definition: VHACD.cs:10
Parameters m_parameters
Definition: VHACD.cs:145
Definition: ClipPainter.cs:5
void InitFast()
Definition: VHACD.cs:35