ResourcesComponent.cs 20.4 KB
Newer Older
T
tanghai 已提交
1 2
using System;
using System.Collections.Generic;
T
tanghai 已提交
3
using System.IO;
4
using System.Linq;
5
using System.Text;
T
tanghai 已提交
6
using UnityEngine;
T
tanghai 已提交
7 8
#if UNITY_EDITOR
using UnityEditor;
9

T
tanghai 已提交
10
#endif
T
tanghai 已提交
11

12
namespace ET
T
tanghai 已提交
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
    [ObjectSystem]
    public class ABInfoAwakeSystem: AwakeSystem<ABInfo, string, AssetBundle>
    {
        public override void Awake(ABInfo self, string abName, AssetBundle a)
        {
            self.AssetBundle = a;
            self.Name = abName;
            self.RefCount = 1;
        }
    }

    [ObjectSystem]
    public class ABInfoDestroySystem: DestroySystem<ABInfo>
    {
        public override void Destroy(ABInfo self)
        {
            //Log.Debug($"desdroy assetbundle: {this.Name}");

            self.RefCount = 0;
            self.Name = "";
        }
    }

    public class ABInfo: Entity
    {
        public string Name
        {
            get;
            set;
        }

        public int RefCount
        {
            get;
            set;
        }

        public AssetBundle AssetBundle;

        public void Destroy(bool unload = true)
        {
            if (this.AssetBundle != null)
            {
                this.AssetBundle.Unload(unload);
            }

            this.Dispose();
        }
    }

    // 用于字符串转换,减少GC
    public static class AssetBundleHelper
    {
        public static string IntToString(this int value)
        {
            string result;
            if (ResourcesComponent.Instance.IntToStringDict.TryGetValue(value, out result))
            {
                return result;
            }

            result = value.ToString();
            ResourcesComponent.Instance.IntToStringDict[value] = result;
            return result;
        }

        public static string StringToAB(this string value)
        {
            string result;
            if (ResourcesComponent.Instance.StringToABDict.TryGetValue(value, out result))
            {
                return result;
            }

            result = value + ".unity3d";
            ResourcesComponent.Instance.StringToABDict[value] = result;
            return result;
        }

        public static string IntToAB(this int value)
        {
            return value.IntToString().StringToAB();
        }

        public static string BundleNameToLower(this string value)
        {
            string result;
            if (ResourcesComponent.Instance.BundleNameToLowerDict.TryGetValue(value, out result))
            {
                return result;
            }

            result = value.ToLower();
            ResourcesComponent.Instance.BundleNameToLowerDict[value] = result;
            return result;
        }
    }

    [ObjectSystem]
    public class ResourcesComponentAwakeSystem: AwakeSystem<ResourcesComponent>
    {
        public override void Awake(ResourcesComponent self)
        {
            self.Awake();
        }
    }

    public class ResourcesComponent: Entity
    {
        public static ResourcesComponent Instance
        {
            get;
            set;
        }

        public AssetBundleManifest AssetBundleManifestObject
        {
            get;
            set;
        }
        
        public Dictionary<int, string> IntToStringDict = new Dictionary<int, string>();

        public Dictionary<string, string> StringToABDict = new Dictionary<string, string>();

        public Dictionary<string, string> BundleNameToLowerDict = new Dictionary<string, string>() { { "StreamingAssets", "StreamingAssets" } };


        private readonly Dictionary<string, Dictionary<string, UnityEngine.Object>> resourceCache = new Dictionary<string, Dictionary<string, UnityEngine.Object>>();

        private readonly Dictionary<string, ABInfo> bundles = new Dictionary<string, ABInfo>();

        public void Awake()
        {
            Instance = this;
149
            
150 151 152 153 154
            if (Define.IsAsync)
            {
			    LoadOneBundle("StreamingAssets");
			    AssetBundleManifestObject = (AssetBundleManifest)GetAsset("StreamingAssets", "AssetBundleManifest");
            }
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
        public override void Dispose()
        {
            if (this.IsDisposed)
            {
                return;
            }

            base.Dispose();

            Instance = null;

            foreach (KeyValuePair<string, ABInfo> abInfo in this.bundles)
            {
                abInfo.Value.Destroy();
            }

            this.bundles.Clear();
            this.resourceCache.Clear();
            this.IntToStringDict.Clear();
            this.StringToABDict.Clear();
            this.BundleNameToLowerDict.Clear();
        }

        private string[] GetDependencies(string assetBundleName, bool isScene = false)
        {
            string[] dependencies = new string[0];
            if (DependenciesCache.TryGetValue(assetBundleName, out dependencies))
            {
                return dependencies;
            }

            if (!Define.IsAsync)
            {
T
tanghai 已提交
190
#if UNITY_EDITOR
191 192 193 194
                if (isScene == false)
                {
                    dependencies = AssetDatabase.GetAssetBundleDependencies(assetBundleName, true);
                }
T
tanghai 已提交
195
#endif
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
            }
            else
            {
                dependencies = this.AssetBundleManifestObject.GetAllDependencies(assetBundleName);
            }

            DependenciesCache.Add(assetBundleName, dependencies);
            return dependencies;
        }

        public string[] GetSortedDependencies(string assetBundleName, bool isScene = false)
        {
            Dictionary<string, int> info = new Dictionary<string, int>();
            List<string> parents = new List<string>();
            CollectDependencies(parents, assetBundleName, info, isScene);
            string[] ss = info.OrderBy(x => x.Value).Select(x => x.Key).ToArray();
            return ss;
        }

        private void CollectDependencies(List<string> parents, string assetBundleName, Dictionary<string, int> info, bool isScene = false)
        {
            parents.Add(assetBundleName);
            string[] deps = GetDependencies(assetBundleName, isScene);
            foreach (string parent in parents)
            {
                if (!info.ContainsKey(parent))
                {
                    info[parent] = 0;
                }

                info[parent] += deps.Length;
            }

            foreach (string dep in deps)
            {
                if (parents.Contains(dep))
                {
                    throw new Exception($"包有循环依赖,请重新标记: {assetBundleName} {dep}");
                }

                CollectDependencies(parents, dep, info, isScene);
            }

            parents.RemoveAt(parents.Count - 1);
        }

        // 缓存包依赖,不用每次计算
243
        public Dictionary<string, string[]> DependenciesCache = new Dictionary<string, string[]>();
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

        public bool Contains(string bundleName)
        {
            return this.bundles.ContainsKey(bundleName);
        }

        public Dictionary<string, UnityEngine.Object> GetBundleAll(string bundleName)
        {
            Dictionary<string, UnityEngine.Object> dict;
            if (!this.resourceCache.TryGetValue(bundleName.BundleNameToLower(), out dict))
            {
                throw new Exception($"not found asset: {bundleName}");
            }

            return dict;
        }

        public UnityEngine.Object GetAsset(string bundleName, string prefab)
        {
            Dictionary<string, UnityEngine.Object> dict;
            if (!this.resourceCache.TryGetValue(bundleName.BundleNameToLower(), out dict))
            {
                throw new Exception($"not found asset: {bundleName} {prefab}");
            }

            UnityEngine.Object resource = null;
            if (!dict.TryGetValue(prefab, out resource))
            {
                throw new Exception($"not found asset: {bundleName} {prefab}");
            }

            return resource;
        }

        public async ETTask UnloadBundles(List<string> bundleList, bool unload = true)
        {
            int i = 0;
            foreach (string bundle in bundleList)
            {
                using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.Resources, bundle.GetHashCode()))
                {
                    if (++i % 5 == 0)
                    {
                        await TimerComponent.Instance.WaitFrameAsync();
                    }
                    this.UnloadBundle(bundle, unload);
                }
            }
        }

        // 只允许场景设置unload为false
        public void UnloadBundle(string assetBundleName, bool unload = true)
        {
            assetBundleName = assetBundleName.BundleNameToLower();

            string[] dependencies = GetSortedDependencies(assetBundleName);

            //Log.Debug($"-----------dep unload start {assetBundleName} dep: {dependencies.ToList().ListToString()}");
            foreach (string dependency in dependencies)
            {
                this.UnloadOneBundle(dependency, unload);
            }

            //Log.Debug($"-----------dep unload finish {assetBundleName} dep: {dependencies.ToList().ListToString()}");
        }

        private void UnloadOneBundle(string assetBundleName, bool unload = true)
        {
            assetBundleName = assetBundleName.BundleNameToLower();

            ABInfo abInfo;
            if (!this.bundles.TryGetValue(assetBundleName, out abInfo))
            {
                return;
            }

            //Log.Debug($"---------------unload one bundle {assetBundleName} refcount: {abInfo.RefCount - 1}");

            --abInfo.RefCount;

            if (abInfo.RefCount > 0)
            {
                return;
            }
            
            //Log.Debug($"---------------truly unload one bundle {assetBundleName} refcount: {abInfo.RefCount}");
            this.bundles.Remove(assetBundleName);
            this.resourceCache.Remove(assetBundleName);
            abInfo.Destroy(unload);
            // Log.Debug($"cache count: {this.cacheDictionary.Count}");
        }

        /// <summary>
        /// 同步加载assetbundle
        /// </summary>
        /// <param name="assetBundleName"></param>
        /// <returns></returns>
        public void LoadBundle(string assetBundleName)
        {
343
            assetBundleName = assetBundleName.ToLower();
344 345 346

            string[] dependencies = GetSortedDependencies(assetBundleName);
            //Log.Debug($"-----------dep load start {assetBundleName} dep: {dependencies.ToList().ListToString()}");
347
            foreach (string dependency in dependencies)
348 349 350 351 352 353 354 355 356 357
            {
                if (string.IsNullOrEmpty(dependency))
                {
                    continue;
                }

                this.LoadOneBundle(dependency);
            }

            //Log.Debug($"-----------dep load finish {assetBundleName} dep: {dependencies.ToList().ListToString()}");
358
        }
T
tanghai 已提交
359

360 361 362 363 364 365 366 367
        public void AddResource(string bundleName, string assetName, UnityEngine.Object resource)
        {
            Dictionary<string, UnityEngine.Object> dict;
            if (!this.resourceCache.TryGetValue(bundleName.BundleNameToLower(), out dict))
            {
                dict = new Dictionary<string, UnityEngine.Object>();
                this.resourceCache[bundleName] = dict;
            }
T
tanghai 已提交
368

369 370 371 372 373 374 375 376 377 378 379 380 381 382
            dict[assetName] = resource;
        }

        private void LoadOneBundle(string assetBundleName)
        {
            assetBundleName = assetBundleName.BundleNameToLower();
            ABInfo abInfo;
            if (this.bundles.TryGetValue(assetBundleName, out abInfo))
            {
                ++abInfo.RefCount;
                //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
                return;
            }
            
383
            if (!Define.IsAsync)
384 385
            {
                string[] realPath = null;
T
tanghai 已提交
386
#if UNITY_EDITOR
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
                realPath = AssetDatabase.GetAssetPathsFromAssetBundle(assetBundleName);
                foreach (string s in realPath)
                {
                    string assetName = Path.GetFileNameWithoutExtension(s);
                    UnityEngine.Object resource = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(s);
                    AddResource(assetBundleName, assetName, resource);
                }

            
              
                if (realPath.Length > 0)
                {
                    abInfo = EntityFactory.CreateWithParent<ABInfo, string, AssetBundle>(this, assetBundleName, null);
                    this.bundles[assetBundleName] = abInfo;
                    //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
                }
                else
                {
                    Log.Error($"assets bundle not found: {assetBundleName}");
                }
T
tanghai 已提交
407
#endif
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
                return;
            }

            string p = Path.Combine(PathHelper.AppHotfixResPath, assetBundleName);
            AssetBundle assetBundle = null;
            if (File.Exists(p))
            {
                assetBundle = AssetBundle.LoadFromFile(p);
            }
            else
            {
                p = Path.Combine(PathHelper.AppResPath, assetBundleName);
                assetBundle = AssetBundle.LoadFromFile(p);
            }

            if (assetBundle == null)
            {
                // 获取资源的时候会抛异常,这个地方不直接抛异常,因为有些地方需要Load之后判断是否Load成功
                Log.Warning($"assets bundle not found: {assetBundleName}");
                return;
            }

            if (!assetBundle.isStreamedSceneAssetBundle)
            {
                // 异步load资源到内存cache住
                UnityEngine.Object[] assets = assetBundle.LoadAllAssets();
                foreach (UnityEngine.Object asset in assets)
                {
                    AddResource(assetBundleName, asset.name, asset);
                }
            }

            abInfo = EntityFactory.CreateWithParent<ABInfo, string, AssetBundle>(this, assetBundleName, assetBundle);
            this.bundles[assetBundleName] = abInfo;
            
            //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
        }

        /// <summary>
        /// 异步加载assetbundle
        /// </summary>
        /// <param name="assetBundleName"></param>
        /// <param name="isScene"></param>
        /// <returns></returns>
        public async ETTask LoadBundleAsync(string assetBundleName, bool isScene = false)
        {
            assetBundleName = assetBundleName.BundleNameToLower();
            
            string[] dependencies = GetSortedDependencies(assetBundleName);
            //Log.Debug($"-----------dep load async start {assetBundleName} dep: {dependencies.ToList().ListToString()}");
458 459 460 461 462 463 464 465
            using var tasts = ListComponent<ETTask>.Create();
            async ETTask loadDependency(string dependency)
            {
                using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.Resources, dependency.GetHashCode()))
                {
                    await this.LoadOneBundleAsync(dependency, isScene);
                }
            }
466 467 468 469 470 471
            foreach (string dependency in dependencies)
            {
                if (string.IsNullOrEmpty(dependency))
                {
                    continue;
                }
472
                tasts.List.Add(loadDependency(dependency));
473
            }
474
            await ETTaskHelper.WaitAll(tasts.List);
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
        }
        
        private async ETTask LoadOneBundleAsync(string assetBundleName, bool isScene)
        {
            assetBundleName = assetBundleName.BundleNameToLower();
            ABInfo abInfo;
            if (this.bundles.TryGetValue(assetBundleName, out abInfo))
            {
                ++abInfo.RefCount;
                //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
                return;
            }

            string p = "";
            AssetBundle assetBundle = null;
            
            if (!Define.IsAsync)
            {
#if UNITY_EDITOR

                if (isScene)
                {
497
                    p = Path.Combine(Application.dataPath, "../SceneBundle/", assetBundleName);
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
                    if (File.Exists(p)) // 如果场景有预先打包
                    {
                        using (AssetsBundleLoaderAsync assetsBundleLoaderAsync = EntityFactory.CreateWithParent<AssetsBundleLoaderAsync>(this))
                        {
                            assetBundle = await assetsBundleLoaderAsync.LoadAsync(p);
                        }

                        if (assetBundle == null)
                        {
                            // 获取资源的时候会抛异常,这个地方不直接抛异常,因为有些地方需要Load之后判断是否Load成功
                            Log.Warning($"Scene bundle not found: {assetBundleName}");
                            return;
                        }
                        
                        abInfo = EntityFactory.CreateWithParent<ABInfo, string, AssetBundle>(this, assetBundleName, assetBundle);
                        this.bundles[assetBundleName] = abInfo;
                    }
                }
                else
                {
                    string[] realPath = AssetDatabase.GetAssetPathsFromAssetBundle(assetBundleName);
                    foreach (string s in realPath)
                    {
                        string assetName = Path.GetFileNameWithoutExtension(s);
                        UnityEngine.Object resource = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(s);
                        AddResource(assetBundleName, assetName, resource);
                    }

                    if (realPath.Length > 0)
                    {
                        abInfo = EntityFactory.CreateWithParent<ABInfo, string, AssetBundle>(this, assetBundleName, null);
                        this.bundles[assetBundleName] = abInfo;
                        //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
                    }
                    else
                    {
                        Log.Error("Bundle not exist! BundleName: " + assetBundleName);
                    }
                }
                // 编辑器模式也不能同步加载
                await TimerComponent.Instance.WaitAsync(20);
#endif
                return;
            }

            
            p = Path.Combine(PathHelper.AppHotfixResPath, assetBundleName);
            if (!File.Exists(p))
            {
                p = Path.Combine(PathHelper.AppResPath, assetBundleName);
            }

            if (!File.Exists(p))
            {
                Log.Error("Async load bundle not exist! BundleName : " + p);
                return;
            }

            using (AssetsBundleLoaderAsync assetsBundleLoaderAsync = EntityFactory.CreateWithParent<AssetsBundleLoaderAsync>(this))
            {
                assetBundle = await assetsBundleLoaderAsync.LoadAsync(p);
            }

            if (assetBundle == null)
            {
                // 获取资源的时候会抛异常,这个地方不直接抛异常,因为有些地方需要Load之后判断是否Load成功
                Log.Warning($"assets bundle not found: {assetBundleName}");
                return;
            }

            if (!assetBundle.isStreamedSceneAssetBundle)
            {
                // 异步load资源到内存cache住
                UnityEngine.Object[] assets;
                using (AssetsLoaderAsync assetsLoaderAsync = EntityFactory.CreateWithParent<AssetsLoaderAsync, AssetBundle>(this, assetBundle))
                {
                    assets = await assetsLoaderAsync.LoadAllAssetsAsync();
                }

                foreach (UnityEngine.Object asset in assets)
                {
                    AddResource(assetBundleName, asset.name, asset);
                }
            }

            abInfo = EntityFactory.CreateWithParent<ABInfo, string, AssetBundle>(this, assetBundleName, assetBundle);
            this.bundles[assetBundleName] = abInfo;
            
            //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
        }

        public string DebugString()
        {
            StringBuilder sb = new StringBuilder();
            foreach (ABInfo abInfo in this.bundles.Values)
            {
                sb.Append($"{abInfo.Name}:{abInfo.RefCount}\n");
            }

            return sb.ToString();
        }
    }
T
tanghai 已提交
600
}