Update runtime code

重构原生文件加载流程。
pull/51/head
hevinci 2022-11-19 17:54:09 +08:00
parent 9394ff49fd
commit 29b3ca4e69
22 changed files with 592 additions and 594 deletions

View File

@ -8,7 +8,7 @@ namespace YooAsset
{
internal class AssetSystemImpl
{
private readonly List<AssetBundleLoaderBase> _loaders = new List<AssetBundleLoaderBase>(1000);
private readonly List<BundleLoaderBase> _loaders = new List<BundleLoaderBase>(1000);
private readonly List<ProviderBase> _providers = new List<ProviderBase>(1000);
private readonly static Dictionary<string, SceneOperationHandle> _sceneHandles = new Dictionary<string, SceneOperationHandle>(100);
private static long _sceneCreateCount = 0;
@ -69,6 +69,15 @@ namespace YooAsset
/// </summary>
public void DestroyAll()
{
foreach (var provider in _providers)
{
provider.Destroy();
}
foreach (var loader in _loaders)
{
loader.Destroy(true);
}
_providers.Clear();
_loaders.Clear();
ClearSceneHandle();
@ -97,12 +106,12 @@ namespace YooAsset
{
for (int i = _loaders.Count - 1; i >= 0; i--)
{
AssetBundleLoaderBase loader = _loaders[i];
BundleLoaderBase loader = _loaders[i];
loader.TryDestroyAllProviders();
}
for (int i = _loaders.Count - 1; i >= 0; i--)
{
AssetBundleLoaderBase loader = _loaders[i];
BundleLoaderBase loader = _loaders[i];
if (loader.CanDestroy())
{
loader.Destroy(false);
@ -141,7 +150,7 @@ namespace YooAsset
{
if (assetInfo.IsInvalid)
{
YooLogger.Error($"Failed to load scene. {assetInfo.Error}");
YooLogger.Error($"Failed to load scene ! {assetInfo.Error}");
CompletedProvider completedProvider = new CompletedProvider(assetInfo);
completedProvider.SetCompleted(assetInfo.Error);
return completedProvider.CreateHandle<SceneOperationHandle>();
@ -178,7 +187,7 @@ namespace YooAsset
{
if (assetInfo.IsInvalid)
{
YooLogger.Error($"Failed to load asset. {assetInfo.Error}");
YooLogger.Error($"Failed to load asset ! {assetInfo.Error}");
CompletedProvider completedProvider = new CompletedProvider(assetInfo);
completedProvider.SetCompleted(assetInfo.Error);
return completedProvider.CreateHandle<AssetOperationHandle>();
@ -205,7 +214,7 @@ namespace YooAsset
{
if (assetInfo.IsInvalid)
{
YooLogger.Error($"Failed to load sub assets. {assetInfo.Error}");
YooLogger.Error($"Failed to load sub assets ! {assetInfo.Error}");
CompletedProvider completedProvider = new CompletedProvider(assetInfo);
completedProvider.SetCompleted(assetInfo.Error);
return completedProvider.CreateHandle<SubAssetsOperationHandle>();
@ -225,6 +234,33 @@ namespace YooAsset
return provider.CreateHandle<SubAssetsOperationHandle>();
}
/// <summary>
/// 加载原生文件
/// </summary>
public RawFileOperationHandle LoadRawFileAsync(AssetInfo assetInfo)
{
if (assetInfo.IsInvalid)
{
YooLogger.Error($"Failed to load raw file ! {assetInfo.Error}");
CompletedProvider completedProvider = new CompletedProvider(assetInfo);
completedProvider.SetCompleted(assetInfo.Error);
return completedProvider.CreateHandle<RawFileOperationHandle>();
}
string providerGUID = assetInfo.GUID;
ProviderBase provider = TryGetProvider(providerGUID);
if (provider == null)
{
if (_simulationOnEditor)
provider = new DatabaseRawFileProvider(this, providerGUID, assetInfo);
else
provider = new BundledRawFileProvider(this, providerGUID, assetInfo);
provider.InitSpawnDebugInfo();
_providers.Add(provider);
}
return provider.CreateHandle<RawFileOperationHandle>();
}
internal void UnloadSubScene(ProviderBase provider)
{
string providerGUID = provider.ProviderGUID;
@ -269,18 +305,18 @@ namespace YooAsset
}
}
internal AssetBundleLoaderBase CreateOwnerAssetBundleLoader(AssetInfo assetInfo)
internal BundleLoaderBase CreateOwnerAssetBundleLoader(AssetInfo assetInfo)
{
BundleInfo bundleInfo = BundleServices.GetBundleInfo(assetInfo);
return CreateAssetBundleLoaderInternal(bundleInfo);
}
internal List<AssetBundleLoaderBase> CreateDependAssetBundleLoaders(AssetInfo assetInfo)
internal List<BundleLoaderBase> CreateDependAssetBundleLoaders(AssetInfo assetInfo)
{
BundleInfo[] depends = BundleServices.GetAllDependBundleInfos(assetInfo);
List<AssetBundleLoaderBase> result = new List<AssetBundleLoaderBase>(depends.Length);
List<BundleLoaderBase> result = new List<BundleLoaderBase>(depends.Length);
foreach (var bundleInfo in depends)
{
AssetBundleLoaderBase dependLoader = CreateAssetBundleLoaderInternal(bundleInfo);
BundleLoaderBase dependLoader = CreateAssetBundleLoaderInternal(bundleInfo);
result.Add(dependLoader);
}
return result;
@ -293,10 +329,10 @@ namespace YooAsset
}
}
private AssetBundleLoaderBase CreateAssetBundleLoaderInternal(BundleInfo bundleInfo)
private BundleLoaderBase CreateAssetBundleLoaderInternal(BundleInfo bundleInfo)
{
// 如果加载器已经存在
AssetBundleLoaderBase loader = TryGetAssetBundleLoader(bundleInfo.Bundle.BundleName);
BundleLoaderBase loader = TryGetAssetBundleLoader(bundleInfo.Bundle.BundleName);
if (loader != null)
return loader;
@ -304,18 +340,21 @@ namespace YooAsset
#if UNITY_WEBGL
loader = new AssetBundleWebLoader(this, bundleInfo);
#else
if (bundleInfo.Bundle.IsRawFile)
loader = new RawBundleFileLoader(this, bundleInfo);
else
loader = new AssetBundleFileLoader(this, bundleInfo);
#endif
_loaders.Add(loader);
return loader;
}
private AssetBundleLoaderBase TryGetAssetBundleLoader(string bundleName)
private BundleLoaderBase TryGetAssetBundleLoader(string bundleName)
{
AssetBundleLoaderBase loader = null;
BundleLoaderBase loader = null;
for (int i = 0; i < _loaders.Count; i++)
{
AssetBundleLoaderBase temp = _loaders[i];
BundleLoaderBase temp = _loaders[i];
if (temp.MainBundleInfo.Bundle.BundleName.Equals(bundleName))
{
loader = temp;

View File

@ -0,0 +1,95 @@
using System.IO;
using System.Text;
namespace YooAsset
{
public class RawFileOperationHandle : OperationHandleBase
{
private System.Action<RawFileOperationHandle> _callback;
internal RawFileOperationHandle(ProviderBase provider) : base(provider)
{
}
internal override void InvokeCallback()
{
_callback?.Invoke(this);
}
/// <summary>
/// 完成委托
/// </summary>
public event System.Action<RawFileOperationHandle> Completed
{
add
{
if (IsValid == false)
throw new System.Exception($"{nameof(RawFileOperationHandle)} is invalid");
if (Provider.IsDone)
value.Invoke(this);
else
_callback += value;
}
remove
{
if (IsValid == false)
throw new System.Exception($"{nameof(RawFileOperationHandle)} is invalid");
_callback -= value;
}
}
/// <summary>
/// 等待异步执行完毕
/// </summary>
public void WaitForAsyncComplete()
{
if (IsValid == false)
return;
Provider.WaitForAsyncComplete();
}
/// <summary>
/// 释放资源句柄
/// </summary>
public void Release()
{
this.ReleaseInternal();
}
/// <summary>
/// 获取原生文件的二进制数据
/// </summary>
public byte[] GetRawFileData()
{
if (IsValid == false)
return null;
string filePath = Provider.RawFilePath;
if (File.Exists(filePath) == false)
return null;
return File.ReadAllBytes(filePath);
}
/// <summary>
/// 获取原生文件的文本数据
/// </summary>
public string GetRawFileText()
{
if (IsValid == false)
return null;
string filePath = Provider.RawFilePath;
if (File.Exists(filePath) == false)
return null;
return File.ReadAllText(filePath, Encoding.UTF8);
}
/// <summary>
/// 获取原生文件的路径
/// </summary>
public string GetRawFilePath()
{
if (IsValid == false)
return string.Empty;
return Provider.RawFilePath;
}
}
}

View File

@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: e26f14db9addb4c49b4f0f520bf75d9d
guid: e8420ba734d425a4ba9f19173d74503c
MonoImporter:
externalObjects: {}
serializedVersion: 2

View File

@ -6,7 +6,7 @@ using UnityEngine;
namespace YooAsset
{
internal sealed class AssetBundleFileLoader : AssetBundleLoaderBase
internal sealed class AssetBundleFileLoader : BundleLoaderBase
{
private enum ESteps
{
@ -21,7 +21,6 @@ namespace YooAsset
}
private ESteps _steps = ESteps.None;
private string _fileLoadPath;
private bool _isWaitForAsyncComplete = false;
private bool _isShowWaitForAsyncError = false;
private DownloaderBase _unpacker;
@ -47,7 +46,7 @@ namespace YooAsset
if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromRemote)
{
_steps = ESteps.Download;
_fileLoadPath = MainBundleInfo.Bundle.CachedFilePath;
FileLoadPath = MainBundleInfo.Bundle.CachedFilePath;
}
else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromStreaming)
{
@ -56,22 +55,22 @@ namespace YooAsset
if (loadMethod == EBundleLoadMethod.LoadFromMemory || loadMethod == EBundleLoadMethod.LoadFromStream)
{
_steps = ESteps.Unpack;
_fileLoadPath = MainBundleInfo.Bundle.CachedFilePath;
FileLoadPath = MainBundleInfo.Bundle.CachedFilePath;
}
else
{
_steps = ESteps.LoadFile;
_fileLoadPath = MainBundleInfo.Bundle.StreamingFilePath;
FileLoadPath = MainBundleInfo.Bundle.StreamingFilePath;
}
#else
_steps = ESteps.LoadFile;
_fileLoadPath = MainBundleInfo.Bundle.StreamingFilePath;
FileLoadPath = MainBundleInfo.Bundle.StreamingFilePath;
#endif
}
else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromCache)
{
_steps = ESteps.LoadFile;
_fileLoadPath = MainBundleInfo.Bundle.CachedFilePath;
FileLoadPath = MainBundleInfo.Bundle.CachedFilePath;
}
else
{
@ -137,11 +136,11 @@ namespace YooAsset
{
#if UNITY_EDITOR
// 注意Unity2017.4编辑器模式下如果AssetBundle文件不存在会导致编辑器崩溃这里做了预判。
if (System.IO.File.Exists(_fileLoadPath) == false)
if (System.IO.File.Exists(FileLoadPath) == false)
{
_steps = ESteps.Done;
Status = EStatus.Failed;
LastError = $"Not found assetBundle file : {_fileLoadPath}";
LastError = $"Not found assetBundle file : {FileLoadPath}";
YooLogger.Error(LastError);
return;
}
@ -152,9 +151,9 @@ namespace YooAsset
if (loadMethod == EBundleLoadMethod.Normal)
{
if (_isWaitForAsyncComplete)
CacheBundle = AssetBundle.LoadFromFile(_fileLoadPath);
CacheBundle = AssetBundle.LoadFromFile(FileLoadPath);
else
_createRequest = AssetBundle.LoadFromFileAsync(_fileLoadPath);
_createRequest = AssetBundle.LoadFromFileAsync(FileLoadPath);
}
else
{
@ -169,15 +168,15 @@ namespace YooAsset
DecryptFileInfo fileInfo = new DecryptFileInfo();
fileInfo.BundleName = MainBundleInfo.Bundle.BundleName;
fileInfo.FilePath = _fileLoadPath;
fileInfo.FilePath = FileLoadPath;
if (loadMethod == EBundleLoadMethod.LoadFromFileOffset)
{
ulong offset = Impl.DecryptionServices.LoadFromFileOffset(fileInfo);
if (_isWaitForAsyncComplete)
CacheBundle = AssetBundle.LoadFromFile(_fileLoadPath, 0, offset);
CacheBundle = AssetBundle.LoadFromFile(FileLoadPath, 0, offset);
else
_createRequest = AssetBundle.LoadFromFileAsync(_fileLoadPath, 0, offset);
_createRequest = AssetBundle.LoadFromFileAsync(FileLoadPath, 0, offset);
}
else if (loadMethod == EBundleLoadMethod.LoadFromMemory)
{
@ -279,6 +278,14 @@ namespace YooAsset
int frame = 1000;
while (true)
{
// 文件解压
if (_unpacker != null)
{
_unpacker.Update();
if (_unpacker.IsDone() == false)
continue;
}
// 保险机制
// 注意如果需要从WEB端下载资源可能会触发保险机制
frame--;

View File

@ -7,7 +7,7 @@ using UnityEngine.Networking;
namespace YooAsset
{
internal sealed class AssetBundleWebLoader : AssetBundleLoaderBase
internal sealed class AssetBundleWebLoader : BundleLoaderBase
{
private enum ESteps
{
@ -24,7 +24,6 @@ namespace YooAsset
private ESteps _steps = ESteps.None;
private float _tryTimer = 0;
private string _fileLoadPath;
private bool _isShowWaitForAsyncError = false;
private DownloaderBase _downloader;
private UnityWebRequest _webRequest;
@ -48,17 +47,17 @@ namespace YooAsset
if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromRemote)
{
_steps = ESteps.Download;
_fileLoadPath = MainBundleInfo.Bundle.CachedFilePath;
FileLoadPath = MainBundleInfo.Bundle.CachedFilePath;
}
else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromStreaming)
{
_steps = ESteps.LoadWebFile;
_fileLoadPath = MainBundleInfo.Bundle.StreamingFilePath;
FileLoadPath = MainBundleInfo.Bundle.StreamingFilePath;
}
else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromCache)
{
_steps = ESteps.LoadCacheFile;
_fileLoadPath = MainBundleInfo.Bundle.CachedFilePath;
FileLoadPath = MainBundleInfo.Bundle.CachedFilePath;
}
else
{
@ -97,11 +96,11 @@ namespace YooAsset
{
#if UNITY_EDITOR
// 注意Unity2017.4编辑器模式下如果AssetBundle文件不存在会导致编辑器崩溃这里做了预判。
if (System.IO.File.Exists(_fileLoadPath) == false)
if (System.IO.File.Exists(FileLoadPath) == false)
{
_steps = ESteps.Done;
Status = EStatus.Failed;
LastError = $"Not found assetBundle file : {_fileLoadPath}";
LastError = $"Not found assetBundle file : {FileLoadPath}";
YooLogger.Error(LastError);
return;
}
@ -111,7 +110,7 @@ namespace YooAsset
var loadMethod = (EBundleLoadMethod)MainBundleInfo.Bundle.LoadMethod;
if (loadMethod == EBundleLoadMethod.Normal)
{
_createRequest = AssetBundle.LoadFromFileAsync(_fileLoadPath);
_createRequest = AssetBundle.LoadFromFileAsync(FileLoadPath);
}
else
{
@ -164,7 +163,7 @@ namespace YooAsset
if (_steps == ESteps.LoadWebFile)
{
var hash = Hash128.Parse(MainBundleInfo.Bundle.FileHash);
_webRequest = UnityWebRequestAssetBundle.GetAssetBundle(_fileLoadPath, hash);
_webRequest = UnityWebRequestAssetBundle.GetAssetBundle(FileLoadPath, hash);
_webRequest.SendWebRequest();
_steps = ESteps.CheckLoadWebFile;
}
@ -181,7 +180,7 @@ namespace YooAsset
if (_webRequest.isNetworkError || _webRequest.isHttpError)
#endif
{
YooLogger.Warning($"Failed to get asset bundle from web : {_fileLoadPath} Error : {_webRequest.error}");
YooLogger.Warning($"Failed to get asset bundle from web : {FileLoadPath} Error : {_webRequest.error}");
_steps = ESteps.TryLoadWebFile;
_tryTimer = 0;
}

View File

@ -5,7 +5,7 @@ using UnityEngine;
namespace YooAsset
{
internal abstract class AssetBundleLoaderBase
internal abstract class BundleLoaderBase
{
public enum EStatus
{
@ -46,9 +46,10 @@ namespace YooAsset
private readonly List<ProviderBase> _providers = new List<ProviderBase>(100);
internal AssetBundle CacheBundle { set; get; }
internal string FileLoadPath { set; get; }
public AssetBundleLoaderBase(AssetSystemImpl impl, BundleInfo bundleInfo)
public BundleLoaderBase(AssetSystemImpl impl, BundleInfo bundleInfo)
{
Impl = impl;
MainBundleInfo = bundleInfo;

View File

@ -9,10 +9,10 @@ namespace YooAsset
/// <summary>
/// 依赖的资源包加载器列表
/// </summary>
private readonly List<AssetBundleLoaderBase> _dependBundles;
private readonly List<BundleLoaderBase> _dependBundles;
public DependAssetBundleGroup(List<AssetBundleLoaderBase> dpendBundles)
public DependAssetBundleGroup(List<BundleLoaderBase> dpendBundles)
{
_dependBundles = dpendBundles;
}
@ -37,7 +37,7 @@ namespace YooAsset
{
foreach (var loader in _dependBundles)
{
if (loader.Status != AssetBundleLoaderBase.EStatus.Succeed)
if (loader.Status != BundleLoaderBase.EStatus.Succeed)
{
return false;
}
@ -52,7 +52,7 @@ namespace YooAsset
{
foreach (var loader in _dependBundles)
{
if (loader.Status != AssetBundleLoaderBase.EStatus.Succeed)
if (loader.Status != BundleLoaderBase.EStatus.Succeed)
{
return loader.LastError;
}

View File

@ -0,0 +1,174 @@
using System.IO;
namespace YooAsset
{
internal class RawBundleFileLoader : BundleLoaderBase
{
private enum ESteps
{
None,
Download,
CheckDownload,
Unpack,
CheckUnpack,
CheckFile,
Done,
}
private ESteps _steps = ESteps.None;
private bool _isWaitForAsyncComplete = false;
private bool _isShowWaitForAsyncError = false;
private DownloaderBase _unpacker;
private DownloaderBase _downloader;
public RawBundleFileLoader(AssetSystemImpl impl, BundleInfo bundleInfo) : base(impl, bundleInfo)
{
}
/// <summary>
/// 轮询更新
/// </summary>
public override void Update()
{
if (_steps == ESteps.Done)
return;
if (_steps == ESteps.None)
{
if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromRemote)
{
_steps = ESteps.Download;
FileLoadPath = MainBundleInfo.Bundle.CachedFilePath;
}
else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromStreaming)
{
#if UNITY_ANDROID || UNITY_WEBGL
_steps = ESteps.Unpack;
FileLoadPath = MainBundleInfo.Bundle.CachedFilePath;
#else
_steps = ESteps.CheckFile;
FileLoadPath = MainBundleInfo.Bundle.StreamingFilePath;
#endif
}
else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromCache)
{
_steps = ESteps.CheckFile;
FileLoadPath = MainBundleInfo.Bundle.CachedFilePath;
}
else
{
throw new System.NotImplementedException(MainBundleInfo.LoadMode.ToString());
}
}
// 1. 下载远端文件
if (_steps == ESteps.Download)
{
int failedTryAgain = int.MaxValue;
_downloader = DownloadSystem.BeginDownload(MainBundleInfo, failedTryAgain);
_steps = ESteps.CheckDownload;
}
// 2. 检测下载结果
if (_steps == ESteps.CheckDownload)
{
if (_downloader.IsDone() == false)
return;
if (_downloader.HasError())
{
_steps = ESteps.Done;
Status = EStatus.Failed;
LastError = _downloader.GetLastError();
}
else
{
_steps = ESteps.CheckFile;
}
}
// 3. 解压内置文件
if (_steps == ESteps.Unpack)
{
int failedTryAgain = 1;
var bundleInfo = HostPlayModeImpl.ConvertToUnpackInfo(MainBundleInfo.Bundle);
_unpacker = DownloadSystem.BeginDownload(bundleInfo, failedTryAgain);
_steps = ESteps.CheckUnpack;
}
// 4. 检测解压结果
if (_steps == ESteps.CheckUnpack)
{
if (_unpacker.IsDone() == false)
return;
if (_unpacker.HasError())
{
_steps = ESteps.Done;
Status = EStatus.Failed;
LastError = _unpacker.GetLastError();
}
else
{
_steps = ESteps.CheckFile;
}
}
// 5. 检测结果
if (_steps == ESteps.CheckFile)
{
_steps = ESteps.Done;
if (File.Exists(FileLoadPath))
{
Status = EStatus.Succeed;
}
else
{
Status = EStatus.Failed;
LastError = $"Raw file not found : {FileLoadPath}";
}
}
}
/// <summary>
/// 主线程等待异步操作完毕
/// </summary>
public override void WaitForAsyncComplete()
{
_isWaitForAsyncComplete = true;
int frame = 1000;
while (true)
{
// 文件解压
if (_unpacker != null)
{
_unpacker.Update();
if (_unpacker.IsDone() == false)
continue;
}
// 保险机制
// 注意如果需要从WEB端下载资源可能会触发保险机制
frame--;
if (frame == 0)
{
if (_isShowWaitForAsyncError == false)
{
_isShowWaitForAsyncError = true;
YooLogger.Error($"WaitForAsyncComplete failed ! Try load bundle : {MainBundleInfo.Bundle.BundleName} from remote with sync load method !");
}
break;
}
// 驱动流程
Update();
// 完成后退出
if (IsDone())
break;
}
}
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: fa39f24727abe514093f18787c0c7e27
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -1,468 +0,0 @@
using System.IO;
namespace YooAsset
{
/// <summary>
/// 原生文件操作
/// </summary>
public abstract class RawFileOperation : AsyncOperationBase
{
internal readonly BundleInfo _bundleInfo;
/// <summary>
/// 原生文件的拷贝路径
/// </summary>
public string CopyPath { private set; get; }
internal RawFileOperation(BundleInfo bundleInfo, string copyPath)
{
_bundleInfo = bundleInfo;
CopyPath = copyPath;
}
/// <summary>
/// 原生文件的缓存路径
/// </summary>
public abstract string GetCachePath();
/// <summary>
/// 获取原生文件的二进制数据
/// </summary>
public byte[] LoadFileData()
{
string filePath = GetCachePath();
if (File.Exists(filePath) == false)
return null;
return File.ReadAllBytes(filePath);
}
/// <summary>
/// 获取原生文件的文本数据
/// </summary>
public string LoadFileText()
{
string filePath = GetCachePath();
if (File.Exists(filePath) == false)
return string.Empty;
return File.ReadAllText(filePath, System.Text.Encoding.UTF8);
}
}
/// <summary>
/// 发生错误的原生文件操作
/// </summary>
internal sealed class CompletedRawFileOperation : RawFileOperation
{
private readonly string _error;
internal CompletedRawFileOperation(string error, string copyPath) : base(null, copyPath)
{
_error = error;
}
internal override void Start()
{
Status = EOperationStatus.Failed;
Error = _error;
}
internal override void Update()
{
}
/// <summary>
/// 原生文件的缓存路径
/// </summary>
public override string GetCachePath()
{
return string.Empty;
}
}
/// <summary>
/// 编辑器下模拟运行的原生文件操作
/// </summary>
internal sealed class EditorPlayModeRawFileOperation : RawFileOperation
{
private enum ESteps
{
None,
Prepare,
CheckAndCopyFile,
Done,
}
private ESteps _steps = ESteps.None;
internal EditorPlayModeRawFileOperation(BundleInfo bundleInfo, string copyPath) : base(bundleInfo, copyPath)
{
}
internal override void Start()
{
_steps = ESteps.Prepare;
}
internal override void Update()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
// 1. 准备工作
if (_steps == ESteps.Prepare)
{
if (_bundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromEditor)
{
_steps = ESteps.CheckAndCopyFile;
return; // 模拟实现异步操作
}
else
{
throw new System.NotImplementedException(_bundleInfo.LoadMode.ToString());
}
}
// 2. 检测并拷贝原生文件
if (_steps == ESteps.CheckAndCopyFile)
{
// 如果不需要保存文件
if (string.IsNullOrEmpty(CopyPath))
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
return;
}
// 如果原生文件已经存在,则将其删除
if (File.Exists(CopyPath))
{
File.Delete(CopyPath);
}
try
{
FileUtility.CreateFileDirectory(CopyPath);
File.Copy(GetCachePath(), CopyPath, true);
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
catch (System.Exception e)
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = e.Message;
}
}
}
/// <summary>
/// 原生文件的缓存路径
/// </summary>
public override string GetCachePath()
{
if (_bundleInfo == null)
return string.Empty;
return _bundleInfo.EditorAssetPath;
}
}
/// <summary>
/// 离线模式的原生文件操作
/// </summary>
internal sealed class OfflinePlayModeRawFileOperation : RawFileOperation
{
private enum ESteps
{
None,
Prepare,
Unpack,
CheckUnpack,
CheckAndCopyFile,
Done,
}
private ESteps _steps = ESteps.None;
private DownloaderBase _unpacker;
public OfflinePlayModeRawFileOperation(BundleInfo bundleInfo, string copyPath) : base(bundleInfo, copyPath)
{
}
internal override void Start()
{
_steps = ESteps.Prepare;
}
internal override void Update()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
// 1. 准备工作
if (_steps == ESteps.Prepare)
{
if (_bundleInfo.LoadMode == BundleInfo.ELoadMode.None)
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"Bundle info is invalid : {_bundleInfo.Bundle.BundleName}";
}
else if (_bundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromStreaming)
{
_steps = ESteps.Unpack;
}
else if (_bundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromCache)
{
_steps = ESteps.CheckAndCopyFile;
}
else
{
throw new System.NotImplementedException(_bundleInfo.LoadMode.ToString());
}
}
// 2. 内置文件解压
if (_steps == ESteps.Unpack)
{
int failedTryAgain = 1;
var bundleInfo = HostPlayModeImpl.ConvertToUnpackInfo(_bundleInfo.Bundle);
_unpacker = DownloadSystem.BeginDownload(bundleInfo, failedTryAgain);
_steps = ESteps.CheckUnpack;
}
// 3. 检测内置文件解压结果
if (_steps == ESteps.CheckUnpack)
{
Progress = _unpacker.DownloadProgress;
if (_unpacker.IsDone() == false)
return;
if (_unpacker.HasError())
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = _unpacker.GetLastError();
}
else
{
_steps = ESteps.CheckAndCopyFile;
}
}
// 4. 检测并拷贝原生文件
if (_steps == ESteps.CheckAndCopyFile)
{
// 如果不需要保存文件
if (string.IsNullOrEmpty(CopyPath))
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
return;
}
// 如果原生文件已经存在,则验证其完整性
if (File.Exists(CopyPath))
{
var verifyResult = CacheSystem.VerifyContentInternal(CopyPath, _bundleInfo.Bundle.FileSize, _bundleInfo.Bundle.FileCRC, EVerifyLevel.High);
if (verifyResult == EVerifyResult.Succeed)
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
return;
}
else
{
File.Delete(CopyPath);
}
}
try
{
FileUtility.CreateFileDirectory(CopyPath);
File.Copy(GetCachePath(), CopyPath, true);
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
catch (System.Exception e)
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = e.Message;
}
}
}
/// <summary>
/// 原生文件的缓存路径
/// </summary>
public override string GetCachePath()
{
if (_bundleInfo == null)
return string.Empty;
return _bundleInfo.Bundle.CachedFilePath;
}
}
/// <summary>
/// 联机模式的原生文件操作
/// </summary>
internal sealed class HostPlayModeRawFileOperation : RawFileOperation
{
private enum ESteps
{
None,
Prepare,
Download,
CheckDownload,
Unpack,
CheckUnpack,
CheckAndCopyFile,
Done,
}
private ESteps _steps = ESteps.None;
private DownloaderBase _unpacker;
private DownloaderBase _downloader;
internal HostPlayModeRawFileOperation(BundleInfo bundleInfo, string copyPath) : base(bundleInfo, copyPath)
{
}
internal override void Start()
{
_steps = ESteps.Prepare;
}
internal override void Update()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
// 1. 准备工作
if (_steps == ESteps.Prepare)
{
if (_bundleInfo.LoadMode == BundleInfo.ELoadMode.None)
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"Bundle info is invalid : {_bundleInfo.Bundle.BundleName}";
}
else if (_bundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromRemote)
{
_steps = ESteps.Download;
}
else if (_bundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromStreaming)
{
_steps = ESteps.Unpack;
}
else if (_bundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromCache)
{
_steps = ESteps.CheckAndCopyFile;
}
else
{
throw new System.NotImplementedException(_bundleInfo.LoadMode.ToString());
}
}
// 2. 下载远端文件
if (_steps == ESteps.Download)
{
int failedTryAgain = int.MaxValue;
_downloader = DownloadSystem.BeginDownload(_bundleInfo, failedTryAgain);
_steps = ESteps.CheckDownload;
}
// 3. 检测下载结果
if (_steps == ESteps.CheckDownload)
{
Progress = _downloader.DownloadProgress;
if (_downloader.IsDone() == false)
return;
if (_downloader.HasError())
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = _downloader.GetLastError();
}
else
{
_steps = ESteps.CheckAndCopyFile;
}
}
// 3. 解压内置文件
if (_steps == ESteps.Unpack)
{
int failedTryAgain = 1;
var bundleInfo = HostPlayModeImpl.ConvertToUnpackInfo(_bundleInfo.Bundle);
_unpacker = DownloadSystem.BeginDownload(bundleInfo, failedTryAgain);
_steps = ESteps.CheckUnpack;
}
// 4. 检测解压结果
if (_steps == ESteps.CheckUnpack)
{
Progress = _unpacker.DownloadProgress;
if (_unpacker.IsDone() == false)
return;
if (_unpacker.HasError())
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = _unpacker.GetLastError();
}
else
{
_steps = ESteps.CheckAndCopyFile;
}
}
// 5. 检测并拷贝原生文件
if (_steps == ESteps.CheckAndCopyFile)
{
// 如果不需要保存文件
if (string.IsNullOrEmpty(CopyPath))
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
return;
}
// 如果原生文件已经存在,则验证其完整性
if (File.Exists(CopyPath))
{
var verifyResult = CacheSystem.VerifyContentInternal(CopyPath, _bundleInfo.Bundle.FileSize, _bundleInfo.Bundle.FileCRC, EVerifyLevel.High);
if (verifyResult == EVerifyResult.Succeed)
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
return;
}
else
{
File.Delete(CopyPath);
}
}
try
{
FileUtility.CreateFileDirectory(CopyPath);
File.Copy(GetCachePath(), CopyPath, true);
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
catch (System.Exception e)
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = e.Message;
}
}
}
/// <summary>
/// 原生文件的缓存路径
/// </summary>
public override string GetCachePath()
{
if (_bundleInfo == null)
return string.Empty;
return _bundleInfo.Bundle.CachedFilePath;
}
}
}

View File

@ -54,7 +54,7 @@ namespace YooAsset
return;
}
if (OwnerBundle.Status != AssetBundleLoaderBase.EStatus.Succeed)
if (OwnerBundle.Status != BundleLoaderBase.EStatus.Succeed)
{
Status = EStatus.Fail;
LastError = OwnerBundle.LastError;

View File

@ -5,7 +5,7 @@ namespace YooAsset
{
internal abstract class BundledProvider : ProviderBase
{
protected AssetBundleLoaderBase OwnerBundle { private set; get; }
protected BundleLoaderBase OwnerBundle { private set; get; }
protected DependAssetBundleGroup DependBundleGroup { private set; get; }
public BundledProvider(AssetSystemImpl impl, string providerGUID, AssetInfo assetInfo) : base(impl, providerGUID, assetInfo)

View File

@ -0,0 +1,61 @@

namespace YooAsset
{
internal class BundledRawFileProvider : BundledProvider
{
public override float Progress
{
get
{
if (IsDone)
return 1f;
else
return 0;
}
}
public BundledRawFileProvider(AssetSystemImpl impl, string providerGUID, AssetInfo assetInfo) : base(impl, providerGUID, assetInfo)
{
}
public override void Update()
{
DebugRecording();
if (IsDone)
return;
if (Status == EStatus.None)
{
Status = EStatus.CheckBundle;
}
if (Status == EStatus.CheckBundle)
{
if (IsWaitForAsyncComplete)
{
OwnerBundle.WaitForAsyncComplete();
}
if (OwnerBundle.IsDone() == false)
return;
if (OwnerBundle.Status != BundleLoaderBase.EStatus.Succeed)
{
Status = EStatus.Fail;
LastError = OwnerBundle.LastError;
InvokeCompletion();
return;
}
Status = EStatus.Checking;
}
if (Status == EStatus.Checking)
{
RawFilePath = OwnerBundle.FileLoadPath;
Status = EStatus.Success;
InvokeCompletion();
}
}
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 8a00889582fd95446b103af1074fa6ba
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -58,7 +58,7 @@ namespace YooAsset
return;
}
if (OwnerBundle.Status != AssetBundleLoaderBase.EStatus.Succeed)
if (OwnerBundle.Status != BundleLoaderBase.EStatus.Succeed)
{
Status = EStatus.Fail;
LastError = OwnerBundle.LastError;

View File

@ -54,7 +54,7 @@ namespace YooAsset
return;
}
if (OwnerBundle.Status != AssetBundleLoaderBase.EStatus.Succeed)
if (OwnerBundle.Status != BundleLoaderBase.EStatus.Succeed)
{
Status = EStatus.Fail;
LastError = OwnerBundle.LastError;

View File

@ -0,0 +1,55 @@

namespace YooAsset
{
internal class DatabaseRawFileProvider : ProviderBase
{
public override float Progress
{
get
{
if (IsDone)
return 1f;
else
return 0;
}
}
public DatabaseRawFileProvider(AssetSystemImpl impl, string providerGUID, AssetInfo assetInfo) : base(impl, providerGUID, assetInfo)
{
}
public override void Update()
{
#if UNITY_EDITOR
if (IsDone)
return;
if (Status == EStatus.None)
{
// 检测资源文件是否存在
string guid = UnityEditor.AssetDatabase.AssetPathToGUID(MainAssetInfo.AssetPath);
if (string.IsNullOrEmpty(guid))
{
Status = EStatus.Fail;
LastError = $"Not found asset : {MainAssetInfo.AssetPath}";
YooLogger.Error(LastError);
InvokeCompletion();
return;
}
Status = EStatus.Checking;
// 注意:模拟异步加载效果提前返回
if (IsWaitForAsyncComplete == false)
return;
}
if(Status == EStatus.Checking)
{
RawFilePath = MainAssetInfo.AssetPath;
Status = EStatus.Success;
InvokeCompletion();
}
#endif
}
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 41d0e9bbc5a3a5b4e8b05d60d40d495a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -47,6 +47,11 @@ namespace YooAsset
/// </summary>
public UnityEngine.SceneManagement.Scene SceneObject { protected set; get; }
/// <summary>
/// 原生文件路径
/// </summary>
public string RawFilePath { protected set; get; }
/// <summary>
/// 当前的加载状态
@ -152,6 +157,8 @@ namespace YooAsset
handle = new SceneOperationHandle(this);
else if (typeof(T) == typeof(SubAssetsOperationHandle))
handle = new SubAssetsOperationHandle(this);
else if (typeof(T) == typeof(RawFileOperationHandle))
handle = new RawFileOperationHandle(this);
else
throw new System.NotImplementedException();

View File

@ -412,74 +412,63 @@ namespace YooAsset
#region 原生文件
/// <summary>
/// 异步获取原生文件
/// 同步加载原生文件
/// </summary>
/// <param name="location">资源的定位地址</param>
/// <param name="copyPath">拷贝路径</param>
public RawFileOperation GetRawFileAsync(string location, string copyPath = null)
/// <param name="assetInfo">资源信息</param>
public RawFileOperationHandle LoadRawFileSync(AssetInfo assetInfo)
{
DebugCheckInitialize();
AssetInfo assetInfo = ConvertLocationToAssetInfo(location, null);
return GetRawFileInternal(assetInfo, copyPath);
return LoadRawFileInternal(assetInfo, true);
}
/// <summary>
/// 异步获取原生文件
/// 同步加载原生文件
/// </summary>
/// <param name="assetInfo">资源信息</param>
/// <param name="copyPath">拷贝路径</param>
public RawFileOperation GetRawFileAsync(AssetInfo assetInfo, string copyPath = null)
/// <param name="location">资源的定位地址</param>
public RawFileOperationHandle LoadRawFileSync(string location)
{
DebugCheckInitialize();
return GetRawFileInternal(assetInfo, copyPath);
AssetInfo assetInfo = ConvertLocationToAssetInfo(location, null);
return LoadRawFileInternal(assetInfo, true);
}
/// <summary>
/// 异步加载原生文件
/// </summary>
/// <param name="assetInfo">资源信息</param>
public RawFileOperationHandle LoadRawFileAsync(AssetInfo assetInfo)
{
DebugCheckInitialize();
return LoadRawFileInternal(assetInfo, false);
}
/// <summary>
/// 异步加载原生文件
/// </summary>
/// <param name="location">资源的定位地址</param>
public RawFileOperationHandle LoadRawFileAsync(string location)
{
DebugCheckInitialize();
AssetInfo assetInfo = ConvertLocationToAssetInfo(location, null);
return LoadRawFileInternal(assetInfo, false);
}
private RawFileOperation GetRawFileInternal(AssetInfo assetInfo, string copyPath)
private RawFileOperationHandle LoadRawFileInternal(AssetInfo assetInfo, bool waitForAsyncComplete)
{
if (assetInfo.IsInvalid)
{
YooLogger.Error($"Failed to get raw file. {assetInfo.Error}");
RawFileOperation operation = new CompletedRawFileOperation(assetInfo.Error, copyPath);
OperationSystem.StartOperation(operation);
return operation;
}
BundleInfo bundleInfo = _bundleServices.GetBundleInfo(assetInfo);
#if UNITY_EDITOR
if (bundleInfo.Bundle.IsRawFile == false)
if (assetInfo.IsInvalid == false)
{
string error = $"Cannot load asset bundle file using {nameof(GetRawFileAsync)} method !";
YooLogger.Error(error);
RawFileOperation operation = new CompletedRawFileOperation(error, copyPath);
OperationSystem.StartOperation(operation);
return operation;
BundleInfo bundleInfo = _bundleServices.GetBundleInfo(assetInfo);
if (bundleInfo.Bundle.IsRawFile == false)
throw new Exception($"Cannot load asset bundle file using {nameof(LoadRawFileAsync)} method !");
}
#endif
if (_playMode == EPlayMode.EditorSimulateMode)
{
RawFileOperation operation = new EditorPlayModeRawFileOperation(bundleInfo, copyPath);
OperationSystem.StartOperation(operation);
return operation;
}
else if (_playMode == EPlayMode.OfflinePlayMode)
{
RawFileOperation operation = new OfflinePlayModeRawFileOperation(bundleInfo, copyPath);
OperationSystem.StartOperation(operation);
return operation;
}
else if (_playMode == EPlayMode.HostPlayMode)
{
RawFileOperation operation = new HostPlayModeRawFileOperation(bundleInfo, copyPath);
OperationSystem.StartOperation(operation);
return operation;
}
else
{
throw new NotImplementedException();
}
var handle = _assetSystemImpl.LoadRawFileAsync(assetInfo);
if (waitForAsyncComplete)
handle.WaitForAsyncComplete();
return handle;
}
#endregion
@ -592,13 +581,7 @@ namespace YooAsset
{
BundleInfo bundleInfo = _bundleServices.GetBundleInfo(assetInfo);
if (bundleInfo.Bundle.IsRawFile)
{
string error = $"Cannot load raw file using LoadAsset method !";
YooLogger.Error(error);
CompletedProvider completedProvider = new CompletedProvider(assetInfo);
completedProvider.SetCompleted(error);
return completedProvider.CreateHandle<AssetOperationHandle>();
}
throw new Exception($"Cannot load raw file using {nameof(LoadAssetAsync)} method !");
}
#endif
@ -687,13 +670,7 @@ namespace YooAsset
{
BundleInfo bundleInfo = _bundleServices.GetBundleInfo(assetInfo);
if (bundleInfo.Bundle.IsRawFile)
{
string error = $"Cannot load raw file using LoadSubAssets method !";
YooLogger.Error(error);
CompletedProvider completedProvider = new CompletedProvider(assetInfo);
completedProvider.SetCompleted(error);
return completedProvider.CreateHandle<SubAssetsOperationHandle>();
}
throw new Exception($"Cannot load raw file using {nameof(LoadSubAssetsAsync)} method !");
}
#endif

View File

@ -82,25 +82,43 @@ namespace YooAsset
#region 原生文件
/// <summary>
/// 异步获取原生文件
/// 同步加载原生文件
/// </summary>
/// <param name="location">资源的定位地址</param>
/// <param name="copyPath">拷贝路径</param>
public static RawFileOperation GetRawFileAsync(string location, string copyPath = null)
/// <param name="assetInfo">资源信息</param>
public static RawFileOperationHandle LoadRawFileSync(AssetInfo assetInfo)
{
DebugCheckDefaultPackageValid();
return _defaultPackage.GetRawFileAsync(location, copyPath);
return _defaultPackage.LoadRawFileSync(assetInfo);
}
/// <summary>
/// 异步获取原生文件
/// 同步加载原生文件
/// </summary>
/// <param name="assetInfo">资源信息</param>
/// <param name="copyPath">拷贝路径</param>
public static RawFileOperation GetRawFileAsync(AssetInfo assetInfo, string copyPath = null)
/// <param name="location">资源的定位地址</param>
public static RawFileOperationHandle LoadRawFileSync(string location)
{
DebugCheckDefaultPackageValid();
return _defaultPackage.GetRawFileAsync(assetInfo, copyPath);
return _defaultPackage.LoadRawFileSync(location);
}
/// <summary>
/// 异步加载原生文件
/// </summary>
/// <param name="assetInfo">资源信息</param>
public static RawFileOperationHandle LoadRawFileAsync(AssetInfo assetInfo)
{
DebugCheckDefaultPackageValid();
return _defaultPackage.LoadRawFileAsync(assetInfo);
}
/// <summary>
/// 异步加载原生文件
/// </summary>
/// <param name="location">资源的定位地址</param>
public static RawFileOperationHandle LoadRawFileAsync(string location)
{
DebugCheckDefaultPackageValid();
return _defaultPackage.LoadRawFileAsync(location);
}
#endregion