Tanoda
Preloader.cs
Go to the documentation of this file.
1using System;
2using System.Collections;
3using System.Collections.Generic;
4using System.IO;
5using System.Linq;
6using NaughtyAttributes;
7using UnityEngine;
8using UnityEngine.UI;
9#if !TRILIB_2
10using TriLib;
11#endif
12
13public class Preloader : MonoBehaviour
14{
15 public Text ProgressText;
16 public Slider ProgressBar;
17 public GameObject LoadRoot, LoadingCanvas;
18 private readonly Queue<Action> dispatcher = new Queue<Action>();
19 private readonly Dictionary<string, GameObject> loadedObjects = new Dictionary<string, GameObject>();
20 private string currentPath = "";
21 private bool loadingNow = false;
22 private bool stopLoading = false;
23 private short progress = 0;
24 private byte nextUnload = 1;
25#if UNITY_EDITOR
26 public bool EditorFastLoad = true;
27#endif
28
29#if !TRILIB_2
30
31 public bool HasFileLoaded(string filepath, out GameObject go)
32 {
33 if (loadedObjects.ContainsKey(filepath))
34 {
35 go = loadedObjects[filepath];
36 return true;
37 }
38 go = null;
39 return false;
40 }
41
42 public void StopLoading()
43 {
44 stopLoading = true;
45 }
46
47 void Start()
48 {
49 if (FindObjectsOfType<Preloader>().Length > 1)
50 {
51 Destroy(gameObject);
52 return;
53 }
54 DontDestroyOnLoad(gameObject);
55 Directory.CreateDirectory(Path.Combine(Application.streamingAssetsPath, "models"));
56 Directory.CreateDirectory(Path.Combine(Application.streamingAssetsPath, "pictures"));
57 Directory.CreateDirectory(Path.Combine(Application.streamingAssetsPath, "quizes"));
58 Directory.CreateDirectory(Path.Combine(Application.streamingAssetsPath, "sounds"));
59 Directory.CreateDirectory(Path.Combine(Application.streamingAssetsPath, "videos"));
60 Directory.CreateDirectory(Path.Combine(Application.streamingAssetsPath, "scripts"));
61 Directory.CreateDirectory(Path.Combine(Application.streamingAssetsPath, "helps"));
62#if UNITY_EDITOR
63 if (EditorFastLoad)
64 {
65 LoadingCanvas.SetActive(false);
66 return;
67 }
68#endif
69 var list = Directory.GetFiles(Application.streamingAssetsPath).ToList()
70 .Concat(Directory.GetFiles(Path.Combine(Application.streamingAssetsPath, "models")).ToList()
71 .Concat(Directory.GetFiles(Path.Combine(Application.streamingAssetsPath, "pictures")).ToList()));
72 var preloadFiles = new List<string>();
73 foreach (var s in list)
74 {
75 switch (s.Substring(s.LastIndexOf('.') + 1).ToLower())
76 {
77 case "png":
78 case "jpg":
79 case "jpeg":
80 case "bmp":
81 preloadFiles.Add(s);
82 break;
83 case "3d":
84 case "3ds":
85 case "3mf":
86 case "ac":
87 case "ac3d":
88 case "acc":
89 case "amf":
90 case "amj":
91 case "ase":
92 case "ask":
93 case "b3d":
94 case "blend":
95 case "bvh":
96 case "cob":
97 case "dae":
98 case "dxf":
99 case "enff":
100 case "fbx":
101#if !DANA
102 case "gltf":
103 case "glb":
104#endif
105 case "ifc":
106 case "irr":
107 case "irrmesh":
108 case "lwo":
109 case "lws":
110 case "lxo":
111 case "md2":
112 case "md3":
113 case "md5":
114 case "mdc":
115 case "mdl":
116 case "mesh":
117 case "xml":
118 case "mot":
119 case "ms3d":
120 case "ndo":
121 case "nff":
122 case "obj":
123 case "off":
124 case "ogex":
125 case "ply":
126 case "pmx":
127 case "prj":
128 case "q3o":
129 case "q3s":
130 case "raw":
131 case "scn":
132 case "sib":
133 case "smd":
134 case "stl":
135 case "ter":
136 case "uc":
137 case "vta":
138 case "x":
139 case "x3d":
140 case "xgl":
141 case "zgl":
142 preloadFiles.Add(s);
143 break;
144 default:
145 break;
146 }
147 }
148
149 StartCoroutine(WorkPreload(preloadFiles));
150 }
151 private bool IsPicture(string file)
152 {
153 var ext = Path.GetExtension(file).ToLower();
154 //Debug.Log(ext);
155 return ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".bmp";
156 }
157
158 private IEnumerator WorkPreload(IEnumerable<string> allFile)
159 {
160 var enumerable = allFile as string[] ?? allFile.ToArray();
161 ProgressText.text = $"{progress}/{enumerable.Count()}";
162 foreach (var s in enumerable)
163 {
164 yield return null;
165 while (loadingNow)
166 {
167 yield return null;
168 }
169
170 //long MonoUsedSize = UnityEngine.Profiling.Profiler.GetMonoUsedSizeLong();
171 long MonoHeapSize = UnityEngine.Profiling.Profiler.GetMonoHeapSizeLong();
172#if UNITY_EDITOR
173 //Debug.Log($"MonoUsedSize: {MonoUsedSize / 1024 / 1024}MB");
174 Debug.Log($"MonoHeapSize: {MonoHeapSize / 1024 / 1024}MB");
175 Debug.Log($"usedHeapSize: {UnityEngine.Profiling.Profiler.usedHeapSizeLong / 1024 / 1024}MB");
176#endif
177 if (stopLoading)
178 {
179 Resources.UnloadUnusedAssets();
180 yield return null;
181 GC.Collect();
182 yield return null;
183 LoadingCanvas.SetActive(false);
184 yield break;
185 }
186
187 progress++;
188 ProgressText.text = $"{progress}/{enumerable.Count()}";
189 if (IsPicture(s))
190 {
191 //var go = new GameObject(s.Substring(s.LastIndexOf('\\') + 1));
192 //var ri = go.AddComponent<RawImage>();
193 //go.GetComponent<RectTransform>().sizeDelta = Vector2.one;
194
195 var fileData = File.ReadAllBytes(s);
196 var filename = s.Substring(s.LastIndexOf('\\') + 1);
198 {
199 var tex = new Texture2D(1, 1);
200 tex.LoadImage(fileData);
202 }
203 //go.transform.SetParent(LoadRoot.transform);
204 //loadedObjects.Add(go.name, go);
205 }
206 else
207 {
208 LoadModel(s);
209 }
210 if (MonoHeapSize / 1024 / 1024 > 1024)
211 {
212 nextUnload--;
213 if (nextUnload <= 0)
214 {
215 nextUnload = 5;
216 continue;
217 }
218 Resources.UnloadUnusedAssets();
219 yield return null;
220 GC.Collect();
221 yield return null;
222 }
223 }
224 Resources.UnloadUnusedAssets();
225 GC.Collect();
226 yield return null;
227 LoadingCanvas.SetActive(false);
228 }
229
230 private void LoadModel(string path)
231 {
232 loadingNow = true;
233 currentPath = path;
234 using (var assetLoader = new AssetLoaderAsync())
235 {
236 var assetLoaderOptions = AssetLoaderOptions.CreateInstance();
237 assetLoaderOptions.MaterialTransparencyMode = MaterialTransparencyMode.Cutout;
238 assetLoaderOptions.AdvancedConfigs.Add(AssetAdvancedConfig.CreateConfig(AssetAdvancedPropertyClassNames.FBXImportPreservePivots, false));
239 var thread = assetLoader.LoadFromFile(path, assetLoaderOptions, LoadRoot, progressCallback: ProgressCallback, onAssetLoaded: OnLoadFinished);
240 }
241 }
242
243 private void ProgressCallback(float progress)
244 {
245 dispatcher.Enqueue(() =>
246 {
247 ProgressBar.value = progress;
248 });
249 }
250
251 private void OnLoadFinished(GameObject go)
252 {
253 try
254 {
255 go.name = currentPath.Remove(0, currentPath.LastIndexOf("\\") + 1);
256 }
257 catch (Exception)
258 {
259 go.name = currentPath;
260 }
261
262 try
263 {
264 loadedObjects.Add(go.name, go);
265 }
266 catch (Exception)
267 {
268 Debug.LogError("Same named models, can't load into dictionary!");
269 }
270
271 if (Macro.IsInChild(go.transform, "ForceDoubleSided"))
272 {
273 ShaderChanger.Change(go.GetComponentsInChildren<MeshRenderer>(), "Ciconia Studio/Double Sided/Standard/Diffuse Bump");
274 }
275
276 loadingNow = false;
277 }
278
279 public void Update()
280 {
281 while (dispatcher.Count > 0)
282 {
283 try
284 {
285 dispatcher?.Dequeue()();
286 }
287 catch (Exception)
288 {
289 // ignored
290 }
291 }
292 }
293
294#endif
295 }
UnityEngine.Debug Debug
Definition: TanodaServer.cs:19
TriLibCore.AssetLoaderOptions AssetLoaderOptions
Definition: TriLibLoader.cs:9
bool HasTexture(string filename)
void AddTexture(string filename, Texture2D texture)
static GlobalTextureHolder instance
Definition: Macro.cs:12
static bool IsInChild(Transform t, string childName)
Definition: Macro.cs:552
GameObject LoadRoot
Definition: Preloader.cs:17
Slider ProgressBar
Definition: Preloader.cs:16
void Update()
Definition: Preloader.cs:279
bool HasFileLoaded(string filepath, out GameObject go)
Definition: Preloader.cs:31
Text ProgressText
Definition: Preloader.cs:15
GameObject LoadingCanvas
Definition: Preloader.cs:17
void StopLoading()
Definition: Preloader.cs:42
static void Change(Material mat, string shaderName)
Definition: ShaderChanger.cs:7