style : Code text indent format

pull/229/head
hevinci 2023-12-21 19:10:46 +08:00
parent 5c1d316d67
commit 544832c46a
117 changed files with 14101 additions and 14103 deletions

View File

@ -3,34 +3,34 @@ using System.IO;
namespace YooAsset namespace YooAsset
{ {
internal class CacheFileInfo internal class CacheFileInfo
{ {
private static readonly BufferWriter SharedBuffer = new BufferWriter(1024); private static readonly BufferWriter SharedBuffer = new BufferWriter(1024);
/// <summary> /// <summary>
/// 写入资源包信息 /// 写入资源包信息
/// </summary> /// </summary>
public static void WriteInfoToFile(string filePath, string dataFileCRC, long dataFileSize) public static void WriteInfoToFile(string filePath, string dataFileCRC, long dataFileSize)
{ {
using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Read)) using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Read))
{ {
SharedBuffer.Clear(); SharedBuffer.Clear();
SharedBuffer.WriteUTF8(dataFileCRC); SharedBuffer.WriteUTF8(dataFileCRC);
SharedBuffer.WriteInt64(dataFileSize); SharedBuffer.WriteInt64(dataFileSize);
SharedBuffer.WriteToStream(fs); SharedBuffer.WriteToStream(fs);
fs.Flush(); fs.Flush();
} }
} }
/// <summary> /// <summary>
/// 读取资源包信息 /// 读取资源包信息
/// </summary> /// </summary>
public static void ReadInfoFromFile(string filePath, out string dataFileCRC, out long dataFileSize) public static void ReadInfoFromFile(string filePath, out string dataFileCRC, out long dataFileSize)
{ {
byte[] binaryData = FileUtility.ReadAllBytes(filePath); byte[] binaryData = FileUtility.ReadAllBytes(filePath);
BufferReader buffer = new BufferReader(binaryData); BufferReader buffer = new BufferReader(binaryData);
dataFileCRC = buffer.ReadUTF8(); dataFileCRC = buffer.ReadUTF8();
dataFileSize = buffer.ReadInt64(); dataFileSize = buffer.ReadInt64();
} }
} }
} }

View File

@ -6,98 +6,98 @@ using System.Diagnostics;
namespace YooAsset namespace YooAsset
{ {
internal static class CacheHelper internal static class CacheHelper
{ {
/// <summary> /// <summary>
/// 禁用Unity缓存系统在WebGL平台 /// 禁用Unity缓存系统在WebGL平台
/// </summary> /// </summary>
public static bool DisableUnityCacheOnWebGL = false; public static bool DisableUnityCacheOnWebGL = false;
/// <summary> /// <summary>
/// 验证缓存文件(子线程内操作) /// 验证缓存文件(子线程内操作)
/// </summary> /// </summary>
public static EVerifyResult VerifyingCacheFile(VerifyCacheFileElement element, EVerifyLevel verifyLevel) public static EVerifyResult VerifyingCacheFile(VerifyCacheFileElement element, EVerifyLevel verifyLevel)
{ {
try try
{ {
if (verifyLevel == EVerifyLevel.Low) if (verifyLevel == EVerifyLevel.Low)
{ {
if (File.Exists(element.InfoFilePath) == false) if (File.Exists(element.InfoFilePath) == false)
return EVerifyResult.InfoFileNotExisted; return EVerifyResult.InfoFileNotExisted;
if (File.Exists(element.DataFilePath) == false) if (File.Exists(element.DataFilePath) == false)
return EVerifyResult.DataFileNotExisted; return EVerifyResult.DataFileNotExisted;
return EVerifyResult.Succeed; return EVerifyResult.Succeed;
} }
else else
{ {
if (File.Exists(element.InfoFilePath) == false) if (File.Exists(element.InfoFilePath) == false)
return EVerifyResult.InfoFileNotExisted; return EVerifyResult.InfoFileNotExisted;
// 解析信息文件获取验证数据 // 解析信息文件获取验证数据
CacheFileInfo.ReadInfoFromFile(element.InfoFilePath, out element.DataFileCRC, out element.DataFileSize); CacheFileInfo.ReadInfoFromFile(element.InfoFilePath, out element.DataFileCRC, out element.DataFileSize);
} }
} }
catch (Exception) catch (Exception)
{ {
return EVerifyResult.Exception; return EVerifyResult.Exception;
} }
return VerifyingInternal(element.DataFilePath, element.DataFileSize, element.DataFileCRC, verifyLevel); return VerifyingInternal(element.DataFilePath, element.DataFileSize, element.DataFileCRC, verifyLevel);
} }
/// <summary> /// <summary>
/// 验证下载文件(子线程内操作) /// 验证下载文件(子线程内操作)
/// </summary> /// </summary>
public static EVerifyResult VerifyingTempFile(VerifyTempFileElement element) public static EVerifyResult VerifyingTempFile(VerifyTempFileElement element)
{ {
return VerifyingInternal(element.TempDataFilePath, element.FileSize, element.FileCRC, EVerifyLevel.High); return VerifyingInternal(element.TempDataFilePath, element.FileSize, element.FileCRC, EVerifyLevel.High);
} }
/// <summary> /// <summary>
/// 验证记录文件(主线程内操作) /// 验证记录文件(主线程内操作)
/// </summary> /// </summary>
public static EVerifyResult VerifyingRecordFile(CacheManager cache, string cacheGUID) public static EVerifyResult VerifyingRecordFile(CacheManager cache, string cacheGUID)
{ {
var wrapper = cache.TryGetWrapper(cacheGUID); var wrapper = cache.TryGetWrapper(cacheGUID);
if (wrapper == null) if (wrapper == null)
return EVerifyResult.CacheNotFound; return EVerifyResult.CacheNotFound;
EVerifyResult result = VerifyingInternal(wrapper.DataFilePath, wrapper.DataFileSize, wrapper.DataFileCRC, EVerifyLevel.High); EVerifyResult result = VerifyingInternal(wrapper.DataFilePath, wrapper.DataFileSize, wrapper.DataFileCRC, EVerifyLevel.High);
return result; return result;
} }
private static EVerifyResult VerifyingInternal(string filePath, long fileSize, string fileCRC, EVerifyLevel verifyLevel) private static EVerifyResult VerifyingInternal(string filePath, long fileSize, string fileCRC, EVerifyLevel verifyLevel)
{ {
try try
{ {
if (File.Exists(filePath) == false) if (File.Exists(filePath) == false)
return EVerifyResult.DataFileNotExisted; return EVerifyResult.DataFileNotExisted;
// 先验证文件大小 // 先验证文件大小
long size = FileUtility.GetFileSize(filePath); long size = FileUtility.GetFileSize(filePath);
if (size < fileSize) if (size < fileSize)
return EVerifyResult.FileNotComplete; return EVerifyResult.FileNotComplete;
else if (size > fileSize) else if (size > fileSize)
return EVerifyResult.FileOverflow; return EVerifyResult.FileOverflow;
// 再验证文件CRC // 再验证文件CRC
if (verifyLevel == EVerifyLevel.High) if (verifyLevel == EVerifyLevel.High)
{ {
string crc = HashUtility.FileCRC32(filePath); string crc = HashUtility.FileCRC32(filePath);
if (crc == fileCRC) if (crc == fileCRC)
return EVerifyResult.Succeed; return EVerifyResult.Succeed;
else else
return EVerifyResult.FileCrcError; return EVerifyResult.FileCrcError;
} }
else else
{ {
return EVerifyResult.Succeed; return EVerifyResult.Succeed;
} }
} }
catch (Exception) catch (Exception)
{ {
return EVerifyResult.Exception; return EVerifyResult.Exception;
} }
} }
} }
} }

View File

@ -5,132 +5,132 @@ using System.Collections.Generic;
namespace YooAsset namespace YooAsset
{ {
internal class CacheManager internal class CacheManager
{ {
internal class RecordWrapper internal class RecordWrapper
{ {
public string InfoFilePath { private set; get; } public string InfoFilePath { private set; get; }
public string DataFilePath { private set; get; } public string DataFilePath { private set; get; }
public string DataFileCRC { private set; get; } public string DataFileCRC { private set; get; }
public long DataFileSize { private set; get; } public long DataFileSize { private set; get; }
public RecordWrapper(string infoFilePath, string dataFilePath, string dataFileCRC, long dataFileSize) public RecordWrapper(string infoFilePath, string dataFilePath, string dataFileCRC, long dataFileSize)
{ {
InfoFilePath = infoFilePath; InfoFilePath = infoFilePath;
DataFilePath = dataFilePath; DataFilePath = dataFilePath;
DataFileCRC = dataFileCRC; DataFileCRC = dataFileCRC;
DataFileSize = dataFileSize; DataFileSize = dataFileSize;
} }
} }
private readonly Dictionary<string, RecordWrapper> _wrappers = new Dictionary<string, RecordWrapper>(); private readonly Dictionary<string, RecordWrapper> _wrappers = new Dictionary<string, RecordWrapper>();
/// <summary> /// <summary>
/// 所属包裹 /// 所属包裹
/// </summary> /// </summary>
public readonly string PackageName; public readonly string PackageName;
/// <summary> /// <summary>
/// 验证级别 /// 验证级别
/// </summary> /// </summary>
public readonly EVerifyLevel BootVerifyLevel; public readonly EVerifyLevel BootVerifyLevel;
public CacheManager(string packageName, EVerifyLevel bootVerifyLevel) public CacheManager(string packageName, EVerifyLevel bootVerifyLevel)
{ {
PackageName = packageName; PackageName = packageName;
BootVerifyLevel = bootVerifyLevel; BootVerifyLevel = bootVerifyLevel;
} }
/// <summary> /// <summary>
/// 清空所有数据 /// 清空所有数据
/// </summary> /// </summary>
public void ClearAll() public void ClearAll()
{ {
_wrappers.Clear(); _wrappers.Clear();
} }
/// <summary> /// <summary>
/// 查询缓存记录 /// 查询缓存记录
/// </summary> /// </summary>
public bool IsCached(string cacheGUID) public bool IsCached(string cacheGUID)
{ {
return _wrappers.ContainsKey(cacheGUID); return _wrappers.ContainsKey(cacheGUID);
} }
/// <summary> /// <summary>
/// 记录验证结果 /// 记录验证结果
/// </summary> /// </summary>
public void Record(string cacheGUID, RecordWrapper wrapper) public void Record(string cacheGUID, RecordWrapper wrapper)
{ {
if (_wrappers.ContainsKey(cacheGUID) == false) if (_wrappers.ContainsKey(cacheGUID) == false)
{ {
_wrappers.Add(cacheGUID, wrapper); _wrappers.Add(cacheGUID, wrapper);
} }
else else
{ {
throw new Exception("Should never get here !"); throw new Exception("Should never get here !");
} }
} }
/// <summary> /// <summary>
/// 丢弃验证结果并删除缓存文件 /// 丢弃验证结果并删除缓存文件
/// </summary> /// </summary>
public void Discard(string cacheGUID) public void Discard(string cacheGUID)
{ {
var wrapper = TryGetWrapper(cacheGUID); var wrapper = TryGetWrapper(cacheGUID);
if (wrapper != null) if (wrapper != null)
{ {
try try
{ {
string dataFilePath = wrapper.DataFilePath; string dataFilePath = wrapper.DataFilePath;
FileInfo fileInfo = new FileInfo(dataFilePath); FileInfo fileInfo = new FileInfo(dataFilePath);
if (fileInfo.Exists) if (fileInfo.Exists)
fileInfo.Directory.Delete(true); fileInfo.Directory.Delete(true);
} }
catch (Exception e) catch (Exception e)
{ {
YooLogger.Error($"Failed to delete cache file ! {e.Message}"); YooLogger.Error($"Failed to delete cache file ! {e.Message}");
} }
} }
if (_wrappers.ContainsKey(cacheGUID)) if (_wrappers.ContainsKey(cacheGUID))
{ {
_wrappers.Remove(cacheGUID); _wrappers.Remove(cacheGUID);
} }
} }
/// <summary> /// <summary>
/// 获取记录对象 /// 获取记录对象
/// </summary> /// </summary>
public RecordWrapper TryGetWrapper(string cacheGUID) public RecordWrapper TryGetWrapper(string cacheGUID)
{ {
if (_wrappers.TryGetValue(cacheGUID, out RecordWrapper value)) if (_wrappers.TryGetValue(cacheGUID, out RecordWrapper value))
return value; return value;
else else
return null; return null;
} }
/// <summary> /// <summary>
/// 获取缓存文件总数 /// 获取缓存文件总数
/// </summary> /// </summary>
public int GetAllCachedFilesCount() public int GetAllCachedFilesCount()
{ {
return _wrappers.Count; return _wrappers.Count;
} }
/// <summary> /// <summary>
/// 获取缓存GUID集合 /// 获取缓存GUID集合
/// </summary> /// </summary>
public List<string> GetAllCachedGUIDs() public List<string> GetAllCachedGUIDs()
{ {
List<string> keys = new List<string>(_wrappers.Keys.Count); List<string> keys = new List<string>(_wrappers.Keys.Count);
var keyCollection = _wrappers.Keys; var keyCollection = _wrappers.Keys;
foreach (var key in keyCollection) foreach (var key in keyCollection)
{ {
keys.Add(key); keys.Add(key);
} }
return keys; return keys;
} }
} }
} }

View File

@ -1,24 +1,24 @@
 
namespace YooAsset namespace YooAsset
{ {
/// <summary> /// <summary>
/// 下载文件校验等级 /// 下载文件校验等级
/// </summary> /// </summary>
public enum EVerifyLevel public enum EVerifyLevel
{ {
/// <summary> /// <summary>
/// 验证文件存在 /// 验证文件存在
/// </summary> /// </summary>
Low, Low,
/// <summary> /// <summary>
/// 验证文件大小 /// 验证文件大小
/// </summary> /// </summary>
Middle, Middle,
/// <summary> /// <summary>
/// 验证文件大小和CRC /// 验证文件大小和CRC
/// </summary> /// </summary>
High, High,
} }
} }

View File

@ -4,68 +4,68 @@ using System.IO;
namespace YooAsset namespace YooAsset
{ {
/// <summary> /// <summary>
/// 清理本地包裹所有的缓存文件 /// 清理本地包裹所有的缓存文件
/// </summary> /// </summary>
public sealed class ClearAllCacheFilesOperation : AsyncOperationBase public sealed class ClearAllCacheFilesOperation : AsyncOperationBase
{ {
private enum ESteps private enum ESteps
{ {
None, None,
GetAllCacheFiles, GetAllCacheFiles,
ClearAllCacheFiles, ClearAllCacheFiles,
Done, Done,
} }
private readonly CacheManager _cache; private readonly CacheManager _cache;
private List<string> _allCacheGUIDs; private List<string> _allCacheGUIDs;
private int _fileTotalCount = 0; private int _fileTotalCount = 0;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
internal ClearAllCacheFilesOperation(CacheManager cache)
{
_cache = cache;
}
internal override void InternalOnStart()
{
_steps = ESteps.GetAllCacheFiles;
}
internal override void InternalOnUpdate()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.GetAllCacheFiles) internal ClearAllCacheFilesOperation(CacheManager cache)
{ {
_allCacheGUIDs = _cache.GetAllCachedGUIDs(); _cache = cache;
_fileTotalCount = _allCacheGUIDs.Count; }
YooLogger.Log($"Found all cache file count : {_fileTotalCount}"); internal override void InternalOnStart()
_steps = ESteps.ClearAllCacheFiles; {
} _steps = ESteps.GetAllCacheFiles;
}
internal override void InternalOnUpdate()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.ClearAllCacheFiles) if (_steps == ESteps.GetAllCacheFiles)
{ {
for (int i = _allCacheGUIDs.Count - 1; i >= 0; i--) _allCacheGUIDs = _cache.GetAllCachedGUIDs();
{ _fileTotalCount = _allCacheGUIDs.Count;
string cacheGUID = _allCacheGUIDs[i]; YooLogger.Log($"Found all cache file count : {_fileTotalCount}");
_cache.Discard(cacheGUID); _steps = ESteps.ClearAllCacheFiles;
_allCacheGUIDs.RemoveAt(i); }
if (OperationSystem.IsBusy) if (_steps == ESteps.ClearAllCacheFiles)
break; {
} for (int i = _allCacheGUIDs.Count - 1; i >= 0; i--)
{
string cacheGUID = _allCacheGUIDs[i];
_cache.Discard(cacheGUID);
_allCacheGUIDs.RemoveAt(i);
if (_fileTotalCount == 0) if (OperationSystem.IsBusy)
Progress = 1.0f; break;
else }
Progress = 1.0f - (_allCacheGUIDs.Count / _fileTotalCount);
if (_allCacheGUIDs.Count == 0) if (_fileTotalCount == 0)
{ Progress = 1.0f;
_steps = ESteps.Done; else
Status = EOperationStatus.Succeed; Progress = 1.0f - (_allCacheGUIDs.Count / _fileTotalCount);
}
} if (_allCacheGUIDs.Count == 0)
} {
} _steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
}
}
}
} }

View File

@ -4,84 +4,84 @@ using System.IO;
namespace YooAsset namespace YooAsset
{ {
/// <summary> /// <summary>
/// 清理本地包裹未使用的缓存文件 /// 清理本地包裹未使用的缓存文件
/// </summary> /// </summary>
public sealed class ClearUnusedCacheFilesOperation : AsyncOperationBase public sealed class ClearUnusedCacheFilesOperation : AsyncOperationBase
{ {
private enum ESteps private enum ESteps
{ {
None, None,
GetUnusedCacheFiles, GetUnusedCacheFiles,
ClearUnusedCacheFiles, ClearUnusedCacheFiles,
Done, Done,
} }
private readonly ResourcePackage _package; private readonly ResourcePackage _package;
private readonly CacheManager _cache; private readonly CacheManager _cache;
private List<string> _unusedCacheGUIDs; private List<string> _unusedCacheGUIDs;
private int _unusedFileTotalCount = 0; private int _unusedFileTotalCount = 0;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
internal ClearUnusedCacheFilesOperation(ResourcePackage package, CacheManager cache) internal ClearUnusedCacheFilesOperation(ResourcePackage package, CacheManager cache)
{ {
_package = package; _package = package;
_cache = cache; _cache = cache;
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
_steps = ESteps.GetUnusedCacheFiles; _steps = ESteps.GetUnusedCacheFiles;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
if (_steps == ESteps.None || _steps == ESteps.Done) if (_steps == ESteps.None || _steps == ESteps.Done)
return; return;
if (_steps == ESteps.GetUnusedCacheFiles) if (_steps == ESteps.GetUnusedCacheFiles)
{ {
_unusedCacheGUIDs = GetUnusedCacheGUIDs(); _unusedCacheGUIDs = GetUnusedCacheGUIDs();
_unusedFileTotalCount = _unusedCacheGUIDs.Count; _unusedFileTotalCount = _unusedCacheGUIDs.Count;
YooLogger.Log($"Found unused cache file count : {_unusedFileTotalCount}"); YooLogger.Log($"Found unused cache file count : {_unusedFileTotalCount}");
_steps = ESteps.ClearUnusedCacheFiles; _steps = ESteps.ClearUnusedCacheFiles;
} }
if (_steps == ESteps.ClearUnusedCacheFiles) if (_steps == ESteps.ClearUnusedCacheFiles)
{ {
for (int i = _unusedCacheGUIDs.Count - 1; i >= 0; i--) for (int i = _unusedCacheGUIDs.Count - 1; i >= 0; i--)
{ {
string cacheGUID = _unusedCacheGUIDs[i]; string cacheGUID = _unusedCacheGUIDs[i];
_cache.Discard(cacheGUID); _cache.Discard(cacheGUID);
_unusedCacheGUIDs.RemoveAt(i); _unusedCacheGUIDs.RemoveAt(i);
if (OperationSystem.IsBusy) if (OperationSystem.IsBusy)
break; break;
} }
if (_unusedFileTotalCount == 0) if (_unusedFileTotalCount == 0)
Progress = 1.0f; Progress = 1.0f;
else else
Progress = 1.0f - (_unusedCacheGUIDs.Count / _unusedFileTotalCount); Progress = 1.0f - (_unusedCacheGUIDs.Count / _unusedFileTotalCount);
if (_unusedCacheGUIDs.Count == 0) if (_unusedCacheGUIDs.Count == 0)
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
} }
} }
private List<string> GetUnusedCacheGUIDs() private List<string> GetUnusedCacheGUIDs()
{ {
var allCacheGUIDs = _cache.GetAllCachedGUIDs(); var allCacheGUIDs = _cache.GetAllCachedGUIDs();
List<string> result = new List<string>(allCacheGUIDs.Count); List<string> result = new List<string>(allCacheGUIDs.Count);
foreach (var cacheGUID in allCacheGUIDs) foreach (var cacheGUID in allCacheGUIDs)
{ {
if (_package.IsIncludeBundleFile(cacheGUID) == false) if (_package.IsIncludeBundleFile(cacheGUID) == false)
{ {
result.Add(cacheGUID); result.Add(cacheGUID);
} }
} }
return result; return result;
} }
} }
} }

View File

@ -5,127 +5,127 @@ using System.Collections.Generic;
namespace YooAsset namespace YooAsset
{ {
internal sealed class FindCacheFilesOperation : AsyncOperationBase internal sealed class FindCacheFilesOperation : AsyncOperationBase
{ {
private enum ESteps private enum ESteps
{ {
None, None,
Prepare, Prepare,
UpdateCacheFiles, UpdateCacheFiles,
Done, Done,
} }
private readonly PersistentManager _persistent; private readonly PersistentManager _persistent;
private readonly CacheManager _cache; private readonly CacheManager _cache;
private IEnumerator<DirectoryInfo> _filesEnumerator = null; private IEnumerator<DirectoryInfo> _filesEnumerator = null;
private float _verifyStartTime; private float _verifyStartTime;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
/// <summary> /// <summary>
/// 需要验证的元素 /// 需要验证的元素
/// </summary> /// </summary>
public readonly List<VerifyCacheFileElement> VerifyElements = new List<VerifyCacheFileElement>(5000); public readonly List<VerifyCacheFileElement> VerifyElements = new List<VerifyCacheFileElement>(5000);
public FindCacheFilesOperation(PersistentManager persistent, CacheManager cache) public FindCacheFilesOperation(PersistentManager persistent, CacheManager cache)
{ {
_persistent = persistent; _persistent = persistent;
_cache = cache; _cache = cache;
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
_steps = ESteps.Prepare; _steps = ESteps.Prepare;
_verifyStartTime = UnityEngine.Time.realtimeSinceStartup; _verifyStartTime = UnityEngine.Time.realtimeSinceStartup;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
if (_steps == ESteps.None || _steps == ESteps.Done) if (_steps == ESteps.None || _steps == ESteps.Done)
return; return;
if (_steps == ESteps.Prepare) if (_steps == ESteps.Prepare)
{ {
string rootPath = _persistent.SandboxCacheFilesRoot; string rootPath = _persistent.SandboxCacheFilesRoot;
DirectoryInfo rootDirectory = new DirectoryInfo(rootPath); DirectoryInfo rootDirectory = new DirectoryInfo(rootPath);
if (rootDirectory.Exists) if (rootDirectory.Exists)
{ {
var directorieInfos = rootDirectory.EnumerateDirectories(); var directorieInfos = rootDirectory.EnumerateDirectories();
_filesEnumerator = directorieInfos.GetEnumerator(); _filesEnumerator = directorieInfos.GetEnumerator();
} }
_steps = ESteps.UpdateCacheFiles; _steps = ESteps.UpdateCacheFiles;
} }
if (_steps == ESteps.UpdateCacheFiles) if (_steps == ESteps.UpdateCacheFiles)
{ {
if (UpdateCacheFiles()) if (UpdateCacheFiles())
return; return;
// 注意:总是返回成功 // 注意:总是返回成功
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
float costTime = UnityEngine.Time.realtimeSinceStartup - _verifyStartTime; float costTime = UnityEngine.Time.realtimeSinceStartup - _verifyStartTime;
YooLogger.Log($"Find cache files elapsed time {costTime:f1} seconds"); YooLogger.Log($"Find cache files elapsed time {costTime:f1} seconds");
} }
} }
private bool UpdateCacheFiles() private bool UpdateCacheFiles()
{ {
if (_filesEnumerator == null) if (_filesEnumerator == null)
return false; return false;
bool isFindItem; bool isFindItem;
while (true) while (true)
{ {
isFindItem = _filesEnumerator.MoveNext(); isFindItem = _filesEnumerator.MoveNext();
if (isFindItem == false) if (isFindItem == false)
break; break;
var rootFoder = _filesEnumerator.Current; var rootFoder = _filesEnumerator.Current;
var childDirectories = rootFoder.GetDirectories(); var childDirectories = rootFoder.GetDirectories();
foreach (var chidDirectory in childDirectories) foreach (var chidDirectory in childDirectories)
{ {
string cacheGUID = chidDirectory.Name; string cacheGUID = chidDirectory.Name;
if (_cache.IsCached(cacheGUID)) if (_cache.IsCached(cacheGUID))
continue; continue;
// 创建验证元素类 // 创建验证元素类
string fileRootPath = chidDirectory.FullName; string fileRootPath = chidDirectory.FullName;
string dataFilePath = $"{fileRootPath}/{ YooAssetSettings.CacheBundleDataFileName}"; string dataFilePath = $"{fileRootPath}/{ YooAssetSettings.CacheBundleDataFileName}";
string infoFilePath = $"{fileRootPath}/{ YooAssetSettings.CacheBundleInfoFileName}"; string infoFilePath = $"{fileRootPath}/{ YooAssetSettings.CacheBundleInfoFileName}";
string dataFileExtension = FindDataFileExtension(chidDirectory); string dataFileExtension = FindDataFileExtension(chidDirectory);
// 跳过断点续传的临时文件 // 跳过断点续传的临时文件
if (dataFileExtension == ".temp") if (dataFileExtension == ".temp")
continue; continue;
// 注意:根据配置需求数据文件会带文件格式 // 注意:根据配置需求数据文件会带文件格式
if (_persistent.AppendFileExtension) if (_persistent.AppendFileExtension)
{ {
if (string.IsNullOrEmpty(dataFileExtension) == false) if (string.IsNullOrEmpty(dataFileExtension) == false)
dataFilePath += dataFileExtension; dataFilePath += dataFileExtension;
} }
VerifyCacheFileElement element = new VerifyCacheFileElement(_cache.PackageName, cacheGUID, fileRootPath, dataFilePath, infoFilePath); VerifyCacheFileElement element = new VerifyCacheFileElement(_cache.PackageName, cacheGUID, fileRootPath, dataFilePath, infoFilePath);
VerifyElements.Add(element); VerifyElements.Add(element);
} }
if (OperationSystem.IsBusy) if (OperationSystem.IsBusy)
break; break;
} }
return isFindItem; return isFindItem;
} }
private string FindDataFileExtension(DirectoryInfo directoryInfo) private string FindDataFileExtension(DirectoryInfo directoryInfo)
{ {
string dataFileExtension = string.Empty; string dataFileExtension = string.Empty;
var fileInfos = directoryInfo.GetFiles(); var fileInfos = directoryInfo.GetFiles();
foreach (var fileInfo in fileInfos) foreach (var fileInfo in fileInfos)
{ {
if (fileInfo.Name.StartsWith(YooAssetSettings.CacheBundleDataFileName)) if (fileInfo.Name.StartsWith(YooAssetSettings.CacheBundleDataFileName))
{ {
dataFileExtension = fileInfo.Extension; dataFileExtension = fileInfo.Extension;
break; break;
} }
} }
return dataFileExtension; return dataFileExtension;
} }
} }
} }

View File

@ -6,249 +6,249 @@ using System.Threading;
namespace YooAsset namespace YooAsset
{ {
internal abstract class VerifyCacheFilesOperation : AsyncOperationBase internal abstract class VerifyCacheFilesOperation : AsyncOperationBase
{ {
public static VerifyCacheFilesOperation CreateOperation(CacheManager cache, List<VerifyCacheFileElement> elements) public static VerifyCacheFilesOperation CreateOperation(CacheManager cache, List<VerifyCacheFileElement> elements)
{ {
#if UNITY_WEBGL #if UNITY_WEBGL
var operation = new VerifyCacheFilesWithoutThreadOperation(cache, elements); var operation = new VerifyCacheFilesWithoutThreadOperation(cache, elements);
#else #else
var operation = new VerifyCacheFilesWithThreadOperation(cache, elements); var operation = new VerifyCacheFilesWithThreadOperation(cache, elements);
#endif #endif
return operation; return operation;
} }
} }
/// <summary> /// <summary>
/// 本地缓存文件验证(线程版) /// 本地缓存文件验证(线程版)
/// </summary> /// </summary>
internal class VerifyCacheFilesWithThreadOperation : VerifyCacheFilesOperation internal class VerifyCacheFilesWithThreadOperation : VerifyCacheFilesOperation
{ {
private enum ESteps private enum ESteps
{ {
None, None,
InitVerify, InitVerify,
UpdateVerify, UpdateVerify,
Done, Done,
} }
private readonly ThreadSyncContext _syncContext = new ThreadSyncContext(); private readonly ThreadSyncContext _syncContext = new ThreadSyncContext();
private readonly CacheManager _cache; private readonly CacheManager _cache;
private List<VerifyCacheFileElement> _waitingList; private List<VerifyCacheFileElement> _waitingList;
private List<VerifyCacheFileElement> _verifyingList; private List<VerifyCacheFileElement> _verifyingList;
private int _verifyMaxNum; private int _verifyMaxNum;
private int _verifyTotalCount; private int _verifyTotalCount;
private float _verifyStartTime; private float _verifyStartTime;
private int _succeedCount; private int _succeedCount;
private int _failedCount; private int _failedCount;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
public VerifyCacheFilesWithThreadOperation(CacheManager cache, List<VerifyCacheFileElement> elements) public VerifyCacheFilesWithThreadOperation(CacheManager cache, List<VerifyCacheFileElement> elements)
{ {
_cache = cache; _cache = cache;
_waitingList = elements; _waitingList = elements;
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
_steps = ESteps.InitVerify; _steps = ESteps.InitVerify;
_verifyStartTime = UnityEngine.Time.realtimeSinceStartup; _verifyStartTime = UnityEngine.Time.realtimeSinceStartup;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
if (_steps == ESteps.None || _steps == ESteps.Done) if (_steps == ESteps.None || _steps == ESteps.Done)
return; return;
if (_steps == ESteps.InitVerify) if (_steps == ESteps.InitVerify)
{ {
int fileCount = _waitingList.Count; int fileCount = _waitingList.Count;
// 设置同时验证的最大数 // 设置同时验证的最大数
ThreadPool.GetMaxThreads(out int workerThreads, out int ioThreads); ThreadPool.GetMaxThreads(out int workerThreads, out int ioThreads);
YooLogger.Log($"Work threads : {workerThreads}, IO threads : {ioThreads}"); YooLogger.Log($"Work threads : {workerThreads}, IO threads : {ioThreads}");
_verifyMaxNum = Math.Min(workerThreads, ioThreads); _verifyMaxNum = Math.Min(workerThreads, ioThreads);
_verifyTotalCount = fileCount; _verifyTotalCount = fileCount;
if (_verifyMaxNum < 1) if (_verifyMaxNum < 1)
_verifyMaxNum = 1; _verifyMaxNum = 1;
_verifyingList = new List<VerifyCacheFileElement>(_verifyMaxNum); _verifyingList = new List<VerifyCacheFileElement>(_verifyMaxNum);
_steps = ESteps.UpdateVerify; _steps = ESteps.UpdateVerify;
} }
if (_steps == ESteps.UpdateVerify) if (_steps == ESteps.UpdateVerify)
{ {
_syncContext.Update(); _syncContext.Update();
Progress = GetProgress(); Progress = GetProgress();
if (_waitingList.Count == 0 && _verifyingList.Count == 0) if (_waitingList.Count == 0 && _verifyingList.Count == 0)
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
float costTime = UnityEngine.Time.realtimeSinceStartup - _verifyStartTime; float costTime = UnityEngine.Time.realtimeSinceStartup - _verifyStartTime;
YooLogger.Log($"Verify cache files elapsed time {costTime:f1} seconds"); YooLogger.Log($"Verify cache files elapsed time {costTime:f1} seconds");
} }
for (int i = _waitingList.Count - 1; i >= 0; i--) for (int i = _waitingList.Count - 1; i >= 0; i--)
{ {
if (OperationSystem.IsBusy) if (OperationSystem.IsBusy)
break; break;
if (_verifyingList.Count >= _verifyMaxNum) if (_verifyingList.Count >= _verifyMaxNum)
break; break;
var element = _waitingList[i]; var element = _waitingList[i];
if (BeginVerifyFileWithThread(element)) if (BeginVerifyFileWithThread(element))
{ {
_waitingList.RemoveAt(i); _waitingList.RemoveAt(i);
_verifyingList.Add(element); _verifyingList.Add(element);
} }
else else
{ {
YooLogger.Warning("The thread pool is failed queued."); YooLogger.Warning("The thread pool is failed queued.");
break; break;
} }
} }
} }
} }
private float GetProgress() private float GetProgress()
{ {
if (_verifyTotalCount == 0) if (_verifyTotalCount == 0)
return 1f; return 1f;
return (float)(_succeedCount + _failedCount) / _verifyTotalCount; return (float)(_succeedCount + _failedCount) / _verifyTotalCount;
} }
private bool BeginVerifyFileWithThread(VerifyCacheFileElement element) private bool BeginVerifyFileWithThread(VerifyCacheFileElement element)
{ {
return ThreadPool.QueueUserWorkItem(new WaitCallback(VerifyInThread), element); return ThreadPool.QueueUserWorkItem(new WaitCallback(VerifyInThread), element);
} }
private void VerifyInThread(object obj) private void VerifyInThread(object obj)
{ {
VerifyCacheFileElement element = (VerifyCacheFileElement)obj; VerifyCacheFileElement element = (VerifyCacheFileElement)obj;
element.Result = CacheHelper.VerifyingCacheFile(element, _cache.BootVerifyLevel); element.Result = CacheHelper.VerifyingCacheFile(element, _cache.BootVerifyLevel);
_syncContext.Post(VerifyCallback, element); _syncContext.Post(VerifyCallback, element);
} }
private void VerifyCallback(object obj) private void VerifyCallback(object obj)
{ {
VerifyCacheFileElement element = (VerifyCacheFileElement)obj; VerifyCacheFileElement element = (VerifyCacheFileElement)obj;
_verifyingList.Remove(element); _verifyingList.Remove(element);
if (element.Result == EVerifyResult.Succeed) if (element.Result == EVerifyResult.Succeed)
{ {
_succeedCount++; _succeedCount++;
var wrapper = new CacheManager.RecordWrapper(element.InfoFilePath, element.DataFilePath, element.DataFileCRC, element.DataFileSize); var wrapper = new CacheManager.RecordWrapper(element.InfoFilePath, element.DataFilePath, element.DataFileCRC, element.DataFileSize);
_cache.Record(element.CacheGUID, wrapper); _cache.Record(element.CacheGUID, wrapper);
} }
else else
{ {
_failedCount++; _failedCount++;
YooLogger.Warning($"Failed verify file and delete files : {element.FileRootPath}"); YooLogger.Warning($"Failed verify file and delete files : {element.FileRootPath}");
element.DeleteFiles(); element.DeleteFiles();
} }
} }
} }
/// <summary> /// <summary>
/// 本地缓存文件验证(非线程版) /// 本地缓存文件验证(非线程版)
/// </summary> /// </summary>
internal class VerifyCacheFilesWithoutThreadOperation : VerifyCacheFilesOperation internal class VerifyCacheFilesWithoutThreadOperation : VerifyCacheFilesOperation
{ {
private enum ESteps private enum ESteps
{ {
None, None,
InitVerify, InitVerify,
UpdateVerify, UpdateVerify,
Done, Done,
} }
private readonly CacheManager _cache; private readonly CacheManager _cache;
private List<VerifyCacheFileElement> _waitingList; private List<VerifyCacheFileElement> _waitingList;
private List<VerifyCacheFileElement> _verifyingList; private List<VerifyCacheFileElement> _verifyingList;
private int _verifyMaxNum; private int _verifyMaxNum;
private int _verifyTotalCount; private int _verifyTotalCount;
private float _verifyStartTime; private float _verifyStartTime;
private int _succeedCount; private int _succeedCount;
private int _failedCount; private int _failedCount;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
public VerifyCacheFilesWithoutThreadOperation(CacheManager cache, List<VerifyCacheFileElement> elements)
{
_cache = cache;
_waitingList = elements;
}
internal override void InternalOnStart()
{
_steps = ESteps.InitVerify;
_verifyStartTime = UnityEngine.Time.realtimeSinceStartup;
}
internal override void InternalOnUpdate()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.InitVerify) public VerifyCacheFilesWithoutThreadOperation(CacheManager cache, List<VerifyCacheFileElement> elements)
{ {
int fileCount = _waitingList.Count; _cache = cache;
_waitingList = elements;
}
internal override void InternalOnStart()
{
_steps = ESteps.InitVerify;
_verifyStartTime = UnityEngine.Time.realtimeSinceStartup;
}
internal override void InternalOnUpdate()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
// 设置同时验证的最大数 if (_steps == ESteps.InitVerify)
_verifyMaxNum = fileCount; {
_verifyTotalCount = fileCount; int fileCount = _waitingList.Count;
_verifyingList = new List<VerifyCacheFileElement>(_verifyMaxNum); // 设置同时验证的最大数
_steps = ESteps.UpdateVerify; _verifyMaxNum = fileCount;
} _verifyTotalCount = fileCount;
if (_steps == ESteps.UpdateVerify) _verifyingList = new List<VerifyCacheFileElement>(_verifyMaxNum);
{ _steps = ESteps.UpdateVerify;
Progress = GetProgress(); }
if (_waitingList.Count == 0 && _verifyingList.Count == 0)
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
float costTime = UnityEngine.Time.realtimeSinceStartup - _verifyStartTime;
YooLogger.Log($"Package verify elapsed time {costTime:f1} seconds");
}
for (int i = _waitingList.Count - 1; i >= 0; i--) if (_steps == ESteps.UpdateVerify)
{ {
if (OperationSystem.IsBusy) Progress = GetProgress();
break; if (_waitingList.Count == 0 && _verifyingList.Count == 0)
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
float costTime = UnityEngine.Time.realtimeSinceStartup - _verifyStartTime;
YooLogger.Log($"Package verify elapsed time {costTime:f1} seconds");
}
if (_verifyingList.Count >= _verifyMaxNum) for (int i = _waitingList.Count - 1; i >= 0; i--)
break; {
if (OperationSystem.IsBusy)
break;
var element = _waitingList[i]; if (_verifyingList.Count >= _verifyMaxNum)
BeginVerifyFileWithoutThread(element); break;
_waitingList.RemoveAt(i);
_verifyingList.Add(element);
}
// 主线程内验证,可以清空列表 var element = _waitingList[i];
_verifyingList.Clear(); BeginVerifyFileWithoutThread(element);
} _waitingList.RemoveAt(i);
} _verifyingList.Add(element);
}
private float GetProgress() // 主线程内验证,可以清空列表
{ _verifyingList.Clear();
if (_verifyTotalCount == 0) }
return 1f; }
return (float)(_succeedCount + _failedCount) / _verifyTotalCount;
}
private void BeginVerifyFileWithoutThread(VerifyCacheFileElement element)
{
element.Result = CacheHelper.VerifyingCacheFile(element, _cache.BootVerifyLevel);
if (element.Result == EVerifyResult.Succeed)
{
_succeedCount++;
var wrapper = new CacheManager.RecordWrapper(element.InfoFilePath, element.DataFilePath, element.DataFileCRC, element.DataFileSize);
_cache.Record(element.CacheGUID, wrapper);
}
else
{
_failedCount++;
YooLogger.Warning($"Failed verify file and delete files : {element.FileRootPath}"); private float GetProgress()
element.DeleteFiles(); {
} if (_verifyTotalCount == 0)
} return 1f;
} return (float)(_succeedCount + _failedCount) / _verifyTotalCount;
}
private void BeginVerifyFileWithoutThread(VerifyCacheFileElement element)
{
element.Result = CacheHelper.VerifyingCacheFile(element, _cache.BootVerifyLevel);
if (element.Result == EVerifyResult.Succeed)
{
_succeedCount++;
var wrapper = new CacheManager.RecordWrapper(element.InfoFilePath, element.DataFilePath, element.DataFileCRC, element.DataFileSize);
_cache.Record(element.CacheGUID, wrapper);
}
else
{
_failedCount++;
YooLogger.Warning($"Failed verify file and delete files : {element.FileRootPath}");
element.DeleteFiles();
}
}
}
} }

View File

@ -6,136 +6,136 @@ using System.Threading;
namespace YooAsset namespace YooAsset
{ {
internal abstract class VerifyTempFileOperation : AsyncOperationBase internal abstract class VerifyTempFileOperation : AsyncOperationBase
{ {
public EVerifyResult VerifyResult { protected set; get; } public EVerifyResult VerifyResult { protected set; get; }
public static VerifyTempFileOperation CreateOperation(VerifyTempFileElement element) public static VerifyTempFileOperation CreateOperation(VerifyTempFileElement element)
{ {
#if UNITY_WEBGL #if UNITY_WEBGL
var operation = new VerifyTempFileWithoutThreadOperation(element); var operation = new VerifyTempFileWithoutThreadOperation(element);
#else #else
var operation = new VerifyTempFileWithThreadOperation(element); var operation = new VerifyTempFileWithThreadOperation(element);
#endif #endif
return operation; return operation;
} }
} }
/// <summary> /// <summary>
/// 下载文件验证(线程版) /// 下载文件验证(线程版)
/// </summary> /// </summary>
internal class VerifyTempFileWithThreadOperation : VerifyTempFileOperation internal class VerifyTempFileWithThreadOperation : VerifyTempFileOperation
{ {
private enum ESteps private enum ESteps
{ {
None, None,
VerifyFile, VerifyFile,
Waiting, Waiting,
Done, Done,
} }
private readonly VerifyTempFileElement _element; private readonly VerifyTempFileElement _element;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
public VerifyTempFileWithThreadOperation(VerifyTempFileElement element) public VerifyTempFileWithThreadOperation(VerifyTempFileElement element)
{ {
_element = element; _element = element;
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
_steps = ESteps.VerifyFile; _steps = ESteps.VerifyFile;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
if (_steps == ESteps.None || _steps == ESteps.Done) if (_steps == ESteps.None || _steps == ESteps.Done)
return; return;
if (_steps == ESteps.VerifyFile) if (_steps == ESteps.VerifyFile)
{ {
if (BeginVerifyFileWithThread(_element)) if (BeginVerifyFileWithThread(_element))
{ {
_steps = ESteps.Waiting; _steps = ESteps.Waiting;
} }
} }
if (_steps == ESteps.Waiting) if (_steps == ESteps.Waiting)
{ {
int result = _element.Result; int result = _element.Result;
if (result == 0) if (result == 0)
return; return;
VerifyResult = (EVerifyResult)result; VerifyResult = (EVerifyResult)result;
if (VerifyResult == EVerifyResult.Succeed) if (VerifyResult == EVerifyResult.Succeed)
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
else else
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = $"Failed verify file : {_element.TempDataFilePath} ! ErrorCode : {VerifyResult}"; Error = $"Failed verify file : {_element.TempDataFilePath} ! ErrorCode : {VerifyResult}";
} }
} }
} }
private bool BeginVerifyFileWithThread(VerifyTempFileElement element) private bool BeginVerifyFileWithThread(VerifyTempFileElement element)
{ {
return ThreadPool.QueueUserWorkItem(new WaitCallback(VerifyInThread), element); return ThreadPool.QueueUserWorkItem(new WaitCallback(VerifyInThread), element);
} }
private void VerifyInThread(object obj) private void VerifyInThread(object obj)
{ {
VerifyTempFileElement element = (VerifyTempFileElement)obj; VerifyTempFileElement element = (VerifyTempFileElement)obj;
int result = (int)CacheHelper.VerifyingTempFile(element); int result = (int)CacheHelper.VerifyingTempFile(element);
element.Result = result; element.Result = result;
} }
} }
/// <summary> /// <summary>
/// 下载文件验证(非线程版) /// 下载文件验证(非线程版)
/// </summary> /// </summary>
internal class VerifyTempFileWithoutThreadOperation : VerifyTempFileOperation internal class VerifyTempFileWithoutThreadOperation : VerifyTempFileOperation
{ {
private enum ESteps private enum ESteps
{ {
None, None,
VerifyFile, VerifyFile,
Done, Done,
} }
private readonly VerifyTempFileElement _element; private readonly VerifyTempFileElement _element;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
public VerifyTempFileWithoutThreadOperation(VerifyTempFileElement element) public VerifyTempFileWithoutThreadOperation(VerifyTempFileElement element)
{ {
_element = element; _element = element;
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
_steps = ESteps.VerifyFile; _steps = ESteps.VerifyFile;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
if (_steps == ESteps.None || _steps == ESteps.Done) if (_steps == ESteps.None || _steps == ESteps.Done)
return; return;
if (_steps == ESteps.VerifyFile) if (_steps == ESteps.VerifyFile)
{ {
_element.Result = (int)CacheHelper.VerifyingTempFile(_element); _element.Result = (int)CacheHelper.VerifyingTempFile(_element);
VerifyResult = (EVerifyResult)_element.Result; VerifyResult = (EVerifyResult)_element.Result;
if (VerifyResult == EVerifyResult.Succeed) if (VerifyResult == EVerifyResult.Succeed)
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
else else
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = $"Failed verify file : {_element.TempDataFilePath} ! ErrorCode : {VerifyResult}"; Error = $"Failed verify file : {_element.TempDataFilePath} ! ErrorCode : {VerifyResult}";
} }
} }
} }
} }
} }

View File

@ -5,70 +5,70 @@ using System.Collections.Generic;
namespace YooAsset namespace YooAsset
{ {
internal class PackageCachingOperation : AsyncOperationBase internal class PackageCachingOperation : AsyncOperationBase
{ {
private enum ESteps private enum ESteps
{ {
None, None,
FindCacheFiles, FindCacheFiles,
VerifyCacheFiles, VerifyCacheFiles,
Done, Done,
} }
private readonly PersistentManager _persistent; private readonly PersistentManager _persistent;
private readonly CacheManager _cache; private readonly CacheManager _cache;
private FindCacheFilesOperation _findCacheFilesOp; private FindCacheFilesOperation _findCacheFilesOp;
private VerifyCacheFilesOperation _verifyCacheFilesOp; private VerifyCacheFilesOperation _verifyCacheFilesOp;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
public PackageCachingOperation(PersistentManager persistent, CacheManager cache) public PackageCachingOperation(PersistentManager persistent, CacheManager cache)
{ {
_persistent = persistent; _persistent = persistent;
_cache = cache; _cache = cache;
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
_steps = ESteps.FindCacheFiles; _steps = ESteps.FindCacheFiles;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
if (_steps == ESteps.None || _steps == ESteps.Done) if (_steps == ESteps.None || _steps == ESteps.Done)
return; return;
if (_steps == ESteps.FindCacheFiles) if (_steps == ESteps.FindCacheFiles)
{ {
if (_findCacheFilesOp == null) if (_findCacheFilesOp == null)
{ {
_findCacheFilesOp = new FindCacheFilesOperation(_persistent, _cache); _findCacheFilesOp = new FindCacheFilesOperation(_persistent, _cache);
OperationSystem.StartOperation(_cache.PackageName, _findCacheFilesOp); OperationSystem.StartOperation(_cache.PackageName, _findCacheFilesOp);
} }
Progress = _findCacheFilesOp.Progress; Progress = _findCacheFilesOp.Progress;
if (_findCacheFilesOp.IsDone == false) if (_findCacheFilesOp.IsDone == false)
return; return;
_steps = ESteps.VerifyCacheFiles; _steps = ESteps.VerifyCacheFiles;
} }
if (_steps == ESteps.VerifyCacheFiles) if (_steps == ESteps.VerifyCacheFiles)
{ {
if (_verifyCacheFilesOp == null) if (_verifyCacheFilesOp == null)
{ {
_verifyCacheFilesOp = VerifyCacheFilesOperation.CreateOperation(_cache, _findCacheFilesOp.VerifyElements); _verifyCacheFilesOp = VerifyCacheFilesOperation.CreateOperation(_cache, _findCacheFilesOp.VerifyElements);
OperationSystem.StartOperation(_cache.PackageName, _verifyCacheFilesOp); OperationSystem.StartOperation(_cache.PackageName, _verifyCacheFilesOp);
} }
Progress = _verifyCacheFilesOp.Progress; Progress = _verifyCacheFilesOp.Progress;
if (_verifyCacheFilesOp.IsDone == false) if (_verifyCacheFilesOp.IsDone == false)
return; return;
// 注意:总是返回成功 // 注意:总是返回成功
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
int totalCount = _cache.GetAllCachedFilesCount(); int totalCount = _cache.GetAllCachedFilesCount();
YooLogger.Log($"Package '{_cache.PackageName}' cached files count : {totalCount}"); YooLogger.Log($"Package '{_cache.PackageName}' cached files count : {totalCount}");
} }
} }
} }
} }

View File

@ -1,15 +1,15 @@
 
namespace YooAsset namespace YooAsset
{ {
internal static class PersistentHelper internal static class PersistentHelper
{ {
/// <summary> /// <summary>
/// 获取WWW加载本地资源的路径 /// 获取WWW加载本地资源的路径
/// </summary> /// </summary>
public static string ConvertToWWWPath(string path) public static string ConvertToWWWPath(string path)
{ {
#if UNITY_EDITOR #if UNITY_EDITOR
return StringUtility.Format("file:///{0}", path); return StringUtility.Format("file:///{0}", path);
#elif UNITY_WEBGL #elif UNITY_WEBGL
return path; return path;
#elif UNITY_IPHONE #elif UNITY_IPHONE
@ -23,6 +23,6 @@ namespace YooAsset
#else #else
return path; return path;
#endif #endif
} }
} }
} }

View File

@ -5,207 +5,207 @@ using System.Collections.Generic;
namespace YooAsset namespace YooAsset
{ {
internal class PersistentManager internal class PersistentManager
{ {
private readonly Dictionary<string, string> _cachedDataFilePaths = new Dictionary<string, string>(10000); private readonly Dictionary<string, string> _cachedDataFilePaths = new Dictionary<string, string>(10000);
private readonly Dictionary<string, string> _cachedInfoFilePaths = new Dictionary<string, string>(10000); private readonly Dictionary<string, string> _cachedInfoFilePaths = new Dictionary<string, string>(10000);
private readonly Dictionary<string, string> _tempDataFilePaths = new Dictionary<string, string>(10000); private readonly Dictionary<string, string> _tempDataFilePaths = new Dictionary<string, string>(10000);
private readonly Dictionary<string, string> _buildinFilePaths = new Dictionary<string, string>(10000); private readonly Dictionary<string, string> _buildinFilePaths = new Dictionary<string, string>(10000);
/// <summary> /// <summary>
/// 所属包裹 /// 所属包裹
/// </summary> /// </summary>
public readonly string PackageName; public readonly string PackageName;
public string BuildinRoot { private set; get; } public string BuildinRoot { private set; get; }
public string BuildinPackageRoot { private set; get; } public string BuildinPackageRoot { private set; get; }
public string SandboxRoot { private set; get; } public string SandboxRoot { private set; get; }
public string SandboxPackageRoot { private set; get; } public string SandboxPackageRoot { private set; get; }
public string SandboxCacheFilesRoot { private set; get; } public string SandboxCacheFilesRoot { private set; get; }
public string SandboxManifestFilesRoot { private set; get; } public string SandboxManifestFilesRoot { private set; get; }
public string SandboxAppFootPrintFilePath { private set; get; } public string SandboxAppFootPrintFilePath { private set; get; }
public bool AppendFileExtension { private set; get; } public bool AppendFileExtension { private set; get; }
public PersistentManager(string packageName) public PersistentManager(string packageName)
{ {
PackageName = packageName; PackageName = packageName;
} }
/// <summary> /// <summary>
/// 初始化 /// 初始化
/// </summary> /// </summary>
public void Initialize(string buildinRoot, string sandboxRoot, bool appendFileExtension) public void Initialize(string buildinRoot, string sandboxRoot, bool appendFileExtension)
{ {
if (string.IsNullOrEmpty(buildinRoot)) if (string.IsNullOrEmpty(buildinRoot))
BuildinRoot = CreateDefaultBuildinRoot(); BuildinRoot = CreateDefaultBuildinRoot();
else else
BuildinRoot = buildinRoot; BuildinRoot = buildinRoot;
if (string.IsNullOrEmpty(sandboxRoot)) if (string.IsNullOrEmpty(sandboxRoot))
SandboxRoot = CreateDefaultSandboxRoot(); SandboxRoot = CreateDefaultSandboxRoot();
else else
SandboxRoot = sandboxRoot; SandboxRoot = sandboxRoot;
BuildinPackageRoot = PathUtility.Combine(BuildinRoot, PackageName); BuildinPackageRoot = PathUtility.Combine(BuildinRoot, PackageName);
SandboxPackageRoot = PathUtility.Combine(SandboxRoot, PackageName); SandboxPackageRoot = PathUtility.Combine(SandboxRoot, PackageName);
SandboxCacheFilesRoot = PathUtility.Combine(SandboxPackageRoot, YooAssetSettings.CacheFilesFolderName); SandboxCacheFilesRoot = PathUtility.Combine(SandboxPackageRoot, YooAssetSettings.CacheFilesFolderName);
SandboxManifestFilesRoot = PathUtility.Combine(SandboxPackageRoot, YooAssetSettings.ManifestFolderName); SandboxManifestFilesRoot = PathUtility.Combine(SandboxPackageRoot, YooAssetSettings.ManifestFolderName);
SandboxAppFootPrintFilePath = PathUtility.Combine(SandboxPackageRoot, YooAssetSettings.AppFootPrintFileName); SandboxAppFootPrintFilePath = PathUtility.Combine(SandboxPackageRoot, YooAssetSettings.AppFootPrintFileName);
AppendFileExtension = appendFileExtension; AppendFileExtension = appendFileExtension;
} }
private static string CreateDefaultBuildinRoot() private static string CreateDefaultBuildinRoot()
{ {
return PathUtility.Combine(UnityEngine.Application.streamingAssetsPath, YooAssetSettingsData.Setting.DefaultYooFolderName); return PathUtility.Combine(UnityEngine.Application.streamingAssetsPath, YooAssetSettingsData.Setting.DefaultYooFolderName);
} }
private static string CreateDefaultSandboxRoot() private static string CreateDefaultSandboxRoot()
{ {
#if UNITY_EDITOR #if UNITY_EDITOR
// 注意:为了方便调试查看,编辑器下把存储目录放到项目里。 // 注意:为了方便调试查看,编辑器下把存储目录放到项目里。
string projectPath = Path.GetDirectoryName(UnityEngine.Application.dataPath); string projectPath = Path.GetDirectoryName(UnityEngine.Application.dataPath);
projectPath = PathUtility.RegularPath(projectPath); projectPath = PathUtility.RegularPath(projectPath);
return PathUtility.Combine(projectPath, YooAssetSettingsData.Setting.DefaultYooFolderName); return PathUtility.Combine(projectPath, YooAssetSettingsData.Setting.DefaultYooFolderName);
#elif UNITY_STANDALONE #elif UNITY_STANDALONE
return PathUtility.Combine(UnityEngine.Application.dataPath, YooAssetSettingsData.Setting.DefaultYooFolderName); return PathUtility.Combine(UnityEngine.Application.dataPath, YooAssetSettingsData.Setting.DefaultYooFolderName);
#else #else
return PathUtility.Combine(UnityEngine.Application.persistentDataPath, YooAssetSettingsData.Setting.DefaultYooFolderName); return PathUtility.Combine(UnityEngine.Application.persistentDataPath, YooAssetSettingsData.Setting.DefaultYooFolderName);
#endif #endif
} }
public string GetCachedDataFilePath(PackageBundle bundle) public string GetCachedDataFilePath(PackageBundle bundle)
{ {
if (_cachedDataFilePaths.TryGetValue(bundle.CacheGUID, out string filePath) == false) if (_cachedDataFilePaths.TryGetValue(bundle.CacheGUID, out string filePath) == false)
{ {
string folderName = bundle.FileHash.Substring(0, 2); string folderName = bundle.FileHash.Substring(0, 2);
filePath = PathUtility.Combine(SandboxCacheFilesRoot, folderName, bundle.CacheGUID, YooAssetSettings.CacheBundleDataFileName); filePath = PathUtility.Combine(SandboxCacheFilesRoot, folderName, bundle.CacheGUID, YooAssetSettings.CacheBundleDataFileName);
if (AppendFileExtension) if (AppendFileExtension)
filePath += bundle.FileExtension; filePath += bundle.FileExtension;
_cachedDataFilePaths.Add(bundle.CacheGUID, filePath); _cachedDataFilePaths.Add(bundle.CacheGUID, filePath);
} }
return filePath; return filePath;
} }
public string GetCachedInfoFilePath(PackageBundle bundle) public string GetCachedInfoFilePath(PackageBundle bundle)
{ {
if (_cachedInfoFilePaths.TryGetValue(bundle.CacheGUID, out string filePath) == false) if (_cachedInfoFilePaths.TryGetValue(bundle.CacheGUID, out string filePath) == false)
{ {
string folderName = bundle.FileHash.Substring(0, 2); string folderName = bundle.FileHash.Substring(0, 2);
filePath = PathUtility.Combine(SandboxCacheFilesRoot, folderName, bundle.CacheGUID, YooAssetSettings.CacheBundleInfoFileName); filePath = PathUtility.Combine(SandboxCacheFilesRoot, folderName, bundle.CacheGUID, YooAssetSettings.CacheBundleInfoFileName);
_cachedInfoFilePaths.Add(bundle.CacheGUID, filePath); _cachedInfoFilePaths.Add(bundle.CacheGUID, filePath);
} }
return filePath; return filePath;
} }
public string GetTempDataFilePath(PackageBundle bundle) public string GetTempDataFilePath(PackageBundle bundle)
{ {
if (_tempDataFilePaths.TryGetValue(bundle.CacheGUID, out string filePath) == false) if (_tempDataFilePaths.TryGetValue(bundle.CacheGUID, out string filePath) == false)
{ {
string cachedDataFilePath = GetCachedDataFilePath(bundle); string cachedDataFilePath = GetCachedDataFilePath(bundle);
filePath = $"{cachedDataFilePath}.temp"; filePath = $"{cachedDataFilePath}.temp";
_tempDataFilePaths.Add(bundle.CacheGUID, filePath); _tempDataFilePaths.Add(bundle.CacheGUID, filePath);
} }
return filePath; return filePath;
} }
public string GetBuildinFilePath(PackageBundle bundle) public string GetBuildinFilePath(PackageBundle bundle)
{ {
if (_buildinFilePaths.TryGetValue(bundle.CacheGUID, out string filePath) == false) if (_buildinFilePaths.TryGetValue(bundle.CacheGUID, out string filePath) == false)
{ {
filePath = PathUtility.Combine(BuildinPackageRoot, bundle.FileName); filePath = PathUtility.Combine(BuildinPackageRoot, bundle.FileName);
_buildinFilePaths.Add(bundle.CacheGUID, filePath); _buildinFilePaths.Add(bundle.CacheGUID, filePath);
} }
return filePath; return filePath;
} }
/// <summary> /// <summary>
/// 删除沙盒里的包裹目录 /// 删除沙盒里的包裹目录
/// </summary> /// </summary>
public void DeleteSandboxPackageFolder() public void DeleteSandboxPackageFolder()
{ {
if (Directory.Exists(SandboxPackageRoot)) if (Directory.Exists(SandboxPackageRoot))
Directory.Delete(SandboxPackageRoot, true); Directory.Delete(SandboxPackageRoot, true);
} }
/// <summary> /// <summary>
/// 删除沙盒内的缓存文件夹 /// 删除沙盒内的缓存文件夹
/// </summary> /// </summary>
public void DeleteSandboxCacheFilesFolder() public void DeleteSandboxCacheFilesFolder()
{ {
if (Directory.Exists(SandboxCacheFilesRoot)) if (Directory.Exists(SandboxCacheFilesRoot))
Directory.Delete(SandboxCacheFilesRoot, true); Directory.Delete(SandboxCacheFilesRoot, true);
} }
/// <summary> /// <summary>
/// 删除沙盒内的清单文件夹 /// 删除沙盒内的清单文件夹
/// </summary> /// </summary>
public void DeleteSandboxManifestFilesFolder() public void DeleteSandboxManifestFilesFolder()
{ {
if (Directory.Exists(SandboxManifestFilesRoot)) if (Directory.Exists(SandboxManifestFilesRoot))
Directory.Delete(SandboxManifestFilesRoot, true); Directory.Delete(SandboxManifestFilesRoot, true);
} }
/// <summary> /// <summary>
/// 获取沙盒内包裹的清单文件的路径 /// 获取沙盒内包裹的清单文件的路径
/// </summary> /// </summary>
public string GetSandboxPackageManifestFilePath(string packageVersion) public string GetSandboxPackageManifestFilePath(string packageVersion)
{ {
string fileName = YooAssetSettingsData.GetManifestBinaryFileName(PackageName, packageVersion); string fileName = YooAssetSettingsData.GetManifestBinaryFileName(PackageName, packageVersion);
return PathUtility.Combine(SandboxManifestFilesRoot, fileName); return PathUtility.Combine(SandboxManifestFilesRoot, fileName);
} }
/// <summary> /// <summary>
/// 获取沙盒内包裹的哈希文件的路径 /// 获取沙盒内包裹的哈希文件的路径
/// </summary> /// </summary>
public string GetSandboxPackageHashFilePath(string packageVersion) public string GetSandboxPackageHashFilePath(string packageVersion)
{ {
string fileName = YooAssetSettingsData.GetPackageHashFileName(PackageName, packageVersion); string fileName = YooAssetSettingsData.GetPackageHashFileName(PackageName, packageVersion);
return PathUtility.Combine(SandboxManifestFilesRoot, fileName); return PathUtility.Combine(SandboxManifestFilesRoot, fileName);
} }
/// <summary> /// <summary>
/// 获取沙盒内包裹的版本文件的路径 /// 获取沙盒内包裹的版本文件的路径
/// </summary> /// </summary>
public string GetSandboxPackageVersionFilePath() public string GetSandboxPackageVersionFilePath()
{ {
string fileName = YooAssetSettingsData.GetPackageVersionFileName(PackageName); string fileName = YooAssetSettingsData.GetPackageVersionFileName(PackageName);
return PathUtility.Combine(SandboxManifestFilesRoot, fileName); return PathUtility.Combine(SandboxManifestFilesRoot, fileName);
} }
/// <summary> /// <summary>
/// 保存沙盒内默认的包裹版本 /// 保存沙盒内默认的包裹版本
/// </summary> /// </summary>
public void SaveSandboxPackageVersionFile(string version) public void SaveSandboxPackageVersionFile(string version)
{ {
string filePath = GetSandboxPackageVersionFilePath(); string filePath = GetSandboxPackageVersionFilePath();
FileUtility.WriteAllText(filePath, version); FileUtility.WriteAllText(filePath, version);
} }
/// <summary> /// <summary>
/// 获取APP内包裹的清单文件的路径 /// 获取APP内包裹的清单文件的路径
/// </summary> /// </summary>
public string GetBuildinPackageManifestFilePath(string packageVersion) public string GetBuildinPackageManifestFilePath(string packageVersion)
{ {
string fileName = YooAssetSettingsData.GetManifestBinaryFileName(PackageName, packageVersion); string fileName = YooAssetSettingsData.GetManifestBinaryFileName(PackageName, packageVersion);
return PathUtility.Combine(BuildinPackageRoot, fileName); return PathUtility.Combine(BuildinPackageRoot, fileName);
} }
/// <summary> /// <summary>
/// 获取APP内包裹的哈希文件的路径 /// 获取APP内包裹的哈希文件的路径
/// </summary> /// </summary>
public string GetBuildinPackageHashFilePath(string packageVersion) public string GetBuildinPackageHashFilePath(string packageVersion)
{ {
string fileName = YooAssetSettingsData.GetPackageHashFileName(PackageName, packageVersion); string fileName = YooAssetSettingsData.GetPackageHashFileName(PackageName, packageVersion);
return PathUtility.Combine(BuildinPackageRoot, fileName); return PathUtility.Combine(BuildinPackageRoot, fileName);
} }
/// <summary> /// <summary>
/// 获取APP内包裹的版本文件的路径 /// 获取APP内包裹的版本文件的路径
/// </summary> /// </summary>
public string GetBuildinPackageVersionFilePath() public string GetBuildinPackageVersionFilePath()
{ {
string fileName = YooAssetSettingsData.GetPackageVersionFileName(PackageName); string fileName = YooAssetSettingsData.GetPackageVersionFileName(PackageName);
return PathUtility.Combine(BuildinPackageRoot, fileName); return PathUtility.Combine(BuildinPackageRoot, fileName);
} }
} }
} }

View File

@ -2,59 +2,59 @@
namespace YooAsset namespace YooAsset
{ {
/// <summary> /// <summary>
/// 缓存文件验证元素 /// 缓存文件验证元素
/// </summary> /// </summary>
internal class VerifyCacheFileElement internal class VerifyCacheFileElement
{ {
public string PackageName { private set; get; } public string PackageName { private set; get; }
public string CacheGUID { private set; get; } public string CacheGUID { private set; get; }
public string FileRootPath { private set; get; } public string FileRootPath { private set; get; }
public string DataFilePath { private set; get; } public string DataFilePath { private set; get; }
public string InfoFilePath { private set; get; } public string InfoFilePath { private set; get; }
public EVerifyResult Result; public EVerifyResult Result;
public string DataFileCRC; public string DataFileCRC;
public long DataFileSize; public long DataFileSize;
public VerifyCacheFileElement(string packageName, string cacheGUID, string fileRootPath, string dataFilePath, string infoFilePath) public VerifyCacheFileElement(string packageName, string cacheGUID, string fileRootPath, string dataFilePath, string infoFilePath)
{ {
PackageName = packageName; PackageName = packageName;
CacheGUID = cacheGUID; CacheGUID = cacheGUID;
FileRootPath = fileRootPath; FileRootPath = fileRootPath;
DataFilePath = dataFilePath; DataFilePath = dataFilePath;
InfoFilePath = infoFilePath; InfoFilePath = infoFilePath;
} }
public void DeleteFiles() public void DeleteFiles()
{ {
try try
{ {
Directory.Delete(FileRootPath, true); Directory.Delete(FileRootPath, true);
} }
catch(System.Exception e) catch (System.Exception e)
{ {
YooLogger.Warning($"Failed delete cache bundle folder : {e}"); YooLogger.Warning($"Failed delete cache bundle folder : {e}");
} }
} }
} }
/// <summary> /// <summary>
/// 下载文件验证元素 /// 下载文件验证元素
/// </summary> /// </summary>
internal class VerifyTempFileElement internal class VerifyTempFileElement
{ {
public string TempDataFilePath { private set; get; } public string TempDataFilePath { private set; get; }
public string FileCRC { private set; get; } public string FileCRC { private set; get; }
public long FileSize { private set; get; } public long FileSize { private set; get; }
public int Result = 0; // 注意:原子操作对象 public int Result = 0; // 注意:原子操作对象
public VerifyTempFileElement(string tempDataFilePath, string fileCRC, long fileSize) public VerifyTempFileElement(string tempDataFilePath, string fileCRC, long fileSize)
{ {
TempDataFilePath = tempDataFilePath; TempDataFilePath = tempDataFilePath;
FileCRC = fileCRC; FileCRC = fileCRC;
FileSize = fileSize; FileSize = fileSize;
} }
} }
} }

View File

@ -4,36 +4,36 @@ using System.Collections.Generic;
namespace YooAsset namespace YooAsset
{ {
[Serializable] [Serializable]
internal class DebugBundleInfo : IComparer<DebugBundleInfo>, IComparable<DebugBundleInfo> internal class DebugBundleInfo : IComparer<DebugBundleInfo>, IComparable<DebugBundleInfo>
{ {
/// <summary> /// <summary>
/// 包裹名 /// 包裹名
/// </summary> /// </summary>
public string PackageName { set; get; } public string PackageName { set; get; }
/// <summary> /// <summary>
/// 资源包名称 /// 资源包名称
/// </summary> /// </summary>
public string BundleName; public string BundleName;
/// <summary> /// <summary>
/// 引用计数 /// 引用计数
/// </summary> /// </summary>
public int RefCount; public int RefCount;
/// <summary> /// <summary>
/// 加载状态 /// 加载状态
/// </summary> /// </summary>
public string Status; public string Status;
public int CompareTo(DebugBundleInfo other) public int CompareTo(DebugBundleInfo other)
{ {
return Compare(this, other); return Compare(this, other);
} }
public int Compare(DebugBundleInfo a, DebugBundleInfo b) public int Compare(DebugBundleInfo a, DebugBundleInfo b)
{ {
return string.CompareOrdinal(a.BundleName, b.BundleName); return string.CompareOrdinal(a.BundleName, b.BundleName);
} }
} }
} }

View File

@ -5,17 +5,17 @@ using System.Collections.Generic;
namespace YooAsset namespace YooAsset
{ {
[Serializable] [Serializable]
internal class DebugPackageData internal class DebugPackageData
{ {
/// <summary> /// <summary>
/// 包裹名称 /// 包裹名称
/// </summary> /// </summary>
public string PackageName; public string PackageName;
/// <summary> /// <summary>
/// 调试数据列表 /// 调试数据列表
/// </summary> /// </summary>
public List<DebugProviderInfo> ProviderInfos = new List<DebugProviderInfo>(1000); public List<DebugProviderInfo> ProviderInfos = new List<DebugProviderInfo>(1000);
} }
} }

View File

@ -4,56 +4,56 @@ using System.Collections.Generic;
namespace YooAsset namespace YooAsset
{ {
[Serializable] [Serializable]
internal class DebugProviderInfo : IComparer<DebugProviderInfo>, IComparable<DebugProviderInfo> internal class DebugProviderInfo : IComparer<DebugProviderInfo>, IComparable<DebugProviderInfo>
{ {
/// <summary> /// <summary>
/// 包裹名 /// 包裹名
/// </summary> /// </summary>
public string PackageName { set; get; } public string PackageName { set; get; }
/// <summary> /// <summary>
/// 资源对象路径 /// 资源对象路径
/// </summary> /// </summary>
public string AssetPath; public string AssetPath;
/// <summary> /// <summary>
/// 资源出生的场景 /// 资源出生的场景
/// </summary> /// </summary>
public string SpawnScene; public string SpawnScene;
/// <summary> /// <summary>
/// 资源出生的时间 /// 资源出生的时间
/// </summary> /// </summary>
public string SpawnTime; public string SpawnTime;
/// <summary> /// <summary>
/// 加载耗时(单位:毫秒) /// 加载耗时(单位:毫秒)
/// </summary> /// </summary>
public long LoadingTime; public long LoadingTime;
/// <summary> /// <summary>
/// 引用计数 /// 引用计数
/// </summary> /// </summary>
public int RefCount; public int RefCount;
/// <summary> /// <summary>
/// 加载状态 /// 加载状态
/// </summary> /// </summary>
public string Status; public string Status;
/// <summary> /// <summary>
/// 依赖的资源包列表 /// 依赖的资源包列表
/// </summary> /// </summary>
public List<DebugBundleInfo> DependBundleInfos; public List<DebugBundleInfo> DependBundleInfos;
public int CompareTo(DebugProviderInfo other) public int CompareTo(DebugProviderInfo other)
{ {
return Compare(this, other); return Compare(this, other);
} }
public int Compare(DebugProviderInfo a, DebugProviderInfo b) public int Compare(DebugProviderInfo a, DebugProviderInfo b)
{ {
return string.CompareOrdinal(a.AssetPath, b.AssetPath); return string.CompareOrdinal(a.AssetPath, b.AssetPath);
} }
} }
} }

View File

@ -6,34 +6,34 @@ using UnityEngine;
namespace YooAsset namespace YooAsset
{ {
/// <summary> /// <summary>
/// 资源系统调试信息 /// 资源系统调试信息
/// </summary> /// </summary>
[Serializable] [Serializable]
internal class DebugReport internal class DebugReport
{ {
/// <summary> /// <summary>
/// 游戏帧 /// 游戏帧
/// </summary> /// </summary>
public int FrameCount; public int FrameCount;
/// <summary> /// <summary>
/// 调试的包裹数据列表 /// 调试的包裹数据列表
/// </summary> /// </summary>
public List<DebugPackageData> PackageDatas = new List<DebugPackageData>(10); public List<DebugPackageData> PackageDatas = new List<DebugPackageData>(10);
/// <summary>
/// 序列化 /// <summary>
/// </summary> /// 序列化
public static byte[] Serialize(DebugReport debugReport) /// </summary>
public static byte[] Serialize(DebugReport debugReport)
{ {
return Encoding.UTF8.GetBytes(JsonUtility.ToJson(debugReport)); return Encoding.UTF8.GetBytes(JsonUtility.ToJson(debugReport));
} }
/// <summary> /// <summary>
/// 反序列化 /// 反序列化
/// </summary> /// </summary>
public static DebugReport Deserialize(byte[] data) public static DebugReport Deserialize(byte[] data)
{ {
return JsonUtility.FromJson<DebugReport>(Encoding.UTF8.GetString(data)); return JsonUtility.FromJson<DebugReport>(Encoding.UTF8.GetString(data));

View File

@ -4,42 +4,42 @@ using UnityEngine;
namespace YooAsset namespace YooAsset
{ {
internal enum ERemoteCommand internal enum ERemoteCommand
{ {
/// <summary> /// <summary>
/// 采样一次 /// 采样一次
/// </summary> /// </summary>
SampleOnce = 0, SampleOnce = 0,
} }
[Serializable] [Serializable]
internal class RemoteCommand internal class RemoteCommand
{ {
/// <summary> /// <summary>
/// 命令类型 /// 命令类型
/// </summary> /// </summary>
public int CommandType; public int CommandType;
/// <summary> /// <summary>
/// 命令附加参数 /// 命令附加参数
/// </summary> /// </summary>
public string CommandParam; public string CommandParam;
/// <summary> /// <summary>
/// 序列化 /// 序列化
/// </summary> /// </summary>
public static byte[] Serialize(RemoteCommand command) public static byte[] Serialize(RemoteCommand command)
{ {
return Encoding.UTF8.GetBytes(JsonUtility.ToJson(command)); return Encoding.UTF8.GetBytes(JsonUtility.ToJson(command));
} }
/// <summary> /// <summary>
/// 反序列化 /// 反序列化
/// </summary> /// </summary>
public static RemoteCommand Deserialize(byte[] data) public static RemoteCommand Deserialize(byte[] data)
{ {
return JsonUtility.FromJson<RemoteCommand>(Encoding.UTF8.GetString(data)); return JsonUtility.FromJson<RemoteCommand>(Encoding.UTF8.GetString(data));
} }
} }
} }

View File

@ -1,12 +1,11 @@
using System; using System;
using System.Text; using System.Text;
using UnityEngine;
namespace YooAsset namespace YooAsset
{ {
internal class RemoteDebuggerDefine internal class RemoteDebuggerDefine
{ {
public static readonly Guid kMsgSendPlayerToEditor = new Guid("e34a5702dd353724aa315fb8011f08c3"); public static readonly Guid kMsgSendPlayerToEditor = new Guid("e34a5702dd353724aa315fb8011f08c3");
public static readonly Guid kMsgSendEditorToPlayer = new Guid("4d1926c9df5b052469a1c63448b7609a"); public static readonly Guid kMsgSendEditorToPlayer = new Guid("4d1926c9df5b052469a1c63448b7609a");
} }
} }

View File

@ -5,25 +5,25 @@ using UnityEngine.Networking.PlayerConnection;
namespace YooAsset namespace YooAsset
{ {
internal class RemoteDebuggerInRuntime : MonoBehaviour internal class RemoteDebuggerInRuntime : MonoBehaviour
{ {
#if UNITY_EDITOR #if UNITY_EDITOR
/// <summary> /// <summary>
/// 编辑器下获取报告的回调 /// 编辑器下获取报告的回调
/// </summary> /// </summary>
public static Action<int, DebugReport> EditorHandleDebugReportCallback; public static Action<int, DebugReport> EditorHandleDebugReportCallback;
/// <summary> /// <summary>
/// 编辑器下请求报告数据 /// 编辑器下请求报告数据
/// </summary> /// </summary>
public static void EditorRequestDebugReport() public static void EditorRequestDebugReport()
{ {
if(UnityEditor.EditorApplication.isPlaying) if (UnityEditor.EditorApplication.isPlaying)
{ {
var report = YooAssets.GetDebugReport(); var report = YooAssets.GetDebugReport();
EditorHandleDebugReportCallback?.Invoke(0, report); EditorHandleDebugReportCallback?.Invoke(0, report);
} }
} }
#else #else
private void OnEnable() private void OnEnable()
{ {
@ -49,5 +49,5 @@ namespace YooAsset
} }
} }
#endif #endif
} }
} }

View File

@ -7,35 +7,35 @@ using UnityEngine.Networking;
namespace YooAsset namespace YooAsset
{ {
/// <summary> /// <summary>
/// 自定义下载器的请求委托 /// 自定义下载器的请求委托
/// </summary> /// </summary>
public delegate UnityWebRequest DownloadRequestDelegate(string url); public delegate UnityWebRequest DownloadRequestDelegate(string url);
internal static class DownloadHelper internal static class DownloadHelper
{ {
/// <summary> /// <summary>
/// 下载失败后清理文件的HTTP错误码 /// 下载失败后清理文件的HTTP错误码
/// </summary> /// </summary>
public static List<long> ClearFileResponseCodes { set; get; } public static List<long> ClearFileResponseCodes { set; get; }
/// <summary> /// <summary>
/// 自定义下载器的请求委托 /// 自定义下载器的请求委托
/// </summary> /// </summary>
public static DownloadRequestDelegate RequestDelegate = null; public static DownloadRequestDelegate RequestDelegate = null;
/// <summary> /// <summary>
/// 创建一个新的网络请求 /// 创建一个新的网络请求
/// </summary> /// </summary>
public static UnityWebRequest NewRequest(string requestURL) public static UnityWebRequest NewRequest(string requestURL)
{ {
UnityWebRequest webRequest; UnityWebRequest webRequest;
if (RequestDelegate != null) if (RequestDelegate != null)
webRequest = RequestDelegate.Invoke(requestURL); webRequest = RequestDelegate.Invoke(requestURL);
else else
webRequest = new UnityWebRequest(requestURL, UnityWebRequest.kHttpVerbGET); webRequest = new UnityWebRequest(requestURL, UnityWebRequest.kHttpVerbGET);
return webRequest; return webRequest;
} }
} }
} }

View File

@ -6,99 +6,99 @@ using UnityEngine.Networking;
namespace YooAsset namespace YooAsset
{ {
/// <summary> /// <summary>
/// 1. 保证每一时刻资源文件只存在一个下载器 /// 1. 保证每一时刻资源文件只存在一个下载器
/// 2. 保证下载器下载完成后立刻验证并缓存 /// 2. 保证下载器下载完成后立刻验证并缓存
/// 3. 保证资源文件不会被重复下载 /// 3. 保证资源文件不会被重复下载
/// </summary> /// </summary>
internal class DownloadManager internal class DownloadManager
{ {
private readonly Dictionary<string, DownloaderBase> _downloaders = new Dictionary<string, DownloaderBase>(1000); private readonly Dictionary<string, DownloaderBase> _downloaders = new Dictionary<string, DownloaderBase>(1000);
private readonly List<string> _removeList = new List<string>(1000); private readonly List<string> _removeList = new List<string>(1000);
private uint _breakpointResumeFileSize; private uint _breakpointResumeFileSize;
/// <summary> /// <summary>
/// 所属包裹 /// 所属包裹
/// </summary> /// </summary>
public readonly string PackageName; public readonly string PackageName;
public DownloadManager(string packageName) public DownloadManager(string packageName)
{ {
PackageName = packageName; PackageName = packageName;
} }
/// <summary> /// <summary>
/// 初始化 /// 初始化
/// </summary> /// </summary>
public void Initialize(uint breakpointResumeFileSize) public void Initialize(uint breakpointResumeFileSize)
{ {
_breakpointResumeFileSize = breakpointResumeFileSize; _breakpointResumeFileSize = breakpointResumeFileSize;
} }
/// <summary> /// <summary>
/// 更新下载器 /// 更新下载器
/// </summary> /// </summary>
public void Update() public void Update()
{ {
// 更新下载器 // 更新下载器
_removeList.Clear(); _removeList.Clear();
foreach (var valuePair in _downloaders) foreach (var valuePair in _downloaders)
{ {
var downloader = valuePair.Value; var downloader = valuePair.Value;
downloader.Update(); downloader.Update();
if (downloader.IsDone()) if (downloader.IsDone())
{ {
_removeList.Add(valuePair.Key); _removeList.Add(valuePair.Key);
} }
} }
// 移除下载器 // 移除下载器
foreach (var key in _removeList) foreach (var key in _removeList)
{ {
_downloaders.Remove(key); _downloaders.Remove(key);
} }
} }
/// <summary> /// <summary>
/// 销毁所有下载器 /// 销毁所有下载器
/// </summary> /// </summary>
public void DestroyAll() public void DestroyAll()
{ {
foreach (var valuePair in _downloaders) foreach (var valuePair in _downloaders)
{ {
var downloader = valuePair.Value; var downloader = valuePair.Value;
downloader.Abort(); downloader.Abort();
} }
_downloaders.Clear(); _downloaders.Clear();
_removeList.Clear(); _removeList.Clear();
} }
/// <summary> /// <summary>
/// 创建下载器 /// 创建下载器
/// 注意:只有第一次请求的参数才有效 /// 注意:只有第一次请求的参数才有效
/// </summary> /// </summary>
public DownloaderBase CreateDownload(BundleInfo bundleInfo, int failedTryAgain, int timeout = 60) public DownloaderBase CreateDownload(BundleInfo bundleInfo, int failedTryAgain, int timeout = 60)
{ {
// 查询存在的下载器 // 查询存在的下载器
if (_downloaders.TryGetValue(bundleInfo.CachedDataFilePath, out var downloader)) if (_downloaders.TryGetValue(bundleInfo.CachedDataFilePath, out var downloader))
{ {
downloader.Reference(); downloader.Reference();
return downloader; return downloader;
} }
// 如果资源已经缓存 // 如果资源已经缓存
if (bundleInfo.IsCached()) if (bundleInfo.IsCached())
{ {
var completedDownloader = new CompletedDownloader(bundleInfo); var completedDownloader = new CompletedDownloader(bundleInfo);
return completedDownloader; return completedDownloader;
} }
// 创建新的下载器 // 创建新的下载器
DownloaderBase newDownloader = null; DownloaderBase newDownloader = null;
YooLogger.Log($"Beginning to download bundle : {bundleInfo.Bundle.BundleName} URL : {bundleInfo.RemoteMainURL}"); YooLogger.Log($"Beginning to download bundle : {bundleInfo.Bundle.BundleName} URL : {bundleInfo.RemoteMainURL}");
#if UNITY_WEBGL #if UNITY_WEBGL
if (bundleInfo.Bundle.Buildpipeline == EDefaultBuildPipeline.RawFileBuildPipeline.ToString()) if (bundleInfo.Bundle.Buildpipeline == EDefaultBuildPipeline.RawFileBuildPipeline.ToString())
{ {
@ -112,39 +112,39 @@ namespace YooAsset
newDownloader = new WebDownloader(bundleInfo, requesterType, failedTryAgain, timeout); newDownloader = new WebDownloader(bundleInfo, requesterType, failedTryAgain, timeout);
} }
#else #else
FileUtility.CreateFileDirectory(bundleInfo.CachedDataFilePath); FileUtility.CreateFileDirectory(bundleInfo.CachedDataFilePath);
bool resumeDownload = bundleInfo.Bundle.FileSize >= _breakpointResumeFileSize; bool resumeDownload = bundleInfo.Bundle.FileSize >= _breakpointResumeFileSize;
if (resumeDownload) if (resumeDownload)
{ {
System.Type requesterType = typeof(FileResumeRequest); System.Type requesterType = typeof(FileResumeRequest);
newDownloader = new FileDownloader(bundleInfo, requesterType, failedTryAgain, timeout); newDownloader = new FileDownloader(bundleInfo, requesterType, failedTryAgain, timeout);
} }
else else
{ {
System.Type requesterType = typeof(FileGeneralRequest); System.Type requesterType = typeof(FileGeneralRequest);
newDownloader = new FileDownloader(bundleInfo, requesterType, failedTryAgain, timeout); newDownloader = new FileDownloader(bundleInfo, requesterType, failedTryAgain, timeout);
} }
#endif #endif
// 返回新创建的下载器 // 返回新创建的下载器
_downloaders.Add(bundleInfo.CachedDataFilePath, newDownloader); _downloaders.Add(bundleInfo.CachedDataFilePath, newDownloader);
newDownloader.Reference(); newDownloader.Reference();
return newDownloader; return newDownloader;
} }
/// <summary> /// <summary>
/// 停止不再使用的下载器 /// 停止不再使用的下载器
/// </summary> /// </summary>
public void AbortUnusedDownloader() public void AbortUnusedDownloader()
{ {
foreach (var valuePair in _downloaders) foreach (var valuePair in _downloaders)
{ {
var downloader = valuePair.Value; var downloader = valuePair.Value;
if (downloader.RefCount <= 0) if (downloader.RefCount <= 0)
{ {
downloader.Abort(); downloader.Abort();
} }
} }
} }
} }
} }

View File

@ -1,36 +1,36 @@
 
namespace YooAsset namespace YooAsset
{ {
public struct DownloadStatus public struct DownloadStatus
{ {
/// <summary> /// <summary>
/// 下载是否完成 /// 下载是否完成
/// </summary> /// </summary>
public bool IsDone; public bool IsDone;
/// <summary> /// <summary>
/// 下载进度0f~1f /// 下载进度0f~1f
/// </summary> /// </summary>
public float Progress; public float Progress;
/// <summary> /// <summary>
/// 需要下载的总字节数 /// 需要下载的总字节数
/// </summary> /// </summary>
public ulong TotalBytes; public ulong TotalBytes;
/// <summary> /// <summary>
/// 已经下载的字节数 /// 已经下载的字节数
/// </summary> /// </summary>
public ulong DownloadedBytes; public ulong DownloadedBytes;
public static DownloadStatus CreateDefaultStatus() public static DownloadStatus CreateDefaultStatus()
{ {
DownloadStatus status = new DownloadStatus(); DownloadStatus status = new DownloadStatus();
status.IsDone = false; status.IsDone = false;
status.Progress = 0f; status.Progress = 0f;
status.TotalBytes = 0; status.TotalBytes = 0;
status.DownloadedBytes = 0; status.DownloadedBytes = 0;
return status; return status;
} }
} }
} }

View File

@ -1,29 +1,28 @@
 using UnityEngine;
using UnityEngine;
namespace YooAsset namespace YooAsset
{ {
internal sealed class CompletedDownloader : DownloaderBase internal sealed class CompletedDownloader : DownloaderBase
{ {
public CompletedDownloader(BundleInfo bundleInfo) : base(bundleInfo, null, 0, 0) public CompletedDownloader(BundleInfo bundleInfo) : base(bundleInfo, null, 0, 0)
{ {
DownloadProgress = 1f; DownloadProgress = 1f;
DownloadedBytes = (ulong)bundleInfo.Bundle.FileSize; DownloadedBytes = (ulong)bundleInfo.Bundle.FileSize;
_status = EStatus.Succeed; _status = EStatus.Succeed;
} }
public override void SendRequest(params object[] param) public override void SendRequest(params object[] param)
{ {
} }
public override void Update() public override void Update()
{ {
} }
public override void Abort() public override void Abort()
{ {
} }
public override AssetBundle GetAssetBundle() public override AssetBundle GetAssetBundle()
{ {
throw new System.NotImplementedException(); throw new System.NotImplementedException();
} }
} }
} }

View File

@ -4,179 +4,179 @@ using UnityEngine.Networking;
namespace YooAsset namespace YooAsset
{ {
internal abstract class DownloaderBase internal abstract class DownloaderBase
{ {
public enum EStatus public enum EStatus
{ {
None = 0, None = 0,
Succeed, Succeed,
Failed Failed
} }
protected readonly BundleInfo _bundleInfo; protected readonly BundleInfo _bundleInfo;
protected readonly System.Type _requesterType; protected readonly System.Type _requesterType;
protected readonly int _timeout; protected readonly int _timeout;
protected int _failedTryAgain; protected int _failedTryAgain;
protected IWebRequester _requester; protected IWebRequester _requester;
protected EStatus _status = EStatus.None; protected EStatus _status = EStatus.None;
protected string _lastestNetError = string.Empty; protected string _lastestNetError = string.Empty;
protected long _lastestHttpCode = 0; protected long _lastestHttpCode = 0;
// 请求次数 // 请求次数
protected int _requestCount = 0; protected int _requestCount = 0;
protected string _requestURL; protected string _requestURL;
// 超时相关 // 超时相关
protected bool _isAbort = false; protected bool _isAbort = false;
protected ulong _latestDownloadBytes; protected ulong _latestDownloadBytes;
protected float _latestDownloadRealtime; protected float _latestDownloadRealtime;
protected float _tryAgainTimer; protected float _tryAgainTimer;
/// <summary> /// <summary>
/// 是否等待异步结束 /// 是否等待异步结束
/// 警告只能用于解压APP内部资源 /// 警告只能用于解压APP内部资源
/// </summary> /// </summary>
public bool WaitForAsyncComplete = false; public bool WaitForAsyncComplete = false;
/// <summary> /// <summary>
/// 下载进度0f~1f /// 下载进度0f~1f
/// </summary> /// </summary>
public float DownloadProgress { protected set; get; } public float DownloadProgress { protected set; get; }
/// <summary> /// <summary>
/// 已经下载的总字节数 /// 已经下载的总字节数
/// </summary> /// </summary>
public ulong DownloadedBytes { protected set; get; } public ulong DownloadedBytes { protected set; get; }
/// <summary> /// <summary>
/// 引用计数 /// 引用计数
/// </summary> /// </summary>
public int RefCount { private set; get; } public int RefCount { private set; get; }
public DownloaderBase(BundleInfo bundleInfo, System.Type requesterType, int failedTryAgain, int timeout) public DownloaderBase(BundleInfo bundleInfo, System.Type requesterType, int failedTryAgain, int timeout)
{ {
_bundleInfo = bundleInfo; _bundleInfo = bundleInfo;
_requesterType = requesterType; _requesterType = requesterType;
_failedTryAgain = failedTryAgain; _failedTryAgain = failedTryAgain;
_timeout = timeout; _timeout = timeout;
} }
public abstract void SendRequest(params object[] args); public abstract void SendRequest(params object[] args);
public abstract void Update(); public abstract void Update();
public abstract void Abort(); public abstract void Abort();
public abstract AssetBundle GetAssetBundle(); public abstract AssetBundle GetAssetBundle();
/// <summary> /// <summary>
/// 引用(引用计数递加) /// 引用(引用计数递加)
/// </summary> /// </summary>
public void Reference() public void Reference()
{ {
RefCount++; RefCount++;
} }
/// <summary> /// <summary>
/// 释放(引用计数递减) /// 释放(引用计数递减)
/// </summary> /// </summary>
public void Release() public void Release()
{ {
RefCount--; RefCount--;
} }
/// <summary> /// <summary>
/// 检测下载器是否已经完成(无论成功或失败) /// 检测下载器是否已经完成(无论成功或失败)
/// </summary> /// </summary>
public bool IsDone() public bool IsDone()
{ {
return _status == EStatus.Succeed || _status == EStatus.Failed; return _status == EStatus.Succeed || _status == EStatus.Failed;
} }
/// <summary> /// <summary>
/// 下载过程是否发生错误 /// 下载过程是否发生错误
/// </summary> /// </summary>
public bool HasError() public bool HasError()
{ {
return _status == EStatus.Failed; return _status == EStatus.Failed;
} }
/// <summary> /// <summary>
/// 按照错误级别打印错误 /// 按照错误级别打印错误
/// </summary> /// </summary>
public void ReportError() public void ReportError()
{ {
YooLogger.Error(GetLastError()); YooLogger.Error(GetLastError());
} }
/// <summary> /// <summary>
/// 按照警告级别打印错误 /// 按照警告级别打印错误
/// </summary> /// </summary>
public void ReportWarning() public void ReportWarning()
{ {
YooLogger.Warning(GetLastError()); YooLogger.Warning(GetLastError());
} }
/// <summary> /// <summary>
/// 获取最近发生的错误信息 /// 获取最近发生的错误信息
/// </summary> /// </summary>
public string GetLastError() public string GetLastError()
{ {
return $"Failed to download : {_requestURL} Error : {_lastestNetError} Code : {_lastestHttpCode}"; return $"Failed to download : {_requestURL} Error : {_lastestNetError} Code : {_lastestHttpCode}";
} }
/// <summary> /// <summary>
/// 获取下载文件的大小 /// 获取下载文件的大小
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public long GetDownloadFileSize() public long GetDownloadFileSize()
{ {
return _bundleInfo.Bundle.FileSize; return _bundleInfo.Bundle.FileSize;
} }
/// <summary> /// <summary>
/// 获取下载的资源包名称 /// 获取下载的资源包名称
/// </summary> /// </summary>
public string GetDownloadBundleName() public string GetDownloadBundleName()
{ {
return _bundleInfo.Bundle.BundleName; return _bundleInfo.Bundle.BundleName;
} }
/// <summary> /// <summary>
/// 获取网络请求地址 /// 获取网络请求地址
/// </summary> /// </summary>
protected string GetRequestURL() protected string GetRequestURL()
{ {
// 轮流返回请求地址 // 轮流返回请求地址
_requestCount++; _requestCount++;
if (_requestCount % 2 == 0) if (_requestCount % 2 == 0)
return _bundleInfo.RemoteFallbackURL; return _bundleInfo.RemoteFallbackURL;
else else
return _bundleInfo.RemoteMainURL; return _bundleInfo.RemoteMainURL;
} }
/// <summary> /// <summary>
/// 超时判定方法 /// 超时判定方法
/// </summary> /// </summary>
protected void CheckTimeout() protected void CheckTimeout()
{ {
// 注意:在连续时间段内无新增下载数据及判定为超时 // 注意:在连续时间段内无新增下载数据及判定为超时
if (_isAbort == false) if (_isAbort == false)
{ {
if (_latestDownloadBytes != DownloadedBytes) if (_latestDownloadBytes != DownloadedBytes)
{ {
_latestDownloadBytes = DownloadedBytes; _latestDownloadBytes = DownloadedBytes;
_latestDownloadRealtime = Time.realtimeSinceStartup; _latestDownloadRealtime = Time.realtimeSinceStartup;
} }
float offset = Time.realtimeSinceStartup - _latestDownloadRealtime; float offset = Time.realtimeSinceStartup - _latestDownloadRealtime;
if (offset > _timeout) if (offset > _timeout)
{ {
YooLogger.Warning($"Web file request timeout : {_requestURL}"); YooLogger.Warning($"Web file request timeout : {_requestURL}");
if(_requester != null) if (_requester != null)
_requester.Abort(); _requester.Abort();
_isAbort = true; _isAbort = true;
} }
} }
} }
} }
} }

View File

@ -6,211 +6,211 @@ using UnityEngine;
namespace YooAsset namespace YooAsset
{ {
/// <summary> /// <summary>
/// 文件下载器 /// 文件下载器
/// </summary> /// </summary>
internal sealed class FileDownloader : DownloaderBase internal sealed class FileDownloader : DownloaderBase
{ {
private enum ESteps private enum ESteps
{ {
None, None,
PrepareDownload, PrepareDownload,
CreateDownloader, CreateDownloader,
CheckDownload, CheckDownload,
VerifyTempFile, VerifyTempFile,
WaitingVerifyTempFile, WaitingVerifyTempFile,
CachingFile, CachingFile,
TryAgain, TryAgain,
Done, Done,
} }
private VerifyTempFileOperation _verifyFileOp = null; private VerifyTempFileOperation _verifyFileOp = null;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
public FileDownloader(BundleInfo bundleInfo, System.Type requesterType, int failedTryAgain, int timeout) : base(bundleInfo, requesterType, failedTryAgain, timeout) public FileDownloader(BundleInfo bundleInfo, System.Type requesterType, int failedTryAgain, int timeout) : base(bundleInfo, requesterType, failedTryAgain, timeout)
{ {
} }
public override void SendRequest(params object[] args) public override void SendRequest(params object[] args)
{ {
if (_steps == ESteps.None) if (_steps == ESteps.None)
{ {
_steps = ESteps.PrepareDownload; _steps = ESteps.PrepareDownload;
} }
} }
public override void Update() public override void Update()
{ {
if (_steps == ESteps.None) if (_steps == ESteps.None)
return; return;
if (IsDone()) if (IsDone())
return; return;
// 准备下载 // 准备下载
if (_steps == ESteps.PrepareDownload) if (_steps == ESteps.PrepareDownload)
{ {
// 获取请求地址 // 获取请求地址
_requestURL = GetRequestURL(); _requestURL = GetRequestURL();
// 重置变量 // 重置变量
DownloadProgress = 0f; DownloadProgress = 0f;
DownloadedBytes = 0; DownloadedBytes = 0;
// 重置变量 // 重置变量
_isAbort = false; _isAbort = false;
_latestDownloadBytes = 0; _latestDownloadBytes = 0;
_latestDownloadRealtime = Time.realtimeSinceStartup; _latestDownloadRealtime = Time.realtimeSinceStartup;
// 重置计时器 // 重置计时器
if (_tryAgainTimer > 0f) if (_tryAgainTimer > 0f)
YooLogger.Warning($"Try again download : {_requestURL}"); YooLogger.Warning($"Try again download : {_requestURL}");
_tryAgainTimer = 0f; _tryAgainTimer = 0f;
_steps = ESteps.CreateDownloader; _steps = ESteps.CreateDownloader;
} }
// 创建下载器 // 创建下载器
if (_steps == ESteps.CreateDownloader) if (_steps == ESteps.CreateDownloader)
{ {
_requester = (IWebRequester)Activator.CreateInstance(_requesterType); _requester = (IWebRequester)Activator.CreateInstance(_requesterType);
_requester.Create(_requestURL, _bundleInfo); _requester.Create(_requestURL, _bundleInfo);
_steps = ESteps.CheckDownload; _steps = ESteps.CheckDownload;
} }
// 检测下载结果 // 检测下载结果
if (_steps == ESteps.CheckDownload) if (_steps == ESteps.CheckDownload)
{ {
_requester.Update(); _requester.Update();
DownloadedBytes = _requester.DownloadedBytes; DownloadedBytes = _requester.DownloadedBytes;
DownloadProgress = _requester.DownloadProgress; DownloadProgress = _requester.DownloadProgress;
if (_requester.IsDone() == false) if (_requester.IsDone() == false)
{ {
CheckTimeout(); CheckTimeout();
return; return;
} }
_lastestNetError = _requester.RequestNetError; _lastestNetError = _requester.RequestNetError;
_lastestHttpCode = _requester.RequestHttpCode; _lastestHttpCode = _requester.RequestHttpCode;
if (_requester.Status != ERequestStatus.Success) if (_requester.Status != ERequestStatus.Success)
{ {
_steps = ESteps.TryAgain; _steps = ESteps.TryAgain;
} }
else else
{ {
_steps = ESteps.VerifyTempFile; _steps = ESteps.VerifyTempFile;
} }
} }
// 验证下载文件 // 验证下载文件
if (_steps == ESteps.VerifyTempFile) if (_steps == ESteps.VerifyTempFile)
{ {
VerifyTempFileElement element = new VerifyTempFileElement(_bundleInfo.TempDataFilePath, _bundleInfo.Bundle.FileCRC, _bundleInfo.Bundle.FileSize); VerifyTempFileElement element = new VerifyTempFileElement(_bundleInfo.TempDataFilePath, _bundleInfo.Bundle.FileCRC, _bundleInfo.Bundle.FileSize);
_verifyFileOp = VerifyTempFileOperation.CreateOperation(element); _verifyFileOp = VerifyTempFileOperation.CreateOperation(element);
OperationSystem.StartOperation(_bundleInfo.Bundle.PackageName, _verifyFileOp); OperationSystem.StartOperation(_bundleInfo.Bundle.PackageName, _verifyFileOp);
_steps = ESteps.WaitingVerifyTempFile; _steps = ESteps.WaitingVerifyTempFile;
} }
// 等待验证完成 // 等待验证完成
if (_steps == ESteps.WaitingVerifyTempFile) if (_steps == ESteps.WaitingVerifyTempFile)
{ {
if (WaitForAsyncComplete) if (WaitForAsyncComplete)
_verifyFileOp.InternalOnUpdate(); _verifyFileOp.InternalOnUpdate();
if (_verifyFileOp.IsDone == false) if (_verifyFileOp.IsDone == false)
return; return;
if (_verifyFileOp.Status == EOperationStatus.Succeed) if (_verifyFileOp.Status == EOperationStatus.Succeed)
{ {
_steps = ESteps.CachingFile; _steps = ESteps.CachingFile;
} }
else else
{ {
string tempFilePath = _bundleInfo.TempDataFilePath; string tempFilePath = _bundleInfo.TempDataFilePath;
if (File.Exists(tempFilePath)) if (File.Exists(tempFilePath))
File.Delete(tempFilePath); File.Delete(tempFilePath);
_lastestNetError = _verifyFileOp.Error; _lastestNetError = _verifyFileOp.Error;
_steps = ESteps.TryAgain; _steps = ESteps.TryAgain;
} }
} }
// 缓存下载文件 // 缓存下载文件
if (_steps == ESteps.CachingFile) if (_steps == ESteps.CachingFile)
{ {
try try
{ {
CachingFile(); CachingFile();
_status = EStatus.Succeed; _status = EStatus.Succeed;
_steps = ESteps.Done; _steps = ESteps.Done;
} }
catch (Exception e) catch (Exception e)
{ {
_lastestNetError = e.Message; _lastestNetError = e.Message;
_steps = ESteps.TryAgain; _steps = ESteps.TryAgain;
} }
} }
// 重新尝试下载 // 重新尝试下载
if (_steps == ESteps.TryAgain) if (_steps == ESteps.TryAgain)
{ {
if (_failedTryAgain <= 0) if (_failedTryAgain <= 0)
{ {
ReportError(); ReportError();
_status = EStatus.Failed; _status = EStatus.Failed;
_steps = ESteps.Done; _steps = ESteps.Done;
return; return;
} }
_tryAgainTimer += Time.unscaledDeltaTime; _tryAgainTimer += Time.unscaledDeltaTime;
if (_tryAgainTimer > 1f) if (_tryAgainTimer > 1f)
{ {
_failedTryAgain--; _failedTryAgain--;
_steps = ESteps.PrepareDownload; _steps = ESteps.PrepareDownload;
ReportWarning(); ReportWarning();
} }
} }
} }
public override void Abort() public override void Abort()
{ {
if (_requester != null) if (_requester != null)
_requester.Abort(); _requester.Abort();
if (IsDone() == false) if (IsDone() == false)
{ {
_status = EStatus.Failed; _status = EStatus.Failed;
_steps = ESteps.Done; _steps = ESteps.Done;
_lastestNetError = "user abort"; _lastestNetError = "user abort";
_lastestHttpCode = 0; _lastestHttpCode = 0;
} }
} }
public override AssetBundle GetAssetBundle() public override AssetBundle GetAssetBundle()
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
/// <summary> /// <summary>
/// 缓存下载文件 /// 缓存下载文件
/// </summary> /// </summary>
private void CachingFile() private void CachingFile()
{ {
string tempFilePath = _bundleInfo.TempDataFilePath; string tempFilePath = _bundleInfo.TempDataFilePath;
string infoFilePath = _bundleInfo.CachedInfoFilePath; string infoFilePath = _bundleInfo.CachedInfoFilePath;
string dataFilePath = _bundleInfo.CachedDataFilePath; string dataFilePath = _bundleInfo.CachedDataFilePath;
string dataFileCRC = _bundleInfo.Bundle.FileCRC; string dataFileCRC = _bundleInfo.Bundle.FileCRC;
long dataFileSize = _bundleInfo.Bundle.FileSize; long dataFileSize = _bundleInfo.Bundle.FileSize;
if (File.Exists(infoFilePath)) if (File.Exists(infoFilePath))
File.Delete(infoFilePath); File.Delete(infoFilePath);
if (File.Exists(dataFilePath)) if (File.Exists(dataFilePath))
File.Delete(dataFilePath); File.Delete(dataFilePath);
// 移动临时文件路径 // 移动临时文件路径
FileInfo fileInfo = new FileInfo(tempFilePath); FileInfo fileInfo = new FileInfo(tempFilePath);
fileInfo.MoveTo(dataFilePath); fileInfo.MoveTo(dataFilePath);
// 写入信息文件记录验证数据 // 写入信息文件记录验证数据
CacheFileInfo.WriteInfoToFile(infoFilePath, dataFileCRC, dataFileSize); CacheFileInfo.WriteInfoToFile(infoFilePath, dataFileCRC, dataFileSize);
// 记录缓存文件 // 记录缓存文件
_bundleInfo.CacheRecord(); _bundleInfo.CacheRecord();
} }
} }
} }

View File

@ -6,135 +6,135 @@ using UnityEngine;
namespace YooAsset namespace YooAsset
{ {
internal sealed class WebDownloader : DownloaderBase internal sealed class WebDownloader : DownloaderBase
{ {
private enum ESteps private enum ESteps
{ {
None, None,
PrepareDownload, PrepareDownload,
CreateDownloader, CreateDownloader,
CheckDownload, CheckDownload,
TryAgain, TryAgain,
Done, Done,
} }
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
private bool _getAssetBundle = false; private bool _getAssetBundle = false;
public WebDownloader(BundleInfo bundleInfo, System.Type requesterType, int failedTryAgain, int timeout) : base(bundleInfo, requesterType, failedTryAgain, timeout) public WebDownloader(BundleInfo bundleInfo, System.Type requesterType, int failedTryAgain, int timeout) : base(bundleInfo, requesterType, failedTryAgain, timeout)
{ {
} }
public override void SendRequest(params object[] args) public override void SendRequest(params object[] args)
{ {
if (_steps == ESteps.None) if (_steps == ESteps.None)
{ {
if (args.Length > 0) if (args.Length > 0)
{ {
_getAssetBundle = (bool)args[0]; _getAssetBundle = (bool)args[0];
} }
_steps = ESteps.PrepareDownload; _steps = ESteps.PrepareDownload;
} }
} }
public override void Update() public override void Update()
{ {
if (_steps == ESteps.None) if (_steps == ESteps.None)
return; return;
if (IsDone()) if (IsDone())
return; return;
// 创建下载器 // 创建下载器
if (_steps == ESteps.PrepareDownload) if (_steps == ESteps.PrepareDownload)
{ {
// 获取请求地址 // 获取请求地址
_requestURL = GetRequestURL(); _requestURL = GetRequestURL();
// 重置变量 // 重置变量
DownloadProgress = 0f; DownloadProgress = 0f;
DownloadedBytes = 0; DownloadedBytes = 0;
// 重置变量 // 重置变量
_isAbort = false; _isAbort = false;
_latestDownloadBytes = 0; _latestDownloadBytes = 0;
_latestDownloadRealtime = Time.realtimeSinceStartup; _latestDownloadRealtime = Time.realtimeSinceStartup;
// 重置计时器 // 重置计时器
if (_tryAgainTimer > 0f) if (_tryAgainTimer > 0f)
YooLogger.Warning($"Try again download : {_requestURL}"); YooLogger.Warning($"Try again download : {_requestURL}");
_tryAgainTimer = 0f; _tryAgainTimer = 0f;
_steps = ESteps.CreateDownloader; _steps = ESteps.CreateDownloader;
} }
// 创建下载器 // 创建下载器
if (_steps == ESteps.CreateDownloader) if (_steps == ESteps.CreateDownloader)
{ {
_requester = (IWebRequester)Activator.CreateInstance(_requesterType); _requester = (IWebRequester)Activator.CreateInstance(_requesterType);
_requester.Create(_requestURL, _bundleInfo, _getAssetBundle); _requester.Create(_requestURL, _bundleInfo, _getAssetBundle);
_steps = ESteps.CheckDownload; _steps = ESteps.CheckDownload;
} }
// 检测下载结果 // 检测下载结果
if (_steps == ESteps.CheckDownload) if (_steps == ESteps.CheckDownload)
{ {
_requester.Update(); _requester.Update();
DownloadedBytes = _requester.DownloadedBytes; DownloadedBytes = _requester.DownloadedBytes;
DownloadProgress = _requester.DownloadProgress; DownloadProgress = _requester.DownloadProgress;
if (_requester.IsDone() == false) if (_requester.IsDone() == false)
{ {
CheckTimeout(); CheckTimeout();
return; return;
} }
_lastestNetError = _requester.RequestNetError; _lastestNetError = _requester.RequestNetError;
_lastestHttpCode = _requester.RequestHttpCode; _lastestHttpCode = _requester.RequestHttpCode;
if (_requester.Status != ERequestStatus.Success) if (_requester.Status != ERequestStatus.Success)
{ {
_steps = ESteps.TryAgain; _steps = ESteps.TryAgain;
} }
else else
{ {
_status = EStatus.Succeed; _status = EStatus.Succeed;
_steps = ESteps.Done; _steps = ESteps.Done;
} }
} }
// 重新尝试下载 // 重新尝试下载
if (_steps == ESteps.TryAgain) if (_steps == ESteps.TryAgain)
{ {
if (_failedTryAgain <= 0) if (_failedTryAgain <= 0)
{ {
ReportError(); ReportError();
_status = EStatus.Failed; _status = EStatus.Failed;
_steps = ESteps.Done; _steps = ESteps.Done;
return; return;
} }
_tryAgainTimer += Time.unscaledDeltaTime; _tryAgainTimer += Time.unscaledDeltaTime;
if (_tryAgainTimer > 1f) if (_tryAgainTimer > 1f)
{ {
_failedTryAgain--; _failedTryAgain--;
_steps = ESteps.PrepareDownload; _steps = ESteps.PrepareDownload;
ReportWarning(); ReportWarning();
YooLogger.Warning($"Try again download : {_requestURL}"); YooLogger.Warning($"Try again download : {_requestURL}");
} }
} }
} }
public override void Abort() public override void Abort()
{ {
if (_requester != null) if (_requester != null)
_requester.Abort(); _requester.Abort();
if (IsDone() == false) if (IsDone() == false)
{ {
_status = EStatus.Failed; _status = EStatus.Failed;
_steps = ESteps.Done; _steps = ESteps.Done;
_lastestNetError = "user abort"; _lastestNetError = "user abort";
_lastestHttpCode = 0; _lastestHttpCode = 0;
} }
} }
public override AssetBundle GetAssetBundle() public override AssetBundle GetAssetBundle()
{ {
return (AssetBundle)_requester.GetRequestObject(); return (AssetBundle)_requester.GetRequestObject();
} }
} }
} }

View File

@ -4,33 +4,33 @@ using System.Collections.Generic;
namespace YooAsset namespace YooAsset
{ {
public class RequestHelper public class RequestHelper
{ {
/// <summary> /// <summary>
/// 记录网络请求失败事件的次数 /// 记录网络请求失败事件的次数
/// </summary> /// </summary>
private static readonly Dictionary<string, int> _requestFailedRecorder = new Dictionary<string, int>(1000); private static readonly Dictionary<string, int> _requestFailedRecorder = new Dictionary<string, int>(1000);
/// <summary> /// <summary>
/// 记录请求失败事件 /// 记录请求失败事件
/// </summary> /// </summary>
public static void RecordRequestFailed(string packageName, string eventName) public static void RecordRequestFailed(string packageName, string eventName)
{ {
string key = $"{packageName}_{eventName}"; string key = $"{packageName}_{eventName}";
if (_requestFailedRecorder.ContainsKey(key) == false) if (_requestFailedRecorder.ContainsKey(key) == false)
_requestFailedRecorder.Add(key, 0); _requestFailedRecorder.Add(key, 0);
_requestFailedRecorder[key]++; _requestFailedRecorder[key]++;
} }
/// <summary> /// <summary>
/// 获取请求失败的次数 /// 获取请求失败的次数
/// </summary> /// </summary>
public static int GetRequestFailedCount(string packageName, string eventName) public static int GetRequestFailedCount(string packageName, string eventName)
{ {
string key = $"{packageName}_{eventName}"; string key = $"{packageName}_{eventName}";
if (_requestFailedRecorder.ContainsKey(key) == false) if (_requestFailedRecorder.ContainsKey(key) == false)
_requestFailedRecorder.Add(key, 0); _requestFailedRecorder.Add(key, 0);
return _requestFailedRecorder[key]; return _requestFailedRecorder[key];
} }
} }
} }

View File

@ -4,76 +4,76 @@ using UnityEngine.Networking;
namespace YooAsset namespace YooAsset
{ {
internal class AssetBundleWebRequest : IWebRequester internal class AssetBundleWebRequest : IWebRequester
{ {
private UnityWebRequest _webRequest; private UnityWebRequest _webRequest;
private DownloadHandlerAssetBundle _downloadhandler; private DownloadHandlerAssetBundle _downloadhandler;
private AssetBundle _cacheAssetBundle; private AssetBundle _cacheAssetBundle;
private bool _getAssetBundle = false; private bool _getAssetBundle = false;
public ERequestStatus Status { private set; get; } = ERequestStatus.None; public ERequestStatus Status { private set; get; } = ERequestStatus.None;
public float DownloadProgress { private set; get; } public float DownloadProgress { private set; get; }
public ulong DownloadedBytes { private set; get; } public ulong DownloadedBytes { private set; get; }
public string RequestNetError { private set; get; } public string RequestNetError { private set; get; }
public long RequestHttpCode { private set; get; } public long RequestHttpCode { private set; get; }
public AssetBundleWebRequest() { } public AssetBundleWebRequest() { }
public void Create(string requestURL, BundleInfo bundleInfo, params object[] args) public void Create(string requestURL, BundleInfo bundleInfo, params object[] args)
{ {
if (Status != ERequestStatus.None) if (Status != ERequestStatus.None)
throw new System.Exception("Should never get here !"); throw new System.Exception("Should never get here !");
if (args.Length == 0) if (args.Length == 0)
throw new System.Exception("Not found param value"); throw new System.Exception("Not found param value");
// 解析附加参数 // 解析附加参数
_getAssetBundle = (bool)args[0]; _getAssetBundle = (bool)args[0];
// 创建下载器 // 创建下载器
_webRequest = DownloadHelper.NewRequest(requestURL); _webRequest = DownloadHelper.NewRequest(requestURL);
if (CacheHelper.DisableUnityCacheOnWebGL) if (CacheHelper.DisableUnityCacheOnWebGL)
{ {
uint crc = bundleInfo.Bundle.UnityCRC; uint crc = bundleInfo.Bundle.UnityCRC;
_downloadhandler = new DownloadHandlerAssetBundle(requestURL, crc); _downloadhandler = new DownloadHandlerAssetBundle(requestURL, crc);
} }
else else
{ {
uint crc = bundleInfo.Bundle.UnityCRC; uint crc = bundleInfo.Bundle.UnityCRC;
var hash = Hash128.Parse(bundleInfo.Bundle.FileHash); var hash = Hash128.Parse(bundleInfo.Bundle.FileHash);
_downloadhandler = new DownloadHandlerAssetBundle(requestURL, hash, crc); _downloadhandler = new DownloadHandlerAssetBundle(requestURL, hash, crc);
} }
#if UNITY_2020_3_OR_NEWER #if UNITY_2020_3_OR_NEWER
_downloadhandler.autoLoadAssetBundle = false; _downloadhandler.autoLoadAssetBundle = false;
#endif #endif
_webRequest.downloadHandler = _downloadhandler; _webRequest.downloadHandler = _downloadhandler;
_webRequest.disposeDownloadHandlerOnDispose = true; _webRequest.disposeDownloadHandlerOnDispose = true;
_webRequest.SendWebRequest(); _webRequest.SendWebRequest();
Status = ERequestStatus.InProgress; Status = ERequestStatus.InProgress;
} }
public void Update() public void Update()
{ {
if (Status == ERequestStatus.None) if (Status == ERequestStatus.None)
return; return;
if (IsDone()) if (IsDone())
return; return;
DownloadProgress = _webRequest.downloadProgress; DownloadProgress = _webRequest.downloadProgress;
DownloadedBytes = _webRequest.downloadedBytes; DownloadedBytes = _webRequest.downloadedBytes;
if (_webRequest.isDone == false) if (_webRequest.isDone == false)
return; return;
// 检查网络错误 // 检查网络错误
#if UNITY_2020_3_OR_NEWER #if UNITY_2020_3_OR_NEWER
RequestHttpCode = _webRequest.responseCode; RequestHttpCode = _webRequest.responseCode;
if (_webRequest.result != UnityWebRequest.Result.Success) if (_webRequest.result != UnityWebRequest.Result.Success)
{ {
RequestNetError = _webRequest.error; RequestNetError = _webRequest.error;
Status = ERequestStatus.Error; Status = ERequestStatus.Error;
} }
else else
{ {
Status = ERequestStatus.Success; Status = ERequestStatus.Success;
} }
#else #else
RequestHttpCode = _webRequest.responseCode; RequestHttpCode = _webRequest.responseCode;
if (_webRequest.isNetworkError || _webRequest.isHttpError) if (_webRequest.isNetworkError || _webRequest.isHttpError)
@ -87,59 +87,59 @@ namespace YooAsset
} }
#endif #endif
// 缓存加载的AssetBundle对象 // 缓存加载的AssetBundle对象
if (Status == ERequestStatus.Success) if (Status == ERequestStatus.Success)
{ {
if (_getAssetBundle) if (_getAssetBundle)
{ {
_cacheAssetBundle = _downloadhandler.assetBundle; _cacheAssetBundle = _downloadhandler.assetBundle;
if (_cacheAssetBundle == null) if (_cacheAssetBundle == null)
{ {
RequestNetError = "assetBundle is null"; RequestNetError = "assetBundle is null";
Status = ERequestStatus.Error; Status = ERequestStatus.Error;
} }
} }
} }
// 最终释放下载器 // 最终释放下载器
DisposeWebRequest(); DisposeWebRequest();
} }
public void Abort() public void Abort()
{ {
// 如果下载任务还未开始 // 如果下载任务还未开始
if (Status == ERequestStatus.None) if (Status == ERequestStatus.None)
{ {
RequestNetError = "user cancel"; RequestNetError = "user cancel";
Status = ERequestStatus.Error; Status = ERequestStatus.Error;
} }
else else
{ {
// 注意:为了防止同一个文件强制停止之后立马创建新的请求,应该让进行中的请求自然终止。 // 注意:为了防止同一个文件强制停止之后立马创建新的请求,应该让进行中的请求自然终止。
if (_webRequest != null) if (_webRequest != null)
{ {
if (_webRequest.isDone == false) if (_webRequest.isDone == false)
_webRequest.Abort(); // If in progress, halts the UnityWebRequest as soon as possible. _webRequest.Abort(); // If in progress, halts the UnityWebRequest as soon as possible.
} }
} }
} }
public bool IsDone() public bool IsDone()
{ {
if (Status == ERequestStatus.Success || Status == ERequestStatus.Error) if (Status == ERequestStatus.Success || Status == ERequestStatus.Error)
return true; return true;
else else
return false; return false;
} }
public object GetRequestObject() public object GetRequestObject()
{ {
return _cacheAssetBundle; return _cacheAssetBundle;
} }
private void DisposeWebRequest() private void DisposeWebRequest()
{ {
if (_webRequest != null) if (_webRequest != null)
{ {
_webRequest.Dispose(); _webRequest.Dispose();
_webRequest = null; _webRequest = null;
} }
} }
} }
} }

View File

@ -5,83 +5,83 @@ using UnityEngine.Networking;
namespace YooAsset namespace YooAsset
{ {
/// <summary> /// <summary>
/// 支持Unity2018版本的断点续传下载器 /// 支持Unity2018版本的断点续传下载器
/// </summary> /// </summary>
internal class DownloadHandlerFileRange : DownloadHandlerScript internal class DownloadHandlerFileRange : DownloadHandlerScript
{ {
private string _fileSavePath; private string _fileSavePath;
private long _fileTotalSize; private long _fileTotalSize;
private UnityWebRequest _webRequest; private UnityWebRequest _webRequest;
private FileStream _fileStream; private FileStream _fileStream;
private long _localFileSize = 0; private long _localFileSize = 0;
private long _curFileSize = 0; private long _curFileSize = 0;
public DownloadHandlerFileRange(string fileSavePath, long fileTotalSize, UnityWebRequest webRequest) : base(new byte[1024 * 1024]) public DownloadHandlerFileRange(string fileSavePath, long fileTotalSize, UnityWebRequest webRequest) : base(new byte[1024 * 1024])
{ {
_fileSavePath = fileSavePath; _fileSavePath = fileSavePath;
_fileTotalSize = fileTotalSize; _fileTotalSize = fileTotalSize;
_webRequest = webRequest; _webRequest = webRequest;
if (File.Exists(fileSavePath)) if (File.Exists(fileSavePath))
{ {
FileInfo fileInfo = new FileInfo(fileSavePath); FileInfo fileInfo = new FileInfo(fileSavePath);
_localFileSize = fileInfo.Length; _localFileSize = fileInfo.Length;
} }
_fileStream = new FileStream(_fileSavePath, FileMode.Append, FileAccess.Write); _fileStream = new FileStream(_fileSavePath, FileMode.Append, FileAccess.Write);
_curFileSize = _localFileSize; _curFileSize = _localFileSize;
} }
protected override bool ReceiveData(byte[] data, int dataLength) protected override bool ReceiveData(byte[] data, int dataLength)
{ {
if (data == null || dataLength == 0 || _webRequest.responseCode >= 400) if (data == null || dataLength == 0 || _webRequest.responseCode >= 400)
return false; return false;
if (_fileStream == null) if (_fileStream == null)
return false; return false;
_fileStream.Write(data, 0, dataLength); _fileStream.Write(data, 0, dataLength);
_curFileSize += dataLength; _curFileSize += dataLength;
return true; return true;
} }
/// <summary> /// <summary>
/// UnityWebRequest.downloadHandler.data /// UnityWebRequest.downloadHandler.data
/// </summary> /// </summary>
protected override byte[] GetData() protected override byte[] GetData()
{ {
return null; return null;
} }
/// <summary> /// <summary>
/// UnityWebRequest.downloadHandler.text /// UnityWebRequest.downloadHandler.text
/// </summary> /// </summary>
protected override string GetText() protected override string GetText()
{ {
return null; return null;
} }
/// <summary> /// <summary>
/// UnityWebRequest.downloadProgress /// UnityWebRequest.downloadProgress
/// </summary> /// </summary>
protected override float GetProgress() protected override float GetProgress()
{ {
return _fileTotalSize == 0 ? 0 : ((float)_curFileSize) / _fileTotalSize; return _fileTotalSize == 0 ? 0 : ((float)_curFileSize) / _fileTotalSize;
} }
/// <summary> /// <summary>
/// 释放下载句柄 /// 释放下载句柄
/// </summary> /// </summary>
public void Cleanup() public void Cleanup()
{ {
if (_fileStream != null) if (_fileStream != null)
{ {
_fileStream.Flush(); _fileStream.Flush();
_fileStream.Dispose(); _fileStream.Dispose();
_fileStream = null; _fileStream = null;
} }
} }
} }
} }

View File

@ -3,61 +3,61 @@ using UnityEngine.Networking;
namespace YooAsset namespace YooAsset
{ {
internal class FileGeneralRequest : IWebRequester internal class FileGeneralRequest : IWebRequester
{ {
private UnityWebRequest _webRequest; private UnityWebRequest _webRequest;
public ERequestStatus Status { private set; get; } = ERequestStatus.None; public ERequestStatus Status { private set; get; } = ERequestStatus.None;
public float DownloadProgress { private set; get; } public float DownloadProgress { private set; get; }
public ulong DownloadedBytes { private set; get; } public ulong DownloadedBytes { private set; get; }
public string RequestNetError { private set; get; } public string RequestNetError { private set; get; }
public long RequestHttpCode { private set; get; } public long RequestHttpCode { private set; get; }
public FileGeneralRequest() { }
public void Create(string requestURL, BundleInfo bundleInfo, params object[] args)
{
if (Status != ERequestStatus.None)
throw new System.Exception("Should never get here !");
string tempFilePath = bundleInfo.TempDataFilePath; public FileGeneralRequest() { }
public void Create(string requestURL, BundleInfo bundleInfo, params object[] args)
{
if (Status != ERequestStatus.None)
throw new System.Exception("Should never get here !");
// 删除临时文件 string tempFilePath = bundleInfo.TempDataFilePath;
if (File.Exists(tempFilePath))
File.Delete(tempFilePath);
// 创建下载器 // 删除临时文件
_webRequest = DownloadHelper.NewRequest(requestURL); if (File.Exists(tempFilePath))
DownloadHandlerFile handler = new DownloadHandlerFile(tempFilePath); File.Delete(tempFilePath);
handler.removeFileOnAbort = true;
_webRequest.downloadHandler = handler;
_webRequest.disposeDownloadHandlerOnDispose = true;
_webRequest.SendWebRequest();
Status = ERequestStatus.InProgress;
}
public void Update()
{
if (Status == ERequestStatus.None)
return;
if (IsDone())
return;
DownloadProgress = _webRequest.downloadProgress; // 创建下载器
DownloadedBytes = _webRequest.downloadedBytes; _webRequest = DownloadHelper.NewRequest(requestURL);
if (_webRequest.isDone == false) DownloadHandlerFile handler = new DownloadHandlerFile(tempFilePath);
return; handler.removeFileOnAbort = true;
_webRequest.downloadHandler = handler;
_webRequest.disposeDownloadHandlerOnDispose = true;
_webRequest.SendWebRequest();
Status = ERequestStatus.InProgress;
}
public void Update()
{
if (Status == ERequestStatus.None)
return;
if (IsDone())
return;
// 检查网络错误 DownloadProgress = _webRequest.downloadProgress;
DownloadedBytes = _webRequest.downloadedBytes;
if (_webRequest.isDone == false)
return;
// 检查网络错误
#if UNITY_2020_3_OR_NEWER #if UNITY_2020_3_OR_NEWER
RequestHttpCode = _webRequest.responseCode; RequestHttpCode = _webRequest.responseCode;
if (_webRequest.result != UnityWebRequest.Result.Success) if (_webRequest.result != UnityWebRequest.Result.Success)
{ {
RequestNetError = _webRequest.error; RequestNetError = _webRequest.error;
Status = ERequestStatus.Error; Status = ERequestStatus.Error;
} }
else else
{ {
Status = ERequestStatus.Success; Status = ERequestStatus.Success;
} }
#else #else
RequestHttpCode = _webRequest.responseCode; RequestHttpCode = _webRequest.responseCode;
if (_webRequest.isNetworkError || _webRequest.isHttpError) if (_webRequest.isNetworkError || _webRequest.isHttpError)
@ -71,37 +71,37 @@ namespace YooAsset
} }
#endif #endif
// 最终释放下载器 // 最终释放下载器
DisposeWebRequest(); DisposeWebRequest();
} }
public void Abort() public void Abort()
{ {
DisposeWebRequest(); DisposeWebRequest();
if (IsDone() == false) if (IsDone() == false)
{ {
RequestNetError = "user abort"; RequestNetError = "user abort";
RequestHttpCode = 0; RequestHttpCode = 0;
Status = ERequestStatus.Error; Status = ERequestStatus.Error;
} }
} }
public bool IsDone() public bool IsDone()
{ {
if (Status == ERequestStatus.Success || Status == ERequestStatus.Error) if (Status == ERequestStatus.Success || Status == ERequestStatus.Error)
return true; return true;
else else
return false; return false;
} }
public object GetRequestObject() public object GetRequestObject()
{ {
throw new System.NotImplementedException(); throw new System.NotImplementedException();
} }
private void DisposeWebRequest() private void DisposeWebRequest()
{ {
if (_webRequest != null) if (_webRequest != null)
{ {
_webRequest.Dispose(); //注意引擎底层会自动调用Abort方法 _webRequest.Dispose(); //注意引擎底层会自动调用Abort方法
_webRequest = null; _webRequest = null;
} }
} }
} }
} }

View File

@ -3,85 +3,85 @@ using UnityEngine.Networking;
namespace YooAsset namespace YooAsset
{ {
internal class FileResumeRequest : IWebRequester internal class FileResumeRequest : IWebRequester
{ {
private string _tempFilePath; private string _tempFilePath;
private UnityWebRequest _webRequest; private UnityWebRequest _webRequest;
private DownloadHandlerFileRange _downloadHandle; private DownloadHandlerFileRange _downloadHandle;
private ulong _fileOriginLength = 0; private ulong _fileOriginLength = 0;
public ERequestStatus Status { private set; get; } = ERequestStatus.None; public ERequestStatus Status { private set; get; } = ERequestStatus.None;
public float DownloadProgress { private set; get; } public float DownloadProgress { private set; get; }
public ulong DownloadedBytes { private set; get; } public ulong DownloadedBytes { private set; get; }
public string RequestNetError { private set; get; } public string RequestNetError { private set; get; }
public long RequestHttpCode { private set; get; } public long RequestHttpCode { private set; get; }
public FileResumeRequest() { }
public void Create(string requestURL, BundleInfo bundleInfo, params object[] args)
{
if (Status != ERequestStatus.None)
throw new System.Exception("Should never get here !");
_tempFilePath = bundleInfo.TempDataFilePath; public FileResumeRequest() { }
long fileBytes = bundleInfo.Bundle.FileSize; public void Create(string requestURL, BundleInfo bundleInfo, params object[] args)
{
if (Status != ERequestStatus.None)
throw new System.Exception("Should never get here !");
// 获取下载的起始位置 _tempFilePath = bundleInfo.TempDataFilePath;
long fileLength = -1; long fileBytes = bundleInfo.Bundle.FileSize;
if (File.Exists(_tempFilePath))
{
FileInfo fileInfo = new FileInfo(_tempFilePath);
fileLength = fileInfo.Length;
_fileOriginLength = (ulong)fileLength;
DownloadedBytes = _fileOriginLength;
}
// 检测下载起始位置是否有效 // 获取下载的起始位置
if (fileLength >= fileBytes) long fileLength = -1;
{ if (File.Exists(_tempFilePath))
if (File.Exists(_tempFilePath)) {
File.Delete(_tempFilePath); FileInfo fileInfo = new FileInfo(_tempFilePath);
} fileLength = fileInfo.Length;
_fileOriginLength = (ulong)fileLength;
DownloadedBytes = _fileOriginLength;
}
// 创建下载器 // 检测下载起始位置是否有效
_webRequest = DownloadHelper.NewRequest(requestURL); if (fileLength >= fileBytes)
{
if (File.Exists(_tempFilePath))
File.Delete(_tempFilePath);
}
// 创建下载器
_webRequest = DownloadHelper.NewRequest(requestURL);
#if UNITY_2019_4_OR_NEWER #if UNITY_2019_4_OR_NEWER
var handler = new DownloadHandlerFile(_tempFilePath, true); var handler = new DownloadHandlerFile(_tempFilePath, true);
handler.removeFileOnAbort = false; handler.removeFileOnAbort = false;
#else #else
var handler = new DownloadHandlerFileRange(tempFilePath, _bundleInfo.Bundle.FileSize, _webRequest); var handler = new DownloadHandlerFileRange(tempFilePath, _bundleInfo.Bundle.FileSize, _webRequest);
_downloadHandle = handler; _downloadHandle = handler;
#endif #endif
_webRequest.downloadHandler = handler; _webRequest.downloadHandler = handler;
_webRequest.disposeDownloadHandlerOnDispose = true; _webRequest.disposeDownloadHandlerOnDispose = true;
if (fileLength > 0) if (fileLength > 0)
_webRequest.SetRequestHeader("Range", $"bytes={fileLength}-"); _webRequest.SetRequestHeader("Range", $"bytes={fileLength}-");
_webRequest.SendWebRequest(); _webRequest.SendWebRequest();
Status = ERequestStatus.InProgress; Status = ERequestStatus.InProgress;
} }
public void Update() public void Update()
{ {
if (Status == ERequestStatus.None) if (Status == ERequestStatus.None)
return; return;
if (IsDone()) if (IsDone())
return; return;
DownloadProgress = _webRequest.downloadProgress; DownloadProgress = _webRequest.downloadProgress;
DownloadedBytes = _fileOriginLength + _webRequest.downloadedBytes; DownloadedBytes = _fileOriginLength + _webRequest.downloadedBytes;
if (_webRequest.isDone == false) if (_webRequest.isDone == false)
return; return;
// 检查网络错误 // 检查网络错误
#if UNITY_2020_3_OR_NEWER #if UNITY_2020_3_OR_NEWER
RequestHttpCode = _webRequest.responseCode; RequestHttpCode = _webRequest.responseCode;
if (_webRequest.result != UnityWebRequest.Result.Success) if (_webRequest.result != UnityWebRequest.Result.Success)
{ {
RequestNetError = _webRequest.error; RequestNetError = _webRequest.error;
Status = ERequestStatus.Error; Status = ERequestStatus.Error;
} }
else else
{ {
Status = ERequestStatus.Success; Status = ERequestStatus.Success;
} }
#else #else
RequestHttpCode = _webRequest.responseCode; RequestHttpCode = _webRequest.responseCode;
if (_webRequest.isNetworkError || _webRequest.isHttpError) if (_webRequest.isNetworkError || _webRequest.isHttpError)
@ -95,56 +95,56 @@ namespace YooAsset
} }
#endif #endif
// 注意:下载断点续传文件发生特殊错误码之后删除文件 // 注意:下载断点续传文件发生特殊错误码之后删除文件
if (Status == ERequestStatus.Error) if (Status == ERequestStatus.Error)
{ {
if (DownloadHelper.ClearFileResponseCodes != null) if (DownloadHelper.ClearFileResponseCodes != null)
{ {
if (DownloadHelper.ClearFileResponseCodes.Contains(RequestHttpCode)) if (DownloadHelper.ClearFileResponseCodes.Contains(RequestHttpCode))
{ {
if (File.Exists(_tempFilePath)) if (File.Exists(_tempFilePath))
File.Delete(_tempFilePath); File.Delete(_tempFilePath);
} }
} }
} }
// 最终释放下载器 // 最终释放下载器
DisposeWebRequest(); DisposeWebRequest();
} }
public void Abort() public void Abort()
{ {
DisposeWebRequest(); DisposeWebRequest();
if (IsDone() == false) if (IsDone() == false)
{ {
RequestNetError = "user abort"; RequestNetError = "user abort";
RequestHttpCode = 0; RequestHttpCode = 0;
Status = ERequestStatus.Error; Status = ERequestStatus.Error;
} }
} }
public bool IsDone() public bool IsDone()
{ {
if (Status == ERequestStatus.Success || Status == ERequestStatus.Error) if (Status == ERequestStatus.Success || Status == ERequestStatus.Error)
return true; return true;
else else
return false; return false;
} }
public object GetRequestObject() public object GetRequestObject()
{ {
throw new System.NotImplementedException(); throw new System.NotImplementedException();
} }
private void DisposeWebRequest() private void DisposeWebRequest()
{ {
if (_downloadHandle != null) if (_downloadHandle != null)
{ {
_downloadHandle.Cleanup(); _downloadHandle.Cleanup();
_downloadHandle = null; _downloadHandle = null;
} }
if (_webRequest != null) if (_webRequest != null)
{ {
_webRequest.Dispose(); _webRequest.Dispose();
_webRequest = null; _webRequest = null;
} }
} }
} }
} }

View File

@ -1,65 +1,65 @@
 
namespace YooAsset namespace YooAsset
{ {
internal enum ERequestStatus internal enum ERequestStatus
{ {
None, None,
InProgress, InProgress,
Error, Error,
Success, Success,
} }
internal interface IWebRequester internal interface IWebRequester
{ {
/// <summary> /// <summary>
/// 任务状态 /// 任务状态
/// </summary> /// </summary>
public ERequestStatus Status { get; } public ERequestStatus Status { get; }
/// <summary> /// <summary>
/// 下载进度0f~1f /// 下载进度0f~1f
/// </summary> /// </summary>
public float DownloadProgress { get; } public float DownloadProgress { get; }
/// <summary> /// <summary>
/// 已经下载的总字节数 /// 已经下载的总字节数
/// </summary> /// </summary>
public ulong DownloadedBytes { get; } public ulong DownloadedBytes { get; }
/// <summary> /// <summary>
/// 返回的网络错误 /// 返回的网络错误
/// </summary> /// </summary>
public string RequestNetError { get; } public string RequestNetError { get; }
/// <summary> /// <summary>
/// 返回的HTTP CODE /// 返回的HTTP CODE
/// </summary> /// </summary>
public long RequestHttpCode { get; } public long RequestHttpCode { get; }
/// <summary> /// <summary>
/// 创建任务 /// 创建任务
/// </summary> /// </summary>
public void Create(string url, BundleInfo bundleInfo, params object[] args); public void Create(string url, BundleInfo bundleInfo, params object[] args);
/// <summary> /// <summary>
/// 更新任务 /// 更新任务
/// </summary> /// </summary>
public void Update(); public void Update();
/// <summary> /// <summary>
/// 终止任务 /// 终止任务
/// </summary> /// </summary>
public void Abort(); public void Abort();
/// <summary> /// <summary>
/// 是否已经完成(无论成功或失败) /// 是否已经完成(无论成功或失败)
/// </summary> /// </summary>
public bool IsDone(); public bool IsDone();
/// <summary> /// <summary>
/// 获取请求的对象 /// 获取请求的对象
/// </summary> /// </summary>
public object GetRequestObject(); public object GetRequestObject();
} }
} }

View File

@ -5,34 +5,34 @@ using System.Threading;
namespace YooAsset namespace YooAsset
{ {
/// <summary> /// <summary>
/// 同步其它线程里的回调到主线程里 /// 同步其它线程里的回调到主线程里
/// 注意Unity3D中需要设置Scripting Runtime Version为.NET4.6 /// 注意Unity3D中需要设置Scripting Runtime Version为.NET4.6
/// </summary> /// </summary>
internal sealed class ThreadSyncContext : SynchronizationContext internal sealed class ThreadSyncContext : SynchronizationContext
{ {
private readonly ConcurrentQueue<Action> _safeQueue = new ConcurrentQueue<Action>(); private readonly ConcurrentQueue<Action> _safeQueue = new ConcurrentQueue<Action>();
/// <summary> /// <summary>
/// 更新同步队列 /// 更新同步队列
/// </summary> /// </summary>
public void Update() public void Update()
{ {
while (true) while (true)
{ {
if (_safeQueue.TryDequeue(out Action action) == false) if (_safeQueue.TryDequeue(out Action action) == false)
return; return;
action.Invoke(); action.Invoke();
} }
} }
/// <summary> /// <summary>
/// 向同步队列里投递一个回调方法 /// 向同步队列里投递一个回调方法
/// </summary> /// </summary>
public override void Post(SendOrPostCallback callback, object state) public override void Post(SendOrPostCallback callback, object state)
{ {
Action action = new Action(() => { callback(state); }); Action action = new Action(() => { callback(state); });
_safeQueue.Enqueue(action); _safeQueue.Enqueue(action);
} }
} }
} }

View File

@ -6,46 +6,46 @@ using UnityEngine;
namespace YooAsset namespace YooAsset
{ {
internal class UnityWebDataRequester : UnityWebRequesterBase internal class UnityWebDataRequester : UnityWebRequesterBase
{ {
/// <summary> /// <summary>
/// 发送GET请求 /// 发送GET请求
/// </summary> /// </summary>
public void SendRequest(string url, int timeout = 60) public void SendRequest(string url, int timeout = 60)
{ {
if (_webRequest == null) if (_webRequest == null)
{ {
URL = url; URL = url;
ResetTimeout(timeout); ResetTimeout(timeout);
_webRequest = DownloadHelper.NewRequest(URL); _webRequest = DownloadHelper.NewRequest(URL);
DownloadHandlerBuffer handler = new DownloadHandlerBuffer(); DownloadHandlerBuffer handler = new DownloadHandlerBuffer();
_webRequest.downloadHandler = handler; _webRequest.downloadHandler = handler;
_webRequest.disposeDownloadHandlerOnDispose = true; _webRequest.disposeDownloadHandlerOnDispose = true;
_operationHandle = _webRequest.SendWebRequest(); _operationHandle = _webRequest.SendWebRequest();
} }
} }
/// <summary> /// <summary>
/// 获取下载的字节数据 /// 获取下载的字节数据
/// </summary> /// </summary>
public byte[] GetData() public byte[] GetData()
{ {
if (_webRequest != null && IsDone()) if (_webRequest != null && IsDone())
return _webRequest.downloadHandler.data; return _webRequest.downloadHandler.data;
else else
return null; return null;
} }
/// <summary> /// <summary>
/// 获取下载的文本数据 /// 获取下载的文本数据
/// </summary> /// </summary>
public string GetText() public string GetText()
{ {
if (_webRequest != null && IsDone()) if (_webRequest != null && IsDone())
return _webRequest.downloadHandler.text; return _webRequest.downloadHandler.text;
else else
return null; return null;
} }
} }
} }

View File

@ -6,25 +6,25 @@ using UnityEngine;
namespace YooAsset namespace YooAsset
{ {
internal class UnityWebFileRequester : UnityWebRequesterBase internal class UnityWebFileRequester : UnityWebRequesterBase
{ {
/// <summary> /// <summary>
/// 发送GET请求 /// 发送GET请求
/// </summary> /// </summary>
public void SendRequest(string url, string fileSavePath, int timeout = 60) public void SendRequest(string url, string fileSavePath, int timeout = 60)
{ {
if (_webRequest == null) if (_webRequest == null)
{ {
URL = url; URL = url;
ResetTimeout(timeout); ResetTimeout(timeout);
_webRequest = DownloadHelper.NewRequest(URL); _webRequest = DownloadHelper.NewRequest(URL);
DownloadHandlerFile handler = new DownloadHandlerFile(fileSavePath); DownloadHandlerFile handler = new DownloadHandlerFile(fileSavePath);
handler.removeFileOnAbort = true; handler.removeFileOnAbort = true;
_webRequest.downloadHandler = handler; _webRequest.downloadHandler = handler;
_webRequest.disposeDownloadHandlerOnDispose = true; _webRequest.disposeDownloadHandlerOnDispose = true;
_operationHandle = _webRequest.SendWebRequest(); _operationHandle = _webRequest.SendWebRequest();
} }
} }
} }
} }

View File

@ -6,111 +6,111 @@ using UnityEngine;
namespace YooAsset namespace YooAsset
{ {
internal abstract class UnityWebRequesterBase internal abstract class UnityWebRequesterBase
{ {
protected UnityWebRequest _webRequest; protected UnityWebRequest _webRequest;
protected UnityWebRequestAsyncOperation _operationHandle; protected UnityWebRequestAsyncOperation _operationHandle;
// 超时相关 // 超时相关
private float _timeout; private float _timeout;
private bool _isAbort = false; private bool _isAbort = false;
private ulong _latestDownloadBytes; private ulong _latestDownloadBytes;
private float _latestDownloadRealtime; private float _latestDownloadRealtime;
/// <summary> /// <summary>
/// 请求URL地址 /// 请求URL地址
/// </summary> /// </summary>
public string URL { protected set; get; } public string URL { protected set; get; }
protected void ResetTimeout(float timeout) protected void ResetTimeout(float timeout)
{ {
_timeout = timeout; _timeout = timeout;
_latestDownloadBytes = 0; _latestDownloadBytes = 0;
_latestDownloadRealtime = Time.realtimeSinceStartup; _latestDownloadRealtime = Time.realtimeSinceStartup;
} }
/// <summary> /// <summary>
/// 释放下载器 /// 释放下载器
/// </summary> /// </summary>
public void Dispose() public void Dispose()
{ {
if (_webRequest != null) if (_webRequest != null)
{ {
_webRequest.Dispose(); _webRequest.Dispose();
_webRequest = null; _webRequest = null;
_operationHandle = null; _operationHandle = null;
} }
} }
/// <summary> /// <summary>
/// 是否完毕(无论成功失败) /// 是否完毕(无论成功失败)
/// </summary> /// </summary>
public bool IsDone() public bool IsDone()
{ {
if (_operationHandle == null) if (_operationHandle == null)
return false; return false;
return _operationHandle.isDone; return _operationHandle.isDone;
} }
/// <summary> /// <summary>
/// 下载进度 /// 下载进度
/// </summary> /// </summary>
public float Progress() public float Progress()
{ {
if (_operationHandle == null) if (_operationHandle == null)
return 0; return 0;
return _operationHandle.progress; return _operationHandle.progress;
} }
/// <summary> /// <summary>
/// 下载是否发生错误 /// 下载是否发生错误
/// </summary> /// </summary>
public bool HasError() public bool HasError()
{ {
#if UNITY_2020_3_OR_NEWER #if UNITY_2020_3_OR_NEWER
return _webRequest.result != UnityWebRequest.Result.Success; return _webRequest.result != UnityWebRequest.Result.Success;
#else #else
if (_webRequest.isNetworkError || _webRequest.isHttpError) if (_webRequest.isNetworkError || _webRequest.isHttpError)
return true; return true;
else else
return false; return false;
#endif #endif
} }
/// <summary> /// <summary>
/// 获取错误信息 /// 获取错误信息
/// </summary> /// </summary>
public string GetError() public string GetError()
{ {
if (_webRequest != null) if (_webRequest != null)
{ {
return $"URL : {URL} Error : {_webRequest.error}"; return $"URL : {URL} Error : {_webRequest.error}";
} }
return string.Empty; return string.Empty;
} }
/// <summary> /// <summary>
/// 检测超时 /// 检测超时
/// </summary> /// </summary>
public void CheckTimeout() public void CheckTimeout()
{ {
// 注意:在连续时间段内无新增下载数据及判定为超时 // 注意:在连续时间段内无新增下载数据及判定为超时
if (_isAbort == false) if (_isAbort == false)
{ {
if (_latestDownloadBytes != _webRequest.downloadedBytes) if (_latestDownloadBytes != _webRequest.downloadedBytes)
{ {
_latestDownloadBytes = _webRequest.downloadedBytes; _latestDownloadBytes = _webRequest.downloadedBytes;
_latestDownloadRealtime = Time.realtimeSinceStartup; _latestDownloadRealtime = Time.realtimeSinceStartup;
} }
float offset = Time.realtimeSinceStartup - _latestDownloadRealtime; float offset = Time.realtimeSinceStartup - _latestDownloadRealtime;
if (offset > _timeout) if (offset > _timeout)
{ {
_webRequest.Abort(); _webRequest.Abort();
_isAbort = true; _isAbort = true;
} }
} }
} }
} }
} }

View File

@ -1,154 +1,154 @@
 
namespace YooAsset namespace YooAsset
{ {
/// <summary> /// <summary>
/// 默认的构建管线 /// 默认的构建管线
/// </summary> /// </summary>
public enum EDefaultBuildPipeline public enum EDefaultBuildPipeline
{ {
/// <summary> /// <summary>
/// 内置构建管线 /// 内置构建管线
/// </summary> /// </summary>
BuiltinBuildPipeline, BuiltinBuildPipeline,
/// <summary> /// <summary>
/// 可编程构建管线 /// 可编程构建管线
/// </summary> /// </summary>
ScriptableBuildPipeline, ScriptableBuildPipeline,
/// <summary> /// <summary>
/// 原生文件构建管线 /// 原生文件构建管线
/// </summary> /// </summary>
RawFileBuildPipeline, RawFileBuildPipeline,
} }
/// <summary> /// <summary>
/// 运行模式 /// 运行模式
/// </summary> /// </summary>
public enum EPlayMode public enum EPlayMode
{ {
/// <summary> /// <summary>
/// 编辑器下的模拟模式 /// 编辑器下的模拟模式
/// </summary> /// </summary>
EditorSimulateMode, EditorSimulateMode,
/// <summary> /// <summary>
/// 离线运行模式 /// 离线运行模式
/// </summary> /// </summary>
OfflinePlayMode, OfflinePlayMode,
/// <summary> /// <summary>
/// 联机运行模式 /// 联机运行模式
/// </summary> /// </summary>
HostPlayMode, HostPlayMode,
/// <summary> /// <summary>
/// WebGL运行模式 /// WebGL运行模式
/// </summary> /// </summary>
WebPlayMode, WebPlayMode,
} }
/// <summary> /// <summary>
/// 初始化参数 /// 初始化参数
/// </summary> /// </summary>
public abstract class InitializeParameters public abstract class InitializeParameters
{ {
/// <summary> /// <summary>
/// 内置文件的根路径 /// 内置文件的根路径
/// 注意:当参数为空的时候会使用默认的根目录。 /// 注意:当参数为空的时候会使用默认的根目录。
/// </summary> /// </summary>
public string BuildinRootDirectory = string.Empty; public string BuildinRootDirectory = string.Empty;
/// <summary> /// <summary>
/// 沙盒文件的根路径 /// 沙盒文件的根路径
/// 注意:当参数为空的时候会使用默认的根目录。 /// 注意:当参数为空的时候会使用默认的根目录。
/// </summary> /// </summary>
public string SandboxRootDirectory = string.Empty; public string SandboxRootDirectory = string.Empty;
/// <summary> /// <summary>
/// 缓存文件追加原始后缀格式 /// 缓存文件追加原始后缀格式
/// </summary> /// </summary>
public bool CacheFileAppendExtension = false; public bool CacheFileAppendExtension = false;
/// <summary> /// <summary>
/// 缓存系统启动时的验证级别 /// 缓存系统启动时的验证级别
/// </summary> /// </summary>
public EVerifyLevel CacheBootVerifyLevel = EVerifyLevel.Middle; public EVerifyLevel CacheBootVerifyLevel = EVerifyLevel.Middle;
/// <summary> /// <summary>
/// 自动销毁不再使用的资源提供者 /// 自动销毁不再使用的资源提供者
/// </summary> /// </summary>
public bool AutoDestroyAssetProvider = false; public bool AutoDestroyAssetProvider = false;
/// <summary> /// <summary>
/// 启用断点续传参数 /// 启用断点续传参数
/// 说明:当文件的大小大于设置的字节数时启用断点续传下载器 /// 说明:当文件的大小大于设置的字节数时启用断点续传下载器
/// </summary> /// </summary>
public uint BreakpointResumeFileSize = int.MaxValue; public uint BreakpointResumeFileSize = int.MaxValue;
/// <summary> /// <summary>
/// 文件解密服务接口 /// 文件解密服务接口
/// </summary> /// </summary>
public IDecryptionServices DecryptionServices = null; public IDecryptionServices DecryptionServices = null;
} }
/// <summary> /// <summary>
/// 编辑器下模拟运行模式的初始化参数 /// 编辑器下模拟运行模式的初始化参数
/// </summary> /// </summary>
public class EditorSimulateModeParameters : InitializeParameters public class EditorSimulateModeParameters : InitializeParameters
{ {
/// <summary> /// <summary>
/// 用于模拟运行的资源清单路径 /// 用于模拟运行的资源清单路径
/// </summary> /// </summary>
public string SimulateManifestFilePath = string.Empty; public string SimulateManifestFilePath = string.Empty;
} }
/// <summary> /// <summary>
/// 离线运行模式的初始化参数 /// 离线运行模式的初始化参数
/// </summary> /// </summary>
public class OfflinePlayModeParameters : InitializeParameters public class OfflinePlayModeParameters : InitializeParameters
{ {
} }
/// <summary> /// <summary>
/// 联机运行模式的初始化参数 /// 联机运行模式的初始化参数
/// </summary> /// </summary>
public class HostPlayModeParameters : InitializeParameters public class HostPlayModeParameters : InitializeParameters
{ {
/// <summary> /// <summary>
/// 远端资源地址查询服务类 /// 远端资源地址查询服务类
/// </summary> /// </summary>
public IRemoteServices RemoteServices = null; public IRemoteServices RemoteServices = null;
/// <summary> /// <summary>
/// 内置资源查询服务接口 /// 内置资源查询服务接口
/// </summary> /// </summary>
public IBuildinQueryServices BuildinQueryServices = null; public IBuildinQueryServices BuildinQueryServices = null;
/// <summary> /// <summary>
/// 分发资源查询服务接口 /// 分发资源查询服务接口
/// </summary> /// </summary>
public IDeliveryQueryServices DeliveryQueryServices = null; public IDeliveryQueryServices DeliveryQueryServices = null;
/// <summary> /// <summary>
/// 分发资源加载服务接口 /// 分发资源加载服务接口
/// </summary> /// </summary>
public IDeliveryLoadServices DeliveryLoadServices = null; public IDeliveryLoadServices DeliveryLoadServices = null;
} }
/// <summary> /// <summary>
/// WebGL运行模式的初始化参数 /// WebGL运行模式的初始化参数
/// </summary> /// </summary>
public class WebPlayModeParameters : InitializeParameters public class WebPlayModeParameters : InitializeParameters
{ {
/// <summary> /// <summary>
/// 远端资源地址查询服务类 /// 远端资源地址查询服务类
/// </summary> /// </summary>
public IRemoteServices RemoteServices = null; public IRemoteServices RemoteServices = null;
/// <summary> /// <summary>
/// 内置资源查询服务接口 /// 内置资源查询服务接口
/// </summary> /// </summary>
public IBuildinQueryServices BuildinQueryServices = null; public IBuildinQueryServices BuildinQueryServices = null;
} }
} }

View File

@ -5,148 +5,148 @@ using System.Threading.Tasks;
namespace YooAsset namespace YooAsset
{ {
public abstract class AsyncOperationBase : IEnumerator, IComparable<AsyncOperationBase> public abstract class AsyncOperationBase : IEnumerator, IComparable<AsyncOperationBase>
{ {
// 用户请求的回调 // 用户请求的回调
private Action<AsyncOperationBase> _callback; private Action<AsyncOperationBase> _callback;
// 是否已经完成 // 是否已经完成
internal bool IsFinish = false; internal bool IsFinish = false;
/// <summary>
/// 所属包裹
/// </summary>
public string PackageName { private set; get; }
/// <summary> /// <summary>
/// 优先级 /// 所属包裹
/// </summary> /// </summary>
public uint Priority { set; get; } = 0; public string PackageName { private set; get; }
/// <summary> /// <summary>
/// 状态 /// 优先级
/// </summary> /// </summary>
public EOperationStatus Status { get; protected set; } = EOperationStatus.None; public uint Priority { set; get; } = 0;
/// <summary> /// <summary>
/// 错误信息 /// 状态
/// </summary> /// </summary>
public string Error { get; protected set; } public EOperationStatus Status { get; protected set; } = EOperationStatus.None;
/// <summary> /// <summary>
/// 处理进度 /// 错误信息
/// </summary> /// </summary>
public float Progress { get; protected set; } public string Error { get; protected set; }
/// <summary> /// <summary>
/// 是否已经完成 /// 处理进度
/// </summary> /// </summary>
public bool IsDone public float Progress { get; protected set; }
{
get
{
return Status == EOperationStatus.Failed || Status == EOperationStatus.Succeed;
}
}
/// <summary> /// <summary>
/// 完成事件 /// 是否已经完成
/// </summary> /// </summary>
public event Action<AsyncOperationBase> Completed public bool IsDone
{ {
add get
{ {
if (IsDone) return Status == EOperationStatus.Failed || Status == EOperationStatus.Succeed;
value.Invoke(this); }
else }
_callback += value;
}
remove
{
_callback -= value;
}
}
/// <summary> /// <summary>
/// 异步操作任务 /// 完成事件
/// </summary> /// </summary>
public Task Task public event Action<AsyncOperationBase> Completed
{ {
get add
{ {
if (_taskCompletionSource == null) if (IsDone)
{ value.Invoke(this);
_taskCompletionSource = new TaskCompletionSource<object>(); else
if (IsDone) _callback += value;
_taskCompletionSource.SetResult(null); }
} remove
return _taskCompletionSource.Task; {
} _callback -= value;
} }
}
internal abstract void InternalOnStart(); /// <summary>
internal abstract void InternalOnUpdate(); /// 异步操作任务
internal virtual void InternalOnAbort() { } /// </summary>
public Task Task
{
get
{
if (_taskCompletionSource == null)
{
_taskCompletionSource = new TaskCompletionSource<object>();
if (IsDone)
_taskCompletionSource.SetResult(null);
}
return _taskCompletionSource.Task;
}
}
internal void Init(string packageName) internal abstract void InternalOnStart();
{ internal abstract void InternalOnUpdate();
PackageName = packageName; internal virtual void InternalOnAbort() { }
}
internal void SetStart()
{
Status = EOperationStatus.Processing;
InternalOnStart();
}
internal void SetFinish()
{
IsFinish = true;
// 进度百分百完成 internal void Init(string packageName)
Progress = 1f; {
PackageName = packageName;
}
internal void SetStart()
{
Status = EOperationStatus.Processing;
InternalOnStart();
}
internal void SetFinish()
{
IsFinish = true;
//注意如果完成回调内发生异常会导致Task无限期等待 // 进度百分百完成
_callback?.Invoke(this); Progress = 1f;
if (_taskCompletionSource != null) //注意如果完成回调内发生异常会导致Task无限期等待
_taskCompletionSource.TrySetResult(null); _callback?.Invoke(this);
}
internal void SetAbort()
{
if (IsDone == false)
{
Status = EOperationStatus.Failed;
Error = "user abort";
YooLogger.Warning($"Async operaiton has been abort : {this.GetType().Name}");
InternalOnAbort();
}
}
/// <summary> if (_taskCompletionSource != null)
/// 清空完成回调 _taskCompletionSource.TrySetResult(null);
/// </summary> }
protected void ClearCompletedCallback() internal void SetAbort()
{ {
_callback = null; if (IsDone == false)
} {
Status = EOperationStatus.Failed;
Error = "user abort";
YooLogger.Warning($"Async operaiton has been abort : {this.GetType().Name}");
InternalOnAbort();
}
}
#region 排序接口实现 /// <summary>
public int CompareTo(AsyncOperationBase other) /// 清空完成回调
{ /// </summary>
return other.Priority.CompareTo(this.Priority); protected void ClearCompletedCallback()
} {
#endregion _callback = null;
}
#region 异步编程相关 #region 排序接口实现
bool IEnumerator.MoveNext() public int CompareTo(AsyncOperationBase other)
{ {
return !IsDone; return other.Priority.CompareTo(this.Priority);
} }
void IEnumerator.Reset() #endregion
{
}
object IEnumerator.Current => null;
private TaskCompletionSource<object> _taskCompletionSource; #region 异步编程相关
#endregion bool IEnumerator.MoveNext()
} {
return !IsDone;
}
void IEnumerator.Reset()
{
}
object IEnumerator.Current => null;
private TaskCompletionSource<object> _taskCompletionSource;
#endregion
}
} }

View File

@ -1,11 +1,11 @@
 
namespace YooAsset namespace YooAsset
{ {
public enum EOperationStatus public enum EOperationStatus
{ {
None, None,
Processing, Processing,
Succeed, Succeed,
Failed Failed
} }
} }

View File

@ -1,42 +1,42 @@
 
namespace YooAsset namespace YooAsset
{ {
public abstract class GameAsyncOperation : AsyncOperationBase public abstract class GameAsyncOperation : AsyncOperationBase
{ {
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
OnStart(); OnStart();
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
OnUpdate(); OnUpdate();
} }
internal override void InternalOnAbort() internal override void InternalOnAbort()
{ {
OnAbort(); OnAbort();
} }
/// <summary> /// <summary>
/// 异步操作开始 /// 异步操作开始
/// </summary> /// </summary>
protected abstract void OnStart(); protected abstract void OnStart();
/// <summary> /// <summary>
/// 异步操作更新 /// 异步操作更新
/// </summary> /// </summary>
protected abstract void OnUpdate(); protected abstract void OnUpdate();
/// <summary> /// <summary>
/// 异步操作终止 /// 异步操作终止
/// </summary> /// </summary>
protected abstract void OnAbort(); protected abstract void OnAbort();
/// <summary> /// <summary>
/// 异步操作系统是否繁忙 /// 异步操作系统是否繁忙
/// </summary> /// </summary>
protected bool IsBusy() protected bool IsBusy()
{ {
return OperationSystem.IsBusy; return OperationSystem.IsBusy;
} }
} }
} }

View File

@ -4,138 +4,138 @@ using System.Diagnostics;
namespace YooAsset namespace YooAsset
{ {
internal class OperationSystem internal class OperationSystem
{ {
private static readonly List<AsyncOperationBase> _operations = new List<AsyncOperationBase>(1000); private static readonly List<AsyncOperationBase> _operations = new List<AsyncOperationBase>(1000);
private static readonly List<AsyncOperationBase> _newList = new List<AsyncOperationBase>(1000); private static readonly List<AsyncOperationBase> _newList = new List<AsyncOperationBase>(1000);
// 计时器相关 // 计时器相关
private static Stopwatch _watch; private static Stopwatch _watch;
private static long _frameTime; private static long _frameTime;
/// <summary> /// <summary>
/// 异步操作的最小时间片段 /// 异步操作的最小时间片段
/// </summary> /// </summary>
public static long MaxTimeSlice { set; get; } = long.MaxValue; public static long MaxTimeSlice { set; get; } = long.MaxValue;
/// <summary> /// <summary>
/// 处理器是否繁忙 /// 处理器是否繁忙
/// </summary> /// </summary>
public static bool IsBusy public static bool IsBusy
{ {
get get
{ {
return _watch.ElapsedMilliseconds - _frameTime >= MaxTimeSlice; return _watch.ElapsedMilliseconds - _frameTime >= MaxTimeSlice;
} }
} }
/// <summary> /// <summary>
/// 初始化异步操作系统 /// 初始化异步操作系统
/// </summary> /// </summary>
public static void Initialize() public static void Initialize()
{ {
_watch = Stopwatch.StartNew(); _watch = Stopwatch.StartNew();
} }
/// <summary> /// <summary>
/// 更新异步操作系统 /// 更新异步操作系统
/// </summary> /// </summary>
public static void Update() public static void Update()
{ {
_frameTime = _watch.ElapsedMilliseconds; _frameTime = _watch.ElapsedMilliseconds;
// 添加新增的异步操作 // 添加新增的异步操作
if (_newList.Count > 0) if (_newList.Count > 0)
{ {
bool sorting = false; bool sorting = false;
foreach (var operation in _newList) foreach (var operation in _newList)
{ {
if (operation.Priority > 0) if (operation.Priority > 0)
{ {
sorting = true; sorting = true;
break; break;
} }
} }
_operations.AddRange(_newList); _operations.AddRange(_newList);
_newList.Clear(); _newList.Clear();
// 重新排序优先级 // 重新排序优先级
if (sorting) if (sorting)
_operations.Sort(); _operations.Sort();
} }
// 更新进行中的异步操作 // 更新进行中的异步操作
for (int i = 0; i < _operations.Count; i++) for (int i = 0; i < _operations.Count; i++)
{ {
if (IsBusy) if (IsBusy)
break; break;
var operation = _operations[i]; var operation = _operations[i];
if (operation.IsFinish) if (operation.IsFinish)
continue; continue;
if (operation.IsDone == false) if (operation.IsDone == false)
operation.InternalOnUpdate(); operation.InternalOnUpdate();
if (operation.IsDone) if (operation.IsDone)
operation.SetFinish(); operation.SetFinish();
} }
// 移除已经完成的异步操作 // 移除已经完成的异步操作
for (int i = _operations.Count - 1; i >= 0; i--) for (int i = _operations.Count - 1; i >= 0; i--)
{ {
var operation = _operations[i]; var operation = _operations[i];
if (operation.IsFinish) if (operation.IsFinish)
_operations.RemoveAt(i); _operations.RemoveAt(i);
} }
} }
/// <summary> /// <summary>
/// 销毁异步操作系统 /// 销毁异步操作系统
/// </summary> /// </summary>
public static void DestroyAll() public static void DestroyAll()
{ {
_operations.Clear(); _operations.Clear();
_newList.Clear(); _newList.Clear();
_watch = null; _watch = null;
_frameTime = 0; _frameTime = 0;
MaxTimeSlice = long.MaxValue; MaxTimeSlice = long.MaxValue;
} }
/// <summary> /// <summary>
/// 销毁包裹的所有任务 /// 销毁包裹的所有任务
/// </summary> /// </summary>
public static void ClearPackageOperation(string packageName) public static void ClearPackageOperation(string packageName)
{ {
// 终止临时队列里的任务 // 终止临时队列里的任务
foreach (var operation in _newList) foreach (var operation in _newList)
{ {
if (operation.PackageName == packageName) if (operation.PackageName == packageName)
{ {
operation.SetAbort(); operation.SetAbort();
} }
} }
// 终止正在进行的任务 // 终止正在进行的任务
foreach (var operation in _operations) foreach (var operation in _operations)
{ {
if (operation.PackageName == packageName) if (operation.PackageName == packageName)
{ {
operation.SetAbort(); operation.SetAbort();
} }
} }
} }
/// <summary> /// <summary>
/// 开始处理异步操作类 /// 开始处理异步操作类
/// </summary> /// </summary>
public static void StartOperation(string packageName, AsyncOperationBase operation) public static void StartOperation(string packageName, AsyncOperationBase operation)
{ {
_newList.Add(operation); _newList.Add(operation);
operation.Init(packageName); operation.Init(packageName);
operation.SetStart(); operation.SetStart();
} }
} }
} }

View File

@ -3,78 +3,78 @@ using System.Collections.Generic;
namespace YooAsset namespace YooAsset
{ {
public sealed class AllAssetsHandle : HandleBase, IDisposable public sealed class AllAssetsHandle : HandleBase, IDisposable
{ {
private System.Action<AllAssetsHandle> _callback; private System.Action<AllAssetsHandle> _callback;
internal AllAssetsHandle(ProviderBase provider) : base(provider) internal AllAssetsHandle(ProviderBase provider) : base(provider)
{ {
} }
internal override void InvokeCallback() internal override void InvokeCallback()
{ {
_callback?.Invoke(this); _callback?.Invoke(this);
} }
/// <summary>
/// 完成委托
/// </summary>
public event System.Action<AllAssetsHandle> Completed
{
add
{
if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(AllAssetsHandle)} is invalid");
if (Provider.IsDone)
value.Invoke(this);
else
_callback += value;
}
remove
{
if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(AllAssetsHandle)} is invalid");
_callback -= value;
}
}
/// <summary> /// <summary>
/// 等待异步执行完毕 /// 完成委托
/// </summary> /// </summary>
public void WaitForAsyncComplete() public event System.Action<AllAssetsHandle> Completed
{ {
if (IsValidWithWarning == false) add
return; {
Provider.WaitForAsyncComplete(); if (IsValidWithWarning == false)
} throw new System.Exception($"{nameof(AllAssetsHandle)} is invalid");
if (Provider.IsDone)
value.Invoke(this);
else
_callback += value;
}
remove
{
if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(AllAssetsHandle)} is invalid");
_callback -= value;
}
}
/// <summary> /// <summary>
/// 释放资源句柄 /// 等待异步执行完毕
/// </summary> /// </summary>
public void Release() public void WaitForAsyncComplete()
{ {
this.ReleaseInternal(); if (IsValidWithWarning == false)
} return;
Provider.WaitForAsyncComplete();
}
/// <summary> /// <summary>
/// 释放资源句柄 /// 释放资源句柄
/// </summary> /// </summary>
public void Dispose() public void Release()
{ {
this.ReleaseInternal(); this.ReleaseInternal();
} }
/// <summary>
/// 释放资源句柄
/// </summary>
public void Dispose()
{
this.ReleaseInternal();
}
/// <summary> /// <summary>
/// 子资源对象集合 /// 子资源对象集合
/// </summary> /// </summary>
public UnityEngine.Object[] AllAssetObjects public UnityEngine.Object[] AllAssetObjects
{ {
get get
{ {
if (IsValidWithWarning == false) if (IsValidWithWarning == false)
return null; return null;
return Provider.AllAssetObjects; return Provider.AllAssetObjects;
} }
} }
} }
} }

View File

@ -4,154 +4,154 @@ using UnityEngine;
namespace YooAsset namespace YooAsset
{ {
public sealed class AssetHandle : HandleBase, IDisposable public sealed class AssetHandle : HandleBase, IDisposable
{ {
private System.Action<AssetHandle> _callback; private System.Action<AssetHandle> _callback;
internal AssetHandle(ProviderBase provider) : base(provider) internal AssetHandle(ProviderBase provider) : base(provider)
{ {
} }
internal override void InvokeCallback() internal override void InvokeCallback()
{ {
_callback?.Invoke(this); _callback?.Invoke(this);
} }
/// <summary> /// <summary>
/// 完成委托 /// 完成委托
/// </summary> /// </summary>
public event System.Action<AssetHandle> Completed public event System.Action<AssetHandle> Completed
{ {
add add
{ {
if (IsValidWithWarning == false) if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(AssetHandle)} is invalid"); throw new System.Exception($"{nameof(AssetHandle)} is invalid");
if (Provider.IsDone) if (Provider.IsDone)
value.Invoke(this); value.Invoke(this);
else else
_callback += value; _callback += value;
} }
remove remove
{ {
if (IsValidWithWarning == false) if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(AssetHandle)} is invalid"); throw new System.Exception($"{nameof(AssetHandle)} is invalid");
_callback -= value; _callback -= value;
} }
} }
/// <summary> /// <summary>
/// 等待异步执行完毕 /// 等待异步执行完毕
/// </summary> /// </summary>
public void WaitForAsyncComplete() public void WaitForAsyncComplete()
{ {
if (IsValidWithWarning == false) if (IsValidWithWarning == false)
return; return;
Provider.WaitForAsyncComplete(); Provider.WaitForAsyncComplete();
} }
/// <summary> /// <summary>
/// 释放资源句柄 /// 释放资源句柄
/// </summary> /// </summary>
public void Release() public void Release()
{ {
this.ReleaseInternal(); this.ReleaseInternal();
} }
/// <summary> /// <summary>
/// 释放资源句柄 /// 释放资源句柄
/// </summary> /// </summary>
public void Dispose() public void Dispose()
{ {
this.ReleaseInternal(); this.ReleaseInternal();
} }
/// <summary> /// <summary>
/// 资源对象 /// 资源对象
/// </summary> /// </summary>
public UnityEngine.Object AssetObject public UnityEngine.Object AssetObject
{ {
get get
{ {
if (IsValidWithWarning == false) if (IsValidWithWarning == false)
return null; return null;
return Provider.AssetObject; return Provider.AssetObject;
} }
} }
/// <summary> /// <summary>
/// 获取资源对象 /// 获取资源对象
/// </summary> /// </summary>
/// <typeparam name="TAsset">资源类型</typeparam> /// <typeparam name="TAsset">资源类型</typeparam>
public TAsset GetAssetObject<TAsset>() where TAsset : UnityEngine.Object public TAsset GetAssetObject<TAsset>() where TAsset : UnityEngine.Object
{ {
if (IsValidWithWarning == false) if (IsValidWithWarning == false)
return null; return null;
return Provider.AssetObject as TAsset; return Provider.AssetObject as TAsset;
} }
/// <summary> /// <summary>
/// 同步初始化游戏对象 /// 同步初始化游戏对象
/// </summary> /// </summary>
public GameObject InstantiateSync() public GameObject InstantiateSync()
{ {
return InstantiateSyncInternal(false, Vector3.zero, Quaternion.identity, null, false); return InstantiateSyncInternal(false, Vector3.zero, Quaternion.identity, null, false);
} }
public GameObject InstantiateSync(Transform parent) public GameObject InstantiateSync(Transform parent)
{ {
return InstantiateSyncInternal(false, Vector3.zero, Quaternion.identity, parent, false); return InstantiateSyncInternal(false, Vector3.zero, Quaternion.identity, parent, false);
} }
public GameObject InstantiateSync(Transform parent, bool worldPositionStays) public GameObject InstantiateSync(Transform parent, bool worldPositionStays)
{ {
return InstantiateSyncInternal(false, Vector3.zero, Quaternion.identity, parent, worldPositionStays); return InstantiateSyncInternal(false, Vector3.zero, Quaternion.identity, parent, worldPositionStays);
} }
public GameObject InstantiateSync(Vector3 position, Quaternion rotation) public GameObject InstantiateSync(Vector3 position, Quaternion rotation)
{ {
return InstantiateSyncInternal(true, position, rotation, null, false); return InstantiateSyncInternal(true, position, rotation, null, false);
} }
public GameObject InstantiateSync(Vector3 position, Quaternion rotation, Transform parent) public GameObject InstantiateSync(Vector3 position, Quaternion rotation, Transform parent)
{ {
return InstantiateSyncInternal(true, position, rotation, parent, false); return InstantiateSyncInternal(true, position, rotation, parent, false);
} }
/// <summary> /// <summary>
/// 异步初始化游戏对象 /// 异步初始化游戏对象
/// </summary> /// </summary>
public InstantiateOperation InstantiateAsync() public InstantiateOperation InstantiateAsync()
{ {
return InstantiateAsyncInternal(false, Vector3.zero, Quaternion.identity, null, false); return InstantiateAsyncInternal(false, Vector3.zero, Quaternion.identity, null, false);
} }
public InstantiateOperation InstantiateAsync(Transform parent) public InstantiateOperation InstantiateAsync(Transform parent)
{ {
return InstantiateAsyncInternal(false, Vector3.zero, Quaternion.identity, parent, false); return InstantiateAsyncInternal(false, Vector3.zero, Quaternion.identity, parent, false);
} }
public InstantiateOperation InstantiateAsync(Transform parent, bool worldPositionStays) public InstantiateOperation InstantiateAsync(Transform parent, bool worldPositionStays)
{ {
return InstantiateAsyncInternal(false, Vector3.zero, Quaternion.identity, parent, worldPositionStays); return InstantiateAsyncInternal(false, Vector3.zero, Quaternion.identity, parent, worldPositionStays);
} }
public InstantiateOperation InstantiateAsync(Vector3 position, Quaternion rotation) public InstantiateOperation InstantiateAsync(Vector3 position, Quaternion rotation)
{ {
return InstantiateAsyncInternal(true, position, rotation, null, false); return InstantiateAsyncInternal(true, position, rotation, null, false);
} }
public InstantiateOperation InstantiateAsync(Vector3 position, Quaternion rotation, Transform parent) public InstantiateOperation InstantiateAsync(Vector3 position, Quaternion rotation, Transform parent)
{ {
return InstantiateAsyncInternal(true, position, rotation, parent, false); return InstantiateAsyncInternal(true, position, rotation, parent, false);
} }
private GameObject InstantiateSyncInternal(bool setPositionAndRotation, Vector3 position, Quaternion rotation, Transform parent, bool worldPositionStays) private GameObject InstantiateSyncInternal(bool setPositionAndRotation, Vector3 position, Quaternion rotation, Transform parent, bool worldPositionStays)
{ {
if (IsValidWithWarning == false) if (IsValidWithWarning == false)
return null; return null;
if (Provider.AssetObject == null) if (Provider.AssetObject == null)
return null; return null;
return InstantiateOperation.InstantiateInternal(Provider.AssetObject, setPositionAndRotation, position, rotation, parent, worldPositionStays); return InstantiateOperation.InstantiateInternal(Provider.AssetObject, setPositionAndRotation, position, rotation, parent, worldPositionStays);
} }
private InstantiateOperation InstantiateAsyncInternal(bool setPositionAndRotation, Vector3 position, Quaternion rotation, Transform parent, bool worldPositionStays) private InstantiateOperation InstantiateAsyncInternal(bool setPositionAndRotation, Vector3 position, Quaternion rotation, Transform parent, bool worldPositionStays)
{ {
string packageName = GetAssetInfo().PackageName; string packageName = GetAssetInfo().PackageName;
InstantiateOperation operation = new InstantiateOperation(this, setPositionAndRotation, position, rotation, parent, worldPositionStays); InstantiateOperation operation = new InstantiateOperation(this, setPositionAndRotation, position, rotation, parent, worldPositionStays);
OperationSystem.StartOperation(packageName, operation); OperationSystem.StartOperation(packageName, operation);
return operation; return operation;
} }
} }
} }

View File

@ -3,159 +3,159 @@ using System.Collections;
namespace YooAsset namespace YooAsset
{ {
public abstract class HandleBase : IEnumerator public abstract class HandleBase : IEnumerator
{ {
private readonly AssetInfo _assetInfo; private readonly AssetInfo _assetInfo;
internal ProviderBase Provider { private set; get; } internal ProviderBase Provider { private set; get; }
internal HandleBase(ProviderBase provider) internal HandleBase(ProviderBase provider)
{ {
Provider = provider; Provider = provider;
_assetInfo = provider.MainAssetInfo; _assetInfo = provider.MainAssetInfo;
} }
internal abstract void InvokeCallback(); internal abstract void InvokeCallback();
/// <summary> /// <summary>
/// 获取资源信息 /// 获取资源信息
/// </summary> /// </summary>
public AssetInfo GetAssetInfo() public AssetInfo GetAssetInfo()
{ {
return _assetInfo; return _assetInfo;
} }
/// <summary> /// <summary>
/// 获取下载报告 /// 获取下载报告
/// </summary> /// </summary>
public DownloadStatus GetDownloadStatus() public DownloadStatus GetDownloadStatus()
{ {
if (IsValidWithWarning == false) if (IsValidWithWarning == false)
{ {
return DownloadStatus.CreateDefaultStatus(); return DownloadStatus.CreateDefaultStatus();
} }
return Provider.GetDownloadStatus(); return Provider.GetDownloadStatus();
} }
/// <summary> /// <summary>
/// 当前状态 /// 当前状态
/// </summary> /// </summary>
public EOperationStatus Status public EOperationStatus Status
{ {
get get
{ {
if (IsValidWithWarning == false) if (IsValidWithWarning == false)
return EOperationStatus.None; return EOperationStatus.None;
return Provider.Status; return Provider.Status;
} }
} }
/// <summary> /// <summary>
/// 最近的错误信息 /// 最近的错误信息
/// </summary> /// </summary>
public string LastError public string LastError
{ {
get get
{ {
if (IsValidWithWarning == false) if (IsValidWithWarning == false)
return string.Empty; return string.Empty;
return Provider.Error; return Provider.Error;
} }
} }
/// <summary> /// <summary>
/// 加载进度 /// 加载进度
/// </summary> /// </summary>
public float Progress public float Progress
{ {
get get
{ {
if (IsValidWithWarning == false) if (IsValidWithWarning == false)
return 0; return 0;
return Provider.Progress; return Provider.Progress;
} }
} }
/// <summary> /// <summary>
/// 是否加载完毕 /// 是否加载完毕
/// </summary> /// </summary>
public bool IsDone public bool IsDone
{ {
get get
{ {
if (IsValidWithWarning == false) if (IsValidWithWarning == false)
return false; return false;
return Provider.IsDone; return Provider.IsDone;
} }
} }
/// <summary> /// <summary>
/// 句柄是否有效 /// 句柄是否有效
/// </summary> /// </summary>
public bool IsValid public bool IsValid
{ {
get get
{ {
if (Provider != null && Provider.IsDestroyed == false) if (Provider != null && Provider.IsDestroyed == false)
return true; return true;
else else
return false; return false;
} }
} }
/// <summary> /// <summary>
/// 句柄是否有效 /// 句柄是否有效
/// </summary> /// </summary>
internal bool IsValidWithWarning internal bool IsValidWithWarning
{ {
get get
{ {
if (Provider != null && Provider.IsDestroyed == false) if (Provider != null && Provider.IsDestroyed == false)
{ {
return true; return true;
} }
else else
{ {
if (Provider == null) if (Provider == null)
YooLogger.Warning($"Operation handle is released : {_assetInfo.AssetPath}"); YooLogger.Warning($"Operation handle is released : {_assetInfo.AssetPath}");
else if (Provider.IsDestroyed) else if (Provider.IsDestroyed)
YooLogger.Warning($"Provider is destroyed : {_assetInfo.AssetPath}"); YooLogger.Warning($"Provider is destroyed : {_assetInfo.AssetPath}");
return false; return false;
} }
} }
} }
/// <summary> /// <summary>
/// 释放句柄 /// 释放句柄
/// </summary> /// </summary>
internal void ReleaseInternal() internal void ReleaseInternal()
{ {
if (IsValidWithWarning == false) if (IsValidWithWarning == false)
return; return;
Provider.ReleaseHandle(this); Provider.ReleaseHandle(this);
Provider = null; Provider = null;
} }
#region 异步操作相关 #region 异步操作相关
/// <summary> /// <summary>
/// 异步操作任务 /// 异步操作任务
/// </summary> /// </summary>
public System.Threading.Tasks.Task Task public System.Threading.Tasks.Task Task
{ {
get { return Provider.Task; } get { return Provider.Task; }
} }
// 协程相关 // 协程相关
bool IEnumerator.MoveNext() bool IEnumerator.MoveNext()
{ {
return !IsDone; return !IsDone;
} }
void IEnumerator.Reset() void IEnumerator.Reset()
{ {
} }
object IEnumerator.Current object IEnumerator.Current
{ {
get { return Provider; } get { return Provider; }
} }
#endregion #endregion
} }
} }

View File

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

View File

@ -2,174 +2,174 @@
namespace YooAsset namespace YooAsset
{ {
public class SceneHandle : HandleBase public class SceneHandle : HandleBase
{ {
private System.Action<SceneHandle> _callback; private System.Action<SceneHandle> _callback;
internal string PackageName { set; get; } internal string PackageName { set; get; }
internal SceneHandle(ProviderBase provider) : base(provider) internal SceneHandle(ProviderBase provider) : base(provider)
{ {
} }
internal override void InvokeCallback() internal override void InvokeCallback()
{ {
_callback?.Invoke(this); _callback?.Invoke(this);
} }
/// <summary> /// <summary>
/// 完成委托 /// 完成委托
/// </summary> /// </summary>
public event System.Action<SceneHandle> Completed public event System.Action<SceneHandle> Completed
{ {
add add
{ {
if (IsValidWithWarning == false) if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(SceneHandle)} is invalid"); throw new System.Exception($"{nameof(SceneHandle)} is invalid");
if (Provider.IsDone) if (Provider.IsDone)
value.Invoke(this); value.Invoke(this);
else else
_callback += value; _callback += value;
} }
remove remove
{ {
if (IsValidWithWarning == false) if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(SceneHandle)} is invalid"); throw new System.Exception($"{nameof(SceneHandle)} is invalid");
_callback -= value; _callback -= value;
} }
} }
/// <summary> /// <summary>
/// 场景名称 /// 场景名称
/// </summary> /// </summary>
public string SceneName public string SceneName
{ {
get get
{ {
if (IsValidWithWarning == false) if (IsValidWithWarning == false)
return string.Empty; return string.Empty;
return Provider.SceneName; return Provider.SceneName;
} }
} }
/// <summary> /// <summary>
/// 场景对象 /// 场景对象
/// </summary> /// </summary>
public Scene SceneObject public Scene SceneObject
{ {
get get
{ {
if (IsValidWithWarning == false) if (IsValidWithWarning == false)
return new Scene(); return new Scene();
return Provider.SceneObject; return Provider.SceneObject;
} }
} }
/// <summary> /// <summary>
/// 激活场景(当同时存在多个场景时用于切换激活场景) /// 激活场景(当同时存在多个场景时用于切换激活场景)
/// </summary> /// </summary>
public bool ActivateScene() public bool ActivateScene()
{ {
if (IsValidWithWarning == false) if (IsValidWithWarning == false)
return false; return false;
if (SceneObject.IsValid() && SceneObject.isLoaded) if (SceneObject.IsValid() && SceneObject.isLoaded)
{ {
return SceneManager.SetActiveScene(SceneObject); return SceneManager.SetActiveScene(SceneObject);
} }
else else
{ {
YooLogger.Warning($"Scene is invalid or not loaded : {SceneObject.name}"); YooLogger.Warning($"Scene is invalid or not loaded : {SceneObject.name}");
return false; return false;
} }
} }
/// <summary> /// <summary>
/// 解除场景加载挂起操作 /// 解除场景加载挂起操作
/// </summary> /// </summary>
public bool UnSuspend() public bool UnSuspend()
{ {
if (IsValidWithWarning == false) if (IsValidWithWarning == false)
return false; return false;
if (SceneObject.IsValid()) if (SceneObject.IsValid())
{ {
if (Provider is DatabaseSceneProvider) if (Provider is DatabaseSceneProvider)
{ {
var temp = Provider as DatabaseSceneProvider; var temp = Provider as DatabaseSceneProvider;
return temp.UnSuspendLoad(); return temp.UnSuspendLoad();
} }
else if (Provider is BundledSceneProvider) else if (Provider is BundledSceneProvider)
{ {
var temp = Provider as BundledSceneProvider; var temp = Provider as BundledSceneProvider;
return temp.UnSuspendLoad(); return temp.UnSuspendLoad();
} }
else else
{ {
throw new System.NotImplementedException(); throw new System.NotImplementedException();
} }
} }
else else
{ {
YooLogger.Warning($"Scene is invalid : {SceneObject.name}"); YooLogger.Warning($"Scene is invalid : {SceneObject.name}");
return false; return false;
} }
} }
/// <summary> /// <summary>
/// 是否为主场景 /// 是否为主场景
/// </summary> /// </summary>
public bool IsMainScene() public bool IsMainScene()
{ {
if (IsValidWithWarning == false) if (IsValidWithWarning == false)
return false; return false;
if (Provider is DatabaseSceneProvider) if (Provider is DatabaseSceneProvider)
{ {
var temp = Provider as DatabaseSceneProvider; var temp = Provider as DatabaseSceneProvider;
return temp.SceneMode == LoadSceneMode.Single; return temp.SceneMode == LoadSceneMode.Single;
} }
else if (Provider is BundledSceneProvider) else if (Provider is BundledSceneProvider)
{ {
var temp = Provider as BundledSceneProvider; var temp = Provider as BundledSceneProvider;
return temp.SceneMode == LoadSceneMode.Single; return temp.SceneMode == LoadSceneMode.Single;
} }
else else
{ {
throw new System.NotImplementedException(); throw new System.NotImplementedException();
} }
} }
/// <summary> /// <summary>
/// 异步卸载子场景 /// 异步卸载子场景
/// </summary> /// </summary>
public UnloadSceneOperation UnloadAsync() public UnloadSceneOperation UnloadAsync()
{ {
string packageName = GetAssetInfo().PackageName; string packageName = GetAssetInfo().PackageName;
// 如果句柄无效 // 如果句柄无效
if (IsValidWithWarning == false) if (IsValidWithWarning == false)
{ {
string error = $"{nameof(SceneHandle)} is invalid."; string error = $"{nameof(SceneHandle)} is invalid.";
var operation = new UnloadSceneOperation(error); var operation = new UnloadSceneOperation(error);
OperationSystem.StartOperation(packageName, operation); OperationSystem.StartOperation(packageName, operation);
return operation; return operation;
} }
// 如果是主场景 // 如果是主场景
if (IsMainScene()) if (IsMainScene())
{ {
string error = $"Cannot unload main scene. Use {nameof(YooAssets.LoadSceneAsync)} method to change the main scene !"; string error = $"Cannot unload main scene. Use {nameof(YooAssets.LoadSceneAsync)} method to change the main scene !";
YooLogger.Error(error); YooLogger.Error(error);
var operation = new UnloadSceneOperation(error); var operation = new UnloadSceneOperation(error);
OperationSystem.StartOperation(packageName, operation); OperationSystem.StartOperation(packageName, operation);
return operation; return operation;
} }
// 卸载子场景 // 卸载子场景
{ {
var operation = new UnloadSceneOperation(Provider); var operation = new UnloadSceneOperation(Provider);
OperationSystem.StartOperation(packageName, operation); OperationSystem.StartOperation(packageName, operation);
return operation; return operation;
} }
} }
} }
} }

View File

@ -3,117 +3,117 @@ using System.Collections.Generic;
namespace YooAsset namespace YooAsset
{ {
public sealed class SubAssetsHandle : HandleBase, IDisposable public sealed class SubAssetsHandle : HandleBase, IDisposable
{ {
private System.Action<SubAssetsHandle> _callback; private System.Action<SubAssetsHandle> _callback;
internal SubAssetsHandle(ProviderBase provider) : base(provider) internal SubAssetsHandle(ProviderBase provider) : base(provider)
{ {
} }
internal override void InvokeCallback() internal override void InvokeCallback()
{ {
_callback?.Invoke(this); _callback?.Invoke(this);
} }
/// <summary> /// <summary>
/// 完成委托 /// 完成委托
/// </summary> /// </summary>
public event System.Action<SubAssetsHandle> Completed public event System.Action<SubAssetsHandle> Completed
{ {
add add
{ {
if (IsValidWithWarning == false) if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(SubAssetsHandle)} is invalid"); throw new System.Exception($"{nameof(SubAssetsHandle)} is invalid");
if (Provider.IsDone) if (Provider.IsDone)
value.Invoke(this); value.Invoke(this);
else else
_callback += value; _callback += value;
} }
remove remove
{ {
if (IsValidWithWarning == false) if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(SubAssetsHandle)} is invalid"); throw new System.Exception($"{nameof(SubAssetsHandle)} is invalid");
_callback -= value; _callback -= value;
} }
} }
/// <summary> /// <summary>
/// 等待异步执行完毕 /// 等待异步执行完毕
/// </summary> /// </summary>
public void WaitForAsyncComplete() public void WaitForAsyncComplete()
{ {
if (IsValidWithWarning == false) if (IsValidWithWarning == false)
return; return;
Provider.WaitForAsyncComplete(); Provider.WaitForAsyncComplete();
} }
/// <summary> /// <summary>
/// 释放资源句柄 /// 释放资源句柄
/// </summary> /// </summary>
public void Release() public void Release()
{ {
this.ReleaseInternal(); this.ReleaseInternal();
} }
/// <summary> /// <summary>
/// 释放资源句柄 /// 释放资源句柄
/// </summary> /// </summary>
public void Dispose() public void Dispose()
{ {
this.ReleaseInternal(); this.ReleaseInternal();
} }
/// <summary> /// <summary>
/// 子资源对象集合 /// 子资源对象集合
/// </summary> /// </summary>
public UnityEngine.Object[] AllAssetObjects public UnityEngine.Object[] AllAssetObjects
{ {
get get
{ {
if (IsValidWithWarning == false) if (IsValidWithWarning == false)
return null; return null;
return Provider.AllAssetObjects; return Provider.AllAssetObjects;
} }
} }
/// <summary> /// <summary>
/// 获取子资源对象 /// 获取子资源对象
/// </summary> /// </summary>
/// <typeparam name="TObject">子资源对象类型</typeparam> /// <typeparam name="TObject">子资源对象类型</typeparam>
/// <param name="assetName">子资源对象名称</param> /// <param name="assetName">子资源对象名称</param>
public TObject GetSubAssetObject<TObject>(string assetName) where TObject : UnityEngine.Object public TObject GetSubAssetObject<TObject>(string assetName) where TObject : UnityEngine.Object
{ {
if (IsValidWithWarning == false) if (IsValidWithWarning == false)
return null; return null;
foreach (var assetObject in Provider.AllAssetObjects) foreach (var assetObject in Provider.AllAssetObjects)
{ {
if (assetObject.name == assetName) if (assetObject.name == assetName)
return assetObject as TObject; return assetObject as TObject;
} }
YooLogger.Warning($"Not found sub asset object : {assetName}"); YooLogger.Warning($"Not found sub asset object : {assetName}");
return null; return null;
} }
/// <summary> /// <summary>
/// 获取所有的子资源对象集合 /// 获取所有的子资源对象集合
/// </summary> /// </summary>
/// <typeparam name="TObject">子资源对象类型</typeparam> /// <typeparam name="TObject">子资源对象类型</typeparam>
public TObject[] GetSubAssetObjects<TObject>() where TObject : UnityEngine.Object public TObject[] GetSubAssetObjects<TObject>() where TObject : UnityEngine.Object
{ {
if (IsValidWithWarning == false) if (IsValidWithWarning == false)
return null; return null;
List<TObject> ret = new List<TObject>(Provider.AllAssetObjects.Length); List<TObject> ret = new List<TObject>(Provider.AllAssetObjects.Length);
foreach (var assetObject in Provider.AllAssetObjects) foreach (var assetObject in Provider.AllAssetObjects)
{ {
var retObject = assetObject as TObject; var retObject = assetObject as TObject;
if (retObject != null) if (retObject != null)
ret.Add(retObject); ret.Add(retObject);
} }
return ret.ToArray(); return ret.ToArray();
} }
} }
} }

View File

@ -6,289 +6,289 @@ using UnityEngine;
namespace YooAsset namespace YooAsset
{ {
internal sealed class AssetBundleFileLoader : BundleLoaderBase internal sealed class AssetBundleFileLoader : BundleLoaderBase
{ {
private enum ESteps private enum ESteps
{ {
None = 0, None = 0,
Download, Download,
CheckDownload, CheckDownload,
Unpack, Unpack,
CheckUnpack, CheckUnpack,
LoadBundleFile, LoadBundleFile,
LoadDeliveryFile, LoadDeliveryFile,
CheckLoadFile, CheckLoadFile,
Done, Done,
} }
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
private bool _isWaitForAsyncComplete = false; private bool _isWaitForAsyncComplete = false;
private bool _isShowWaitForAsyncError = false; private bool _isShowWaitForAsyncError = false;
private DownloaderBase _unpacker; private DownloaderBase _unpacker;
private DownloaderBase _downloader; private DownloaderBase _downloader;
private AssetBundleCreateRequest _createRequest; private AssetBundleCreateRequest _createRequest;
private Stream _managedStream; private Stream _managedStream;
public AssetBundleFileLoader(ResourceManager impl, BundleInfo bundleInfo) : base(impl, bundleInfo) public AssetBundleFileLoader(ResourceManager impl, BundleInfo bundleInfo) : base(impl, bundleInfo)
{ {
} }
/// <summary> /// <summary>
/// 轮询更新 /// 轮询更新
/// </summary> /// </summary>
public override void Update() public override void Update()
{ {
if (_steps == ESteps.Done) if (_steps == ESteps.Done)
return; return;
if (_steps == ESteps.None) if (_steps == ESteps.None)
{ {
if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromRemote) if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromRemote)
{ {
_steps = ESteps.Download; _steps = ESteps.Download;
FileLoadPath = MainBundleInfo.CachedDataFilePath; FileLoadPath = MainBundleInfo.CachedDataFilePath;
} }
else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromStreaming) else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromStreaming)
{ {
#if UNITY_ANDROID #if UNITY_ANDROID
if (MainBundleInfo.Bundle.Encrypted) if (MainBundleInfo.Bundle.Encrypted)
{ {
_steps = ESteps.Unpack; _steps = ESteps.Unpack;
FileLoadPath = MainBundleInfo.CachedDataFilePath; FileLoadPath = MainBundleInfo.CachedDataFilePath;
} }
else else
{ {
_steps = ESteps.LoadBundleFile; _steps = ESteps.LoadBundleFile;
FileLoadPath = MainBundleInfo.BuildinFilePath; FileLoadPath = MainBundleInfo.BuildinFilePath;
} }
#else #else
_steps = ESteps.LoadBundleFile; _steps = ESteps.LoadBundleFile;
FileLoadPath = MainBundleInfo.BuildinFilePath; FileLoadPath = MainBundleInfo.BuildinFilePath;
#endif #endif
} }
else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromCache) else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromCache)
{ {
_steps = ESteps.LoadBundleFile; _steps = ESteps.LoadBundleFile;
FileLoadPath = MainBundleInfo.CachedDataFilePath; FileLoadPath = MainBundleInfo.CachedDataFilePath;
} }
else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromDelivery) else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromDelivery)
{ {
_steps = ESteps.LoadDeliveryFile; _steps = ESteps.LoadDeliveryFile;
FileLoadPath = MainBundleInfo.DeliveryFilePath; FileLoadPath = MainBundleInfo.DeliveryFilePath;
} }
else else
{ {
throw new System.NotImplementedException(MainBundleInfo.LoadMode.ToString()); throw new System.NotImplementedException(MainBundleInfo.LoadMode.ToString());
} }
} }
// 1. 从服务器下载 // 1. 从服务器下载
if (_steps == ESteps.Download) if (_steps == ESteps.Download)
{ {
_downloader = MainBundleInfo.CreateDownloader(int.MaxValue); _downloader = MainBundleInfo.CreateDownloader(int.MaxValue);
_downloader.SendRequest(); _downloader.SendRequest();
_steps = ESteps.CheckDownload; _steps = ESteps.CheckDownload;
} }
// 2. 检测服务器下载结果 // 2. 检测服务器下载结果
if (_steps == ESteps.CheckDownload) if (_steps == ESteps.CheckDownload)
{ {
DownloadProgress = _downloader.DownloadProgress; DownloadProgress = _downloader.DownloadProgress;
DownloadedBytes = _downloader.DownloadedBytes; DownloadedBytes = _downloader.DownloadedBytes;
if (_downloader.IsDone() == false) if (_downloader.IsDone() == false)
return; return;
if (_downloader.HasError()) if (_downloader.HasError())
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EStatus.Failed; Status = EStatus.Failed;
LastError = _downloader.GetLastError(); LastError = _downloader.GetLastError();
} }
else else
{ {
_steps = ESteps.LoadBundleFile; _steps = ESteps.LoadBundleFile;
return; //下载完毕等待一帧再去加载! return; //下载完毕等待一帧再去加载!
} }
} }
// 3. 内置文件解压 // 3. 内置文件解压
if (_steps == ESteps.Unpack) if (_steps == ESteps.Unpack)
{ {
int failedTryAgain = 1; int failedTryAgain = 1;
_unpacker = MainBundleInfo.CreateUnpacker(failedTryAgain); _unpacker = MainBundleInfo.CreateUnpacker(failedTryAgain);
_unpacker.SendRequest(); _unpacker.SendRequest();
_steps = ESteps.CheckUnpack; _steps = ESteps.CheckUnpack;
} }
// 4.检测内置文件解压结果 // 4.检测内置文件解压结果
if (_steps == ESteps.CheckUnpack) if (_steps == ESteps.CheckUnpack)
{ {
DownloadProgress = _unpacker.DownloadProgress; DownloadProgress = _unpacker.DownloadProgress;
DownloadedBytes = _unpacker.DownloadedBytes; DownloadedBytes = _unpacker.DownloadedBytes;
if (_unpacker.IsDone() == false) if (_unpacker.IsDone() == false)
return; return;
if (_unpacker.HasError()) if (_unpacker.HasError())
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EStatus.Failed; Status = EStatus.Failed;
LastError = _unpacker.GetLastError(); LastError = _unpacker.GetLastError();
} }
else else
{ {
_steps = ESteps.LoadBundleFile; _steps = ESteps.LoadBundleFile;
} }
} }
// 5. 加载AssetBundle // 5. 加载AssetBundle
if (_steps == ESteps.LoadBundleFile) if (_steps == ESteps.LoadBundleFile)
{ {
#if UNITY_EDITOR #if UNITY_EDITOR
// 注意Unity2017.4编辑器模式下如果AssetBundle文件不存在会导致编辑器崩溃这里做了预判。 // 注意Unity2017.4编辑器模式下如果AssetBundle文件不存在会导致编辑器崩溃这里做了预判。
if (System.IO.File.Exists(FileLoadPath) == false) if (System.IO.File.Exists(FileLoadPath) == false)
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EStatus.Failed; Status = EStatus.Failed;
LastError = $"Not found assetBundle file : {FileLoadPath}"; LastError = $"Not found assetBundle file : {FileLoadPath}";
YooLogger.Error(LastError); YooLogger.Error(LastError);
return; return;
} }
#endif #endif
// 设置下载进度 // 设置下载进度
DownloadProgress = 1f; DownloadProgress = 1f;
DownloadedBytes = (ulong)MainBundleInfo.Bundle.FileSize; DownloadedBytes = (ulong)MainBundleInfo.Bundle.FileSize;
// 加载AssetBundle资源对象 // 加载AssetBundle资源对象
// 注意:解密服务类可能会返回空的对象。 // 注意:解密服务类可能会返回空的对象。
if (_isWaitForAsyncComplete) if (_isWaitForAsyncComplete)
CacheBundle = MainBundleInfo.LoadAssetBundle(FileLoadPath, out _managedStream); CacheBundle = MainBundleInfo.LoadAssetBundle(FileLoadPath, out _managedStream);
else else
_createRequest = MainBundleInfo.LoadAssetBundleAsync(FileLoadPath, out _managedStream); _createRequest = MainBundleInfo.LoadAssetBundleAsync(FileLoadPath, out _managedStream);
_steps = ESteps.CheckLoadFile; _steps = ESteps.CheckLoadFile;
} }
// 6. 加载AssetBundle // 6. 加载AssetBundle
if (_steps == ESteps.LoadDeliveryFile) if (_steps == ESteps.LoadDeliveryFile)
{ {
// 设置下载进度 // 设置下载进度
DownloadProgress = 1f; DownloadProgress = 1f;
DownloadedBytes = (ulong)MainBundleInfo.Bundle.FileSize; DownloadedBytes = (ulong)MainBundleInfo.Bundle.FileSize;
// Load assetBundle file // Load assetBundle file
if (_isWaitForAsyncComplete) if (_isWaitForAsyncComplete)
CacheBundle = MainBundleInfo.LoadDeliveryAssetBundle(FileLoadPath); CacheBundle = MainBundleInfo.LoadDeliveryAssetBundle(FileLoadPath);
else else
_createRequest = MainBundleInfo.LoadDeliveryAssetBundleAsync(FileLoadPath); _createRequest = MainBundleInfo.LoadDeliveryAssetBundleAsync(FileLoadPath);
_steps = ESteps.CheckLoadFile; _steps = ESteps.CheckLoadFile;
} }
// 7. 检测AssetBundle加载结果 // 7. 检测AssetBundle加载结果
if (_steps == ESteps.CheckLoadFile) if (_steps == ESteps.CheckLoadFile)
{ {
if (_createRequest != null) if (_createRequest != null)
{ {
if (_isWaitForAsyncComplete || IsForceDestroyComplete) if (_isWaitForAsyncComplete || IsForceDestroyComplete)
{ {
// 强制挂起主线程(注意:该操作会很耗时) // 强制挂起主线程(注意:该操作会很耗时)
YooLogger.Warning("Suspend the main thread to load unity bundle."); YooLogger.Warning("Suspend the main thread to load unity bundle.");
CacheBundle = _createRequest.assetBundle; CacheBundle = _createRequest.assetBundle;
} }
else else
{ {
if (_createRequest.isDone == false) if (_createRequest.isDone == false)
return; return;
CacheBundle = _createRequest.assetBundle; CacheBundle = _createRequest.assetBundle;
} }
} }
// Check error // Check error
if (CacheBundle == null) if (CacheBundle == null)
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EStatus.Failed; Status = EStatus.Failed;
LastError = $"Failed to load assetBundle : {MainBundleInfo.Bundle.BundleName}"; LastError = $"Failed to load assetBundle : {MainBundleInfo.Bundle.BundleName}";
YooLogger.Error(LastError); YooLogger.Error(LastError);
// 注意当缓存文件的校验等级为Low的时候并不能保证缓存文件的完整性。 // 注意当缓存文件的校验等级为Low的时候并不能保证缓存文件的完整性。
// 在AssetBundle文件加载失败的情况下我们需要重新验证文件的完整性 // 在AssetBundle文件加载失败的情况下我们需要重新验证文件的完整性
if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromCache) if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromCache)
{ {
var result = MainBundleInfo.VerifySelf(); var result = MainBundleInfo.VerifySelf();
if (result != EVerifyResult.Succeed) if (result != EVerifyResult.Succeed)
{ {
YooLogger.Error($"Found possibly corrupt file ! {MainBundleInfo.Bundle.CacheGUID} Verify result : {result}"); YooLogger.Error($"Found possibly corrupt file ! {MainBundleInfo.Bundle.CacheGUID} Verify result : {result}");
MainBundleInfo.CacheDiscard(); MainBundleInfo.CacheDiscard();
} }
} }
} }
else else
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EStatus.Succeed; Status = EStatus.Succeed;
} }
} }
} }
/// <summary> /// <summary>
/// 销毁 /// 销毁
/// </summary> /// </summary>
public override void Destroy() public override void Destroy()
{ {
base.Destroy(); base.Destroy();
if (_managedStream != null) if (_managedStream != null)
{ {
_managedStream.Close(); _managedStream.Close();
_managedStream.Dispose(); _managedStream.Dispose();
_managedStream = null; _managedStream = null;
} }
} }
/// <summary> /// <summary>
/// 主线程等待异步操作完毕 /// 主线程等待异步操作完毕
/// </summary> /// </summary>
public override void WaitForAsyncComplete() public override void WaitForAsyncComplete()
{ {
_isWaitForAsyncComplete = true; _isWaitForAsyncComplete = true;
int frame = 1000; int frame = 1000;
while (true) while (true)
{ {
// 文件解压 // 文件解压
if (_unpacker != null) if (_unpacker != null)
{ {
if (_unpacker.IsDone() == false) if (_unpacker.IsDone() == false)
{ {
_unpacker.WaitForAsyncComplete = true; _unpacker.WaitForAsyncComplete = true;
_unpacker.Update(); _unpacker.Update();
continue; continue;
} }
} }
// 保险机制 // 保险机制
// 注意如果需要从WEB端下载资源可能会触发保险机制 // 注意如果需要从WEB端下载资源可能会触发保险机制
frame--; frame--;
if (frame == 0) if (frame == 0)
{ {
if (_isShowWaitForAsyncError == false) if (_isShowWaitForAsyncError == false)
{ {
_isShowWaitForAsyncError = true; _isShowWaitForAsyncError = true;
YooLogger.Error($"{nameof(WaitForAsyncComplete)} failed ! Try load bundle : {MainBundleInfo.Bundle.BundleName} from remote with sync load method !"); YooLogger.Error($"{nameof(WaitForAsyncComplete)} failed ! Try load bundle : {MainBundleInfo.Bundle.BundleName} from remote with sync load method !");
} }
break; break;
} }
// 驱动流程 // 驱动流程
Update(); Update();
// 完成后退出 // 完成后退出
if (IsDone()) if (IsDone())
break; break;
} }
} }
} }
} }

View File

@ -7,105 +7,105 @@ using UnityEngine.Networking;
namespace YooAsset namespace YooAsset
{ {
/// <summary> /// <summary>
/// WebGL平台加载器 /// WebGL平台加载器
/// </summary> /// </summary>
internal sealed class AssetBundleWebLoader : BundleLoaderBase internal sealed class AssetBundleWebLoader : BundleLoaderBase
{ {
private enum ESteps private enum ESteps
{ {
None = 0, None = 0,
LoadWebSiteFile, LoadWebSiteFile,
LoadRemoteFile, LoadRemoteFile,
CheckLoadFile, CheckLoadFile,
Done, Done,
} }
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
private DownloaderBase _downloader; private DownloaderBase _downloader;
public AssetBundleWebLoader(ResourceManager impl, BundleInfo bundleInfo) : base(impl, bundleInfo) public AssetBundleWebLoader(ResourceManager impl, BundleInfo bundleInfo) : base(impl, bundleInfo)
{ {
} }
/// <summary> /// <summary>
/// 轮询更新 /// 轮询更新
/// </summary> /// </summary>
public override void Update() public override void Update()
{ {
if (_steps == ESteps.Done) if (_steps == ESteps.Done)
return; return;
if (_steps == ESteps.None) if (_steps == ESteps.None)
{ {
if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromRemote) if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromRemote)
{ {
_steps = ESteps.LoadRemoteFile; _steps = ESteps.LoadRemoteFile;
FileLoadPath = string.Empty; FileLoadPath = string.Empty;
} }
else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromStreaming) else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromStreaming)
{ {
_steps = ESteps.LoadWebSiteFile; _steps = ESteps.LoadWebSiteFile;
FileLoadPath = string.Empty; FileLoadPath = string.Empty;
} }
else else
{ {
throw new System.NotImplementedException(MainBundleInfo.LoadMode.ToString()); throw new System.NotImplementedException(MainBundleInfo.LoadMode.ToString());
} }
} }
// 1. 跨域获取资源包 // 1. 跨域获取资源包
if (_steps == ESteps.LoadRemoteFile) if (_steps == ESteps.LoadRemoteFile)
{ {
_downloader = MainBundleInfo.CreateDownloader(int.MaxValue); _downloader = MainBundleInfo.CreateDownloader(int.MaxValue);
_downloader.SendRequest(true); _downloader.SendRequest(true);
_steps = ESteps.CheckLoadFile; _steps = ESteps.CheckLoadFile;
} }
// 2. 从站点获取资源包 // 2. 从站点获取资源包
if (_steps == ESteps.LoadWebSiteFile) if (_steps == ESteps.LoadWebSiteFile)
{ {
_downloader = MainBundleInfo.CreateUnpacker(int.MaxValue); _downloader = MainBundleInfo.CreateUnpacker(int.MaxValue);
_downloader.SendRequest(true); _downloader.SendRequest(true);
_steps = ESteps.CheckLoadFile; _steps = ESteps.CheckLoadFile;
} }
// 3. 检测加载结果 // 3. 检测加载结果
if (_steps == ESteps.CheckLoadFile) if (_steps == ESteps.CheckLoadFile)
{ {
DownloadProgress = _downloader.DownloadProgress; DownloadProgress = _downloader.DownloadProgress;
DownloadedBytes = _downloader.DownloadedBytes; DownloadedBytes = _downloader.DownloadedBytes;
if (_downloader.IsDone() == false) if (_downloader.IsDone() == false)
return; return;
CacheBundle = _downloader.GetAssetBundle(); CacheBundle = _downloader.GetAssetBundle();
if (CacheBundle == null) if (CacheBundle == null)
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EStatus.Failed; Status = EStatus.Failed;
LastError = $"AssetBundle file is invalid : {MainBundleInfo.Bundle.BundleName}"; LastError = $"AssetBundle file is invalid : {MainBundleInfo.Bundle.BundleName}";
YooLogger.Error(LastError); YooLogger.Error(LastError);
} }
else else
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EStatus.Succeed; Status = EStatus.Succeed;
} }
} }
} }
/// <summary> /// <summary>
/// 主线程等待异步操作完毕 /// 主线程等待异步操作完毕
/// </summary> /// </summary>
public override void WaitForAsyncComplete() public override void WaitForAsyncComplete()
{ {
if (IsDone() == false) if (IsDone() == false)
{ {
Status = EStatus.Failed; Status = EStatus.Failed;
LastError = $"{nameof(WaitForAsyncComplete)} failed ! WebGL platform not support sync load method !"; LastError = $"{nameof(WaitForAsyncComplete)} failed ! WebGL platform not support sync load method !";
YooLogger.Error(LastError); YooLogger.Error(LastError);
} }
} }
} }
} }

View File

@ -5,177 +5,177 @@ using UnityEngine;
namespace YooAsset namespace YooAsset
{ {
internal abstract class BundleLoaderBase internal abstract class BundleLoaderBase
{ {
public enum EStatus public enum EStatus
{ {
None = 0, None = 0,
Succeed, Succeed,
Failed Failed
} }
/// <summary> /// <summary>
/// 所属资源系统 /// 所属资源系统
/// </summary> /// </summary>
public ResourceManager Impl { private set; get; } public ResourceManager Impl { private set; get; }
/// <summary> /// <summary>
/// 资源包文件信息 /// 资源包文件信息
/// </summary> /// </summary>
public BundleInfo MainBundleInfo { private set; get; } public BundleInfo MainBundleInfo { private set; get; }
/// <summary> /// <summary>
/// 引用计数 /// 引用计数
/// </summary> /// </summary>
public int RefCount { private set; get; } public int RefCount { private set; get; }
/// <summary> /// <summary>
/// 加载状态 /// 加载状态
/// </summary> /// </summary>
public EStatus Status { protected set; get; } public EStatus Status { protected set; get; }
/// <summary> /// <summary>
/// 最近的错误信息 /// 最近的错误信息
/// </summary> /// </summary>
public string LastError { protected set; get; } public string LastError { protected set; get; }
/// <summary> /// <summary>
/// 是否已经销毁 /// 是否已经销毁
/// </summary> /// </summary>
public bool IsDestroyed { private set; get; } = false; public bool IsDestroyed { private set; get; } = false;
private readonly List<ProviderBase> _providers = new List<ProviderBase>(100); private readonly List<ProviderBase> _providers = new List<ProviderBase>(100);
private readonly List<ProviderBase> _removeList = new List<ProviderBase>(100); private readonly List<ProviderBase> _removeList = new List<ProviderBase>(100);
protected bool IsForceDestroyComplete { private set; get; } = false; protected bool IsForceDestroyComplete { private set; get; } = false;
internal AssetBundle CacheBundle { set; get; } internal AssetBundle CacheBundle { set; get; }
internal string FileLoadPath { set; get; } internal string FileLoadPath { set; get; }
internal float DownloadProgress { set; get; } internal float DownloadProgress { set; get; }
internal ulong DownloadedBytes { set; get; } internal ulong DownloadedBytes { set; get; }
public BundleLoaderBase(ResourceManager impl, BundleInfo bundleInfo) public BundleLoaderBase(ResourceManager impl, BundleInfo bundleInfo)
{ {
Impl = impl; Impl = impl;
MainBundleInfo = bundleInfo; MainBundleInfo = bundleInfo;
RefCount = 0; RefCount = 0;
Status = EStatus.None; Status = EStatus.None;
} }
/// <summary> /// <summary>
/// 引用(引用计数递加) /// 引用(引用计数递加)
/// </summary> /// </summary>
public void Reference() public void Reference()
{ {
RefCount++; RefCount++;
} }
/// <summary> /// <summary>
/// 释放(引用计数递减) /// 释放(引用计数递减)
/// </summary> /// </summary>
public void Release() public void Release()
{ {
RefCount--; RefCount--;
} }
/// <summary> /// <summary>
/// 是否完毕(无论成功或失败) /// 是否完毕(无论成功或失败)
/// </summary> /// </summary>
public bool IsDone() public bool IsDone()
{ {
return Status == EStatus.Succeed || Status == EStatus.Failed; return Status == EStatus.Succeed || Status == EStatus.Failed;
} }
/// <summary> /// <summary>
/// 是否可以销毁 /// 是否可以销毁
/// </summary> /// </summary>
public bool CanDestroy() public bool CanDestroy()
{ {
if (IsDone() == false) if (IsDone() == false)
return false; return false;
return RefCount <= 0; return RefCount <= 0;
} }
/// <summary> /// <summary>
/// 添加附属的资源提供者 /// 添加附属的资源提供者
/// </summary> /// </summary>
public void AddProvider(ProviderBase provider) public void AddProvider(ProviderBase provider)
{ {
if (_providers.Contains(provider) == false) if (_providers.Contains(provider) == false)
_providers.Add(provider); _providers.Add(provider);
} }
/// <summary> /// <summary>
/// 尝试销毁资源提供者 /// 尝试销毁资源提供者
/// </summary> /// </summary>
public void TryDestroyProviders() public void TryDestroyProviders()
{ {
// 获取移除列表 // 获取移除列表
_removeList.Clear(); _removeList.Clear();
foreach (var provider in _providers) foreach (var provider in _providers)
{ {
if (provider.CanDestroy()) if (provider.CanDestroy())
{ {
_removeList.Add(provider); _removeList.Add(provider);
} }
} }
// 销毁资源提供者 // 销毁资源提供者
foreach (var provider in _removeList) foreach (var provider in _removeList)
{ {
_providers.Remove(provider); _providers.Remove(provider);
provider.Destroy(); provider.Destroy();
} }
// 移除资源提供者 // 移除资源提供者
if (_removeList.Count > 0) if (_removeList.Count > 0)
{ {
Impl.RemoveBundleProviders(_removeList); Impl.RemoveBundleProviders(_removeList);
_removeList.Clear(); _removeList.Clear();
} }
} }
/// <summary> /// <summary>
/// 轮询更新 /// 轮询更新
/// </summary> /// </summary>
public abstract void Update(); public abstract void Update();
/// <summary> /// <summary>
/// 销毁 /// 销毁
/// </summary> /// </summary>
public virtual void Destroy() public virtual void Destroy()
{ {
IsDestroyed = true; IsDestroyed = true;
// Check fatal // Check fatal
if (RefCount > 0) if (RefCount > 0)
throw new Exception($"Bundle file loader ref is not zero : {MainBundleInfo.Bundle.BundleName}"); throw new Exception($"Bundle file loader ref is not zero : {MainBundleInfo.Bundle.BundleName}");
if (IsDone() == false) if (IsDone() == false)
throw new Exception($"Bundle file loader is not done : {MainBundleInfo.Bundle.BundleName}"); throw new Exception($"Bundle file loader is not done : {MainBundleInfo.Bundle.BundleName}");
if (CacheBundle != null) if (CacheBundle != null)
{ {
CacheBundle.Unload(true); CacheBundle.Unload(true);
CacheBundle = null; CacheBundle = null;
} }
} }
/// <summary> /// <summary>
/// 强制销毁资源提供者 /// 强制销毁资源提供者
/// </summary> /// </summary>
public void ForceDestroyComplete() public void ForceDestroyComplete()
{ {
IsForceDestroyComplete = true; IsForceDestroyComplete = true;
// 注意:主动轮询更新完成同步加载 // 注意:主动轮询更新完成同步加载
// 说明:如果正在下载或解压也可以放心销毁。 // 说明:如果正在下载或解压也可以放心销毁。
Update(); Update();
} }
/// <summary> /// <summary>
/// 主线程等待异步操作完毕 /// 主线程等待异步操作完毕
/// </summary> /// </summary>
public abstract void WaitForAsyncComplete(); public abstract void WaitForAsyncComplete();
} }
} }

View File

@ -4,109 +4,109 @@ using System.Collections.Generic;
namespace YooAsset namespace YooAsset
{ {
internal class DependAssetBundles internal class DependAssetBundles
{ {
/// <summary> /// <summary>
/// 依赖的资源包加载器列表 /// 依赖的资源包加载器列表
/// </summary> /// </summary>
internal readonly List<BundleLoaderBase> DependList; internal readonly List<BundleLoaderBase> DependList;
public DependAssetBundles(List<BundleLoaderBase> dpendList) public DependAssetBundles(List<BundleLoaderBase> dpendList)
{ {
DependList = dpendList; DependList = dpendList;
} }
/// <summary> /// <summary>
/// 是否已经完成(无论成功或失败) /// 是否已经完成(无论成功或失败)
/// </summary> /// </summary>
public bool IsDone() public bool IsDone()
{ {
foreach (var loader in DependList) foreach (var loader in DependList)
{ {
if (loader.IsDone() == false) if (loader.IsDone() == false)
return false; return false;
} }
return true; return true;
} }
/// <summary> /// <summary>
/// 依赖资源包是否全部加载成功 /// 依赖资源包是否全部加载成功
/// </summary> /// </summary>
public bool IsSucceed() public bool IsSucceed()
{ {
foreach (var loader in DependList) foreach (var loader in DependList)
{ {
if (loader.Status != BundleLoaderBase.EStatus.Succeed) if (loader.Status != BundleLoaderBase.EStatus.Succeed)
{ {
return false; return false;
} }
} }
return true; return true;
} }
/// <summary> /// <summary>
/// 获取某个加载失败的资源包错误信息 /// 获取某个加载失败的资源包错误信息
/// </summary> /// </summary>
public string GetLastError() public string GetLastError()
{ {
foreach (var loader in DependList) foreach (var loader in DependList)
{ {
if (loader.Status != BundleLoaderBase.EStatus.Succeed) if (loader.Status != BundleLoaderBase.EStatus.Succeed)
{ {
return loader.LastError; return loader.LastError;
} }
} }
return string.Empty; return string.Empty;
} }
/// <summary> /// <summary>
/// 主线程等待异步操作完毕 /// 主线程等待异步操作完毕
/// </summary> /// </summary>
public void WaitForAsyncComplete() public void WaitForAsyncComplete()
{ {
foreach (var loader in DependList) foreach (var loader in DependList)
{ {
if (loader.IsDone() == false) if (loader.IsDone() == false)
loader.WaitForAsyncComplete(); loader.WaitForAsyncComplete();
} }
} }
/// <summary> /// <summary>
/// 增加引用计数 /// 增加引用计数
/// </summary> /// </summary>
public void Reference() public void Reference()
{ {
foreach (var loader in DependList) foreach (var loader in DependList)
{ {
loader.Reference(); loader.Reference();
} }
} }
/// <summary> /// <summary>
/// 减少引用计数 /// 减少引用计数
/// </summary> /// </summary>
public void Release() public void Release()
{ {
foreach (var loader in DependList) foreach (var loader in DependList)
{ {
loader.Release(); loader.Release();
} }
} }
/// <summary> /// <summary>
/// 获取资源包的调试信息列表 /// 获取资源包的调试信息列表
/// </summary> /// </summary>
internal void GetBundleDebugInfos(List<DebugBundleInfo> output) internal void GetBundleDebugInfos(List<DebugBundleInfo> output)
{ {
foreach (var loader in DependList) foreach (var loader in DependList)
{ {
var bundleInfo = new DebugBundleInfo(); var bundleInfo = new DebugBundleInfo();
bundleInfo.BundleName = loader.MainBundleInfo.Bundle.BundleName; bundleInfo.BundleName = loader.MainBundleInfo.Bundle.BundleName;
bundleInfo.RefCount = loader.RefCount; bundleInfo.RefCount = loader.RefCount;
bundleInfo.Status = loader.Status.ToString(); bundleInfo.Status = loader.Status.ToString();
output.Add(bundleInfo); output.Add(bundleInfo);
} }
} }
} }
} }

View File

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

View File

@ -2,144 +2,144 @@
namespace YooAsset namespace YooAsset
{ {
/// <summary> /// <summary>
/// WebGL平台加载器 /// WebGL平台加载器
/// </summary> /// </summary>
internal class RawBundleWebLoader : BundleLoaderBase internal class RawBundleWebLoader : BundleLoaderBase
{ {
private enum ESteps private enum ESteps
{ {
None, None,
Download, Download,
CheckDownload, CheckDownload,
Website, Website,
CheckWebsite, CheckWebsite,
CheckFile, CheckFile,
Done, Done,
} }
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
private DownloaderBase _website; private DownloaderBase _website;
private DownloaderBase _downloader; private DownloaderBase _downloader;
public RawBundleWebLoader(ResourceManager impl, BundleInfo bundleInfo) : base(impl, bundleInfo) public RawBundleWebLoader(ResourceManager impl, BundleInfo bundleInfo) : base(impl, bundleInfo)
{ {
} }
/// <summary> /// <summary>
/// 轮询更新 /// 轮询更新
/// </summary> /// </summary>
public override void Update() public override void Update()
{ {
if (_steps == ESteps.Done) if (_steps == ESteps.Done)
return; return;
if (_steps == ESteps.None) if (_steps == ESteps.None)
{ {
if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromRemote) if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromRemote)
{ {
_steps = ESteps.Download; _steps = ESteps.Download;
FileLoadPath = MainBundleInfo.CachedDataFilePath; FileLoadPath = MainBundleInfo.CachedDataFilePath;
} }
else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromStreaming) else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromStreaming)
{ {
_steps = ESteps.Website; _steps = ESteps.Website;
FileLoadPath = MainBundleInfo.CachedDataFilePath; FileLoadPath = MainBundleInfo.CachedDataFilePath;
} }
else else
{ {
throw new System.NotImplementedException(MainBundleInfo.LoadMode.ToString()); throw new System.NotImplementedException(MainBundleInfo.LoadMode.ToString());
} }
} }
// 1. 下载远端文件 // 1. 下载远端文件
if (_steps == ESteps.Download) if (_steps == ESteps.Download)
{ {
_downloader = MainBundleInfo.CreateDownloader(int.MaxValue); _downloader = MainBundleInfo.CreateDownloader(int.MaxValue);
_downloader.SendRequest(); _downloader.SendRequest();
_steps = ESteps.CheckDownload; _steps = ESteps.CheckDownload;
} }
// 2. 检测下载结果 // 2. 检测下载结果
if (_steps == ESteps.CheckDownload) if (_steps == ESteps.CheckDownload)
{ {
DownloadProgress = _downloader.DownloadProgress; DownloadProgress = _downloader.DownloadProgress;
DownloadedBytes = _downloader.DownloadedBytes; DownloadedBytes = _downloader.DownloadedBytes;
if (_downloader.IsDone() == false) if (_downloader.IsDone() == false)
return; return;
if (_downloader.HasError()) if (_downloader.HasError())
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EStatus.Failed; Status = EStatus.Failed;
LastError = _downloader.GetLastError(); LastError = _downloader.GetLastError();
} }
else else
{ {
_steps = ESteps.CheckFile; _steps = ESteps.CheckFile;
} }
} }
// 3. 从站点下载 // 3. 从站点下载
if (_steps == ESteps.Website) if (_steps == ESteps.Website)
{ {
_website = MainBundleInfo.CreateUnpacker(int.MaxValue); _website = MainBundleInfo.CreateUnpacker(int.MaxValue);
_website.SendRequest(); _website.SendRequest();
_steps = ESteps.CheckWebsite; _steps = ESteps.CheckWebsite;
} }
// 4. 检测站点下载 // 4. 检测站点下载
if (_steps == ESteps.CheckWebsite) if (_steps == ESteps.CheckWebsite)
{ {
DownloadProgress = _website.DownloadProgress; DownloadProgress = _website.DownloadProgress;
DownloadedBytes = _website.DownloadedBytes; DownloadedBytes = _website.DownloadedBytes;
if (_website.IsDone() == false) if (_website.IsDone() == false)
return; return;
if (_website.HasError()) if (_website.HasError())
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EStatus.Failed; Status = EStatus.Failed;
LastError = _website.GetLastError(); LastError = _website.GetLastError();
} }
else else
{ {
_steps = ESteps.CheckFile; _steps = ESteps.CheckFile;
} }
} }
// 5. 检测结果 // 5. 检测结果
if (_steps == ESteps.CheckFile) if (_steps == ESteps.CheckFile)
{ {
// 设置下载进度 // 设置下载进度
DownloadProgress = 1f; DownloadProgress = 1f;
DownloadedBytes = (ulong)MainBundleInfo.Bundle.FileSize; DownloadedBytes = (ulong)MainBundleInfo.Bundle.FileSize;
_steps = ESteps.Done; _steps = ESteps.Done;
if (File.Exists(FileLoadPath)) if (File.Exists(FileLoadPath))
{ {
Status = EStatus.Succeed; Status = EStatus.Succeed;
} }
else else
{ {
Status = EStatus.Failed; Status = EStatus.Failed;
LastError = $"Raw file not found : {FileLoadPath}"; LastError = $"Raw file not found : {FileLoadPath}";
} }
} }
} }
/// <summary> /// <summary>
/// 主线程等待异步操作完毕 /// 主线程等待异步操作完毕
/// </summary> /// </summary>
public override void WaitForAsyncComplete() public override void WaitForAsyncComplete()
{ {
if (IsDone() == false) if (IsDone() == false)
{ {
Status = EStatus.Failed; Status = EStatus.Failed;
LastError = $"{nameof(WaitForAsyncComplete)} failed ! WebGL platform not support sync load method !"; LastError = $"{nameof(WaitForAsyncComplete)} failed ! WebGL platform not support sync load method !";
YooLogger.Error(LastError); YooLogger.Error(LastError);
} }
} }
} }
} }

View File

@ -1,82 +1,82 @@
 
namespace YooAsset namespace YooAsset
{ {
internal class VirtualBundleFileLoader : BundleLoaderBase internal class VirtualBundleFileLoader : BundleLoaderBase
{ {
private enum ESteps private enum ESteps
{ {
None, None,
CheckFile, CheckFile,
Done, Done,
} }
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
public VirtualBundleFileLoader(ResourceManager impl, BundleInfo bundleInfo) : base(impl, bundleInfo) public VirtualBundleFileLoader(ResourceManager impl, BundleInfo bundleInfo) : base(impl, bundleInfo)
{ {
} }
/// <summary> /// <summary>
/// 轮询更新 /// 轮询更新
/// </summary> /// </summary>
public override void Update() public override void Update()
{ {
if (_steps == ESteps.Done) if (_steps == ESteps.Done)
return; return;
if (_steps == ESteps.None) if (_steps == ESteps.None)
{ {
if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromEditor) if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromEditor)
{ {
_steps = ESteps.CheckFile; _steps = ESteps.CheckFile;
} }
else else
{ {
throw new System.NotImplementedException(MainBundleInfo.LoadMode.ToString()); throw new System.NotImplementedException(MainBundleInfo.LoadMode.ToString());
} }
} }
// 1. 检测结果 // 1. 检测结果
if (_steps == ESteps.CheckFile) if (_steps == ESteps.CheckFile)
{ {
// 设置下载进度 // 设置下载进度
DownloadProgress = 1f; DownloadProgress = 1f;
DownloadedBytes = (ulong)MainBundleInfo.Bundle.FileSize; DownloadedBytes = (ulong)MainBundleInfo.Bundle.FileSize;
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EStatus.Succeed; Status = EStatus.Succeed;
} }
} }
/// <summary> /// <summary>
/// 主线程等待异步操作完毕 /// 主线程等待异步操作完毕
/// </summary> /// </summary>
public override void WaitForAsyncComplete() public override void WaitForAsyncComplete()
{ {
int frame = 1000; int frame = 1000;
while (true) while (true)
{ {
// 保险机制 // 保险机制
// 注意:如果需要从远端下载资源,可能会触发保险机制! // 注意:如果需要从远端下载资源,可能会触发保险机制!
frame--; frame--;
if (frame == 0) if (frame == 0)
{ {
if (IsDone() == false) if (IsDone() == false)
{ {
Status = EStatus.Failed; Status = EStatus.Failed;
LastError = $"WaitForAsyncComplete failed ! Try load bundle : {MainBundleInfo.Bundle.BundleName} from remote with sync load method !"; LastError = $"WaitForAsyncComplete failed ! Try load bundle : {MainBundleInfo.Bundle.BundleName} from remote with sync load method !";
YooLogger.Error(LastError); YooLogger.Error(LastError);
} }
break; break;
} }
// 驱动流程 // 驱动流程
Update(); Update();
// 完成后退出 // 完成后退出
if (IsDone()) if (IsDone())
break; break;
} }
} }
} }
} }

View File

@ -2,131 +2,131 @@
namespace YooAsset namespace YooAsset
{ {
public sealed class InstantiateOperation : AsyncOperationBase public sealed class InstantiateOperation : AsyncOperationBase
{ {
private enum ESteps private enum ESteps
{ {
None, None,
Clone, Clone,
Done, Done,
} }
private readonly AssetHandle _handle; private readonly AssetHandle _handle;
private readonly bool _setPositionAndRotation; private readonly bool _setPositionAndRotation;
private readonly Vector3 _position; private readonly Vector3 _position;
private readonly Quaternion _rotation; private readonly Quaternion _rotation;
private readonly Transform _parent; private readonly Transform _parent;
private readonly bool _worldPositionStays; private readonly bool _worldPositionStays;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
/// <summary> /// <summary>
/// 实例化的游戏对象 /// 实例化的游戏对象
/// </summary> /// </summary>
public GameObject Result = null; public GameObject Result = null;
internal InstantiateOperation(AssetHandle handle, bool setPositionAndRotation, Vector3 position, Quaternion rotation, Transform parent, bool worldPositionStays) internal InstantiateOperation(AssetHandle handle, bool setPositionAndRotation, Vector3 position, Quaternion rotation, Transform parent, bool worldPositionStays)
{ {
_handle = handle; _handle = handle;
_setPositionAndRotation = setPositionAndRotation; _setPositionAndRotation = setPositionAndRotation;
_position = position; _position = position;
_rotation = rotation; _rotation = rotation;
_parent = parent; _parent = parent;
_worldPositionStays = worldPositionStays; _worldPositionStays = worldPositionStays;
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
_steps = ESteps.Clone; _steps = ESteps.Clone;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
if (_steps == ESteps.None || _steps == ESteps.Done) if (_steps == ESteps.None || _steps == ESteps.Done)
return; return;
if (_steps == ESteps.Clone) if (_steps == ESteps.Clone)
{ {
if (_handle.IsValidWithWarning == false) if (_handle.IsValidWithWarning == false)
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = $"{nameof(AssetHandle)} is invalid."; Error = $"{nameof(AssetHandle)} is invalid.";
return; return;
} }
if (_handle.IsDone == false) if (_handle.IsDone == false)
return; return;
if (_handle.AssetObject == null) if (_handle.AssetObject == null)
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = $"{nameof(AssetHandle.AssetObject)} is null."; Error = $"{nameof(AssetHandle.AssetObject)} is null.";
return; return;
} }
// 实例化游戏对象 // 实例化游戏对象
Result = InstantiateInternal(_handle.AssetObject, _setPositionAndRotation, _position, _rotation, _parent, _worldPositionStays); Result = InstantiateInternal(_handle.AssetObject, _setPositionAndRotation, _position, _rotation, _parent, _worldPositionStays);
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
} }
/// <summary> /// <summary>
/// 取消实例化对象操作 /// 取消实例化对象操作
/// </summary> /// </summary>
public void Cancel() public void Cancel()
{ {
if (IsDone == false) if (IsDone == false)
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = $"User cancelled !"; Error = $"User cancelled !";
} }
} }
/// <summary> /// <summary>
/// 等待异步实例化结束 /// 等待异步实例化结束
/// </summary> /// </summary>
public void WaitForAsyncComplete() public void WaitForAsyncComplete()
{ {
if (_steps == ESteps.Done) if (_steps == ESteps.Done)
return; return;
_handle.WaitForAsyncComplete(); _handle.WaitForAsyncComplete();
InternalOnUpdate(); InternalOnUpdate();
} }
internal static GameObject InstantiateInternal(UnityEngine.Object assetObject, bool setPositionAndRotation, Vector3 position, Quaternion rotation, Transform parent, bool worldPositionStays) internal static GameObject InstantiateInternal(UnityEngine.Object assetObject, bool setPositionAndRotation, Vector3 position, Quaternion rotation, Transform parent, bool worldPositionStays)
{ {
if (assetObject == null) if (assetObject == null)
return null; return null;
if (setPositionAndRotation) if (setPositionAndRotation)
{ {
if (parent != null) if (parent != null)
{ {
GameObject clone = UnityEngine.Object.Instantiate(assetObject as GameObject, position, rotation, parent); GameObject clone = UnityEngine.Object.Instantiate(assetObject as GameObject, position, rotation, parent);
return clone; return clone;
} }
else else
{ {
GameObject clone = UnityEngine.Object.Instantiate(assetObject as GameObject, position, rotation); GameObject clone = UnityEngine.Object.Instantiate(assetObject as GameObject, position, rotation);
return clone; return clone;
} }
} }
else else
{ {
if (parent != null) if (parent != null)
{ {
GameObject clone = UnityEngine.Object.Instantiate(assetObject as GameObject, parent, worldPositionStays); GameObject clone = UnityEngine.Object.Instantiate(assetObject as GameObject, parent, worldPositionStays);
return clone; return clone;
} }
else else
{ {
GameObject clone = UnityEngine.Object.Instantiate(assetObject as GameObject); GameObject clone = UnityEngine.Object.Instantiate(assetObject as GameObject);
return clone; return clone;
} }
} }
} }
} }
} }

View File

@ -3,98 +3,98 @@ using UnityEngine.SceneManagement;
namespace YooAsset namespace YooAsset
{ {
/// <summary> /// <summary>
/// 场景卸载异步操作类 /// 场景卸载异步操作类
/// </summary> /// </summary>
public sealed class UnloadSceneOperation : AsyncOperationBase public sealed class UnloadSceneOperation : AsyncOperationBase
{ {
private enum ESteps private enum ESteps
{ {
None, None,
CheckError, CheckError,
PrepareDone, PrepareDone,
UnLoadScene, UnLoadScene,
Checking, Checking,
Done, Done,
} }
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
private readonly string _error; private readonly string _error;
private readonly ProviderBase _provider; private readonly ProviderBase _provider;
private AsyncOperation _asyncOp; private AsyncOperation _asyncOp;
internal UnloadSceneOperation(string error) internal UnloadSceneOperation(string error)
{ {
_error = error; _error = error;
} }
internal UnloadSceneOperation(ProviderBase provider) internal UnloadSceneOperation(ProviderBase provider)
{ {
_error = null; _error = null;
_provider = provider; _provider = provider;
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
_steps = ESteps.CheckError; _steps = ESteps.CheckError;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
if (_steps == ESteps.None || _steps == ESteps.Done) if (_steps == ESteps.None || _steps == ESteps.Done)
return; return;
if (_steps == ESteps.CheckError) if (_steps == ESteps.CheckError)
{ {
if (string.IsNullOrEmpty(_error) == false) if (string.IsNullOrEmpty(_error) == false)
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = _error; Error = _error;
return; return;
} }
_steps = ESteps.PrepareDone; _steps = ESteps.PrepareDone;
} }
if(_steps == ESteps.PrepareDone) if (_steps == ESteps.PrepareDone)
{ {
if (_provider.IsDone == false) if (_provider.IsDone == false)
return; return;
if (_provider.SceneObject.IsValid() == false) if (_provider.SceneObject.IsValid() == false)
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = "Scene is invalid !"; Error = "Scene is invalid !";
return; return;
} }
if (_provider.SceneObject.isLoaded == false) if (_provider.SceneObject.isLoaded == false)
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = "Scene is not loaded !"; Error = "Scene is not loaded !";
return; return;
} }
_steps = ESteps.UnLoadScene; _steps = ESteps.UnLoadScene;
} }
if (_steps == ESteps.UnLoadScene) if (_steps == ESteps.UnLoadScene)
{ {
_asyncOp = SceneManager.UnloadSceneAsync(_provider.SceneObject); _asyncOp = SceneManager.UnloadSceneAsync(_provider.SceneObject);
_provider.ResourceMgr.UnloadSubScene(_provider.SceneName); _provider.ResourceMgr.UnloadSubScene(_provider.SceneName);
_provider.ResourceMgr.TryUnloadUnusedAsset(_provider.MainAssetInfo); _provider.ResourceMgr.TryUnloadUnusedAsset(_provider.MainAssetInfo);
_steps = ESteps.Checking; _steps = ESteps.Checking;
} }
if (_steps == ESteps.Checking) if (_steps == ESteps.Checking)
{ {
Progress = _asyncOp.progress; Progress = _asyncOp.progress;
if (_asyncOp.isDone == false) if (_asyncOp.isDone == false)
return; return;
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
} }
} }
} }

View File

@ -4,119 +4,119 @@ using UnityEngine;
namespace YooAsset namespace YooAsset
{ {
internal sealed class BundledAllAssetsProvider : ProviderBase internal sealed class BundledAllAssetsProvider : ProviderBase
{ {
private AssetBundleRequest _cacheRequest; private AssetBundleRequest _cacheRequest;
public BundledAllAssetsProvider(ResourceManager manager, string providerGUID, AssetInfo assetInfo) : base(manager, providerGUID, assetInfo) public BundledAllAssetsProvider(ResourceManager manager, string providerGUID, AssetInfo assetInfo) : base(manager, providerGUID, assetInfo)
{ {
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
DebugBeginRecording(); DebugBeginRecording();
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
if (IsDone) if (IsDone)
return; return;
if (_steps == ESteps.None) if (_steps == ESteps.None)
{ {
_steps = ESteps.CheckBundle; _steps = ESteps.CheckBundle;
} }
// 1. 检测资源包 // 1. 检测资源包
if (_steps == ESteps.CheckBundle) if (_steps == ESteps.CheckBundle)
{ {
if (IsWaitForAsyncComplete) if (IsWaitForAsyncComplete)
{ {
DependBundles.WaitForAsyncComplete(); DependBundles.WaitForAsyncComplete();
OwnerBundle.WaitForAsyncComplete(); OwnerBundle.WaitForAsyncComplete();
} }
if (DependBundles.IsDone() == false) if (DependBundles.IsDone() == false)
return; return;
if (OwnerBundle.IsDone() == false) if (OwnerBundle.IsDone() == false)
return; return;
if (DependBundles.IsSucceed() == false) if (DependBundles.IsSucceed() == false)
{ {
string error = DependBundles.GetLastError(); string error = DependBundles.GetLastError();
InvokeCompletion(error, EOperationStatus.Failed); InvokeCompletion(error, EOperationStatus.Failed);
return; return;
} }
if (OwnerBundle.Status != BundleLoaderBase.EStatus.Succeed) if (OwnerBundle.Status != BundleLoaderBase.EStatus.Succeed)
{ {
string error = OwnerBundle.LastError; string error = OwnerBundle.LastError;
InvokeCompletion(error, EOperationStatus.Failed); InvokeCompletion(error, EOperationStatus.Failed);
return; return;
} }
if (OwnerBundle.CacheBundle == null) if (OwnerBundle.CacheBundle == null)
{ {
ProcessCacheBundleException(); ProcessCacheBundleException();
return; return;
} }
_steps = ESteps.Loading; _steps = ESteps.Loading;
} }
// 2. 加载资源对象 // 2. 加载资源对象
if (_steps == ESteps.Loading) if (_steps == ESteps.Loading)
{ {
if (IsWaitForAsyncComplete || IsForceDestroyComplete) if (IsWaitForAsyncComplete || IsForceDestroyComplete)
{ {
if (MainAssetInfo.AssetType == null) if (MainAssetInfo.AssetType == null)
AllAssetObjects = OwnerBundle.CacheBundle.LoadAllAssets(); AllAssetObjects = OwnerBundle.CacheBundle.LoadAllAssets();
else else
AllAssetObjects = OwnerBundle.CacheBundle.LoadAllAssets(MainAssetInfo.AssetType); AllAssetObjects = OwnerBundle.CacheBundle.LoadAllAssets(MainAssetInfo.AssetType);
} }
else else
{ {
if (MainAssetInfo.AssetType == null) if (MainAssetInfo.AssetType == null)
_cacheRequest = OwnerBundle.CacheBundle.LoadAllAssetsAsync(); _cacheRequest = OwnerBundle.CacheBundle.LoadAllAssetsAsync();
else else
_cacheRequest = OwnerBundle.CacheBundle.LoadAllAssetsAsync(MainAssetInfo.AssetType); _cacheRequest = OwnerBundle.CacheBundle.LoadAllAssetsAsync(MainAssetInfo.AssetType);
} }
_steps = ESteps.Checking; _steps = ESteps.Checking;
} }
// 3. 检测加载结果 // 3. 检测加载结果
if (_steps == ESteps.Checking) if (_steps == ESteps.Checking)
{ {
if (_cacheRequest != null) if (_cacheRequest != null)
{ {
if (IsWaitForAsyncComplete || IsForceDestroyComplete) if (IsWaitForAsyncComplete || IsForceDestroyComplete)
{ {
// 强制挂起主线程(注意:该操作会很耗时) // 强制挂起主线程(注意:该操作会很耗时)
YooLogger.Warning("Suspend the main thread to load unity asset."); YooLogger.Warning("Suspend the main thread to load unity asset.");
AllAssetObjects = _cacheRequest.allAssets; AllAssetObjects = _cacheRequest.allAssets;
} }
else else
{ {
Progress = _cacheRequest.progress; Progress = _cacheRequest.progress;
if (_cacheRequest.isDone == false) if (_cacheRequest.isDone == false)
return; return;
AllAssetObjects = _cacheRequest.allAssets; AllAssetObjects = _cacheRequest.allAssets;
} }
} }
if (AllAssetObjects == null) if (AllAssetObjects == null)
{ {
string error; string error;
if (MainAssetInfo.AssetType == null) if (MainAssetInfo.AssetType == null)
error = $"Failed to load all assets : {MainAssetInfo.AssetPath} AssetType : null AssetBundle : {OwnerBundle.MainBundleInfo.Bundle.BundleName}"; error = $"Failed to load all assets : {MainAssetInfo.AssetPath} AssetType : null AssetBundle : {OwnerBundle.MainBundleInfo.Bundle.BundleName}";
else else
error = $"Failed to load all assets : {MainAssetInfo.AssetPath} AssetType : {MainAssetInfo.AssetType} AssetBundle : {OwnerBundle.MainBundleInfo.Bundle.BundleName}"; error = $"Failed to load all assets : {MainAssetInfo.AssetPath} AssetType : {MainAssetInfo.AssetType} AssetBundle : {OwnerBundle.MainBundleInfo.Bundle.BundleName}";
YooLogger.Error(error); YooLogger.Error(error);
InvokeCompletion(error, EOperationStatus.Failed); InvokeCompletion(error, EOperationStatus.Failed);
} }
else else
{ {
InvokeCompletion(string.Empty, EOperationStatus.Succeed); InvokeCompletion(string.Empty, EOperationStatus.Succeed);
} }
} }
} }
} }
} }

View File

@ -4,119 +4,119 @@ using UnityEngine;
namespace YooAsset namespace YooAsset
{ {
internal sealed class BundledAssetProvider : ProviderBase internal sealed class BundledAssetProvider : ProviderBase
{ {
private AssetBundleRequest _cacheRequest; private AssetBundleRequest _cacheRequest;
public BundledAssetProvider(ResourceManager manager, string providerGUID, AssetInfo assetInfo) : base(manager, providerGUID, assetInfo) public BundledAssetProvider(ResourceManager manager, string providerGUID, AssetInfo assetInfo) : base(manager, providerGUID, assetInfo)
{ {
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
DebugBeginRecording(); DebugBeginRecording();
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
if (IsDone) if (IsDone)
return; return;
if (_steps == ESteps.None) if (_steps == ESteps.None)
{ {
_steps = ESteps.CheckBundle; _steps = ESteps.CheckBundle;
} }
// 1. 检测资源包 // 1. 检测资源包
if (_steps == ESteps.CheckBundle) if (_steps == ESteps.CheckBundle)
{ {
if (IsWaitForAsyncComplete) if (IsWaitForAsyncComplete)
{ {
DependBundles.WaitForAsyncComplete(); DependBundles.WaitForAsyncComplete();
OwnerBundle.WaitForAsyncComplete(); OwnerBundle.WaitForAsyncComplete();
} }
if (DependBundles.IsDone() == false) if (DependBundles.IsDone() == false)
return; return;
if (OwnerBundle.IsDone() == false) if (OwnerBundle.IsDone() == false)
return; return;
if (DependBundles.IsSucceed() == false) if (DependBundles.IsSucceed() == false)
{ {
string error = DependBundles.GetLastError(); string error = DependBundles.GetLastError();
InvokeCompletion(error, EOperationStatus.Failed); InvokeCompletion(error, EOperationStatus.Failed);
return; return;
} }
if (OwnerBundle.Status != BundleLoaderBase.EStatus.Succeed) if (OwnerBundle.Status != BundleLoaderBase.EStatus.Succeed)
{ {
string error = OwnerBundle.LastError; string error = OwnerBundle.LastError;
InvokeCompletion(error, EOperationStatus.Failed); InvokeCompletion(error, EOperationStatus.Failed);
return; return;
} }
if (OwnerBundle.CacheBundle == null) if (OwnerBundle.CacheBundle == null)
{ {
ProcessCacheBundleException(); ProcessCacheBundleException();
return; return;
} }
_steps = ESteps.Loading; _steps = ESteps.Loading;
} }
// 2. 加载资源对象 // 2. 加载资源对象
if (_steps == ESteps.Loading) if (_steps == ESteps.Loading)
{ {
if (IsWaitForAsyncComplete || IsForceDestroyComplete) if (IsWaitForAsyncComplete || IsForceDestroyComplete)
{ {
if (MainAssetInfo.AssetType == null) if (MainAssetInfo.AssetType == null)
AssetObject = OwnerBundle.CacheBundle.LoadAsset(MainAssetInfo.AssetPath); AssetObject = OwnerBundle.CacheBundle.LoadAsset(MainAssetInfo.AssetPath);
else else
AssetObject = OwnerBundle.CacheBundle.LoadAsset(MainAssetInfo.AssetPath, MainAssetInfo.AssetType); AssetObject = OwnerBundle.CacheBundle.LoadAsset(MainAssetInfo.AssetPath, MainAssetInfo.AssetType);
} }
else else
{ {
if (MainAssetInfo.AssetType == null) if (MainAssetInfo.AssetType == null)
_cacheRequest = OwnerBundle.CacheBundle.LoadAssetAsync(MainAssetInfo.AssetPath); _cacheRequest = OwnerBundle.CacheBundle.LoadAssetAsync(MainAssetInfo.AssetPath);
else else
_cacheRequest = OwnerBundle.CacheBundle.LoadAssetAsync(MainAssetInfo.AssetPath, MainAssetInfo.AssetType); _cacheRequest = OwnerBundle.CacheBundle.LoadAssetAsync(MainAssetInfo.AssetPath, MainAssetInfo.AssetType);
} }
_steps = ESteps.Checking; _steps = ESteps.Checking;
} }
// 3. 检测加载结果 // 3. 检测加载结果
if (_steps == ESteps.Checking) if (_steps == ESteps.Checking)
{ {
if (_cacheRequest != null) if (_cacheRequest != null)
{ {
if (IsWaitForAsyncComplete || IsForceDestroyComplete) if (IsWaitForAsyncComplete || IsForceDestroyComplete)
{ {
// 强制挂起主线程(注意:该操作会很耗时) // 强制挂起主线程(注意:该操作会很耗时)
YooLogger.Warning("Suspend the main thread to load unity asset."); YooLogger.Warning("Suspend the main thread to load unity asset.");
AssetObject = _cacheRequest.asset; AssetObject = _cacheRequest.asset;
} }
else else
{ {
Progress = _cacheRequest.progress; Progress = _cacheRequest.progress;
if (_cacheRequest.isDone == false) if (_cacheRequest.isDone == false)
return; return;
AssetObject = _cacheRequest.asset; AssetObject = _cacheRequest.asset;
} }
} }
if (AssetObject == null) if (AssetObject == null)
{ {
string error; string error;
if (MainAssetInfo.AssetType == null) if (MainAssetInfo.AssetType == null)
error = $"Failed to load asset : {MainAssetInfo.AssetPath} AssetType : null AssetBundle : {OwnerBundle.MainBundleInfo.Bundle.BundleName}"; error = $"Failed to load asset : {MainAssetInfo.AssetPath} AssetType : null AssetBundle : {OwnerBundle.MainBundleInfo.Bundle.BundleName}";
else else
error = $"Failed to load asset : {MainAssetInfo.AssetPath} AssetType : {MainAssetInfo.AssetType} AssetBundle : {OwnerBundle.MainBundleInfo.Bundle.BundleName}"; error = $"Failed to load asset : {MainAssetInfo.AssetPath} AssetType : {MainAssetInfo.AssetType} AssetBundle : {OwnerBundle.MainBundleInfo.Bundle.BundleName}";
YooLogger.Error(error); YooLogger.Error(error);
InvokeCompletion(error, EOperationStatus.Failed); InvokeCompletion(error, EOperationStatus.Failed);
} }
else else
{ {
InvokeCompletion(string.Empty, EOperationStatus.Succeed); InvokeCompletion(string.Empty, EOperationStatus.Succeed);
} }
} }
} }
} }
} }

View File

@ -1,52 +1,52 @@
 
namespace YooAsset namespace YooAsset
{ {
internal class BundledRawFileProvider : ProviderBase internal class BundledRawFileProvider : ProviderBase
{ {
public BundledRawFileProvider(ResourceManager manager, string providerGUID, AssetInfo assetInfo) : base(manager, providerGUID, assetInfo) public BundledRawFileProvider(ResourceManager manager, string providerGUID, AssetInfo assetInfo) : base(manager, providerGUID, assetInfo)
{ {
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
DebugBeginRecording(); DebugBeginRecording();
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
if (IsDone) if (IsDone)
return; return;
if (_steps == ESteps.None) if (_steps == ESteps.None)
{ {
_steps = ESteps.CheckBundle; _steps = ESteps.CheckBundle;
} }
// 1. 检测资源包 // 1. 检测资源包
if (_steps == ESteps.CheckBundle) if (_steps == ESteps.CheckBundle)
{ {
if (IsWaitForAsyncComplete) if (IsWaitForAsyncComplete)
{ {
OwnerBundle.WaitForAsyncComplete(); OwnerBundle.WaitForAsyncComplete();
} }
if (OwnerBundle.IsDone() == false) if (OwnerBundle.IsDone() == false)
return; return;
if (OwnerBundle.Status != BundleLoaderBase.EStatus.Succeed) if (OwnerBundle.Status != BundleLoaderBase.EStatus.Succeed)
{ {
string error = OwnerBundle.LastError; string error = OwnerBundle.LastError;
InvokeCompletion(error, EOperationStatus.Failed); InvokeCompletion(error, EOperationStatus.Failed);
return; return;
} }
_steps = ESteps.Checking; _steps = ESteps.Checking;
} }
// 2. 检测加载结果 // 2. 检测加载结果
if (_steps == ESteps.Checking) if (_steps == ESteps.Checking)
{ {
RawFilePath = OwnerBundle.FileLoadPath; RawFilePath = OwnerBundle.FileLoadPath;
InvokeCompletion(string.Empty, EOperationStatus.Succeed); InvokeCompletion(string.Empty, EOperationStatus.Succeed);
} }
} }
} }
} }

View File

@ -6,107 +6,107 @@ using UnityEngine.SceneManagement;
namespace YooAsset namespace YooAsset
{ {
internal sealed class BundledSceneProvider : ProviderBase internal sealed class BundledSceneProvider : ProviderBase
{ {
public readonly LoadSceneMode SceneMode; public readonly LoadSceneMode SceneMode;
private readonly bool _suspendLoad; private readonly bool _suspendLoad;
private AsyncOperation _asyncOperation; private AsyncOperation _asyncOperation;
public BundledSceneProvider(ResourceManager manager, string providerGUID, AssetInfo assetInfo, LoadSceneMode sceneMode, bool suspendLoad) : base(manager, providerGUID, assetInfo) public BundledSceneProvider(ResourceManager manager, string providerGUID, AssetInfo assetInfo, LoadSceneMode sceneMode, bool suspendLoad) : base(manager, providerGUID, assetInfo)
{ {
SceneMode = sceneMode; SceneMode = sceneMode;
SceneName = Path.GetFileNameWithoutExtension(assetInfo.AssetPath); SceneName = Path.GetFileNameWithoutExtension(assetInfo.AssetPath);
_suspendLoad = suspendLoad; _suspendLoad = suspendLoad;
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
DebugBeginRecording(); DebugBeginRecording();
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
if (IsDone) if (IsDone)
return; return;
if (_steps == ESteps.None) if (_steps == ESteps.None)
{ {
_steps = ESteps.CheckBundle; _steps = ESteps.CheckBundle;
} }
// 1. 检测资源包 // 1. 检测资源包
if (_steps == ESteps.CheckBundle) if (_steps == ESteps.CheckBundle)
{ {
if (DependBundles.IsDone() == false) if (DependBundles.IsDone() == false)
return; return;
if (OwnerBundle.IsDone() == false) if (OwnerBundle.IsDone() == false)
return; return;
if (DependBundles.IsSucceed() == false) if (DependBundles.IsSucceed() == false)
{ {
string error = DependBundles.GetLastError(); string error = DependBundles.GetLastError();
InvokeCompletion(error, EOperationStatus.Failed); InvokeCompletion(error, EOperationStatus.Failed);
return; return;
} }
if (OwnerBundle.Status != BundleLoaderBase.EStatus.Succeed) if (OwnerBundle.Status != BundleLoaderBase.EStatus.Succeed)
{ {
string error = OwnerBundle.LastError; string error = OwnerBundle.LastError;
InvokeCompletion(error, EOperationStatus.Failed); InvokeCompletion(error, EOperationStatus.Failed);
return; return;
} }
_steps = ESteps.Loading; _steps = ESteps.Loading;
} }
// 2. 加载场景 // 2. 加载场景
if (_steps == ESteps.Loading) if (_steps == ESteps.Loading)
{ {
// 注意如果场景不存在则返回NULL // 注意如果场景不存在则返回NULL
_asyncOperation = SceneManager.LoadSceneAsync(MainAssetInfo.AssetPath, SceneMode); _asyncOperation = SceneManager.LoadSceneAsync(MainAssetInfo.AssetPath, SceneMode);
if (_asyncOperation != null) if (_asyncOperation != null)
{ {
_asyncOperation.allowSceneActivation = !_suspendLoad; _asyncOperation.allowSceneActivation = !_suspendLoad;
_asyncOperation.priority = 100; _asyncOperation.priority = 100;
SceneObject = SceneManager.GetSceneAt(SceneManager.sceneCount - 1); SceneObject = SceneManager.GetSceneAt(SceneManager.sceneCount - 1);
_steps = ESteps.Checking; _steps = ESteps.Checking;
} }
else else
{ {
string error = $"Failed to load scene : {MainAssetInfo.AssetPath}"; string error = $"Failed to load scene : {MainAssetInfo.AssetPath}";
YooLogger.Error(error); YooLogger.Error(error);
InvokeCompletion(error, EOperationStatus.Failed); InvokeCompletion(error, EOperationStatus.Failed);
} }
} }
// 3. 检测加载结果 // 3. 检测加载结果
if (_steps == ESteps.Checking) if (_steps == ESteps.Checking)
{ {
Progress = _asyncOperation.progress; Progress = _asyncOperation.progress;
if (_asyncOperation.isDone) if (_asyncOperation.isDone)
{ {
if (SceneObject.IsValid()) if (SceneObject.IsValid())
{ {
InvokeCompletion(string.Empty, EOperationStatus.Succeed); InvokeCompletion(string.Empty, EOperationStatus.Succeed);
} }
else else
{ {
string error = $"The load scene is invalid : {MainAssetInfo.AssetPath}"; string error = $"The load scene is invalid : {MainAssetInfo.AssetPath}";
YooLogger.Error(error); YooLogger.Error(error);
InvokeCompletion(error, EOperationStatus.Failed); InvokeCompletion(error, EOperationStatus.Failed);
} }
} }
} }
} }
/// <summary> /// <summary>
/// 解除场景加载挂起操作 /// 解除场景加载挂起操作
/// </summary> /// </summary>
public bool UnSuspendLoad() public bool UnSuspendLoad()
{ {
if (_asyncOperation == null) if (_asyncOperation == null)
return false; return false;
_asyncOperation.allowSceneActivation = true; _asyncOperation.allowSceneActivation = true;
return true; return true;
} }
} }
} }

View File

@ -4,119 +4,119 @@ using UnityEngine;
namespace YooAsset namespace YooAsset
{ {
internal sealed class BundledSubAssetsProvider : ProviderBase internal sealed class BundledSubAssetsProvider : ProviderBase
{ {
private AssetBundleRequest _cacheRequest; private AssetBundleRequest _cacheRequest;
public BundledSubAssetsProvider(ResourceManager manager, string providerGUID, AssetInfo assetInfo) : base(manager, providerGUID, assetInfo) public BundledSubAssetsProvider(ResourceManager manager, string providerGUID, AssetInfo assetInfo) : base(manager, providerGUID, assetInfo)
{ {
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
DebugBeginRecording(); DebugBeginRecording();
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
if (IsDone) if (IsDone)
return; return;
if (_steps == ESteps.None) if (_steps == ESteps.None)
{ {
_steps = ESteps.CheckBundle; _steps = ESteps.CheckBundle;
} }
// 1. 检测资源包 // 1. 检测资源包
if (_steps == ESteps.CheckBundle) if (_steps == ESteps.CheckBundle)
{ {
if (IsWaitForAsyncComplete) if (IsWaitForAsyncComplete)
{ {
DependBundles.WaitForAsyncComplete(); DependBundles.WaitForAsyncComplete();
OwnerBundle.WaitForAsyncComplete(); OwnerBundle.WaitForAsyncComplete();
} }
if (DependBundles.IsDone() == false) if (DependBundles.IsDone() == false)
return; return;
if (OwnerBundle.IsDone() == false) if (OwnerBundle.IsDone() == false)
return; return;
if (DependBundles.IsSucceed() == false) if (DependBundles.IsSucceed() == false)
{ {
string error = DependBundles.GetLastError(); string error = DependBundles.GetLastError();
InvokeCompletion(error, EOperationStatus.Failed); InvokeCompletion(error, EOperationStatus.Failed);
return; return;
} }
if (OwnerBundle.Status != BundleLoaderBase.EStatus.Succeed) if (OwnerBundle.Status != BundleLoaderBase.EStatus.Succeed)
{ {
string error = OwnerBundle.LastError; string error = OwnerBundle.LastError;
InvokeCompletion(error, EOperationStatus.Failed); InvokeCompletion(error, EOperationStatus.Failed);
return; return;
} }
if (OwnerBundle.CacheBundle == null) if (OwnerBundle.CacheBundle == null)
{ {
ProcessCacheBundleException(); ProcessCacheBundleException();
return; return;
} }
_steps = ESteps.Loading; _steps = ESteps.Loading;
} }
// 2. 加载资源对象 // 2. 加载资源对象
if (_steps == ESteps.Loading) if (_steps == ESteps.Loading)
{ {
if (IsWaitForAsyncComplete || IsForceDestroyComplete) if (IsWaitForAsyncComplete || IsForceDestroyComplete)
{ {
if (MainAssetInfo.AssetType == null) if (MainAssetInfo.AssetType == null)
AllAssetObjects = OwnerBundle.CacheBundle.LoadAssetWithSubAssets(MainAssetInfo.AssetPath); AllAssetObjects = OwnerBundle.CacheBundle.LoadAssetWithSubAssets(MainAssetInfo.AssetPath);
else else
AllAssetObjects = OwnerBundle.CacheBundle.LoadAssetWithSubAssets(MainAssetInfo.AssetPath, MainAssetInfo.AssetType); AllAssetObjects = OwnerBundle.CacheBundle.LoadAssetWithSubAssets(MainAssetInfo.AssetPath, MainAssetInfo.AssetType);
} }
else else
{ {
if (MainAssetInfo.AssetType == null) if (MainAssetInfo.AssetType == null)
_cacheRequest = OwnerBundle.CacheBundle.LoadAssetWithSubAssetsAsync(MainAssetInfo.AssetPath); _cacheRequest = OwnerBundle.CacheBundle.LoadAssetWithSubAssetsAsync(MainAssetInfo.AssetPath);
else else
_cacheRequest = OwnerBundle.CacheBundle.LoadAssetWithSubAssetsAsync(MainAssetInfo.AssetPath, MainAssetInfo.AssetType); _cacheRequest = OwnerBundle.CacheBundle.LoadAssetWithSubAssetsAsync(MainAssetInfo.AssetPath, MainAssetInfo.AssetType);
} }
_steps = ESteps.Checking; _steps = ESteps.Checking;
} }
// 3. 检测加载结果 // 3. 检测加载结果
if (_steps == ESteps.Checking) if (_steps == ESteps.Checking)
{ {
if (_cacheRequest != null) if (_cacheRequest != null)
{ {
if (IsWaitForAsyncComplete || IsForceDestroyComplete) if (IsWaitForAsyncComplete || IsForceDestroyComplete)
{ {
// 强制挂起主线程(注意:该操作会很耗时) // 强制挂起主线程(注意:该操作会很耗时)
YooLogger.Warning("Suspend the main thread to load unity asset."); YooLogger.Warning("Suspend the main thread to load unity asset.");
AllAssetObjects = _cacheRequest.allAssets; AllAssetObjects = _cacheRequest.allAssets;
} }
else else
{ {
Progress = _cacheRequest.progress; Progress = _cacheRequest.progress;
if (_cacheRequest.isDone == false) if (_cacheRequest.isDone == false)
return; return;
AllAssetObjects = _cacheRequest.allAssets; AllAssetObjects = _cacheRequest.allAssets;
} }
} }
if (AllAssetObjects == null) if (AllAssetObjects == null)
{ {
string error; string error;
if (MainAssetInfo.AssetType == null) if (MainAssetInfo.AssetType == null)
error = $"Failed to load sub assets : {MainAssetInfo.AssetPath} AssetType : null AssetBundle : {OwnerBundle.MainBundleInfo.Bundle.BundleName}"; error = $"Failed to load sub assets : {MainAssetInfo.AssetPath} AssetType : null AssetBundle : {OwnerBundle.MainBundleInfo.Bundle.BundleName}";
else else
error = $"Failed to load sub assets : {MainAssetInfo.AssetPath} AssetType : {MainAssetInfo.AssetType} AssetBundle : {OwnerBundle.MainBundleInfo.Bundle.BundleName}"; error = $"Failed to load sub assets : {MainAssetInfo.AssetPath} AssetType : {MainAssetInfo.AssetType} AssetBundle : {OwnerBundle.MainBundleInfo.Bundle.BundleName}";
YooLogger.Error(error); YooLogger.Error(error);
InvokeCompletion(error, EOperationStatus.Failed); InvokeCompletion(error, EOperationStatus.Failed);
} }
else else
{ {
InvokeCompletion(string.Empty, EOperationStatus.Succeed); InvokeCompletion(string.Empty, EOperationStatus.Succeed);
} }
} }
} }
} }
} }

View File

@ -1,25 +1,25 @@
 
namespace YooAsset namespace YooAsset
{ {
internal sealed class CompletedProvider : ProviderBase internal sealed class CompletedProvider : ProviderBase
{ {
public CompletedProvider(AssetInfo assetInfo) : base(null, string.Empty, assetInfo) public CompletedProvider(AssetInfo assetInfo) : base(null, string.Empty, assetInfo)
{ {
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
} }
public void SetCompleted(string error) public void SetCompleted(string error)
{ {
if (_steps == ESteps.None) if (_steps == ESteps.None)
{ {
InvokeCompletion(error, EOperationStatus.Failed); InvokeCompletion(error, EOperationStatus.Failed);
} }
} }
} }
} }

View File

@ -4,108 +4,108 @@ using UnityEngine;
namespace YooAsset namespace YooAsset
{ {
internal sealed class DatabaseAllAssetsProvider : ProviderBase internal sealed class DatabaseAllAssetsProvider : ProviderBase
{ {
public DatabaseAllAssetsProvider(ResourceManager manager, string providerGUID, AssetInfo assetInfo) : base(manager, providerGUID, assetInfo) public DatabaseAllAssetsProvider(ResourceManager manager, string providerGUID, AssetInfo assetInfo) : base(manager, providerGUID, assetInfo)
{ {
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
DebugBeginRecording(); DebugBeginRecording();
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
#if UNITY_EDITOR #if UNITY_EDITOR
if (IsDone) if (IsDone)
return; return;
if (_steps == ESteps.None) if (_steps == ESteps.None)
{ {
// 检测资源文件是否存在 // 检测资源文件是否存在
string guid = UnityEditor.AssetDatabase.AssetPathToGUID(MainAssetInfo.AssetPath); string guid = UnityEditor.AssetDatabase.AssetPathToGUID(MainAssetInfo.AssetPath);
if (string.IsNullOrEmpty(guid)) if (string.IsNullOrEmpty(guid))
{ {
string error = $"Not found asset : {MainAssetInfo.AssetPath}"; string error = $"Not found asset : {MainAssetInfo.AssetPath}";
YooLogger.Error(error); YooLogger.Error(error);
InvokeCompletion(error, EOperationStatus.Failed); InvokeCompletion(error, EOperationStatus.Failed);
return; return;
} }
_steps = ESteps.CheckBundle; _steps = ESteps.CheckBundle;
// 注意:模拟异步加载效果提前返回 // 注意:模拟异步加载效果提前返回
if (IsWaitForAsyncComplete == false) if (IsWaitForAsyncComplete == false)
return; return;
} }
// 1. 检测资源包 // 1. 检测资源包
if (_steps == ESteps.CheckBundle) if (_steps == ESteps.CheckBundle)
{ {
if (IsWaitForAsyncComplete) if (IsWaitForAsyncComplete)
{ {
OwnerBundle.WaitForAsyncComplete(); OwnerBundle.WaitForAsyncComplete();
} }
if (OwnerBundle.IsDone() == false) if (OwnerBundle.IsDone() == false)
return; return;
if (OwnerBundle.Status != BundleLoaderBase.EStatus.Succeed) if (OwnerBundle.Status != BundleLoaderBase.EStatus.Succeed)
{ {
string error = OwnerBundle.LastError; string error = OwnerBundle.LastError;
InvokeCompletion(error, EOperationStatus.Failed); InvokeCompletion(error, EOperationStatus.Failed);
return; return;
} }
_steps = ESteps.Loading; _steps = ESteps.Loading;
} }
// 2. 加载资源对象 // 2. 加载资源对象
if (_steps == ESteps.Loading) if (_steps == ESteps.Loading)
{ {
if (MainAssetInfo.AssetType == null) if (MainAssetInfo.AssetType == null)
{ {
List<UnityEngine.Object> result = new List<Object>(); List<UnityEngine.Object> result = new List<Object>();
foreach (var assetPath in OwnerBundle.MainBundleInfo.IncludeAssetsInEditor) foreach (var assetPath in OwnerBundle.MainBundleInfo.IncludeAssetsInEditor)
{ {
UnityEngine.Object mainAsset = UnityEditor.AssetDatabase.LoadMainAssetAtPath(assetPath); UnityEngine.Object mainAsset = UnityEditor.AssetDatabase.LoadMainAssetAtPath(assetPath);
if (mainAsset != null) if (mainAsset != null)
result.Add(mainAsset); result.Add(mainAsset);
} }
AllAssetObjects = result.ToArray(); AllAssetObjects = result.ToArray();
} }
else else
{ {
List<UnityEngine.Object> result = new List<Object>(); List<UnityEngine.Object> result = new List<Object>();
foreach (var assetPath in OwnerBundle.MainBundleInfo.IncludeAssetsInEditor) foreach (var assetPath in OwnerBundle.MainBundleInfo.IncludeAssetsInEditor)
{ {
UnityEngine.Object mainAsset = UnityEditor.AssetDatabase.LoadAssetAtPath(assetPath, MainAssetInfo.AssetType); UnityEngine.Object mainAsset = UnityEditor.AssetDatabase.LoadAssetAtPath(assetPath, MainAssetInfo.AssetType);
if (mainAsset != null) if (mainAsset != null)
result.Add(mainAsset); result.Add(mainAsset);
} }
AllAssetObjects = result.ToArray(); AllAssetObjects = result.ToArray();
} }
_steps = ESteps.Checking; _steps = ESteps.Checking;
} }
// 3. 检测加载结果 // 3. 检测加载结果
if (_steps == ESteps.Checking) if (_steps == ESteps.Checking)
{ {
if (AllAssetObjects == null) if (AllAssetObjects == null)
{ {
string error; string error;
if (MainAssetInfo.AssetType == null) if (MainAssetInfo.AssetType == null)
error = $"Failed to load all assets : {MainAssetInfo.AssetPath} AssetType : null"; error = $"Failed to load all assets : {MainAssetInfo.AssetPath} AssetType : null";
else else
error = $"Failed to load all assets : {MainAssetInfo.AssetPath} AssetType : {MainAssetInfo.AssetType}"; error = $"Failed to load all assets : {MainAssetInfo.AssetPath} AssetType : {MainAssetInfo.AssetType}";
YooLogger.Error(error); YooLogger.Error(error);
InvokeCompletion(error, EOperationStatus.Failed); InvokeCompletion(error, EOperationStatus.Failed);
} }
else else
{ {
InvokeCompletion(string.Empty, EOperationStatus.Succeed); InvokeCompletion(string.Empty, EOperationStatus.Succeed);
} }
} }
#endif #endif
} }
} }
} }

View File

@ -4,90 +4,90 @@ using UnityEngine;
namespace YooAsset namespace YooAsset
{ {
internal sealed class DatabaseAssetProvider : ProviderBase internal sealed class DatabaseAssetProvider : ProviderBase
{ {
public DatabaseAssetProvider(ResourceManager manager, string providerGUID, AssetInfo assetInfo) : base(manager, providerGUID, assetInfo) public DatabaseAssetProvider(ResourceManager manager, string providerGUID, AssetInfo assetInfo) : base(manager, providerGUID, assetInfo)
{ {
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
DebugBeginRecording(); DebugBeginRecording();
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
#if UNITY_EDITOR #if UNITY_EDITOR
if (IsDone) if (IsDone)
return; return;
if (_steps == ESteps.None) if (_steps == ESteps.None)
{ {
// 检测资源文件是否存在 // 检测资源文件是否存在
string guid = UnityEditor.AssetDatabase.AssetPathToGUID(MainAssetInfo.AssetPath); string guid = UnityEditor.AssetDatabase.AssetPathToGUID(MainAssetInfo.AssetPath);
if (string.IsNullOrEmpty(guid)) if (string.IsNullOrEmpty(guid))
{ {
string error = $"Not found asset : {MainAssetInfo.AssetPath}"; string error = $"Not found asset : {MainAssetInfo.AssetPath}";
YooLogger.Error(error); YooLogger.Error(error);
InvokeCompletion(error, EOperationStatus.Failed); InvokeCompletion(error, EOperationStatus.Failed);
return; return;
} }
_steps = ESteps.CheckBundle; _steps = ESteps.CheckBundle;
// 注意:模拟异步加载效果提前返回 // 注意:模拟异步加载效果提前返回
if (IsWaitForAsyncComplete == false) if (IsWaitForAsyncComplete == false)
return; return;
} }
// 1. 检测资源包 // 1. 检测资源包
if (_steps == ESteps.CheckBundle) if (_steps == ESteps.CheckBundle)
{ {
if (IsWaitForAsyncComplete) if (IsWaitForAsyncComplete)
{ {
OwnerBundle.WaitForAsyncComplete(); OwnerBundle.WaitForAsyncComplete();
} }
if (OwnerBundle.IsDone() == false) if (OwnerBundle.IsDone() == false)
return; return;
if (OwnerBundle.Status != BundleLoaderBase.EStatus.Succeed) if (OwnerBundle.Status != BundleLoaderBase.EStatus.Succeed)
{ {
string error = OwnerBundle.LastError; string error = OwnerBundle.LastError;
InvokeCompletion(error, EOperationStatus.Failed); InvokeCompletion(error, EOperationStatus.Failed);
return; return;
} }
_steps = ESteps.Loading; _steps = ESteps.Loading;
} }
// 2. 加载资源对象 // 2. 加载资源对象
if (_steps == ESteps.Loading) if (_steps == ESteps.Loading)
{ {
if (MainAssetInfo.AssetType == null) if (MainAssetInfo.AssetType == null)
AssetObject = UnityEditor.AssetDatabase.LoadMainAssetAtPath(MainAssetInfo.AssetPath); AssetObject = UnityEditor.AssetDatabase.LoadMainAssetAtPath(MainAssetInfo.AssetPath);
else else
AssetObject = UnityEditor.AssetDatabase.LoadAssetAtPath(MainAssetInfo.AssetPath, MainAssetInfo.AssetType); AssetObject = UnityEditor.AssetDatabase.LoadAssetAtPath(MainAssetInfo.AssetPath, MainAssetInfo.AssetType);
_steps = ESteps.Checking; _steps = ESteps.Checking;
} }
// 3. 检测加载结果 // 3. 检测加载结果
if (_steps == ESteps.Checking) if (_steps == ESteps.Checking)
{ {
if (AssetObject == null) if (AssetObject == null)
{ {
string error; string error;
if (MainAssetInfo.AssetType == null) if (MainAssetInfo.AssetType == null)
error = $"Failed to load asset object : {MainAssetInfo.AssetPath} AssetType : null"; error = $"Failed to load asset object : {MainAssetInfo.AssetPath} AssetType : null";
else else
error = $"Failed to load asset object : {MainAssetInfo.AssetPath} AssetType : {MainAssetInfo.AssetType}"; error = $"Failed to load asset object : {MainAssetInfo.AssetPath} AssetType : {MainAssetInfo.AssetType}";
YooLogger.Error(error); YooLogger.Error(error);
InvokeCompletion(error, EOperationStatus.Failed); InvokeCompletion(error, EOperationStatus.Failed);
} }
else else
{ {
InvokeCompletion(string.Empty, EOperationStatus.Succeed); InvokeCompletion(string.Empty, EOperationStatus.Succeed);
} }
} }
#endif #endif
} }
} }
} }

View File

@ -1,68 +1,68 @@
 
namespace YooAsset namespace YooAsset
{ {
internal class DatabaseRawFileProvider : ProviderBase internal class DatabaseRawFileProvider : ProviderBase
{ {
public DatabaseRawFileProvider(ResourceManager manager, string providerGUID, AssetInfo assetInfo) : base(manager, providerGUID, assetInfo) public DatabaseRawFileProvider(ResourceManager manager, string providerGUID, AssetInfo assetInfo) : base(manager, providerGUID, assetInfo)
{ {
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
DebugBeginRecording(); DebugBeginRecording();
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
#if UNITY_EDITOR #if UNITY_EDITOR
if (IsDone) if (IsDone)
return; return;
if (_steps == ESteps.None) if (_steps == ESteps.None)
{ {
// 检测资源文件是否存在 // 检测资源文件是否存在
string guid = UnityEditor.AssetDatabase.AssetPathToGUID(MainAssetInfo.AssetPath); string guid = UnityEditor.AssetDatabase.AssetPathToGUID(MainAssetInfo.AssetPath);
if (string.IsNullOrEmpty(guid)) if (string.IsNullOrEmpty(guid))
{ {
string error = $"Not found asset : {MainAssetInfo.AssetPath}"; string error = $"Not found asset : {MainAssetInfo.AssetPath}";
YooLogger.Error(error); YooLogger.Error(error);
InvokeCompletion(error, EOperationStatus.Failed); InvokeCompletion(error, EOperationStatus.Failed);
return; return;
} }
_steps = ESteps.CheckBundle; _steps = ESteps.CheckBundle;
// 注意:模拟异步加载效果提前返回 // 注意:模拟异步加载效果提前返回
if (IsWaitForAsyncComplete == false) if (IsWaitForAsyncComplete == false)
return; return;
} }
// 1. 检测资源包 // 1. 检测资源包
if (_steps == ESteps.CheckBundle) if (_steps == ESteps.CheckBundle)
{ {
if (IsWaitForAsyncComplete) if (IsWaitForAsyncComplete)
{ {
OwnerBundle.WaitForAsyncComplete(); OwnerBundle.WaitForAsyncComplete();
} }
if (OwnerBundle.IsDone() == false) if (OwnerBundle.IsDone() == false)
return; return;
if (OwnerBundle.Status != BundleLoaderBase.EStatus.Succeed) if (OwnerBundle.Status != BundleLoaderBase.EStatus.Succeed)
{ {
string error = OwnerBundle.LastError; string error = OwnerBundle.LastError;
InvokeCompletion(error, EOperationStatus.Failed); InvokeCompletion(error, EOperationStatus.Failed);
return; return;
} }
_steps = ESteps.Checking; _steps = ESteps.Checking;
} }
// 2. 检测加载结果 // 2. 检测加载结果
if (_steps == ESteps.Checking) if (_steps == ESteps.Checking)
{ {
RawFilePath = MainAssetInfo.AssetPath; RawFilePath = MainAssetInfo.AssetPath;
InvokeCompletion(string.Empty, EOperationStatus.Succeed); InvokeCompletion(string.Empty, EOperationStatus.Succeed);
} }
#endif #endif
} }
} }
} }

View File

@ -6,106 +6,106 @@ using UnityEngine.SceneManagement;
namespace YooAsset namespace YooAsset
{ {
internal sealed class DatabaseSceneProvider : ProviderBase internal sealed class DatabaseSceneProvider : ProviderBase
{ {
public readonly LoadSceneMode SceneMode; public readonly LoadSceneMode SceneMode;
private readonly bool _suspendLoad; private readonly bool _suspendLoad;
private AsyncOperation _asyncOperation; private AsyncOperation _asyncOperation;
public DatabaseSceneProvider(ResourceManager manager, string providerGUID, AssetInfo assetInfo, LoadSceneMode sceneMode, bool suspendLoad) : base(manager, providerGUID, assetInfo) public DatabaseSceneProvider(ResourceManager manager, string providerGUID, AssetInfo assetInfo, LoadSceneMode sceneMode, bool suspendLoad) : base(manager, providerGUID, assetInfo)
{ {
SceneMode = sceneMode; SceneMode = sceneMode;
SceneName = Path.GetFileNameWithoutExtension(assetInfo.AssetPath); SceneName = Path.GetFileNameWithoutExtension(assetInfo.AssetPath);
_suspendLoad = suspendLoad; _suspendLoad = suspendLoad;
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
DebugBeginRecording(); DebugBeginRecording();
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
#if UNITY_EDITOR #if UNITY_EDITOR
if (IsDone) if (IsDone)
return; return;
if (_steps == ESteps.None) if (_steps == ESteps.None)
{ {
_steps = ESteps.CheckBundle; _steps = ESteps.CheckBundle;
} }
// 1. 检测资源包 // 1. 检测资源包
if (_steps == ESteps.CheckBundle) if (_steps == ESteps.CheckBundle)
{ {
if (IsWaitForAsyncComplete) if (IsWaitForAsyncComplete)
{ {
OwnerBundle.WaitForAsyncComplete(); OwnerBundle.WaitForAsyncComplete();
} }
if (OwnerBundle.IsDone() == false) if (OwnerBundle.IsDone() == false)
return; return;
if (OwnerBundle.Status != BundleLoaderBase.EStatus.Succeed) if (OwnerBundle.Status != BundleLoaderBase.EStatus.Succeed)
{ {
string error = OwnerBundle.LastError; string error = OwnerBundle.LastError;
InvokeCompletion(error, EOperationStatus.Failed); InvokeCompletion(error, EOperationStatus.Failed);
return; return;
} }
_steps = ESteps.Loading; _steps = ESteps.Loading;
} }
// 2. 加载资源对象 // 2. 加载资源对象
if (_steps == ESteps.Loading) if (_steps == ESteps.Loading)
{ {
LoadSceneParameters loadSceneParameters = new LoadSceneParameters(); LoadSceneParameters loadSceneParameters = new LoadSceneParameters();
loadSceneParameters.loadSceneMode = SceneMode; loadSceneParameters.loadSceneMode = SceneMode;
_asyncOperation = UnityEditor.SceneManagement.EditorSceneManager.LoadSceneAsyncInPlayMode(MainAssetInfo.AssetPath, loadSceneParameters); _asyncOperation = UnityEditor.SceneManagement.EditorSceneManager.LoadSceneAsyncInPlayMode(MainAssetInfo.AssetPath, loadSceneParameters);
if (_asyncOperation != null) if (_asyncOperation != null)
{ {
_asyncOperation.allowSceneActivation = !_suspendLoad; _asyncOperation.allowSceneActivation = !_suspendLoad;
_asyncOperation.priority = 100; _asyncOperation.priority = 100;
SceneObject = SceneManager.GetSceneAt(SceneManager.sceneCount - 1); SceneObject = SceneManager.GetSceneAt(SceneManager.sceneCount - 1);
_steps = ESteps.Checking; _steps = ESteps.Checking;
} }
else else
{ {
string error = $"Failed to load scene : {MainAssetInfo.AssetPath}"; string error = $"Failed to load scene : {MainAssetInfo.AssetPath}";
YooLogger.Error(error); YooLogger.Error(error);
InvokeCompletion(error, EOperationStatus.Failed); InvokeCompletion(error, EOperationStatus.Failed);
} }
} }
// 3. 检测加载结果 // 3. 检测加载结果
if (_steps == ESteps.Checking) if (_steps == ESteps.Checking)
{ {
Progress = _asyncOperation.progress; Progress = _asyncOperation.progress;
if (_asyncOperation.isDone) if (_asyncOperation.isDone)
{ {
if (SceneObject.IsValid()) if (SceneObject.IsValid())
{ {
InvokeCompletion(string.Empty, EOperationStatus.Succeed); InvokeCompletion(string.Empty, EOperationStatus.Succeed);
} }
else else
{ {
string error = $"The loaded scene is invalid : {MainAssetInfo.AssetPath}"; string error = $"The loaded scene is invalid : {MainAssetInfo.AssetPath}";
YooLogger.Error(error); YooLogger.Error(error);
InvokeCompletion(error, EOperationStatus.Failed); InvokeCompletion(error, EOperationStatus.Failed);
} }
} }
} }
#endif #endif
} }
/// <summary> /// <summary>
/// 解除场景加载挂起操作 /// 解除场景加载挂起操作
/// </summary> /// </summary>
public bool UnSuspendLoad() public bool UnSuspendLoad()
{ {
if (_asyncOperation == null) if (_asyncOperation == null)
return false; return false;
_asyncOperation.allowSceneActivation = true; _asyncOperation.allowSceneActivation = true;
return true; return true;
} }
} }
} }

View File

@ -4,101 +4,101 @@ using UnityEngine;
namespace YooAsset namespace YooAsset
{ {
internal sealed class DatabaseSubAssetsProvider : ProviderBase internal sealed class DatabaseSubAssetsProvider : ProviderBase
{ {
public DatabaseSubAssetsProvider(ResourceManager manager, string providerGUID, AssetInfo assetInfo) : base(manager, providerGUID, assetInfo) public DatabaseSubAssetsProvider(ResourceManager manager, string providerGUID, AssetInfo assetInfo) : base(manager, providerGUID, assetInfo)
{ {
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
DebugBeginRecording(); DebugBeginRecording();
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
#if UNITY_EDITOR #if UNITY_EDITOR
if (IsDone) if (IsDone)
return; return;
if (_steps == ESteps.None) if (_steps == ESteps.None)
{ {
// 检测资源文件是否存在 // 检测资源文件是否存在
string guid = UnityEditor.AssetDatabase.AssetPathToGUID(MainAssetInfo.AssetPath); string guid = UnityEditor.AssetDatabase.AssetPathToGUID(MainAssetInfo.AssetPath);
if (string.IsNullOrEmpty(guid)) if (string.IsNullOrEmpty(guid))
{ {
string error = $"Not found asset : {MainAssetInfo.AssetPath}"; string error = $"Not found asset : {MainAssetInfo.AssetPath}";
YooLogger.Error(error); YooLogger.Error(error);
InvokeCompletion(error, EOperationStatus.Failed); InvokeCompletion(error, EOperationStatus.Failed);
return; return;
} }
_steps = ESteps.CheckBundle; _steps = ESteps.CheckBundle;
// 注意:模拟异步加载效果提前返回 // 注意:模拟异步加载效果提前返回
if (IsWaitForAsyncComplete == false) if (IsWaitForAsyncComplete == false)
return; return;
} }
// 1. 检测资源包 // 1. 检测资源包
if (_steps == ESteps.CheckBundle) if (_steps == ESteps.CheckBundle)
{ {
if (IsWaitForAsyncComplete) if (IsWaitForAsyncComplete)
{ {
OwnerBundle.WaitForAsyncComplete(); OwnerBundle.WaitForAsyncComplete();
} }
if (OwnerBundle.IsDone() == false) if (OwnerBundle.IsDone() == false)
return; return;
if (OwnerBundle.Status != BundleLoaderBase.EStatus.Succeed) if (OwnerBundle.Status != BundleLoaderBase.EStatus.Succeed)
{ {
string error = OwnerBundle.LastError; string error = OwnerBundle.LastError;
InvokeCompletion(error, EOperationStatus.Failed); InvokeCompletion(error, EOperationStatus.Failed);
return; return;
} }
_steps = ESteps.Loading; _steps = ESteps.Loading;
} }
// 2. 加载资源对象 // 2. 加载资源对象
if (_steps == ESteps.Loading) if (_steps == ESteps.Loading)
{ {
if (MainAssetInfo.AssetType == null) if (MainAssetInfo.AssetType == null)
{ {
AllAssetObjects = UnityEditor.AssetDatabase.LoadAllAssetRepresentationsAtPath(MainAssetInfo.AssetPath); AllAssetObjects = UnityEditor.AssetDatabase.LoadAllAssetRepresentationsAtPath(MainAssetInfo.AssetPath);
} }
else else
{ {
UnityEngine.Object[] findAssets = UnityEditor.AssetDatabase.LoadAllAssetRepresentationsAtPath(MainAssetInfo.AssetPath); UnityEngine.Object[] findAssets = UnityEditor.AssetDatabase.LoadAllAssetRepresentationsAtPath(MainAssetInfo.AssetPath);
List<UnityEngine.Object> result = new List<Object>(findAssets.Length); List<UnityEngine.Object> result = new List<Object>(findAssets.Length);
foreach (var findAsset in findAssets) foreach (var findAsset in findAssets)
{ {
if (MainAssetInfo.AssetType.IsAssignableFrom(findAsset.GetType())) if (MainAssetInfo.AssetType.IsAssignableFrom(findAsset.GetType()))
result.Add(findAsset); result.Add(findAsset);
} }
AllAssetObjects = result.ToArray(); AllAssetObjects = result.ToArray();
} }
_steps = ESteps.Checking; _steps = ESteps.Checking;
} }
// 3. 检测加载结果 // 3. 检测加载结果
if (_steps == ESteps.Checking) if (_steps == ESteps.Checking)
{ {
if (AllAssetObjects == null) if (AllAssetObjects == null)
{ {
string error; string error;
if (MainAssetInfo.AssetType == null) if (MainAssetInfo.AssetType == null)
error = $"Failed to load sub assets : {MainAssetInfo.AssetPath} AssetType : null"; error = $"Failed to load sub assets : {MainAssetInfo.AssetPath} AssetType : null";
else else
error = $"Failed to load sub assets : {MainAssetInfo.AssetPath} AssetType : {MainAssetInfo.AssetType}"; error = $"Failed to load sub assets : {MainAssetInfo.AssetPath} AssetType : {MainAssetInfo.AssetType}";
YooLogger.Error(error); YooLogger.Error(error);
InvokeCompletion(error, EOperationStatus.Failed); InvokeCompletion(error, EOperationStatus.Failed);
} }
else else
{ {
InvokeCompletion(string.Empty, EOperationStatus.Succeed); InvokeCompletion(string.Empty, EOperationStatus.Succeed);
} }
} }
#endif #endif
} }
} }
} }

View File

@ -6,339 +6,339 @@ using System;
namespace YooAsset namespace YooAsset
{ {
internal abstract class ProviderBase : AsyncOperationBase internal abstract class ProviderBase : AsyncOperationBase
{ {
protected enum ESteps protected enum ESteps
{ {
None = 0, None = 0,
CheckBundle, CheckBundle,
Loading, Loading,
Checking, Checking,
Done, Done,
} }
/// <summary> /// <summary>
/// 资源提供者唯一标识符 /// 资源提供者唯一标识符
/// </summary> /// </summary>
public string ProviderGUID { private set; get; } public string ProviderGUID { private set; get; }
/// <summary> /// <summary>
/// 所属资源系统 /// 所属资源系统
/// </summary> /// </summary>
public ResourceManager ResourceMgr { private set; get; } public ResourceManager ResourceMgr { private set; get; }
/// <summary> /// <summary>
/// 资源信息 /// 资源信息
/// </summary> /// </summary>
public AssetInfo MainAssetInfo { private set; get; } public AssetInfo MainAssetInfo { private set; get; }
/// <summary> /// <summary>
/// 获取的资源对象 /// 获取的资源对象
/// </summary> /// </summary>
public UnityEngine.Object AssetObject { protected set; get; } public UnityEngine.Object AssetObject { protected set; get; }
/// <summary> /// <summary>
/// 获取的资源对象集合 /// 获取的资源对象集合
/// </summary> /// </summary>
public UnityEngine.Object[] AllAssetObjects { protected set; get; } public UnityEngine.Object[] AllAssetObjects { protected set; get; }
/// <summary> /// <summary>
/// 获取的场景对象 /// 获取的场景对象
/// </summary> /// </summary>
public UnityEngine.SceneManagement.Scene SceneObject { protected set; get; } public UnityEngine.SceneManagement.Scene SceneObject { protected set; get; }
/// <summary> /// <summary>
/// 加载的场景名称 /// 加载的场景名称
/// </summary> /// </summary>
public string SceneName { protected set; get; } public string SceneName { protected set; get; }
/// <summary> /// <summary>
/// 原生文件路径 /// 原生文件路径
/// </summary> /// </summary>
public string RawFilePath { protected set; get; } public string RawFilePath { protected set; get; }
/// <summary> /// <summary>
/// 引用计数 /// 引用计数
/// </summary> /// </summary>
public int RefCount { private set; get; } = 0; public int RefCount { private set; get; } = 0;
/// <summary> /// <summary>
/// 是否已经销毁 /// 是否已经销毁
/// </summary> /// </summary>
public bool IsDestroyed { private set; get; } = false; public bool IsDestroyed { private set; get; } = false;
protected ESteps _steps = ESteps.None; protected ESteps _steps = ESteps.None;
protected BundleLoaderBase OwnerBundle { private set; get; } protected BundleLoaderBase OwnerBundle { private set; get; }
protected DependAssetBundles DependBundles { private set; get; } protected DependAssetBundles DependBundles { private set; get; }
protected bool IsWaitForAsyncComplete { private set; get; } = false; protected bool IsWaitForAsyncComplete { private set; get; } = false;
protected bool IsForceDestroyComplete { private set; get; } = false; protected bool IsForceDestroyComplete { private set; get; } = false;
private readonly List<HandleBase> _handles = new List<HandleBase>(); private readonly List<HandleBase> _handles = new List<HandleBase>();
public ProviderBase(ResourceManager manager, string providerGUID, AssetInfo assetInfo) public ProviderBase(ResourceManager manager, string providerGUID, AssetInfo assetInfo)
{ {
ResourceMgr = manager; ResourceMgr = manager;
ProviderGUID = providerGUID; ProviderGUID = providerGUID;
MainAssetInfo = assetInfo; MainAssetInfo = assetInfo;
// 创建资源包加载器 // 创建资源包加载器
if (manager != null) if (manager != null)
{ {
OwnerBundle = manager.CreateOwnerAssetBundleLoader(assetInfo); OwnerBundle = manager.CreateOwnerAssetBundleLoader(assetInfo);
OwnerBundle.Reference(); OwnerBundle.Reference();
OwnerBundle.AddProvider(this); OwnerBundle.AddProvider(this);
var dependList = manager.CreateDependAssetBundleLoaders(assetInfo); var dependList = manager.CreateDependAssetBundleLoaders(assetInfo);
DependBundles = new DependAssetBundles(dependList); DependBundles = new DependAssetBundles(dependList);
DependBundles.Reference(); DependBundles.Reference();
} }
} }
/// <summary> /// <summary>
/// 销毁资源提供者 /// 销毁资源提供者
/// </summary> /// </summary>
public void Destroy() public void Destroy()
{ {
IsDestroyed = true; IsDestroyed = true;
// 检测是否为正常销毁 // 检测是否为正常销毁
if (IsDone == false) if (IsDone == false)
{ {
Error = "User abort !"; Error = "User abort !";
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
} }
// 释放资源包加载器 // 释放资源包加载器
if (OwnerBundle != null) if (OwnerBundle != null)
{ {
OwnerBundle.Release(); OwnerBundle.Release();
OwnerBundle = null; OwnerBundle = null;
} }
if (DependBundles != null) if (DependBundles != null)
{ {
DependBundles.Release(); DependBundles.Release();
DependBundles = null; DependBundles = null;
} }
} }
/// <summary> /// <summary>
/// 是否可以销毁 /// 是否可以销毁
/// </summary> /// </summary>
public bool CanDestroy() public bool CanDestroy()
{ {
// 注意:在进行资源加载过程时不可以销毁 // 注意:在进行资源加载过程时不可以销毁
if (_steps == ESteps.Loading || _steps == ESteps.Checking) if (_steps == ESteps.Loading || _steps == ESteps.Checking)
return false; return false;
return RefCount <= 0; return RefCount <= 0;
} }
/// <summary> /// <summary>
/// 创建资源句柄 /// 创建资源句柄
/// </summary> /// </summary>
public T CreateHandle<T>() where T : HandleBase public T CreateHandle<T>() where T : HandleBase
{ {
// 引用计数增加 // 引用计数增加
RefCount++; RefCount++;
HandleBase handle; HandleBase handle;
if (typeof(T) == typeof(AssetHandle)) if (typeof(T) == typeof(AssetHandle))
handle = new AssetHandle(this); handle = new AssetHandle(this);
else if (typeof(T) == typeof(SceneHandle)) else if (typeof(T) == typeof(SceneHandle))
handle = new SceneHandle(this); handle = new SceneHandle(this);
else if (typeof(T) == typeof(SubAssetsHandle)) else if (typeof(T) == typeof(SubAssetsHandle))
handle = new SubAssetsHandle(this); handle = new SubAssetsHandle(this);
else if (typeof(T) == typeof(AllAssetsHandle)) else if (typeof(T) == typeof(AllAssetsHandle))
handle = new AllAssetsHandle(this); handle = new AllAssetsHandle(this);
else if (typeof(T) == typeof(RawFileHandle)) else if (typeof(T) == typeof(RawFileHandle))
handle = new RawFileHandle(this); handle = new RawFileHandle(this);
else else
throw new System.NotImplementedException(); throw new System.NotImplementedException();
_handles.Add(handle); _handles.Add(handle);
return handle as T; return handle as T;
} }
/// <summary> /// <summary>
/// 释放资源句柄 /// 释放资源句柄
/// </summary> /// </summary>
public void ReleaseHandle(HandleBase handle) public void ReleaseHandle(HandleBase handle)
{ {
if (RefCount <= 0) if (RefCount <= 0)
throw new System.Exception("Should never get here !"); throw new System.Exception("Should never get here !");
if (_handles.Remove(handle) == false) if (_handles.Remove(handle) == false)
throw new System.Exception("Should never get here !"); throw new System.Exception("Should never get here !");
// 引用计数减少 // 引用计数减少
RefCount--; RefCount--;
} }
/// <summary> /// <summary>
/// 释放所有资源句柄 /// 释放所有资源句柄
/// </summary> /// </summary>
public void ReleaseAllHandles() public void ReleaseAllHandles()
{ {
for (int i = _handles.Count - 1; i >= 0; i--) for (int i = _handles.Count - 1; i >= 0; i--)
{ {
var handle = _handles[i]; var handle = _handles[i];
handle.ReleaseInternal(); handle.ReleaseInternal();
} }
} }
/// <summary> /// <summary>
/// 等待异步执行完毕 /// 等待异步执行完毕
/// </summary> /// </summary>
public void WaitForAsyncComplete() public void WaitForAsyncComplete()
{ {
IsWaitForAsyncComplete = true; IsWaitForAsyncComplete = true;
// 注意:主动轮询更新完成同步加载 // 注意:主动轮询更新完成同步加载
InternalOnUpdate(); InternalOnUpdate();
// 验证结果 // 验证结果
if (IsDone == false) if (IsDone == false)
{ {
YooLogger.Warning($"{nameof(WaitForAsyncComplete)} failed to loading : {MainAssetInfo.AssetPath}"); YooLogger.Warning($"{nameof(WaitForAsyncComplete)} failed to loading : {MainAssetInfo.AssetPath}");
} }
} }
/// <summary> /// <summary>
/// 强制销毁资源提供者 /// 强制销毁资源提供者
/// </summary> /// </summary>
public void ForceDestroyComplete() public void ForceDestroyComplete()
{ {
IsForceDestroyComplete = true; IsForceDestroyComplete = true;
// 注意:主动轮询更新完成同步加载 // 注意:主动轮询更新完成同步加载
// 说明:如果资源包未准备完毕也可以放心销毁。 // 说明:如果资源包未准备完毕也可以放心销毁。
InternalOnUpdate(); InternalOnUpdate();
} }
/// <summary> /// <summary>
/// 处理特殊异常 /// 处理特殊异常
/// </summary> /// </summary>
protected void ProcessCacheBundleException() protected void ProcessCacheBundleException()
{ {
if (OwnerBundle.IsDestroyed) if (OwnerBundle.IsDestroyed)
throw new System.Exception("Should never get here !"); throw new System.Exception("Should never get here !");
string error = $"The bundle {OwnerBundle.MainBundleInfo.Bundle.BundleName} has been destroyed by unity bugs !"; string error = $"The bundle {OwnerBundle.MainBundleInfo.Bundle.BundleName} has been destroyed by unity bugs !";
YooLogger.Error(error); YooLogger.Error(error);
InvokeCompletion(Error, EOperationStatus.Failed); InvokeCompletion(Error, EOperationStatus.Failed);
} }
/// <summary> /// <summary>
/// 结束流程 /// 结束流程
/// </summary> /// </summary>
protected void InvokeCompletion(string error, EOperationStatus status) protected void InvokeCompletion(string error, EOperationStatus status)
{ {
DebugEndRecording(); DebugEndRecording();
_steps = ESteps.Done; _steps = ESteps.Done;
Error = error; Error = error;
Status = status; Status = status;
// 注意:创建临时列表是为了防止外部逻辑在回调函数内创建或者释放资源句柄。 // 注意:创建临时列表是为了防止外部逻辑在回调函数内创建或者释放资源句柄。
// 注意:回调方法如果发生异常,会阻断列表里的后续回调方法! // 注意:回调方法如果发生异常,会阻断列表里的后续回调方法!
List<HandleBase> tempers = new List<HandleBase>(_handles); List<HandleBase> tempers = new List<HandleBase>(_handles);
foreach (var hande in tempers) foreach (var hande in tempers)
{ {
if (hande.IsValid) if (hande.IsValid)
{ {
hande.InvokeCallback(); hande.InvokeCallback();
} }
} }
} }
#region 调试信息相关 #region 调试信息相关
/// <summary> /// <summary>
/// 出生的场景 /// 出生的场景
/// </summary> /// </summary>
public string SpawnScene = string.Empty; public string SpawnScene = string.Empty;
/// <summary> /// <summary>
/// 出生的时间 /// 出生的时间
/// </summary> /// </summary>
public string SpawnTime = string.Empty; public string SpawnTime = string.Empty;
/// <summary> /// <summary>
/// 加载耗时(单位:毫秒) /// 加载耗时(单位:毫秒)
/// </summary> /// </summary>
public long LoadingTime { protected set; get; } public long LoadingTime { protected set; get; }
// 加载耗时统计 // 加载耗时统计
private Stopwatch _watch = null; private Stopwatch _watch = null;
[Conditional("DEBUG")] [Conditional("DEBUG")]
public void InitSpawnDebugInfo() public void InitSpawnDebugInfo()
{ {
SpawnScene = UnityEngine.SceneManagement.SceneManager.GetActiveScene().name; ; SpawnScene = UnityEngine.SceneManagement.SceneManager.GetActiveScene().name; ;
SpawnTime = SpawnTimeToString(UnityEngine.Time.realtimeSinceStartup); SpawnTime = SpawnTimeToString(UnityEngine.Time.realtimeSinceStartup);
} }
private string SpawnTimeToString(float spawnTime) private string SpawnTimeToString(float spawnTime)
{ {
float h = UnityEngine.Mathf.FloorToInt(spawnTime / 3600f); float h = UnityEngine.Mathf.FloorToInt(spawnTime / 3600f);
float m = UnityEngine.Mathf.FloorToInt(spawnTime / 60f - h * 60f); float m = UnityEngine.Mathf.FloorToInt(spawnTime / 60f - h * 60f);
float s = UnityEngine.Mathf.FloorToInt(spawnTime - m * 60f - h * 3600f); float s = UnityEngine.Mathf.FloorToInt(spawnTime - m * 60f - h * 3600f);
return h.ToString("00") + ":" + m.ToString("00") + ":" + s.ToString("00"); return h.ToString("00") + ":" + m.ToString("00") + ":" + s.ToString("00");
} }
[Conditional("DEBUG")] [Conditional("DEBUG")]
protected void DebugBeginRecording() protected void DebugBeginRecording()
{ {
if (_watch == null) if (_watch == null)
{ {
_watch = Stopwatch.StartNew(); _watch = Stopwatch.StartNew();
} }
} }
[Conditional("DEBUG")] [Conditional("DEBUG")]
private void DebugEndRecording() private void DebugEndRecording()
{ {
if (_watch != null) if (_watch != null)
{ {
LoadingTime = _watch.ElapsedMilliseconds; LoadingTime = _watch.ElapsedMilliseconds;
_watch = null; _watch = null;
} }
} }
/// <summary> /// <summary>
/// 获取下载报告 /// 获取下载报告
/// </summary> /// </summary>
internal DownloadStatus GetDownloadStatus() internal DownloadStatus GetDownloadStatus()
{ {
DownloadStatus status = new DownloadStatus(); DownloadStatus status = new DownloadStatus();
status.TotalBytes = (ulong)OwnerBundle.MainBundleInfo.Bundle.FileSize; status.TotalBytes = (ulong)OwnerBundle.MainBundleInfo.Bundle.FileSize;
status.DownloadedBytes = OwnerBundle.DownloadedBytes; status.DownloadedBytes = OwnerBundle.DownloadedBytes;
foreach (var dependBundle in DependBundles.DependList) foreach (var dependBundle in DependBundles.DependList)
{ {
status.TotalBytes += (ulong)dependBundle.MainBundleInfo.Bundle.FileSize; status.TotalBytes += (ulong)dependBundle.MainBundleInfo.Bundle.FileSize;
status.DownloadedBytes += dependBundle.DownloadedBytes; status.DownloadedBytes += dependBundle.DownloadedBytes;
} }
if (status.TotalBytes == 0) if (status.TotalBytes == 0)
throw new System.Exception("Should never get here !"); throw new System.Exception("Should never get here !");
status.IsDone = status.DownloadedBytes == status.TotalBytes; status.IsDone = status.DownloadedBytes == status.TotalBytes;
status.Progress = (float)status.DownloadedBytes / status.TotalBytes; status.Progress = (float)status.DownloadedBytes / status.TotalBytes;
return status; return status;
} }
/// <summary> /// <summary>
/// 获取资源包的调试信息列表 /// 获取资源包的调试信息列表
/// </summary> /// </summary>
internal void GetBundleDebugInfos(List<DebugBundleInfo> output) internal void GetBundleDebugInfos(List<DebugBundleInfo> output)
{ {
var bundleInfo = new DebugBundleInfo(); var bundleInfo = new DebugBundleInfo();
bundleInfo.BundleName = OwnerBundle.MainBundleInfo.Bundle.BundleName; bundleInfo.BundleName = OwnerBundle.MainBundleInfo.Bundle.BundleName;
bundleInfo.RefCount = OwnerBundle.RefCount; bundleInfo.RefCount = OwnerBundle.RefCount;
bundleInfo.Status = OwnerBundle.Status.ToString(); bundleInfo.Status = OwnerBundle.Status.ToString();
output.Add(bundleInfo); output.Add(bundleInfo);
DependBundles.GetBundleDebugInfos(output); DependBundles.GetBundleDebugInfos(output);
} }
#endregion #endregion
} }
} }

View File

@ -3,101 +3,101 @@ using UnityEngine;
namespace YooAsset namespace YooAsset
{ {
internal class ResourceLoader internal class ResourceLoader
{ {
private IDecryptionServices _decryption; private IDecryptionServices _decryption;
private IDeliveryLoadServices _delivery; private IDeliveryLoadServices _delivery;
public void Init(IDecryptionServices decryption, IDeliveryLoadServices delivery) public void Init(IDecryptionServices decryption, IDeliveryLoadServices delivery)
{ {
_decryption = decryption; _decryption = decryption;
_delivery = delivery; _delivery = delivery;
} }
/// <summary> /// <summary>
/// 同步加载资源包对象 /// 同步加载资源包对象
/// </summary> /// </summary>
public AssetBundle LoadAssetBundle(BundleInfo bundleInfo, string fileLoadPath, out Stream managedStream) public AssetBundle LoadAssetBundle(BundleInfo bundleInfo, string fileLoadPath, out Stream managedStream)
{ {
managedStream = null; managedStream = null;
if (bundleInfo.Bundle.Encrypted) if (bundleInfo.Bundle.Encrypted)
{ {
if (_decryption == null) if (_decryption == null)
{ {
YooLogger.Error($"{nameof(IDecryptionServices)} is null ! when load asset bundle {bundleInfo.Bundle.BundleName}!"); YooLogger.Error($"{nameof(IDecryptionServices)} is null ! when load asset bundle {bundleInfo.Bundle.BundleName}!");
return null; return null;
} }
DecryptFileInfo fileInfo = new DecryptFileInfo(); DecryptFileInfo fileInfo = new DecryptFileInfo();
fileInfo.BundleName = bundleInfo.Bundle.BundleName; fileInfo.BundleName = bundleInfo.Bundle.BundleName;
fileInfo.FileLoadPath = fileLoadPath; fileInfo.FileLoadPath = fileLoadPath;
fileInfo.ConentCRC = bundleInfo.Bundle.UnityCRC; fileInfo.ConentCRC = bundleInfo.Bundle.UnityCRC;
return _decryption.LoadAssetBundle(fileInfo, out managedStream); return _decryption.LoadAssetBundle(fileInfo, out managedStream);
} }
else else
{ {
return AssetBundle.LoadFromFile(fileLoadPath); return AssetBundle.LoadFromFile(fileLoadPath);
} }
} }
/// <summary> /// <summary>
/// 异步加载资源包对象 /// 异步加载资源包对象
/// </summary> /// </summary>
public AssetBundleCreateRequest LoadAssetBundleAsync(BundleInfo bundleInfo, string fileLoadPath, out Stream managedStream) public AssetBundleCreateRequest LoadAssetBundleAsync(BundleInfo bundleInfo, string fileLoadPath, out Stream managedStream)
{ {
managedStream = null; managedStream = null;
if (bundleInfo.Bundle.Encrypted) if (bundleInfo.Bundle.Encrypted)
{ {
if (_decryption == null) if (_decryption == null)
{ {
YooLogger.Error($"{nameof(IDecryptionServices)} is null ! when load asset bundle {bundleInfo.Bundle.BundleName}!"); YooLogger.Error($"{nameof(IDecryptionServices)} is null ! when load asset bundle {bundleInfo.Bundle.BundleName}!");
return null; return null;
} }
DecryptFileInfo fileInfo = new DecryptFileInfo(); DecryptFileInfo fileInfo = new DecryptFileInfo();
fileInfo.BundleName = bundleInfo.Bundle.BundleName; fileInfo.BundleName = bundleInfo.Bundle.BundleName;
fileInfo.FileLoadPath = fileLoadPath; fileInfo.FileLoadPath = fileLoadPath;
fileInfo.ConentCRC = bundleInfo.Bundle.UnityCRC; fileInfo.ConentCRC = bundleInfo.Bundle.UnityCRC;
return _decryption.LoadAssetBundleAsync(fileInfo, out managedStream); return _decryption.LoadAssetBundleAsync(fileInfo, out managedStream);
} }
else else
{ {
return AssetBundle.LoadFromFileAsync(fileLoadPath); return AssetBundle.LoadFromFileAsync(fileLoadPath);
} }
} }
/// <summary> /// <summary>
/// 同步加载分发的资源包对象 /// 同步加载分发的资源包对象
/// </summary> /// </summary>
public AssetBundle LoadDeliveryAssetBundle(BundleInfo bundleInfo, string fileLoadPath) public AssetBundle LoadDeliveryAssetBundle(BundleInfo bundleInfo, string fileLoadPath)
{ {
if (_delivery == null) if (_delivery == null)
throw new System.Exception("Should never get here !"); throw new System.Exception("Should never get here !");
// 注意:对于已经加密的资源包,需要开发者自行解密。 // 注意:对于已经加密的资源包,需要开发者自行解密。
DeliveryFileInfo fileInfo = new DeliveryFileInfo(); DeliveryFileInfo fileInfo = new DeliveryFileInfo();
fileInfo.BundleName = bundleInfo.Bundle.BundleName; fileInfo.BundleName = bundleInfo.Bundle.BundleName;
fileInfo.FileLoadPath = fileLoadPath; fileInfo.FileLoadPath = fileLoadPath;
fileInfo.ConentCRC = bundleInfo.Bundle.UnityCRC; fileInfo.ConentCRC = bundleInfo.Bundle.UnityCRC;
fileInfo.Encrypted = bundleInfo.Bundle.Encrypted; fileInfo.Encrypted = bundleInfo.Bundle.Encrypted;
return _delivery.LoadAssetBundle(fileInfo); return _delivery.LoadAssetBundle(fileInfo);
} }
/// <summary> /// <summary>
/// 异步加载分发的资源包对象 /// 异步加载分发的资源包对象
/// </summary> /// </summary>
public AssetBundleCreateRequest LoadDeliveryAssetBundleAsync(BundleInfo bundleInfo, string fileLoadPath) public AssetBundleCreateRequest LoadDeliveryAssetBundleAsync(BundleInfo bundleInfo, string fileLoadPath)
{ {
if (_delivery == null) if (_delivery == null)
throw new System.Exception("Should never get here !"); throw new System.Exception("Should never get here !");
// 注意:对于已经加密的资源包,需要开发者自行解密。 // 注意:对于已经加密的资源包,需要开发者自行解密。
DeliveryFileInfo fileInfo = new DeliveryFileInfo(); DeliveryFileInfo fileInfo = new DeliveryFileInfo();
fileInfo.BundleName = bundleInfo.Bundle.BundleName; fileInfo.BundleName = bundleInfo.Bundle.BundleName;
fileInfo.FileLoadPath = fileLoadPath; fileInfo.FileLoadPath = fileLoadPath;
fileInfo.ConentCRC = bundleInfo.Bundle.UnityCRC; fileInfo.ConentCRC = bundleInfo.Bundle.UnityCRC;
fileInfo.Encrypted = bundleInfo.Bundle.Encrypted; fileInfo.Encrypted = bundleInfo.Bundle.Encrypted;
return _delivery.LoadAssetBundleAsync(fileInfo); return _delivery.LoadAssetBundleAsync(fileInfo);
} }
} }
} }

View File

@ -7,478 +7,478 @@ using UnityEngine.SceneManagement;
namespace YooAsset namespace YooAsset
{ {
internal class ResourceManager internal class ResourceManager
{ {
// 全局场景句柄集合 // 全局场景句柄集合
private readonly static Dictionary<string, SceneHandle> _sceneHandles = new Dictionary<string, SceneHandle>(100); private readonly static Dictionary<string, SceneHandle> _sceneHandles = new Dictionary<string, SceneHandle>(100);
private static long _sceneCreateCount = 0; private static long _sceneCreateCount = 0;
private readonly Dictionary<string, ProviderBase> _providerDic = new Dictionary<string, ProviderBase>(5000); private readonly Dictionary<string, ProviderBase> _providerDic = new Dictionary<string, ProviderBase>(5000);
private readonly Dictionary<string, BundleLoaderBase> _loaderDic = new Dictionary<string, BundleLoaderBase>(5000); private readonly Dictionary<string, BundleLoaderBase> _loaderDic = new Dictionary<string, BundleLoaderBase>(5000);
private readonly List<BundleLoaderBase> _loaderList = new List<BundleLoaderBase>(5000); private readonly List<BundleLoaderBase> _loaderList = new List<BundleLoaderBase>(5000);
private bool _simulationOnEditor; private bool _simulationOnEditor;
private bool _autoDestroyAssetProvider; private bool _autoDestroyAssetProvider;
private IBundleQuery _bundleQuery; private IBundleQuery _bundleQuery;
/// <summary> /// <summary>
/// 所属包裹 /// 所属包裹
/// </summary> /// </summary>
public readonly string PackageName; public readonly string PackageName;
public ResourceManager(string packageName) public ResourceManager(string packageName)
{ {
PackageName = packageName; PackageName = packageName;
} }
/// <summary> /// <summary>
/// 初始化 /// 初始化
/// </summary> /// </summary>
public void Initialize(bool simulationOnEditor, bool autoDestroyAssetProvider, IBundleQuery bundleServices) public void Initialize(bool simulationOnEditor, bool autoDestroyAssetProvider, IBundleQuery bundleServices)
{ {
_simulationOnEditor = simulationOnEditor; _simulationOnEditor = simulationOnEditor;
_autoDestroyAssetProvider = autoDestroyAssetProvider; _autoDestroyAssetProvider = autoDestroyAssetProvider;
_bundleQuery = bundleServices; _bundleQuery = bundleServices;
} }
/// <summary> /// <summary>
/// 更新 /// 更新
/// </summary> /// </summary>
public void Update() public void Update()
{ {
foreach (var loader in _loaderList) foreach (var loader in _loaderList)
{ {
loader.Update(); loader.Update();
if (_autoDestroyAssetProvider) if (_autoDestroyAssetProvider)
loader.TryDestroyProviders(); loader.TryDestroyProviders();
} }
} }
/// <summary> /// <summary>
/// 资源回收(卸载引用计数为零的资源) /// 资源回收(卸载引用计数为零的资源)
/// </summary> /// </summary>
public void UnloadUnusedAssets() public void UnloadUnusedAssets()
{ {
for (int i = _loaderList.Count - 1; i >= 0; i--) for (int i = _loaderList.Count - 1; i >= 0; i--)
{ {
BundleLoaderBase loader = _loaderList[i]; BundleLoaderBase loader = _loaderList[i];
loader.TryDestroyProviders(); loader.TryDestroyProviders();
} }
for (int i = _loaderList.Count - 1; i >= 0; i--) for (int i = _loaderList.Count - 1; i >= 0; i--)
{ {
BundleLoaderBase loader = _loaderList[i]; BundleLoaderBase loader = _loaderList[i];
if (loader.CanDestroy()) if (loader.CanDestroy())
{ {
string bundleName = loader.MainBundleInfo.Bundle.BundleName; string bundleName = loader.MainBundleInfo.Bundle.BundleName;
loader.Destroy(); loader.Destroy();
_loaderList.RemoveAt(i); _loaderList.RemoveAt(i);
_loaderDic.Remove(bundleName); _loaderDic.Remove(bundleName);
} }
} }
} }
/// <summary> /// <summary>
/// 尝试卸载指定资源的资源包(包括依赖资源) /// 尝试卸载指定资源的资源包(包括依赖资源)
/// </summary> /// </summary>
public void TryUnloadUnusedAsset(AssetInfo assetInfo) public void TryUnloadUnusedAsset(AssetInfo assetInfo)
{ {
if (assetInfo.IsInvalid) if (assetInfo.IsInvalid)
{ {
YooLogger.Error($"Failed to unload asset ! {assetInfo.Error}"); YooLogger.Error($"Failed to unload asset ! {assetInfo.Error}");
return; return;
} }
// 卸载主资源包加载器 // 卸载主资源包加载器
string manBundleName = _bundleQuery.GetMainBundleName(assetInfo); string manBundleName = _bundleQuery.GetMainBundleName(assetInfo);
var mainLoader = TryGetAssetBundleLoader(manBundleName); var mainLoader = TryGetAssetBundleLoader(manBundleName);
if (mainLoader != null) if (mainLoader != null)
{ {
mainLoader.TryDestroyProviders(); mainLoader.TryDestroyProviders();
if (mainLoader.CanDestroy()) if (mainLoader.CanDestroy())
{ {
string bundleName = mainLoader.MainBundleInfo.Bundle.BundleName; string bundleName = mainLoader.MainBundleInfo.Bundle.BundleName;
mainLoader.Destroy(); mainLoader.Destroy();
_loaderList.Remove(mainLoader); _loaderList.Remove(mainLoader);
_loaderDic.Remove(bundleName); _loaderDic.Remove(bundleName);
} }
} }
// 卸载依赖资源包加载器 // 卸载依赖资源包加载器
string[] dependBundleNames = _bundleQuery.GetDependBundleNames(assetInfo); string[] dependBundleNames = _bundleQuery.GetDependBundleNames(assetInfo);
foreach (var dependBundleName in dependBundleNames) foreach (var dependBundleName in dependBundleNames)
{ {
var dependLoader = TryGetAssetBundleLoader(dependBundleName); var dependLoader = TryGetAssetBundleLoader(dependBundleName);
if (dependLoader != null) if (dependLoader != null)
{ {
if (dependLoader.CanDestroy()) if (dependLoader.CanDestroy())
{ {
string bundleName = dependLoader.MainBundleInfo.Bundle.BundleName; string bundleName = dependLoader.MainBundleInfo.Bundle.BundleName;
dependLoader.Destroy(); dependLoader.Destroy();
_loaderList.Remove(dependLoader); _loaderList.Remove(dependLoader);
_loaderDic.Remove(bundleName); _loaderDic.Remove(bundleName);
} }
} }
} }
} }
/// <summary> /// <summary>
/// 强制回收所有资源 /// 强制回收所有资源
/// 注意:加载器在销毁后关联的下载器还会继续下载! /// 注意:加载器在销毁后关联的下载器还会继续下载!
/// </summary> /// </summary>
public void ForceUnloadAllAssets() public void ForceUnloadAllAssets()
{ {
#if UNITY_WEBGL #if UNITY_WEBGL
throw new Exception($"WebGL not support invoke {nameof(ForceUnloadAllAssets)}"); throw new Exception($"WebGL not support invoke {nameof(ForceUnloadAllAssets)}");
#else #else
// 注意:因为场景无法异步转同步,需要等待所有场景加载完毕! // 注意:因为场景无法异步转同步,需要等待所有场景加载完毕!
foreach (var sceneHandlePair in _sceneHandles) foreach (var sceneHandlePair in _sceneHandles)
{ {
var sceneHandle = sceneHandlePair.Value; var sceneHandle = sceneHandlePair.Value;
if (sceneHandle.PackageName == PackageName) if (sceneHandle.PackageName == PackageName)
{ {
if (sceneHandle.IsDone == false) if (sceneHandle.IsDone == false)
throw new Exception($"{nameof(ForceUnloadAllAssets)} cannot be called when loading the scene !"); throw new Exception($"{nameof(ForceUnloadAllAssets)} cannot be called when loading the scene !");
} }
} }
// 释放所有资源句柄 // 释放所有资源句柄
foreach (var provider in _providerDic.Values) foreach (var provider in _providerDic.Values)
{ {
provider.ReleaseAllHandles(); provider.ReleaseAllHandles();
} }
// 强制销毁资源提供者 // 强制销毁资源提供者
foreach (var provider in _providerDic.Values) foreach (var provider in _providerDic.Values)
{ {
provider.ForceDestroyComplete(); provider.ForceDestroyComplete();
provider.Destroy(); provider.Destroy();
} }
// 强制销毁资源加载器 // 强制销毁资源加载器
foreach (var loader in _loaderList) foreach (var loader in _loaderList)
{ {
loader.ForceDestroyComplete(); loader.ForceDestroyComplete();
loader.Destroy(); loader.Destroy();
} }
// 清空数据 // 清空数据
_providerDic.Clear(); _providerDic.Clear();
_loaderList.Clear(); _loaderList.Clear();
_loaderDic.Clear(); _loaderDic.Clear();
ClearSceneHandle(); ClearSceneHandle();
// 注意:调用底层接口释放所有资源 // 注意:调用底层接口释放所有资源
Resources.UnloadUnusedAssets(); Resources.UnloadUnusedAssets();
#endif #endif
} }
/// <summary> /// <summary>
/// 加载场景对象 /// 加载场景对象
/// 注意:返回的场景句柄是唯一的,每个场景句柄对应自己的场景提供者对象。 /// 注意:返回的场景句柄是唯一的,每个场景句柄对应自己的场景提供者对象。
/// 注意:业务逻辑层应该避免同时加载一个子场景。 /// 注意:业务逻辑层应该避免同时加载一个子场景。
/// </summary> /// </summary>
public SceneHandle LoadSceneAsync(AssetInfo assetInfo, LoadSceneMode sceneMode, bool suspendLoad, uint priority) public SceneHandle LoadSceneAsync(AssetInfo assetInfo, LoadSceneMode sceneMode, bool suspendLoad, uint priority)
{ {
if (assetInfo.IsInvalid) 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 completedProvider = new CompletedProvider(assetInfo);
completedProvider.SetCompleted(assetInfo.Error); completedProvider.SetCompleted(assetInfo.Error);
return completedProvider.CreateHandle<SceneHandle>(); return completedProvider.CreateHandle<SceneHandle>();
} }
// 如果加载的是主场景,则卸载所有缓存的场景 // 如果加载的是主场景,则卸载所有缓存的场景
if (sceneMode == LoadSceneMode.Single) if (sceneMode == LoadSceneMode.Single)
{ {
UnloadAllScene(); UnloadAllScene();
} }
// 注意同一个场景的ProviderGUID每次加载都会变化 // 注意同一个场景的ProviderGUID每次加载都会变化
string providerGUID = $"{assetInfo.GUID}-{++_sceneCreateCount}"; string providerGUID = $"{assetInfo.GUID}-{++_sceneCreateCount}";
ProviderBase provider; ProviderBase provider;
{ {
if (_simulationOnEditor) if (_simulationOnEditor)
provider = new DatabaseSceneProvider(this, providerGUID, assetInfo, sceneMode, suspendLoad); provider = new DatabaseSceneProvider(this, providerGUID, assetInfo, sceneMode, suspendLoad);
else else
provider = new BundledSceneProvider(this, providerGUID, assetInfo, sceneMode, suspendLoad); provider = new BundledSceneProvider(this, providerGUID, assetInfo, sceneMode, suspendLoad);
provider.InitSpawnDebugInfo(); provider.InitSpawnDebugInfo();
_providerDic.Add(providerGUID, provider); _providerDic.Add(providerGUID, provider);
OperationSystem.StartOperation(PackageName, provider); OperationSystem.StartOperation(PackageName, provider);
} }
provider.Priority = priority; provider.Priority = priority;
var handle = provider.CreateHandle<SceneHandle>(); var handle = provider.CreateHandle<SceneHandle>();
handle.PackageName = PackageName; handle.PackageName = PackageName;
_sceneHandles.Add(providerGUID, handle); _sceneHandles.Add(providerGUID, handle);
return handle; return handle;
} }
/// <summary> /// <summary>
/// 加载资源对象 /// 加载资源对象
/// </summary> /// </summary>
public AssetHandle LoadAssetAsync(AssetInfo assetInfo, uint priority) public AssetHandle LoadAssetAsync(AssetInfo assetInfo, uint priority)
{ {
if (assetInfo.IsInvalid) 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 completedProvider = new CompletedProvider(assetInfo);
completedProvider.SetCompleted(assetInfo.Error); completedProvider.SetCompleted(assetInfo.Error);
return completedProvider.CreateHandle<AssetHandle>(); return completedProvider.CreateHandle<AssetHandle>();
} }
string providerGUID = nameof(LoadAssetAsync) + assetInfo.GUID; string providerGUID = nameof(LoadAssetAsync) + assetInfo.GUID;
ProviderBase provider = TryGetProvider(providerGUID); ProviderBase provider = TryGetProvider(providerGUID);
if (provider == null) if (provider == null)
{ {
if (_simulationOnEditor) if (_simulationOnEditor)
provider = new DatabaseAssetProvider(this, providerGUID, assetInfo); provider = new DatabaseAssetProvider(this, providerGUID, assetInfo);
else else
provider = new BundledAssetProvider(this, providerGUID, assetInfo); provider = new BundledAssetProvider(this, providerGUID, assetInfo);
provider.InitSpawnDebugInfo(); provider.InitSpawnDebugInfo();
_providerDic.Add(providerGUID, provider); _providerDic.Add(providerGUID, provider);
OperationSystem.StartOperation(PackageName, provider); OperationSystem.StartOperation(PackageName, provider);
} }
provider.Priority = priority; provider.Priority = priority;
return provider.CreateHandle<AssetHandle>(); return provider.CreateHandle<AssetHandle>();
} }
/// <summary> /// <summary>
/// 加载子资源对象 /// 加载子资源对象
/// </summary> /// </summary>
public SubAssetsHandle LoadSubAssetsAsync(AssetInfo assetInfo, uint priority) public SubAssetsHandle LoadSubAssetsAsync(AssetInfo assetInfo, uint priority)
{ {
if (assetInfo.IsInvalid) 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 completedProvider = new CompletedProvider(assetInfo);
completedProvider.SetCompleted(assetInfo.Error); completedProvider.SetCompleted(assetInfo.Error);
return completedProvider.CreateHandle<SubAssetsHandle>(); return completedProvider.CreateHandle<SubAssetsHandle>();
} }
string providerGUID = nameof(LoadSubAssetsAsync) + assetInfo.GUID; string providerGUID = nameof(LoadSubAssetsAsync) + assetInfo.GUID;
ProviderBase provider = TryGetProvider(providerGUID); ProviderBase provider = TryGetProvider(providerGUID);
if (provider == null) if (provider == null)
{ {
if (_simulationOnEditor) if (_simulationOnEditor)
provider = new DatabaseSubAssetsProvider(this, providerGUID, assetInfo); provider = new DatabaseSubAssetsProvider(this, providerGUID, assetInfo);
else else
provider = new BundledSubAssetsProvider(this, providerGUID, assetInfo); provider = new BundledSubAssetsProvider(this, providerGUID, assetInfo);
provider.InitSpawnDebugInfo(); provider.InitSpawnDebugInfo();
_providerDic.Add(providerGUID, provider); _providerDic.Add(providerGUID, provider);
OperationSystem.StartOperation(PackageName, provider); OperationSystem.StartOperation(PackageName, provider);
} }
provider.Priority = priority; provider.Priority = priority;
return provider.CreateHandle<SubAssetsHandle>(); return provider.CreateHandle<SubAssetsHandle>();
} }
/// <summary> /// <summary>
/// 加载所有资源对象 /// 加载所有资源对象
/// </summary> /// </summary>
public AllAssetsHandle LoadAllAssetsAsync(AssetInfo assetInfo, uint priority) public AllAssetsHandle LoadAllAssetsAsync(AssetInfo assetInfo, uint priority)
{ {
if (assetInfo.IsInvalid) if (assetInfo.IsInvalid)
{ {
YooLogger.Error($"Failed to load all assets ! {assetInfo.Error}"); YooLogger.Error($"Failed to load all assets ! {assetInfo.Error}");
CompletedProvider completedProvider = new CompletedProvider(assetInfo); CompletedProvider completedProvider = new CompletedProvider(assetInfo);
completedProvider.SetCompleted(assetInfo.Error); completedProvider.SetCompleted(assetInfo.Error);
return completedProvider.CreateHandle<AllAssetsHandle>(); return completedProvider.CreateHandle<AllAssetsHandle>();
} }
string providerGUID = nameof(LoadAllAssetsAsync) + assetInfo.GUID; string providerGUID = nameof(LoadAllAssetsAsync) + assetInfo.GUID;
ProviderBase provider = TryGetProvider(providerGUID); ProviderBase provider = TryGetProvider(providerGUID);
if (provider == null) if (provider == null)
{ {
if (_simulationOnEditor) if (_simulationOnEditor)
provider = new DatabaseAllAssetsProvider(this, providerGUID, assetInfo); provider = new DatabaseAllAssetsProvider(this, providerGUID, assetInfo);
else else
provider = new BundledAllAssetsProvider(this, providerGUID, assetInfo); provider = new BundledAllAssetsProvider(this, providerGUID, assetInfo);
provider.InitSpawnDebugInfo(); provider.InitSpawnDebugInfo();
_providerDic.Add(providerGUID, provider); _providerDic.Add(providerGUID, provider);
OperationSystem.StartOperation(PackageName, provider); OperationSystem.StartOperation(PackageName, provider);
} }
provider.Priority = priority; provider.Priority = priority;
return provider.CreateHandle<AllAssetsHandle>(); return provider.CreateHandle<AllAssetsHandle>();
} }
/// <summary> /// <summary>
/// 加载原生文件 /// 加载原生文件
/// </summary> /// </summary>
public RawFileHandle LoadRawFileAsync(AssetInfo assetInfo, uint priority) public RawFileHandle LoadRawFileAsync(AssetInfo assetInfo, uint priority)
{ {
if (assetInfo.IsInvalid) if (assetInfo.IsInvalid)
{ {
YooLogger.Error($"Failed to load raw file ! {assetInfo.Error}"); YooLogger.Error($"Failed to load raw file ! {assetInfo.Error}");
CompletedProvider completedProvider = new CompletedProvider(assetInfo); CompletedProvider completedProvider = new CompletedProvider(assetInfo);
completedProvider.SetCompleted(assetInfo.Error); completedProvider.SetCompleted(assetInfo.Error);
return completedProvider.CreateHandle<RawFileHandle>(); return completedProvider.CreateHandle<RawFileHandle>();
} }
string providerGUID = nameof(LoadRawFileAsync) + assetInfo.GUID; string providerGUID = nameof(LoadRawFileAsync) + assetInfo.GUID;
ProviderBase provider = TryGetProvider(providerGUID); ProviderBase provider = TryGetProvider(providerGUID);
if (provider == null) if (provider == null)
{ {
if (_simulationOnEditor) if (_simulationOnEditor)
provider = new DatabaseRawFileProvider(this, providerGUID, assetInfo); provider = new DatabaseRawFileProvider(this, providerGUID, assetInfo);
else else
provider = new BundledRawFileProvider(this, providerGUID, assetInfo); provider = new BundledRawFileProvider(this, providerGUID, assetInfo);
provider.InitSpawnDebugInfo(); provider.InitSpawnDebugInfo();
_providerDic.Add(providerGUID, provider); _providerDic.Add(providerGUID, provider);
OperationSystem.StartOperation(PackageName, provider); OperationSystem.StartOperation(PackageName, provider);
} }
provider.Priority = priority; provider.Priority = priority;
return provider.CreateHandle<RawFileHandle>(); return provider.CreateHandle<RawFileHandle>();
} }
internal void UnloadSubScene(string sceneName) internal void UnloadSubScene(string sceneName)
{ {
List<string> removeKeys = new List<string>(); List<string> removeKeys = new List<string>();
foreach (var valuePair in _sceneHandles) foreach (var valuePair in _sceneHandles)
{ {
var sceneHandle = valuePair.Value; var sceneHandle = valuePair.Value;
if (sceneHandle.SceneName == sceneName) if (sceneHandle.SceneName == sceneName)
{ {
// 释放子场景句柄 // 释放子场景句柄
sceneHandle.ReleaseInternal(); sceneHandle.ReleaseInternal();
removeKeys.Add(valuePair.Key); removeKeys.Add(valuePair.Key);
} }
} }
foreach (string key in removeKeys) foreach (string key in removeKeys)
{ {
_sceneHandles.Remove(key); _sceneHandles.Remove(key);
} }
} }
private void UnloadAllScene() private void UnloadAllScene()
{ {
// 释放所有场景句柄 // 释放所有场景句柄
foreach (var valuePair in _sceneHandles) foreach (var valuePair in _sceneHandles)
{ {
valuePair.Value.ReleaseInternal(); valuePair.Value.ReleaseInternal();
} }
_sceneHandles.Clear(); _sceneHandles.Clear();
} }
private void ClearSceneHandle() private void ClearSceneHandle()
{ {
// 释放资源包下的所有场景 // 释放资源包下的所有场景
if (_bundleQuery.ManifestValid()) if (_bundleQuery.ManifestValid())
{ {
string packageName = PackageName; string packageName = PackageName;
List<string> removeList = new List<string>(); List<string> removeList = new List<string>();
foreach (var valuePair in _sceneHandles) foreach (var valuePair in _sceneHandles)
{ {
if (valuePair.Value.PackageName == packageName) if (valuePair.Value.PackageName == packageName)
{ {
removeList.Add(valuePair.Key); removeList.Add(valuePair.Key);
} }
} }
foreach (var key in removeList) foreach (var key in removeList)
{ {
_sceneHandles.Remove(key); _sceneHandles.Remove(key);
} }
} }
} }
internal BundleLoaderBase CreateOwnerAssetBundleLoader(AssetInfo assetInfo) internal BundleLoaderBase CreateOwnerAssetBundleLoader(AssetInfo assetInfo)
{ {
BundleInfo bundleInfo = _bundleQuery.GetMainBundleInfo(assetInfo); BundleInfo bundleInfo = _bundleQuery.GetMainBundleInfo(assetInfo);
return CreateAssetBundleLoaderInternal(bundleInfo); return CreateAssetBundleLoaderInternal(bundleInfo);
} }
internal List<BundleLoaderBase> CreateDependAssetBundleLoaders(AssetInfo assetInfo) internal List<BundleLoaderBase> CreateDependAssetBundleLoaders(AssetInfo assetInfo)
{ {
BundleInfo[] depends = _bundleQuery.GetDependBundleInfos(assetInfo); BundleInfo[] depends = _bundleQuery.GetDependBundleInfos(assetInfo);
List<BundleLoaderBase> result = new List<BundleLoaderBase>(depends.Length); List<BundleLoaderBase> result = new List<BundleLoaderBase>(depends.Length);
foreach (var bundleInfo in depends) foreach (var bundleInfo in depends)
{ {
BundleLoaderBase dependLoader = CreateAssetBundleLoaderInternal(bundleInfo); BundleLoaderBase dependLoader = CreateAssetBundleLoaderInternal(bundleInfo);
result.Add(dependLoader); result.Add(dependLoader);
} }
return result; return result;
} }
internal void RemoveBundleProviders(List<ProviderBase> removeList) internal void RemoveBundleProviders(List<ProviderBase> removeList)
{ {
foreach (var provider in removeList) foreach (var provider in removeList)
{ {
_providerDic.Remove(provider.ProviderGUID); _providerDic.Remove(provider.ProviderGUID);
} }
} }
internal bool HasAnyLoader() internal bool HasAnyLoader()
{ {
return _loaderList.Count > 0; return _loaderList.Count > 0;
} }
private BundleLoaderBase CreateAssetBundleLoaderInternal(BundleInfo bundleInfo) private BundleLoaderBase CreateAssetBundleLoaderInternal(BundleInfo bundleInfo)
{ {
// 如果加载器已经存在 // 如果加载器已经存在
string bundleName = bundleInfo.Bundle.BundleName; string bundleName = bundleInfo.Bundle.BundleName;
BundleLoaderBase loader = TryGetAssetBundleLoader(bundleName); BundleLoaderBase loader = TryGetAssetBundleLoader(bundleName);
if (loader != null) if (loader != null)
return loader; return loader;
// 新增下载需求 // 新增下载需求
if (_simulationOnEditor) if (_simulationOnEditor)
{ {
loader = new VirtualBundleFileLoader(this, bundleInfo); loader = new VirtualBundleFileLoader(this, bundleInfo);
} }
else else
{ {
#if UNITY_WEBGL #if UNITY_WEBGL
if (bundleInfo.Bundle.Buildpipeline== EDefaultBuildPipeline.RawFileBuildPipeline.ToString()) if (bundleInfo.Bundle.Buildpipeline== EDefaultBuildPipeline.RawFileBuildPipeline.ToString())
loader = new RawBundleWebLoader(this, bundleInfo); loader = new RawBundleWebLoader(this, bundleInfo);
else else
loader = new AssetBundleWebLoader(this, bundleInfo); loader = new AssetBundleWebLoader(this, bundleInfo);
#else #else
if (bundleInfo.Bundle.Buildpipeline == EDefaultBuildPipeline.RawFileBuildPipeline.ToString()) if (bundleInfo.Bundle.Buildpipeline == EDefaultBuildPipeline.RawFileBuildPipeline.ToString())
loader = new RawBundleFileLoader(this, bundleInfo); loader = new RawBundleFileLoader(this, bundleInfo);
else else
loader = new AssetBundleFileLoader(this, bundleInfo); loader = new AssetBundleFileLoader(this, bundleInfo);
#endif #endif
} }
_loaderList.Add(loader); _loaderList.Add(loader);
_loaderDic.Add(bundleName, loader); _loaderDic.Add(bundleName, loader);
return loader; return loader;
} }
private BundleLoaderBase TryGetAssetBundleLoader(string bundleName) private BundleLoaderBase TryGetAssetBundleLoader(string bundleName)
{ {
if (_loaderDic.TryGetValue(bundleName, out BundleLoaderBase value)) if (_loaderDic.TryGetValue(bundleName, out BundleLoaderBase value))
return value; return value;
else else
return null; return null;
} }
private ProviderBase TryGetProvider(string providerGUID) private ProviderBase TryGetProvider(string providerGUID)
{ {
if (_providerDic.TryGetValue(providerGUID, out ProviderBase value)) if (_providerDic.TryGetValue(providerGUID, out ProviderBase value))
return value; return value;
else else
return null; return null;
} }
#region 调试信息 #region 调试信息
internal List<DebugProviderInfo> GetDebugReportInfos() internal List<DebugProviderInfo> GetDebugReportInfos()
{ {
List<DebugProviderInfo> result = new List<DebugProviderInfo>(_providerDic.Count); List<DebugProviderInfo> result = new List<DebugProviderInfo>(_providerDic.Count);
foreach (var provider in _providerDic.Values) foreach (var provider in _providerDic.Values)
{ {
DebugProviderInfo providerInfo = new DebugProviderInfo(); DebugProviderInfo providerInfo = new DebugProviderInfo();
providerInfo.AssetPath = provider.MainAssetInfo.AssetPath; providerInfo.AssetPath = provider.MainAssetInfo.AssetPath;
providerInfo.SpawnScene = provider.SpawnScene; providerInfo.SpawnScene = provider.SpawnScene;
providerInfo.SpawnTime = provider.SpawnTime; providerInfo.SpawnTime = provider.SpawnTime;
providerInfo.LoadingTime = provider.LoadingTime; providerInfo.LoadingTime = provider.LoadingTime;
providerInfo.RefCount = provider.RefCount; providerInfo.RefCount = provider.RefCount;
providerInfo.Status = provider.Status.ToString(); providerInfo.Status = provider.Status.ToString();
providerInfo.DependBundleInfos = new List<DebugBundleInfo>(); providerInfo.DependBundleInfos = new List<DebugBundleInfo>();
provider.GetBundleDebugInfos(providerInfo.DependBundleInfos); provider.GetBundleDebugInfos(providerInfo.DependBundleInfos);
result.Add(providerInfo); result.Add(providerInfo);
} }
return result; return result;
} }
#endregion #endregion
} }
} }

View File

@ -1,105 +1,105 @@
 
namespace YooAsset namespace YooAsset
{ {
public class AssetInfo public class AssetInfo
{ {
private readonly PackageAsset _packageAsset; private readonly PackageAsset _packageAsset;
private string _providerGUID; private string _providerGUID;
/// <summary> /// <summary>
/// 所属包裹 /// 所属包裹
/// </summary> /// </summary>
public string PackageName { private set; get; } public string PackageName { private set; get; }
/// <summary> /// <summary>
/// 资源类型 /// 资源类型
/// </summary> /// </summary>
public System.Type AssetType { private set; get; } public System.Type AssetType { private set; get; }
/// <summary> /// <summary>
/// 错误信息 /// 错误信息
/// </summary> /// </summary>
public string Error { private set; get; } public string Error { private set; get; }
/// <summary> /// <summary>
/// 唯一标识符 /// 唯一标识符
/// </summary> /// </summary>
internal string GUID internal string GUID
{ {
get get
{ {
if (string.IsNullOrEmpty(_providerGUID) == false) if (string.IsNullOrEmpty(_providerGUID) == false)
return _providerGUID; return _providerGUID;
if (AssetType == null) if (AssetType == null)
_providerGUID = $"[{AssetPath}][null]"; _providerGUID = $"[{AssetPath}][null]";
else else
_providerGUID = $"[{AssetPath}][{AssetType.Name}]"; _providerGUID = $"[{AssetPath}][{AssetType.Name}]";
return _providerGUID; return _providerGUID;
} }
} }
/// <summary> /// <summary>
/// 身份是否无效 /// 身份是否无效
/// </summary> /// </summary>
internal bool IsInvalid internal bool IsInvalid
{ {
get get
{ {
return _packageAsset == null; return _packageAsset == null;
} }
} }
/// <summary> /// <summary>
/// 可寻址地址 /// 可寻址地址
/// </summary> /// </summary>
public string Address public string Address
{ {
get get
{ {
if (_packageAsset == null) if (_packageAsset == null)
return string.Empty; return string.Empty;
return _packageAsset.Address; return _packageAsset.Address;
} }
} }
/// <summary> /// <summary>
/// 资源路径 /// 资源路径
/// </summary> /// </summary>
public string AssetPath public string AssetPath
{ {
get get
{ {
if (_packageAsset == null) if (_packageAsset == null)
return string.Empty; return string.Empty;
return _packageAsset.AssetPath; return _packageAsset.AssetPath;
} }
} }
private AssetInfo() private AssetInfo()
{ {
// 注意:禁止从外部创建该类 // 注意:禁止从外部创建该类
} }
internal AssetInfo(string packageName, PackageAsset packageAsset, System.Type assetType) internal AssetInfo(string packageName, PackageAsset packageAsset, System.Type assetType)
{ {
if (packageAsset == null) if (packageAsset == null)
throw new System.Exception("Should never get here !"); throw new System.Exception("Should never get here !");
_providerGUID = string.Empty; _providerGUID = string.Empty;
_packageAsset = packageAsset; _packageAsset = packageAsset;
PackageName = packageName; PackageName = packageName;
AssetType = assetType; AssetType = assetType;
Error = string.Empty; Error = string.Empty;
} }
internal AssetInfo(string packageName, string error) internal AssetInfo(string packageName, string error)
{ {
_providerGUID = string.Empty; _providerGUID = string.Empty;
_packageAsset = null; _packageAsset = null;
PackageName = packageName; PackageName = packageName;
AssetType = null; AssetType = null;
Error = error; Error = error;
} }
} }
} }

View File

@ -4,206 +4,206 @@ using UnityEngine;
namespace YooAsset namespace YooAsset
{ {
internal class BundleInfo internal class BundleInfo
{ {
public enum ELoadMode public enum ELoadMode
{ {
None, None,
LoadFromDelivery, LoadFromDelivery,
LoadFromStreaming, LoadFromStreaming,
LoadFromCache, LoadFromCache,
LoadFromRemote, LoadFromRemote,
LoadFromEditor, LoadFromEditor,
} }
private readonly ResourceAssist _assist; private readonly ResourceAssist _assist;
/// <summary> /// <summary>
/// 资源包对象 /// 资源包对象
/// </summary> /// </summary>
public readonly PackageBundle Bundle; public readonly PackageBundle Bundle;
/// <summary> /// <summary>
/// 资源包加载模式 /// 资源包加载模式
/// </summary> /// </summary>
public readonly ELoadMode LoadMode; public readonly ELoadMode LoadMode;
/// <summary> /// <summary>
/// 远端下载地址 /// 远端下载地址
/// </summary> /// </summary>
public string RemoteMainURL { private set; get; } public string RemoteMainURL { private set; get; }
/// <summary> /// <summary>
/// 远端下载备用地址 /// 远端下载备用地址
/// </summary> /// </summary>
public string RemoteFallbackURL { private set; get; } public string RemoteFallbackURL { private set; get; }
/// <summary> /// <summary>
/// 分发资源文件路径 /// 分发资源文件路径
/// </summary> /// </summary>
public string DeliveryFilePath { private set; get; } public string DeliveryFilePath { private set; get; }
/// <summary> /// <summary>
/// 注意:该字段只用于帮助编辑器下的模拟模式。 /// 注意:该字段只用于帮助编辑器下的模拟模式。
/// </summary> /// </summary>
public string[] IncludeAssetsInEditor; public string[] IncludeAssetsInEditor;
private BundleInfo() private BundleInfo()
{ {
} }
public BundleInfo(ResourceAssist assist, PackageBundle bundle, ELoadMode loadMode, string mainURL, string fallbackURL) public BundleInfo(ResourceAssist assist, PackageBundle bundle, ELoadMode loadMode, string mainURL, string fallbackURL)
{ {
_assist = assist; _assist = assist;
Bundle = bundle; Bundle = bundle;
LoadMode = loadMode; LoadMode = loadMode;
RemoteMainURL = mainURL; RemoteMainURL = mainURL;
RemoteFallbackURL = fallbackURL; RemoteFallbackURL = fallbackURL;
DeliveryFilePath = string.Empty; DeliveryFilePath = string.Empty;
} }
public BundleInfo(ResourceAssist assist, PackageBundle bundle, ELoadMode loadMode, string deliveryFilePath) public BundleInfo(ResourceAssist assist, PackageBundle bundle, ELoadMode loadMode, string deliveryFilePath)
{ {
_assist = assist; _assist = assist;
Bundle = bundle; Bundle = bundle;
LoadMode = loadMode; LoadMode = loadMode;
RemoteMainURL = string.Empty; RemoteMainURL = string.Empty;
RemoteFallbackURL = string.Empty; RemoteFallbackURL = string.Empty;
DeliveryFilePath = deliveryFilePath; DeliveryFilePath = deliveryFilePath;
} }
public BundleInfo(ResourceAssist assist, PackageBundle bundle, ELoadMode loadMode) public BundleInfo(ResourceAssist assist, PackageBundle bundle, ELoadMode loadMode)
{ {
_assist = assist; _assist = assist;
Bundle = bundle; Bundle = bundle;
LoadMode = loadMode; LoadMode = loadMode;
RemoteMainURL = string.Empty; RemoteMainURL = string.Empty;
RemoteFallbackURL = string.Empty; RemoteFallbackURL = string.Empty;
DeliveryFilePath = string.Empty; DeliveryFilePath = string.Empty;
} }
#region Cache #region Cache
public bool IsCached() public bool IsCached()
{ {
return _assist.Cache.IsCached(Bundle.CacheGUID); return _assist.Cache.IsCached(Bundle.CacheGUID);
} }
public void CacheRecord() public void CacheRecord()
{ {
string infoFilePath = CachedInfoFilePath; string infoFilePath = CachedInfoFilePath;
string dataFilePath = CachedDataFilePath; string dataFilePath = CachedDataFilePath;
string dataFileCRC = Bundle.FileCRC; string dataFileCRC = Bundle.FileCRC;
long dataFileSize = Bundle.FileSize; long dataFileSize = Bundle.FileSize;
var wrapper = new CacheManager.RecordWrapper(infoFilePath, dataFilePath, dataFileCRC, dataFileSize); var wrapper = new CacheManager.RecordWrapper(infoFilePath, dataFilePath, dataFileCRC, dataFileSize);
_assist.Cache.Record(Bundle.CacheGUID, wrapper); _assist.Cache.Record(Bundle.CacheGUID, wrapper);
} }
public void CacheDiscard() public void CacheDiscard()
{ {
_assist.Cache.Discard(Bundle.CacheGUID); _assist.Cache.Discard(Bundle.CacheGUID);
} }
public EVerifyResult VerifySelf() public EVerifyResult VerifySelf()
{ {
return CacheHelper.VerifyingRecordFile(_assist.Cache, Bundle.CacheGUID); return CacheHelper.VerifyingRecordFile(_assist.Cache, Bundle.CacheGUID);
} }
#endregion #endregion
#region Persistent #region Persistent
public string CachedDataFilePath public string CachedDataFilePath
{ {
get get
{ {
return _assist.Persistent.GetCachedDataFilePath(Bundle); return _assist.Persistent.GetCachedDataFilePath(Bundle);
} }
} }
public string CachedInfoFilePath public string CachedInfoFilePath
{ {
get get
{ {
return _assist.Persistent.GetCachedInfoFilePath(Bundle); return _assist.Persistent.GetCachedInfoFilePath(Bundle);
} }
} }
public string TempDataFilePath public string TempDataFilePath
{ {
get get
{ {
return _assist.Persistent.GetTempDataFilePath(Bundle); return _assist.Persistent.GetTempDataFilePath(Bundle);
} }
} }
public string BuildinFilePath public string BuildinFilePath
{ {
get get
{ {
return _assist.Persistent.GetBuildinFilePath(Bundle); return _assist.Persistent.GetBuildinFilePath(Bundle);
} }
} }
#endregion #endregion
#region Download #region Download
public DownloaderBase CreateDownloader(int failedTryAgain, int timeout = 60) public DownloaderBase CreateDownloader(int failedTryAgain, int timeout = 60)
{ {
return _assist.Download.CreateDownload(this, failedTryAgain, timeout); return _assist.Download.CreateDownload(this, failedTryAgain, timeout);
} }
public DownloaderBase CreateUnpacker(int failedTryAgain, int timeout = 60) public DownloaderBase CreateUnpacker(int failedTryAgain, int timeout = 60)
{ {
var unpackBundleInfo = ConvertToUnpackInfo(); var unpackBundleInfo = ConvertToUnpackInfo();
return _assist.Download.CreateDownload(unpackBundleInfo, failedTryAgain, timeout); return _assist.Download.CreateDownload(unpackBundleInfo, failedTryAgain, timeout);
} }
#endregion #endregion
#region AssetBundle #region AssetBundle
internal AssetBundle LoadAssetBundle(string fileLoadPath, out Stream managedStream) internal AssetBundle LoadAssetBundle(string fileLoadPath, out Stream managedStream)
{ {
return _assist.Loader.LoadAssetBundle(this, fileLoadPath, out managedStream); return _assist.Loader.LoadAssetBundle(this, fileLoadPath, out managedStream);
} }
internal AssetBundleCreateRequest LoadAssetBundleAsync(string fileLoadPath, out Stream managedStream) internal AssetBundleCreateRequest LoadAssetBundleAsync(string fileLoadPath, out Stream managedStream)
{ {
return _assist.Loader.LoadAssetBundleAsync(this, fileLoadPath, out managedStream); return _assist.Loader.LoadAssetBundleAsync(this, fileLoadPath, out managedStream);
} }
internal AssetBundle LoadDeliveryAssetBundle(string fileLoadPath) internal AssetBundle LoadDeliveryAssetBundle(string fileLoadPath)
{ {
return _assist.Loader.LoadDeliveryAssetBundle(this, fileLoadPath); return _assist.Loader.LoadDeliveryAssetBundle(this, fileLoadPath);
} }
internal AssetBundleCreateRequest LoadDeliveryAssetBundleAsync(string fileLoadPath) internal AssetBundleCreateRequest LoadDeliveryAssetBundleAsync(string fileLoadPath)
{ {
return _assist.Loader.LoadDeliveryAssetBundleAsync(this, fileLoadPath); return _assist.Loader.LoadDeliveryAssetBundleAsync(this, fileLoadPath);
} }
#endregion #endregion
/// <summary> /// <summary>
/// 转换为解压BundleInfo /// 转换为解压BundleInfo
/// </summary> /// </summary>
private BundleInfo ConvertToUnpackInfo() private BundleInfo ConvertToUnpackInfo()
{ {
string streamingPath = PersistentHelper.ConvertToWWWPath(BuildinFilePath); string streamingPath = PersistentHelper.ConvertToWWWPath(BuildinFilePath);
BundleInfo newBundleInfo = new BundleInfo(_assist, Bundle, ELoadMode.LoadFromStreaming, streamingPath, streamingPath); BundleInfo newBundleInfo = new BundleInfo(_assist, Bundle, ELoadMode.LoadFromStreaming, streamingPath, streamingPath);
return newBundleInfo; return newBundleInfo;
} }
/// <summary> /// <summary>
/// 批量创建解压BundleInfo /// 批量创建解压BundleInfo
/// </summary> /// </summary>
public static List<BundleInfo> CreateUnpackInfos(ResourceAssist assist, List<PackageBundle> unpackList) public static List<BundleInfo> CreateUnpackInfos(ResourceAssist assist, List<PackageBundle> unpackList)
{ {
List<BundleInfo> result = new List<BundleInfo>(unpackList.Count); List<BundleInfo> result = new List<BundleInfo>(unpackList.Count);
foreach (var packageBundle in unpackList) foreach (var packageBundle in unpackList)
{ {
var bundleInfo = CreateUnpackInfo(assist, packageBundle); var bundleInfo = CreateUnpackInfo(assist, packageBundle);
result.Add(bundleInfo); result.Add(bundleInfo);
} }
return result; return result;
} }
private static BundleInfo CreateUnpackInfo(ResourceAssist assist, PackageBundle packageBundle) private static BundleInfo CreateUnpackInfo(ResourceAssist assist, PackageBundle packageBundle)
{ {
string streamingPath = PersistentHelper.ConvertToWWWPath(assist.Persistent.GetBuildinFilePath(packageBundle)); string streamingPath = PersistentHelper.ConvertToWWWPath(assist.Persistent.GetBuildinFilePath(packageBundle));
BundleInfo newBundleInfo = new BundleInfo(assist, packageBundle, ELoadMode.LoadFromStreaming, streamingPath, streamingPath); BundleInfo newBundleInfo = new BundleInfo(assist, packageBundle, ELoadMode.LoadFromStreaming, streamingPath, streamingPath);
return newBundleInfo; return newBundleInfo;
} }
/// <summary> /// <summary>
/// 创建导入BundleInfo /// 创建导入BundleInfo
/// </summary> /// </summary>
public static BundleInfo CreateImportInfo(ResourceAssist assist, PackageBundle packageBundle, string filePath) public static BundleInfo CreateImportInfo(ResourceAssist assist, PackageBundle packageBundle, string filePath)
{ {
// 注意:我们把本地文件路径指定为远端下载地址 // 注意:我们把本地文件路径指定为远端下载地址
string persistentPath = PersistentHelper.ConvertToWWWPath(filePath); string persistentPath = PersistentHelper.ConvertToWWWPath(filePath);
BundleInfo bundleInfo = new BundleInfo(assist, packageBundle, BundleInfo.ELoadMode.None, persistentPath, persistentPath); BundleInfo bundleInfo = new BundleInfo(assist, packageBundle, BundleInfo.ELoadMode.None, persistentPath, persistentPath);
return bundleInfo; return bundleInfo;
} }
} }
} }

View File

@ -1,31 +1,31 @@
 
namespace YooAsset namespace YooAsset
{ {
internal interface IBundleQuery internal interface IBundleQuery
{ {
/// <summary> /// <summary>
/// 获取主资源包信息 /// 获取主资源包信息
/// </summary> /// </summary>
BundleInfo GetMainBundleInfo(AssetInfo assetInfo); BundleInfo GetMainBundleInfo(AssetInfo assetInfo);
/// <summary> /// <summary>
/// 获取依赖的资源包信息集合 /// 获取依赖的资源包信息集合
/// </summary> /// </summary>
BundleInfo[] GetDependBundleInfos(AssetInfo assetPath); BundleInfo[] GetDependBundleInfos(AssetInfo assetPath);
/// <summary> /// <summary>
/// 获取主资源包名称 /// 获取主资源包名称
/// </summary> /// </summary>
string GetMainBundleName(AssetInfo assetInfo); string GetMainBundleName(AssetInfo assetInfo);
/// <summary> /// <summary>
/// 获取依赖的资源包名称集合 /// 获取依赖的资源包名称集合
/// </summary> /// </summary>
string[] GetDependBundleNames(AssetInfo assetInfo); string[] GetDependBundleNames(AssetInfo assetInfo);
/// <summary> /// <summary>
/// 清单是否有效 /// 清单是否有效
/// </summary> /// </summary>
bool ManifestValid(); bool ManifestValid();
} }
} }

View File

@ -1,43 +1,43 @@
 
namespace YooAsset namespace YooAsset
{ {
internal interface IPlayMode internal interface IPlayMode
{ {
/// <summary> /// <summary>
/// 激活的清单 /// 激活的清单
/// </summary> /// </summary>
PackageManifest ActiveManifest { set; get; } PackageManifest ActiveManifest { set; get; }
/// <summary>
/// 保存清单版本文件到沙盒
/// </summary>
void FlushManifestVersionFile();
/// <summary> /// <summary>
/// 向网络端请求最新的资源版本 /// 保存清单版本文件到沙盒
/// </summary> /// </summary>
UpdatePackageVersionOperation UpdatePackageVersionAsync(bool appendTimeTicks, int timeout); void FlushManifestVersionFile();
/// <summary> /// <summary>
/// 向网络端请求并更新清单 /// 向网络端请求最新的资源版本
/// </summary> /// </summary>
UpdatePackageManifestOperation UpdatePackageManifestAsync(string packageVersion, bool autoSaveVersion, int timeout); UpdatePackageVersionOperation UpdatePackageVersionAsync(bool appendTimeTicks, int timeout);
/// <summary> /// <summary>
/// 预下载指定版本的包裹内容 /// 向网络端请求并更新清单
/// </summary> /// </summary>
PreDownloadContentOperation PreDownloadContentAsync(string packageVersion, int timeout); UpdatePackageManifestOperation UpdatePackageManifestAsync(string packageVersion, bool autoSaveVersion, int timeout);
// 下载相关 /// <summary>
ResourceDownloaderOperation CreateResourceDownloaderByAll(int downloadingMaxNumber, int failedTryAgain, int timeout); /// 预下载指定版本的包裹内容
ResourceDownloaderOperation CreateResourceDownloaderByTags(string[] tags, int downloadingMaxNumber, int failedTryAgain, int timeout); /// </summary>
ResourceDownloaderOperation CreateResourceDownloaderByPaths(AssetInfo[] assetInfos, int downloadingMaxNumber, int failedTryAgain, int timeout); PreDownloadContentOperation PreDownloadContentAsync(string packageVersion, int timeout);
// 解压相关 // 下载相关
ResourceUnpackerOperation CreateResourceUnpackerByAll(int upackingMaxNumber, int failedTryAgain, int timeout); ResourceDownloaderOperation CreateResourceDownloaderByAll(int downloadingMaxNumber, int failedTryAgain, int timeout);
ResourceUnpackerOperation CreateResourceUnpackerByTags(string[] tags, int upackingMaxNumber, int failedTryAgain, int timeout); ResourceDownloaderOperation CreateResourceDownloaderByTags(string[] tags, int downloadingMaxNumber, int failedTryAgain, int timeout);
ResourceDownloaderOperation CreateResourceDownloaderByPaths(AssetInfo[] assetInfos, int downloadingMaxNumber, int failedTryAgain, int timeout);
// 导入相关 // 解压相关
ResourceImporterOperation CreateResourceImporterByFilePaths(string[] filePaths, int importerMaxNumber, int failedTryAgain, int timeout); ResourceUnpackerOperation CreateResourceUnpackerByAll(int upackingMaxNumber, int failedTryAgain, int timeout);
} ResourceUnpackerOperation CreateResourceUnpackerByTags(string[] tags, int upackingMaxNumber, int failedTryAgain, int timeout);
// 导入相关
ResourceImporterOperation CreateResourceImporterByFilePaths(string[] filePaths, int importerMaxNumber, int failedTryAgain, int timeout);
}
} }

View File

@ -6,228 +6,228 @@ using UnityEngine;
namespace YooAsset namespace YooAsset
{ {
internal static class ManifestTools internal static class ManifestTools
{ {
#if UNITY_EDITOR #if UNITY_EDITOR
/// <summary> /// <summary>
/// 序列化JSON文件 /// 序列化JSON文件
/// </summary> /// </summary>
public static void SerializeToJson(string savePath, PackageManifest manifest) public static void SerializeToJson(string savePath, PackageManifest manifest)
{ {
string json = JsonUtility.ToJson(manifest, true); string json = JsonUtility.ToJson(manifest, true);
FileUtility.WriteAllText(savePath, json); FileUtility.WriteAllText(savePath, json);
} }
/// <summary> /// <summary>
/// 序列化(二进制文件) /// 序列化(二进制文件)
/// </summary> /// </summary>
public static void SerializeToBinary(string savePath, PackageManifest manifest) public static void SerializeToBinary(string savePath, PackageManifest manifest)
{ {
using (FileStream fs = new FileStream(savePath, FileMode.Create)) using (FileStream fs = new FileStream(savePath, FileMode.Create))
{ {
// 创建缓存器 // 创建缓存器
BufferWriter buffer = new BufferWriter(YooAssetSettings.ManifestFileMaxSize); BufferWriter buffer = new BufferWriter(YooAssetSettings.ManifestFileMaxSize);
// 写入文件标记 // 写入文件标记
buffer.WriteUInt32(YooAssetSettings.ManifestFileSign); buffer.WriteUInt32(YooAssetSettings.ManifestFileSign);
// 写入文件版本 // 写入文件版本
buffer.WriteUTF8(manifest.FileVersion); buffer.WriteUTF8(manifest.FileVersion);
// 写入文件头信息 // 写入文件头信息
buffer.WriteBool(manifest.EnableAddressable); buffer.WriteBool(manifest.EnableAddressable);
buffer.WriteBool(manifest.LocationToLower); buffer.WriteBool(manifest.LocationToLower);
buffer.WriteBool(manifest.IncludeAssetGUID); buffer.WriteBool(manifest.IncludeAssetGUID);
buffer.WriteInt32(manifest.OutputNameStyle); buffer.WriteInt32(manifest.OutputNameStyle);
buffer.WriteUTF8(manifest.BuildPipeline); buffer.WriteUTF8(manifest.BuildPipeline);
buffer.WriteUTF8(manifest.PackageName); buffer.WriteUTF8(manifest.PackageName);
buffer.WriteUTF8(manifest.PackageVersion); buffer.WriteUTF8(manifest.PackageVersion);
// 写入资源列表 // 写入资源列表
buffer.WriteInt32(manifest.AssetList.Count); buffer.WriteInt32(manifest.AssetList.Count);
for (int i = 0; i < manifest.AssetList.Count; i++) for (int i = 0; i < manifest.AssetList.Count; i++)
{ {
var packageAsset = manifest.AssetList[i]; var packageAsset = manifest.AssetList[i];
buffer.WriteUTF8(packageAsset.Address); buffer.WriteUTF8(packageAsset.Address);
buffer.WriteUTF8(packageAsset.AssetPath); buffer.WriteUTF8(packageAsset.AssetPath);
buffer.WriteUTF8(packageAsset.AssetGUID); buffer.WriteUTF8(packageAsset.AssetGUID);
buffer.WriteUTF8Array(packageAsset.AssetTags); buffer.WriteUTF8Array(packageAsset.AssetTags);
buffer.WriteInt32(packageAsset.BundleID); buffer.WriteInt32(packageAsset.BundleID);
} }
// 写入资源包列表 // 写入资源包列表
buffer.WriteInt32(manifest.BundleList.Count); buffer.WriteInt32(manifest.BundleList.Count);
for (int i = 0; i < manifest.BundleList.Count; i++) for (int i = 0; i < manifest.BundleList.Count; i++)
{ {
var packageBundle = manifest.BundleList[i]; var packageBundle = manifest.BundleList[i];
buffer.WriteUTF8(packageBundle.BundleName); buffer.WriteUTF8(packageBundle.BundleName);
buffer.WriteUInt32(packageBundle.UnityCRC); buffer.WriteUInt32(packageBundle.UnityCRC);
buffer.WriteUTF8(packageBundle.FileHash); buffer.WriteUTF8(packageBundle.FileHash);
buffer.WriteUTF8(packageBundle.FileCRC); buffer.WriteUTF8(packageBundle.FileCRC);
buffer.WriteInt64(packageBundle.FileSize); buffer.WriteInt64(packageBundle.FileSize);
buffer.WriteBool(packageBundle.Encrypted); buffer.WriteBool(packageBundle.Encrypted);
buffer.WriteUTF8Array(packageBundle.Tags); buffer.WriteUTF8Array(packageBundle.Tags);
buffer.WriteInt32Array(packageBundle.DependIDs); buffer.WriteInt32Array(packageBundle.DependIDs);
} }
// 写入文件流 // 写入文件流
buffer.WriteToStream(fs); buffer.WriteToStream(fs);
fs.Flush(); fs.Flush();
} }
} }
/// <summary> /// <summary>
/// 反序列化JSON文件 /// 反序列化JSON文件
/// </summary> /// </summary>
public static PackageManifest DeserializeFromJson(string jsonContent) public static PackageManifest DeserializeFromJson(string jsonContent)
{ {
return JsonUtility.FromJson<PackageManifest>(jsonContent); return JsonUtility.FromJson<PackageManifest>(jsonContent);
} }
/// <summary> /// <summary>
/// 反序列化(二进制文件) /// 反序列化(二进制文件)
/// </summary> /// </summary>
public static PackageManifest DeserializeFromBinary(byte[] binaryData) public static PackageManifest DeserializeFromBinary(byte[] binaryData)
{ {
// 创建缓存器 // 创建缓存器
BufferReader buffer = new BufferReader(binaryData); BufferReader buffer = new BufferReader(binaryData);
// 读取文件标记 // 读取文件标记
uint fileSign = buffer.ReadUInt32(); uint fileSign = buffer.ReadUInt32();
if (fileSign != YooAssetSettings.ManifestFileSign) if (fileSign != YooAssetSettings.ManifestFileSign)
throw new Exception("Invalid manifest file !"); throw new Exception("Invalid manifest file !");
// 读取文件版本 // 读取文件版本
string fileVersion = buffer.ReadUTF8(); string fileVersion = buffer.ReadUTF8();
if (fileVersion != YooAssetSettings.ManifestFileVersion) if (fileVersion != YooAssetSettings.ManifestFileVersion)
throw new Exception($"The manifest file version are not compatible : {fileVersion} != {YooAssetSettings.ManifestFileVersion}"); throw new Exception($"The manifest file version are not compatible : {fileVersion} != {YooAssetSettings.ManifestFileVersion}");
PackageManifest manifest = new PackageManifest(); PackageManifest manifest = new PackageManifest();
{ {
// 读取文件头信息 // 读取文件头信息
manifest.FileVersion = fileVersion; manifest.FileVersion = fileVersion;
manifest.EnableAddressable = buffer.ReadBool(); manifest.EnableAddressable = buffer.ReadBool();
manifest.LocationToLower = buffer.ReadBool(); manifest.LocationToLower = buffer.ReadBool();
manifest.IncludeAssetGUID = buffer.ReadBool(); manifest.IncludeAssetGUID = buffer.ReadBool();
manifest.OutputNameStyle = buffer.ReadInt32(); manifest.OutputNameStyle = buffer.ReadInt32();
manifest.BuildPipeline = buffer.ReadUTF8(); manifest.BuildPipeline = buffer.ReadUTF8();
manifest.PackageName = buffer.ReadUTF8(); manifest.PackageName = buffer.ReadUTF8();
manifest.PackageVersion = buffer.ReadUTF8(); manifest.PackageVersion = buffer.ReadUTF8();
// 检测配置 // 检测配置
if (manifest.EnableAddressable && manifest.LocationToLower) if (manifest.EnableAddressable && manifest.LocationToLower)
throw new Exception("Addressable not support location to lower !"); throw new Exception("Addressable not support location to lower !");
// 读取资源列表 // 读取资源列表
int packageAssetCount = buffer.ReadInt32(); int packageAssetCount = buffer.ReadInt32();
manifest.AssetList = new List<PackageAsset>(packageAssetCount); manifest.AssetList = new List<PackageAsset>(packageAssetCount);
for (int i = 0; i < packageAssetCount; i++) for (int i = 0; i < packageAssetCount; i++)
{ {
var packageAsset = new PackageAsset(); var packageAsset = new PackageAsset();
packageAsset.Address = buffer.ReadUTF8(); packageAsset.Address = buffer.ReadUTF8();
packageAsset.AssetPath = buffer.ReadUTF8(); packageAsset.AssetPath = buffer.ReadUTF8();
packageAsset.AssetGUID = buffer.ReadUTF8(); packageAsset.AssetGUID = buffer.ReadUTF8();
packageAsset.AssetTags = buffer.ReadUTF8Array(); packageAsset.AssetTags = buffer.ReadUTF8Array();
packageAsset.BundleID = buffer.ReadInt32(); packageAsset.BundleID = buffer.ReadInt32();
manifest.AssetList.Add(packageAsset); manifest.AssetList.Add(packageAsset);
} }
// 读取资源包列表 // 读取资源包列表
int packageBundleCount = buffer.ReadInt32(); int packageBundleCount = buffer.ReadInt32();
manifest.BundleList = new List<PackageBundle>(packageBundleCount); manifest.BundleList = new List<PackageBundle>(packageBundleCount);
for (int i = 0; i < packageBundleCount; i++) for (int i = 0; i < packageBundleCount; i++)
{ {
var packageBundle = new PackageBundle(); var packageBundle = new PackageBundle();
packageBundle.BundleName = buffer.ReadUTF8(); packageBundle.BundleName = buffer.ReadUTF8();
packageBundle.UnityCRC = buffer.ReadUInt32(); packageBundle.UnityCRC = buffer.ReadUInt32();
packageBundle.FileHash = buffer.ReadUTF8(); packageBundle.FileHash = buffer.ReadUTF8();
packageBundle.FileCRC = buffer.ReadUTF8(); packageBundle.FileCRC = buffer.ReadUTF8();
packageBundle.FileSize = buffer.ReadInt64(); packageBundle.FileSize = buffer.ReadInt64();
packageBundle.Encrypted = buffer.ReadBool(); packageBundle.Encrypted = buffer.ReadBool();
packageBundle.Tags = buffer.ReadUTF8Array(); packageBundle.Tags = buffer.ReadUTF8Array();
packageBundle.DependIDs = buffer.ReadInt32Array(); packageBundle.DependIDs = buffer.ReadInt32Array();
manifest.BundleList.Add(packageBundle); manifest.BundleList.Add(packageBundle);
} }
} }
// 填充BundleDic // 填充BundleDic
manifest.BundleDic1 = new Dictionary<string, PackageBundle>(manifest.BundleList.Count); manifest.BundleDic1 = new Dictionary<string, PackageBundle>(manifest.BundleList.Count);
manifest.BundleDic2 = new Dictionary<string, PackageBundle>(manifest.BundleList.Count); manifest.BundleDic2 = new Dictionary<string, PackageBundle>(manifest.BundleList.Count);
foreach (var packageBundle in manifest.BundleList) foreach (var packageBundle in manifest.BundleList)
{ {
packageBundle.ParseBundle(manifest); packageBundle.ParseBundle(manifest);
manifest.BundleDic1.Add(packageBundle.BundleName, packageBundle); manifest.BundleDic1.Add(packageBundle.BundleName, packageBundle);
manifest.BundleDic2.Add(packageBundle.FileName, packageBundle); manifest.BundleDic2.Add(packageBundle.FileName, packageBundle);
} }
// 填充AssetDic // 填充AssetDic
manifest.AssetDic = new Dictionary<string, PackageAsset>(manifest.AssetList.Count); manifest.AssetDic = new Dictionary<string, PackageAsset>(manifest.AssetList.Count);
foreach (var packageAsset in manifest.AssetList) foreach (var packageAsset in manifest.AssetList)
{ {
// 注意:我们不允许原始路径存在重名 // 注意:我们不允许原始路径存在重名
string assetPath = packageAsset.AssetPath; string assetPath = packageAsset.AssetPath;
if (manifest.AssetDic.ContainsKey(assetPath)) if (manifest.AssetDic.ContainsKey(assetPath))
throw new Exception($"AssetPath have existed : {assetPath}"); throw new Exception($"AssetPath have existed : {assetPath}");
else else
manifest.AssetDic.Add(assetPath, packageAsset); manifest.AssetDic.Add(assetPath, packageAsset);
} }
return manifest; return manifest;
} }
#endif #endif
/// <summary> /// <summary>
/// 注意:该类拷贝自编辑器 /// 注意:该类拷贝自编辑器
/// </summary> /// </summary>
private enum EFileNameStyle private enum EFileNameStyle
{ {
/// <summary> /// <summary>
/// 哈希值名称 /// 哈希值名称
/// </summary> /// </summary>
HashName = 0, HashName = 0,
/// <summary> /// <summary>
/// 资源包名称(不推荐) /// 资源包名称(不推荐)
/// </summary> /// </summary>
BundleName = 1, BundleName = 1,
/// <summary> /// <summary>
/// 资源包名称 + 哈希值名称 /// 资源包名称 + 哈希值名称
/// </summary> /// </summary>
BundleName_HashName = 2, BundleName_HashName = 2,
} }
/// <summary> /// <summary>
/// 获取资源文件的后缀名 /// 获取资源文件的后缀名
/// </summary> /// </summary>
public static string GetRemoteBundleFileExtension(string bundleName) public static string GetRemoteBundleFileExtension(string bundleName)
{ {
string fileExtension = Path.GetExtension(bundleName); string fileExtension = Path.GetExtension(bundleName);
return fileExtension; return fileExtension;
} }
/// <summary> /// <summary>
/// 获取远端的资源文件名 /// 获取远端的资源文件名
/// </summary> /// </summary>
public static string GetRemoteBundleFileName(int nameStyle, string bundleName, string fileExtension, string fileHash) public static string GetRemoteBundleFileName(int nameStyle, string bundleName, string fileExtension, string fileHash)
{ {
if (nameStyle == (int)EFileNameStyle.HashName) if (nameStyle == (int)EFileNameStyle.HashName)
{ {
return StringUtility.Format("{0}{1}", fileHash, fileExtension); return StringUtility.Format("{0}{1}", fileHash, fileExtension);
} }
else if (nameStyle == (int)EFileNameStyle.BundleName) else if (nameStyle == (int)EFileNameStyle.BundleName)
{ {
return bundleName; return bundleName;
} }
else if (nameStyle == (int)EFileNameStyle.BundleName_HashName) else if (nameStyle == (int)EFileNameStyle.BundleName_HashName)
{ {
string fileName = bundleName.Remove(bundleName.LastIndexOf('.')); string fileName = bundleName.Remove(bundleName.LastIndexOf('.'));
return StringUtility.Format("{0}_{1}{2}", fileName, fileHash, fileExtension); return StringUtility.Format("{0}_{1}{2}", fileName, fileHash, fileExtension);
} }
else else
{ {
throw new NotImplementedException($"Invalid name style : {nameStyle}"); throw new NotImplementedException($"Invalid name style : {nameStyle}");
} }
} }
} }
} }

View File

@ -3,366 +3,366 @@ using System.Collections.Generic;
namespace YooAsset namespace YooAsset
{ {
public abstract class DownloaderOperation : AsyncOperationBase public abstract class DownloaderOperation : AsyncOperationBase
{ {
private enum ESteps private enum ESteps
{ {
None, None,
Check, Check,
Loading, Loading,
Done, Done,
} }
private const int MAX_LOADER_COUNT = 64; private const int MAX_LOADER_COUNT = 64;
public delegate void OnDownloadOver(bool isSucceed); public delegate void OnDownloadOver(bool isSucceed);
public delegate void OnDownloadProgress(int totalDownloadCount, int currentDownloadCount, long totalDownloadBytes, long currentDownloadBytes); public delegate void OnDownloadProgress(int totalDownloadCount, int currentDownloadCount, long totalDownloadBytes, long currentDownloadBytes);
public delegate void OnDownloadError(string fileName, string error); public delegate void OnDownloadError(string fileName, string error);
public delegate void OnStartDownloadFile(string fileName, long sizeBytes); public delegate void OnStartDownloadFile(string fileName, long sizeBytes);
private readonly DownloadManager _downloadMgr; private readonly DownloadManager _downloadMgr;
private readonly string _packageName; private readonly string _packageName;
private readonly int _downloadingMaxNumber; private readonly int _downloadingMaxNumber;
private readonly int _failedTryAgain; private readonly int _failedTryAgain;
private readonly int _timeout; private readonly int _timeout;
private readonly List<BundleInfo> _bundleInfoList; private readonly List<BundleInfo> _bundleInfoList;
private readonly List<DownloaderBase> _downloaders = new List<DownloaderBase>(MAX_LOADER_COUNT); private readonly List<DownloaderBase> _downloaders = new List<DownloaderBase>(MAX_LOADER_COUNT);
private readonly List<DownloaderBase> _removeList = new List<DownloaderBase>(MAX_LOADER_COUNT); private readonly List<DownloaderBase> _removeList = new List<DownloaderBase>(MAX_LOADER_COUNT);
private readonly List<DownloaderBase> _failedList = new List<DownloaderBase>(MAX_LOADER_COUNT); private readonly List<DownloaderBase> _failedList = new List<DownloaderBase>(MAX_LOADER_COUNT);
// 数据相关 // 数据相关
private bool _isPause = false; private bool _isPause = false;
private long _lastDownloadBytes = 0; private long _lastDownloadBytes = 0;
private int _lastDownloadCount = 0; private int _lastDownloadCount = 0;
private long _cachedDownloadBytes = 0; private long _cachedDownloadBytes = 0;
private int _cachedDownloadCount = 0; private int _cachedDownloadCount = 0;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
/// <summary> /// <summary>
/// 统计的下载文件总数量 /// 统计的下载文件总数量
/// </summary> /// </summary>
public int TotalDownloadCount { private set; get; } public int TotalDownloadCount { private set; get; }
/// <summary> /// <summary>
/// 统计的下载文件的总大小 /// 统计的下载文件的总大小
/// </summary> /// </summary>
public long TotalDownloadBytes { private set; get; } public long TotalDownloadBytes { private set; get; }
/// <summary> /// <summary>
/// 当前已经完成的下载总数量 /// 当前已经完成的下载总数量
/// </summary> /// </summary>
public int CurrentDownloadCount public int CurrentDownloadCount
{ {
get { return _lastDownloadCount; } get { return _lastDownloadCount; }
} }
/// <summary> /// <summary>
/// 当前已经完成的下载总大小 /// 当前已经完成的下载总大小
/// </summary> /// </summary>
public long CurrentDownloadBytes public long CurrentDownloadBytes
{ {
get { return _lastDownloadBytes; } get { return _lastDownloadBytes; }
} }
/// <summary> /// <summary>
/// 当下载器结束(无论成功或失败) /// 当下载器结束(无论成功或失败)
/// </summary> /// </summary>
public OnDownloadOver OnDownloadOverCallback { set; get; } public OnDownloadOver OnDownloadOverCallback { set; get; }
/// <summary> /// <summary>
/// 当下载进度发生变化 /// 当下载进度发生变化
/// </summary> /// </summary>
public OnDownloadProgress OnDownloadProgressCallback { set; get; } public OnDownloadProgress OnDownloadProgressCallback { set; get; }
/// <summary> /// <summary>
/// 当某个文件下载失败 /// 当某个文件下载失败
/// </summary> /// </summary>
public OnDownloadError OnDownloadErrorCallback { set; get; } public OnDownloadError OnDownloadErrorCallback { set; get; }
/// <summary> /// <summary>
/// 当开始下载某个文件 /// 当开始下载某个文件
/// </summary> /// </summary>
public OnStartDownloadFile OnStartDownloadFileCallback { set; get; } public OnStartDownloadFile OnStartDownloadFileCallback { set; get; }
internal DownloaderOperation(DownloadManager downloadMgr, string packageName, List<BundleInfo> downloadList, int downloadingMaxNumber, int failedTryAgain, int timeout) internal DownloaderOperation(DownloadManager downloadMgr, string packageName, List<BundleInfo> downloadList, int downloadingMaxNumber, int failedTryAgain, int timeout)
{ {
_downloadMgr = downloadMgr; _downloadMgr = downloadMgr;
_packageName = packageName; _packageName = packageName;
_bundleInfoList = downloadList; _bundleInfoList = downloadList;
_downloadingMaxNumber = UnityEngine.Mathf.Clamp(downloadingMaxNumber, 1, MAX_LOADER_COUNT); ; _downloadingMaxNumber = UnityEngine.Mathf.Clamp(downloadingMaxNumber, 1, MAX_LOADER_COUNT); ;
_failedTryAgain = failedTryAgain; _failedTryAgain = failedTryAgain;
_timeout = timeout; _timeout = timeout;
// 统计下载信息 // 统计下载信息
CalculatDownloaderInfo(); CalculatDownloaderInfo();
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
YooLogger.Log($"Begine to download : {TotalDownloadCount} files and {TotalDownloadBytes} bytes"); YooLogger.Log($"Begine to download : {TotalDownloadCount} files and {TotalDownloadBytes} bytes");
_steps = ESteps.Check; _steps = ESteps.Check;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
if (_steps == ESteps.None || _steps == ESteps.Done) if (_steps == ESteps.None || _steps == ESteps.Done)
return; return;
if (_steps == ESteps.Check) if (_steps == ESteps.Check)
{ {
if (_bundleInfoList == null) if (_bundleInfoList == null)
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = "Download list is null."; Error = "Download list is null.";
} }
else else
{ {
_steps = ESteps.Loading; _steps = ESteps.Loading;
} }
} }
if (_steps == ESteps.Loading) if (_steps == ESteps.Loading)
{ {
// 检测下载器结果 // 检测下载器结果
_removeList.Clear(); _removeList.Clear();
long downloadBytes = _cachedDownloadBytes; long downloadBytes = _cachedDownloadBytes;
foreach (var downloader in _downloaders) foreach (var downloader in _downloaders)
{ {
downloadBytes += (long)downloader.DownloadedBytes; downloadBytes += (long)downloader.DownloadedBytes;
if (downloader.IsDone() == false) if (downloader.IsDone() == false)
continue; continue;
// 检测是否下载失败 // 检测是否下载失败
if (downloader.HasError()) if (downloader.HasError())
{ {
_removeList.Add(downloader); _removeList.Add(downloader);
_failedList.Add(downloader); _failedList.Add(downloader);
continue; continue;
} }
// 下载成功 // 下载成功
_removeList.Add(downloader); _removeList.Add(downloader);
_cachedDownloadCount++; _cachedDownloadCount++;
_cachedDownloadBytes += downloader.GetDownloadFileSize(); _cachedDownloadBytes += downloader.GetDownloadFileSize();
} }
// 移除已经完成的下载器(无论成功或失败) // 移除已经完成的下载器(无论成功或失败)
foreach (var loader in _removeList) foreach (var loader in _removeList)
{ {
_downloaders.Remove(loader); _downloaders.Remove(loader);
} }
// 如果下载进度发生变化 // 如果下载进度发生变化
if (_lastDownloadBytes != downloadBytes || _lastDownloadCount != _cachedDownloadCount) if (_lastDownloadBytes != downloadBytes || _lastDownloadCount != _cachedDownloadCount)
{ {
_lastDownloadBytes = downloadBytes; _lastDownloadBytes = downloadBytes;
_lastDownloadCount = _cachedDownloadCount; _lastDownloadCount = _cachedDownloadCount;
Progress = (float)_lastDownloadBytes / TotalDownloadBytes; Progress = (float)_lastDownloadBytes / TotalDownloadBytes;
OnDownloadProgressCallback?.Invoke(TotalDownloadCount, _lastDownloadCount, TotalDownloadBytes, _lastDownloadBytes); OnDownloadProgressCallback?.Invoke(TotalDownloadCount, _lastDownloadCount, TotalDownloadBytes, _lastDownloadBytes);
} }
// 动态创建新的下载器到最大数量限制 // 动态创建新的下载器到最大数量限制
// 注意:如果期间有下载失败的文件,暂停动态创建下载器 // 注意:如果期间有下载失败的文件,暂停动态创建下载器
if (_bundleInfoList.Count > 0 && _failedList.Count == 0) if (_bundleInfoList.Count > 0 && _failedList.Count == 0)
{ {
if (_isPause) if (_isPause)
return; return;
if (_downloaders.Count < _downloadingMaxNumber) if (_downloaders.Count < _downloadingMaxNumber)
{ {
int index = _bundleInfoList.Count - 1; int index = _bundleInfoList.Count - 1;
var bundleInfo = _bundleInfoList[index]; var bundleInfo = _bundleInfoList[index];
var downloader = bundleInfo.CreateDownloader(_failedTryAgain, _timeout); var downloader = bundleInfo.CreateDownloader(_failedTryAgain, _timeout);
downloader.SendRequest(); downloader.SendRequest();
_downloaders.Add(downloader); _downloaders.Add(downloader);
_bundleInfoList.RemoveAt(index); _bundleInfoList.RemoveAt(index);
OnStartDownloadFileCallback?.Invoke(bundleInfo.Bundle.BundleName, bundleInfo.Bundle.FileSize); OnStartDownloadFileCallback?.Invoke(bundleInfo.Bundle.BundleName, bundleInfo.Bundle.FileSize);
} }
} }
// 下载结算 // 下载结算
if (_downloaders.Count == 0) if (_downloaders.Count == 0)
{ {
if (_failedList.Count > 0) if (_failedList.Count > 0)
{ {
var failedDownloader = _failedList[0]; var failedDownloader = _failedList[0];
string bundleName = failedDownloader.GetDownloadBundleName(); string bundleName = failedDownloader.GetDownloadBundleName();
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = $"Failed to download file : {bundleName}"; Error = $"Failed to download file : {bundleName}";
OnDownloadErrorCallback?.Invoke(bundleName, failedDownloader.GetLastError()); OnDownloadErrorCallback?.Invoke(bundleName, failedDownloader.GetLastError());
OnDownloadOverCallback?.Invoke(false); OnDownloadOverCallback?.Invoke(false);
} }
else else
{ {
// 结算成功 // 结算成功
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
OnDownloadOverCallback?.Invoke(true); OnDownloadOverCallback?.Invoke(true);
} }
} }
} }
} }
private void CalculatDownloaderInfo() private void CalculatDownloaderInfo()
{ {
if (_bundleInfoList != null) if (_bundleInfoList != null)
{ {
TotalDownloadBytes = 0; TotalDownloadBytes = 0;
TotalDownloadCount = _bundleInfoList.Count; TotalDownloadCount = _bundleInfoList.Count;
foreach (var packageBundle in _bundleInfoList) foreach (var packageBundle in _bundleInfoList)
{ {
TotalDownloadBytes += packageBundle.Bundle.FileSize; TotalDownloadBytes += packageBundle.Bundle.FileSize;
} }
} }
else else
{ {
TotalDownloadBytes = 0; TotalDownloadBytes = 0;
TotalDownloadCount = 0; TotalDownloadCount = 0;
} }
} }
/// <summary> /// <summary>
/// 合并其它下载器 /// 合并其它下载器
/// </summary> /// </summary>
/// <param name="downloader">合并的下载器</param> /// <param name="downloader">合并的下载器</param>
public void Combine(DownloaderOperation downloader) public void Combine(DownloaderOperation downloader)
{ {
if (_packageName != downloader._packageName) if (_packageName != downloader._packageName)
{ {
YooLogger.Error("The downloaders have different resource packages !"); YooLogger.Error("The downloaders have different resource packages !");
return; return;
} }
if (Status != EOperationStatus.None) if (Status != EOperationStatus.None)
{ {
YooLogger.Error("The downloader is running, can not combine with other downloader !"); YooLogger.Error("The downloader is running, can not combine with other downloader !");
return; return;
} }
HashSet<string> temper = new HashSet<string>(); HashSet<string> temper = new HashSet<string>();
foreach (var bundleInfo in _bundleInfoList) foreach (var bundleInfo in _bundleInfoList)
{ {
if (temper.Contains(bundleInfo.CachedDataFilePath) == false) if (temper.Contains(bundleInfo.CachedDataFilePath) == false)
{ {
temper.Add(bundleInfo.CachedDataFilePath); temper.Add(bundleInfo.CachedDataFilePath);
} }
} }
// 合并下载列表 // 合并下载列表
foreach (var bundleInfo in downloader._bundleInfoList) foreach (var bundleInfo in downloader._bundleInfoList)
{ {
if (temper.Contains(bundleInfo.CachedDataFilePath) == false) if (temper.Contains(bundleInfo.CachedDataFilePath) == false)
{ {
_bundleInfoList.Add(bundleInfo); _bundleInfoList.Add(bundleInfo);
} }
} }
// 重新统计下载信息 // 重新统计下载信息
CalculatDownloaderInfo(); CalculatDownloaderInfo();
} }
/// <summary> /// <summary>
/// 开始下载 /// 开始下载
/// </summary> /// </summary>
public void BeginDownload() public void BeginDownload()
{ {
if (_steps == ESteps.None) if (_steps == ESteps.None)
{ {
OperationSystem.StartOperation(_packageName, this); OperationSystem.StartOperation(_packageName, this);
} }
} }
/// <summary> /// <summary>
/// 暂停下载 /// 暂停下载
/// </summary> /// </summary>
public void PauseDownload() public void PauseDownload()
{ {
_isPause = true; _isPause = true;
} }
/// <summary> /// <summary>
/// 恢复下载 /// 恢复下载
/// </summary> /// </summary>
public void ResumeDownload() public void ResumeDownload()
{ {
_isPause = false; _isPause = false;
} }
/// <summary> /// <summary>
/// 取消下载 /// 取消下载
/// </summary> /// </summary>
public void CancelDownload() public void CancelDownload()
{ {
if (_steps != ESteps.Done) if (_steps != ESteps.Done)
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = "User cancel."; Error = "User cancel.";
ReleaseAllDownloader(); ReleaseAllDownloader();
} }
} }
private void ReleaseAllDownloader() private void ReleaseAllDownloader()
{ {
foreach (var downloader in _downloaders) foreach (var downloader in _downloaders)
{ {
downloader.Release(); downloader.Release();
} }
// 注意:停止不再使用的下载器 // 注意:停止不再使用的下载器
_downloadMgr.AbortUnusedDownloader(); _downloadMgr.AbortUnusedDownloader();
} }
} }
public sealed class ResourceDownloaderOperation : DownloaderOperation public sealed class ResourceDownloaderOperation : DownloaderOperation
{ {
internal ResourceDownloaderOperation(DownloadManager downloadMgr, string packageName, List<BundleInfo> downloadList, int downloadingMaxNumber, int failedTryAgain, int timeout) internal ResourceDownloaderOperation(DownloadManager downloadMgr, string packageName, List<BundleInfo> downloadList, int downloadingMaxNumber, int failedTryAgain, int timeout)
: base(downloadMgr, packageName, downloadList, downloadingMaxNumber, failedTryAgain, timeout) : base(downloadMgr, packageName, downloadList, downloadingMaxNumber, failedTryAgain, timeout)
{ {
} }
/// <summary> /// <summary>
/// 创建空的下载器 /// 创建空的下载器
/// </summary> /// </summary>
internal static ResourceDownloaderOperation CreateEmptyDownloader(DownloadManager downloadMgr, string packageName, int downloadingMaxNumber, int failedTryAgain, int timeout) internal static ResourceDownloaderOperation CreateEmptyDownloader(DownloadManager downloadMgr, string packageName, int downloadingMaxNumber, int failedTryAgain, int timeout)
{ {
List<BundleInfo> downloadList = new List<BundleInfo>(); List<BundleInfo> downloadList = new List<BundleInfo>();
var operation = new ResourceDownloaderOperation(downloadMgr, packageName, downloadList, downloadingMaxNumber, failedTryAgain, timeout); var operation = new ResourceDownloaderOperation(downloadMgr, packageName, downloadList, downloadingMaxNumber, failedTryAgain, timeout);
return operation; return operation;
} }
} }
public sealed class ResourceUnpackerOperation : DownloaderOperation public sealed class ResourceUnpackerOperation : DownloaderOperation
{ {
internal ResourceUnpackerOperation(DownloadManager downloadMgr, string packageName, List<BundleInfo> downloadList, int downloadingMaxNumber, int failedTryAgain, int timeout) internal ResourceUnpackerOperation(DownloadManager downloadMgr, string packageName, List<BundleInfo> downloadList, int downloadingMaxNumber, int failedTryAgain, int timeout)
: base(downloadMgr, packageName, downloadList, downloadingMaxNumber, failedTryAgain, timeout) : base(downloadMgr, packageName, downloadList, downloadingMaxNumber, failedTryAgain, timeout)
{ {
} }
/// <summary> /// <summary>
/// 创建空的解压器 /// 创建空的解压器
/// </summary> /// </summary>
internal static ResourceUnpackerOperation CreateEmptyUnpacker(DownloadManager downloadMgr, string packageName, int upackingMaxNumber, int failedTryAgain, int timeout) internal static ResourceUnpackerOperation CreateEmptyUnpacker(DownloadManager downloadMgr, string packageName, int upackingMaxNumber, int failedTryAgain, int timeout)
{ {
List<BundleInfo> downloadList = new List<BundleInfo>(); List<BundleInfo> downloadList = new List<BundleInfo>();
var operation = new ResourceUnpackerOperation(downloadMgr, packageName, downloadList, upackingMaxNumber, failedTryAgain, int.MaxValue); var operation = new ResourceUnpackerOperation(downloadMgr, packageName, downloadList, upackingMaxNumber, failedTryAgain, int.MaxValue);
return operation; return operation;
} }
} }
public sealed class ResourceImporterOperation : DownloaderOperation public sealed class ResourceImporterOperation : DownloaderOperation
{ {
internal ResourceImporterOperation(DownloadManager downloadMgr, string packageName, List<BundleInfo> downloadList, int downloadingMaxNumber, int failedTryAgain, int timeout) internal ResourceImporterOperation(DownloadManager downloadMgr, string packageName, List<BundleInfo> downloadList, int downloadingMaxNumber, int failedTryAgain, int timeout)
: base(downloadMgr, packageName, downloadList, downloadingMaxNumber, failedTryAgain, timeout) : base(downloadMgr, packageName, downloadList, downloadingMaxNumber, failedTryAgain, timeout)
{ {
} }
/// <summary> /// <summary>
/// 创建空的导入器 /// 创建空的导入器
/// </summary> /// </summary>
internal static ResourceImporterOperation CreateEmptyImporter(DownloadManager downloadMgr, string packageName, int upackingMaxNumber, int failedTryAgain, int timeout) internal static ResourceImporterOperation CreateEmptyImporter(DownloadManager downloadMgr, string packageName, int upackingMaxNumber, int failedTryAgain, int timeout)
{ {
List<BundleInfo> downloadList = new List<BundleInfo>(); List<BundleInfo> downloadList = new List<BundleInfo>();
var operation = new ResourceImporterOperation(downloadMgr, packageName, downloadList, upackingMaxNumber, failedTryAgain, int.MaxValue); var operation = new ResourceImporterOperation(downloadMgr, packageName, downloadList, upackingMaxNumber, failedTryAgain, int.MaxValue);
return operation; return operation;
} }
} }
} }

View File

@ -5,500 +5,500 @@ using UnityEngine;
namespace YooAsset namespace YooAsset
{ {
/// <summary> /// <summary>
/// 初始化操作 /// 初始化操作
/// </summary> /// </summary>
public abstract class InitializationOperation : AsyncOperationBase public abstract class InitializationOperation : AsyncOperationBase
{ {
public string PackageVersion { protected set; get; } public string PackageVersion { protected set; get; }
} }
/// <summary> /// <summary>
/// 编辑器下模拟模式的初始化操作 /// 编辑器下模拟模式的初始化操作
/// </summary> /// </summary>
internal sealed class EditorSimulateModeInitializationOperation : InitializationOperation internal sealed class EditorSimulateModeInitializationOperation : InitializationOperation
{ {
private enum ESteps private enum ESteps
{ {
None, None,
LoadEditorManifest, LoadEditorManifest,
Done, Done,
} }
private readonly EditorSimulateModeImpl _impl; private readonly EditorSimulateModeImpl _impl;
private readonly string _simulateManifestFilePath; private readonly string _simulateManifestFilePath;
private LoadEditorManifestOperation _loadEditorManifestOp; private LoadEditorManifestOperation _loadEditorManifestOp;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
internal EditorSimulateModeInitializationOperation(EditorSimulateModeImpl impl, string simulateManifestFilePath) internal EditorSimulateModeInitializationOperation(EditorSimulateModeImpl impl, string simulateManifestFilePath)
{ {
_impl = impl; _impl = impl;
_simulateManifestFilePath = simulateManifestFilePath; _simulateManifestFilePath = simulateManifestFilePath;
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
_steps = ESteps.LoadEditorManifest; _steps = ESteps.LoadEditorManifest;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
if (_steps == ESteps.LoadEditorManifest) if (_steps == ESteps.LoadEditorManifest)
{ {
if (_loadEditorManifestOp == null) if (_loadEditorManifestOp == null)
{ {
_loadEditorManifestOp = new LoadEditorManifestOperation(_impl.PackageName, _simulateManifestFilePath); _loadEditorManifestOp = new LoadEditorManifestOperation(_impl.PackageName, _simulateManifestFilePath);
OperationSystem.StartOperation(_impl.PackageName, _loadEditorManifestOp); OperationSystem.StartOperation(_impl.PackageName, _loadEditorManifestOp);
} }
if (_loadEditorManifestOp.IsDone == false) if (_loadEditorManifestOp.IsDone == false)
return; return;
if (_loadEditorManifestOp.Status == EOperationStatus.Succeed) if (_loadEditorManifestOp.Status == EOperationStatus.Succeed)
{ {
PackageVersion = _loadEditorManifestOp.Manifest.PackageVersion; PackageVersion = _loadEditorManifestOp.Manifest.PackageVersion;
_impl.ActiveManifest = _loadEditorManifestOp.Manifest; _impl.ActiveManifest = _loadEditorManifestOp.Manifest;
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
else else
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = _loadEditorManifestOp.Error; Error = _loadEditorManifestOp.Error;
} }
} }
} }
} }
/// <summary> /// <summary>
/// 离线运行模式的初始化操作 /// 离线运行模式的初始化操作
/// </summary> /// </summary>
internal sealed class OfflinePlayModeInitializationOperation : InitializationOperation internal sealed class OfflinePlayModeInitializationOperation : InitializationOperation
{ {
private enum ESteps private enum ESteps
{ {
None, None,
QueryBuildinPackageVersion, QueryBuildinPackageVersion,
LoadBuildinManifest, LoadBuildinManifest,
PackageCaching, PackageCaching,
Done, Done,
} }
private readonly OfflinePlayModeImpl _impl; private readonly OfflinePlayModeImpl _impl;
private QueryBuildinPackageVersionOperation _queryBuildinPackageVersionOp; private QueryBuildinPackageVersionOperation _queryBuildinPackageVersionOp;
private LoadBuildinManifestOperation _loadBuildinManifestOp; private LoadBuildinManifestOperation _loadBuildinManifestOp;
private PackageCachingOperation _cachingOperation; private PackageCachingOperation _cachingOperation;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
internal OfflinePlayModeInitializationOperation(OfflinePlayModeImpl impl) internal OfflinePlayModeInitializationOperation(OfflinePlayModeImpl impl)
{ {
_impl = impl; _impl = impl;
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
_steps = ESteps.QueryBuildinPackageVersion; _steps = ESteps.QueryBuildinPackageVersion;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
if (_steps == ESteps.None || _steps == ESteps.Done) if (_steps == ESteps.None || _steps == ESteps.Done)
return; return;
if (_steps == ESteps.QueryBuildinPackageVersion) if (_steps == ESteps.QueryBuildinPackageVersion)
{ {
if (_queryBuildinPackageVersionOp == null) if (_queryBuildinPackageVersionOp == null)
{ {
_queryBuildinPackageVersionOp = new QueryBuildinPackageVersionOperation(_impl.Persistent); _queryBuildinPackageVersionOp = new QueryBuildinPackageVersionOperation(_impl.Persistent);
OperationSystem.StartOperation(_impl.PackageName, _queryBuildinPackageVersionOp); OperationSystem.StartOperation(_impl.PackageName, _queryBuildinPackageVersionOp);
} }
if (_queryBuildinPackageVersionOp.IsDone == false) if (_queryBuildinPackageVersionOp.IsDone == false)
return; return;
if (_queryBuildinPackageVersionOp.Status == EOperationStatus.Succeed) if (_queryBuildinPackageVersionOp.Status == EOperationStatus.Succeed)
{ {
_steps = ESteps.LoadBuildinManifest; _steps = ESteps.LoadBuildinManifest;
} }
else else
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = _queryBuildinPackageVersionOp.Error; Error = _queryBuildinPackageVersionOp.Error;
} }
} }
if (_steps == ESteps.LoadBuildinManifest) if (_steps == ESteps.LoadBuildinManifest)
{ {
if (_loadBuildinManifestOp == null) if (_loadBuildinManifestOp == null)
{ {
_loadBuildinManifestOp = new LoadBuildinManifestOperation(_impl.Persistent, _queryBuildinPackageVersionOp.PackageVersion); _loadBuildinManifestOp = new LoadBuildinManifestOperation(_impl.Persistent, _queryBuildinPackageVersionOp.PackageVersion);
OperationSystem.StartOperation(_impl.PackageName, _loadBuildinManifestOp); OperationSystem.StartOperation(_impl.PackageName, _loadBuildinManifestOp);
} }
Progress = _loadBuildinManifestOp.Progress; Progress = _loadBuildinManifestOp.Progress;
if (_loadBuildinManifestOp.IsDone == false) if (_loadBuildinManifestOp.IsDone == false)
return; return;
if (_loadBuildinManifestOp.Status == EOperationStatus.Succeed) if (_loadBuildinManifestOp.Status == EOperationStatus.Succeed)
{ {
PackageVersion = _loadBuildinManifestOp.Manifest.PackageVersion; PackageVersion = _loadBuildinManifestOp.Manifest.PackageVersion;
_impl.ActiveManifest = _loadBuildinManifestOp.Manifest; _impl.ActiveManifest = _loadBuildinManifestOp.Manifest;
_steps = ESteps.PackageCaching; _steps = ESteps.PackageCaching;
} }
else else
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = _loadBuildinManifestOp.Error; Error = _loadBuildinManifestOp.Error;
} }
} }
if (_steps == ESteps.PackageCaching) if (_steps == ESteps.PackageCaching)
{ {
if (_cachingOperation == null) if (_cachingOperation == null)
{ {
_cachingOperation = new PackageCachingOperation(_impl.Persistent, _impl.Cache); _cachingOperation = new PackageCachingOperation(_impl.Persistent, _impl.Cache);
OperationSystem.StartOperation(_impl.PackageName, _cachingOperation); OperationSystem.StartOperation(_impl.PackageName, _cachingOperation);
} }
Progress = _cachingOperation.Progress; Progress = _cachingOperation.Progress;
if (_cachingOperation.IsDone) if (_cachingOperation.IsDone)
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
} }
} }
} }
/// <summary> /// <summary>
/// 联机运行模式的初始化操作 /// 联机运行模式的初始化操作
/// 注意:优先从沙盒里加载清单,如果沙盒里不存在就尝试把内置清单拷贝到沙盒并加载该清单。 /// 注意:优先从沙盒里加载清单,如果沙盒里不存在就尝试把内置清单拷贝到沙盒并加载该清单。
/// </summary> /// </summary>
internal sealed class HostPlayModeInitializationOperation : InitializationOperation internal sealed class HostPlayModeInitializationOperation : InitializationOperation
{ {
private enum ESteps private enum ESteps
{ {
None, None,
CheckAppFootPrint, CheckAppFootPrint,
QueryCachePackageVersion, QueryCachePackageVersion,
TryLoadCacheManifest, TryLoadCacheManifest,
QueryBuildinPackageVersion, QueryBuildinPackageVersion,
UnpackBuildinManifest, UnpackBuildinManifest,
LoadBuildinManifest, LoadBuildinManifest,
PackageCaching, PackageCaching,
Done, Done,
} }
private readonly HostPlayModeImpl _impl; private readonly HostPlayModeImpl _impl;
private QueryBuildinPackageVersionOperation _queryBuildinPackageVersionOp; private QueryBuildinPackageVersionOperation _queryBuildinPackageVersionOp;
private QueryCachePackageVersionOperation _queryCachePackageVersionOp; private QueryCachePackageVersionOperation _queryCachePackageVersionOp;
private UnpackBuildinManifestOperation _unpackBuildinManifestOp; private UnpackBuildinManifestOperation _unpackBuildinManifestOp;
private LoadBuildinManifestOperation _loadBuildinManifestOp; private LoadBuildinManifestOperation _loadBuildinManifestOp;
private LoadCacheManifestOperation _loadCacheManifestOp; private LoadCacheManifestOperation _loadCacheManifestOp;
private PackageCachingOperation _cachingOperation; private PackageCachingOperation _cachingOperation;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
internal HostPlayModeInitializationOperation(HostPlayModeImpl impl) internal HostPlayModeInitializationOperation(HostPlayModeImpl impl)
{ {
_impl = impl; _impl = impl;
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
_steps = ESteps.CheckAppFootPrint; _steps = ESteps.CheckAppFootPrint;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
if (_steps == ESteps.None || _steps == ESteps.Done) if (_steps == ESteps.None || _steps == ESteps.Done)
return; return;
if (_steps == ESteps.CheckAppFootPrint) if (_steps == ESteps.CheckAppFootPrint)
{ {
var appFootPrint = new AppFootPrint(_impl.Persistent); var appFootPrint = new AppFootPrint(_impl.Persistent);
appFootPrint.Load(_impl.PackageName); appFootPrint.Load(_impl.PackageName);
// 如果水印发生变化,则说明覆盖安装后首次打开游戏 // 如果水印发生变化,则说明覆盖安装后首次打开游戏
if (appFootPrint.IsDirty()) if (appFootPrint.IsDirty())
{ {
_impl.Persistent.DeleteSandboxManifestFilesFolder(); _impl.Persistent.DeleteSandboxManifestFilesFolder();
appFootPrint.Coverage(_impl.PackageName); appFootPrint.Coverage(_impl.PackageName);
YooLogger.Log("Delete manifest files when application foot print dirty !"); YooLogger.Log("Delete manifest files when application foot print dirty !");
} }
_steps = ESteps.QueryCachePackageVersion; _steps = ESteps.QueryCachePackageVersion;
} }
if (_steps == ESteps.QueryCachePackageVersion) if (_steps == ESteps.QueryCachePackageVersion)
{ {
if (_queryCachePackageVersionOp == null) if (_queryCachePackageVersionOp == null)
{ {
_queryCachePackageVersionOp = new QueryCachePackageVersionOperation(_impl.Persistent); _queryCachePackageVersionOp = new QueryCachePackageVersionOperation(_impl.Persistent);
OperationSystem.StartOperation(_impl.PackageName, _queryCachePackageVersionOp); OperationSystem.StartOperation(_impl.PackageName, _queryCachePackageVersionOp);
} }
if (_queryCachePackageVersionOp.IsDone == false) if (_queryCachePackageVersionOp.IsDone == false)
return; return;
if (_queryCachePackageVersionOp.Status == EOperationStatus.Succeed) if (_queryCachePackageVersionOp.Status == EOperationStatus.Succeed)
{ {
_steps = ESteps.TryLoadCacheManifest; _steps = ESteps.TryLoadCacheManifest;
} }
else else
{ {
_steps = ESteps.QueryBuildinPackageVersion; _steps = ESteps.QueryBuildinPackageVersion;
} }
} }
if (_steps == ESteps.TryLoadCacheManifest) if (_steps == ESteps.TryLoadCacheManifest)
{ {
if (_loadCacheManifestOp == null) if (_loadCacheManifestOp == null)
{ {
_loadCacheManifestOp = new LoadCacheManifestOperation(_impl.Persistent, _queryCachePackageVersionOp.PackageVersion); _loadCacheManifestOp = new LoadCacheManifestOperation(_impl.Persistent, _queryCachePackageVersionOp.PackageVersion);
OperationSystem.StartOperation(_impl.PackageName, _loadCacheManifestOp); OperationSystem.StartOperation(_impl.PackageName, _loadCacheManifestOp);
} }
if (_loadCacheManifestOp.IsDone == false) if (_loadCacheManifestOp.IsDone == false)
return; return;
if (_loadCacheManifestOp.Status == EOperationStatus.Succeed) if (_loadCacheManifestOp.Status == EOperationStatus.Succeed)
{ {
PackageVersion = _loadCacheManifestOp.Manifest.PackageVersion; PackageVersion = _loadCacheManifestOp.Manifest.PackageVersion;
_impl.ActiveManifest = _loadCacheManifestOp.Manifest; _impl.ActiveManifest = _loadCacheManifestOp.Manifest;
_steps = ESteps.PackageCaching; _steps = ESteps.PackageCaching;
} }
else else
{ {
_steps = ESteps.QueryBuildinPackageVersion; _steps = ESteps.QueryBuildinPackageVersion;
} }
} }
if (_steps == ESteps.QueryBuildinPackageVersion) if (_steps == ESteps.QueryBuildinPackageVersion)
{ {
if (_queryBuildinPackageVersionOp == null) if (_queryBuildinPackageVersionOp == null)
{ {
_queryBuildinPackageVersionOp = new QueryBuildinPackageVersionOperation(_impl.Persistent); _queryBuildinPackageVersionOp = new QueryBuildinPackageVersionOperation(_impl.Persistent);
OperationSystem.StartOperation(_impl.PackageName, _queryBuildinPackageVersionOp); OperationSystem.StartOperation(_impl.PackageName, _queryBuildinPackageVersionOp);
} }
if (_queryBuildinPackageVersionOp.IsDone == false) if (_queryBuildinPackageVersionOp.IsDone == false)
return; return;
if (_queryBuildinPackageVersionOp.Status == EOperationStatus.Succeed) if (_queryBuildinPackageVersionOp.Status == EOperationStatus.Succeed)
{ {
_steps = ESteps.UnpackBuildinManifest; _steps = ESteps.UnpackBuildinManifest;
} }
else else
{ {
// 注意为了兼容MOD模式初始化动态新增的包裹的时候如果内置清单不存在也不需要报错 // 注意为了兼容MOD模式初始化动态新增的包裹的时候如果内置清单不存在也不需要报错
_steps = ESteps.PackageCaching; _steps = ESteps.PackageCaching;
string error = _queryBuildinPackageVersionOp.Error; string error = _queryBuildinPackageVersionOp.Error;
YooLogger.Log($"Failed to load buildin package version file : {error}"); YooLogger.Log($"Failed to load buildin package version file : {error}");
} }
} }
if (_steps == ESteps.UnpackBuildinManifest) if (_steps == ESteps.UnpackBuildinManifest)
{ {
if (_unpackBuildinManifestOp == null) if (_unpackBuildinManifestOp == null)
{ {
_unpackBuildinManifestOp = new UnpackBuildinManifestOperation(_impl.Persistent, _queryBuildinPackageVersionOp.PackageVersion); _unpackBuildinManifestOp = new UnpackBuildinManifestOperation(_impl.Persistent, _queryBuildinPackageVersionOp.PackageVersion);
OperationSystem.StartOperation(_impl.PackageName, _unpackBuildinManifestOp); OperationSystem.StartOperation(_impl.PackageName, _unpackBuildinManifestOp);
} }
if (_unpackBuildinManifestOp.IsDone == false) if (_unpackBuildinManifestOp.IsDone == false)
return; return;
if (_unpackBuildinManifestOp.Status == EOperationStatus.Succeed) if (_unpackBuildinManifestOp.Status == EOperationStatus.Succeed)
{ {
_steps = ESteps.LoadBuildinManifest; _steps = ESteps.LoadBuildinManifest;
} }
else else
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = _unpackBuildinManifestOp.Error; Error = _unpackBuildinManifestOp.Error;
} }
} }
if (_steps == ESteps.LoadBuildinManifest) if (_steps == ESteps.LoadBuildinManifest)
{ {
if (_loadBuildinManifestOp == null) if (_loadBuildinManifestOp == null)
{ {
_loadBuildinManifestOp = new LoadBuildinManifestOperation(_impl.Persistent, _queryBuildinPackageVersionOp.PackageVersion); _loadBuildinManifestOp = new LoadBuildinManifestOperation(_impl.Persistent, _queryBuildinPackageVersionOp.PackageVersion);
OperationSystem.StartOperation(_impl.PackageName, _loadBuildinManifestOp); OperationSystem.StartOperation(_impl.PackageName, _loadBuildinManifestOp);
} }
Progress = _loadBuildinManifestOp.Progress; Progress = _loadBuildinManifestOp.Progress;
if (_loadBuildinManifestOp.IsDone == false) if (_loadBuildinManifestOp.IsDone == false)
return; return;
if (_loadBuildinManifestOp.Status == EOperationStatus.Succeed) if (_loadBuildinManifestOp.Status == EOperationStatus.Succeed)
{ {
PackageVersion = _loadBuildinManifestOp.Manifest.PackageVersion; PackageVersion = _loadBuildinManifestOp.Manifest.PackageVersion;
_impl.ActiveManifest = _loadBuildinManifestOp.Manifest; _impl.ActiveManifest = _loadBuildinManifestOp.Manifest;
_steps = ESteps.PackageCaching; _steps = ESteps.PackageCaching;
} }
else else
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = _loadBuildinManifestOp.Error; Error = _loadBuildinManifestOp.Error;
} }
} }
if (_steps == ESteps.PackageCaching) if (_steps == ESteps.PackageCaching)
{ {
if (_cachingOperation == null) if (_cachingOperation == null)
{ {
_cachingOperation = new PackageCachingOperation(_impl.Persistent, _impl.Cache); _cachingOperation = new PackageCachingOperation(_impl.Persistent, _impl.Cache);
OperationSystem.StartOperation(_impl.PackageName,_cachingOperation); OperationSystem.StartOperation(_impl.PackageName, _cachingOperation);
} }
Progress = _cachingOperation.Progress; Progress = _cachingOperation.Progress;
if (_cachingOperation.IsDone) if (_cachingOperation.IsDone)
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
} }
} }
} }
/// <summary> /// <summary>
/// WebGL运行模式的初始化操作 /// WebGL运行模式的初始化操作
/// </summary> /// </summary>
internal sealed class WebPlayModeInitializationOperation : InitializationOperation internal sealed class WebPlayModeInitializationOperation : InitializationOperation
{ {
private enum ESteps private enum ESteps
{ {
None, None,
QueryWebPackageVersion, QueryWebPackageVersion,
LoadWebManifest, LoadWebManifest,
Done, Done,
} }
private readonly WebPlayModeImpl _impl; private readonly WebPlayModeImpl _impl;
private QueryBuildinPackageVersionOperation _queryWebPackageVersionOp; private QueryBuildinPackageVersionOperation _queryWebPackageVersionOp;
private LoadBuildinManifestOperation _loadWebManifestOp; private LoadBuildinManifestOperation _loadWebManifestOp;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
internal WebPlayModeInitializationOperation(WebPlayModeImpl impl) internal WebPlayModeInitializationOperation(WebPlayModeImpl impl)
{ {
_impl = impl; _impl = impl;
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
_steps = ESteps.QueryWebPackageVersion; _steps = ESteps.QueryWebPackageVersion;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
if (_steps == ESteps.None || _steps == ESteps.Done) if (_steps == ESteps.None || _steps == ESteps.Done)
return; return;
if (_steps == ESteps.QueryWebPackageVersion) if (_steps == ESteps.QueryWebPackageVersion)
{ {
if (_queryWebPackageVersionOp == null) if (_queryWebPackageVersionOp == null)
{ {
_queryWebPackageVersionOp = new QueryBuildinPackageVersionOperation(_impl.Persistent); _queryWebPackageVersionOp = new QueryBuildinPackageVersionOperation(_impl.Persistent);
OperationSystem.StartOperation(_impl.PackageName, _queryWebPackageVersionOp); OperationSystem.StartOperation(_impl.PackageName, _queryWebPackageVersionOp);
} }
if (_queryWebPackageVersionOp.IsDone == false) if (_queryWebPackageVersionOp.IsDone == false)
return; return;
if (_queryWebPackageVersionOp.Status == EOperationStatus.Succeed) if (_queryWebPackageVersionOp.Status == EOperationStatus.Succeed)
{ {
_steps = ESteps.LoadWebManifest; _steps = ESteps.LoadWebManifest;
} }
else else
{ {
// 注意WebGL平台可能因为网络的原因会导致请求失败。如果内置清单不存在或者超时也不需要报错 // 注意WebGL平台可能因为网络的原因会导致请求失败。如果内置清单不存在或者超时也不需要报错
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
string error = _queryWebPackageVersionOp.Error; string error = _queryWebPackageVersionOp.Error;
YooLogger.Log($"Failed to load web package version file : {error}"); YooLogger.Log($"Failed to load web package version file : {error}");
} }
} }
if (_steps == ESteps.LoadWebManifest) if (_steps == ESteps.LoadWebManifest)
{ {
if (_loadWebManifestOp == null) if (_loadWebManifestOp == null)
{ {
_loadWebManifestOp = new LoadBuildinManifestOperation(_impl.Persistent, _queryWebPackageVersionOp.PackageVersion); _loadWebManifestOp = new LoadBuildinManifestOperation(_impl.Persistent, _queryWebPackageVersionOp.PackageVersion);
OperationSystem.StartOperation(_impl.PackageName, _loadWebManifestOp); OperationSystem.StartOperation(_impl.PackageName, _loadWebManifestOp);
} }
Progress = _loadWebManifestOp.Progress; Progress = _loadWebManifestOp.Progress;
if (_loadWebManifestOp.IsDone == false) if (_loadWebManifestOp.IsDone == false)
return; return;
if (_loadWebManifestOp.Status == EOperationStatus.Succeed) if (_loadWebManifestOp.Status == EOperationStatus.Succeed)
{ {
PackageVersion = _loadWebManifestOp.Manifest.PackageVersion; PackageVersion = _loadWebManifestOp.Manifest.PackageVersion;
_impl.ActiveManifest = _loadWebManifestOp.Manifest; _impl.ActiveManifest = _loadWebManifestOp.Manifest;
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
else else
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = _loadWebManifestOp.Error; Error = _loadWebManifestOp.Error;
} }
} }
} }
} }
/// <summary> /// <summary>
/// 应用程序水印 /// 应用程序水印
/// </summary> /// </summary>
internal class AppFootPrint internal class AppFootPrint
{ {
private PersistentManager _persistent; private PersistentManager _persistent;
private string _footPrint; private string _footPrint;
public AppFootPrint(PersistentManager persistent) public AppFootPrint(PersistentManager persistent)
{ {
_persistent = persistent; _persistent = persistent;
} }
/// <summary> /// <summary>
/// 读取应用程序水印 /// 读取应用程序水印
/// </summary> /// </summary>
public void Load(string packageName) public void Load(string packageName)
{ {
string footPrintFilePath = _persistent.SandboxAppFootPrintFilePath; string footPrintFilePath = _persistent.SandboxAppFootPrintFilePath;
if (File.Exists(footPrintFilePath)) if (File.Exists(footPrintFilePath))
{ {
_footPrint = FileUtility.ReadAllText(footPrintFilePath); _footPrint = FileUtility.ReadAllText(footPrintFilePath);
} }
else else
{ {
Coverage(packageName); Coverage(packageName);
} }
} }
/// <summary> /// <summary>
/// 检测水印是否发生变化 /// 检测水印是否发生变化
/// </summary> /// </summary>
public bool IsDirty() public bool IsDirty()
{ {
#if UNITY_EDITOR #if UNITY_EDITOR
return _footPrint != Application.version; return _footPrint != Application.version;
#else #else
return _footPrint != Application.buildGUID; return _footPrint != Application.buildGUID;
#endif #endif
} }
/// <summary> /// <summary>
/// 覆盖掉水印 /// 覆盖掉水印
/// </summary> /// </summary>
public void Coverage(string packageName) public void Coverage(string packageName)
{ {
#if UNITY_EDITOR #if UNITY_EDITOR
_footPrint = Application.version; _footPrint = Application.version;
#else #else
_footPrint = Application.buildGUID; _footPrint = Application.buildGUID;
#endif #endif
string footPrintFilePath = _persistent.SandboxAppFootPrintFilePath; string footPrintFilePath = _persistent.SandboxAppFootPrintFilePath;
FileUtility.WriteAllText(footPrintFilePath, _footPrint); FileUtility.WriteAllText(footPrintFilePath, _footPrint);
YooLogger.Log($"Save application foot print : {_footPrint}"); YooLogger.Log($"Save application foot print : {_footPrint}");
} }
} }
} }

View File

@ -4,237 +4,237 @@ using System.Collections.Generic;
namespace YooAsset namespace YooAsset
{ {
internal class DeserializeManifestOperation : AsyncOperationBase internal class DeserializeManifestOperation : AsyncOperationBase
{ {
private enum ESteps private enum ESteps
{ {
None, None,
DeserializeFileHeader, DeserializeFileHeader,
PrepareAssetList, PrepareAssetList,
DeserializeAssetList, DeserializeAssetList,
PrepareBundleList, PrepareBundleList,
DeserializeBundleList, DeserializeBundleList,
Done, Done,
} }
private readonly BufferReader _buffer; private readonly BufferReader _buffer;
private int _packageAssetCount; private int _packageAssetCount;
private int _packageBundleCount; private int _packageBundleCount;
private int _progressTotalValue; private int _progressTotalValue;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
/// <summary> /// <summary>
/// 解析的清单实例 /// 解析的清单实例
/// </summary> /// </summary>
public PackageManifest Manifest { private set; get; } public PackageManifest Manifest { private set; get; }
public DeserializeManifestOperation(byte[] binaryData) public DeserializeManifestOperation(byte[] binaryData)
{ {
_buffer = new BufferReader(binaryData); _buffer = new BufferReader(binaryData);
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
_steps = ESteps.DeserializeFileHeader; _steps = ESteps.DeserializeFileHeader;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
if (_steps == ESteps.None || _steps == ESteps.Done) if (_steps == ESteps.None || _steps == ESteps.Done)
return; return;
try try
{ {
if (_steps == ESteps.DeserializeFileHeader) if (_steps == ESteps.DeserializeFileHeader)
{ {
if (_buffer.IsValid == false) if (_buffer.IsValid == false)
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = "Buffer is invalid !"; Error = "Buffer is invalid !";
return; return;
} }
// 读取文件标记 // 读取文件标记
uint fileSign = _buffer.ReadUInt32(); uint fileSign = _buffer.ReadUInt32();
if (fileSign != YooAssetSettings.ManifestFileSign) if (fileSign != YooAssetSettings.ManifestFileSign)
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = "The manifest file format is invalid !"; Error = "The manifest file format is invalid !";
return; return;
} }
// 读取文件版本 // 读取文件版本
string fileVersion = _buffer.ReadUTF8(); string fileVersion = _buffer.ReadUTF8();
if (fileVersion != YooAssetSettings.ManifestFileVersion) if (fileVersion != YooAssetSettings.ManifestFileVersion)
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = $"The manifest file version are not compatible : {fileVersion} != {YooAssetSettings.ManifestFileVersion}"; Error = $"The manifest file version are not compatible : {fileVersion} != {YooAssetSettings.ManifestFileVersion}";
return; return;
} }
// 读取文件头信息 // 读取文件头信息
Manifest = new PackageManifest(); Manifest = new PackageManifest();
Manifest.FileVersion = fileVersion; Manifest.FileVersion = fileVersion;
Manifest.EnableAddressable = _buffer.ReadBool(); Manifest.EnableAddressable = _buffer.ReadBool();
Manifest.LocationToLower = _buffer.ReadBool(); Manifest.LocationToLower = _buffer.ReadBool();
Manifest.IncludeAssetGUID = _buffer.ReadBool(); Manifest.IncludeAssetGUID = _buffer.ReadBool();
Manifest.OutputNameStyle = _buffer.ReadInt32(); Manifest.OutputNameStyle = _buffer.ReadInt32();
Manifest.BuildPipeline = _buffer.ReadUTF8(); Manifest.BuildPipeline = _buffer.ReadUTF8();
Manifest.PackageName = _buffer.ReadUTF8(); Manifest.PackageName = _buffer.ReadUTF8();
Manifest.PackageVersion = _buffer.ReadUTF8(); Manifest.PackageVersion = _buffer.ReadUTF8();
// 检测配置 // 检测配置
if (Manifest.EnableAddressable && Manifest.LocationToLower) if (Manifest.EnableAddressable && Manifest.LocationToLower)
throw new System.Exception("Addressable not support location to lower !"); throw new System.Exception("Addressable not support location to lower !");
_steps = ESteps.PrepareAssetList; _steps = ESteps.PrepareAssetList;
} }
if (_steps == ESteps.PrepareAssetList) if (_steps == ESteps.PrepareAssetList)
{ {
_packageAssetCount = _buffer.ReadInt32(); _packageAssetCount = _buffer.ReadInt32();
Manifest.AssetList = new List<PackageAsset>(_packageAssetCount); Manifest.AssetList = new List<PackageAsset>(_packageAssetCount);
Manifest.AssetDic = new Dictionary<string, PackageAsset>(_packageAssetCount); Manifest.AssetDic = new Dictionary<string, PackageAsset>(_packageAssetCount);
if (Manifest.EnableAddressable) if (Manifest.EnableAddressable)
Manifest.AssetPathMapping1 = new Dictionary<string, string>(_packageAssetCount * 3); Manifest.AssetPathMapping1 = new Dictionary<string, string>(_packageAssetCount * 3);
else else
Manifest.AssetPathMapping1 = new Dictionary<string, string>(_packageAssetCount * 2); Manifest.AssetPathMapping1 = new Dictionary<string, string>(_packageAssetCount * 2);
if (Manifest.IncludeAssetGUID) if (Manifest.IncludeAssetGUID)
Manifest.AssetPathMapping2 = new Dictionary<string, string>(_packageAssetCount); Manifest.AssetPathMapping2 = new Dictionary<string, string>(_packageAssetCount);
else else
Manifest.AssetPathMapping2 = new Dictionary<string, string>(); Manifest.AssetPathMapping2 = new Dictionary<string, string>();
_progressTotalValue = _packageAssetCount; _progressTotalValue = _packageAssetCount;
_steps = ESteps.DeserializeAssetList; _steps = ESteps.DeserializeAssetList;
} }
if (_steps == ESteps.DeserializeAssetList) if (_steps == ESteps.DeserializeAssetList)
{ {
while (_packageAssetCount > 0) while (_packageAssetCount > 0)
{ {
var packageAsset = new PackageAsset(); var packageAsset = new PackageAsset();
packageAsset.Address = _buffer.ReadUTF8(); packageAsset.Address = _buffer.ReadUTF8();
packageAsset.AssetPath = _buffer.ReadUTF8(); packageAsset.AssetPath = _buffer.ReadUTF8();
packageAsset.AssetGUID = _buffer.ReadUTF8(); packageAsset.AssetGUID = _buffer.ReadUTF8();
packageAsset.AssetTags = _buffer.ReadUTF8Array(); packageAsset.AssetTags = _buffer.ReadUTF8Array();
packageAsset.BundleID = _buffer.ReadInt32(); packageAsset.BundleID = _buffer.ReadInt32();
Manifest.AssetList.Add(packageAsset); Manifest.AssetList.Add(packageAsset);
// 注意:我们不允许原始路径存在重名 // 注意:我们不允许原始路径存在重名
string assetPath = packageAsset.AssetPath; string assetPath = packageAsset.AssetPath;
if (Manifest.AssetDic.ContainsKey(assetPath)) if (Manifest.AssetDic.ContainsKey(assetPath))
throw new System.Exception($"AssetPath have existed : {assetPath}"); throw new System.Exception($"AssetPath have existed : {assetPath}");
else else
Manifest.AssetDic.Add(assetPath, packageAsset); Manifest.AssetDic.Add(assetPath, packageAsset);
// 填充AssetPathMapping1 // 填充AssetPathMapping1
{ {
string location = packageAsset.AssetPath; string location = packageAsset.AssetPath;
if (Manifest.LocationToLower) if (Manifest.LocationToLower)
location = location.ToLower(); location = location.ToLower();
// 添加原生路径的映射 // 添加原生路径的映射
if (Manifest.AssetPathMapping1.ContainsKey(location)) if (Manifest.AssetPathMapping1.ContainsKey(location))
throw new System.Exception($"Location have existed : {location}"); throw new System.Exception($"Location have existed : {location}");
else else
Manifest.AssetPathMapping1.Add(location, packageAsset.AssetPath); Manifest.AssetPathMapping1.Add(location, packageAsset.AssetPath);
// 添加无后缀名路径的映射 // 添加无后缀名路径的映射
if (Path.HasExtension(location)) if (Path.HasExtension(location))
{ {
string locationWithoutExtension = PathUtility.RemoveExtension(location); string locationWithoutExtension = PathUtility.RemoveExtension(location);
if (Manifest.AssetPathMapping1.ContainsKey(locationWithoutExtension)) if (Manifest.AssetPathMapping1.ContainsKey(locationWithoutExtension))
YooLogger.Warning($"Location have existed : {locationWithoutExtension}"); YooLogger.Warning($"Location have existed : {locationWithoutExtension}");
else else
Manifest.AssetPathMapping1.Add(locationWithoutExtension, packageAsset.AssetPath); Manifest.AssetPathMapping1.Add(locationWithoutExtension, packageAsset.AssetPath);
} }
} }
if (Manifest.EnableAddressable) if (Manifest.EnableAddressable)
{ {
string location = packageAsset.Address; string location = packageAsset.Address;
if (string.IsNullOrEmpty(location) == false) if (string.IsNullOrEmpty(location) == false)
{ {
if (Manifest.AssetPathMapping1.ContainsKey(location)) if (Manifest.AssetPathMapping1.ContainsKey(location))
throw new System.Exception($"Location have existed : {location}"); throw new System.Exception($"Location have existed : {location}");
else else
Manifest.AssetPathMapping1.Add(location, packageAsset.AssetPath); Manifest.AssetPathMapping1.Add(location, packageAsset.AssetPath);
} }
} }
// 填充AssetPathMapping2 // 填充AssetPathMapping2
if (Manifest.IncludeAssetGUID) if (Manifest.IncludeAssetGUID)
{ {
if (Manifest.AssetPathMapping2.ContainsKey(packageAsset.AssetGUID)) if (Manifest.AssetPathMapping2.ContainsKey(packageAsset.AssetGUID))
throw new System.Exception($"AssetGUID have existed : {packageAsset.AssetGUID}"); throw new System.Exception($"AssetGUID have existed : {packageAsset.AssetGUID}");
else else
Manifest.AssetPathMapping2.Add(packageAsset.AssetGUID, packageAsset.AssetPath); Manifest.AssetPathMapping2.Add(packageAsset.AssetGUID, packageAsset.AssetPath);
} }
_packageAssetCount--; _packageAssetCount--;
Progress = 1f - _packageAssetCount / _progressTotalValue; Progress = 1f - _packageAssetCount / _progressTotalValue;
if (OperationSystem.IsBusy) if (OperationSystem.IsBusy)
break; break;
} }
if (_packageAssetCount <= 0) if (_packageAssetCount <= 0)
{ {
_steps = ESteps.PrepareBundleList; _steps = ESteps.PrepareBundleList;
} }
} }
if (_steps == ESteps.PrepareBundleList) if (_steps == ESteps.PrepareBundleList)
{ {
_packageBundleCount = _buffer.ReadInt32(); _packageBundleCount = _buffer.ReadInt32();
Manifest.BundleList = new List<PackageBundle>(_packageBundleCount); Manifest.BundleList = new List<PackageBundle>(_packageBundleCount);
Manifest.BundleDic1 = new Dictionary<string, PackageBundle>(_packageBundleCount); Manifest.BundleDic1 = new Dictionary<string, PackageBundle>(_packageBundleCount);
Manifest.BundleDic2 = new Dictionary<string, PackageBundle>(_packageBundleCount); Manifest.BundleDic2 = new Dictionary<string, PackageBundle>(_packageBundleCount);
_progressTotalValue = _packageBundleCount; _progressTotalValue = _packageBundleCount;
_steps = ESteps.DeserializeBundleList; _steps = ESteps.DeserializeBundleList;
} }
if (_steps == ESteps.DeserializeBundleList) if (_steps == ESteps.DeserializeBundleList)
{ {
while (_packageBundleCount > 0) while (_packageBundleCount > 0)
{ {
var packageBundle = new PackageBundle(); var packageBundle = new PackageBundle();
packageBundle.BundleName = _buffer.ReadUTF8(); packageBundle.BundleName = _buffer.ReadUTF8();
packageBundle.UnityCRC = _buffer.ReadUInt32(); packageBundle.UnityCRC = _buffer.ReadUInt32();
packageBundle.FileHash = _buffer.ReadUTF8(); packageBundle.FileHash = _buffer.ReadUTF8();
packageBundle.FileCRC = _buffer.ReadUTF8(); packageBundle.FileCRC = _buffer.ReadUTF8();
packageBundle.FileSize = _buffer.ReadInt64(); packageBundle.FileSize = _buffer.ReadInt64();
packageBundle.Encrypted = _buffer.ReadBool(); packageBundle.Encrypted = _buffer.ReadBool();
packageBundle.Tags = _buffer.ReadUTF8Array(); packageBundle.Tags = _buffer.ReadUTF8Array();
packageBundle.DependIDs = _buffer.ReadInt32Array(); packageBundle.DependIDs = _buffer.ReadInt32Array();
packageBundle.ParseBundle(Manifest); packageBundle.ParseBundle(Manifest);
Manifest.BundleList.Add(packageBundle); Manifest.BundleList.Add(packageBundle);
Manifest.BundleDic1.Add(packageBundle.BundleName, packageBundle); Manifest.BundleDic1.Add(packageBundle.BundleName, packageBundle);
Manifest.BundleDic2.Add(packageBundle.FileName, packageBundle); Manifest.BundleDic2.Add(packageBundle.FileName, packageBundle);
// 注意原始文件可能存在相同的CacheGUID // 注意原始文件可能存在相同的CacheGUID
if (Manifest.CacheGUIDs.Contains(packageBundle.CacheGUID) == false) if (Manifest.CacheGUIDs.Contains(packageBundle.CacheGUID) == false)
Manifest.CacheGUIDs.Add(packageBundle.CacheGUID); Manifest.CacheGUIDs.Add(packageBundle.CacheGUID);
_packageBundleCount--; _packageBundleCount--;
Progress = 1f - _packageBundleCount / _progressTotalValue; Progress = 1f - _packageBundleCount / _progressTotalValue;
if (OperationSystem.IsBusy) if (OperationSystem.IsBusy)
break; break;
} }
if (_packageBundleCount <= 0) if (_packageBundleCount <= 0)
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
} }
} }
catch (System.Exception e) catch (System.Exception e)
{ {
Manifest = null; Manifest = null;
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = e.Message; Error = e.Message;
} }
} }
} }
} }

View File

@ -1,113 +1,113 @@
 
namespace YooAsset namespace YooAsset
{ {
internal class DownloadManifestOperation : AsyncOperationBase internal class DownloadManifestOperation : AsyncOperationBase
{ {
private enum ESteps private enum ESteps
{ {
None, None,
DownloadPackageHashFile, DownloadPackageHashFile,
DownloadManifestFile, DownloadManifestFile,
Done, Done,
} }
private readonly PersistentManager _persistent;
private readonly IRemoteServices _remoteServices;
private readonly string _packageVersion;
private readonly int _timeout;
private UnityWebFileRequester _downloader1;
private UnityWebFileRequester _downloader2;
private ESteps _steps = ESteps.None;
private int _requestCount = 0;
internal DownloadManifestOperation(PersistentManager persistent, IRemoteServices remoteServices, string packageVersion, int timeout) private readonly PersistentManager _persistent;
{ private readonly IRemoteServices _remoteServices;
_persistent = persistent; private readonly string _packageVersion;
_remoteServices = remoteServices; private readonly int _timeout;
_packageVersion = packageVersion; private UnityWebFileRequester _downloader1;
_timeout = timeout; private UnityWebFileRequester _downloader2;
} private ESteps _steps = ESteps.None;
internal override void InternalOnStart() private int _requestCount = 0;
{
_requestCount = RequestHelper.GetRequestFailedCount(_persistent.PackageName, nameof(DownloadManifestOperation));
_steps = ESteps.DownloadPackageHashFile;
}
internal override void InternalOnUpdate()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.DownloadPackageHashFile) internal DownloadManifestOperation(PersistentManager persistent, IRemoteServices remoteServices, string packageVersion, int timeout)
{ {
if (_downloader1 == null) _persistent = persistent;
{ _remoteServices = remoteServices;
string savePath = _persistent.GetSandboxPackageHashFilePath(_packageVersion); _packageVersion = packageVersion;
string fileName = YooAssetSettingsData.GetPackageHashFileName(_persistent.PackageName, _packageVersion); _timeout = timeout;
string webURL = GetDownloadRequestURL(fileName); }
YooLogger.Log($"Beginning to download package hash file : {webURL}"); internal override void InternalOnStart()
_downloader1 = new UnityWebFileRequester(); {
_downloader1.SendRequest(webURL, savePath, _timeout); _requestCount = RequestHelper.GetRequestFailedCount(_persistent.PackageName, nameof(DownloadManifestOperation));
} _steps = ESteps.DownloadPackageHashFile;
}
internal override void InternalOnUpdate()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
_downloader1.CheckTimeout(); if (_steps == ESteps.DownloadPackageHashFile)
if (_downloader1.IsDone() == false) {
return; if (_downloader1 == null)
{
string savePath = _persistent.GetSandboxPackageHashFilePath(_packageVersion);
string fileName = YooAssetSettingsData.GetPackageHashFileName(_persistent.PackageName, _packageVersion);
string webURL = GetDownloadRequestURL(fileName);
YooLogger.Log($"Beginning to download package hash file : {webURL}");
_downloader1 = new UnityWebFileRequester();
_downloader1.SendRequest(webURL, savePath, _timeout);
}
if (_downloader1.HasError()) _downloader1.CheckTimeout();
{ if (_downloader1.IsDone() == false)
_steps = ESteps.Done; return;
Status = EOperationStatus.Failed;
Error = _downloader1.GetError();
RequestHelper.RecordRequestFailed(_persistent.PackageName, nameof(DownloadManifestOperation));
}
else
{
_steps = ESteps.DownloadManifestFile;
}
_downloader1.Dispose(); if (_downloader1.HasError())
} {
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = _downloader1.GetError();
RequestHelper.RecordRequestFailed(_persistent.PackageName, nameof(DownloadManifestOperation));
}
else
{
_steps = ESteps.DownloadManifestFile;
}
if (_steps == ESteps.DownloadManifestFile) _downloader1.Dispose();
{ }
if (_downloader2 == null)
{
string savePath = _persistent.GetSandboxPackageManifestFilePath(_packageVersion);
string fileName = YooAssetSettingsData.GetManifestBinaryFileName(_persistent.PackageName, _packageVersion);
string webURL = GetDownloadRequestURL(fileName);
YooLogger.Log($"Beginning to download package manifest file : {webURL}");
_downloader2 = new UnityWebFileRequester();
_downloader2.SendRequest(webURL, savePath, _timeout);
}
_downloader2.CheckTimeout(); if (_steps == ESteps.DownloadManifestFile)
if (_downloader2.IsDone() == false) {
return; if (_downloader2 == null)
{
string savePath = _persistent.GetSandboxPackageManifestFilePath(_packageVersion);
string fileName = YooAssetSettingsData.GetManifestBinaryFileName(_persistent.PackageName, _packageVersion);
string webURL = GetDownloadRequestURL(fileName);
YooLogger.Log($"Beginning to download package manifest file : {webURL}");
_downloader2 = new UnityWebFileRequester();
_downloader2.SendRequest(webURL, savePath, _timeout);
}
if (_downloader2.HasError()) _downloader2.CheckTimeout();
{ if (_downloader2.IsDone() == false)
_steps = ESteps.Done; return;
Status = EOperationStatus.Failed;
Error = _downloader2.GetError();
RequestHelper.RecordRequestFailed(_persistent.PackageName, nameof(DownloadManifestOperation));
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
_downloader2.Dispose(); if (_downloader2.HasError())
} {
} _steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = _downloader2.GetError();
RequestHelper.RecordRequestFailed(_persistent.PackageName, nameof(DownloadManifestOperation));
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
private string GetDownloadRequestURL(string fileName) _downloader2.Dispose();
{ }
// 轮流返回请求地址 }
if (_requestCount % 2 == 0)
return _remoteServices.GetRemoteMainURL(fileName); private string GetDownloadRequestURL(string fileName)
else {
return _remoteServices.GetRemoteFallbackURL(fileName); // 轮流返回请求地址
} if (_requestCount % 2 == 0)
} return _remoteServices.GetRemoteMainURL(fileName);
else
return _remoteServices.GetRemoteFallbackURL(fileName);
}
}
} }

View File

@ -1,91 +1,91 @@
 
namespace YooAsset namespace YooAsset
{ {
internal class LoadBuildinManifestOperation : AsyncOperationBase internal class LoadBuildinManifestOperation : AsyncOperationBase
{ {
private enum ESteps private enum ESteps
{ {
None, None,
LoadBuildinManifest, LoadBuildinManifest,
CheckDeserializeManifest, CheckDeserializeManifest,
Done, Done,
} }
private readonly PersistentManager _persistent; private readonly PersistentManager _persistent;
private readonly string _buildinPackageVersion; private readonly string _buildinPackageVersion;
private UnityWebDataRequester _downloader; private UnityWebDataRequester _downloader;
private DeserializeManifestOperation _deserializer; private DeserializeManifestOperation _deserializer;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
/// <summary> /// <summary>
/// 加载的清单实例 /// 加载的清单实例
/// </summary> /// </summary>
public PackageManifest Manifest { private set; get; } public PackageManifest Manifest { private set; get; }
public LoadBuildinManifestOperation(PersistentManager persistent, string buildinPackageVersion) public LoadBuildinManifestOperation(PersistentManager persistent, string buildinPackageVersion)
{ {
_persistent = persistent; _persistent = persistent;
_buildinPackageVersion = buildinPackageVersion; _buildinPackageVersion = buildinPackageVersion;
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
_steps = ESteps.LoadBuildinManifest; _steps = ESteps.LoadBuildinManifest;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
if (_steps == ESteps.None || _steps == ESteps.Done) if (_steps == ESteps.None || _steps == ESteps.Done)
return; return;
if (_steps == ESteps.LoadBuildinManifest) if (_steps == ESteps.LoadBuildinManifest)
{ {
if (_downloader == null) if (_downloader == null)
{ {
string filePath = _persistent.GetBuildinPackageManifestFilePath(_buildinPackageVersion); string filePath = _persistent.GetBuildinPackageManifestFilePath(_buildinPackageVersion);
string url = PersistentHelper.ConvertToWWWPath(filePath); string url = PersistentHelper.ConvertToWWWPath(filePath);
_downloader = new UnityWebDataRequester(); _downloader = new UnityWebDataRequester();
_downloader.SendRequest(url); _downloader.SendRequest(url);
} }
if (_downloader.IsDone() == false) if (_downloader.IsDone() == false)
return; return;
if (_downloader.HasError()) if (_downloader.HasError())
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = _downloader.GetError(); Error = _downloader.GetError();
} }
else else
{ {
byte[] bytesData = _downloader.GetData(); byte[] bytesData = _downloader.GetData();
_deserializer = new DeserializeManifestOperation(bytesData); _deserializer = new DeserializeManifestOperation(bytesData);
OperationSystem.StartOperation(_persistent.PackageName, _deserializer); OperationSystem.StartOperation(_persistent.PackageName, _deserializer);
_steps = ESteps.CheckDeserializeManifest; _steps = ESteps.CheckDeserializeManifest;
} }
_downloader.Dispose(); _downloader.Dispose();
} }
if (_steps == ESteps.CheckDeserializeManifest) if (_steps == ESteps.CheckDeserializeManifest)
{ {
Progress = _deserializer.Progress; Progress = _deserializer.Progress;
if (_deserializer.IsDone == false) if (_deserializer.IsDone == false)
return; return;
if (_deserializer.Status == EOperationStatus.Succeed) if (_deserializer.Status == EOperationStatus.Succeed)
{ {
Manifest = _deserializer.Manifest; Manifest = _deserializer.Manifest;
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
else else
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = _deserializer.Error; Error = _deserializer.Error;
} }
} }
} }
} }
} }

View File

@ -2,140 +2,140 @@
namespace YooAsset namespace YooAsset
{ {
internal class LoadCacheManifestOperation : AsyncOperationBase internal class LoadCacheManifestOperation : AsyncOperationBase
{ {
private enum ESteps private enum ESteps
{ {
None, None,
QueryCachePackageHash, QueryCachePackageHash,
VerifyFileHash, VerifyFileHash,
LoadCacheManifest, LoadCacheManifest,
CheckDeserializeManifest, CheckDeserializeManifest,
Done, Done,
} }
private readonly PersistentManager _persistent; private readonly PersistentManager _persistent;
private readonly string _packageVersion; private readonly string _packageVersion;
private QueryCachePackageHashOperation _queryCachePackageHashOp; private QueryCachePackageHashOperation _queryCachePackageHashOp;
private DeserializeManifestOperation _deserializer; private DeserializeManifestOperation _deserializer;
private string _manifestFilePath; private string _manifestFilePath;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
/// <summary> /// <summary>
/// 加载的清单实例 /// 加载的清单实例
/// </summary> /// </summary>
public PackageManifest Manifest { private set; get; } public PackageManifest Manifest { private set; get; }
public LoadCacheManifestOperation(PersistentManager persistent, string packageVersion) public LoadCacheManifestOperation(PersistentManager persistent, string packageVersion)
{ {
_persistent = persistent; _persistent = persistent;
_packageVersion = packageVersion; _packageVersion = packageVersion;
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
_steps = ESteps.QueryCachePackageHash; _steps = ESteps.QueryCachePackageHash;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
if (_steps == ESteps.None || _steps == ESteps.Done) if (_steps == ESteps.None || _steps == ESteps.Done)
return; return;
if (_steps == ESteps.QueryCachePackageHash) if (_steps == ESteps.QueryCachePackageHash)
{ {
if (_queryCachePackageHashOp == null) if (_queryCachePackageHashOp == null)
{ {
_queryCachePackageHashOp = new QueryCachePackageHashOperation(_persistent, _packageVersion); _queryCachePackageHashOp = new QueryCachePackageHashOperation(_persistent, _packageVersion);
OperationSystem.StartOperation(_persistent.PackageName, _queryCachePackageHashOp); OperationSystem.StartOperation(_persistent.PackageName, _queryCachePackageHashOp);
} }
if (_queryCachePackageHashOp.IsDone == false) if (_queryCachePackageHashOp.IsDone == false)
return; return;
if (_queryCachePackageHashOp.Status == EOperationStatus.Succeed) if (_queryCachePackageHashOp.Status == EOperationStatus.Succeed)
{ {
_steps = ESteps.VerifyFileHash; _steps = ESteps.VerifyFileHash;
} }
else else
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = _queryCachePackageHashOp.Error; Error = _queryCachePackageHashOp.Error;
ClearCacheFile(); ClearCacheFile();
} }
} }
if (_steps == ESteps.VerifyFileHash) if (_steps == ESteps.VerifyFileHash)
{ {
_manifestFilePath = _persistent.GetSandboxPackageManifestFilePath(_packageVersion); _manifestFilePath = _persistent.GetSandboxPackageManifestFilePath(_packageVersion);
if (File.Exists(_manifestFilePath) == false) if (File.Exists(_manifestFilePath) == false)
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = $"Not found cache manifest file : {_manifestFilePath}"; Error = $"Not found cache manifest file : {_manifestFilePath}";
ClearCacheFile(); ClearCacheFile();
return; return;
} }
string fileHash = HashUtility.FileMD5(_manifestFilePath); string fileHash = HashUtility.FileMD5(_manifestFilePath);
if (fileHash != _queryCachePackageHashOp.PackageHash) if (fileHash != _queryCachePackageHashOp.PackageHash)
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = "Failed to verify cache manifest file hash !"; Error = "Failed to verify cache manifest file hash !";
ClearCacheFile(); ClearCacheFile();
} }
else else
{ {
_steps = ESteps.LoadCacheManifest; _steps = ESteps.LoadCacheManifest;
} }
} }
if (_steps == ESteps.LoadCacheManifest) if (_steps == ESteps.LoadCacheManifest)
{ {
byte[] bytesData = File.ReadAllBytes(_manifestFilePath); byte[] bytesData = File.ReadAllBytes(_manifestFilePath);
_deserializer = new DeserializeManifestOperation(bytesData); _deserializer = new DeserializeManifestOperation(bytesData);
OperationSystem.StartOperation(_persistent.PackageName, _deserializer); OperationSystem.StartOperation(_persistent.PackageName, _deserializer);
_steps = ESteps.CheckDeserializeManifest; _steps = ESteps.CheckDeserializeManifest;
} }
if (_steps == ESteps.CheckDeserializeManifest) if (_steps == ESteps.CheckDeserializeManifest)
{ {
Progress = _deserializer.Progress; Progress = _deserializer.Progress;
if (_deserializer.IsDone == false) if (_deserializer.IsDone == false)
return; return;
if (_deserializer.Status == EOperationStatus.Succeed) if (_deserializer.Status == EOperationStatus.Succeed)
{ {
Manifest = _deserializer.Manifest; Manifest = _deserializer.Manifest;
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
else else
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = _deserializer.Error; Error = _deserializer.Error;
ClearCacheFile(); ClearCacheFile();
} }
} }
} }
private void ClearCacheFile() private void ClearCacheFile()
{ {
// 注意:如果加载沙盒内的清单报错,为了避免流程被卡住,主动把损坏的文件删除。 // 注意:如果加载沙盒内的清单报错,为了避免流程被卡住,主动把损坏的文件删除。
if (File.Exists(_manifestFilePath)) if (File.Exists(_manifestFilePath))
{ {
YooLogger.Warning($"Failed to load cache manifest file : {Error}"); YooLogger.Warning($"Failed to load cache manifest file : {Error}");
YooLogger.Warning($"Invalid cache manifest file have been removed : {_manifestFilePath}"); YooLogger.Warning($"Invalid cache manifest file have been removed : {_manifestFilePath}");
File.Delete(_manifestFilePath); File.Delete(_manifestFilePath);
} }
string hashFilePath = _persistent.GetSandboxPackageHashFilePath(_packageVersion); string hashFilePath = _persistent.GetSandboxPackageHashFilePath(_packageVersion);
if (File.Exists(hashFilePath)) if (File.Exists(hashFilePath))
{ {
File.Delete(hashFilePath); File.Delete(hashFilePath);
} }
} }
} }
} }

View File

@ -2,77 +2,77 @@
namespace YooAsset namespace YooAsset
{ {
internal class LoadEditorManifestOperation : AsyncOperationBase internal class LoadEditorManifestOperation : AsyncOperationBase
{ {
private enum ESteps private enum ESteps
{ {
None, None,
LoadEditorManifest, LoadEditorManifest,
CheckDeserializeManifest, CheckDeserializeManifest,
Done, Done,
} }
private readonly string _packageName; private readonly string _packageName;
private readonly string _manifestFilePath; private readonly string _manifestFilePath;
private DeserializeManifestOperation _deserializer; private DeserializeManifestOperation _deserializer;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
/// <summary> /// <summary>
/// 加载的清单实例 /// 加载的清单实例
/// </summary> /// </summary>
public PackageManifest Manifest { private set; get; } public PackageManifest Manifest { private set; get; }
public LoadEditorManifestOperation(string packageName, string manifestFilePath) public LoadEditorManifestOperation(string packageName, string manifestFilePath)
{ {
_packageName = packageName; _packageName = packageName;
_manifestFilePath = manifestFilePath; _manifestFilePath = manifestFilePath;
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
_steps = ESteps.LoadEditorManifest; _steps = ESteps.LoadEditorManifest;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
if (_steps == ESteps.None || _steps == ESteps.Done) if (_steps == ESteps.None || _steps == ESteps.Done)
return; return;
if (_steps == ESteps.LoadEditorManifest) if (_steps == ESteps.LoadEditorManifest)
{ {
if (File.Exists(_manifestFilePath) == false) if (File.Exists(_manifestFilePath) == false)
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = $"Not found simulation manifest file : {_manifestFilePath}"; Error = $"Not found simulation manifest file : {_manifestFilePath}";
return; return;
} }
YooLogger.Log($"Load editor manifest file : {_manifestFilePath}");
byte[] bytesData = FileUtility.ReadAllBytes(_manifestFilePath);
_deserializer = new DeserializeManifestOperation(bytesData);
OperationSystem.StartOperation(_packageName, _deserializer);
_steps = ESteps.CheckDeserializeManifest;
}
if (_steps == ESteps.CheckDeserializeManifest) YooLogger.Log($"Load editor manifest file : {_manifestFilePath}");
{ byte[] bytesData = FileUtility.ReadAllBytes(_manifestFilePath);
Progress = _deserializer.Progress; _deserializer = new DeserializeManifestOperation(bytesData);
if (_deserializer.IsDone == false) OperationSystem.StartOperation(_packageName, _deserializer);
return; _steps = ESteps.CheckDeserializeManifest;
}
if (_deserializer.Status == EOperationStatus.Succeed) if (_steps == ESteps.CheckDeserializeManifest)
{ {
Manifest = _deserializer.Manifest; Progress = _deserializer.Progress;
_steps = ESteps.Done; if (_deserializer.IsDone == false)
Status = EOperationStatus.Succeed; return;
}
else if (_deserializer.Status == EOperationStatus.Succeed)
{ {
_steps = ESteps.Done; Manifest = _deserializer.Manifest;
Status = EOperationStatus.Failed; _steps = ESteps.Done;
Error = _deserializer.Error; Status = EOperationStatus.Succeed;
} }
} else
} {
} _steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = _deserializer.Error;
}
}
}
}
} }

View File

@ -1,151 +1,151 @@
 
namespace YooAsset namespace YooAsset
{ {
internal class LoadRemoteManifestOperation : AsyncOperationBase internal class LoadRemoteManifestOperation : AsyncOperationBase
{ {
private enum ESteps private enum ESteps
{ {
None, None,
DownloadPackageHashFile, DownloadPackageHashFile,
DownloadManifestFile, DownloadManifestFile,
VerifyFileHash, VerifyFileHash,
CheckDeserializeManifest, CheckDeserializeManifest,
Done, Done,
} }
private readonly IRemoteServices _remoteServices; private readonly IRemoteServices _remoteServices;
private readonly string _packageName; private readonly string _packageName;
private readonly string _packageVersion; private readonly string _packageVersion;
private readonly int _timeout; private readonly int _timeout;
private QueryRemotePackageHashOperation _queryRemotePackageHashOp; private QueryRemotePackageHashOperation _queryRemotePackageHashOp;
private UnityWebDataRequester _downloader; private UnityWebDataRequester _downloader;
private DeserializeManifestOperation _deserializer; private DeserializeManifestOperation _deserializer;
private byte[] _fileData; private byte[] _fileData;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
private int _requestCount = 0; private int _requestCount = 0;
/// <summary> /// <summary>
/// 加载的清单实例 /// 加载的清单实例
/// </summary> /// </summary>
public PackageManifest Manifest { private set; get; } public PackageManifest Manifest { private set; get; }
internal LoadRemoteManifestOperation(IRemoteServices remoteServices, string packageName, string packageVersion, int timeout) internal LoadRemoteManifestOperation(IRemoteServices remoteServices, string packageName, string packageVersion, int timeout)
{ {
_remoteServices = remoteServices; _remoteServices = remoteServices;
_packageName = packageName; _packageName = packageName;
_packageVersion = packageVersion; _packageVersion = packageVersion;
_timeout = timeout; _timeout = timeout;
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
_requestCount = RequestHelper.GetRequestFailedCount(_packageName, nameof(LoadRemoteManifestOperation)); _requestCount = RequestHelper.GetRequestFailedCount(_packageName, nameof(LoadRemoteManifestOperation));
_steps = ESteps.DownloadPackageHashFile; _steps = ESteps.DownloadPackageHashFile;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
if (_steps == ESteps.None || _steps == ESteps.Done) if (_steps == ESteps.None || _steps == ESteps.Done)
return; return;
if (_steps == ESteps.DownloadPackageHashFile) if (_steps == ESteps.DownloadPackageHashFile)
{ {
if (_queryRemotePackageHashOp == null) if (_queryRemotePackageHashOp == null)
{ {
_queryRemotePackageHashOp = new QueryRemotePackageHashOperation(_remoteServices, _packageName, _packageVersion, _timeout); _queryRemotePackageHashOp = new QueryRemotePackageHashOperation(_remoteServices, _packageName, _packageVersion, _timeout);
OperationSystem.StartOperation(_packageName, _queryRemotePackageHashOp); OperationSystem.StartOperation(_packageName, _queryRemotePackageHashOp);
} }
if (_queryRemotePackageHashOp.IsDone == false) if (_queryRemotePackageHashOp.IsDone == false)
return; return;
if (_queryRemotePackageHashOp.Status == EOperationStatus.Succeed) if (_queryRemotePackageHashOp.Status == EOperationStatus.Succeed)
{ {
_steps = ESteps.DownloadManifestFile; _steps = ESteps.DownloadManifestFile;
} }
else else
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = _queryRemotePackageHashOp.Error; Error = _queryRemotePackageHashOp.Error;
} }
} }
if (_steps == ESteps.DownloadManifestFile) if (_steps == ESteps.DownloadManifestFile)
{ {
if (_downloader == null) if (_downloader == null)
{ {
string fileName = YooAssetSettingsData.GetManifestBinaryFileName(_packageName, _packageVersion); string fileName = YooAssetSettingsData.GetManifestBinaryFileName(_packageName, _packageVersion);
string webURL = GetDownloadRequestURL(fileName); string webURL = GetDownloadRequestURL(fileName);
YooLogger.Log($"Beginning to download manifest file : {webURL}"); YooLogger.Log($"Beginning to download manifest file : {webURL}");
_downloader = new UnityWebDataRequester(); _downloader = new UnityWebDataRequester();
_downloader.SendRequest(webURL, _timeout); _downloader.SendRequest(webURL, _timeout);
} }
_downloader.CheckTimeout(); _downloader.CheckTimeout();
if (_downloader.IsDone() == false) if (_downloader.IsDone() == false)
return; return;
if (_downloader.HasError()) if (_downloader.HasError())
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = _downloader.GetError(); Error = _downloader.GetError();
RequestHelper.RecordRequestFailed(_packageName, nameof(LoadRemoteManifestOperation)); RequestHelper.RecordRequestFailed(_packageName, nameof(LoadRemoteManifestOperation));
} }
else else
{ {
_fileData = _downloader.GetData(); _fileData = _downloader.GetData();
_steps = ESteps.VerifyFileHash; _steps = ESteps.VerifyFileHash;
} }
_downloader.Dispose(); _downloader.Dispose();
} }
if (_steps == ESteps.VerifyFileHash) if (_steps == ESteps.VerifyFileHash)
{ {
string fileHash = HashUtility.BytesMD5(_fileData); string fileHash = HashUtility.BytesMD5(_fileData);
if (fileHash != _queryRemotePackageHashOp.PackageHash) if (fileHash != _queryRemotePackageHashOp.PackageHash)
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = "Failed to verify remote manifest file hash !"; Error = "Failed to verify remote manifest file hash !";
} }
else else
{ {
_deserializer = new DeserializeManifestOperation(_fileData); _deserializer = new DeserializeManifestOperation(_fileData);
OperationSystem.StartOperation(_packageName, _deserializer); OperationSystem.StartOperation(_packageName, _deserializer);
_steps = ESteps.CheckDeserializeManifest; _steps = ESteps.CheckDeserializeManifest;
} }
} }
if (_steps == ESteps.CheckDeserializeManifest) if (_steps == ESteps.CheckDeserializeManifest)
{ {
Progress = _deserializer.Progress; Progress = _deserializer.Progress;
if (_deserializer.IsDone == false) if (_deserializer.IsDone == false)
return; return;
if (_deserializer.Status == EOperationStatus.Succeed) if (_deserializer.Status == EOperationStatus.Succeed)
{ {
Manifest = _deserializer.Manifest; Manifest = _deserializer.Manifest;
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
else else
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = _deserializer.Error; Error = _deserializer.Error;
} }
} }
} }
private string GetDownloadRequestURL(string fileName) private string GetDownloadRequestURL(string fileName)
{ {
// 轮流返回请求地址 // 轮流返回请求地址
if (_requestCount % 2 == 0) if (_requestCount % 2 == 0)
return _remoteServices.GetRemoteMainURL(fileName); return _remoteServices.GetRemoteMainURL(fileName);
else else
return _remoteServices.GetRemoteFallbackURL(fileName); return _remoteServices.GetRemoteFallbackURL(fileName);
} }
} }
} }

View File

@ -1,75 +1,75 @@
 
namespace YooAsset namespace YooAsset
{ {
internal class QueryBuildinPackageVersionOperation : AsyncOperationBase internal class QueryBuildinPackageVersionOperation : AsyncOperationBase
{ {
private enum ESteps private enum ESteps
{ {
None, None,
LoadBuildinPackageVersionFile, LoadBuildinPackageVersionFile,
Done, Done,
} }
private readonly PersistentManager _persistent; private readonly PersistentManager _persistent;
private UnityWebDataRequester _downloader; private UnityWebDataRequester _downloader;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
/// <summary> /// <summary>
/// 包裹版本 /// 包裹版本
/// </summary> /// </summary>
public string PackageVersion { private set; get; } public string PackageVersion { private set; get; }
public QueryBuildinPackageVersionOperation(PersistentManager persistent) public QueryBuildinPackageVersionOperation(PersistentManager persistent)
{ {
_persistent = persistent; _persistent = persistent;
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
_steps = ESteps.LoadBuildinPackageVersionFile; _steps = ESteps.LoadBuildinPackageVersionFile;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
if (_steps == ESteps.None || _steps == ESteps.Done) if (_steps == ESteps.None || _steps == ESteps.Done)
return; return;
if (_steps == ESteps.LoadBuildinPackageVersionFile) if (_steps == ESteps.LoadBuildinPackageVersionFile)
{ {
if (_downloader == null) if (_downloader == null)
{ {
string filePath = _persistent.GetBuildinPackageVersionFilePath(); string filePath = _persistent.GetBuildinPackageVersionFilePath();
string url = PersistentHelper.ConvertToWWWPath(filePath); string url = PersistentHelper.ConvertToWWWPath(filePath);
_downloader = new UnityWebDataRequester(); _downloader = new UnityWebDataRequester();
_downloader.SendRequest(url); _downloader.SendRequest(url);
} }
if (_downloader.IsDone() == false) if (_downloader.IsDone() == false)
return; return;
if (_downloader.HasError()) if (_downloader.HasError())
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = _downloader.GetError(); Error = _downloader.GetError();
} }
else else
{ {
PackageVersion = _downloader.GetText(); PackageVersion = _downloader.GetText();
if (string.IsNullOrEmpty(PackageVersion)) if (string.IsNullOrEmpty(PackageVersion))
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = $"Buildin package version file content is empty !"; Error = $"Buildin package version file content is empty !";
} }
else else
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
} }
_downloader.Dispose(); _downloader.Dispose();
} }
} }
} }
} }

View File

@ -2,63 +2,63 @@
namespace YooAsset namespace YooAsset
{ {
internal class QueryCachePackageHashOperation : AsyncOperationBase internal class QueryCachePackageHashOperation : AsyncOperationBase
{ {
private enum ESteps private enum ESteps
{ {
None, None,
LoadCachePackageHashFile, LoadCachePackageHashFile,
Done, Done,
} }
private readonly PersistentManager _persistent; private readonly PersistentManager _persistent;
private readonly string _packageVersion; private readonly string _packageVersion;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
/// <summary> /// <summary>
/// 包裹哈希值 /// 包裹哈希值
/// </summary> /// </summary>
public string PackageHash { private set; get; } public string PackageHash { private set; get; }
public QueryCachePackageHashOperation(PersistentManager persistent, string packageVersion) public QueryCachePackageHashOperation(PersistentManager persistent, string packageVersion)
{ {
_persistent = persistent; _persistent = persistent;
_packageVersion = packageVersion; _packageVersion = packageVersion;
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
_steps = ESteps.LoadCachePackageHashFile; _steps = ESteps.LoadCachePackageHashFile;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
if (_steps == ESteps.None || _steps == ESteps.Done) if (_steps == ESteps.None || _steps == ESteps.Done)
return; return;
if (_steps == ESteps.LoadCachePackageHashFile) if (_steps == ESteps.LoadCachePackageHashFile)
{ {
string filePath = _persistent.GetSandboxPackageHashFilePath(_packageVersion); string filePath = _persistent.GetSandboxPackageHashFilePath(_packageVersion);
if (File.Exists(filePath) == false) if (File.Exists(filePath) == false)
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = $"Cache package hash file not found : {filePath}"; Error = $"Cache package hash file not found : {filePath}";
return; return;
} }
PackageHash = FileUtility.ReadAllText(filePath); PackageHash = FileUtility.ReadAllText(filePath);
if (string.IsNullOrEmpty(PackageHash)) if (string.IsNullOrEmpty(PackageHash))
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = $"Cache package hash file content is empty !"; Error = $"Cache package hash file content is empty !";
} }
else else
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
} }
} }
} }
} }

View File

@ -2,61 +2,61 @@
namespace YooAsset namespace YooAsset
{ {
internal class QueryCachePackageVersionOperation : AsyncOperationBase internal class QueryCachePackageVersionOperation : AsyncOperationBase
{ {
private enum ESteps private enum ESteps
{ {
None, None,
LoadCachePackageVersionFile, LoadCachePackageVersionFile,
Done, Done,
} }
private readonly PersistentManager _persistent; private readonly PersistentManager _persistent;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
/// <summary> /// <summary>
/// 包裹版本 /// 包裹版本
/// </summary> /// </summary>
public string PackageVersion { private set; get; } public string PackageVersion { private set; get; }
public QueryCachePackageVersionOperation(PersistentManager persistent) public QueryCachePackageVersionOperation(PersistentManager persistent)
{ {
_persistent = persistent; _persistent = persistent;
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
_steps = ESteps.LoadCachePackageVersionFile; _steps = ESteps.LoadCachePackageVersionFile;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
if (_steps == ESteps.None || _steps == ESteps.Done) if (_steps == ESteps.None || _steps == ESteps.Done)
return; return;
if (_steps == ESteps.LoadCachePackageVersionFile) if (_steps == ESteps.LoadCachePackageVersionFile)
{ {
string filePath = _persistent.GetSandboxPackageVersionFilePath(); string filePath = _persistent.GetSandboxPackageVersionFilePath();
if (File.Exists(filePath) == false) if (File.Exists(filePath) == false)
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = $"Cache package version file not found : {filePath}"; Error = $"Cache package version file not found : {filePath}";
return; return;
} }
PackageVersion = FileUtility.ReadAllText(filePath); PackageVersion = FileUtility.ReadAllText(filePath);
if (string.IsNullOrEmpty(PackageVersion)) if (string.IsNullOrEmpty(PackageVersion))
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = $"Cache package version file content is empty !"; Error = $"Cache package version file content is empty !";
} }
else else
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
} }
} }
} }
} }

View File

@ -1,100 +1,100 @@
 
namespace YooAsset namespace YooAsset
{ {
internal class QueryRemotePackageHashOperation : AsyncOperationBase internal class QueryRemotePackageHashOperation : AsyncOperationBase
{ {
private enum ESteps private enum ESteps
{ {
None, None,
DownloadPackageHash, DownloadPackageHash,
Done, Done,
} }
private readonly IRemoteServices _remoteServices;
private readonly string _packageName;
private readonly string _packageVersion;
private readonly int _timeout;
private UnityWebDataRequester _downloader;
private ESteps _steps = ESteps.None;
private int _requestCount = 0;
/// <summary> private readonly IRemoteServices _remoteServices;
/// 包裹哈希值 private readonly string _packageName;
/// </summary> private readonly string _packageVersion;
public string PackageHash { private set; get; } private readonly int _timeout;
private UnityWebDataRequester _downloader;
private ESteps _steps = ESteps.None;
private int _requestCount = 0;
/// <summary>
/// 包裹哈希值
/// </summary>
public string PackageHash { private set; get; }
public QueryRemotePackageHashOperation(IRemoteServices remoteServices, string packageName, string packageVersion, int timeout) public QueryRemotePackageHashOperation(IRemoteServices remoteServices, string packageName, string packageVersion, int timeout)
{ {
_remoteServices = remoteServices; _remoteServices = remoteServices;
_packageName = packageName; _packageName = packageName;
_packageVersion = packageVersion; _packageVersion = packageVersion;
_timeout = timeout; _timeout = timeout;
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
_requestCount = RequestHelper.GetRequestFailedCount(_packageName, nameof(QueryRemotePackageHashOperation)); _requestCount = RequestHelper.GetRequestFailedCount(_packageName, nameof(QueryRemotePackageHashOperation));
_steps = ESteps.DownloadPackageHash; _steps = ESteps.DownloadPackageHash;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
if (_steps == ESteps.None || _steps == ESteps.Done) if (_steps == ESteps.None || _steps == ESteps.Done)
return; return;
if (_steps == ESteps.DownloadPackageHash) if (_steps == ESteps.DownloadPackageHash)
{ {
if (_downloader == null) if (_downloader == null)
{ {
string fileName = YooAssetSettingsData.GetPackageHashFileName(_packageName, _packageVersion); string fileName = YooAssetSettingsData.GetPackageHashFileName(_packageName, _packageVersion);
string webURL = GetPackageHashRequestURL(fileName); string webURL = GetPackageHashRequestURL(fileName);
YooLogger.Log($"Beginning to request package hash : {webURL}"); YooLogger.Log($"Beginning to request package hash : {webURL}");
_downloader = new UnityWebDataRequester(); _downloader = new UnityWebDataRequester();
_downloader.SendRequest(webURL, _timeout); _downloader.SendRequest(webURL, _timeout);
} }
Progress = _downloader.Progress(); Progress = _downloader.Progress();
_downloader.CheckTimeout(); _downloader.CheckTimeout();
if (_downloader.IsDone() == false) if (_downloader.IsDone() == false)
return; return;
if (_downloader.HasError()) if (_downloader.HasError())
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = _downloader.GetError(); Error = _downloader.GetError();
RequestHelper.RecordRequestFailed(_packageName, nameof(QueryRemotePackageHashOperation)); RequestHelper.RecordRequestFailed(_packageName, nameof(QueryRemotePackageHashOperation));
} }
else else
{ {
PackageHash = _downloader.GetText(); PackageHash = _downloader.GetText();
if (string.IsNullOrEmpty(PackageHash)) if (string.IsNullOrEmpty(PackageHash))
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = $"Remote package hash is empty : {_downloader.URL}"; Error = $"Remote package hash is empty : {_downloader.URL}";
} }
else else
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
} }
_downloader.Dispose(); _downloader.Dispose();
} }
} }
private string GetPackageHashRequestURL(string fileName) private string GetPackageHashRequestURL(string fileName)
{ {
string url; string url;
// 轮流返回请求地址 // 轮流返回请求地址
if (_requestCount % 2 == 0) if (_requestCount % 2 == 0)
url = _remoteServices.GetRemoteMainURL(fileName); url = _remoteServices.GetRemoteMainURL(fileName);
else else
url = _remoteServices.GetRemoteFallbackURL(fileName); url = _remoteServices.GetRemoteFallbackURL(fileName);
return url; return url;
} }
} }
} }

View File

@ -1,104 +1,104 @@
 
namespace YooAsset namespace YooAsset
{ {
internal class QueryRemotePackageVersionOperation : AsyncOperationBase internal class QueryRemotePackageVersionOperation : AsyncOperationBase
{ {
private enum ESteps private enum ESteps
{ {
None, None,
DownloadPackageVersion, DownloadPackageVersion,
Done, Done,
} }
private readonly IRemoteServices _remoteServices; private readonly IRemoteServices _remoteServices;
private readonly string _packageName; private readonly string _packageName;
private readonly bool _appendTimeTicks; private readonly bool _appendTimeTicks;
private readonly int _timeout; private readonly int _timeout;
private UnityWebDataRequester _downloader; private UnityWebDataRequester _downloader;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
private int _requestCount = 0; private int _requestCount = 0;
/// <summary> /// <summary>
/// 包裹版本 /// 包裹版本
/// </summary> /// </summary>
public string PackageVersion { private set; get; } public string PackageVersion { private set; get; }
public QueryRemotePackageVersionOperation(IRemoteServices remoteServices, string packageName, bool appendTimeTicks, int timeout)
{
_remoteServices = remoteServices;
_packageName = packageName;
_appendTimeTicks = appendTimeTicks;
_timeout = timeout;
}
internal override void InternalOnStart()
{
_requestCount = RequestHelper.GetRequestFailedCount(_packageName, nameof(QueryRemotePackageVersionOperation));
_steps = ESteps.DownloadPackageVersion;
}
internal override void InternalOnUpdate()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.DownloadPackageVersion) public QueryRemotePackageVersionOperation(IRemoteServices remoteServices, string packageName, bool appendTimeTicks, int timeout)
{ {
if (_downloader == null) _remoteServices = remoteServices;
{ _packageName = packageName;
string fileName = YooAssetSettingsData.GetPackageVersionFileName(_packageName); _appendTimeTicks = appendTimeTicks;
string webURL = GetPackageVersionRequestURL(fileName); _timeout = timeout;
YooLogger.Log($"Beginning to request package version : {webURL}"); }
_downloader = new UnityWebDataRequester(); internal override void InternalOnStart()
_downloader.SendRequest(webURL, _timeout); {
} _requestCount = RequestHelper.GetRequestFailedCount(_packageName, nameof(QueryRemotePackageVersionOperation));
_steps = ESteps.DownloadPackageVersion;
}
internal override void InternalOnUpdate()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
Progress = _downloader.Progress(); if (_steps == ESteps.DownloadPackageVersion)
_downloader.CheckTimeout(); {
if (_downloader.IsDone() == false) if (_downloader == null)
return; {
string fileName = YooAssetSettingsData.GetPackageVersionFileName(_packageName);
string webURL = GetPackageVersionRequestURL(fileName);
YooLogger.Log($"Beginning to request package version : {webURL}");
_downloader = new UnityWebDataRequester();
_downloader.SendRequest(webURL, _timeout);
}
if (_downloader.HasError()) Progress = _downloader.Progress();
{ _downloader.CheckTimeout();
_steps = ESteps.Done; if (_downloader.IsDone() == false)
Status = EOperationStatus.Failed; return;
Error = _downloader.GetError();
RequestHelper.RecordRequestFailed(_packageName, nameof(QueryRemotePackageVersionOperation));
}
else
{
PackageVersion = _downloader.GetText();
if (string.IsNullOrEmpty(PackageVersion))
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"Remote package version is empty : {_downloader.URL}";
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
}
_downloader.Dispose(); if (_downloader.HasError())
} {
} _steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = _downloader.GetError();
RequestHelper.RecordRequestFailed(_packageName, nameof(QueryRemotePackageVersionOperation));
}
else
{
PackageVersion = _downloader.GetText();
if (string.IsNullOrEmpty(PackageVersion))
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"Remote package version is empty : {_downloader.URL}";
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
}
private string GetPackageVersionRequestURL(string fileName) _downloader.Dispose();
{ }
string url; }
// 轮流返回请求地址 private string GetPackageVersionRequestURL(string fileName)
if (_requestCount % 2 == 0) {
url = _remoteServices.GetRemoteMainURL(fileName); string url;
else
url = _remoteServices.GetRemoteFallbackURL(fileName);
// 在URL末尾添加时间戳 // 轮流返回请求地址
if (_appendTimeTicks) if (_requestCount % 2 == 0)
return $"{url}?{System.DateTime.UtcNow.Ticks}"; url = _remoteServices.GetRemoteMainURL(fileName);
else else
return url; url = _remoteServices.GetRemoteFallbackURL(fileName);
}
} // 在URL末尾添加时间戳
if (_appendTimeTicks)
return $"{url}?{System.DateTime.UtcNow.Ticks}";
else
return url;
}
}
} }

View File

@ -1,92 +1,92 @@
 
namespace YooAsset namespace YooAsset
{ {
internal class UnpackBuildinManifestOperation : AsyncOperationBase internal class UnpackBuildinManifestOperation : AsyncOperationBase
{ {
private enum ESteps private enum ESteps
{ {
None, None,
UnpackManifestHashFile, UnpackManifestHashFile,
UnpackManifestFile, UnpackManifestFile,
Done, Done,
} }
private readonly PersistentManager _persistent; private readonly PersistentManager _persistent;
private readonly string _buildinPackageVersion; private readonly string _buildinPackageVersion;
private UnityWebFileRequester _downloader1; private UnityWebFileRequester _downloader1;
private UnityWebFileRequester _downloader2; private UnityWebFileRequester _downloader2;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
public UnpackBuildinManifestOperation(PersistentManager persistent, string buildinPackageVersion) public UnpackBuildinManifestOperation(PersistentManager persistent, string buildinPackageVersion)
{ {
_persistent = persistent; _persistent = persistent;
_buildinPackageVersion = buildinPackageVersion; _buildinPackageVersion = buildinPackageVersion;
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
_steps = ESteps.UnpackManifestHashFile; _steps = ESteps.UnpackManifestHashFile;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
if (_steps == ESteps.None || _steps == ESteps.Done) if (_steps == ESteps.None || _steps == ESteps.Done)
return; return;
if (_steps == ESteps.UnpackManifestHashFile) if (_steps == ESteps.UnpackManifestHashFile)
{ {
if (_downloader1 == null) if (_downloader1 == null)
{ {
string savePath = _persistent.GetSandboxPackageHashFilePath(_buildinPackageVersion); string savePath = _persistent.GetSandboxPackageHashFilePath(_buildinPackageVersion);
string filePath = _persistent.GetBuildinPackageHashFilePath(_buildinPackageVersion); string filePath = _persistent.GetBuildinPackageHashFilePath(_buildinPackageVersion);
string url = PersistentHelper.ConvertToWWWPath(filePath); string url = PersistentHelper.ConvertToWWWPath(filePath);
_downloader1 = new UnityWebFileRequester(); _downloader1 = new UnityWebFileRequester();
_downloader1.SendRequest(url, savePath); _downloader1.SendRequest(url, savePath);
} }
if (_downloader1.IsDone() == false) if (_downloader1.IsDone() == false)
return; return;
if (_downloader1.HasError()) if (_downloader1.HasError())
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = _downloader1.GetError(); Error = _downloader1.GetError();
} }
else else
{ {
_steps = ESteps.UnpackManifestFile; _steps = ESteps.UnpackManifestFile;
} }
_downloader1.Dispose(); _downloader1.Dispose();
} }
if (_steps == ESteps.UnpackManifestFile) if (_steps == ESteps.UnpackManifestFile)
{ {
if (_downloader2 == null) if (_downloader2 == null)
{ {
string savePath = _persistent.GetSandboxPackageManifestFilePath(_buildinPackageVersion); string savePath = _persistent.GetSandboxPackageManifestFilePath(_buildinPackageVersion);
string filePath = _persistent.GetBuildinPackageManifestFilePath(_buildinPackageVersion); string filePath = _persistent.GetBuildinPackageManifestFilePath(_buildinPackageVersion);
string url = PersistentHelper.ConvertToWWWPath(filePath); string url = PersistentHelper.ConvertToWWWPath(filePath);
_downloader2 = new UnityWebFileRequester(); _downloader2 = new UnityWebFileRequester();
_downloader2.SendRequest(url, savePath); _downloader2.SendRequest(url, savePath);
} }
if (_downloader2.IsDone() == false) if (_downloader2.IsDone() == false)
return; return;
if (_downloader2.HasError()) if (_downloader2.HasError())
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = _downloader2.GetError(); Error = _downloader2.GetError();
} }
else else
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
_downloader2.Dispose(); _downloader2.Dispose();
} }
} }
} }
} }

View File

@ -4,360 +4,360 @@ using System.Collections.Generic;
namespace YooAsset namespace YooAsset
{ {
public abstract class PreDownloadContentOperation : AsyncOperationBase public abstract class PreDownloadContentOperation : AsyncOperationBase
{ {
/// <summary> /// <summary>
/// 创建资源下载器,用于下载当前资源版本所有的资源包文件 /// 创建资源下载器,用于下载当前资源版本所有的资源包文件
/// </summary> /// </summary>
/// <param name="downloadingMaxNumber">同时下载的最大文件数</param> /// <param name="downloadingMaxNumber">同时下载的最大文件数</param>
/// <param name="failedTryAgain">下载失败的重试次数</param> /// <param name="failedTryAgain">下载失败的重试次数</param>
/// <param name="timeout">超时时间</param> /// <param name="timeout">超时时间</param>
public abstract ResourceDownloaderOperation CreateResourceDownloader(int downloadingMaxNumber, int failedTryAgain, int timeout = 60); public abstract ResourceDownloaderOperation CreateResourceDownloader(int downloadingMaxNumber, int failedTryAgain, int timeout = 60);
/// <summary> /// <summary>
/// 创建资源下载器,用于下载指定的资源标签关联的资源包文件 /// 创建资源下载器,用于下载指定的资源标签关联的资源包文件
/// </summary> /// </summary>
/// <param name="tag">资源标签</param> /// <param name="tag">资源标签</param>
/// <param name="downloadingMaxNumber">同时下载的最大文件数</param> /// <param name="downloadingMaxNumber">同时下载的最大文件数</param>
/// <param name="failedTryAgain">下载失败的重试次数</param> /// <param name="failedTryAgain">下载失败的重试次数</param>
/// <param name="timeout">超时时间</param> /// <param name="timeout">超时时间</param>
public abstract ResourceDownloaderOperation CreateResourceDownloader(string tag, int downloadingMaxNumber, int failedTryAgain, int timeout = 60); public abstract ResourceDownloaderOperation CreateResourceDownloader(string tag, int downloadingMaxNumber, int failedTryAgain, int timeout = 60);
/// <summary> /// <summary>
/// 创建资源下载器,用于下载指定的资源标签列表关联的资源包文件 /// 创建资源下载器,用于下载指定的资源标签列表关联的资源包文件
/// </summary> /// </summary>
/// <param name="tags">资源标签列表</param> /// <param name="tags">资源标签列表</param>
/// <param name="downloadingMaxNumber">同时下载的最大文件数</param> /// <param name="downloadingMaxNumber">同时下载的最大文件数</param>
/// <param name="failedTryAgain">下载失败的重试次数</param> /// <param name="failedTryAgain">下载失败的重试次数</param>
/// <param name="timeout">超时时间</param> /// <param name="timeout">超时时间</param>
public abstract ResourceDownloaderOperation CreateResourceDownloader(string[] tags, int downloadingMaxNumber, int failedTryAgain, int timeout = 60); public abstract ResourceDownloaderOperation CreateResourceDownloader(string[] tags, int downloadingMaxNumber, int failedTryAgain, int timeout = 60);
/// <summary> /// <summary>
/// 创建资源下载器,用于下载指定的资源依赖的资源包文件 /// 创建资源下载器,用于下载指定的资源依赖的资源包文件
/// </summary> /// </summary>
/// <param name="location">资源定位地址</param> /// <param name="location">资源定位地址</param>
/// <param name="downloadingMaxNumber">同时下载的最大文件数</param> /// <param name="downloadingMaxNumber">同时下载的最大文件数</param>
/// <param name="failedTryAgain">下载失败的重试次数</param> /// <param name="failedTryAgain">下载失败的重试次数</param>
/// <param name="timeout">超时时间</param> /// <param name="timeout">超时时间</param>
public abstract ResourceDownloaderOperation CreateBundleDownloader(string location, int downloadingMaxNumber, int failedTryAgain, int timeout = 60); public abstract ResourceDownloaderOperation CreateBundleDownloader(string location, int downloadingMaxNumber, int failedTryAgain, int timeout = 60);
/// <summary> /// <summary>
/// 创建资源下载器,用于下载指定的资源列表依赖的资源包文件 /// 创建资源下载器,用于下载指定的资源列表依赖的资源包文件
/// </summary> /// </summary>
/// <param name="locations">资源定位地址列表</param> /// <param name="locations">资源定位地址列表</param>
/// <param name="downloadingMaxNumber">同时下载的最大文件数</param> /// <param name="downloadingMaxNumber">同时下载的最大文件数</param>
/// <param name="failedTryAgain">下载失败的重试次数</param> /// <param name="failedTryAgain">下载失败的重试次数</param>
/// <param name="timeout">超时时间</param> /// <param name="timeout">超时时间</param>
public abstract ResourceDownloaderOperation CreateBundleDownloader(string[] locations, int downloadingMaxNumber, int failedTryAgain, int timeout = 60); public abstract ResourceDownloaderOperation CreateBundleDownloader(string[] locations, int downloadingMaxNumber, int failedTryAgain, int timeout = 60);
} }
internal class EditorPlayModePreDownloadContentOperation : PreDownloadContentOperation internal class EditorPlayModePreDownloadContentOperation : PreDownloadContentOperation
{ {
private readonly EditorSimulateModeImpl _impl; private readonly EditorSimulateModeImpl _impl;
public EditorPlayModePreDownloadContentOperation(EditorSimulateModeImpl impl) public EditorPlayModePreDownloadContentOperation(EditorSimulateModeImpl impl)
{ {
_impl = impl; _impl = impl;
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
} }
public override ResourceDownloaderOperation CreateResourceDownloader(int downloadingMaxNumber, int failedTryAgain, int timeout = 60) public override ResourceDownloaderOperation CreateResourceDownloader(int downloadingMaxNumber, int failedTryAgain, int timeout = 60)
{ {
return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout); return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout);
} }
public override ResourceDownloaderOperation CreateResourceDownloader(string tag, int downloadingMaxNumber, int failedTryAgain, int timeout = 60) public override ResourceDownloaderOperation CreateResourceDownloader(string tag, int downloadingMaxNumber, int failedTryAgain, int timeout = 60)
{ {
return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout); return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout);
} }
public override ResourceDownloaderOperation CreateResourceDownloader(string[] tags, int downloadingMaxNumber, int failedTryAgain, int timeout = 60) public override ResourceDownloaderOperation CreateResourceDownloader(string[] tags, int downloadingMaxNumber, int failedTryAgain, int timeout = 60)
{ {
return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout); return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout);
} }
public override ResourceDownloaderOperation CreateBundleDownloader(string location, int downloadingMaxNumber, int failedTryAgain, int timeout = 60) public override ResourceDownloaderOperation CreateBundleDownloader(string location, int downloadingMaxNumber, int failedTryAgain, int timeout = 60)
{ {
return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout); return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout);
} }
public override ResourceDownloaderOperation CreateBundleDownloader(string[] locations, int downloadingMaxNumber, int failedTryAgain, int timeout = 60) public override ResourceDownloaderOperation CreateBundleDownloader(string[] locations, int downloadingMaxNumber, int failedTryAgain, int timeout = 60)
{ {
return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout); return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout);
} }
} }
internal class OfflinePlayModePreDownloadContentOperation : PreDownloadContentOperation internal class OfflinePlayModePreDownloadContentOperation : PreDownloadContentOperation
{ {
private readonly OfflinePlayModeImpl _impl; private readonly OfflinePlayModeImpl _impl;
public OfflinePlayModePreDownloadContentOperation(OfflinePlayModeImpl impl) public OfflinePlayModePreDownloadContentOperation(OfflinePlayModeImpl impl)
{ {
_impl = impl; _impl = impl;
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
} }
public override ResourceDownloaderOperation CreateResourceDownloader(int downloadingMaxNumber, int failedTryAgain, int timeout = 60) public override ResourceDownloaderOperation CreateResourceDownloader(int downloadingMaxNumber, int failedTryAgain, int timeout = 60)
{ {
return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout); return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout);
} }
public override ResourceDownloaderOperation CreateResourceDownloader(string tag, int downloadingMaxNumber, int failedTryAgain, int timeout = 60) public override ResourceDownloaderOperation CreateResourceDownloader(string tag, int downloadingMaxNumber, int failedTryAgain, int timeout = 60)
{ {
return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout); return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout);
} }
public override ResourceDownloaderOperation CreateResourceDownloader(string[] tags, int downloadingMaxNumber, int failedTryAgain, int timeout = 60) public override ResourceDownloaderOperation CreateResourceDownloader(string[] tags, int downloadingMaxNumber, int failedTryAgain, int timeout = 60)
{ {
return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout); return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout);
} }
public override ResourceDownloaderOperation CreateBundleDownloader(string location, int downloadingMaxNumber, int failedTryAgain, int timeout = 60) public override ResourceDownloaderOperation CreateBundleDownloader(string location, int downloadingMaxNumber, int failedTryAgain, int timeout = 60)
{ {
return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout); return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout);
} }
public override ResourceDownloaderOperation CreateBundleDownloader(string[] locations, int downloadingMaxNumber, int failedTryAgain, int timeout = 60) public override ResourceDownloaderOperation CreateBundleDownloader(string[] locations, int downloadingMaxNumber, int failedTryAgain, int timeout = 60)
{ {
return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout); return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout);
} }
} }
internal class HostPlayModePreDownloadContentOperation : PreDownloadContentOperation internal class HostPlayModePreDownloadContentOperation : PreDownloadContentOperation
{ {
private enum ESteps private enum ESteps
{ {
None, None,
CheckActiveManifest, CheckActiveManifest,
TryLoadCacheManifest, TryLoadCacheManifest,
DownloadManifest, DownloadManifest,
LoadCacheManifest, LoadCacheManifest,
CheckDeserializeManifest, CheckDeserializeManifest,
Done, Done,
} }
private readonly HostPlayModeImpl _impl; private readonly HostPlayModeImpl _impl;
private readonly string _packageVersion; private readonly string _packageVersion;
private readonly int _timeout; private readonly int _timeout;
private LoadCacheManifestOperation _tryLoadCacheManifestOp; private LoadCacheManifestOperation _tryLoadCacheManifestOp;
private LoadCacheManifestOperation _loadCacheManifestOp; private LoadCacheManifestOperation _loadCacheManifestOp;
private DownloadManifestOperation _downloadManifestOp; private DownloadManifestOperation _downloadManifestOp;
private PackageManifest _manifest; private PackageManifest _manifest;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
internal HostPlayModePreDownloadContentOperation(HostPlayModeImpl impl, string packageVersion, int timeout) internal HostPlayModePreDownloadContentOperation(HostPlayModeImpl impl, string packageVersion, int timeout)
{ {
_impl = impl; _impl = impl;
_packageVersion = packageVersion; _packageVersion = packageVersion;
_timeout = timeout; _timeout = timeout;
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
_steps = ESteps.CheckActiveManifest; _steps = ESteps.CheckActiveManifest;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
if (_steps == ESteps.None || _steps == ESteps.Done) if (_steps == ESteps.None || _steps == ESteps.Done)
return; return;
if (_steps == ESteps.CheckActiveManifest) if (_steps == ESteps.CheckActiveManifest)
{ {
// 检测当前激活的清单对象 // 检测当前激活的清单对象
if (_impl.ActiveManifest != null) if (_impl.ActiveManifest != null)
{ {
if (_impl.ActiveManifest.PackageVersion == _packageVersion) if (_impl.ActiveManifest.PackageVersion == _packageVersion)
{ {
_manifest = _impl.ActiveManifest; _manifest = _impl.ActiveManifest;
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
return; return;
} }
} }
_steps = ESteps.TryLoadCacheManifest; _steps = ESteps.TryLoadCacheManifest;
} }
if (_steps == ESteps.TryLoadCacheManifest) if (_steps == ESteps.TryLoadCacheManifest)
{ {
if (_tryLoadCacheManifestOp == null) if (_tryLoadCacheManifestOp == null)
{ {
_tryLoadCacheManifestOp = new LoadCacheManifestOperation(_impl.Persistent, _packageVersion); _tryLoadCacheManifestOp = new LoadCacheManifestOperation(_impl.Persistent, _packageVersion);
OperationSystem.StartOperation(_impl.PackageName, _tryLoadCacheManifestOp); OperationSystem.StartOperation(_impl.PackageName, _tryLoadCacheManifestOp);
} }
if (_tryLoadCacheManifestOp.IsDone == false) if (_tryLoadCacheManifestOp.IsDone == false)
return; return;
if (_tryLoadCacheManifestOp.Status == EOperationStatus.Succeed) if (_tryLoadCacheManifestOp.Status == EOperationStatus.Succeed)
{ {
_manifest = _tryLoadCacheManifestOp.Manifest; _manifest = _tryLoadCacheManifestOp.Manifest;
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
else else
{ {
_steps = ESteps.DownloadManifest; _steps = ESteps.DownloadManifest;
} }
} }
if (_steps == ESteps.DownloadManifest) if (_steps == ESteps.DownloadManifest)
{ {
if (_downloadManifestOp == null) if (_downloadManifestOp == null)
{ {
_downloadManifestOp = new DownloadManifestOperation(_impl.Persistent, _impl.RemoteServices, _packageVersion, _timeout); _downloadManifestOp = new DownloadManifestOperation(_impl.Persistent, _impl.RemoteServices, _packageVersion, _timeout);
OperationSystem.StartOperation(_impl.PackageName, _downloadManifestOp); OperationSystem.StartOperation(_impl.PackageName, _downloadManifestOp);
} }
if (_downloadManifestOp.IsDone == false) if (_downloadManifestOp.IsDone == false)
return; return;
if (_downloadManifestOp.Status == EOperationStatus.Succeed) if (_downloadManifestOp.Status == EOperationStatus.Succeed)
{ {
_steps = ESteps.LoadCacheManifest; _steps = ESteps.LoadCacheManifest;
} }
else else
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = _downloadManifestOp.Error; Error = _downloadManifestOp.Error;
} }
} }
if (_steps == ESteps.LoadCacheManifest) if (_steps == ESteps.LoadCacheManifest)
{ {
if (_loadCacheManifestOp == null) if (_loadCacheManifestOp == null)
{ {
_loadCacheManifestOp = new LoadCacheManifestOperation(_impl.Persistent, _packageVersion); _loadCacheManifestOp = new LoadCacheManifestOperation(_impl.Persistent, _packageVersion);
OperationSystem.StartOperation(_impl.PackageName, _loadCacheManifestOp); OperationSystem.StartOperation(_impl.PackageName, _loadCacheManifestOp);
} }
if (_loadCacheManifestOp.IsDone == false) if (_loadCacheManifestOp.IsDone == false)
return; return;
if (_loadCacheManifestOp.Status == EOperationStatus.Succeed) if (_loadCacheManifestOp.Status == EOperationStatus.Succeed)
{ {
_manifest = _loadCacheManifestOp.Manifest; _manifest = _loadCacheManifestOp.Manifest;
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
else else
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = _loadCacheManifestOp.Error; Error = _loadCacheManifestOp.Error;
} }
} }
} }
public override ResourceDownloaderOperation CreateResourceDownloader(int downloadingMaxNumber, int failedTryAgain, int timeout = 60) public override ResourceDownloaderOperation CreateResourceDownloader(int downloadingMaxNumber, int failedTryAgain, int timeout = 60)
{ {
if (Status != EOperationStatus.Succeed) if (Status != EOperationStatus.Succeed)
{ {
YooLogger.Warning($"{nameof(PreDownloadContentOperation)} status is not succeed !"); YooLogger.Warning($"{nameof(PreDownloadContentOperation)} status is not succeed !");
return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout); return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout);
} }
List<BundleInfo> downloadList = _impl.GetDownloadListByAll(_manifest); List<BundleInfo> downloadList = _impl.GetDownloadListByAll(_manifest);
var operation = new ResourceDownloaderOperation(_impl.Download, _impl.PackageName, downloadList, downloadingMaxNumber, failedTryAgain, timeout); var operation = new ResourceDownloaderOperation(_impl.Download, _impl.PackageName, downloadList, downloadingMaxNumber, failedTryAgain, timeout);
return operation; return operation;
} }
public override ResourceDownloaderOperation CreateResourceDownloader(string tag, int downloadingMaxNumber, int failedTryAgain, int timeout = 60) public override ResourceDownloaderOperation CreateResourceDownloader(string tag, int downloadingMaxNumber, int failedTryAgain, int timeout = 60)
{ {
if (Status != EOperationStatus.Succeed) if (Status != EOperationStatus.Succeed)
{ {
YooLogger.Warning($"{nameof(PreDownloadContentOperation)} status is not succeed !"); YooLogger.Warning($"{nameof(PreDownloadContentOperation)} status is not succeed !");
return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout); return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout);
} }
List<BundleInfo> downloadList = _impl.GetDownloadListByTags(_manifest, new string[] { tag }); List<BundleInfo> downloadList = _impl.GetDownloadListByTags(_manifest, new string[] { tag });
var operation = new ResourceDownloaderOperation(_impl.Download, _impl.PackageName, downloadList, downloadingMaxNumber, failedTryAgain, timeout); var operation = new ResourceDownloaderOperation(_impl.Download, _impl.PackageName, downloadList, downloadingMaxNumber, failedTryAgain, timeout);
return operation; return operation;
} }
public override ResourceDownloaderOperation CreateResourceDownloader(string[] tags, int downloadingMaxNumber, int failedTryAgain, int timeout = 60) public override ResourceDownloaderOperation CreateResourceDownloader(string[] tags, int downloadingMaxNumber, int failedTryAgain, int timeout = 60)
{ {
if (Status != EOperationStatus.Succeed) if (Status != EOperationStatus.Succeed)
{ {
YooLogger.Warning($"{nameof(PreDownloadContentOperation)} status is not succeed !"); YooLogger.Warning($"{nameof(PreDownloadContentOperation)} status is not succeed !");
return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout); return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout);
} }
List<BundleInfo> downloadList = _impl.GetDownloadListByTags(_manifest, tags); List<BundleInfo> downloadList = _impl.GetDownloadListByTags(_manifest, tags);
var operation = new ResourceDownloaderOperation(_impl.Download, _impl.PackageName, downloadList, downloadingMaxNumber, failedTryAgain, timeout); var operation = new ResourceDownloaderOperation(_impl.Download, _impl.PackageName, downloadList, downloadingMaxNumber, failedTryAgain, timeout);
return operation; return operation;
} }
public override ResourceDownloaderOperation CreateBundleDownloader(string location, int downloadingMaxNumber, int failedTryAgain, int timeout = 60) public override ResourceDownloaderOperation CreateBundleDownloader(string location, int downloadingMaxNumber, int failedTryAgain, int timeout = 60)
{ {
if (Status != EOperationStatus.Succeed) if (Status != EOperationStatus.Succeed)
{ {
YooLogger.Warning($"{nameof(PreDownloadContentOperation)} status is not succeed !"); YooLogger.Warning($"{nameof(PreDownloadContentOperation)} status is not succeed !");
return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout); return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout);
} }
List<AssetInfo> assetInfos = new List<AssetInfo>(); List<AssetInfo> assetInfos = new List<AssetInfo>();
var assetInfo = _manifest.ConvertLocationToAssetInfo(location, null); var assetInfo = _manifest.ConvertLocationToAssetInfo(location, null);
assetInfos.Add(assetInfo); assetInfos.Add(assetInfo);
List<BundleInfo> downloadList = _impl.GetDownloadListByPaths(_manifest, assetInfos.ToArray()); List<BundleInfo> downloadList = _impl.GetDownloadListByPaths(_manifest, assetInfos.ToArray());
var operation = new ResourceDownloaderOperation(_impl.Download, _impl.PackageName, downloadList, downloadingMaxNumber, failedTryAgain, timeout); var operation = new ResourceDownloaderOperation(_impl.Download, _impl.PackageName, downloadList, downloadingMaxNumber, failedTryAgain, timeout);
return operation; return operation;
} }
public override ResourceDownloaderOperation CreateBundleDownloader(string[] locations, int downloadingMaxNumber, int failedTryAgain, int timeout = 60) public override ResourceDownloaderOperation CreateBundleDownloader(string[] locations, int downloadingMaxNumber, int failedTryAgain, int timeout = 60)
{ {
if (Status != EOperationStatus.Succeed) if (Status != EOperationStatus.Succeed)
{ {
YooLogger.Warning($"{nameof(PreDownloadContentOperation)} status is not succeed !"); YooLogger.Warning($"{nameof(PreDownloadContentOperation)} status is not succeed !");
return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout); return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout);
} }
List<AssetInfo> assetInfos = new List<AssetInfo>(locations.Length); List<AssetInfo> assetInfos = new List<AssetInfo>(locations.Length);
foreach (var location in locations) foreach (var location in locations)
{ {
var assetInfo = _manifest.ConvertLocationToAssetInfo(location, null); var assetInfo = _manifest.ConvertLocationToAssetInfo(location, null);
assetInfos.Add(assetInfo); assetInfos.Add(assetInfo);
} }
List<BundleInfo> downloadList = _impl.GetDownloadListByPaths(_manifest, assetInfos.ToArray()); List<BundleInfo> downloadList = _impl.GetDownloadListByPaths(_manifest, assetInfos.ToArray());
var operation = new ResourceDownloaderOperation(_impl.Download, _impl.PackageName, downloadList, downloadingMaxNumber, failedTryAgain, timeout); var operation = new ResourceDownloaderOperation(_impl.Download, _impl.PackageName, downloadList, downloadingMaxNumber, failedTryAgain, timeout);
return operation; return operation;
} }
} }
internal class WebPlayModePreDownloadContentOperation : PreDownloadContentOperation internal class WebPlayModePreDownloadContentOperation : PreDownloadContentOperation
{ {
private readonly WebPlayModeImpl _impl; private readonly WebPlayModeImpl _impl;
public WebPlayModePreDownloadContentOperation(WebPlayModeImpl impl) public WebPlayModePreDownloadContentOperation(WebPlayModeImpl impl)
{ {
_impl = impl; _impl = impl;
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
} }
public override ResourceDownloaderOperation CreateResourceDownloader(int downloadingMaxNumber, int failedTryAgain, int timeout = 60) public override ResourceDownloaderOperation CreateResourceDownloader(int downloadingMaxNumber, int failedTryAgain, int timeout = 60)
{ {
return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout); return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout);
} }
public override ResourceDownloaderOperation CreateResourceDownloader(string tag, int downloadingMaxNumber, int failedTryAgain, int timeout = 60) public override ResourceDownloaderOperation CreateResourceDownloader(string tag, int downloadingMaxNumber, int failedTryAgain, int timeout = 60)
{ {
return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout); return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout);
} }
public override ResourceDownloaderOperation CreateResourceDownloader(string[] tags, int downloadingMaxNumber, int failedTryAgain, int timeout = 60) public override ResourceDownloaderOperation CreateResourceDownloader(string[] tags, int downloadingMaxNumber, int failedTryAgain, int timeout = 60)
{ {
return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout); return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout);
} }
public override ResourceDownloaderOperation CreateBundleDownloader(string location, int downloadingMaxNumber, int failedTryAgain, int timeout = 60) public override ResourceDownloaderOperation CreateBundleDownloader(string location, int downloadingMaxNumber, int failedTryAgain, int timeout = 60)
{ {
return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout); return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout);
} }
public override ResourceDownloaderOperation CreateBundleDownloader(string[] locations, int downloadingMaxNumber, int failedTryAgain, int timeout = 60) public override ResourceDownloaderOperation CreateBundleDownloader(string[] locations, int downloadingMaxNumber, int failedTryAgain, int timeout = 60)
{ {
return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout); return ResourceDownloaderOperation.CreateEmptyDownloader(_impl.Download, _impl.PackageName, downloadingMaxNumber, failedTryAgain, timeout);
} }
} }
} }

View File

@ -4,291 +4,291 @@ using System.Collections.Generic;
namespace YooAsset namespace YooAsset
{ {
/// <summary> /// <summary>
/// 向远端请求并更新清单 /// 向远端请求并更新清单
/// </summary> /// </summary>
public abstract class UpdatePackageManifestOperation : AsyncOperationBase public abstract class UpdatePackageManifestOperation : AsyncOperationBase
{ {
/// <summary> /// <summary>
/// 保存当前清单的版本,用于下次启动时自动加载的版本。 /// 保存当前清单的版本,用于下次启动时自动加载的版本。
/// </summary> /// </summary>
public virtual void SavePackageVersion() { } public virtual void SavePackageVersion() { }
} }
/// <summary> /// <summary>
/// 编辑器下模拟运行的更新清单操作 /// 编辑器下模拟运行的更新清单操作
/// </summary> /// </summary>
internal sealed class EditorPlayModeUpdatePackageManifestOperation : UpdatePackageManifestOperation internal sealed class EditorPlayModeUpdatePackageManifestOperation : UpdatePackageManifestOperation
{ {
public EditorPlayModeUpdatePackageManifestOperation() public EditorPlayModeUpdatePackageManifestOperation()
{ {
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
} }
} }
/// <summary> /// <summary>
/// 离线模式的更新清单操作 /// 离线模式的更新清单操作
/// </summary> /// </summary>
internal sealed class OfflinePlayModeUpdatePackageManifestOperation : UpdatePackageManifestOperation internal sealed class OfflinePlayModeUpdatePackageManifestOperation : UpdatePackageManifestOperation
{ {
public OfflinePlayModeUpdatePackageManifestOperation() public OfflinePlayModeUpdatePackageManifestOperation()
{ {
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
} }
} }
/// <summary> /// <summary>
/// 联机模式的更新清单操作 /// 联机模式的更新清单操作
/// 注意:优先加载沙盒里缓存的清单文件,如果缓存没找到就下载远端清单文件,并保存到本地。 /// 注意:优先加载沙盒里缓存的清单文件,如果缓存没找到就下载远端清单文件,并保存到本地。
/// </summary> /// </summary>
internal sealed class HostPlayModeUpdatePackageManifestOperation : UpdatePackageManifestOperation internal sealed class HostPlayModeUpdatePackageManifestOperation : UpdatePackageManifestOperation
{ {
private enum ESteps private enum ESteps
{ {
None, None,
CheckParams, CheckParams,
CheckActiveManifest, CheckActiveManifest,
TryLoadCacheManifest, TryLoadCacheManifest,
DownloadManifest, DownloadManifest,
LoadCacheManifest, LoadCacheManifest,
CheckDeserializeManifest, CheckDeserializeManifest,
Done, Done,
} }
private readonly HostPlayModeImpl _impl; private readonly HostPlayModeImpl _impl;
private readonly string _packageVersion; private readonly string _packageVersion;
private readonly bool _autoSaveVersion; private readonly bool _autoSaveVersion;
private readonly int _timeout; private readonly int _timeout;
private LoadCacheManifestOperation _tryLoadCacheManifestOp; private LoadCacheManifestOperation _tryLoadCacheManifestOp;
private LoadCacheManifestOperation _loadCacheManifestOp; private LoadCacheManifestOperation _loadCacheManifestOp;
private DownloadManifestOperation _downloadManifestOp; private DownloadManifestOperation _downloadManifestOp;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
internal HostPlayModeUpdatePackageManifestOperation(HostPlayModeImpl impl, string packageVersion, bool autoSaveVersion, int timeout) internal HostPlayModeUpdatePackageManifestOperation(HostPlayModeImpl impl, string packageVersion, bool autoSaveVersion, int timeout)
{ {
_impl = impl; _impl = impl;
_packageVersion = packageVersion; _packageVersion = packageVersion;
_autoSaveVersion = autoSaveVersion; _autoSaveVersion = autoSaveVersion;
_timeout = timeout; _timeout = timeout;
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
_steps = ESteps.CheckParams; _steps = ESteps.CheckParams;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
if (_steps == ESteps.None || _steps == ESteps.Done) if (_steps == ESteps.None || _steps == ESteps.Done)
return; return;
if (_steps == ESteps.CheckParams) if (_steps == ESteps.CheckParams)
{ {
if (string.IsNullOrEmpty(_packageVersion)) if (string.IsNullOrEmpty(_packageVersion))
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = "Package version is null or empty."; Error = "Package version is null or empty.";
return; return;
} }
_steps = ESteps.CheckActiveManifest; _steps = ESteps.CheckActiveManifest;
} }
if (_steps == ESteps.CheckActiveManifest) if (_steps == ESteps.CheckActiveManifest)
{ {
// 检测当前激活的清单对象 // 检测当前激活的清单对象
if (_impl.ActiveManifest != null && _impl.ActiveManifest.PackageVersion == _packageVersion) if (_impl.ActiveManifest != null && _impl.ActiveManifest.PackageVersion == _packageVersion)
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
else else
{ {
_steps = ESteps.TryLoadCacheManifest; _steps = ESteps.TryLoadCacheManifest;
} }
} }
if (_steps == ESteps.TryLoadCacheManifest) if (_steps == ESteps.TryLoadCacheManifest)
{ {
if (_tryLoadCacheManifestOp == null) if (_tryLoadCacheManifestOp == null)
{ {
_tryLoadCacheManifestOp = new LoadCacheManifestOperation(_impl.Persistent, _packageVersion); _tryLoadCacheManifestOp = new LoadCacheManifestOperation(_impl.Persistent, _packageVersion);
OperationSystem.StartOperation(_impl.PackageName, _tryLoadCacheManifestOp); OperationSystem.StartOperation(_impl.PackageName, _tryLoadCacheManifestOp);
} }
if (_tryLoadCacheManifestOp.IsDone == false) if (_tryLoadCacheManifestOp.IsDone == false)
return; return;
if (_tryLoadCacheManifestOp.Status == EOperationStatus.Succeed) if (_tryLoadCacheManifestOp.Status == EOperationStatus.Succeed)
{ {
_impl.ActiveManifest = _tryLoadCacheManifestOp.Manifest; _impl.ActiveManifest = _tryLoadCacheManifestOp.Manifest;
if (_autoSaveVersion) if (_autoSaveVersion)
SavePackageVersion(); SavePackageVersion();
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
else else
{ {
_steps = ESteps.DownloadManifest; _steps = ESteps.DownloadManifest;
} }
} }
if (_steps == ESteps.DownloadManifest) if (_steps == ESteps.DownloadManifest)
{ {
if (_downloadManifestOp == null) if (_downloadManifestOp == null)
{ {
_downloadManifestOp = new DownloadManifestOperation(_impl.Persistent, _impl.RemoteServices, _packageVersion, _timeout); _downloadManifestOp = new DownloadManifestOperation(_impl.Persistent, _impl.RemoteServices, _packageVersion, _timeout);
OperationSystem.StartOperation(_impl.PackageName, _downloadManifestOp); OperationSystem.StartOperation(_impl.PackageName, _downloadManifestOp);
} }
if (_downloadManifestOp.IsDone == false) if (_downloadManifestOp.IsDone == false)
return; return;
if (_downloadManifestOp.Status == EOperationStatus.Succeed) if (_downloadManifestOp.Status == EOperationStatus.Succeed)
{ {
_steps = ESteps.LoadCacheManifest; _steps = ESteps.LoadCacheManifest;
} }
else else
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = _downloadManifestOp.Error; Error = _downloadManifestOp.Error;
} }
} }
if (_steps == ESteps.LoadCacheManifest) if (_steps == ESteps.LoadCacheManifest)
{ {
if (_loadCacheManifestOp == null) if (_loadCacheManifestOp == null)
{ {
_loadCacheManifestOp = new LoadCacheManifestOperation(_impl.Persistent, _packageVersion); _loadCacheManifestOp = new LoadCacheManifestOperation(_impl.Persistent, _packageVersion);
OperationSystem.StartOperation(_impl.PackageName, _loadCacheManifestOp); OperationSystem.StartOperation(_impl.PackageName, _loadCacheManifestOp);
} }
if (_loadCacheManifestOp.IsDone == false) if (_loadCacheManifestOp.IsDone == false)
return; return;
if (_loadCacheManifestOp.Status == EOperationStatus.Succeed) if (_loadCacheManifestOp.Status == EOperationStatus.Succeed)
{ {
_impl.ActiveManifest = _loadCacheManifestOp.Manifest; _impl.ActiveManifest = _loadCacheManifestOp.Manifest;
if (_autoSaveVersion) if (_autoSaveVersion)
SavePackageVersion(); SavePackageVersion();
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
else else
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = _loadCacheManifestOp.Error; Error = _loadCacheManifestOp.Error;
} }
} }
} }
public override void SavePackageVersion() public override void SavePackageVersion()
{ {
_impl.FlushManifestVersionFile(); _impl.FlushManifestVersionFile();
} }
} }
/// <summary> /// <summary>
/// WebGL模式的更新清单操作 /// WebGL模式的更新清单操作
/// </summary> /// </summary>
internal sealed class WebPlayModeUpdatePackageManifestOperation : UpdatePackageManifestOperation internal sealed class WebPlayModeUpdatePackageManifestOperation : UpdatePackageManifestOperation
{ {
private enum ESteps private enum ESteps
{ {
None, None,
CheckParams, CheckParams,
CheckActiveManifest, CheckActiveManifest,
LoadRemoteManifest, LoadRemoteManifest,
Done, Done,
} }
private readonly WebPlayModeImpl _impl; private readonly WebPlayModeImpl _impl;
private readonly string _packageVersion; private readonly string _packageVersion;
private readonly int _timeout; private readonly int _timeout;
private LoadRemoteManifestOperation _loadCacheManifestOp; private LoadRemoteManifestOperation _loadCacheManifestOp;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
internal WebPlayModeUpdatePackageManifestOperation(WebPlayModeImpl impl, string packageVersion, int timeout) internal WebPlayModeUpdatePackageManifestOperation(WebPlayModeImpl impl, string packageVersion, int timeout)
{ {
_impl = impl; _impl = impl;
_packageVersion = packageVersion; _packageVersion = packageVersion;
_timeout = timeout; _timeout = timeout;
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
_steps = ESteps.CheckParams; _steps = ESteps.CheckParams;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
if (_steps == ESteps.None || _steps == ESteps.Done) if (_steps == ESteps.None || _steps == ESteps.Done)
return; return;
if (_steps == ESteps.CheckParams) if (_steps == ESteps.CheckParams)
{ {
if (string.IsNullOrEmpty(_packageVersion)) if (string.IsNullOrEmpty(_packageVersion))
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = "Package version is null or empty."; Error = "Package version is null or empty.";
return; return;
} }
_steps = ESteps.CheckActiveManifest; _steps = ESteps.CheckActiveManifest;
} }
if (_steps == ESteps.CheckActiveManifest) if (_steps == ESteps.CheckActiveManifest)
{ {
// 检测当前激活的清单对象 // 检测当前激活的清单对象
if (_impl.ActiveManifest != null && _impl.ActiveManifest.PackageVersion == _packageVersion) if (_impl.ActiveManifest != null && _impl.ActiveManifest.PackageVersion == _packageVersion)
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
else else
{ {
_steps = ESteps.LoadRemoteManifest; _steps = ESteps.LoadRemoteManifest;
} }
} }
if (_steps == ESteps.LoadRemoteManifest) if (_steps == ESteps.LoadRemoteManifest)
{ {
if (_loadCacheManifestOp == null) if (_loadCacheManifestOp == null)
{ {
_loadCacheManifestOp = new LoadRemoteManifestOperation(_impl.RemoteServices, _impl.PackageName, _packageVersion, _timeout); _loadCacheManifestOp = new LoadRemoteManifestOperation(_impl.RemoteServices, _impl.PackageName, _packageVersion, _timeout);
OperationSystem.StartOperation(_impl.PackageName, _loadCacheManifestOp); OperationSystem.StartOperation(_impl.PackageName, _loadCacheManifestOp);
} }
if (_loadCacheManifestOp.IsDone == false) if (_loadCacheManifestOp.IsDone == false)
return; return;
if (_loadCacheManifestOp.Status == EOperationStatus.Succeed) if (_loadCacheManifestOp.Status == EOperationStatus.Succeed)
{ {
_impl.ActiveManifest = _loadCacheManifestOp.Manifest; _impl.ActiveManifest = _loadCacheManifestOp.Manifest;
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
else else
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = _loadCacheManifestOp.Error; Error = _loadCacheManifestOp.Error;
} }
} }
} }
} }
} }

View File

@ -4,162 +4,162 @@ using UnityEngine;
namespace YooAsset namespace YooAsset
{ {
/// <summary> /// <summary>
/// 请求远端包裹的最新版本 /// 请求远端包裹的最新版本
/// </summary> /// </summary>
public abstract class UpdatePackageVersionOperation : AsyncOperationBase public abstract class UpdatePackageVersionOperation : AsyncOperationBase
{ {
/// <summary> /// <summary>
/// 当前最新的包裹版本 /// 当前最新的包裹版本
/// </summary> /// </summary>
public string PackageVersion { protected set; get; } public string PackageVersion { protected set; get; }
} }
/// <summary> /// <summary>
/// 编辑器下模拟模式的请求远端包裹的最新版本 /// 编辑器下模拟模式的请求远端包裹的最新版本
/// </summary> /// </summary>
internal sealed class EditorPlayModeUpdatePackageVersionOperation : UpdatePackageVersionOperation internal sealed class EditorPlayModeUpdatePackageVersionOperation : UpdatePackageVersionOperation
{ {
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
} }
} }
/// <summary> /// <summary>
/// 离线模式的请求远端包裹的最新版本 /// 离线模式的请求远端包裹的最新版本
/// </summary> /// </summary>
internal sealed class OfflinePlayModeUpdatePackageVersionOperation : UpdatePackageVersionOperation internal sealed class OfflinePlayModeUpdatePackageVersionOperation : UpdatePackageVersionOperation
{ {
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
} }
} }
/// <summary> /// <summary>
/// 联机模式的请求远端包裹的最新版本 /// 联机模式的请求远端包裹的最新版本
/// </summary> /// </summary>
internal sealed class HostPlayModeUpdatePackageVersionOperation : UpdatePackageVersionOperation internal sealed class HostPlayModeUpdatePackageVersionOperation : UpdatePackageVersionOperation
{ {
private enum ESteps private enum ESteps
{ {
None, None,
QueryRemotePackageVersion, QueryRemotePackageVersion,
Done, Done,
} }
private readonly HostPlayModeImpl _impl; private readonly HostPlayModeImpl _impl;
private readonly bool _appendTimeTicks; private readonly bool _appendTimeTicks;
private readonly int _timeout; private readonly int _timeout;
private QueryRemotePackageVersionOperation _queryRemotePackageVersionOp; private QueryRemotePackageVersionOperation _queryRemotePackageVersionOp;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
internal HostPlayModeUpdatePackageVersionOperation(HostPlayModeImpl impl, bool appendTimeTicks, int timeout) internal HostPlayModeUpdatePackageVersionOperation(HostPlayModeImpl impl, bool appendTimeTicks, int timeout)
{ {
_impl = impl; _impl = impl;
_appendTimeTicks = appendTimeTicks; _appendTimeTicks = appendTimeTicks;
_timeout = timeout; _timeout = timeout;
} }
internal override void InternalOnStart() internal override void InternalOnStart()
{ {
_steps = ESteps.QueryRemotePackageVersion; _steps = ESteps.QueryRemotePackageVersion;
} }
internal override void InternalOnUpdate() internal override void InternalOnUpdate()
{ {
if (_steps == ESteps.None || _steps == ESteps.Done) if (_steps == ESteps.None || _steps == ESteps.Done)
return; return;
if (_steps == ESteps.QueryRemotePackageVersion) if (_steps == ESteps.QueryRemotePackageVersion)
{ {
if (_queryRemotePackageVersionOp == null) if (_queryRemotePackageVersionOp == null)
{ {
_queryRemotePackageVersionOp = new QueryRemotePackageVersionOperation(_impl.RemoteServices, _impl.PackageName, _appendTimeTicks, _timeout); _queryRemotePackageVersionOp = new QueryRemotePackageVersionOperation(_impl.RemoteServices, _impl.PackageName, _appendTimeTicks, _timeout);
OperationSystem.StartOperation(_impl.PackageName, _queryRemotePackageVersionOp); OperationSystem.StartOperation(_impl.PackageName, _queryRemotePackageVersionOp);
} }
if (_queryRemotePackageVersionOp.IsDone == false) if (_queryRemotePackageVersionOp.IsDone == false)
return; return;
if (_queryRemotePackageVersionOp.Status == EOperationStatus.Succeed) if (_queryRemotePackageVersionOp.Status == EOperationStatus.Succeed)
{ {
PackageVersion = _queryRemotePackageVersionOp.PackageVersion; PackageVersion = _queryRemotePackageVersionOp.PackageVersion;
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
else else
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;
Error = _queryRemotePackageVersionOp.Error; Error = _queryRemotePackageVersionOp.Error;
} }
} }
} }
} }
/// <summary>
/// WebGL模式的请求远端包裹的最新版本
/// </summary>
internal sealed class WebPlayModeUpdatePackageVersionOperation : UpdatePackageVersionOperation
{
private enum ESteps
{
None,
QueryRemotePackageVersion,
Done,
}
private readonly WebPlayModeImpl _impl; /// <summary>
private readonly bool _appendTimeTicks; /// WebGL模式的请求远端包裹的最新版本
private readonly int _timeout; /// </summary>
private QueryRemotePackageVersionOperation _queryRemotePackageVersionOp; internal sealed class WebPlayModeUpdatePackageVersionOperation : UpdatePackageVersionOperation
private ESteps _steps = ESteps.None; {
private enum ESteps
internal WebPlayModeUpdatePackageVersionOperation(WebPlayModeImpl impl, bool appendTimeTicks, int timeout) {
{ None,
_impl = impl; QueryRemotePackageVersion,
_appendTimeTicks = appendTimeTicks; Done,
_timeout = timeout; }
}
internal override void InternalOnStart()
{
_steps = ESteps.QueryRemotePackageVersion;
}
internal override void InternalOnUpdate()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.QueryRemotePackageVersion) private readonly WebPlayModeImpl _impl;
{ private readonly bool _appendTimeTicks;
if (_queryRemotePackageVersionOp == null) private readonly int _timeout;
{ private QueryRemotePackageVersionOperation _queryRemotePackageVersionOp;
_queryRemotePackageVersionOp = new QueryRemotePackageVersionOperation(_impl.RemoteServices, _impl.PackageName, _appendTimeTicks, _timeout); private ESteps _steps = ESteps.None;
OperationSystem.StartOperation(_impl.PackageName, _queryRemotePackageVersionOp);
}
if (_queryRemotePackageVersionOp.IsDone == false) internal WebPlayModeUpdatePackageVersionOperation(WebPlayModeImpl impl, bool appendTimeTicks, int timeout)
return; {
_impl = impl;
_appendTimeTicks = appendTimeTicks;
_timeout = timeout;
}
internal override void InternalOnStart()
{
_steps = ESteps.QueryRemotePackageVersion;
}
internal override void InternalOnUpdate()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_queryRemotePackageVersionOp.Status == EOperationStatus.Succeed) if (_steps == ESteps.QueryRemotePackageVersion)
{ {
PackageVersion = _queryRemotePackageVersionOp.PackageVersion; if (_queryRemotePackageVersionOp == null)
_steps = ESteps.Done; {
Status = EOperationStatus.Succeed; _queryRemotePackageVersionOp = new QueryRemotePackageVersionOperation(_impl.RemoteServices, _impl.PackageName, _appendTimeTicks, _timeout);
} OperationSystem.StartOperation(_impl.PackageName, _queryRemotePackageVersionOp);
else }
{
_steps = ESteps.Done; if (_queryRemotePackageVersionOp.IsDone == false)
Status = EOperationStatus.Failed; return;
Error = _queryRemotePackageVersionOp.Error;
} if (_queryRemotePackageVersionOp.Status == EOperationStatus.Succeed)
} {
} PackageVersion = _queryRemotePackageVersionOp.PackageVersion;
} _steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = _queryRemotePackageVersionOp.Error;
}
}
}
}
} }

View File

@ -3,50 +3,50 @@ using System.Linq;
namespace YooAsset namespace YooAsset
{ {
[Serializable] [Serializable]
internal class PackageAsset internal class PackageAsset
{ {
/// <summary> /// <summary>
/// 可寻址地址 /// 可寻址地址
/// </summary> /// </summary>
public string Address; public string Address;
/// <summary>
/// 资源路径
/// </summary>
public string AssetPath;
/// <summary> /// <summary>
/// 资源GUID /// 资源路径
/// </summary> /// </summary>
public string AssetGUID; public string AssetPath;
/// <summary> /// <summary>
/// 资源的分类标签 /// 资源GUID
/// </summary> /// </summary>
public string[] AssetTags; public string AssetGUID;
/// <summary>
/// 所属资源包ID
/// </summary>
public int BundleID;
/// <summary> /// <summary>
/// 是否包含Tag /// 资源的分类标签
/// </summary> /// </summary>
public bool HasTag(string[] tags) public string[] AssetTags;
{
if (tags == null || tags.Length == 0)
return false;
if (AssetTags == null || AssetTags.Length == 0)
return false;
foreach (var tag in tags) /// <summary>
{ /// 所属资源包ID
if (AssetTags.Contains(tag)) /// </summary>
return true; public int BundleID;
}
return false; /// <summary>
} /// 是否包含Tag
} /// </summary>
public bool HasTag(string[] tags)
{
if (tags == null || tags.Length == 0)
return false;
if (AssetTags == null || AssetTags.Length == 0)
return false;
foreach (var tag in tags)
{
if (AssetTags.Contains(tag))
return true;
}
return false;
}
}
} }

View File

@ -3,150 +3,150 @@ using System.Linq;
namespace YooAsset namespace YooAsset
{ {
[Serializable] [Serializable]
internal class PackageBundle internal class PackageBundle
{ {
/// <summary> /// <summary>
/// 资源包名称 /// 资源包名称
/// </summary> /// </summary>
public string BundleName; public string BundleName;
/// <summary> /// <summary>
/// Unity引擎生成的CRC /// Unity引擎生成的CRC
/// </summary> /// </summary>
public uint UnityCRC; public uint UnityCRC;
/// <summary> /// <summary>
/// 文件哈希值 /// 文件哈希值
/// </summary> /// </summary>
public string FileHash; public string FileHash;
/// <summary> /// <summary>
/// 文件校验码 /// 文件校验码
/// </summary> /// </summary>
public string FileCRC; public string FileCRC;
/// <summary> /// <summary>
/// 文件大小(字节数) /// 文件大小(字节数)
/// </summary> /// </summary>
public long FileSize; public long FileSize;
/// <summary> /// <summary>
/// 文件是否加密 /// 文件是否加密
/// </summary> /// </summary>
public bool Encrypted; public bool Encrypted;
/// <summary>
/// 资源包的分类标签
/// </summary>
public string[] Tags;
/// <summary> /// <summary>
/// 依赖的资源包ID集合 /// 资源包的分类标签
/// </summary> /// </summary>
public int[] DependIDs; public string[] Tags;
/// <summary>
/// 依赖的资源包ID集合
/// </summary>
public int[] DependIDs;
/// <summary> /// <summary>
/// 所属的包裹名称 /// 所属的包裹名称
/// </summary> /// </summary>
public string PackageName { private set; get; } public string PackageName { private set; get; }
/// <summary> /// <summary>
/// 所属的构建管线 /// 所属的构建管线
/// </summary> /// </summary>
public string Buildpipeline { private set; get; } public string Buildpipeline { private set; get; }
/// <summary> /// <summary>
/// 缓存GUID /// 缓存GUID
/// </summary> /// </summary>
public string CacheGUID public string CacheGUID
{ {
get { return FileHash; } get { return FileHash; }
} }
/// <summary> /// <summary>
/// 文件名称 /// 文件名称
/// </summary> /// </summary>
private string _fileName; private string _fileName;
public string FileName public string FileName
{ {
get get
{ {
if (string.IsNullOrEmpty(_fileName)) if (string.IsNullOrEmpty(_fileName))
throw new Exception("Should never get here !"); throw new Exception("Should never get here !");
return _fileName; return _fileName;
} }
} }
/// <summary> /// <summary>
/// 文件后缀名 /// 文件后缀名
/// </summary> /// </summary>
private string _fileExtension; private string _fileExtension;
public string FileExtension public string FileExtension
{ {
get get
{ {
if (string.IsNullOrEmpty(_fileExtension)) if (string.IsNullOrEmpty(_fileExtension))
throw new Exception("Should never get here !"); throw new Exception("Should never get here !");
return _fileExtension; return _fileExtension;
} }
} }
public PackageBundle() public PackageBundle()
{ {
} }
/// <summary> /// <summary>
/// 解析资源包 /// 解析资源包
/// </summary> /// </summary>
public void ParseBundle(PackageManifest manifest) public void ParseBundle(PackageManifest manifest)
{ {
PackageName = manifest.PackageName; PackageName = manifest.PackageName;
Buildpipeline = manifest.BuildPipeline; Buildpipeline = manifest.BuildPipeline;
_fileExtension = ManifestTools.GetRemoteBundleFileExtension(BundleName); _fileExtension = ManifestTools.GetRemoteBundleFileExtension(BundleName);
_fileName = ManifestTools.GetRemoteBundleFileName(manifest.OutputNameStyle, BundleName, _fileExtension, FileHash); _fileName = ManifestTools.GetRemoteBundleFileName(manifest.OutputNameStyle, BundleName, _fileExtension, FileHash);
} }
/// <summary> /// <summary>
/// 是否包含Tag /// 是否包含Tag
/// </summary> /// </summary>
public bool HasTag(string[] tags) public bool HasTag(string[] tags)
{ {
if (tags == null || tags.Length == 0) if (tags == null || tags.Length == 0)
return false; return false;
if (Tags == null || Tags.Length == 0) if (Tags == null || Tags.Length == 0)
return false; return false;
foreach (var tag in tags) foreach (var tag in tags)
{ {
if (Tags.Contains(tag)) if (Tags.Contains(tag))
return true; return true;
} }
return false; return false;
} }
/// <summary> /// <summary>
/// 是否包含任意Tags /// 是否包含任意Tags
/// </summary> /// </summary>
public bool HasAnyTags() public bool HasAnyTags()
{ {
if (Tags != null && Tags.Length > 0) if (Tags != null && Tags.Length > 0)
return true; return true;
else else
return false; return false;
} }
/// <summary> /// <summary>
/// 检测资源包文件内容是否相同 /// 检测资源包文件内容是否相同
/// </summary> /// </summary>
public bool Equals(PackageBundle otherBundle) public bool Equals(PackageBundle otherBundle)
{ {
if (FileHash == otherBundle.FileHash) if (FileHash == otherBundle.FileHash)
return true; return true;
return false; return false;
} }
} }
} }

View File

@ -6,347 +6,347 @@ using System.Collections.Generic;
namespace YooAsset namespace YooAsset
{ {
/// <summary> /// <summary>
/// 清单文件 /// 清单文件
/// </summary> /// </summary>
[Serializable] [Serializable]
internal class PackageManifest internal class PackageManifest
{ {
/// <summary> /// <summary>
/// 文件版本 /// 文件版本
/// </summary> /// </summary>
public string FileVersion; public string FileVersion;
/// <summary> /// <summary>
/// 启用可寻址资源定位 /// 启用可寻址资源定位
/// </summary> /// </summary>
public bool EnableAddressable; public bool EnableAddressable;
/// <summary> /// <summary>
/// 资源定位地址大小写不敏感 /// 资源定位地址大小写不敏感
/// </summary> /// </summary>
public bool LocationToLower; public bool LocationToLower;
/// <summary> /// <summary>
/// 包含资源GUID数据 /// 包含资源GUID数据
/// </summary> /// </summary>
public bool IncludeAssetGUID; public bool IncludeAssetGUID;
/// <summary> /// <summary>
/// 文件名称样式 /// 文件名称样式
/// </summary> /// </summary>
public int OutputNameStyle; public int OutputNameStyle;
/// <summary> /// <summary>
/// 构建管线名称 /// 构建管线名称
/// </summary> /// </summary>
public string BuildPipeline; public string BuildPipeline;
/// <summary> /// <summary>
/// 资源包裹名称 /// 资源包裹名称
/// </summary> /// </summary>
public string PackageName; public string PackageName;
/// <summary> /// <summary>
/// 资源包裹的版本信息 /// 资源包裹的版本信息
/// </summary> /// </summary>
public string PackageVersion; public string PackageVersion;
/// <summary> /// <summary>
/// 资源列表(主动收集的资源列表) /// 资源列表(主动收集的资源列表)
/// </summary> /// </summary>
public List<PackageAsset> AssetList = new List<PackageAsset>(); public List<PackageAsset> AssetList = new List<PackageAsset>();
/// <summary> /// <summary>
/// 资源包列表 /// 资源包列表
/// </summary> /// </summary>
public List<PackageBundle> BundleList = new List<PackageBundle>(); public List<PackageBundle> BundleList = new List<PackageBundle>();
/// <summary> /// <summary>
/// 资源包集合提供BundleName获取PackageBundle /// 资源包集合提供BundleName获取PackageBundle
/// </summary> /// </summary>
[NonSerialized] [NonSerialized]
public Dictionary<string, PackageBundle> BundleDic1; public Dictionary<string, PackageBundle> BundleDic1;
/// <summary> /// <summary>
/// 资源包集合提供FileName获取PackageBundle /// 资源包集合提供FileName获取PackageBundle
/// </summary> /// </summary>
[NonSerialized] [NonSerialized]
public Dictionary<string, PackageBundle> BundleDic2; public Dictionary<string, PackageBundle> BundleDic2;
/// <summary> /// <summary>
/// 资源映射集合提供AssetPath获取PackageAsset /// 资源映射集合提供AssetPath获取PackageAsset
/// </summary> /// </summary>
[NonSerialized] [NonSerialized]
public Dictionary<string, PackageAsset> AssetDic; public Dictionary<string, PackageAsset> AssetDic;
/// <summary> /// <summary>
/// 资源路径映射集合提供Location获取AssetPath /// 资源路径映射集合提供Location获取AssetPath
/// </summary> /// </summary>
[NonSerialized] [NonSerialized]
public Dictionary<string, string> AssetPathMapping1; public Dictionary<string, string> AssetPathMapping1;
/// <summary> /// <summary>
/// 资源路径映射集合提供AssetGUID获取AssetPath /// 资源路径映射集合提供AssetGUID获取AssetPath
/// </summary> /// </summary>
[NonSerialized] [NonSerialized]
public Dictionary<string, string> AssetPathMapping2; public Dictionary<string, string> AssetPathMapping2;
/// <summary> /// <summary>
/// 该资源清单所有文件的缓存GUID集合 /// 该资源清单所有文件的缓存GUID集合
/// </summary> /// </summary>
[NonSerialized] [NonSerialized]
public HashSet<string> CacheGUIDs = new HashSet<string>(); public HashSet<string> CacheGUIDs = new HashSet<string>();
/// <summary> /// <summary>
/// 尝试映射为资源路径 /// 尝试映射为资源路径
/// </summary> /// </summary>
public string TryMappingToAssetPath(string location) public string TryMappingToAssetPath(string location)
{ {
if (string.IsNullOrEmpty(location)) if (string.IsNullOrEmpty(location))
return string.Empty; return string.Empty;
if (LocationToLower) if (LocationToLower)
location = location.ToLower(); location = location.ToLower();
if (AssetPathMapping1.TryGetValue(location, out string assetPath)) if (AssetPathMapping1.TryGetValue(location, out string assetPath))
return assetPath; return assetPath;
else else
return string.Empty; return string.Empty;
} }
/// <summary> /// <summary>
/// 获取主资源包 /// 获取主资源包
/// 注意:传入的资源路径一定合法有效! /// 注意:传入的资源路径一定合法有效!
/// </summary> /// </summary>
public PackageBundle GetMainPackageBundle(string assetPath) public PackageBundle GetMainPackageBundle(string assetPath)
{ {
if (AssetDic.TryGetValue(assetPath, out PackageAsset packageAsset)) if (AssetDic.TryGetValue(assetPath, out PackageAsset packageAsset))
{ {
int bundleID = packageAsset.BundleID; int bundleID = packageAsset.BundleID;
if (bundleID >= 0 && bundleID < BundleList.Count) if (bundleID >= 0 && bundleID < BundleList.Count)
{ {
var packageBundle = BundleList[bundleID]; var packageBundle = BundleList[bundleID];
return packageBundle; return packageBundle;
} }
else else
{ {
throw new Exception($"Invalid bundle id : {bundleID} Asset path : {assetPath}"); throw new Exception($"Invalid bundle id : {bundleID} Asset path : {assetPath}");
} }
} }
else else
{ {
throw new Exception("Should never get here !"); throw new Exception("Should never get here !");
} }
} }
/// <summary> /// <summary>
/// 获取资源依赖列表 /// 获取资源依赖列表
/// 注意:传入的资源路径一定合法有效! /// 注意:传入的资源路径一定合法有效!
/// </summary> /// </summary>
public PackageBundle[] GetAllDependencies(string assetPath) public PackageBundle[] GetAllDependencies(string assetPath)
{ {
var packageBundle = GetMainPackageBundle(assetPath); var packageBundle = GetMainPackageBundle(assetPath);
List<PackageBundle> result = new List<PackageBundle>(packageBundle.DependIDs.Length); List<PackageBundle> result = new List<PackageBundle>(packageBundle.DependIDs.Length);
foreach (var dependID in packageBundle.DependIDs) foreach (var dependID in packageBundle.DependIDs)
{ {
if (dependID >= 0 && dependID < BundleList.Count) if (dependID >= 0 && dependID < BundleList.Count)
{ {
var dependBundle = BundleList[dependID]; var dependBundle = BundleList[dependID];
result.Add(dependBundle); result.Add(dependBundle);
} }
else else
{ {
throw new Exception($"Invalid bundle id : {dependID} Asset path : {assetPath}"); throw new Exception($"Invalid bundle id : {dependID} Asset path : {assetPath}");
} }
} }
return result.ToArray(); return result.ToArray();
} }
/// <summary> /// <summary>
/// 尝试获取包裹的资源 /// 尝试获取包裹的资源
/// </summary> /// </summary>
public bool TryGetPackageAsset(string assetPath, out PackageAsset result) public bool TryGetPackageAsset(string assetPath, out PackageAsset result)
{ {
return AssetDic.TryGetValue(assetPath, out result); return AssetDic.TryGetValue(assetPath, out result);
} }
/// <summary> /// <summary>
/// 尝试获取包裹的资源包 /// 尝试获取包裹的资源包
/// </summary> /// </summary>
public bool TryGetPackageBundleByBundleName(string bundleName, out PackageBundle result) public bool TryGetPackageBundleByBundleName(string bundleName, out PackageBundle result)
{ {
return BundleDic1.TryGetValue(bundleName, out result); return BundleDic1.TryGetValue(bundleName, out result);
} }
/// <summary> /// <summary>
/// 尝试获取包裹的资源包 /// 尝试获取包裹的资源包
/// </summary> /// </summary>
public bool TryGetPackageBundleByFileName(string fileName, out PackageBundle result) public bool TryGetPackageBundleByFileName(string fileName, out PackageBundle result)
{ {
return BundleDic2.TryGetValue(fileName, out result); return BundleDic2.TryGetValue(fileName, out result);
} }
/// <summary> /// <summary>
/// 是否包含资源文件 /// 是否包含资源文件
/// </summary> /// </summary>
public bool IsIncludeBundleFile(string cacheGUID) public bool IsIncludeBundleFile(string cacheGUID)
{ {
return CacheGUIDs.Contains(cacheGUID); return CacheGUIDs.Contains(cacheGUID);
} }
/// <summary> /// <summary>
/// 获取资源信息列表 /// 获取资源信息列表
/// </summary> /// </summary>
public AssetInfo[] GetAssetsInfoByTags(string[] tags) public AssetInfo[] GetAssetsInfoByTags(string[] tags)
{ {
List<AssetInfo> result = new List<AssetInfo>(100); List<AssetInfo> result = new List<AssetInfo>(100);
foreach (var packageAsset in AssetList) foreach (var packageAsset in AssetList)
{ {
if (packageAsset.HasTag(tags)) if (packageAsset.HasTag(tags))
{ {
AssetInfo assetInfo = new AssetInfo(PackageName, packageAsset, null); AssetInfo assetInfo = new AssetInfo(PackageName, packageAsset, null);
result.Add(assetInfo); result.Add(assetInfo);
} }
} }
return result.ToArray(); return result.ToArray();
} }
/// <summary> /// <summary>
/// 资源定位地址转换为资源信息。 /// 资源定位地址转换为资源信息。
/// </summary> /// </summary>
/// <returns>如果转换失败会返回一个无效的资源信息类</returns> /// <returns>如果转换失败会返回一个无效的资源信息类</returns>
public AssetInfo ConvertLocationToAssetInfo(string location, System.Type assetType) public AssetInfo ConvertLocationToAssetInfo(string location, System.Type assetType)
{ {
DebugCheckLocation(location); DebugCheckLocation(location);
string assetPath = ConvertLocationToAssetInfoMapping(location); string assetPath = ConvertLocationToAssetInfoMapping(location);
if (TryGetPackageAsset(assetPath, out PackageAsset packageAsset)) if (TryGetPackageAsset(assetPath, out PackageAsset packageAsset))
{ {
AssetInfo assetInfo = new AssetInfo(PackageName, packageAsset, assetType); AssetInfo assetInfo = new AssetInfo(PackageName, packageAsset, assetType);
return assetInfo; return assetInfo;
} }
else else
{ {
string error; string error;
if (string.IsNullOrEmpty(location)) if (string.IsNullOrEmpty(location))
error = $"The location is null or empty !"; error = $"The location is null or empty !";
else else
error = $"The location is invalid : {location}"; error = $"The location is invalid : {location}";
AssetInfo assetInfo = new AssetInfo(PackageName, error); AssetInfo assetInfo = new AssetInfo(PackageName, error);
return assetInfo; return assetInfo;
} }
} }
private string ConvertLocationToAssetInfoMapping(string location) private string ConvertLocationToAssetInfoMapping(string location)
{ {
if (string.IsNullOrEmpty(location)) if (string.IsNullOrEmpty(location))
{ {
YooLogger.Error("Failed to mapping location to asset path, The location is null or empty."); YooLogger.Error("Failed to mapping location to asset path, The location is null or empty.");
return string.Empty; return string.Empty;
} }
if (LocationToLower) if (LocationToLower)
location = location.ToLower(); location = location.ToLower();
if (AssetPathMapping1.TryGetValue(location, out string assetPath)) if (AssetPathMapping1.TryGetValue(location, out string assetPath))
{ {
return assetPath; return assetPath;
} }
else else
{ {
YooLogger.Warning($"Failed to mapping location to asset path : {location}"); YooLogger.Warning($"Failed to mapping location to asset path : {location}");
return string.Empty; return string.Empty;
} }
} }
/// <summary> /// <summary>
/// 资源GUID转换为资源信息。 /// 资源GUID转换为资源信息。
/// </summary> /// </summary>
/// <returns>如果转换失败会返回一个无效的资源信息类</returns> /// <returns>如果转换失败会返回一个无效的资源信息类</returns>
public AssetInfo ConvertAssetGUIDToAssetInfo(string assetGUID, System.Type assetType) public AssetInfo ConvertAssetGUIDToAssetInfo(string assetGUID, System.Type assetType)
{ {
if (IncludeAssetGUID == false) if (IncludeAssetGUID == false)
{ {
YooLogger.Warning("Package manifest not include asset guid ! Please check asset bundle collector settings."); YooLogger.Warning("Package manifest not include asset guid ! Please check asset bundle collector settings.");
AssetInfo assetInfo = new AssetInfo(PackageName, "AssetGUID data is empty !"); AssetInfo assetInfo = new AssetInfo(PackageName, "AssetGUID data is empty !");
return assetInfo; return assetInfo;
} }
string assetPath = ConvertAssetGUIDToAssetInfoMapping(assetGUID); string assetPath = ConvertAssetGUIDToAssetInfoMapping(assetGUID);
if (TryGetPackageAsset(assetPath, out PackageAsset packageAsset)) if (TryGetPackageAsset(assetPath, out PackageAsset packageAsset))
{ {
AssetInfo assetInfo = new AssetInfo(PackageName, packageAsset, assetType); AssetInfo assetInfo = new AssetInfo(PackageName, packageAsset, assetType);
return assetInfo; return assetInfo;
} }
else else
{ {
string error; string error;
if (string.IsNullOrEmpty(assetGUID)) if (string.IsNullOrEmpty(assetGUID))
error = $"The assetGUID is null or empty !"; error = $"The assetGUID is null or empty !";
else else
error = $"The assetGUID is invalid : {assetGUID}"; error = $"The assetGUID is invalid : {assetGUID}";
AssetInfo assetInfo = new AssetInfo(PackageName, error); AssetInfo assetInfo = new AssetInfo(PackageName, error);
return assetInfo; return assetInfo;
} }
} }
private string ConvertAssetGUIDToAssetInfoMapping(string assetGUID) private string ConvertAssetGUIDToAssetInfoMapping(string assetGUID)
{ {
if (string.IsNullOrEmpty(assetGUID)) if (string.IsNullOrEmpty(assetGUID))
{ {
YooLogger.Error("Failed to mapping assetGUID to asset path, The assetGUID is null or empty."); YooLogger.Error("Failed to mapping assetGUID to asset path, The assetGUID is null or empty.");
return string.Empty; return string.Empty;
} }
if (AssetPathMapping2.TryGetValue(assetGUID, out string assetPath)) if (AssetPathMapping2.TryGetValue(assetGUID, out string assetPath))
{ {
return assetPath; return assetPath;
} }
else else
{ {
YooLogger.Warning($"Failed to mapping assetGUID to asset path : {assetGUID}"); YooLogger.Warning($"Failed to mapping assetGUID to asset path : {assetGUID}");
return string.Empty; return string.Empty;
} }
} }
/// <summary> /// <summary>
/// 获取资源包内的主资源列表 /// 获取资源包内的主资源列表
/// </summary> /// </summary>
public string[] GetBundleIncludeAssets(string assetPath) public string[] GetBundleIncludeAssets(string assetPath)
{ {
List<string> assetList = new List<string>(); List<string> assetList = new List<string>();
if (TryGetPackageAsset(assetPath, out PackageAsset result)) if (TryGetPackageAsset(assetPath, out PackageAsset result))
{ {
foreach (var packageAsset in AssetList) foreach (var packageAsset in AssetList)
{ {
if (packageAsset.BundleID == result.BundleID) if (packageAsset.BundleID == result.BundleID)
{ {
assetList.Add(packageAsset.AssetPath); assetList.Add(packageAsset.AssetPath);
} }
} }
} }
return assetList.ToArray(); return assetList.ToArray();
} }
#region 调试方法 #region 调试方法
[Conditional("DEBUG")] [Conditional("DEBUG")]
private void DebugCheckLocation(string location) private void DebugCheckLocation(string location)
{ {
if (string.IsNullOrEmpty(location) == false) if (string.IsNullOrEmpty(location) == false)
{ {
// 检查路径末尾是否有空格 // 检查路径末尾是否有空格
int index = location.LastIndexOf(" "); int index = location.LastIndexOf(" ");
if (index != -1) if (index != -1)
{ {
if (location.Length == index + 1) if (location.Length == index + 1)
YooLogger.Warning($"Found blank character in location : \"{location}\""); YooLogger.Warning($"Found blank character in location : \"{location}\"");
} }
if (location.IndexOfAny(System.IO.Path.GetInvalidPathChars()) >= 0) if (location.IndexOfAny(System.IO.Path.GetInvalidPathChars()) >= 0)
YooLogger.Warning($"Found illegal character in location : \"{location}\""); YooLogger.Warning($"Found illegal character in location : \"{location}\"");
} }
} }
#endregion #endregion
} }
} }

View File

@ -3,41 +3,41 @@ using System.Reflection;
namespace YooAsset namespace YooAsset
{ {
public static class EditorSimulateModeHelper public static class EditorSimulateModeHelper
{ {
private static System.Type _classType; private static System.Type _classType;
/// <summary> /// <summary>
/// 编辑器下模拟构建清单 /// 编辑器下模拟构建清单
/// </summary> /// </summary>
public static string SimulateBuild(string buildPipelineName, string packageName) public static string SimulateBuild(string buildPipelineName, string packageName)
{ {
if (_classType == null) if (_classType == null)
_classType = Assembly.Load("YooAsset.Editor").GetType("YooAsset.Editor.AssetBundleSimulateBuilder"); _classType = Assembly.Load("YooAsset.Editor").GetType("YooAsset.Editor.AssetBundleSimulateBuilder");
string manifestFilePath = (string)InvokePublicStaticMethod(_classType, "SimulateBuild", buildPipelineName, packageName); string manifestFilePath = (string)InvokePublicStaticMethod(_classType, "SimulateBuild", buildPipelineName, packageName);
return manifestFilePath; return manifestFilePath;
} }
/// <summary> /// <summary>
/// 编辑器下模拟构建清单 /// 编辑器下模拟构建清单
/// </summary> /// </summary>
public static string SimulateBuild(EDefaultBuildPipeline buildPipeline, string packageName) public static string SimulateBuild(EDefaultBuildPipeline buildPipeline, string packageName)
{ {
return SimulateBuild(buildPipeline.ToString(), packageName); return SimulateBuild(buildPipeline.ToString(), packageName);
} }
private static object InvokePublicStaticMethod(System.Type type, string method, params object[] parameters) private static object InvokePublicStaticMethod(System.Type type, string method, params object[] parameters)
{ {
var methodInfo = type.GetMethod(method, BindingFlags.Public | BindingFlags.Static); var methodInfo = type.GetMethod(method, BindingFlags.Public | BindingFlags.Static);
if (methodInfo == null) if (methodInfo == null)
{ {
UnityEngine.Debug.LogError($"{type.FullName} not found method : {method}"); UnityEngine.Debug.LogError($"{type.FullName} not found method : {method}");
return null; return null;
} }
return methodInfo.Invoke(null, parameters); return methodInfo.Invoke(null, parameters);
} }
} }
} }
#else #else
namespace YooAsset namespace YooAsset

View File

@ -4,158 +4,158 @@ using System.Collections.Generic;
namespace YooAsset namespace YooAsset
{ {
internal class EditorSimulateModeImpl : IPlayMode, IBundleQuery internal class EditorSimulateModeImpl : IPlayMode, IBundleQuery
{ {
private PackageManifest _activeManifest; private PackageManifest _activeManifest;
private ResourceAssist _assist; private ResourceAssist _assist;
public readonly string PackageName; public readonly string PackageName;
public DownloadManager Download public DownloadManager Download
{ {
get { return _assist.Download; } get { return _assist.Download; }
} }
public EditorSimulateModeImpl(string packageName) public EditorSimulateModeImpl(string packageName)
{ {
PackageName = packageName; PackageName = packageName;
} }
/// <summary> /// <summary>
/// 异步初始化 /// 异步初始化
/// </summary> /// </summary>
public InitializationOperation InitializeAsync(ResourceAssist assist, string simulateManifestFilePath) public InitializationOperation InitializeAsync(ResourceAssist assist, string simulateManifestFilePath)
{ {
_assist = assist; _assist = assist;
var operation = new EditorSimulateModeInitializationOperation(this, simulateManifestFilePath); var operation = new EditorSimulateModeInitializationOperation(this, simulateManifestFilePath);
OperationSystem.StartOperation(PackageName, operation); OperationSystem.StartOperation(PackageName, operation);
return operation; return operation;
} }
#region IPlayMode接口 #region IPlayMode接口
public PackageManifest ActiveManifest public PackageManifest ActiveManifest
{ {
set set
{ {
_activeManifest = value; _activeManifest = value;
} }
get get
{ {
return _activeManifest; return _activeManifest;
} }
} }
public void FlushManifestVersionFile() public void FlushManifestVersionFile()
{ {
} }
UpdatePackageVersionOperation IPlayMode.UpdatePackageVersionAsync(bool appendTimeTicks, int timeout) UpdatePackageVersionOperation IPlayMode.UpdatePackageVersionAsync(bool appendTimeTicks, int timeout)
{ {
var operation = new EditorPlayModeUpdatePackageVersionOperation(); var operation = new EditorPlayModeUpdatePackageVersionOperation();
OperationSystem.StartOperation(PackageName, operation); OperationSystem.StartOperation(PackageName, operation);
return operation; return operation;
} }
UpdatePackageManifestOperation IPlayMode.UpdatePackageManifestAsync(string packageVersion, bool autoSaveVersion, int timeout) UpdatePackageManifestOperation IPlayMode.UpdatePackageManifestAsync(string packageVersion, bool autoSaveVersion, int timeout)
{ {
var operation = new EditorPlayModeUpdatePackageManifestOperation(); var operation = new EditorPlayModeUpdatePackageManifestOperation();
OperationSystem.StartOperation(PackageName, operation); OperationSystem.StartOperation(PackageName, operation);
return operation; return operation;
} }
PreDownloadContentOperation IPlayMode.PreDownloadContentAsync(string packageVersion, int timeout) PreDownloadContentOperation IPlayMode.PreDownloadContentAsync(string packageVersion, int timeout)
{ {
var operation = new EditorPlayModePreDownloadContentOperation(this); var operation = new EditorPlayModePreDownloadContentOperation(this);
OperationSystem.StartOperation(PackageName, operation); OperationSystem.StartOperation(PackageName, operation);
return operation; return operation;
} }
ResourceDownloaderOperation IPlayMode.CreateResourceDownloaderByAll(int downloadingMaxNumber, int failedTryAgain, int timeout) ResourceDownloaderOperation IPlayMode.CreateResourceDownloaderByAll(int downloadingMaxNumber, int failedTryAgain, int timeout)
{ {
return ResourceDownloaderOperation.CreateEmptyDownloader(Download, PackageName, downloadingMaxNumber, failedTryAgain, timeout); return ResourceDownloaderOperation.CreateEmptyDownloader(Download, PackageName, downloadingMaxNumber, failedTryAgain, timeout);
} }
ResourceDownloaderOperation IPlayMode.CreateResourceDownloaderByTags(string[] tags, int downloadingMaxNumber, int failedTryAgain, int timeout) ResourceDownloaderOperation IPlayMode.CreateResourceDownloaderByTags(string[] tags, int downloadingMaxNumber, int failedTryAgain, int timeout)
{ {
return ResourceDownloaderOperation.CreateEmptyDownloader(Download, PackageName, downloadingMaxNumber, failedTryAgain, timeout); return ResourceDownloaderOperation.CreateEmptyDownloader(Download, PackageName, downloadingMaxNumber, failedTryAgain, timeout);
} }
ResourceDownloaderOperation IPlayMode.CreateResourceDownloaderByPaths(AssetInfo[] assetInfos, int downloadingMaxNumber, int failedTryAgain, int timeout) ResourceDownloaderOperation IPlayMode.CreateResourceDownloaderByPaths(AssetInfo[] assetInfos, int downloadingMaxNumber, int failedTryAgain, int timeout)
{ {
return ResourceDownloaderOperation.CreateEmptyDownloader(Download, PackageName, downloadingMaxNumber, failedTryAgain, timeout); return ResourceDownloaderOperation.CreateEmptyDownloader(Download, PackageName, downloadingMaxNumber, failedTryAgain, timeout);
} }
ResourceUnpackerOperation IPlayMode.CreateResourceUnpackerByAll(int upackingMaxNumber, int failedTryAgain, int timeout) ResourceUnpackerOperation IPlayMode.CreateResourceUnpackerByAll(int upackingMaxNumber, int failedTryAgain, int timeout)
{ {
return ResourceUnpackerOperation.CreateEmptyUnpacker(Download, PackageName, upackingMaxNumber, failedTryAgain, timeout); return ResourceUnpackerOperation.CreateEmptyUnpacker(Download, PackageName, upackingMaxNumber, failedTryAgain, timeout);
} }
ResourceUnpackerOperation IPlayMode.CreateResourceUnpackerByTags(string[] tags, int upackingMaxNumber, int failedTryAgain, int timeout) ResourceUnpackerOperation IPlayMode.CreateResourceUnpackerByTags(string[] tags, int upackingMaxNumber, int failedTryAgain, int timeout)
{ {
return ResourceUnpackerOperation.CreateEmptyUnpacker(Download, PackageName, upackingMaxNumber, failedTryAgain, timeout); return ResourceUnpackerOperation.CreateEmptyUnpacker(Download, PackageName, upackingMaxNumber, failedTryAgain, timeout);
} }
ResourceImporterOperation IPlayMode.CreateResourceImporterByFilePaths(string[] filePaths, int importerMaxNumber, int failedTryAgain, int timeout) ResourceImporterOperation IPlayMode.CreateResourceImporterByFilePaths(string[] filePaths, int importerMaxNumber, int failedTryAgain, int timeout)
{ {
return ResourceImporterOperation.CreateEmptyImporter(Download, PackageName, importerMaxNumber, failedTryAgain, timeout); return ResourceImporterOperation.CreateEmptyImporter(Download, PackageName, importerMaxNumber, failedTryAgain, timeout);
} }
#endregion #endregion
#region IBundleQuery接口 #region IBundleQuery接口
private BundleInfo CreateBundleInfo(PackageBundle packageBundle, AssetInfo assetInfo) private BundleInfo CreateBundleInfo(PackageBundle packageBundle, AssetInfo assetInfo)
{ {
if (packageBundle == null) if (packageBundle == null)
throw new Exception("Should never get here !"); throw new Exception("Should never get here !");
BundleInfo bundleInfo = new BundleInfo(_assist, packageBundle, BundleInfo.ELoadMode.LoadFromEditor); BundleInfo bundleInfo = new BundleInfo(_assist, packageBundle, BundleInfo.ELoadMode.LoadFromEditor);
bundleInfo.IncludeAssetsInEditor = _activeManifest.GetBundleIncludeAssets(assetInfo.AssetPath); bundleInfo.IncludeAssetsInEditor = _activeManifest.GetBundleIncludeAssets(assetInfo.AssetPath);
return bundleInfo; return bundleInfo;
} }
BundleInfo IBundleQuery.GetMainBundleInfo(AssetInfo assetInfo) BundleInfo IBundleQuery.GetMainBundleInfo(AssetInfo assetInfo)
{ {
if (assetInfo.IsInvalid) if (assetInfo.IsInvalid)
throw new Exception("Should never get here !"); throw new Exception("Should never get here !");
// 注意:如果清单里未找到资源包会抛出异常! // 注意:如果清单里未找到资源包会抛出异常!
var packageBundle = _activeManifest.GetMainPackageBundle(assetInfo.AssetPath); var packageBundle = _activeManifest.GetMainPackageBundle(assetInfo.AssetPath);
return CreateBundleInfo(packageBundle, assetInfo); return CreateBundleInfo(packageBundle, assetInfo);
} }
BundleInfo[] IBundleQuery.GetDependBundleInfos(AssetInfo assetInfo) BundleInfo[] IBundleQuery.GetDependBundleInfos(AssetInfo assetInfo)
{ {
if (assetInfo.IsInvalid) if (assetInfo.IsInvalid)
throw new Exception("Should never get here !"); throw new Exception("Should never get here !");
// 注意:如果清单里未找到资源包会抛出异常! // 注意:如果清单里未找到资源包会抛出异常!
var depends = _activeManifest.GetAllDependencies(assetInfo.AssetPath); var depends = _activeManifest.GetAllDependencies(assetInfo.AssetPath);
List<BundleInfo> result = new List<BundleInfo>(depends.Length); List<BundleInfo> result = new List<BundleInfo>(depends.Length);
foreach (var packageBundle in depends) foreach (var packageBundle in depends)
{ {
BundleInfo bundleInfo = CreateBundleInfo(packageBundle, assetInfo); BundleInfo bundleInfo = CreateBundleInfo(packageBundle, assetInfo);
result.Add(bundleInfo); result.Add(bundleInfo);
} }
return result.ToArray(); return result.ToArray();
} }
string IBundleQuery.GetMainBundleName(AssetInfo assetInfo) string IBundleQuery.GetMainBundleName(AssetInfo assetInfo)
{ {
if (assetInfo.IsInvalid) if (assetInfo.IsInvalid)
throw new Exception("Should never get here !"); throw new Exception("Should never get here !");
// 注意:如果清单里未找到资源包会抛出异常! // 注意:如果清单里未找到资源包会抛出异常!
var packageBundle = _activeManifest.GetMainPackageBundle(assetInfo.AssetPath); var packageBundle = _activeManifest.GetMainPackageBundle(assetInfo.AssetPath);
return packageBundle.BundleName; return packageBundle.BundleName;
} }
string[] IBundleQuery.GetDependBundleNames(AssetInfo assetInfo) string[] IBundleQuery.GetDependBundleNames(AssetInfo assetInfo)
{ {
if (assetInfo.IsInvalid) if (assetInfo.IsInvalid)
throw new Exception("Should never get here !"); throw new Exception("Should never get here !");
// 注意:如果清单里未找到资源包会抛出异常! // 注意:如果清单里未找到资源包会抛出异常!
var depends = _activeManifest.GetAllDependencies(assetInfo.AssetPath); var depends = _activeManifest.GetAllDependencies(assetInfo.AssetPath);
List<string> result = new List<string>(depends.Length); List<string> result = new List<string>(depends.Length);
foreach (var packageBundle in depends) foreach (var packageBundle in depends)
{ {
result.Add(packageBundle.BundleName); result.Add(packageBundle.BundleName);
} }
return result.ToArray(); return result.ToArray();
} }
bool IBundleQuery.ManifestValid() bool IBundleQuery.ManifestValid()
{ {
return _activeManifest != null; return _activeManifest != null;
} }
#endregion #endregion
} }
} }

View File

@ -4,414 +4,414 @@ using System.Collections.Generic;
namespace YooAsset namespace YooAsset
{ {
internal class HostPlayModeImpl : IPlayMode, IBundleQuery internal class HostPlayModeImpl : IPlayMode, IBundleQuery
{ {
private PackageManifest _activeManifest; private PackageManifest _activeManifest;
private ResourceAssist _assist; private ResourceAssist _assist;
private IBuildinQueryServices _buildinQueryServices; private IBuildinQueryServices _buildinQueryServices;
private IDeliveryQueryServices _deliveryQueryServices; private IDeliveryQueryServices _deliveryQueryServices;
private IRemoteServices _remoteServices; private IRemoteServices _remoteServices;
public readonly string PackageName; public readonly string PackageName;
public DownloadManager Download public DownloadManager Download
{ {
get { return _assist.Download; } get { return _assist.Download; }
} }
public PersistentManager Persistent public PersistentManager Persistent
{ {
get { return _assist.Persistent; } get { return _assist.Persistent; }
} }
public CacheManager Cache public CacheManager Cache
{ {
get { return _assist.Cache; } get { return _assist.Cache; }
} }
public IRemoteServices RemoteServices public IRemoteServices RemoteServices
{ {
get { return _remoteServices; } get { return _remoteServices; }
} }
public HostPlayModeImpl(string packageName) public HostPlayModeImpl(string packageName)
{ {
PackageName = packageName; PackageName = packageName;
} }
/// <summary> /// <summary>
/// 异步初始化 /// 异步初始化
/// </summary> /// </summary>
public InitializationOperation InitializeAsync(ResourceAssist assist, IBuildinQueryServices buildinQueryServices, IDeliveryQueryServices deliveryQueryServices, IRemoteServices remoteServices) public InitializationOperation InitializeAsync(ResourceAssist assist, IBuildinQueryServices buildinQueryServices, IDeliveryQueryServices deliveryQueryServices, IRemoteServices remoteServices)
{ {
_assist = assist; _assist = assist;
_buildinQueryServices = buildinQueryServices; _buildinQueryServices = buildinQueryServices;
_deliveryQueryServices = deliveryQueryServices; _deliveryQueryServices = deliveryQueryServices;
_remoteServices = remoteServices; _remoteServices = remoteServices;
var operation = new HostPlayModeInitializationOperation(this); var operation = new HostPlayModeInitializationOperation(this);
OperationSystem.StartOperation(PackageName, operation); OperationSystem.StartOperation(PackageName, operation);
return operation; return operation;
} }
// 下载相关 // 下载相关
private List<BundleInfo> ConvertToDownloadList(List<PackageBundle> downloadList) private List<BundleInfo> ConvertToDownloadList(List<PackageBundle> downloadList)
{ {
List<BundleInfo> result = new List<BundleInfo>(downloadList.Count); List<BundleInfo> result = new List<BundleInfo>(downloadList.Count);
foreach (var packageBundle in downloadList) foreach (var packageBundle in downloadList)
{ {
var bundleInfo = ConvertToDownloadInfo(packageBundle); var bundleInfo = ConvertToDownloadInfo(packageBundle);
result.Add(bundleInfo); result.Add(bundleInfo);
} }
return result; return result;
} }
private BundleInfo ConvertToDownloadInfo(PackageBundle packageBundle) private BundleInfo ConvertToDownloadInfo(PackageBundle packageBundle)
{ {
string remoteMainURL = _remoteServices.GetRemoteMainURL(packageBundle.FileName); string remoteMainURL = _remoteServices.GetRemoteMainURL(packageBundle.FileName);
string remoteFallbackURL = _remoteServices.GetRemoteFallbackURL(packageBundle.FileName); string remoteFallbackURL = _remoteServices.GetRemoteFallbackURL(packageBundle.FileName);
BundleInfo bundleInfo = new BundleInfo(_assist, packageBundle, BundleInfo.ELoadMode.LoadFromRemote, remoteMainURL, remoteFallbackURL); BundleInfo bundleInfo = new BundleInfo(_assist, packageBundle, BundleInfo.ELoadMode.LoadFromRemote, remoteMainURL, remoteFallbackURL);
return bundleInfo; return bundleInfo;
} }
// 查询相关 // 查询相关
private bool IsDeliveryPackageBundle(PackageBundle packageBundle) private bool IsDeliveryPackageBundle(PackageBundle packageBundle)
{ {
if (_deliveryQueryServices == null) if (_deliveryQueryServices == null)
return false; return false;
return _deliveryQueryServices.Query(PackageName, packageBundle.FileName, packageBundle.FileCRC); return _deliveryQueryServices.Query(PackageName, packageBundle.FileName, packageBundle.FileCRC);
} }
private bool IsCachedPackageBundle(PackageBundle packageBundle) private bool IsCachedPackageBundle(PackageBundle packageBundle)
{ {
return _assist.Cache.IsCached(packageBundle.CacheGUID); return _assist.Cache.IsCached(packageBundle.CacheGUID);
} }
private bool IsBuildinPackageBundle(PackageBundle packageBundle) private bool IsBuildinPackageBundle(PackageBundle packageBundle)
{ {
return _buildinQueryServices.Query(PackageName, packageBundle.FileName, packageBundle.FileCRC); return _buildinQueryServices.Query(PackageName, packageBundle.FileName, packageBundle.FileCRC);
} }
#region IPlayMode接口 #region IPlayMode接口
public PackageManifest ActiveManifest public PackageManifest ActiveManifest
{ {
set set
{ {
_activeManifest = value; _activeManifest = value;
} }
get get
{ {
return _activeManifest; return _activeManifest;
} }
} }
public void FlushManifestVersionFile() public void FlushManifestVersionFile()
{ {
if (_activeManifest != null) if (_activeManifest != null)
{ {
_assist.Persistent.SaveSandboxPackageVersionFile(_activeManifest.PackageVersion); _assist.Persistent.SaveSandboxPackageVersionFile(_activeManifest.PackageVersion);
} }
} }
UpdatePackageVersionOperation IPlayMode.UpdatePackageVersionAsync(bool appendTimeTicks, int timeout) UpdatePackageVersionOperation IPlayMode.UpdatePackageVersionAsync(bool appendTimeTicks, int timeout)
{ {
var operation = new HostPlayModeUpdatePackageVersionOperation(this, appendTimeTicks, timeout); var operation = new HostPlayModeUpdatePackageVersionOperation(this, appendTimeTicks, timeout);
OperationSystem.StartOperation(PackageName, operation); OperationSystem.StartOperation(PackageName, operation);
return operation; return operation;
} }
UpdatePackageManifestOperation IPlayMode.UpdatePackageManifestAsync(string packageVersion, bool autoSaveVersion, int timeout) UpdatePackageManifestOperation IPlayMode.UpdatePackageManifestAsync(string packageVersion, bool autoSaveVersion, int timeout)
{ {
var operation = new HostPlayModeUpdatePackageManifestOperation(this, packageVersion, autoSaveVersion, timeout); var operation = new HostPlayModeUpdatePackageManifestOperation(this, packageVersion, autoSaveVersion, timeout);
OperationSystem.StartOperation(PackageName, operation); OperationSystem.StartOperation(PackageName, operation);
return operation; return operation;
} }
PreDownloadContentOperation IPlayMode.PreDownloadContentAsync(string packageVersion, int timeout) PreDownloadContentOperation IPlayMode.PreDownloadContentAsync(string packageVersion, int timeout)
{ {
var operation = new HostPlayModePreDownloadContentOperation(this, packageVersion, timeout); var operation = new HostPlayModePreDownloadContentOperation(this, packageVersion, timeout);
OperationSystem.StartOperation(PackageName, operation); OperationSystem.StartOperation(PackageName, operation);
return operation; return operation;
} }
ResourceDownloaderOperation IPlayMode.CreateResourceDownloaderByAll(int downloadingMaxNumber, int failedTryAgain, int timeout) ResourceDownloaderOperation IPlayMode.CreateResourceDownloaderByAll(int downloadingMaxNumber, int failedTryAgain, int timeout)
{ {
List<BundleInfo> downloadList = GetDownloadListByAll(_activeManifest); List<BundleInfo> downloadList = GetDownloadListByAll(_activeManifest);
var operation = new ResourceDownloaderOperation(Download, PackageName, downloadList, downloadingMaxNumber, failedTryAgain, timeout); var operation = new ResourceDownloaderOperation(Download, PackageName, downloadList, downloadingMaxNumber, failedTryAgain, timeout);
return operation; return operation;
} }
public List<BundleInfo> GetDownloadListByAll(PackageManifest manifest) public List<BundleInfo> GetDownloadListByAll(PackageManifest manifest)
{ {
List<PackageBundle> downloadList = new List<PackageBundle>(1000); List<PackageBundle> downloadList = new List<PackageBundle>(1000);
foreach (var packageBundle in manifest.BundleList) foreach (var packageBundle in manifest.BundleList)
{ {
// 忽略分发文件 // 忽略分发文件
if (IsDeliveryPackageBundle(packageBundle)) if (IsDeliveryPackageBundle(packageBundle))
continue; continue;
// 忽略缓存文件 // 忽略缓存文件
if (IsCachedPackageBundle(packageBundle)) if (IsCachedPackageBundle(packageBundle))
continue; continue;
// 忽略APP资源 // 忽略APP资源
if (IsBuildinPackageBundle(packageBundle)) if (IsBuildinPackageBundle(packageBundle))
continue; continue;
downloadList.Add(packageBundle); downloadList.Add(packageBundle);
} }
return ConvertToDownloadList(downloadList); return ConvertToDownloadList(downloadList);
} }
ResourceDownloaderOperation IPlayMode.CreateResourceDownloaderByTags(string[] tags, int downloadingMaxNumber, int failedTryAgain, int timeout) ResourceDownloaderOperation IPlayMode.CreateResourceDownloaderByTags(string[] tags, int downloadingMaxNumber, int failedTryAgain, int timeout)
{ {
List<BundleInfo> downloadList = GetDownloadListByTags(_activeManifest, tags); List<BundleInfo> downloadList = GetDownloadListByTags(_activeManifest, tags);
var operation = new ResourceDownloaderOperation(Download, PackageName, downloadList, downloadingMaxNumber, failedTryAgain, timeout); var operation = new ResourceDownloaderOperation(Download, PackageName, downloadList, downloadingMaxNumber, failedTryAgain, timeout);
return operation; return operation;
} }
public List<BundleInfo> GetDownloadListByTags(PackageManifest manifest, string[] tags) public List<BundleInfo> GetDownloadListByTags(PackageManifest manifest, string[] tags)
{ {
List<PackageBundle> downloadList = new List<PackageBundle>(1000); List<PackageBundle> downloadList = new List<PackageBundle>(1000);
foreach (var packageBundle in manifest.BundleList) foreach (var packageBundle in manifest.BundleList)
{ {
// 忽略分发文件 // 忽略分发文件
if (IsDeliveryPackageBundle(packageBundle)) if (IsDeliveryPackageBundle(packageBundle))
continue; continue;
// 忽略缓存文件 // 忽略缓存文件
if (IsCachedPackageBundle(packageBundle)) if (IsCachedPackageBundle(packageBundle))
continue; continue;
// 忽略APP资源 // 忽略APP资源
if (IsBuildinPackageBundle(packageBundle)) if (IsBuildinPackageBundle(packageBundle))
continue; continue;
// 如果未带任何标记,则统一下载 // 如果未带任何标记,则统一下载
if (packageBundle.HasAnyTags() == false) if (packageBundle.HasAnyTags() == false)
{ {
downloadList.Add(packageBundle); downloadList.Add(packageBundle);
} }
else else
{ {
// 查询DLC资源 // 查询DLC资源
if (packageBundle.HasTag(tags)) if (packageBundle.HasTag(tags))
{ {
downloadList.Add(packageBundle); downloadList.Add(packageBundle);
} }
} }
} }
return ConvertToDownloadList(downloadList); return ConvertToDownloadList(downloadList);
} }
ResourceDownloaderOperation IPlayMode.CreateResourceDownloaderByPaths(AssetInfo[] assetInfos, int downloadingMaxNumber, int failedTryAgain, int timeout) ResourceDownloaderOperation IPlayMode.CreateResourceDownloaderByPaths(AssetInfo[] assetInfos, int downloadingMaxNumber, int failedTryAgain, int timeout)
{ {
List<BundleInfo> downloadList = GetDownloadListByPaths(_activeManifest, assetInfos); List<BundleInfo> downloadList = GetDownloadListByPaths(_activeManifest, assetInfos);
var operation = new ResourceDownloaderOperation(Download, PackageName, downloadList, downloadingMaxNumber, failedTryAgain, timeout); var operation = new ResourceDownloaderOperation(Download, PackageName, downloadList, downloadingMaxNumber, failedTryAgain, timeout);
return operation; return operation;
} }
public List<BundleInfo> GetDownloadListByPaths(PackageManifest manifest, AssetInfo[] assetInfos) public List<BundleInfo> GetDownloadListByPaths(PackageManifest manifest, AssetInfo[] assetInfos)
{ {
// 获取资源对象的资源包和所有依赖资源包 // 获取资源对象的资源包和所有依赖资源包
List<PackageBundle> checkList = new List<PackageBundle>(); List<PackageBundle> checkList = new List<PackageBundle>();
foreach (var assetInfo in assetInfos) foreach (var assetInfo in assetInfos)
{ {
if (assetInfo.IsInvalid) if (assetInfo.IsInvalid)
{ {
YooLogger.Warning(assetInfo.Error); YooLogger.Warning(assetInfo.Error);
continue; continue;
} }
// 注意:如果清单里未找到资源包会抛出异常! // 注意:如果清单里未找到资源包会抛出异常!
PackageBundle mainBundle = manifest.GetMainPackageBundle(assetInfo.AssetPath); PackageBundle mainBundle = manifest.GetMainPackageBundle(assetInfo.AssetPath);
if (checkList.Contains(mainBundle) == false) if (checkList.Contains(mainBundle) == false)
checkList.Add(mainBundle); checkList.Add(mainBundle);
// 注意:如果清单里未找到资源包会抛出异常! // 注意:如果清单里未找到资源包会抛出异常!
PackageBundle[] dependBundles = manifest.GetAllDependencies(assetInfo.AssetPath); PackageBundle[] dependBundles = manifest.GetAllDependencies(assetInfo.AssetPath);
foreach (var dependBundle in dependBundles) foreach (var dependBundle in dependBundles)
{ {
if (checkList.Contains(dependBundle) == false) if (checkList.Contains(dependBundle) == false)
checkList.Add(dependBundle); checkList.Add(dependBundle);
} }
} }
List<PackageBundle> downloadList = new List<PackageBundle>(1000); List<PackageBundle> downloadList = new List<PackageBundle>(1000);
foreach (var packageBundle in checkList) foreach (var packageBundle in checkList)
{ {
// 忽略分发文件 // 忽略分发文件
if (IsDeliveryPackageBundle(packageBundle)) if (IsDeliveryPackageBundle(packageBundle))
continue; continue;
// 忽略缓存文件 // 忽略缓存文件
if (IsCachedPackageBundle(packageBundle)) if (IsCachedPackageBundle(packageBundle))
continue; continue;
// 忽略APP资源 // 忽略APP资源
if (IsBuildinPackageBundle(packageBundle)) if (IsBuildinPackageBundle(packageBundle))
continue; continue;
downloadList.Add(packageBundle); downloadList.Add(packageBundle);
} }
return ConvertToDownloadList(downloadList); return ConvertToDownloadList(downloadList);
} }
ResourceUnpackerOperation IPlayMode.CreateResourceUnpackerByAll(int upackingMaxNumber, int failedTryAgain, int timeout) ResourceUnpackerOperation IPlayMode.CreateResourceUnpackerByAll(int upackingMaxNumber, int failedTryAgain, int timeout)
{ {
List<BundleInfo> unpcakList = GetUnpackListByAll(_activeManifest); List<BundleInfo> unpcakList = GetUnpackListByAll(_activeManifest);
var operation = new ResourceUnpackerOperation(Download, PackageName, unpcakList, upackingMaxNumber, failedTryAgain, timeout); var operation = new ResourceUnpackerOperation(Download, PackageName, unpcakList, upackingMaxNumber, failedTryAgain, timeout);
return operation; return operation;
} }
private List<BundleInfo> GetUnpackListByAll(PackageManifest manifest) private List<BundleInfo> GetUnpackListByAll(PackageManifest manifest)
{ {
List<PackageBundle> downloadList = new List<PackageBundle>(1000); List<PackageBundle> downloadList = new List<PackageBundle>(1000);
foreach (var packageBundle in manifest.BundleList) foreach (var packageBundle in manifest.BundleList)
{ {
// 忽略缓存文件 // 忽略缓存文件
if (IsCachedPackageBundle(packageBundle)) if (IsCachedPackageBundle(packageBundle))
continue; continue;
if (IsBuildinPackageBundle(packageBundle)) if (IsBuildinPackageBundle(packageBundle))
{ {
downloadList.Add(packageBundle); downloadList.Add(packageBundle);
} }
} }
return BundleInfo.CreateUnpackInfos(_assist, downloadList); return BundleInfo.CreateUnpackInfos(_assist, downloadList);
} }
ResourceUnpackerOperation IPlayMode.CreateResourceUnpackerByTags(string[] tags, int upackingMaxNumber, int failedTryAgain, int timeout) ResourceUnpackerOperation IPlayMode.CreateResourceUnpackerByTags(string[] tags, int upackingMaxNumber, int failedTryAgain, int timeout)
{ {
List<BundleInfo> unpcakList = GetUnpackListByTags(_activeManifest, tags); List<BundleInfo> unpcakList = GetUnpackListByTags(_activeManifest, tags);
var operation = new ResourceUnpackerOperation(Download, PackageName, unpcakList, upackingMaxNumber, failedTryAgain, timeout); var operation = new ResourceUnpackerOperation(Download, PackageName, unpcakList, upackingMaxNumber, failedTryAgain, timeout);
return operation; return operation;
} }
private List<BundleInfo> GetUnpackListByTags(PackageManifest manifest, string[] tags) private List<BundleInfo> GetUnpackListByTags(PackageManifest manifest, string[] tags)
{ {
List<PackageBundle> downloadList = new List<PackageBundle>(1000); List<PackageBundle> downloadList = new List<PackageBundle>(1000);
foreach (var packageBundle in manifest.BundleList) foreach (var packageBundle in manifest.BundleList)
{ {
// 忽略缓存文件 // 忽略缓存文件
if (IsCachedPackageBundle(packageBundle)) if (IsCachedPackageBundle(packageBundle))
continue; continue;
// 查询DLC资源 // 查询DLC资源
if (IsBuildinPackageBundle(packageBundle)) if (IsBuildinPackageBundle(packageBundle))
{ {
if (packageBundle.HasTag(tags)) if (packageBundle.HasTag(tags))
{ {
downloadList.Add(packageBundle); downloadList.Add(packageBundle);
} }
} }
} }
return BundleInfo.CreateUnpackInfos(_assist, downloadList); return BundleInfo.CreateUnpackInfos(_assist, downloadList);
} }
ResourceImporterOperation IPlayMode.CreateResourceImporterByFilePaths(string[] filePaths, int importerMaxNumber, int failedTryAgain, int timeout) ResourceImporterOperation IPlayMode.CreateResourceImporterByFilePaths(string[] filePaths, int importerMaxNumber, int failedTryAgain, int timeout)
{ {
List<BundleInfo> importerList = GetImporterListByFilePaths(_activeManifest, filePaths); List<BundleInfo> importerList = GetImporterListByFilePaths(_activeManifest, filePaths);
var operation = new ResourceImporterOperation(Download, PackageName, importerList, importerMaxNumber, failedTryAgain, timeout); var operation = new ResourceImporterOperation(Download, PackageName, importerList, importerMaxNumber, failedTryAgain, timeout);
return operation; return operation;
} }
private List<BundleInfo> GetImporterListByFilePaths(PackageManifest manifest, string[] filePaths) private List<BundleInfo> GetImporterListByFilePaths(PackageManifest manifest, string[] filePaths)
{ {
List<BundleInfo> result = new List<BundleInfo>(); List<BundleInfo> result = new List<BundleInfo>();
foreach (var filePath in filePaths) foreach (var filePath in filePaths)
{ {
string fileName = System.IO.Path.GetFileName(filePath); string fileName = System.IO.Path.GetFileName(filePath);
if (manifest.TryGetPackageBundleByFileName(fileName, out PackageBundle packageBundle)) if (manifest.TryGetPackageBundleByFileName(fileName, out PackageBundle packageBundle))
{ {
// 忽略缓存文件 // 忽略缓存文件
if (IsCachedPackageBundle(packageBundle)) if (IsCachedPackageBundle(packageBundle))
continue; continue;
var bundleInfo = BundleInfo.CreateImportInfo(_assist, packageBundle, filePath); var bundleInfo = BundleInfo.CreateImportInfo(_assist, packageBundle, filePath);
result.Add(bundleInfo); result.Add(bundleInfo);
} }
else else
{ {
YooLogger.Warning($"Not found package bundle, importer file path : {filePath}"); YooLogger.Warning($"Not found package bundle, importer file path : {filePath}");
} }
} }
return result; return result;
} }
#endregion #endregion
#region IBundleQuery接口 #region IBundleQuery接口
private BundleInfo CreateBundleInfo(PackageBundle packageBundle) private BundleInfo CreateBundleInfo(PackageBundle packageBundle)
{ {
if (packageBundle == null) if (packageBundle == null)
throw new Exception("Should never get here !"); throw new Exception("Should never get here !");
// 查询分发资源 // 查询分发资源
if (IsDeliveryPackageBundle(packageBundle)) if (IsDeliveryPackageBundle(packageBundle))
{ {
string deliveryFilePath = _deliveryQueryServices.GetFilePath(PackageName, packageBundle.FileName); string deliveryFilePath = _deliveryQueryServices.GetFilePath(PackageName, packageBundle.FileName);
BundleInfo bundleInfo = new BundleInfo(_assist, packageBundle, BundleInfo.ELoadMode.LoadFromDelivery, deliveryFilePath); BundleInfo bundleInfo = new BundleInfo(_assist, packageBundle, BundleInfo.ELoadMode.LoadFromDelivery, deliveryFilePath);
return bundleInfo; return bundleInfo;
} }
// 查询沙盒资源 // 查询沙盒资源
if (IsCachedPackageBundle(packageBundle)) if (IsCachedPackageBundle(packageBundle))
{ {
BundleInfo bundleInfo = new BundleInfo(_assist, packageBundle, BundleInfo.ELoadMode.LoadFromCache); BundleInfo bundleInfo = new BundleInfo(_assist, packageBundle, BundleInfo.ELoadMode.LoadFromCache);
return bundleInfo; return bundleInfo;
} }
// 查询APP资源 // 查询APP资源
if (IsBuildinPackageBundle(packageBundle)) if (IsBuildinPackageBundle(packageBundle))
{ {
BundleInfo bundleInfo = new BundleInfo(_assist, packageBundle, BundleInfo.ELoadMode.LoadFromStreaming); BundleInfo bundleInfo = new BundleInfo(_assist, packageBundle, BundleInfo.ELoadMode.LoadFromStreaming);
return bundleInfo; return bundleInfo;
} }
// 从服务端下载 // 从服务端下载
return ConvertToDownloadInfo(packageBundle); return ConvertToDownloadInfo(packageBundle);
} }
BundleInfo IBundleQuery.GetMainBundleInfo(AssetInfo assetInfo) BundleInfo IBundleQuery.GetMainBundleInfo(AssetInfo assetInfo)
{ {
if (assetInfo.IsInvalid) if (assetInfo.IsInvalid)
throw new Exception("Should never get here !"); throw new Exception("Should never get here !");
// 注意:如果清单里未找到资源包会抛出异常! // 注意:如果清单里未找到资源包会抛出异常!
var packageBundle = _activeManifest.GetMainPackageBundle(assetInfo.AssetPath); var packageBundle = _activeManifest.GetMainPackageBundle(assetInfo.AssetPath);
return CreateBundleInfo(packageBundle); return CreateBundleInfo(packageBundle);
} }
BundleInfo[] IBundleQuery.GetDependBundleInfos(AssetInfo assetInfo) BundleInfo[] IBundleQuery.GetDependBundleInfos(AssetInfo assetInfo)
{ {
if (assetInfo.IsInvalid) if (assetInfo.IsInvalid)
throw new Exception("Should never get here !"); throw new Exception("Should never get here !");
// 注意:如果清单里未找到资源包会抛出异常! // 注意:如果清单里未找到资源包会抛出异常!
var depends = _activeManifest.GetAllDependencies(assetInfo.AssetPath); var depends = _activeManifest.GetAllDependencies(assetInfo.AssetPath);
List<BundleInfo> result = new List<BundleInfo>(depends.Length); List<BundleInfo> result = new List<BundleInfo>(depends.Length);
foreach (var packageBundle in depends) foreach (var packageBundle in depends)
{ {
BundleInfo bundleInfo = CreateBundleInfo(packageBundle); BundleInfo bundleInfo = CreateBundleInfo(packageBundle);
result.Add(bundleInfo); result.Add(bundleInfo);
} }
return result.ToArray(); return result.ToArray();
} }
string IBundleQuery.GetMainBundleName(AssetInfo assetInfo) string IBundleQuery.GetMainBundleName(AssetInfo assetInfo)
{ {
if (assetInfo.IsInvalid) if (assetInfo.IsInvalid)
throw new Exception("Should never get here !"); throw new Exception("Should never get here !");
// 注意:如果清单里未找到资源包会抛出异常! // 注意:如果清单里未找到资源包会抛出异常!
var packageBundle = _activeManifest.GetMainPackageBundle(assetInfo.AssetPath); var packageBundle = _activeManifest.GetMainPackageBundle(assetInfo.AssetPath);
return packageBundle.BundleName; return packageBundle.BundleName;
} }
string[] IBundleQuery.GetDependBundleNames(AssetInfo assetInfo) string[] IBundleQuery.GetDependBundleNames(AssetInfo assetInfo)
{ {
if (assetInfo.IsInvalid) if (assetInfo.IsInvalid)
throw new Exception("Should never get here !"); throw new Exception("Should never get here !");
// 注意:如果清单里未找到资源包会抛出异常! // 注意:如果清单里未找到资源包会抛出异常!
var depends = _activeManifest.GetAllDependencies(assetInfo.AssetPath); var depends = _activeManifest.GetAllDependencies(assetInfo.AssetPath);
List<string> result = new List<string>(depends.Length); List<string> result = new List<string>(depends.Length);
foreach (var packageBundle in depends) foreach (var packageBundle in depends)
{ {
result.Add(packageBundle.BundleName); result.Add(packageBundle.BundleName);
} }
return result.ToArray(); return result.ToArray();
} }
bool IBundleQuery.ManifestValid() bool IBundleQuery.ManifestValid()
{ {
return _activeManifest != null; return _activeManifest != null;
} }
#endregion #endregion
} }
} }

View File

@ -4,243 +4,243 @@ using System.Collections.Generic;
namespace YooAsset namespace YooAsset
{ {
internal class OfflinePlayModeImpl : IPlayMode, IBundleQuery internal class OfflinePlayModeImpl : IPlayMode, IBundleQuery
{ {
private PackageManifest _activeManifest; private PackageManifest _activeManifest;
private ResourceAssist _assist; private ResourceAssist _assist;
public readonly string PackageName; public readonly string PackageName;
public DownloadManager Download public DownloadManager Download
{ {
get { return _assist.Download; } get { return _assist.Download; }
} }
public PersistentManager Persistent public PersistentManager Persistent
{ {
get { return _assist.Persistent; } get { return _assist.Persistent; }
} }
public CacheManager Cache public CacheManager Cache
{ {
get { return _assist.Cache; } get { return _assist.Cache; }
} }
public OfflinePlayModeImpl(string packageName) public OfflinePlayModeImpl(string packageName)
{ {
PackageName = packageName; PackageName = packageName;
} }
/// <summary> /// <summary>
/// 异步初始化 /// 异步初始化
/// </summary> /// </summary>
public InitializationOperation InitializeAsync(ResourceAssist assist) public InitializationOperation InitializeAsync(ResourceAssist assist)
{ {
_assist = assist; _assist = assist;
var operation = new OfflinePlayModeInitializationOperation(this); var operation = new OfflinePlayModeInitializationOperation(this);
OperationSystem.StartOperation(PackageName, operation); OperationSystem.StartOperation(PackageName, operation);
return operation; return operation;
} }
// 查询相关 // 查询相关
private bool IsCachedPackageBundle(PackageBundle packageBundle) private bool IsCachedPackageBundle(PackageBundle packageBundle)
{ {
return _assist.Cache.IsCached(packageBundle.CacheGUID); return _assist.Cache.IsCached(packageBundle.CacheGUID);
} }
#region IPlayMode接口 #region IPlayMode接口
public PackageManifest ActiveManifest public PackageManifest ActiveManifest
{ {
set set
{ {
_activeManifest = value; _activeManifest = value;
} }
get get
{ {
return _activeManifest; return _activeManifest;
} }
} }
public void FlushManifestVersionFile() public void FlushManifestVersionFile()
{ {
} }
UpdatePackageVersionOperation IPlayMode.UpdatePackageVersionAsync(bool appendTimeTicks, int timeout) UpdatePackageVersionOperation IPlayMode.UpdatePackageVersionAsync(bool appendTimeTicks, int timeout)
{ {
var operation = new OfflinePlayModeUpdatePackageVersionOperation(); var operation = new OfflinePlayModeUpdatePackageVersionOperation();
OperationSystem.StartOperation(PackageName, operation); OperationSystem.StartOperation(PackageName, operation);
return operation; return operation;
} }
UpdatePackageManifestOperation IPlayMode.UpdatePackageManifestAsync(string packageVersion, bool autoSaveVersion, int timeout) UpdatePackageManifestOperation IPlayMode.UpdatePackageManifestAsync(string packageVersion, bool autoSaveVersion, int timeout)
{ {
var operation = new OfflinePlayModeUpdatePackageManifestOperation(); var operation = new OfflinePlayModeUpdatePackageManifestOperation();
OperationSystem.StartOperation(PackageName, operation); OperationSystem.StartOperation(PackageName, operation);
return operation; return operation;
} }
PreDownloadContentOperation IPlayMode.PreDownloadContentAsync(string packageVersion, int timeout) PreDownloadContentOperation IPlayMode.PreDownloadContentAsync(string packageVersion, int timeout)
{ {
var operation = new OfflinePlayModePreDownloadContentOperation(this); var operation = new OfflinePlayModePreDownloadContentOperation(this);
OperationSystem.StartOperation(PackageName, operation); OperationSystem.StartOperation(PackageName, operation);
return operation; return operation;
} }
ResourceDownloaderOperation IPlayMode.CreateResourceDownloaderByAll(int downloadingMaxNumber, int failedTryAgain, int timeout) ResourceDownloaderOperation IPlayMode.CreateResourceDownloaderByAll(int downloadingMaxNumber, int failedTryAgain, int timeout)
{ {
return ResourceDownloaderOperation.CreateEmptyDownloader(Download, PackageName, downloadingMaxNumber, failedTryAgain, timeout); return ResourceDownloaderOperation.CreateEmptyDownloader(Download, PackageName, downloadingMaxNumber, failedTryAgain, timeout);
} }
ResourceDownloaderOperation IPlayMode.CreateResourceDownloaderByTags(string[] tags, int downloadingMaxNumber, int failedTryAgain, int timeout) ResourceDownloaderOperation IPlayMode.CreateResourceDownloaderByTags(string[] tags, int downloadingMaxNumber, int failedTryAgain, int timeout)
{ {
return ResourceDownloaderOperation.CreateEmptyDownloader(Download, PackageName, downloadingMaxNumber, failedTryAgain, timeout); return ResourceDownloaderOperation.CreateEmptyDownloader(Download, PackageName, downloadingMaxNumber, failedTryAgain, timeout);
} }
ResourceDownloaderOperation IPlayMode.CreateResourceDownloaderByPaths(AssetInfo[] assetInfos, int downloadingMaxNumber, int failedTryAgain, int timeout) ResourceDownloaderOperation IPlayMode.CreateResourceDownloaderByPaths(AssetInfo[] assetInfos, int downloadingMaxNumber, int failedTryAgain, int timeout)
{ {
return ResourceDownloaderOperation.CreateEmptyDownloader(Download, PackageName, downloadingMaxNumber, failedTryAgain, timeout); return ResourceDownloaderOperation.CreateEmptyDownloader(Download, PackageName, downloadingMaxNumber, failedTryAgain, timeout);
} }
ResourceUnpackerOperation IPlayMode.CreateResourceUnpackerByAll(int upackingMaxNumber, int failedTryAgain, int timeout) ResourceUnpackerOperation IPlayMode.CreateResourceUnpackerByAll(int upackingMaxNumber, int failedTryAgain, int timeout)
{ {
List<BundleInfo> unpcakList = GetUnpackListByAll(_activeManifest); List<BundleInfo> unpcakList = GetUnpackListByAll(_activeManifest);
var operation = new ResourceUnpackerOperation(Download, PackageName, unpcakList, upackingMaxNumber, failedTryAgain, timeout); var operation = new ResourceUnpackerOperation(Download, PackageName, unpcakList, upackingMaxNumber, failedTryAgain, timeout);
return operation; return operation;
} }
private List<BundleInfo> GetUnpackListByAll(PackageManifest manifest) private List<BundleInfo> GetUnpackListByAll(PackageManifest manifest)
{ {
List<PackageBundle> downloadList = new List<PackageBundle>(1000); List<PackageBundle> downloadList = new List<PackageBundle>(1000);
foreach (var packageBundle in manifest.BundleList) foreach (var packageBundle in manifest.BundleList)
{ {
// 忽略缓存文件 // 忽略缓存文件
if (IsCachedPackageBundle(packageBundle)) if (IsCachedPackageBundle(packageBundle))
continue; continue;
downloadList.Add(packageBundle); downloadList.Add(packageBundle);
} }
return BundleInfo.CreateUnpackInfos(_assist, downloadList); return BundleInfo.CreateUnpackInfos(_assist, downloadList);
} }
ResourceUnpackerOperation IPlayMode.CreateResourceUnpackerByTags(string[] tags, int upackingMaxNumber, int failedTryAgain, int timeout) ResourceUnpackerOperation IPlayMode.CreateResourceUnpackerByTags(string[] tags, int upackingMaxNumber, int failedTryAgain, int timeout)
{ {
List<BundleInfo> unpcakList = GetUnpackListByTags(_activeManifest, tags); List<BundleInfo> unpcakList = GetUnpackListByTags(_activeManifest, tags);
var operation = new ResourceUnpackerOperation(Download, PackageName, unpcakList, upackingMaxNumber, failedTryAgain, timeout); var operation = new ResourceUnpackerOperation(Download, PackageName, unpcakList, upackingMaxNumber, failedTryAgain, timeout);
return operation; return operation;
} }
private List<BundleInfo> GetUnpackListByTags(PackageManifest manifest, string[] tags) private List<BundleInfo> GetUnpackListByTags(PackageManifest manifest, string[] tags)
{ {
List<PackageBundle> downloadList = new List<PackageBundle>(1000); List<PackageBundle> downloadList = new List<PackageBundle>(1000);
foreach (var packageBundle in manifest.BundleList) foreach (var packageBundle in manifest.BundleList)
{ {
// 忽略缓存文件 // 忽略缓存文件
if (IsCachedPackageBundle(packageBundle)) if (IsCachedPackageBundle(packageBundle))
continue; continue;
// 查询DLC资源 // 查询DLC资源
if (packageBundle.HasTag(tags)) if (packageBundle.HasTag(tags))
{ {
downloadList.Add(packageBundle); downloadList.Add(packageBundle);
} }
} }
return BundleInfo.CreateUnpackInfos(_assist, downloadList); return BundleInfo.CreateUnpackInfos(_assist, downloadList);
} }
ResourceImporterOperation IPlayMode.CreateResourceImporterByFilePaths(string[] filePaths, int importerMaxNumber, int failedTryAgain, int timeout) ResourceImporterOperation IPlayMode.CreateResourceImporterByFilePaths(string[] filePaths, int importerMaxNumber, int failedTryAgain, int timeout)
{ {
List<BundleInfo> importerList = GetImporterListByFilePaths(_activeManifest, filePaths); List<BundleInfo> importerList = GetImporterListByFilePaths(_activeManifest, filePaths);
var operation = new ResourceImporterOperation(Download, PackageName, importerList, importerMaxNumber, failedTryAgain, timeout); var operation = new ResourceImporterOperation(Download, PackageName, importerList, importerMaxNumber, failedTryAgain, timeout);
return operation; return operation;
} }
private List<BundleInfo> GetImporterListByFilePaths(PackageManifest manifest, string[] filePaths) private List<BundleInfo> GetImporterListByFilePaths(PackageManifest manifest, string[] filePaths)
{ {
List<BundleInfo> result = new List<BundleInfo>(); List<BundleInfo> result = new List<BundleInfo>();
foreach (var filePath in filePaths) foreach (var filePath in filePaths)
{ {
string fileName = System.IO.Path.GetFileName(filePath); string fileName = System.IO.Path.GetFileName(filePath);
if (manifest.TryGetPackageBundleByFileName(fileName, out PackageBundle packageBundle)) if (manifest.TryGetPackageBundleByFileName(fileName, out PackageBundle packageBundle))
{ {
// 忽略缓存文件 // 忽略缓存文件
if (IsCachedPackageBundle(packageBundle)) if (IsCachedPackageBundle(packageBundle))
continue; continue;
var bundleInfo = BundleInfo.CreateImportInfo(_assist, packageBundle, filePath); var bundleInfo = BundleInfo.CreateImportInfo(_assist, packageBundle, filePath);
result.Add(bundleInfo); result.Add(bundleInfo);
} }
else else
{ {
YooLogger.Warning($"Not found package bundle, importer file path : {filePath}"); YooLogger.Warning($"Not found package bundle, importer file path : {filePath}");
} }
} }
return result; return result;
} }
#endregion #endregion
#region IBundleQuery接口 #region IBundleQuery接口
private BundleInfo CreateBundleInfo(PackageBundle packageBundle) private BundleInfo CreateBundleInfo(PackageBundle packageBundle)
{ {
if (packageBundle == null) if (packageBundle == null)
throw new Exception("Should never get here !"); throw new Exception("Should never get here !");
// 查询沙盒资源 // 查询沙盒资源
if (IsCachedPackageBundle(packageBundle)) if (IsCachedPackageBundle(packageBundle))
{ {
BundleInfo bundleInfo = new BundleInfo(_assist, packageBundle, BundleInfo.ELoadMode.LoadFromCache); BundleInfo bundleInfo = new BundleInfo(_assist, packageBundle, BundleInfo.ELoadMode.LoadFromCache);
return bundleInfo; return bundleInfo;
} }
// 查询APP资源 // 查询APP资源
{ {
BundleInfo bundleInfo = new BundleInfo(_assist, packageBundle, BundleInfo.ELoadMode.LoadFromStreaming); BundleInfo bundleInfo = new BundleInfo(_assist, packageBundle, BundleInfo.ELoadMode.LoadFromStreaming);
return bundleInfo; return bundleInfo;
} }
} }
BundleInfo IBundleQuery.GetMainBundleInfo(AssetInfo assetInfo) BundleInfo IBundleQuery.GetMainBundleInfo(AssetInfo assetInfo)
{ {
if (assetInfo.IsInvalid) if (assetInfo.IsInvalid)
throw new Exception("Should never get here !"); throw new Exception("Should never get here !");
// 注意:如果清单里未找到资源包会抛出异常! // 注意:如果清单里未找到资源包会抛出异常!
var packageBundle = _activeManifest.GetMainPackageBundle(assetInfo.AssetPath); var packageBundle = _activeManifest.GetMainPackageBundle(assetInfo.AssetPath);
return CreateBundleInfo(packageBundle); return CreateBundleInfo(packageBundle);
} }
BundleInfo[] IBundleQuery.GetDependBundleInfos(AssetInfo assetInfo) BundleInfo[] IBundleQuery.GetDependBundleInfos(AssetInfo assetInfo)
{ {
if (assetInfo.IsInvalid) if (assetInfo.IsInvalid)
throw new Exception("Should never get here !"); throw new Exception("Should never get here !");
// 注意:如果清单里未找到资源包会抛出异常! // 注意:如果清单里未找到资源包会抛出异常!
var depends = _activeManifest.GetAllDependencies(assetInfo.AssetPath); var depends = _activeManifest.GetAllDependencies(assetInfo.AssetPath);
List<BundleInfo> result = new List<BundleInfo>(depends.Length); List<BundleInfo> result = new List<BundleInfo>(depends.Length);
foreach (var packageBundle in depends) foreach (var packageBundle in depends)
{ {
BundleInfo bundleInfo = CreateBundleInfo(packageBundle); BundleInfo bundleInfo = CreateBundleInfo(packageBundle);
result.Add(bundleInfo); result.Add(bundleInfo);
} }
return result.ToArray(); return result.ToArray();
} }
string IBundleQuery.GetMainBundleName(AssetInfo assetInfo) string IBundleQuery.GetMainBundleName(AssetInfo assetInfo)
{ {
if (assetInfo.IsInvalid) if (assetInfo.IsInvalid)
throw new Exception("Should never get here !"); throw new Exception("Should never get here !");
// 注意:如果清单里未找到资源包会抛出异常! // 注意:如果清单里未找到资源包会抛出异常!
var packageBundle = _activeManifest.GetMainPackageBundle(assetInfo.AssetPath); var packageBundle = _activeManifest.GetMainPackageBundle(assetInfo.AssetPath);
return packageBundle.BundleName; return packageBundle.BundleName;
} }
string[] IBundleQuery.GetDependBundleNames(AssetInfo assetInfo) string[] IBundleQuery.GetDependBundleNames(AssetInfo assetInfo)
{ {
if (assetInfo.IsInvalid) if (assetInfo.IsInvalid)
throw new Exception("Should never get here !"); throw new Exception("Should never get here !");
// 注意:如果清单里未找到资源包会抛出异常! // 注意:如果清单里未找到资源包会抛出异常!
var depends = _activeManifest.GetAllDependencies(assetInfo.AssetPath); var depends = _activeManifest.GetAllDependencies(assetInfo.AssetPath);
List<string> result = new List<string>(depends.Length); List<string> result = new List<string>(depends.Length);
foreach (var packageBundle in depends) foreach (var packageBundle in depends)
{ {
result.Add(packageBundle.BundleName); result.Add(packageBundle.BundleName);
} }
return result.ToArray(); return result.ToArray();
} }
bool IBundleQuery.ManifestValid() bool IBundleQuery.ManifestValid()
{ {
return _activeManifest != null; return _activeManifest != null;
} }
#endregion #endregion
} }
} }

Some files were not shown because too many files have changed in this diff Show More