update sample
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 89357359fd1b3f74fa7cb048a1ffa2b6
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,34 @@
|
||||
/[Ll]ibrary/
|
||||
/[Tt]emp/
|
||||
/[Oo]bj/
|
||||
/[Bb]uild/
|
||||
/[Bb]uilds/
|
||||
/Assets/AssetStoreTools*
|
||||
|
||||
# Visual Studio 2015 cache directory
|
||||
/.vs/
|
||||
|
||||
# Autogenerated VS/MD/Consulo solution and project files
|
||||
ExportedObj/
|
||||
.consulo/
|
||||
*.csproj
|
||||
*.unityproj
|
||||
*.sln
|
||||
*.suo
|
||||
*.tmp
|
||||
*.user
|
||||
*.userprefs
|
||||
*.pidb
|
||||
*.booproj
|
||||
*.svd
|
||||
*.pdb
|
||||
|
||||
# Unity3D generated meta files
|
||||
*.pidb.meta
|
||||
|
||||
# Unity3D Generated File On Crash Reports
|
||||
sysinfo.txt
|
||||
|
||||
# Builds
|
||||
*.apk
|
||||
*.unitypackage
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2017 gwiazdorrr
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f3d9e435137e34d34a54f181bf3dc7c2
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
# Better Streaming Assets
|
||||
|
||||
Better Streaming Assets is a plugin that lets you access Streaming Assets directly in an uniform and thread-safe way, with tiny overhead. Mostly beneficial for Android projects, where the alternatives are to use archaic and hugely inefficient WWW or embed data in Asset Bundles. API is based on Syste.IO.File and System.IO.Directory classes.
|
||||
|
||||
# Note on Android & App Bundles
|
||||
|
||||
App Bundles (.aab) builds are bugged when it comes to Streaming Assets. See https://github.com/gwiazdorrr/BetterStreamingAssets/issues/10 for details. The bottom line is:
|
||||
|
||||
⚠️ **Keep all file names in Streaming Assets lowercase!** ⚠️
|
||||
|
||||
# Getting started
|
||||
|
||||
This plugin can be installed in following ways:
|
||||
* Select "Add package from git URL..." in the Unity Package Manager and use this URL: `https://github.com/gwiazdorrr/BetterStreamingAssets.git`
|
||||
* Clone this repository and copy `Runtime` directory to your project.
|
||||
* Download the latest release from the [Asset Store](https://assetstore.unity.com/packages/tools/input-management/better-streaming-assets-103788).
|
||||
|
||||
# Usage
|
||||
|
||||
Check examples below. Note that all the paths are relative to StreamingAssets directory. That is, if you have files
|
||||
|
||||
```
|
||||
<project>/Assets/StreamingAssets/foo.bar
|
||||
<project>/Assets/StreamingAssets/dir/foo.bar
|
||||
````
|
||||
|
||||
You are expected to use following paths:
|
||||
|
||||
```
|
||||
foo.bar (or /foo.bar)
|
||||
dir/foo.bar (or /dir/foo.bar)
|
||||
```
|
||||
|
||||
# Examples
|
||||
|
||||
Initialization (before first use, needs to be called on main thread):
|
||||
|
||||
```csharp
|
||||
BetterStreamingAssets.Initialize();
|
||||
```
|
||||
|
||||
Typical scenario, deserializing from Xml:
|
||||
|
||||
```csharp
|
||||
public static Foo ReadFromXml(string path)
|
||||
{
|
||||
if ( !BetterStreamingAssets.FileExists(path) )
|
||||
{
|
||||
Debug.LogErrorFormat("Streaming asset not found: {0}", path);
|
||||
return null;
|
||||
}
|
||||
|
||||
using ( var stream = BetterStreamingAssets.OpenRead(path) )
|
||||
{
|
||||
var serializer = new System.Xml.Serialization.XmlSerializer(typeof(Foo));
|
||||
return (Foo)serializer.Deserialize(stream);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Note that ReadFromXml can be called from any thread, as long as Foo's constructor doesn't make any UnityEngine calls.
|
||||
|
||||
Listing all Streaming Assets in with .xml extension:
|
||||
|
||||
```csharp
|
||||
// all the xmls
|
||||
string[] paths = BetterStreamingAssets.GetFiles("\\", "*.xml", SearchOption.AllDirectories);
|
||||
// just xmls in Config directory (and nested)
|
||||
string[] paths = BetterStreamingAssets.GetFiles("Config", "*.xml", SearchOption.AllDirectories);
|
||||
```
|
||||
|
||||
Checking if a directory exists:
|
||||
|
||||
```csharp
|
||||
Debug.Assert( BetterStreamingAssets.DirectoryExists("Config") );
|
||||
```
|
||||
|
||||
Ways of reading a file:
|
||||
|
||||
```csharp
|
||||
// all at once
|
||||
byte[] data = BetterStreamingAssets.ReadAllBytes("Foo/bar.data");
|
||||
|
||||
// as stream, last 10 bytes
|
||||
byte[] footer = new byte[10];
|
||||
using (var stream = BetterStreamingAssets.OpenRead("Foo/bar.data"))
|
||||
{
|
||||
stream.Seek(-footer.Length, SeekOrigin.End);
|
||||
stream.Read(footer, 0, footer.Length);
|
||||
}
|
||||
```
|
||||
|
||||
Asset bundles (again, main thread only):
|
||||
|
||||
```csharp
|
||||
// synchronous
|
||||
var bundle = BetterStreamingAssets.LoadAssetBundle(path);
|
||||
// async
|
||||
var bundleOp = BetterStreamingAssets.LoadAssetBundleAsync(path);
|
||||
```
|
||||
|
||||
# (Android) False-positive compressed Streaming Assets messages
|
||||
|
||||
Streaming Assets end up in the same part of APK as files added by many custom plugins (`assets` directory), so it is impossible to tell whether a compressed file is a Streaming Asset (an indication something has gone terribly wrong) or not. This tool acts conservatively and logs errors whenever it finds a compressed file inside of `assets`, but outside of `assets/bin`. If you are annoyed by this and are certain a compressed file was not meant to be a Streaming Asset, add a file like this in the same assembly as Better Streaming Assets:
|
||||
|
||||
```csharp
|
||||
partial class BetterStreamingAssets
|
||||
{
|
||||
static partial void AndroidIsCompressedFileStreamingAsset(string path, ref bool result)
|
||||
{
|
||||
if ( path == "assets/my_custom_plugin_settings.json")
|
||||
{
|
||||
result = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: c59a049ac5cdb4a48996edcefd9ac9c7
|
||||
TextScriptImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 89bc753a71211472587f0baa7a08d0e7
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+663
@@ -0,0 +1,663 @@
|
||||
// Better Streaming Assets, Piotr Gwiazdowski <gwiazdorrr+github at gmail.com>, 2017
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
using System.IO;
|
||||
using System.Text.RegularExpressions;
|
||||
using Better;
|
||||
using Better.StreamingAssets;
|
||||
using Better.StreamingAssets.ZipArchive;
|
||||
|
||||
#if UNITY_EDITOR
|
||||
using BetterStreamingAssetsImp = BetterStreamingAssets.EditorImpl;
|
||||
#elif UNITY_ANDROID
|
||||
using BetterStreamingAssetsImp = BetterStreamingAssets.ApkImpl;
|
||||
#else
|
||||
using BetterStreamingAssetsImp = BetterStreamingAssets.LooseFilesImpl;
|
||||
#endif
|
||||
|
||||
public static partial class BetterStreamingAssets
|
||||
{
|
||||
internal struct ReadInfo
|
||||
{
|
||||
public string readPath;
|
||||
public long size;
|
||||
public long offset;
|
||||
public uint crc32;
|
||||
}
|
||||
|
||||
public static string Root
|
||||
{
|
||||
get { return BetterStreamingAssetsImp.s_root; }
|
||||
}
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
BetterStreamingAssetsImp.Initialize(Application.dataPath, Application.streamingAssetsPath);
|
||||
}
|
||||
|
||||
#if UNITY_EDITOR
|
||||
public static void InitializeWithExternalApk(string apkPath)
|
||||
{
|
||||
BetterStreamingAssetsImp.ApkMode = true;
|
||||
BetterStreamingAssetsImp.Initialize(apkPath, "jar:file://" + apkPath + "!/assets/");
|
||||
}
|
||||
|
||||
public static void InitializeWithExternalDirectories(string dataPath, string streamingAssetsPath)
|
||||
{
|
||||
BetterStreamingAssetsImp.ApkMode = false;
|
||||
BetterStreamingAssetsImp.Initialize(dataPath, streamingAssetsPath);
|
||||
}
|
||||
#endif
|
||||
|
||||
public static bool FileExists(string path)
|
||||
{
|
||||
ReadInfo info;
|
||||
return BetterStreamingAssetsImp.TryGetInfo(path, out info);
|
||||
}
|
||||
|
||||
public static bool DirectoryExists(string path)
|
||||
{
|
||||
return BetterStreamingAssetsImp.DirectoryExists(path);
|
||||
}
|
||||
|
||||
public static AssetBundleCreateRequest LoadAssetBundleAsync(string path, uint crc = 0)
|
||||
{
|
||||
var info = GetInfoOrThrow(path);
|
||||
return AssetBundle.LoadFromFileAsync(info.readPath, crc, (ulong)info.offset);
|
||||
}
|
||||
|
||||
public static AssetBundle LoadAssetBundle(string path, uint crc = 0)
|
||||
{
|
||||
var info = GetInfoOrThrow(path);
|
||||
return AssetBundle.LoadFromFile(info.readPath, crc, (ulong)info.offset);
|
||||
}
|
||||
|
||||
public static System.IO.Stream OpenRead(string path)
|
||||
{
|
||||
if ( path == null )
|
||||
throw new ArgumentNullException("path");
|
||||
if ( path.Length == 0 )
|
||||
throw new ArgumentException("Empty path", "path");
|
||||
|
||||
return BetterStreamingAssetsImp.OpenRead(path);
|
||||
}
|
||||
|
||||
public static System.IO.StreamReader OpenText(string path)
|
||||
{
|
||||
Stream str = OpenRead(path);
|
||||
try
|
||||
{
|
||||
return new StreamReader(str);
|
||||
}
|
||||
catch (System.Exception)
|
||||
{
|
||||
if (str != null)
|
||||
str.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public static string ReadAllText(string path)
|
||||
{
|
||||
using ( var sr = OpenText(path) )
|
||||
{
|
||||
return sr.ReadToEnd();
|
||||
}
|
||||
}
|
||||
|
||||
public static string[] ReadAllLines(string path)
|
||||
{
|
||||
string line;
|
||||
var lines = new List<string>();
|
||||
|
||||
using ( var sr = OpenText(path) )
|
||||
{
|
||||
while ( ( line = sr.ReadLine() ) != null )
|
||||
{
|
||||
lines.Add(line);
|
||||
}
|
||||
}
|
||||
|
||||
return lines.ToArray();
|
||||
}
|
||||
|
||||
public static byte[] ReadAllBytes(string path)
|
||||
{
|
||||
if ( path == null )
|
||||
throw new ArgumentNullException("path");
|
||||
if ( path.Length == 0 )
|
||||
throw new ArgumentException("Empty path", "path");
|
||||
|
||||
return BetterStreamingAssetsImp.ReadAllBytes(path);
|
||||
}
|
||||
|
||||
public static string[] GetFiles(string path, string searchPattern, SearchOption searchOption)
|
||||
{
|
||||
return BetterStreamingAssetsImp.GetFiles(path, searchPattern, searchOption);
|
||||
}
|
||||
|
||||
public static string[] GetFiles(string path)
|
||||
{
|
||||
return GetFiles(path, null);
|
||||
}
|
||||
|
||||
public static string[] GetFiles(string path, string searchPattern)
|
||||
{
|
||||
return GetFiles(path, searchPattern, SearchOption.TopDirectoryOnly);
|
||||
}
|
||||
|
||||
private static ReadInfo GetInfoOrThrow(string path)
|
||||
{
|
||||
ReadInfo result;
|
||||
if ( !BetterStreamingAssetsImp.TryGetInfo(path, out result) )
|
||||
ThrowFileNotFound(path);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void ThrowFileNotFound(string path)
|
||||
{
|
||||
throw new FileNotFoundException("File not found", path);
|
||||
}
|
||||
|
||||
static partial void AndroidIsCompressedFileStreamingAsset(string path, ref bool result);
|
||||
|
||||
#if UNITY_EDITOR
|
||||
internal static class EditorImpl
|
||||
{
|
||||
public static bool ApkMode = false;
|
||||
|
||||
public static string s_root
|
||||
{
|
||||
get { return ApkMode ? ApkImpl.s_root : LooseFilesImpl.s_root; }
|
||||
}
|
||||
|
||||
internal static void Initialize(string dataPath, string streamingAssetsPath)
|
||||
{
|
||||
if ( ApkMode )
|
||||
{
|
||||
ApkImpl.Initialize(dataPath, streamingAssetsPath);
|
||||
}
|
||||
else
|
||||
{
|
||||
LooseFilesImpl.Initialize(dataPath, streamingAssetsPath);
|
||||
}
|
||||
}
|
||||
|
||||
internal static bool TryGetInfo(string path, out ReadInfo info)
|
||||
{
|
||||
if ( ApkMode )
|
||||
return ApkImpl.TryGetInfo(path, out info);
|
||||
else
|
||||
return LooseFilesImpl.TryGetInfo(path, out info);
|
||||
}
|
||||
|
||||
internal static bool DirectoryExists(string path)
|
||||
{
|
||||
if ( ApkMode )
|
||||
return ApkImpl.DirectoryExists(path);
|
||||
else
|
||||
return LooseFilesImpl.DirectoryExists(path);
|
||||
}
|
||||
|
||||
internal static Stream OpenRead(string path)
|
||||
{
|
||||
if ( ApkMode )
|
||||
return ApkImpl.OpenRead(path);
|
||||
else
|
||||
return LooseFilesImpl.OpenRead(path);
|
||||
}
|
||||
|
||||
internal static byte[] ReadAllBytes(string path)
|
||||
{
|
||||
if ( ApkMode )
|
||||
return ApkImpl.ReadAllBytes(path);
|
||||
else
|
||||
return LooseFilesImpl.ReadAllBytes(path);
|
||||
}
|
||||
|
||||
internal static string[] GetFiles(string path, string searchPattern, SearchOption searchOption)
|
||||
{
|
||||
if ( ApkMode )
|
||||
return ApkImpl.GetFiles(path, searchPattern, searchOption);
|
||||
else
|
||||
return LooseFilesImpl.GetFiles(path, searchPattern, searchOption);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if UNITY_EDITOR || !UNITY_ANDROID
|
||||
internal static class LooseFilesImpl
|
||||
{
|
||||
public static string s_root;
|
||||
private static string[] s_emptyArray = new string[0];
|
||||
|
||||
public static void Initialize(string dataPath, string streamingAssetsPath)
|
||||
{
|
||||
s_root = Path.GetFullPath(streamingAssetsPath).Replace('\\', '/').TrimEnd('/');
|
||||
}
|
||||
|
||||
public static string[] GetFiles(string path, string searchPattern, SearchOption searchOption)
|
||||
{
|
||||
if (!Directory.Exists(s_root))
|
||||
return s_emptyArray;
|
||||
|
||||
// this will throw if something is fishy
|
||||
path = PathUtil.NormalizeRelativePath(path, forceTrailingSlash : true);
|
||||
|
||||
Debug.Assert(s_root.Last() != '\\' && s_root.Last() != '/' && path.StartsWith("/"));
|
||||
|
||||
var files = Directory.GetFiles(s_root + path, searchPattern ?? "*", searchOption);
|
||||
|
||||
for ( int i = 0; i < files.Length; ++i )
|
||||
{
|
||||
Debug.Assert(files[i].StartsWith(s_root));
|
||||
files[i] = files[i].Substring(s_root.Length + 1).Replace('\\', '/');
|
||||
}
|
||||
|
||||
#if UNITY_EDITOR
|
||||
// purge meta files
|
||||
{
|
||||
int j = 0;
|
||||
for ( int i = 0; i < files.Length; ++i )
|
||||
{
|
||||
if ( !files[i].EndsWith(".meta") )
|
||||
{
|
||||
files[j++] = files[i];
|
||||
}
|
||||
}
|
||||
Array.Resize(ref files, j);
|
||||
}
|
||||
|
||||
#endif
|
||||
return files;
|
||||
}
|
||||
|
||||
public static bool TryGetInfo(string path, out ReadInfo info)
|
||||
{
|
||||
path = PathUtil.NormalizeRelativePath(path);
|
||||
|
||||
info = new ReadInfo();
|
||||
|
||||
var fullPath = s_root + path;
|
||||
if ( !File.Exists(fullPath) )
|
||||
return false;
|
||||
|
||||
info.readPath = fullPath;
|
||||
return true;
|
||||
}
|
||||
|
||||
public static bool DirectoryExists(string path)
|
||||
{
|
||||
var normalized = PathUtil.NormalizeRelativePath(path);
|
||||
return Directory.Exists(s_root + normalized);
|
||||
}
|
||||
|
||||
public static byte[] ReadAllBytes(string path)
|
||||
{
|
||||
ReadInfo info;
|
||||
|
||||
if ( !TryGetInfo(path, out info) )
|
||||
ThrowFileNotFound(path);
|
||||
|
||||
return File.ReadAllBytes(info.readPath);
|
||||
}
|
||||
|
||||
public static System.IO.Stream OpenRead(string path)
|
||||
{
|
||||
ReadInfo info;
|
||||
if ( !TryGetInfo(path, out info) )
|
||||
ThrowFileNotFound(path);
|
||||
|
||||
Stream fileStream = File.OpenRead(info.readPath);
|
||||
try
|
||||
{
|
||||
return new SubReadOnlyStream(fileStream, leaveOpen: false);
|
||||
}
|
||||
catch ( System.Exception )
|
||||
{
|
||||
fileStream.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if UNITY_EDITOR || UNITY_ANDROID
|
||||
internal static class ApkImpl
|
||||
{
|
||||
private static string[] s_paths;
|
||||
private static PartInfo[] s_streamingAssets;
|
||||
public static string s_root;
|
||||
|
||||
private struct PartInfo
|
||||
{
|
||||
public long size;
|
||||
public long offset;
|
||||
public uint crc32;
|
||||
}
|
||||
|
||||
public static void Initialize(string dataPath, string streamingAssetsPath)
|
||||
{
|
||||
s_root = dataPath;
|
||||
|
||||
List<string> paths = new List<string>();
|
||||
List<PartInfo> parts = new List<PartInfo>();
|
||||
|
||||
GetStreamingAssetsInfoFromJar(s_root, paths, parts);
|
||||
|
||||
if (paths.Count == 0 && !Application.isEditor && Path.GetFileName(dataPath) != "base.apk")
|
||||
{
|
||||
// maybe split?
|
||||
var newDataPath = Path.GetDirectoryName(dataPath) + "/base.apk";
|
||||
if (File.Exists(newDataPath))
|
||||
{
|
||||
s_root = newDataPath;
|
||||
GetStreamingAssetsInfoFromJar(newDataPath, paths, parts);
|
||||
}
|
||||
}
|
||||
|
||||
s_paths = paths.ToArray();
|
||||
s_streamingAssets = parts.ToArray();
|
||||
}
|
||||
|
||||
public static bool TryGetInfo(string path, out ReadInfo info)
|
||||
{
|
||||
path = PathUtil.NormalizeRelativePath(path);
|
||||
info = new ReadInfo();
|
||||
|
||||
var index = Array.BinarySearch(s_paths, path, StringComparer.OrdinalIgnoreCase);
|
||||
if ( index < 0 )
|
||||
return false;
|
||||
|
||||
var dataInfo = s_streamingAssets[index];
|
||||
info.crc32 = dataInfo.crc32;
|
||||
info.offset = dataInfo.offset;
|
||||
info.size = dataInfo.size;
|
||||
info.readPath = s_root;
|
||||
return true;
|
||||
}
|
||||
|
||||
public static bool DirectoryExists(string path)
|
||||
{
|
||||
var normalized = PathUtil.NormalizeRelativePath(path, forceTrailingSlash : true);
|
||||
var dirIndex = GetDirectoryIndex(normalized);
|
||||
return dirIndex >= 0 && dirIndex < s_paths.Length;
|
||||
}
|
||||
|
||||
public static string[] GetFiles(string path, string searchPattern, SearchOption searchOption)
|
||||
{
|
||||
if ( path == null )
|
||||
throw new ArgumentNullException("path");
|
||||
|
||||
var actualDirPath = PathUtil.NormalizeRelativePath(path, forceTrailingSlash : true);
|
||||
|
||||
// find first file there
|
||||
var index = GetDirectoryIndex(actualDirPath);
|
||||
if ( index < 0 )
|
||||
throw new IOException();
|
||||
if ( index == s_paths.Length )
|
||||
throw new DirectoryNotFoundException();
|
||||
|
||||
Predicate<string> filter;
|
||||
if ( string.IsNullOrEmpty(searchPattern) || searchPattern == "*" )
|
||||
{
|
||||
filter = null;
|
||||
}
|
||||
else if ( searchPattern.IndexOf('*') >= 0 || searchPattern.IndexOf('?') >= 0 )
|
||||
{
|
||||
var regex = PathUtil.WildcardToRegex(searchPattern);
|
||||
filter = (x) => regex.IsMatch(x);
|
||||
}
|
||||
else
|
||||
{
|
||||
filter = (x) => string.Compare(x, searchPattern, true) == 0;
|
||||
}
|
||||
|
||||
List<string> results = new List<string>();
|
||||
string fixedPath = null;
|
||||
|
||||
for ( int i = index; i < s_paths.Length; ++i )
|
||||
{
|
||||
var filePath = s_paths[i];
|
||||
|
||||
if ( !filePath.StartsWith(actualDirPath) )
|
||||
break;
|
||||
|
||||
string fileName;
|
||||
|
||||
var dirSeparatorIndex = filePath.LastIndexOf('/', filePath.Length - 1, filePath.Length - actualDirPath.Length);
|
||||
if ( dirSeparatorIndex >= 0 )
|
||||
{
|
||||
if ( searchOption == SearchOption.TopDirectoryOnly )
|
||||
continue;
|
||||
|
||||
fileName = filePath.Substring(dirSeparatorIndex + 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
fileName = filePath.Substring(actualDirPath.Length);
|
||||
}
|
||||
|
||||
// now do a match
|
||||
if ( filter == null || filter(fileName) )
|
||||
{
|
||||
var normalizedPart = filePath.Substring(actualDirPath.Length);
|
||||
|
||||
if ( fixedPath == null )
|
||||
{
|
||||
fixedPath = PathUtil.FixTrailingDirectorySeparators(path);
|
||||
if ( fixedPath == "/" )
|
||||
fixedPath = string.Empty;
|
||||
}
|
||||
|
||||
var result = PathUtil.CombineSlash(fixedPath, normalizedPart);
|
||||
results.Add(result);
|
||||
}
|
||||
}
|
||||
|
||||
return results.ToArray();
|
||||
}
|
||||
|
||||
public static byte[] ReadAllBytes(string path)
|
||||
{
|
||||
ReadInfo info;
|
||||
if ( !TryGetInfo(path, out info) )
|
||||
ThrowFileNotFound(path);
|
||||
|
||||
byte[] buffer;
|
||||
using ( var fileStream = File.OpenRead(info.readPath) )
|
||||
{
|
||||
if ( info.offset != 0 )
|
||||
{
|
||||
if ( fileStream.Seek(info.offset, SeekOrigin.Begin) != info.offset )
|
||||
throw new IOException();
|
||||
}
|
||||
|
||||
if ( info.size > (long)int.MaxValue )
|
||||
throw new IOException();
|
||||
|
||||
int count = (int)info.size;
|
||||
int offset = 0;
|
||||
|
||||
buffer = new byte[count];
|
||||
while ( count > 0 )
|
||||
{
|
||||
int num = fileStream.Read(buffer, offset, count);
|
||||
if ( num == 0 )
|
||||
throw new EndOfStreamException();
|
||||
offset += num;
|
||||
count -= num;
|
||||
}
|
||||
}
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
public static System.IO.Stream OpenRead(string path)
|
||||
{
|
||||
ReadInfo info;
|
||||
if ( !TryGetInfo(path, out info) )
|
||||
ThrowFileNotFound(path);
|
||||
|
||||
Stream fileStream = File.OpenRead(info.readPath);
|
||||
try
|
||||
{
|
||||
return new SubReadOnlyStream(fileStream, info.offset, info.size, leaveOpen : false);
|
||||
}
|
||||
catch ( System.Exception )
|
||||
{
|
||||
fileStream.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private static int GetDirectoryIndex(string path)
|
||||
{
|
||||
Debug.Assert(s_paths != null);
|
||||
|
||||
// find first file there
|
||||
var index = Array.BinarySearch(s_paths, path, StringComparer.OrdinalIgnoreCase);
|
||||
if ( index >= 0 )
|
||||
return ~index;
|
||||
|
||||
// if the end, no such directory exists
|
||||
index = ~index;
|
||||
if ( index == s_paths.Length )
|
||||
return index;
|
||||
|
||||
for ( int i = index; i < s_paths.Length && s_paths[i].StartsWith(path); ++i )
|
||||
{
|
||||
// because otherwise there would be a match
|
||||
Debug.Assert(s_paths[i].Length > path.Length);
|
||||
|
||||
if ( path[path.Length - 1] == '/' )
|
||||
return i;
|
||||
|
||||
if ( s_paths[i][path.Length] == '/' )
|
||||
return i;
|
||||
}
|
||||
|
||||
return s_paths.Length;
|
||||
}
|
||||
|
||||
private static void GetStreamingAssetsInfoFromJar(string apkPath, List<string> paths, List<PartInfo> parts)
|
||||
{
|
||||
using ( var stream = File.OpenRead(apkPath) )
|
||||
using ( var reader = new BinaryReader(stream) )
|
||||
{
|
||||
if ( !stream.CanRead )
|
||||
throw new ArgumentException();
|
||||
if ( !stream.CanSeek )
|
||||
throw new ArgumentException();
|
||||
|
||||
long expectedNumberOfEntries;
|
||||
long centralDirectoryStart;
|
||||
ZipArchiveUtils.ReadEndOfCentralDirectory(stream, reader, out expectedNumberOfEntries, out centralDirectoryStart);
|
||||
|
||||
try
|
||||
{
|
||||
stream.Seek(centralDirectoryStart, SeekOrigin.Begin);
|
||||
|
||||
long numberOfEntries = 0;
|
||||
|
||||
ZipCentralDirectoryFileHeader header;
|
||||
|
||||
const int prefixLength = 7;
|
||||
const string prefix = "assets/";
|
||||
const string assetsPrefix = "assets/bin/";
|
||||
Debug.Assert(prefixLength == prefix.Length);
|
||||
|
||||
while ( ZipCentralDirectoryFileHeader.TryReadBlock(reader, out header) )
|
||||
{
|
||||
if ( header.CompressedSize != header.UncompressedSize )
|
||||
{
|
||||
#if UNITY_ASSERTIONS
|
||||
var fileName = Encoding.UTF8.GetString(header.Filename);
|
||||
if (fileName.StartsWith(prefix) && !fileName.StartsWith(assetsPrefix))
|
||||
{
|
||||
bool isStreamingAsset = true;
|
||||
AndroidIsCompressedFileStreamingAsset(fileName, ref isStreamingAsset);
|
||||
if (isStreamingAsset)
|
||||
{
|
||||
Debug.LogAssertionFormat("BetterStreamingAssets: file {0} is where Streaming Assets are put, but is compressed. " +
|
||||
"If this is a App Bundle build, see README for a possible workaround. " +
|
||||
"If this file is not a Streaming Asset (has been on purpose by hand or by another plug-in), implement " +
|
||||
"BetterStreamingAssets.AndroidIsCompressedFileStreamingAsset partial method to prevent this message from appearing again. ",
|
||||
fileName);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
// we only want uncompressed files
|
||||
}
|
||||
else
|
||||
{
|
||||
var fileName = Encoding.UTF8.GetString(header.Filename);
|
||||
|
||||
if (fileName.EndsWith("/"))
|
||||
{
|
||||
// there's some strangeness when it comes to OBB: directories are listed as files
|
||||
// simply ignoring them should be enough
|
||||
Debug.Assert(header.UncompressedSize == 0);
|
||||
}
|
||||
else if ( fileName.StartsWith(prefix) )
|
||||
{
|
||||
// ignore normal assets...
|
||||
if ( fileName.StartsWith(assetsPrefix) )
|
||||
{
|
||||
// Note: if you put bin directory in your StreamingAssets you will get false negative here
|
||||
}
|
||||
else
|
||||
{
|
||||
var relativePath = fileName.Substring(prefixLength - 1);
|
||||
var entry = new PartInfo()
|
||||
{
|
||||
crc32 = header.Crc32,
|
||||
offset = header.RelativeOffsetOfLocalHeader, // this offset will need fixing later on
|
||||
size = header.UncompressedSize
|
||||
};
|
||||
|
||||
var index = paths.BinarySearch(relativePath, StringComparer.OrdinalIgnoreCase);
|
||||
if ( index >= 0 )
|
||||
throw new System.InvalidOperationException("Paths duplicate! " + fileName);
|
||||
|
||||
paths.Insert(~index, relativePath);
|
||||
parts.Insert(~index, entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
numberOfEntries++;
|
||||
}
|
||||
|
||||
if ( numberOfEntries != expectedNumberOfEntries )
|
||||
throw new ZipArchiveException("Number of entries does not match");
|
||||
|
||||
}
|
||||
catch ( EndOfStreamException ex )
|
||||
{
|
||||
throw new ZipArchiveException("CentralDirectoryInvalid", ex);
|
||||
}
|
||||
|
||||
// now fix offsets
|
||||
for ( int i = 0; i < parts.Count; ++i )
|
||||
{
|
||||
var entry = parts[i];
|
||||
stream.Seek(entry.offset, SeekOrigin.Begin);
|
||||
|
||||
if ( !ZipLocalFileHeader.TrySkipBlock(reader) )
|
||||
throw new ZipArchiveException("Local file header corrupt");
|
||||
|
||||
entry.offset = stream.Position;
|
||||
|
||||
parts[i] = entry;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 12bc032fc47a6c34fb90f0f4a48f4441
|
||||
timeCreated: 1506516969
|
||||
licenseType: Pro
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Vendored
+164
@@ -0,0 +1,164 @@
|
||||
// Better Streaming Assets, Piotr Gwiazdowski <gwiazdorrr+github at gmail.com>, 2017
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Better.StreamingAssets
|
||||
{
|
||||
public static partial class PathUtil
|
||||
{
|
||||
private enum NormalizeState
|
||||
{
|
||||
PrevSlash,
|
||||
PrevDot,
|
||||
PrevDoubleDot,
|
||||
NothingSpecial,
|
||||
}
|
||||
|
||||
public static bool IsDirectorySeparator(char c)
|
||||
{
|
||||
return c == '/' || c == '\\';
|
||||
}
|
||||
|
||||
public static string FixTrailingDirectorySeparators(string path)
|
||||
{
|
||||
if ( path.Length >= 2 )
|
||||
{
|
||||
var lastChar = path[path.Length - 1];
|
||||
var prevChar = path[path.Length - 2];
|
||||
if ( PathUtil.IsDirectorySeparator(lastChar) && PathUtil.IsDirectorySeparator(prevChar) )
|
||||
{
|
||||
return path.TrimEnd('\\', '/') + lastChar;
|
||||
}
|
||||
}
|
||||
|
||||
return path;
|
||||
}
|
||||
|
||||
public static string CombineSlash(string a, string b)
|
||||
{
|
||||
if ( a == null )
|
||||
throw new ArgumentNullException("a");
|
||||
if ( b == null )
|
||||
throw new ArgumentNullException("b");
|
||||
|
||||
if ( string.IsNullOrEmpty(b) )
|
||||
return a;
|
||||
if ( string.IsNullOrEmpty(a) )
|
||||
return b;
|
||||
|
||||
if (b[0] == '/')
|
||||
return b;
|
||||
|
||||
if ( IsDirectorySeparator(a[a.Length -1]) )
|
||||
return a + b;
|
||||
else
|
||||
return a + '/' + b;
|
||||
}
|
||||
|
||||
public static string NormalizeRelativePath(string relative, bool forceTrailingSlash = false)
|
||||
{
|
||||
if (string.IsNullOrEmpty(relative))
|
||||
throw new System.ArgumentException("Empty or null", "relative");
|
||||
|
||||
StringBuilder output = new StringBuilder(relative.Length);
|
||||
|
||||
NormalizeState state = NormalizeState.PrevSlash;
|
||||
output.Append('/');
|
||||
|
||||
int startIndex = 0;
|
||||
int lastIndexPlus1 = relative.Length;
|
||||
|
||||
if ( relative[0] == '"' && relative.Length > 2 && relative[relative.Length - 1] == '"')
|
||||
{
|
||||
startIndex++;
|
||||
lastIndexPlus1--;
|
||||
}
|
||||
|
||||
for ( int i = startIndex; i <= lastIndexPlus1; ++i )
|
||||
{
|
||||
if (i == lastIndexPlus1 || relative[i] == '/' || relative[i] == '\\')
|
||||
{
|
||||
if ( state == NormalizeState.PrevSlash || state == NormalizeState.PrevDot )
|
||||
{
|
||||
// do nothing
|
||||
}
|
||||
else if ( state == NormalizeState.PrevDoubleDot )
|
||||
{
|
||||
if ( output.Length == 1 )
|
||||
throw new System.IO.IOException("Invalid path: double dot error (before " + i + ")");
|
||||
|
||||
// on level up!
|
||||
int j;
|
||||
for ( j = output.Length - 2; j >= 0 && output[j] != '/'; --j)
|
||||
{
|
||||
}
|
||||
|
||||
output.Remove(j + 1, output.Length - j - 1);
|
||||
}
|
||||
else if ( i < lastIndexPlus1 || forceTrailingSlash )
|
||||
{
|
||||
output.Append('/');
|
||||
}
|
||||
|
||||
state = NormalizeState.PrevSlash;
|
||||
}
|
||||
else if ( relative[i] == '.' )
|
||||
{
|
||||
if ( state == NormalizeState.PrevSlash )
|
||||
{
|
||||
state = NormalizeState.PrevDot;
|
||||
}
|
||||
else if ( state == NormalizeState.PrevDot )
|
||||
{
|
||||
state = NormalizeState.PrevDoubleDot;
|
||||
}
|
||||
else if ( state == NormalizeState.PrevDoubleDot )
|
||||
{
|
||||
state = NormalizeState.NothingSpecial;
|
||||
output.Append("...");
|
||||
}
|
||||
else
|
||||
{
|
||||
output.Append('.');
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if ( state == NormalizeState.PrevDot )
|
||||
{
|
||||
output.Append('.');
|
||||
}
|
||||
else if ( state == NormalizeState.PrevDoubleDot )
|
||||
{
|
||||
output.Append("..");
|
||||
}
|
||||
|
||||
if (!IsValidCharacter(relative[i]))
|
||||
throw new System.IO.IOException("Invalid characters");
|
||||
|
||||
output.Append(relative[i]);
|
||||
state = NormalizeState.NothingSpecial;
|
||||
}
|
||||
}
|
||||
|
||||
return output.ToString();
|
||||
}
|
||||
|
||||
public static bool IsValidCharacter(char c)
|
||||
{
|
||||
if (c == '\"' || c == '<' || c == '>' || c == '|' || c < 32 || c == ':' || c == '*' || c == '?')
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
public static Regex WildcardToRegex(string pattern)
|
||||
{
|
||||
return new Regex("^" + Regex.Escape(pattern).Replace(@"\*", ".*").Replace(@"\?", ".") + "$", RegexOptions.IgnoreCase);
|
||||
}
|
||||
}
|
||||
}
|
||||
Assets/YooAsset/Samples~/Space Shooter/ThirdParty/BetterStreamingAssets/Runtime/BSA_PathUtil.cs.meta
Vendored
+12
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 34f6b4de9962c114299b3b9bfdd590d5
|
||||
timeCreated: 1506546248
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
// Better Streaming Assets, Piotr Gwiazdowski <gwiazdorrr+github at gmail.com>, 2017
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Better.StreamingAssets
|
||||
{
|
||||
internal class SubReadOnlyStream: Stream
|
||||
{
|
||||
private readonly long m_offset;
|
||||
private readonly bool m_leaveOpen;
|
||||
|
||||
private long? m_length;
|
||||
private Stream m_actualStream;
|
||||
private long m_position;
|
||||
|
||||
public SubReadOnlyStream(Stream actualStream, bool leaveOpen = false)
|
||||
{
|
||||
if (actualStream == null)
|
||||
throw new ArgumentNullException("superStream");
|
||||
|
||||
m_actualStream = actualStream;
|
||||
m_leaveOpen = leaveOpen;
|
||||
}
|
||||
|
||||
public SubReadOnlyStream(Stream actualStream, long offset, long length, bool leaveOpen = false)
|
||||
: this(actualStream, leaveOpen)
|
||||
{
|
||||
if (offset < 0)
|
||||
throw new ArgumentOutOfRangeException("offset");
|
||||
|
||||
if (length < 0)
|
||||
throw new ArgumentOutOfRangeException("length");
|
||||
|
||||
Debug.Assert(offset <= actualStream.Length);
|
||||
Debug.Assert(actualStream.Length >= length);
|
||||
Debug.Assert(offset + length <= actualStream.Length);
|
||||
|
||||
m_offset = offset;
|
||||
m_position = offset;
|
||||
m_length = length;
|
||||
}
|
||||
|
||||
public override long Length
|
||||
{
|
||||
get
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
|
||||
if (!m_length.HasValue)
|
||||
m_length = m_actualStream.Length - m_offset;
|
||||
|
||||
return m_length.Value;
|
||||
}
|
||||
}
|
||||
|
||||
public override long Position
|
||||
{
|
||||
get
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
return m_position - m_offset;
|
||||
}
|
||||
set
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
m_position = m_offset + value;
|
||||
}
|
||||
}
|
||||
|
||||
public override bool CanRead { get { return m_actualStream.CanRead; } }
|
||||
|
||||
public override bool CanSeek { get { return m_actualStream.CanSeek; } }
|
||||
|
||||
public override bool CanWrite { get { return false; } }
|
||||
|
||||
public override int Read(byte[] buffer, int offset, int count)
|
||||
{
|
||||
ThrowIfCantRead();
|
||||
ThrowIfDisposed();
|
||||
|
||||
if ( m_actualStream.Position != m_position )
|
||||
m_actualStream.Seek(m_position, SeekOrigin.Begin);
|
||||
|
||||
if ( m_length.HasValue )
|
||||
{
|
||||
var endPosition = m_offset + m_length.Value;
|
||||
if (m_position + count > endPosition)
|
||||
{
|
||||
count = (int)(endPosition - m_position);
|
||||
}
|
||||
}
|
||||
|
||||
int bytesRead = m_actualStream.Read(buffer, offset, count);
|
||||
m_position += bytesRead;
|
||||
return bytesRead;
|
||||
}
|
||||
|
||||
public override long Seek(long offset, SeekOrigin origin)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
|
||||
if ( origin == SeekOrigin.Begin )
|
||||
{
|
||||
m_position = m_actualStream.Seek(m_offset + offset, SeekOrigin.Begin);
|
||||
}
|
||||
else if ( origin == SeekOrigin.End )
|
||||
{
|
||||
m_position = m_actualStream.Seek(m_offset + Length + offset, SeekOrigin.Begin);
|
||||
}
|
||||
else
|
||||
{
|
||||
m_position = m_actualStream.Seek(offset, SeekOrigin.Current);
|
||||
}
|
||||
return m_position - m_offset;
|
||||
}
|
||||
|
||||
public override void SetLength(long value)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public override void Write(byte[] buffer, int offset, int count)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public override void Flush()
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
// Close the stream for reading. Note that this does NOT close the superStream (since
|
||||
// the substream is just 'a chunk' of the super-stream
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if ( disposing )
|
||||
{
|
||||
if (m_actualStream != null)
|
||||
{
|
||||
if (!m_leaveOpen)
|
||||
m_actualStream.Dispose();
|
||||
|
||||
m_actualStream = null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
private void ThrowIfDisposed()
|
||||
{
|
||||
if (m_actualStream == null)
|
||||
throw new ObjectDisposedException(GetType().ToString(), "");
|
||||
}
|
||||
|
||||
private void ThrowIfCantRead()
|
||||
{
|
||||
if (!CanRead)
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 23985058976064b4aa47f955e25b32fb
|
||||
timeCreated: 1506207467
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Vendored
+649
@@ -0,0 +1,649 @@
|
||||
// Better Streaming Assets, Piotr Gwiazdowski <gwiazdorrr+github at gmail.com>, 2017
|
||||
// Bits below are copied from or inspired by System.IO.Compression.dll; leaving comments from
|
||||
// original source code and attaching license
|
||||
|
||||
// The MIT License(MIT)
|
||||
//
|
||||
// Copyright(c) .NET Foundation and Contributors
|
||||
//
|
||||
// All rights reserved.
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Better.StreamingAssets.ZipArchive
|
||||
{
|
||||
// All blocks.TryReadBlock do a check to see if signature is correct. Generic extra field is slightly different
|
||||
// all of the TryReadBlocks will throw if there are not enough bytes in the stream
|
||||
|
||||
internal struct ZipGenericExtraField
|
||||
{
|
||||
private const int SizeOfHeader = 4;
|
||||
|
||||
private ushort _tag;
|
||||
private ushort _size;
|
||||
private byte[] _data;
|
||||
|
||||
public ushort Tag { get { return _tag; } }
|
||||
// returns size of data, not of the entire block
|
||||
public ushort Size { get { return _size; } }
|
||||
public byte[] Data { get { return _data; } }
|
||||
|
||||
// shouldn't ever read the byte at position endExtraField
|
||||
// assumes we are positioned at the beginning of an extra field subfield
|
||||
public static bool TryReadBlock(BinaryReader reader, long endExtraField, out ZipGenericExtraField field)
|
||||
{
|
||||
field = new ZipGenericExtraField();
|
||||
|
||||
// not enough bytes to read tag + size
|
||||
if ( endExtraField - reader.BaseStream.Position < 4 )
|
||||
return false;
|
||||
|
||||
field._tag = reader.ReadUInt16();
|
||||
field._size = reader.ReadUInt16();
|
||||
|
||||
// not enough bytes to read the data
|
||||
if ( endExtraField - reader.BaseStream.Position < field._size )
|
||||
return false;
|
||||
|
||||
field._data = reader.ReadBytes(field._size);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
internal struct Zip64ExtraField
|
||||
{
|
||||
// Size is size of the record not including the tag or size fields
|
||||
// If the extra field is going in the local header, it cannot include only
|
||||
// one of uncompressed/compressed size
|
||||
|
||||
public const int OffsetToFirstField = 4;
|
||||
private const ushort TagConstant = 1;
|
||||
|
||||
private ushort _size;
|
||||
private long? _uncompressedSize;
|
||||
private long? _compressedSize;
|
||||
private long? _localHeaderOffset;
|
||||
private int? _startDiskNumber;
|
||||
|
||||
|
||||
public long? UncompressedSize
|
||||
{
|
||||
get { return _uncompressedSize; }
|
||||
set { _uncompressedSize = value; UpdateSize(); }
|
||||
}
|
||||
public long? CompressedSize
|
||||
{
|
||||
get { return _compressedSize; }
|
||||
set { _compressedSize = value; UpdateSize(); }
|
||||
}
|
||||
public long? LocalHeaderOffset
|
||||
{
|
||||
get { return _localHeaderOffset; }
|
||||
set { _localHeaderOffset = value; UpdateSize(); }
|
||||
}
|
||||
public int? StartDiskNumber { get { return _startDiskNumber; } }
|
||||
|
||||
private void UpdateSize()
|
||||
{
|
||||
_size = 0;
|
||||
if ( _uncompressedSize != null ) _size += 8;
|
||||
if ( _compressedSize != null ) _size += 8;
|
||||
if ( _localHeaderOffset != null ) _size += 8;
|
||||
if ( _startDiskNumber != null ) _size += 4;
|
||||
}
|
||||
|
||||
// There is a small chance that something very weird could happen here. The code calling into this function
|
||||
// will ask for a value from the extra field if the field was masked with FF's. It's theoretically possible
|
||||
// that a field was FF's legitimately, and the writer didn't decide to write the corresponding extra field.
|
||||
// Also, at the same time, other fields were masked with FF's to indicate looking in the zip64 record.
|
||||
// Then, the search for the zip64 record will fail because the expected size is wrong,
|
||||
// and a nulled out Zip64ExtraField will be returned. Thus, even though there was Zip64 data,
|
||||
// it will not be used. It is questionable whether this situation is possible to detect
|
||||
|
||||
// unlike the other functions that have try-pattern semantics, these functions always return a
|
||||
// Zip64ExtraField. If a Zip64 extra field actually doesn't exist, all of the fields in the
|
||||
// returned struct will be null
|
||||
//
|
||||
// If there are more than one Zip64 extra fields, we take the first one that has the expected size
|
||||
//
|
||||
public static Zip64ExtraField GetJustZip64Block(Stream extraFieldStream,
|
||||
bool readUncompressedSize, bool readCompressedSize,
|
||||
bool readLocalHeaderOffset, bool readStartDiskNumber)
|
||||
{
|
||||
Zip64ExtraField zip64Field;
|
||||
using ( BinaryReader reader = new BinaryReader(extraFieldStream) )
|
||||
{
|
||||
ZipGenericExtraField currentExtraField;
|
||||
while ( ZipGenericExtraField.TryReadBlock(reader, extraFieldStream.Length, out currentExtraField) )
|
||||
{
|
||||
if ( TryGetZip64BlockFromGenericExtraField(currentExtraField, readUncompressedSize,
|
||||
readCompressedSize, readLocalHeaderOffset, readStartDiskNumber, out zip64Field) )
|
||||
{
|
||||
return zip64Field;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
zip64Field = new Zip64ExtraField();
|
||||
|
||||
zip64Field._compressedSize = null;
|
||||
zip64Field._uncompressedSize = null;
|
||||
zip64Field._localHeaderOffset = null;
|
||||
zip64Field._startDiskNumber = null;
|
||||
|
||||
return zip64Field;
|
||||
}
|
||||
|
||||
private static bool TryGetZip64BlockFromGenericExtraField(ZipGenericExtraField extraField,
|
||||
bool readUncompressedSize, bool readCompressedSize,
|
||||
bool readLocalHeaderOffset, bool readStartDiskNumber,
|
||||
out Zip64ExtraField zip64Block)
|
||||
{
|
||||
zip64Block = new Zip64ExtraField();
|
||||
|
||||
zip64Block._compressedSize = null;
|
||||
zip64Block._uncompressedSize = null;
|
||||
zip64Block._localHeaderOffset = null;
|
||||
zip64Block._startDiskNumber = null;
|
||||
|
||||
if ( extraField.Tag != TagConstant )
|
||||
return false;
|
||||
|
||||
// this pattern needed because nested using blocks trigger CA2202
|
||||
MemoryStream ms = null;
|
||||
try
|
||||
{
|
||||
ms = new MemoryStream(extraField.Data);
|
||||
using ( BinaryReader reader = new BinaryReader(ms) )
|
||||
{
|
||||
ms = null;
|
||||
|
||||
zip64Block._size = extraField.Size;
|
||||
|
||||
ushort expectedSize = 0;
|
||||
|
||||
if ( readUncompressedSize ) expectedSize += 8;
|
||||
if ( readCompressedSize ) expectedSize += 8;
|
||||
if ( readLocalHeaderOffset ) expectedSize += 8;
|
||||
if ( readStartDiskNumber ) expectedSize += 4;
|
||||
|
||||
// if it is not the expected size, perhaps there is another extra field that matches
|
||||
if ( expectedSize != zip64Block._size )
|
||||
return false;
|
||||
|
||||
if ( readUncompressedSize ) zip64Block._uncompressedSize = reader.ReadInt64();
|
||||
if ( readCompressedSize ) zip64Block._compressedSize = reader.ReadInt64();
|
||||
if ( readLocalHeaderOffset ) zip64Block._localHeaderOffset = reader.ReadInt64();
|
||||
if ( readStartDiskNumber ) zip64Block._startDiskNumber = reader.ReadInt32();
|
||||
|
||||
// original values are unsigned, so implies value is too big to fit in signed integer
|
||||
if ( zip64Block._uncompressedSize < 0 ) throw new ZipArchiveException("FieldTooBigUncompressedSize");
|
||||
if ( zip64Block._compressedSize < 0 ) throw new ZipArchiveException("FieldTooBigCompressedSize");
|
||||
if ( zip64Block._localHeaderOffset < 0 ) throw new ZipArchiveException("FieldTooBigLocalHeaderOffset");
|
||||
if ( zip64Block._startDiskNumber < 0 ) throw new ZipArchiveException("FieldTooBigStartDiskNumber");
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
if ( ms != null )
|
||||
ms.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
internal struct Zip64EndOfCentralDirectoryLocator
|
||||
{
|
||||
public const uint SignatureConstant = 0x07064B50;
|
||||
public const int SizeOfBlockWithoutSignature = 16;
|
||||
|
||||
public uint NumberOfDiskWithZip64EOCD;
|
||||
public ulong OffsetOfZip64EOCD;
|
||||
public uint TotalNumberOfDisks;
|
||||
|
||||
public static bool TryReadBlock(BinaryReader reader, out Zip64EndOfCentralDirectoryLocator zip64EOCDLocator)
|
||||
{
|
||||
zip64EOCDLocator = new Zip64EndOfCentralDirectoryLocator();
|
||||
|
||||
if ( reader.ReadUInt32() != SignatureConstant )
|
||||
return false;
|
||||
|
||||
zip64EOCDLocator.NumberOfDiskWithZip64EOCD = reader.ReadUInt32();
|
||||
zip64EOCDLocator.OffsetOfZip64EOCD = reader.ReadUInt64();
|
||||
zip64EOCDLocator.TotalNumberOfDisks = reader.ReadUInt32();
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
internal struct Zip64EndOfCentralDirectoryRecord
|
||||
{
|
||||
private const uint SignatureConstant = 0x06064B50;
|
||||
private const ulong NormalSize = 0x2C; // the size of the data excluding the size/signature fields if no extra data included
|
||||
|
||||
public ulong SizeOfThisRecord;
|
||||
public ushort VersionMadeBy;
|
||||
public ushort VersionNeededToExtract;
|
||||
public uint NumberOfThisDisk;
|
||||
public uint NumberOfDiskWithStartOfCD;
|
||||
public ulong NumberOfEntriesOnThisDisk;
|
||||
public ulong NumberOfEntriesTotal;
|
||||
public ulong SizeOfCentralDirectory;
|
||||
public ulong OffsetOfCentralDirectory;
|
||||
|
||||
public static bool TryReadBlock(BinaryReader reader, out Zip64EndOfCentralDirectoryRecord zip64EOCDRecord)
|
||||
{
|
||||
zip64EOCDRecord = new Zip64EndOfCentralDirectoryRecord();
|
||||
|
||||
if ( reader.ReadUInt32() != SignatureConstant )
|
||||
return false;
|
||||
|
||||
zip64EOCDRecord.SizeOfThisRecord = reader.ReadUInt64();
|
||||
zip64EOCDRecord.VersionMadeBy = reader.ReadUInt16();
|
||||
zip64EOCDRecord.VersionNeededToExtract = reader.ReadUInt16();
|
||||
zip64EOCDRecord.NumberOfThisDisk = reader.ReadUInt32();
|
||||
zip64EOCDRecord.NumberOfDiskWithStartOfCD = reader.ReadUInt32();
|
||||
zip64EOCDRecord.NumberOfEntriesOnThisDisk = reader.ReadUInt64();
|
||||
zip64EOCDRecord.NumberOfEntriesTotal = reader.ReadUInt64();
|
||||
zip64EOCDRecord.SizeOfCentralDirectory = reader.ReadUInt64();
|
||||
zip64EOCDRecord.OffsetOfCentralDirectory = reader.ReadUInt64();
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
internal struct ZipLocalFileHeader
|
||||
{
|
||||
public const uint DataDescriptorSignature = 0x08074B50;
|
||||
public const uint SignatureConstant = 0x04034B50;
|
||||
public const int OffsetToCrcFromHeaderStart = 14;
|
||||
public const int OffsetToBitFlagFromHeaderStart = 6;
|
||||
public const int SizeOfLocalHeader = 30;
|
||||
|
||||
|
||||
// will not throw end of stream exception
|
||||
public static bool TrySkipBlock(BinaryReader reader)
|
||||
{
|
||||
const int OffsetToFilenameLength = 22; // from the point after the signature
|
||||
|
||||
if ( reader.ReadUInt32() != SignatureConstant )
|
||||
return false;
|
||||
|
||||
|
||||
if ( reader.BaseStream.Length < reader.BaseStream.Position + OffsetToFilenameLength )
|
||||
return false;
|
||||
|
||||
reader.BaseStream.Seek(OffsetToFilenameLength, SeekOrigin.Current);
|
||||
|
||||
ushort filenameLength = reader.ReadUInt16();
|
||||
ushort extraFieldLength = reader.ReadUInt16();
|
||||
|
||||
if ( reader.BaseStream.Length < reader.BaseStream.Position + filenameLength + extraFieldLength )
|
||||
return false;
|
||||
|
||||
reader.BaseStream.Seek(filenameLength + extraFieldLength, SeekOrigin.Current);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
internal struct ZipCentralDirectoryFileHeader
|
||||
{
|
||||
public const uint SignatureConstant = 0x02014B50;
|
||||
public byte VersionMadeByCompatibility;
|
||||
public byte VersionMadeBySpecification;
|
||||
public ushort VersionNeededToExtract;
|
||||
public ushort GeneralPurposeBitFlag;
|
||||
public ushort CompressionMethod;
|
||||
public uint LastModified; // convert this on the fly
|
||||
public uint Crc32;
|
||||
public long CompressedSize;
|
||||
public long UncompressedSize;
|
||||
public ushort FilenameLength;
|
||||
public ushort ExtraFieldLength;
|
||||
public ushort FileCommentLength;
|
||||
public int DiskNumberStart;
|
||||
public ushort InternalFileAttributes;
|
||||
public uint ExternalFileAttributes;
|
||||
public long RelativeOffsetOfLocalHeader;
|
||||
|
||||
public byte[] Filename;
|
||||
public byte[] FileComment;
|
||||
public List<ZipGenericExtraField> ExtraFields;
|
||||
|
||||
// if saveExtraFieldsAndComments is false, FileComment and ExtraFields will be null
|
||||
// in either case, the zip64 extra field info will be incorporated into other fields
|
||||
public static bool TryReadBlock(BinaryReader reader, out ZipCentralDirectoryFileHeader header)
|
||||
{
|
||||
header = new ZipCentralDirectoryFileHeader();
|
||||
|
||||
if ( reader.ReadUInt32() != SignatureConstant )
|
||||
return false;
|
||||
header.VersionMadeBySpecification = reader.ReadByte();
|
||||
header.VersionMadeByCompatibility = reader.ReadByte();
|
||||
header.VersionNeededToExtract = reader.ReadUInt16();
|
||||
header.GeneralPurposeBitFlag = reader.ReadUInt16();
|
||||
header.CompressionMethod = reader.ReadUInt16();
|
||||
header.LastModified = reader.ReadUInt32();
|
||||
header.Crc32 = reader.ReadUInt32();
|
||||
uint compressedSizeSmall = reader.ReadUInt32();
|
||||
uint uncompressedSizeSmall = reader.ReadUInt32();
|
||||
header.FilenameLength = reader.ReadUInt16();
|
||||
header.ExtraFieldLength = reader.ReadUInt16();
|
||||
header.FileCommentLength = reader.ReadUInt16();
|
||||
ushort diskNumberStartSmall = reader.ReadUInt16();
|
||||
header.InternalFileAttributes = reader.ReadUInt16();
|
||||
header.ExternalFileAttributes = reader.ReadUInt32();
|
||||
uint relativeOffsetOfLocalHeaderSmall = reader.ReadUInt32();
|
||||
|
||||
header.Filename = reader.ReadBytes(header.FilenameLength);
|
||||
|
||||
bool uncompressedSizeInZip64 = uncompressedSizeSmall == ZipHelper.Mask32Bit;
|
||||
bool compressedSizeInZip64 = compressedSizeSmall == ZipHelper.Mask32Bit;
|
||||
bool relativeOffsetInZip64 = relativeOffsetOfLocalHeaderSmall == ZipHelper.Mask32Bit;
|
||||
bool diskNumberStartInZip64 = diskNumberStartSmall == ZipHelper.Mask16Bit;
|
||||
|
||||
Zip64ExtraField zip64;
|
||||
|
||||
long endExtraFields = reader.BaseStream.Position + header.ExtraFieldLength;
|
||||
using ( Stream str = new SubReadOnlyStream(reader.BaseStream, reader.BaseStream.Position, header.ExtraFieldLength, leaveOpen: true) )
|
||||
{
|
||||
header.ExtraFields = null;
|
||||
zip64 = Zip64ExtraField.GetJustZip64Block(str,
|
||||
uncompressedSizeInZip64, compressedSizeInZip64,
|
||||
relativeOffsetInZip64, diskNumberStartInZip64);
|
||||
}
|
||||
|
||||
// There are zip files that have malformed ExtraField blocks in which GetJustZip64Block() silently bails out without reading all the way to the end
|
||||
// of the ExtraField block. Thus we must force the stream's position to the proper place.
|
||||
reader.BaseStream.AdvanceToPosition(endExtraFields);
|
||||
|
||||
reader.BaseStream.Position += header.FileCommentLength;
|
||||
header.FileComment = null;
|
||||
|
||||
header.UncompressedSize = zip64.UncompressedSize == null
|
||||
? uncompressedSizeSmall
|
||||
: zip64.UncompressedSize.Value;
|
||||
header.CompressedSize = zip64.CompressedSize == null
|
||||
? compressedSizeSmall
|
||||
: zip64.CompressedSize.Value;
|
||||
header.RelativeOffsetOfLocalHeader = zip64.LocalHeaderOffset == null
|
||||
? relativeOffsetOfLocalHeaderSmall
|
||||
: zip64.LocalHeaderOffset.Value;
|
||||
header.DiskNumberStart = zip64.StartDiskNumber == null
|
||||
? diskNumberStartSmall
|
||||
: zip64.StartDiskNumber.Value;
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
internal struct ZipEndOfCentralDirectoryBlock
|
||||
{
|
||||
public const uint SignatureConstant = 0x06054B50;
|
||||
public const int SizeOfBlockWithoutSignature = 18;
|
||||
public uint Signature;
|
||||
public ushort NumberOfThisDisk;
|
||||
public ushort NumberOfTheDiskWithTheStartOfTheCentralDirectory;
|
||||
public ushort NumberOfEntriesInTheCentralDirectoryOnThisDisk;
|
||||
public ushort NumberOfEntriesInTheCentralDirectory;
|
||||
public uint SizeOfCentralDirectory;
|
||||
public uint OffsetOfStartOfCentralDirectoryWithRespectToTheStartingDiskNumber;
|
||||
public byte[] ArchiveComment;
|
||||
|
||||
|
||||
public static bool TryReadBlock(BinaryReader reader, out ZipEndOfCentralDirectoryBlock eocdBlock)
|
||||
{
|
||||
eocdBlock = new ZipEndOfCentralDirectoryBlock();
|
||||
if ( reader.ReadUInt32() != SignatureConstant )
|
||||
return false;
|
||||
|
||||
eocdBlock.Signature = SignatureConstant;
|
||||
eocdBlock.NumberOfThisDisk = reader.ReadUInt16();
|
||||
eocdBlock.NumberOfTheDiskWithTheStartOfTheCentralDirectory = reader.ReadUInt16();
|
||||
eocdBlock.NumberOfEntriesInTheCentralDirectoryOnThisDisk = reader.ReadUInt16();
|
||||
eocdBlock.NumberOfEntriesInTheCentralDirectory = reader.ReadUInt16();
|
||||
eocdBlock.SizeOfCentralDirectory = reader.ReadUInt32();
|
||||
eocdBlock.OffsetOfStartOfCentralDirectoryWithRespectToTheStartingDiskNumber = reader.ReadUInt32();
|
||||
|
||||
ushort commentLength = reader.ReadUInt16();
|
||||
eocdBlock.ArchiveComment = reader.ReadBytes(commentLength);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
internal static class ZipHelper
|
||||
{
|
||||
internal const uint Mask32Bit = 0xFFFFFFFF;
|
||||
internal const ushort Mask16Bit = 0xFFFF;
|
||||
|
||||
private const int BackwardsSeekingBufferSize = 32;
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Reads exactly bytesToRead out of stream, unless it is out of bytes
|
||||
/// </summary>
|
||||
internal static void ReadBytes(Stream stream, byte[] buffer, int bytesToRead)
|
||||
{
|
||||
int bytesLeftToRead = bytesToRead;
|
||||
|
||||
int totalBytesRead = 0;
|
||||
|
||||
while (bytesLeftToRead > 0)
|
||||
{
|
||||
int bytesRead = stream.Read(buffer, totalBytesRead, bytesLeftToRead);
|
||||
if (bytesRead == 0) throw new IOException();
|
||||
|
||||
totalBytesRead += bytesRead;
|
||||
bytesLeftToRead -= bytesRead;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// assumes all bytes of signatureToFind are non zero, looks backwards from current position in stream,
|
||||
// if the signature is found then returns true and positions stream at first byte of signature
|
||||
// if the signature is not found, returns false
|
||||
internal static bool SeekBackwardsToSignature(Stream stream, uint signatureToFind)
|
||||
{
|
||||
int bufferPointer = 0;
|
||||
uint currentSignature = 0;
|
||||
byte[] buffer = new byte[BackwardsSeekingBufferSize];
|
||||
|
||||
bool outOfBytes = false;
|
||||
bool signatureFound = false;
|
||||
|
||||
while (!signatureFound && !outOfBytes)
|
||||
{
|
||||
outOfBytes = SeekBackwardsAndRead(stream, buffer, out bufferPointer);
|
||||
|
||||
Debug.Assert(bufferPointer < buffer.Length);
|
||||
|
||||
while (bufferPointer >= 0 && !signatureFound)
|
||||
{
|
||||
currentSignature = (currentSignature << 8) | ((uint)buffer[bufferPointer]);
|
||||
if (currentSignature == signatureToFind)
|
||||
{
|
||||
signatureFound = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
bufferPointer--;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!signatureFound)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
stream.Seek(bufferPointer, SeekOrigin.Current);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Skip to a further position downstream (without relying on the stream being seekable)
|
||||
internal static void AdvanceToPosition(this Stream stream, long position)
|
||||
{
|
||||
long numBytesLeft = position - stream.Position;
|
||||
Debug.Assert(numBytesLeft >= 0);
|
||||
while (numBytesLeft != 0)
|
||||
{
|
||||
const int throwAwayBufferSize = 64;
|
||||
int numBytesToSkip = (numBytesLeft > throwAwayBufferSize) ? throwAwayBufferSize : (int)numBytesLeft;
|
||||
int numBytesActuallySkipped = stream.Read(new byte[throwAwayBufferSize], 0, numBytesToSkip);
|
||||
if (numBytesActuallySkipped == 0)
|
||||
throw new IOException();
|
||||
numBytesLeft -= numBytesActuallySkipped;
|
||||
}
|
||||
}
|
||||
|
||||
// Returns true if we are out of bytes
|
||||
private static bool SeekBackwardsAndRead(Stream stream, byte[] buffer, out int bufferPointer)
|
||||
{
|
||||
if (stream.Position >= buffer.Length)
|
||||
{
|
||||
stream.Seek(-buffer.Length, SeekOrigin.Current);
|
||||
ReadBytes(stream, buffer, buffer.Length);
|
||||
stream.Seek(-buffer.Length, SeekOrigin.Current);
|
||||
bufferPointer = buffer.Length - 1;
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
int bytesToRead = (int)stream.Position;
|
||||
stream.Seek(0, SeekOrigin.Begin);
|
||||
ReadBytes(stream, buffer, bytesToRead);
|
||||
stream.Seek(0, SeekOrigin.Begin);
|
||||
bufferPointer = bytesToRead - 1;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class ZipArchiveException : Exception
|
||||
{
|
||||
public ZipArchiveException(string msg) : base(msg)
|
||||
{ }
|
||||
|
||||
public ZipArchiveException(string msg, Exception inner)
|
||||
: base(msg, inner)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public static class ZipArchiveUtils
|
||||
{
|
||||
public static void ReadEndOfCentralDirectory(Stream stream, BinaryReader reader, out long expectedNumberOfEntries, out long centralDirectoryStart)
|
||||
{
|
||||
try
|
||||
{
|
||||
// this seeks to the start of the end of central directory record
|
||||
stream.Seek(-ZipEndOfCentralDirectoryBlock.SizeOfBlockWithoutSignature, SeekOrigin.End);
|
||||
if (!ZipHelper.SeekBackwardsToSignature(stream, ZipEndOfCentralDirectoryBlock.SignatureConstant))
|
||||
throw new ZipArchiveException("SignatureConstant");
|
||||
|
||||
long eocdStart = stream.Position;
|
||||
|
||||
// read the EOCD
|
||||
ZipEndOfCentralDirectoryBlock eocd;
|
||||
bool eocdProper = ZipEndOfCentralDirectoryBlock.TryReadBlock(reader, out eocd);
|
||||
Debug.Assert(eocdProper); // we just found this using the signature finder, so it should be okay
|
||||
|
||||
if (eocd.NumberOfThisDisk != eocd.NumberOfTheDiskWithTheStartOfTheCentralDirectory)
|
||||
throw new ZipArchiveException("SplitSpanned");
|
||||
|
||||
centralDirectoryStart = eocd.OffsetOfStartOfCentralDirectoryWithRespectToTheStartingDiskNumber;
|
||||
if (eocd.NumberOfEntriesInTheCentralDirectory != eocd.NumberOfEntriesInTheCentralDirectoryOnThisDisk)
|
||||
throw new ZipArchiveException("SplitSpanned");
|
||||
expectedNumberOfEntries = eocd.NumberOfEntriesInTheCentralDirectory;
|
||||
|
||||
|
||||
// only bother looking for zip64 EOCD stuff if we suspect it is needed because some value is FFFFFFFFF
|
||||
// because these are the only two values we need, we only worry about these
|
||||
// if we don't find the zip64 EOCD, we just give up and try to use the original values
|
||||
if (eocd.NumberOfThisDisk == ZipHelper.Mask16Bit ||
|
||||
eocd.OffsetOfStartOfCentralDirectoryWithRespectToTheStartingDiskNumber == ZipHelper.Mask32Bit ||
|
||||
eocd.NumberOfEntriesInTheCentralDirectory == ZipHelper.Mask16Bit)
|
||||
{
|
||||
// we need to look for zip 64 EOCD stuff
|
||||
// seek to the zip 64 EOCD locator
|
||||
stream.Seek(eocdStart - Zip64EndOfCentralDirectoryLocator.SizeOfBlockWithoutSignature, SeekOrigin.Begin);
|
||||
// if we don't find it, assume it doesn't exist and use data from normal eocd
|
||||
if (ZipHelper.SeekBackwardsToSignature(stream, Zip64EndOfCentralDirectoryLocator.SignatureConstant))
|
||||
{
|
||||
// use locator to get to Zip64EOCD
|
||||
Zip64EndOfCentralDirectoryLocator locator;
|
||||
bool zip64eocdLocatorProper = Zip64EndOfCentralDirectoryLocator.TryReadBlock(reader, out locator);
|
||||
Debug.Assert(zip64eocdLocatorProper); // we just found this using the signature finder, so it should be okay
|
||||
|
||||
if (locator.OffsetOfZip64EOCD > long.MaxValue)
|
||||
throw new ZipArchiveException("FieldTooBigOffsetToZip64EOCD");
|
||||
long zip64EOCDOffset = (long)locator.OffsetOfZip64EOCD;
|
||||
|
||||
stream.Seek(zip64EOCDOffset, SeekOrigin.Begin);
|
||||
|
||||
// read Zip64EOCD
|
||||
Zip64EndOfCentralDirectoryRecord record;
|
||||
if (!Zip64EndOfCentralDirectoryRecord.TryReadBlock(reader, out record))
|
||||
throw new ZipArchiveException("Zip64EOCDNotWhereExpected");
|
||||
|
||||
if (record.NumberOfEntriesTotal > long.MaxValue)
|
||||
throw new ZipArchiveException("FieldTooBigNumEntries");
|
||||
if (record.OffsetOfCentralDirectory > long.MaxValue)
|
||||
throw new ZipArchiveException("FieldTooBigOffsetToCD");
|
||||
if (record.NumberOfEntriesTotal != record.NumberOfEntriesOnThisDisk)
|
||||
throw new ZipArchiveException("SplitSpanned");
|
||||
|
||||
expectedNumberOfEntries = (long)record.NumberOfEntriesTotal;
|
||||
centralDirectoryStart = (long)record.OffsetOfCentralDirectory;
|
||||
}
|
||||
}
|
||||
|
||||
if (centralDirectoryStart > stream.Length)
|
||||
{
|
||||
throw new ZipArchiveException("FieldTooBigOffsetToCD");
|
||||
}
|
||||
}
|
||||
catch (EndOfStreamException ex)
|
||||
{
|
||||
throw new ZipArchiveException("CDCorrupt", ex);
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
throw new ZipArchiveException("CDCorrupt", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4ae0668083250b649a64c7836ec20f11
|
||||
timeCreated: 1506207467
|
||||
licenseType: Free
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"name": "BetterStreamingAssets",
|
||||
"references": [],
|
||||
"optionalUnityReferences": [],
|
||||
"includePlatforms": [],
|
||||
"excludePlatforms": [],
|
||||
"allowUnsafeCode": false
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5e90fee04fdf7164fa71eeef34c6a431
|
||||
AssemblyDefinitionImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"name": "com.gwiazdorrr.betterstreamingassets",
|
||||
"displayName": "Better Streaming Assets",
|
||||
"author": { "name": "Piotr Gwiazdowski" },
|
||||
"version": "1.6.0",
|
||||
"documentationUrl": "https://github.com/gwiazdorrr/BetterStreamingAssets",
|
||||
"changelogUrl": "https://github.com/gwiazdorrr/BetterStreamingAssets",
|
||||
"licensesUrl": "https://github.com/gwiazdorrr/BetterStreamingAssets/blob/master/LICENSE",
|
||||
"description": "Access Streaming Assets directly in an uniform and thread-safe way, with tiny overhead.",
|
||||
"samples": [
|
||||
{
|
||||
"displayName": "Better Streaming Assets Samples",
|
||||
"path": "Samples~/BetterStreamingAssets"
|
||||
}
|
||||
]
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 08dafaa194a7143109cbe1c6403a2ec5
|
||||
TextScriptImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: eb9a320b68b1078468ead3c9a8e9a98a
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f2801816f5bf9e74eb7f2e2b340ad4cc
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
# UniFramework.Event
|
||||
|
||||
一个轻量级的事件系统。
|
||||
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5dfad42c0d1a02f429a99108a35bbfce
|
||||
TextScriptImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e86e06e6a95e6cc43940623bcc15721c
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Vendored
+48
@@ -0,0 +1,48 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace UniFramework.Event
|
||||
{
|
||||
public class EventGroup
|
||||
{
|
||||
private readonly Dictionary<System.Type, List<Action<IEventMessage>>> _cachedListener = new Dictionary<System.Type, List<Action<IEventMessage>>>();
|
||||
|
||||
/// <summary>
|
||||
/// 添加一个监听
|
||||
/// </summary>
|
||||
public void AddListener<TEvent>(System.Action<IEventMessage> listener) where TEvent : IEventMessage
|
||||
{
|
||||
System.Type eventType = typeof(TEvent);
|
||||
if (_cachedListener.ContainsKey(eventType) == false)
|
||||
_cachedListener.Add(eventType, new List<Action<IEventMessage>>());
|
||||
|
||||
if (_cachedListener[eventType].Contains(listener) == false)
|
||||
{
|
||||
_cachedListener[eventType].Add(listener);
|
||||
UniEvent.AddListener(eventType, listener);
|
||||
}
|
||||
else
|
||||
{
|
||||
UniLogger.Warning($"Event listener is exist : {eventType}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 移除所有缓存的监听
|
||||
/// </summary>
|
||||
public void RemoveAllListener()
|
||||
{
|
||||
foreach (var pair in _cachedListener)
|
||||
{
|
||||
System.Type eventType = pair.Key;
|
||||
for (int i = 0; i < pair.Value.Count; i++)
|
||||
{
|
||||
UniEvent.RemoveListener(eventType, pair.Value[i]);
|
||||
}
|
||||
pair.Value.Clear();
|
||||
}
|
||||
_cachedListener.Clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: dcc5e4008d087434eb5db1390d8e4e6a
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
|
||||
namespace UniFramework.Event
|
||||
{
|
||||
public interface IEventMessage
|
||||
{
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7dcd12aabf986c6468f748911b1af65a
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Vendored
+16
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"name": "UniEvent",
|
||||
"rootNamespace": "",
|
||||
"references": [
|
||||
"GUID:e34a5702dd353724aa315fb8011f08c3"
|
||||
],
|
||||
"includePlatforms": [],
|
||||
"excludePlatforms": [],
|
||||
"allowUnsafeCode": true,
|
||||
"overrideReferences": false,
|
||||
"precompiledReferences": [],
|
||||
"autoReferenced": true,
|
||||
"defineConstraints": [],
|
||||
"versionDefines": [],
|
||||
"noEngineReferences": false
|
||||
}
|
||||
Assets/YooAsset/Samples~/Space Shooter/ThirdParty/UniFramework/UniEvent/Runtime/UniEvent.asmdef.meta
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f22fac247a56d2d41b687bb0d900e54e
|
||||
AssemblyDefinitionImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Vendored
+203
@@ -0,0 +1,203 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace UniFramework.Event
|
||||
{
|
||||
public static class UniEvent
|
||||
{
|
||||
private class PostWrapper
|
||||
{
|
||||
public int PostFrame;
|
||||
public int EventID;
|
||||
public IEventMessage Message;
|
||||
|
||||
public void OnRelease()
|
||||
{
|
||||
PostFrame = 0;
|
||||
EventID = 0;
|
||||
Message = null;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool _isInitialize = false;
|
||||
private static readonly Dictionary<int, LinkedList<Action<IEventMessage>>> _listeners = new Dictionary<int, LinkedList<Action<IEventMessage>>>(1000);
|
||||
private static readonly List<PostWrapper> _postingList = new List<PostWrapper>(1000);
|
||||
|
||||
/// <summary>
|
||||
/// 初始化事件系统
|
||||
/// </summary>
|
||||
public static void Initalize()
|
||||
{
|
||||
if (_isInitialize)
|
||||
throw new Exception($"{nameof(UniEvent)} is initialized !");
|
||||
|
||||
if (_isInitialize == false)
|
||||
{
|
||||
// 创建驱动器
|
||||
_isInitialize = true;
|
||||
GameObject driver = new UnityEngine.GameObject($"[{nameof(UniEvent)}]");
|
||||
driver.AddComponent<UniEventDriver>();
|
||||
UnityEngine.Object.DontDestroyOnLoad(driver);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更新事件系统
|
||||
/// </summary>
|
||||
internal static void Update()
|
||||
{
|
||||
for (int i = _postingList.Count - 1; i >= 0; i--)
|
||||
{
|
||||
var wrapper = _postingList[i];
|
||||
if (UnityEngine.Time.frameCount > wrapper.PostFrame)
|
||||
{
|
||||
SendMessage(wrapper.EventID, wrapper.Message);
|
||||
_postingList.RemoveAt(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 销毁事件系统
|
||||
/// </summary>
|
||||
internal static void Destroy()
|
||||
{
|
||||
if (_isInitialize)
|
||||
{
|
||||
_isInitialize = false;
|
||||
ClearAll();
|
||||
|
||||
UniLogger.Log($"{nameof(UniEvent)} destroy all !");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 清空所有监听
|
||||
/// </summary>
|
||||
public static void ClearAll()
|
||||
{
|
||||
foreach (int eventId in _listeners.Keys)
|
||||
{
|
||||
_listeners[eventId].Clear();
|
||||
}
|
||||
_listeners.Clear();
|
||||
_postingList.Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 添加监听
|
||||
/// </summary>
|
||||
public static void AddListener<TEvent>(System.Action<IEventMessage> listener) where TEvent : IEventMessage
|
||||
{
|
||||
System.Type eventType = typeof(TEvent);
|
||||
int eventId = eventType.GetHashCode();
|
||||
AddListener(eventId, listener);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 添加监听
|
||||
/// </summary>
|
||||
public static void AddListener(System.Type eventType, System.Action<IEventMessage> listener)
|
||||
{
|
||||
int eventId = eventType.GetHashCode();
|
||||
AddListener(eventId, listener);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 添加监听
|
||||
/// </summary>
|
||||
public static void AddListener(int eventId, System.Action<IEventMessage> listener)
|
||||
{
|
||||
if (_listeners.ContainsKey(eventId) == false)
|
||||
_listeners.Add(eventId, new LinkedList<Action<IEventMessage>>());
|
||||
if (_listeners[eventId].Contains(listener) == false)
|
||||
_listeners[eventId].AddLast(listener);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 移除监听
|
||||
/// </summary>
|
||||
public static void RemoveListener<TEvent>(System.Action<IEventMessage> listener) where TEvent : IEventMessage
|
||||
{
|
||||
System.Type eventType = typeof(TEvent);
|
||||
int eventId = eventType.GetHashCode();
|
||||
RemoveListener(eventId, listener);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 移除监听
|
||||
/// </summary>
|
||||
public static void RemoveListener(System.Type eventType, System.Action<IEventMessage> listener)
|
||||
{
|
||||
int eventId = eventType.GetHashCode();
|
||||
RemoveListener(eventId, listener);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 移除监听
|
||||
/// </summary>
|
||||
public static void RemoveListener(int eventId, System.Action<IEventMessage> listener)
|
||||
{
|
||||
if (_listeners.ContainsKey(eventId))
|
||||
{
|
||||
if (_listeners[eventId].Contains(listener))
|
||||
_listeners[eventId].Remove(listener);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 实时广播事件
|
||||
/// </summary>
|
||||
public static void SendMessage(IEventMessage message)
|
||||
{
|
||||
int eventId = message.GetType().GetHashCode();
|
||||
SendMessage(eventId, message);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 实时广播事件
|
||||
/// </summary>
|
||||
public static void SendMessage(int eventId, IEventMessage message)
|
||||
{
|
||||
if (_listeners.ContainsKey(eventId) == false)
|
||||
return;
|
||||
|
||||
LinkedList<Action<IEventMessage>> listeners = _listeners[eventId];
|
||||
if (listeners.Count > 0)
|
||||
{
|
||||
var currentNode = listeners.Last;
|
||||
while (currentNode != null)
|
||||
{
|
||||
currentNode.Value.Invoke(message);
|
||||
currentNode = currentNode.Previous;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 延迟广播事件
|
||||
/// </summary>
|
||||
public static void PostMessage(IEventMessage message)
|
||||
{
|
||||
int eventId = message.GetType().GetHashCode();
|
||||
PostMessage(eventId, message);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 延迟广播事件
|
||||
/// </summary>
|
||||
public static void PostMessage(int eventId, IEventMessage message)
|
||||
{
|
||||
var wrapper = new PostWrapper();
|
||||
wrapper.PostFrame = UnityEngine.Time.frameCount;
|
||||
wrapper.EventID = eventId;
|
||||
wrapper.Message = message;
|
||||
_postingList.Add(wrapper);
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a2a39e0393e22c44b8416d1445c9bb2c
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Vendored
+17
@@ -0,0 +1,17 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace UniFramework.Event
|
||||
{
|
||||
internal class UniEventDriver : MonoBehaviour
|
||||
{
|
||||
void Update()
|
||||
{
|
||||
UniEvent.Update();
|
||||
}
|
||||
|
||||
void OnDestroy()
|
||||
{
|
||||
UniEvent.Destroy();
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 91e57d06457f3ec40914e4d3ed58c070
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace UniFramework.Event
|
||||
{
|
||||
internal static class UniLogger
|
||||
{
|
||||
[Conditional("DEBUG")]
|
||||
public static void Log(string info)
|
||||
{
|
||||
UnityEngine.Debug.Log(info);
|
||||
}
|
||||
public static void Warning(string info)
|
||||
{
|
||||
UnityEngine.Debug.LogWarning(info);
|
||||
}
|
||||
public static void Error(string info)
|
||||
{
|
||||
UnityEngine.Debug.LogError(info);
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9bb2f71f321705a4286de583f1c930d7
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 16d76e3e6337b0c4cae28696d4be4c7c
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
# UniFramework.Event
|
||||
|
||||
一个轻量级的状态机。
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4c3656e4009078943b97b6dcca2c5063
|
||||
TextScriptImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 26f3a6fd3a4f2a247a53a37334fd7624
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
|
||||
namespace UniFramework.Machine
|
||||
{
|
||||
public interface IStateNode
|
||||
{
|
||||
void OnCreate(StateMachine machine);
|
||||
void OnEnter();
|
||||
void OnUpdate();
|
||||
void OnExit();
|
||||
}
|
||||
}
|
||||
Assets/YooAsset/Samples~/Space Shooter/ThirdParty/UniFramework/UniMachine/Runtime/IStateNode.cs.meta
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 19d466eecc32f6a478d64f6a78748b23
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Vendored
+142
@@ -0,0 +1,142 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace UniFramework.Machine
|
||||
{
|
||||
public class StateMachine
|
||||
{
|
||||
private readonly Dictionary<string, IStateNode> _nodes = new Dictionary<string, IStateNode>(100);
|
||||
private IStateNode _curNode;
|
||||
private IStateNode _preNode;
|
||||
|
||||
/// <summary>
|
||||
/// 状态机持有者
|
||||
/// </summary>
|
||||
public System.Object Owner { private set; get; }
|
||||
|
||||
/// <summary>
|
||||
/// 当前运行的节点名称
|
||||
/// </summary>
|
||||
public string CurrentNode
|
||||
{
|
||||
get { return _curNode != null ? _curNode.GetType().FullName : string.Empty; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 之前运行的节点名称
|
||||
/// </summary>
|
||||
public string PreviousNode
|
||||
{
|
||||
get { return _preNode != null ? _preNode.GetType().FullName : string.Empty; }
|
||||
}
|
||||
|
||||
|
||||
private StateMachine() { }
|
||||
public StateMachine(System.Object owner)
|
||||
{
|
||||
Owner = owner;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更新状态机
|
||||
/// </summary>
|
||||
public void Update()
|
||||
{
|
||||
if (_curNode != null)
|
||||
_curNode.OnUpdate();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 启动状态机
|
||||
/// </summary>
|
||||
public void Run<TNode>() where TNode : IStateNode
|
||||
{
|
||||
var nodeType = typeof(TNode);
|
||||
var nodeName = nodeType.FullName;
|
||||
Run(nodeName);
|
||||
}
|
||||
public void Run(Type entryNode)
|
||||
{
|
||||
var nodeName = entryNode.FullName;
|
||||
Run(nodeName);
|
||||
}
|
||||
public void Run(string entryNode)
|
||||
{
|
||||
_curNode = TryGetNode(entryNode);
|
||||
_preNode = _curNode;
|
||||
|
||||
if (_curNode == null)
|
||||
throw new Exception($"Not found entry node: {entryNode }");
|
||||
|
||||
_curNode.OnEnter();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 加入一个节点
|
||||
/// </summary>
|
||||
public void AddNode<TNode>() where TNode : IStateNode
|
||||
{
|
||||
var nodeType = typeof(TNode);
|
||||
var stateNode = Activator.CreateInstance(nodeType) as IStateNode;
|
||||
AddNode(stateNode);
|
||||
}
|
||||
public void AddNode(IStateNode stateNode)
|
||||
{
|
||||
if (stateNode == null)
|
||||
throw new ArgumentNullException();
|
||||
|
||||
var nodeType = stateNode.GetType();
|
||||
var nodeName = nodeType.FullName;
|
||||
|
||||
if (_nodes.ContainsKey(nodeName) == false)
|
||||
{
|
||||
stateNode.OnCreate(this);
|
||||
_nodes.Add(nodeName, stateNode);
|
||||
}
|
||||
else
|
||||
{
|
||||
UniLogger.Error($"State node already existed : {nodeName}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 转换状态节点
|
||||
/// </summary>
|
||||
public void ChangeState<TNode>() where TNode : IStateNode
|
||||
{
|
||||
var nodeType = typeof(TNode);
|
||||
var nodeName = nodeType.FullName;
|
||||
ChangeState(nodeName);
|
||||
}
|
||||
public void ChangeState(Type nodeType)
|
||||
{
|
||||
var nodeName = nodeType.FullName;
|
||||
ChangeState(nodeName);
|
||||
}
|
||||
public void ChangeState(string nodeName)
|
||||
{
|
||||
if (string.IsNullOrEmpty(nodeName))
|
||||
throw new ArgumentNullException();
|
||||
|
||||
IStateNode node = TryGetNode(nodeName);
|
||||
if (node == null)
|
||||
{
|
||||
UniLogger.Error($"Can not found state node : {nodeName}");
|
||||
return;
|
||||
}
|
||||
|
||||
UniLogger.Log($"{_curNode.GetType().FullName} --> {node.GetType().FullName}");
|
||||
_preNode = _curNode;
|
||||
_curNode.OnExit();
|
||||
_curNode = node;
|
||||
_curNode.OnEnter();
|
||||
}
|
||||
|
||||
private IStateNode TryGetNode(string nodeName)
|
||||
{
|
||||
_nodes.TryGetValue(nodeName, out IStateNode result);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5999045dd15678e4bbaca21f460ea0e6
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace UniFramework.Machine
|
||||
{
|
||||
internal static class UniLogger
|
||||
{
|
||||
[Conditional("DEBUG")]
|
||||
public static void Log(string info)
|
||||
{
|
||||
UnityEngine.Debug.Log(info);
|
||||
}
|
||||
public static void Warning(string info)
|
||||
{
|
||||
UnityEngine.Debug.LogWarning(info);
|
||||
}
|
||||
public static void Error(string info)
|
||||
{
|
||||
UnityEngine.Debug.LogError(info);
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: db25e4def3ffb6b468dd46b2a6fe1245
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Vendored
+16
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"name": "UniMachine",
|
||||
"rootNamespace": "",
|
||||
"references": [
|
||||
"GUID:e34a5702dd353724aa315fb8011f08c3"
|
||||
],
|
||||
"includePlatforms": [],
|
||||
"excludePlatforms": [],
|
||||
"allowUnsafeCode": true,
|
||||
"overrideReferences": false,
|
||||
"precompiledReferences": [],
|
||||
"autoReferenced": true,
|
||||
"defineConstraints": [],
|
||||
"versionDefines": [],
|
||||
"noEngineReferences": false
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: c55575a9f1747c240822f4b7e0400716
|
||||
AssemblyDefinitionImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4e57ebf0b48a9d94dba1c0ce723da392
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
# UniFramework.Module
|
||||
|
||||
一个轻量级的模块系统。
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 496f400bdfe0c6c46809be47d2a45b37
|
||||
TextScriptImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: aef3e45fdde94b245841e6e62655912f
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
|
||||
namespace UniFramework.Module
|
||||
{
|
||||
public interface IModule
|
||||
{
|
||||
/// <summary>
|
||||
/// 创建模块
|
||||
/// </summary>
|
||||
void OnCreate(System.Object createParam);
|
||||
|
||||
/// <summary>
|
||||
/// 更新模块
|
||||
/// </summary>
|
||||
void OnUpdate();
|
||||
|
||||
/// <summary>
|
||||
/// 销毁模块
|
||||
/// </summary>
|
||||
void OnDestroy();
|
||||
}
|
||||
}
|
||||
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4f4757101f8553d49ad6da27c94c50c5
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Vendored
+28
@@ -0,0 +1,28 @@
|
||||
|
||||
namespace UniFramework.Module
|
||||
{
|
||||
public abstract class ModuleSingleton<T> where T : class, IModule
|
||||
{
|
||||
private static T _instance;
|
||||
public static T Instance
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_instance == null)
|
||||
UniLogger.Error($"{typeof(T)} is not create. Use {nameof(UniModule)}.{nameof(UniModule.CreateModule)} create.");
|
||||
return _instance;
|
||||
}
|
||||
}
|
||||
|
||||
protected ModuleSingleton()
|
||||
{
|
||||
if (_instance != null)
|
||||
throw new System.Exception($"{typeof(T)} instance already created.");
|
||||
_instance = this as T;
|
||||
}
|
||||
protected void DestroySingleton()
|
||||
{
|
||||
_instance = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b6c8230c0d097534e950f4e84ce01e96
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace UniFramework.Module
|
||||
{
|
||||
internal static class UniLogger
|
||||
{
|
||||
[Conditional("DEBUG")]
|
||||
public static void Log(string info)
|
||||
{
|
||||
UnityEngine.Debug.Log(info);
|
||||
}
|
||||
public static void Warning(string info)
|
||||
{
|
||||
UnityEngine.Debug.LogWarning(info);
|
||||
}
|
||||
public static void Error(string info)
|
||||
{
|
||||
UnityEngine.Debug.LogError(info);
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b2a99934c26e0304cb6292b0c40ae684
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Vendored
+16
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"name": "UniModule",
|
||||
"rootNamespace": "",
|
||||
"references": [
|
||||
"GUID:e34a5702dd353724aa315fb8011f08c3"
|
||||
],
|
||||
"includePlatforms": [],
|
||||
"excludePlatforms": [],
|
||||
"allowUnsafeCode": true,
|
||||
"overrideReferences": false,
|
||||
"precompiledReferences": [],
|
||||
"autoReferenced": true,
|
||||
"defineConstraints": [],
|
||||
"versionDefines": [],
|
||||
"noEngineReferences": false
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b35e33884f6755d43b7e0511e88956d0
|
||||
AssemblyDefinitionImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Vendored
+222
@@ -0,0 +1,222 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace UniFramework.Module
|
||||
{
|
||||
public static class UniModule
|
||||
{
|
||||
private class Wrapper
|
||||
{
|
||||
public int Priority { private set; get; }
|
||||
public IModule Module { private set; get; }
|
||||
|
||||
public Wrapper(IModule module, int priority)
|
||||
{
|
||||
Module = module;
|
||||
Priority = priority;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool _isInitialize = false;
|
||||
private static readonly List<Wrapper> _wrappers = new List<Wrapper>(100);
|
||||
private static MonoBehaviour _behaviour;
|
||||
private static bool _isDirty = false;
|
||||
|
||||
/// <summary>
|
||||
/// 初始化模块系统
|
||||
/// </summary>
|
||||
public static void Initialize()
|
||||
{
|
||||
if (_isInitialize)
|
||||
throw new Exception($"{nameof(UniModule)} is initialized !");
|
||||
|
||||
if (_isInitialize == false)
|
||||
{
|
||||
// 创建驱动器
|
||||
_isInitialize = true;
|
||||
GameObject driver = new UnityEngine.GameObject($"[{nameof(UniModule)}]");
|
||||
_behaviour = driver.AddComponent<UniModuleDriver>();
|
||||
UnityEngine.Object.DontDestroyOnLoad(driver);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更新模块系统
|
||||
/// </summary>
|
||||
internal static void Update()
|
||||
{
|
||||
// 如果需要重新排序
|
||||
if (_isDirty)
|
||||
{
|
||||
_isDirty = false;
|
||||
_wrappers.Sort((left, right) =>
|
||||
{
|
||||
if (left.Priority > right.Priority)
|
||||
return -1;
|
||||
else if (left.Priority == right.Priority)
|
||||
return 0;
|
||||
else
|
||||
return 1;
|
||||
});
|
||||
}
|
||||
|
||||
// 轮询所有模块
|
||||
for (int i = 0; i < _wrappers.Count; i++)
|
||||
{
|
||||
_wrappers[i].Module.OnUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 销毁模块系统
|
||||
/// </summary>
|
||||
internal static void Destroy()
|
||||
{
|
||||
if (_isInitialize)
|
||||
{
|
||||
_isInitialize = false;
|
||||
DestroyAll();
|
||||
|
||||
UniLogger.Log($"{nameof(UniModule)} destroy all !");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取模块
|
||||
/// </summary>
|
||||
public static T GetModule<T>() where T : class, IModule
|
||||
{
|
||||
System.Type type = typeof(T);
|
||||
for (int i = 0; i < _wrappers.Count; i++)
|
||||
{
|
||||
if (_wrappers[i].Module.GetType() == type)
|
||||
return _wrappers[i].Module as T;
|
||||
}
|
||||
|
||||
UniLogger.Error($"Not found manager : {type}");
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查询模块是否存在
|
||||
/// </summary>
|
||||
public static bool Contains<T>() where T : class, IModule
|
||||
{
|
||||
System.Type type = typeof(T);
|
||||
for (int i = 0; i < _wrappers.Count; i++)
|
||||
{
|
||||
if (_wrappers[i].Module.GetType() == type)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建模块
|
||||
/// </summary>
|
||||
/// <param name="priority">运行时的优先级,优先级越大越早执行。如果没有设置优先级,那么会按照添加顺序执行</param>
|
||||
public static T CreateModule<T>(int priority = 0) where T : class, IModule
|
||||
{
|
||||
return CreateModule<T>(null, priority);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建模块
|
||||
/// </summary>
|
||||
/// <param name="createParam">附加参数</param>
|
||||
/// <param name="priority">运行时的优先级,优先级越大越早执行。如果没有设置优先级,那么会按照添加顺序执行</param>
|
||||
public static T CreateModule<T>(System.Object createParam, int priority = 0) where T : class, IModule
|
||||
{
|
||||
if (priority < 0)
|
||||
throw new Exception("The priority can not be negative");
|
||||
|
||||
if (Contains<T>())
|
||||
throw new Exception($"Module is already existed : {typeof(T)}");
|
||||
|
||||
// 如果没有设置优先级
|
||||
if (priority == 0)
|
||||
{
|
||||
int minPriority = GetMinPriority();
|
||||
priority = --minPriority;
|
||||
}
|
||||
|
||||
T module = Activator.CreateInstance<T>();
|
||||
Wrapper wrapper = new Wrapper(module, priority);
|
||||
wrapper.Module.OnCreate(createParam);
|
||||
_wrappers.Add(wrapper);
|
||||
_isDirty = true;
|
||||
return module;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 销毁模块
|
||||
/// </summary>
|
||||
public static bool DestroyModule<T>() where T : class, IModule
|
||||
{
|
||||
var type = typeof(T);
|
||||
for (int i = 0; i < _wrappers.Count; i++)
|
||||
{
|
||||
if (_wrappers[i].Module.GetType() == type)
|
||||
{
|
||||
_wrappers[i].Module.OnDestroy();
|
||||
_wrappers.RemoveAt(i);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 开启一个协程
|
||||
/// </summary>
|
||||
public static Coroutine StartCoroutine(IEnumerator coroutine)
|
||||
{
|
||||
return _behaviour.StartCoroutine(coroutine);
|
||||
}
|
||||
public static Coroutine StartCoroutine(string methodName)
|
||||
{
|
||||
return _behaviour.StartCoroutine(methodName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 停止一个协程
|
||||
/// </summary>
|
||||
public static void StopCoroutine(Coroutine coroutine)
|
||||
{
|
||||
_behaviour.StopCoroutine(coroutine);
|
||||
}
|
||||
public static void StopCoroutine(string methodName)
|
||||
{
|
||||
_behaviour.StopCoroutine(methodName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 停止所有协程
|
||||
/// </summary>
|
||||
public static void StopAllCoroutines()
|
||||
{
|
||||
_behaviour.StopAllCoroutines();
|
||||
}
|
||||
|
||||
private static int GetMinPriority()
|
||||
{
|
||||
int minPriority = 0;
|
||||
for (int i = 0; i < _wrappers.Count; i++)
|
||||
{
|
||||
if (_wrappers[i].Priority < minPriority)
|
||||
minPriority = _wrappers[i].Priority;
|
||||
}
|
||||
return minPriority; //小于等于零
|
||||
}
|
||||
private static void DestroyAll()
|
||||
{
|
||||
for (int i = 0; i < _wrappers.Count; i++)
|
||||
{
|
||||
_wrappers[i].Module.OnDestroy();
|
||||
}
|
||||
_wrappers.Clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b799b83d73a9cb543b2504ccb1cf796a
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Vendored
+17
@@ -0,0 +1,17 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace UniFramework.Module
|
||||
{
|
||||
internal class UniModuleDriver : MonoBehaviour
|
||||
{
|
||||
void Update()
|
||||
{
|
||||
UniModule.Update();
|
||||
}
|
||||
|
||||
void OnDestroy()
|
||||
{
|
||||
UniModule.Destroy();
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f0b2648cd533049449e1e81d215afbd7
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7cfeaa68459d1cb4f96e62f6b7bd9fd7
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
# UniFramework.Pooling
|
||||
|
||||
一个功能强大的游戏对象池系统。
|
||||
|
||||
该系统依赖于YooAsset资源系统,支持各类异步编程,支持同步接口和异步接口。
|
||||
|
||||
```c#
|
||||
using UnityEngine;
|
||||
using YooAsset;
|
||||
using UniFramework.Pooling;
|
||||
|
||||
IEnumerator Start()
|
||||
{
|
||||
// 初始化游戏对象池系统
|
||||
UniPooling.Initalize();
|
||||
|
||||
// 创建孵化器
|
||||
var spawner = UniPooling.CreateSpawner("DefaultPackage");
|
||||
|
||||
// 创建Cube预制体的对象池
|
||||
var operation = spawner.CreateGameObjectPoolAsync("Cube.prefab");
|
||||
yield return operation;
|
||||
|
||||
// 孵化Cube游戏对象
|
||||
SpawnHandle handle = spawner.SpawnAsync("Cube.prefab");
|
||||
yield return handle;
|
||||
Debug.Log(handle.GameObj.name);
|
||||
|
||||
// 回收游戏对象
|
||||
handle.Restore();
|
||||
|
||||
// 丢弃游戏对象
|
||||
handle.Discard();
|
||||
}
|
||||
```
|
||||
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7976cbcaa4dcfcc4b932fb01d6c0499a
|
||||
TextScriptImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5904699460a22064182a5cf9129fc09e
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
using YooAsset;
|
||||
|
||||
namespace UniFramework.Pooling
|
||||
{
|
||||
public class CreatePoolOperation : GameAsyncOperation
|
||||
{
|
||||
private enum ESteps
|
||||
{
|
||||
None,
|
||||
Waiting,
|
||||
Done,
|
||||
}
|
||||
|
||||
private readonly AssetOperationHandle _handle;
|
||||
private ESteps _steps = ESteps.None;
|
||||
|
||||
internal CreatePoolOperation(AssetOperationHandle handle)
|
||||
{
|
||||
_handle = handle;
|
||||
}
|
||||
protected override void OnStart()
|
||||
{
|
||||
_steps = ESteps.Waiting;
|
||||
}
|
||||
protected override void OnUpdate()
|
||||
{
|
||||
if (_steps == ESteps.None || _steps == ESteps.Done)
|
||||
return;
|
||||
|
||||
if (_steps == ESteps.Waiting)
|
||||
{
|
||||
if (_handle.IsValid == false)
|
||||
{
|
||||
_steps = ESteps.Done;
|
||||
Status = EOperationStatus.Failed;
|
||||
Error = $"{nameof(AssetOperationHandle)} is invalid.";
|
||||
return;
|
||||
}
|
||||
|
||||
if (_handle.IsDone == false)
|
||||
return;
|
||||
|
||||
if (_handle.AssetObject == null)
|
||||
{
|
||||
_steps = ESteps.Done;
|
||||
Status = EOperationStatus.Failed;
|
||||
Error = $"{nameof(AssetOperationHandle.AssetObject)} is null.";
|
||||
return;
|
||||
}
|
||||
|
||||
_steps = ESteps.Done;
|
||||
Status = EOperationStatus.Succeed;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 等待异步实例化结束
|
||||
/// </summary>
|
||||
public void WaitForAsyncComplete()
|
||||
{
|
||||
if (_handle != null)
|
||||
{
|
||||
if (_steps == ESteps.Done)
|
||||
return;
|
||||
_handle.WaitForAsyncComplete();
|
||||
OnUpdate();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a5687620a17f42e4085a0e2243be7561
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Vendored
+215
@@ -0,0 +1,215 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using YooAsset;
|
||||
|
||||
namespace UniFramework.Pooling
|
||||
{
|
||||
internal class GameObjectPool
|
||||
{
|
||||
private readonly Transform _poolRoot;
|
||||
private readonly Queue<InstantiateOperation> _cacheOperations;
|
||||
private readonly bool _dontDestroy;
|
||||
private readonly int _initCapacity;
|
||||
private readonly int _maxCapacity;
|
||||
private readonly float _destroyTime;
|
||||
private float _lastRestoreRealTime = -1f;
|
||||
|
||||
/// <summary>
|
||||
/// 资源句柄
|
||||
/// </summary>
|
||||
public AssetOperationHandle AssetHandle { private set; get; }
|
||||
|
||||
/// <summary>
|
||||
/// 资源定位地址
|
||||
/// </summary>
|
||||
public string Location { private set; get; }
|
||||
|
||||
/// <summary>
|
||||
/// 内部缓存总数
|
||||
/// </summary>
|
||||
public int CacheCount
|
||||
{
|
||||
get { return _cacheOperations.Count; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 外部使用总数
|
||||
/// </summary>
|
||||
public int SpawnCount { private set; get; } = 0;
|
||||
|
||||
/// <summary>
|
||||
/// 是否常驻不销毁
|
||||
/// </summary>
|
||||
public bool DontDestroy
|
||||
{
|
||||
get { return _dontDestroy; }
|
||||
}
|
||||
|
||||
|
||||
public GameObjectPool(GameObject poolRoot, string location, bool dontDestroy, int initCapacity, int maxCapacity, float destroyTime)
|
||||
{
|
||||
_poolRoot = poolRoot.transform;
|
||||
Location = location;
|
||||
|
||||
_dontDestroy = dontDestroy;
|
||||
_initCapacity = initCapacity;
|
||||
_maxCapacity = maxCapacity;
|
||||
_destroyTime = destroyTime;
|
||||
|
||||
// 创建缓存池
|
||||
_cacheOperations = new Queue<InstantiateOperation>(initCapacity);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建对象池
|
||||
/// </summary>
|
||||
public void CreatePool(AssetsPackage assetPackage)
|
||||
{
|
||||
// 加载游戏对象
|
||||
AssetHandle = assetPackage.LoadAssetAsync<GameObject>(Location);
|
||||
|
||||
// 创建初始对象
|
||||
for (int i = 0; i < _initCapacity; i++)
|
||||
{
|
||||
var operation = AssetHandle.InstantiateAsync(_poolRoot);
|
||||
_cacheOperations.Enqueue(operation);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 销毁游戏对象池
|
||||
/// </summary>
|
||||
public void DestroyPool()
|
||||
{
|
||||
// 卸载资源对象
|
||||
AssetHandle.Release();
|
||||
AssetHandle = null;
|
||||
|
||||
// 销毁游戏对象
|
||||
foreach (var operation in _cacheOperations)
|
||||
{
|
||||
if (operation.Result != null)
|
||||
GameObject.Destroy(operation.Result);
|
||||
}
|
||||
_cacheOperations.Clear();
|
||||
|
||||
SpawnCount = 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查询静默时间内是否可以销毁
|
||||
/// </summary>
|
||||
public bool CanAutoDestroy()
|
||||
{
|
||||
if (_dontDestroy)
|
||||
return false;
|
||||
if (_destroyTime < 0)
|
||||
return false;
|
||||
|
||||
if (_lastRestoreRealTime > 0 && SpawnCount <= 0)
|
||||
return (Time.realtimeSinceStartup - _lastRestoreRealTime) > _destroyTime;
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 游戏对象池是否已经销毁
|
||||
/// </summary>
|
||||
public bool IsDestroyed()
|
||||
{
|
||||
return AssetHandle == null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 回收
|
||||
/// </summary>
|
||||
public void Restore(InstantiateOperation operation)
|
||||
{
|
||||
if (IsDestroyed())
|
||||
{
|
||||
DestroyInstantiateOperation(operation);
|
||||
return;
|
||||
}
|
||||
|
||||
SpawnCount--;
|
||||
if (SpawnCount <= 0)
|
||||
_lastRestoreRealTime = Time.realtimeSinceStartup;
|
||||
|
||||
// 如果外部逻辑销毁了游戏对象
|
||||
if (operation.Status == EOperationStatus.Succeed)
|
||||
{
|
||||
if (operation.Result == null)
|
||||
return;
|
||||
}
|
||||
|
||||
// 如果缓存池还未满员
|
||||
if (_cacheOperations.Count < _maxCapacity)
|
||||
{
|
||||
SetRestoreGameObject(operation.Result);
|
||||
_cacheOperations.Enqueue(operation);
|
||||
}
|
||||
else
|
||||
{
|
||||
DestroyInstantiateOperation(operation);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 丢弃
|
||||
/// </summary>
|
||||
public void Discard(InstantiateOperation operation)
|
||||
{
|
||||
if (IsDestroyed())
|
||||
{
|
||||
DestroyInstantiateOperation(operation);
|
||||
return;
|
||||
}
|
||||
|
||||
SpawnCount--;
|
||||
if (SpawnCount <= 0)
|
||||
_lastRestoreRealTime = Time.realtimeSinceStartup;
|
||||
|
||||
DestroyInstantiateOperation(operation);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取一个游戏对象
|
||||
/// </summary>
|
||||
public SpawnHandle Spawn(Transform parent, Vector3 position, Quaternion rotation, bool forceClone, params System.Object[] userDatas)
|
||||
{
|
||||
InstantiateOperation operation;
|
||||
if (forceClone == false && _cacheOperations.Count > 0)
|
||||
operation = _cacheOperations.Dequeue();
|
||||
else
|
||||
operation = AssetHandle.InstantiateAsync();
|
||||
|
||||
SpawnCount++;
|
||||
SpawnHandle handle = new SpawnHandle(this, operation, parent, position, rotation, userDatas);
|
||||
YooAssets.StartOperation(handle);
|
||||
return handle;
|
||||
}
|
||||
|
||||
private void DestroyInstantiateOperation(InstantiateOperation operation)
|
||||
{
|
||||
// 取消异步操作
|
||||
operation.Cancel();
|
||||
|
||||
// 销毁游戏对象
|
||||
if (operation.Result != null)
|
||||
{
|
||||
GameObject.Destroy(operation.Result);
|
||||
}
|
||||
}
|
||||
private void SetRestoreGameObject(GameObject gameObj)
|
||||
{
|
||||
if (gameObj != null)
|
||||
{
|
||||
gameObj.SetActive(false);
|
||||
gameObj.transform.SetParent(_poolRoot);
|
||||
gameObj.transform.SetPositionAndRotation(Vector3.zero, Quaternion.identity);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 1dd976626eb4ca645b4ec80921f4e8fd
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Vendored
+148
@@ -0,0 +1,148 @@
|
||||
using UnityEngine;
|
||||
using YooAsset;
|
||||
|
||||
namespace UniFramework.Pooling
|
||||
{
|
||||
public sealed class SpawnHandle : GameAsyncOperation
|
||||
{
|
||||
private enum ESteps
|
||||
{
|
||||
None,
|
||||
Waiting,
|
||||
Done,
|
||||
}
|
||||
|
||||
private readonly GameObjectPool _pool;
|
||||
private InstantiateOperation _operation;
|
||||
private readonly Transform _parent;
|
||||
private readonly Vector3 _position;
|
||||
private readonly Quaternion _rotation;
|
||||
private ESteps _steps = ESteps.None;
|
||||
|
||||
/// <summary>
|
||||
/// 实例化的游戏对象
|
||||
/// </summary>
|
||||
public GameObject GameObj
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_operation == null)
|
||||
{
|
||||
UniLogger.Warning("The spawn handle is invalid !");
|
||||
return null;
|
||||
}
|
||||
|
||||
return _operation.Result;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 用户自定义数据集
|
||||
/// </summary>
|
||||
public System.Object[] UserDatas { private set; get; }
|
||||
|
||||
private SpawnHandle()
|
||||
{
|
||||
}
|
||||
internal SpawnHandle(GameObjectPool pool, InstantiateOperation operation, Transform parent, Vector3 position, Quaternion rotation, params System.Object[] userDatas)
|
||||
{
|
||||
_pool = pool;
|
||||
_operation = operation;
|
||||
_parent = parent;
|
||||
_position = position;
|
||||
_rotation = rotation;
|
||||
UserDatas = userDatas;
|
||||
}
|
||||
protected override void OnStart()
|
||||
{
|
||||
_steps = ESteps.Waiting;
|
||||
}
|
||||
protected override void OnUpdate()
|
||||
{
|
||||
if (_steps == ESteps.None || _steps == ESteps.Done)
|
||||
return;
|
||||
|
||||
if (_steps == ESteps.Waiting)
|
||||
{
|
||||
if (_operation.IsDone == false)
|
||||
return;
|
||||
|
||||
if (_operation.Status != EOperationStatus.Succeed)
|
||||
{
|
||||
_steps = ESteps.Done;
|
||||
Status = EOperationStatus.Failed;
|
||||
Error = _operation.Error;
|
||||
return;
|
||||
}
|
||||
|
||||
if (_operation.Result == null)
|
||||
{
|
||||
_steps = ESteps.Done;
|
||||
Status = EOperationStatus.Failed;
|
||||
Error = $"Clone game object is null.";
|
||||
return;
|
||||
}
|
||||
|
||||
// 设置参数
|
||||
_operation.Result.transform.SetParent(_parent);
|
||||
_operation.Result.transform.SetPositionAndRotation(_position, _rotation);
|
||||
_operation.Result.SetActive(true);
|
||||
|
||||
_steps = ESteps.Done;
|
||||
Status = EOperationStatus.Succeed;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 回收
|
||||
/// </summary>
|
||||
public void Restore()
|
||||
{
|
||||
if (_operation != null)
|
||||
{
|
||||
ClearCompletedCallback();
|
||||
CancelHandle();
|
||||
_pool.Restore(_operation);
|
||||
_operation = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 丢弃
|
||||
/// </summary>
|
||||
public void Discard()
|
||||
{
|
||||
if (_operation != null)
|
||||
{
|
||||
ClearCompletedCallback();
|
||||
CancelHandle();
|
||||
_pool.Discard(_operation);
|
||||
_operation = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 等待异步实例化结束
|
||||
/// </summary>
|
||||
public void WaitForAsyncComplete()
|
||||
{
|
||||
if (_operation != null)
|
||||
{
|
||||
if (_steps == ESteps.Done)
|
||||
return;
|
||||
_operation.WaitForAsyncComplete();
|
||||
OnUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
private void CancelHandle()
|
||||
{
|
||||
if (IsDone == false)
|
||||
{
|
||||
_steps = ESteps.Done;
|
||||
Status = EOperationStatus.Failed;
|
||||
Error = $"User cancelled !";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6350d2984a149b349b9cec658d21b12a
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Vendored
+259
@@ -0,0 +1,259 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using YooAsset;
|
||||
|
||||
namespace UniFramework.Pooling
|
||||
{
|
||||
public class Spawner
|
||||
{
|
||||
private readonly List<GameObjectPool> _gameObjectPools = new List<GameObjectPool>(100);
|
||||
private readonly List<GameObjectPool> _removeList = new List<GameObjectPool>(100);
|
||||
private readonly GameObject _spawnerRoot;
|
||||
private readonly AssetsPackage _assetPackage;
|
||||
|
||||
public string PackageName
|
||||
{
|
||||
get
|
||||
{
|
||||
return _assetPackage.PackageName;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private Spawner()
|
||||
{
|
||||
}
|
||||
internal Spawner(GameObject poolingRoot, AssetsPackage assetPackage)
|
||||
{
|
||||
_spawnerRoot = new GameObject($"{assetPackage.PackageName}");
|
||||
_spawnerRoot.transform.SetParent(poolingRoot.transform);
|
||||
_assetPackage = assetPackage;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更新游戏对象池系统
|
||||
/// </summary>
|
||||
internal void Update()
|
||||
{
|
||||
_removeList.Clear();
|
||||
foreach (var pool in _gameObjectPools)
|
||||
{
|
||||
if (pool.CanAutoDestroy())
|
||||
_removeList.Add(pool);
|
||||
}
|
||||
|
||||
foreach (var pool in _removeList)
|
||||
{
|
||||
_gameObjectPools.Remove(pool);
|
||||
pool.DestroyPool();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 销毁游戏对象池系统
|
||||
/// </summary>
|
||||
internal void Destroy()
|
||||
{
|
||||
DestroyAll(true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 销毁所有对象池及其资源
|
||||
/// </summary>
|
||||
/// <param name="includeAll">销毁所有对象池,包括常驻对象池</param>
|
||||
public void DestroyAll(bool includeAll)
|
||||
{
|
||||
if (includeAll)
|
||||
{
|
||||
foreach (var pool in _gameObjectPools)
|
||||
{
|
||||
pool.DestroyPool();
|
||||
}
|
||||
_gameObjectPools.Clear();
|
||||
}
|
||||
else
|
||||
{
|
||||
List<GameObjectPool> removeList = new List<GameObjectPool>();
|
||||
foreach (var pool in _gameObjectPools)
|
||||
{
|
||||
if (pool.DontDestroy == false)
|
||||
removeList.Add(pool);
|
||||
}
|
||||
foreach (var pool in removeList)
|
||||
{
|
||||
_gameObjectPools.Remove(pool);
|
||||
pool.DestroyPool();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 异步创建指定资源的游戏对象池
|
||||
/// </summary>
|
||||
/// <param name="location">资源定位地址</param>
|
||||
/// <param name="dontDestroy">资源常驻不销毁</param>
|
||||
/// <param name="initCapacity">对象池的初始容量</param>
|
||||
/// <param name="maxCapacity">对象池的最大容量</param>
|
||||
/// <param name="destroyTime">静默销毁时间(注意:小于零代表不主动销毁)</param>
|
||||
public CreatePoolOperation CreateGameObjectPoolAsync(string location, bool dontDestroy = false, int initCapacity = 0, int maxCapacity = int.MaxValue, float destroyTime = -1f)
|
||||
{
|
||||
return CreateGameObjectPoolInternal(location, dontDestroy, initCapacity, maxCapacity, destroyTime);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 同步创建指定资源的游戏对象池
|
||||
/// </summary>
|
||||
/// <param name="location">资源定位地址</param>
|
||||
/// <param name="dontDestroy">资源常驻不销毁</param>
|
||||
/// <param name="initCapacity">对象池的初始容量</param>
|
||||
/// <param name="maxCapacity">对象池的最大容量</param>
|
||||
/// <param name="destroyTime">静默销毁时间(注意:小于零代表不主动销毁)</param>
|
||||
public CreatePoolOperation CreateGameObjectPoolSync(string location, bool dontDestroy = false, int initCapacity = 0, int maxCapacity = int.MaxValue, float destroyTime = -1f)
|
||||
{
|
||||
var operation = CreateGameObjectPoolInternal(location, dontDestroy, initCapacity, maxCapacity, destroyTime);
|
||||
operation.WaitForAsyncComplete();
|
||||
return operation;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建指定资源的游戏对象池
|
||||
/// </summary>
|
||||
private CreatePoolOperation CreateGameObjectPoolInternal(string location, bool dontDestroy = false, int initCapacity = 0, int maxCapacity = int.MaxValue, float destroyTime = -1f)
|
||||
{
|
||||
if (maxCapacity < initCapacity)
|
||||
throw new Exception("The max capacity value must be greater the init capacity value.");
|
||||
|
||||
GameObjectPool pool = TryGetGameObjectPool(location);
|
||||
if (pool != null)
|
||||
{
|
||||
UniLogger.Warning($"GameObject pool is already existed : {location}");
|
||||
var operation = new CreatePoolOperation(pool.AssetHandle);
|
||||
YooAssets.StartOperation(operation);
|
||||
return operation;
|
||||
}
|
||||
else
|
||||
{
|
||||
pool = new GameObjectPool(_spawnerRoot, location, dontDestroy, initCapacity, maxCapacity, destroyTime);
|
||||
pool.CreatePool(_assetPackage);
|
||||
_gameObjectPools.Add(pool);
|
||||
|
||||
var operation = new CreatePoolOperation(pool.AssetHandle);
|
||||
YooAssets.StartOperation(operation);
|
||||
return operation;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 异步实例化一个游戏对象
|
||||
/// </summary>
|
||||
/// <param name="location">资源定位地址</param>
|
||||
/// <param name="forceClone">强制克隆游戏对象,忽略缓存池里的对象</param>
|
||||
/// <param name="userDatas">用户自定义数据</param>
|
||||
public SpawnHandle SpawnAsync(string location, bool forceClone = false, params System.Object[] userDatas)
|
||||
{
|
||||
return SpawnInternal(location, null, Vector3.zero, Quaternion.identity, forceClone, userDatas);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 异步实例化一个游戏对象
|
||||
/// </summary>
|
||||
/// <param name="location">资源定位地址</param>
|
||||
/// <param name="parent">父物体</param>
|
||||
/// <param name="forceClone">强制克隆游戏对象,忽略缓存池里的对象</param>
|
||||
/// <param name="userDatas">用户自定义数据</param>
|
||||
public SpawnHandle SpawnAsync(string location, Transform parent, bool forceClone = false, params System.Object[] userDatas)
|
||||
{
|
||||
return SpawnInternal(location, parent, Vector3.zero, Quaternion.identity, forceClone, userDatas);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 异步实例化一个游戏对象
|
||||
/// </summary>
|
||||
/// <param name="location">资源定位地址</param>
|
||||
/// <param name="parent">父物体</param>
|
||||
/// <param name="position">世界坐标</param>
|
||||
/// <param name="rotation">世界角度</param>
|
||||
/// <param name="forceClone">强制克隆游戏对象,忽略缓存池里的对象</param>
|
||||
/// <param name="userDatas">用户自定义数据</param>
|
||||
public SpawnHandle SpawnAsync(string location, Transform parent, Vector3 position, Quaternion rotation, bool forceClone = false, params System.Object[] userDatas)
|
||||
{
|
||||
return SpawnInternal(location, parent, position, rotation, forceClone, userDatas);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 同步实例化一个游戏对象
|
||||
/// </summary>
|
||||
/// <param name="location">资源定位地址</param>
|
||||
/// <param name="forceClone">强制克隆游戏对象,忽略缓存池里的对象</param>
|
||||
/// <param name="userDatas">用户自定义数据</param>
|
||||
public SpawnHandle SpawnSync(string location, bool forceClone = false, params System.Object[] userDatas)
|
||||
{
|
||||
SpawnHandle handle = SpawnInternal(location, null, Vector3.zero, Quaternion.identity, forceClone, userDatas);
|
||||
handle.WaitForAsyncComplete();
|
||||
return handle;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 同步实例化一个游戏对象
|
||||
/// </summary>
|
||||
/// <param name="location">资源定位地址</param>
|
||||
/// <param name="parent">父物体</param>
|
||||
/// <param name="forceClone">强制克隆游戏对象,忽略缓存池里的对象</param>
|
||||
/// <param name="userDatas">用户自定义数据</param>
|
||||
public SpawnHandle SpawnSync(string location, Transform parent, bool forceClone = false, params System.Object[] userDatas)
|
||||
{
|
||||
SpawnHandle handle = SpawnInternal(location, parent, Vector3.zero, Quaternion.identity, forceClone, userDatas);
|
||||
handle.WaitForAsyncComplete();
|
||||
return handle;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 同步实例化一个游戏对象
|
||||
/// </summary>
|
||||
/// <param name="location">资源定位地址</param>
|
||||
/// <param name="parent">父物体</param>
|
||||
/// <param name="position">世界坐标</param>
|
||||
/// <param name="rotation">世界角度</param>
|
||||
/// <param name="forceClone">强制克隆游戏对象,忽略缓存池里的对象</param>
|
||||
/// <param name="userDatas">用户自定义数据</param>
|
||||
public SpawnHandle SpawnSync(string location, Transform parent, Vector3 position, Quaternion rotation, bool forceClone = false, params System.Object[] userDatas)
|
||||
{
|
||||
SpawnHandle handle = SpawnInternal(location, parent, position, rotation, forceClone, userDatas);
|
||||
handle.WaitForAsyncComplete();
|
||||
return handle;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 实例化一个游戏对象
|
||||
/// </summary>
|
||||
private SpawnHandle SpawnInternal(string location, Transform parent, Vector3 position, Quaternion rotation, bool forceClone, params System.Object[] userDatas)
|
||||
{
|
||||
var pool = TryGetGameObjectPool(location);
|
||||
if (pool != null)
|
||||
{
|
||||
return pool.Spawn(parent, position, rotation, forceClone, userDatas);
|
||||
}
|
||||
|
||||
// 如果不存在创建游戏对象池
|
||||
pool = new GameObjectPool(_spawnerRoot, location, false, 0, int.MaxValue, -1f);
|
||||
pool.CreatePool(_assetPackage);
|
||||
_gameObjectPools.Add(pool);
|
||||
return pool.Spawn(parent, position, rotation, forceClone, userDatas);
|
||||
}
|
||||
|
||||
|
||||
private GameObjectPool TryGetGameObjectPool(string location)
|
||||
{
|
||||
foreach (var pool in _gameObjectPools)
|
||||
{
|
||||
if (pool.Location == location)
|
||||
return pool;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6c0b7912d44674d47a5b7240670dcc87
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace UniFramework.Pooling
|
||||
{
|
||||
internal static class UniLogger
|
||||
{
|
||||
[Conditional("DEBUG")]
|
||||
public static void Log(string info)
|
||||
{
|
||||
UnityEngine.Debug.Log(info);
|
||||
}
|
||||
public static void Warning(string info)
|
||||
{
|
||||
UnityEngine.Debug.LogWarning(info);
|
||||
}
|
||||
public static void Error(string info)
|
||||
{
|
||||
UnityEngine.Debug.LogError(info);
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 50142a5596fb6c1439dced35faef4d4c
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Vendored
+16
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"name": "UniPooling",
|
||||
"rootNamespace": "",
|
||||
"references": [
|
||||
"GUID:e34a5702dd353724aa315fb8011f08c3"
|
||||
],
|
||||
"includePlatforms": [],
|
||||
"excludePlatforms": [],
|
||||
"allowUnsafeCode": true,
|
||||
"overrideReferences": false,
|
||||
"precompiledReferences": [],
|
||||
"autoReferenced": true,
|
||||
"defineConstraints": [],
|
||||
"versionDefines": [],
|
||||
"noEngineReferences": false
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b0a84d582f6a6fa4185f67ce934d99c2
|
||||
AssemblyDefinitionImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Vendored
+125
@@ -0,0 +1,125 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using YooAsset;
|
||||
|
||||
namespace UniFramework.Pooling
|
||||
{
|
||||
/// <summary>
|
||||
/// 游戏对象池系统
|
||||
/// </summary>
|
||||
public static class UniPooling
|
||||
{
|
||||
private static bool _isInitialize = false;
|
||||
private static readonly List<Spawner> _spawners = new List<Spawner>();
|
||||
private static GameObject _poolingRoot;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 初始化游戏对象池系统
|
||||
/// </summary>
|
||||
public static void Initalize()
|
||||
{
|
||||
if (_isInitialize)
|
||||
throw new Exception($"{nameof(UniPooling)} is initialized !");
|
||||
|
||||
if (_isInitialize == false)
|
||||
{
|
||||
// 创建驱动器
|
||||
_isInitialize = true;
|
||||
_poolingRoot = new UnityEngine.GameObject($"[{nameof(UniPooling)}]");
|
||||
_poolingRoot.AddComponent<UniPoolingDriver>();
|
||||
UnityEngine.Object.DontDestroyOnLoad(_poolingRoot);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更新游戏对象池系统
|
||||
/// </summary>
|
||||
internal static void Update()
|
||||
{
|
||||
if (_isInitialize)
|
||||
{
|
||||
foreach (var spawner in _spawners)
|
||||
{
|
||||
spawner.Update();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 销毁游戏对象池系统
|
||||
/// </summary>
|
||||
internal static void Destroy()
|
||||
{
|
||||
if (_isInitialize)
|
||||
{
|
||||
foreach (var spawner in _spawners)
|
||||
{
|
||||
spawner.Destroy();
|
||||
}
|
||||
|
||||
_spawners.Clear();
|
||||
_isInitialize = false;
|
||||
UniLogger.Log($"{nameof(UniPooling)} destroy all !");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 创建游戏对象生成器
|
||||
/// </summary>
|
||||
/// <param name="packageName">资源包名称</param>
|
||||
public static Spawner CreateSpawner(string packageName)
|
||||
{
|
||||
// 获取资源包
|
||||
var assetPackage = YooAssets.GetAssetsPackage(packageName);
|
||||
if (assetPackage == null)
|
||||
throw new Exception($"Not found asset package : {packageName}");
|
||||
|
||||
// 检测资源包初始化状态
|
||||
if (assetPackage.InitializeStatus == EOperationStatus.None)
|
||||
throw new Exception($"Asset package {packageName} not initialize !");
|
||||
if (assetPackage.InitializeStatus == EOperationStatus.Failed)
|
||||
throw new Exception($"Asset package {packageName} initialize failed !");
|
||||
|
||||
if (HasSpawner(packageName))
|
||||
return GetSpawner(packageName);
|
||||
|
||||
Spawner spawner = new Spawner(_poolingRoot, assetPackage);
|
||||
_spawners.Add(spawner);
|
||||
return spawner;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取游戏对象生成器
|
||||
/// </summary>
|
||||
/// <param name="packageName">资源包名称</param>
|
||||
public static Spawner GetSpawner(string packageName)
|
||||
{
|
||||
foreach (var spawner in _spawners)
|
||||
{
|
||||
if (spawner.PackageName == packageName)
|
||||
return spawner;
|
||||
}
|
||||
|
||||
UniLogger.Warning($"Not found spawner : {packageName}");
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 检测游戏对象生成器是否存在
|
||||
/// </summary>
|
||||
/// <param name="packageName">资源包名称</param>
|
||||
public static bool HasSpawner(string packageName)
|
||||
{
|
||||
foreach (var spawner in _spawners)
|
||||
{
|
||||
if (spawner.PackageName == packageName)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
Assets/YooAsset/Samples~/Space Shooter/ThirdParty/UniFramework/UniPooling/Runtime/UniPooling.cs.meta
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 04fd1800aa2e61644893fa7893d93db8
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace UniFramework.Pooling
|
||||
{
|
||||
internal class UniPoolingDriver : MonoBehaviour
|
||||
{
|
||||
void Update()
|
||||
{
|
||||
UniPooling.Update();
|
||||
}
|
||||
|
||||
void OnDestroy()
|
||||
{
|
||||
UniPooling.Destroy();
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f4112e0723ed46c45927cc3498d62e5a
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 039eb69f46ea8bf4c873ab10b816da92
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
# UniFramework.Utility
|
||||
|
||||
一些工具类。
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f055964b764f8cc41996f3c543307c85
|
||||
TextScriptImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: c3799338015524b47a601024fd574a90
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Vendored
+199
@@ -0,0 +1,199 @@
|
||||
|
||||
namespace UniFramework.Utility
|
||||
{
|
||||
public sealed class UniTimer
|
||||
{
|
||||
/// <summary>
|
||||
/// 延迟后,触发一次
|
||||
/// </summary>
|
||||
public static UniTimer CreateOnceTimer(float delay)
|
||||
{
|
||||
return new UniTimer(delay, -1, -1, 1);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 延迟后,永久性的间隔触发
|
||||
/// </summary>
|
||||
/// <param name="delay">延迟时间</param>
|
||||
/// <param name="interval">间隔时间</param>
|
||||
public static UniTimer CreatePepeatTimer(float delay, float interval)
|
||||
{
|
||||
return new UniTimer(delay, interval, -1, -1);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 延迟后,在一段时间内间隔触发
|
||||
/// </summary>
|
||||
/// <param name="delay">延迟时间</param>
|
||||
/// <param name="interval">间隔时间</param>
|
||||
/// <param name="duration">触发周期</param>
|
||||
public static UniTimer CreatePepeatTimer(float delay, float interval, float duration)
|
||||
{
|
||||
return new UniTimer(delay, interval, duration, -1);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 延迟后,间隔触发一定次数
|
||||
/// </summary>
|
||||
/// <param name="delay">延迟时间</param>
|
||||
/// <param name="interval">间隔时间</param>
|
||||
/// <param name="maxTriggerCount">最大触发次数</param>
|
||||
public static UniTimer CreatePepeatTimer(float delay, float interval, long maxTriggerCount)
|
||||
{
|
||||
return new UniTimer(delay, interval, -1, maxTriggerCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 延迟后,在一段时间内触发
|
||||
/// </summary>
|
||||
/// <param name="delay">延迟时间</param>
|
||||
/// <param name="duration">触发周期</param>
|
||||
public static UniTimer CreateDurationTimer(float delay, float duration)
|
||||
{
|
||||
return new UniTimer(delay, -1, duration, -1);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 延迟后,永久触发
|
||||
/// </summary>
|
||||
public static UniTimer CreateForeverTimer(float delay)
|
||||
{
|
||||
return new UniTimer(delay, -1, -1, -1);
|
||||
}
|
||||
|
||||
|
||||
private readonly float _intervalTime;
|
||||
private readonly float _durationTime;
|
||||
private readonly long _maxTriggerCount;
|
||||
|
||||
// 需要重置的变量
|
||||
private float _delayTimer = 0;
|
||||
private float _durationTimer = 0;
|
||||
private float _intervalTimer = 0;
|
||||
private long _triggerCount = 0;
|
||||
|
||||
/// <summary>
|
||||
/// 延迟时间
|
||||
/// </summary>
|
||||
public float DelayTime { private set; get; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否已经结束
|
||||
/// </summary>
|
||||
public bool IsOver { private set; get; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否已经暂停
|
||||
/// </summary>
|
||||
public bool IsPause { private set; get; }
|
||||
|
||||
/// <summary>
|
||||
/// 延迟剩余时间
|
||||
/// </summary>
|
||||
public float Remaining
|
||||
{
|
||||
get
|
||||
{
|
||||
if (IsOver)
|
||||
return 0f;
|
||||
else
|
||||
return System.Math.Max(0f, DelayTime - _delayTimer);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 计时器
|
||||
/// </summary>
|
||||
/// <param name="delay">延迟时间</param>
|
||||
/// <param name="interval">间隔时间</param>
|
||||
/// <param name="duration">运行时间</param>
|
||||
/// <param name="maxTriggerTimes">最大触发次数</param>
|
||||
public UniTimer(float delay, float interval, float duration, long maxTriggerCount)
|
||||
{
|
||||
DelayTime = delay;
|
||||
_intervalTime = interval;
|
||||
_durationTime = duration;
|
||||
_maxTriggerCount = maxTriggerCount;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 暂停计时器
|
||||
/// </summary>
|
||||
public void Pause()
|
||||
{
|
||||
IsPause = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 恢复计时器
|
||||
/// </summary>
|
||||
public void Resume()
|
||||
{
|
||||
IsPause = false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 结束计时器
|
||||
/// </summary>
|
||||
public void Kill()
|
||||
{
|
||||
IsOver = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 重置计时器
|
||||
/// </summary>
|
||||
public void Reset()
|
||||
{
|
||||
_delayTimer = 0;
|
||||
_durationTimer = 0;
|
||||
_intervalTimer = 0;
|
||||
_triggerCount = 0;
|
||||
IsOver = false;
|
||||
IsPause = false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更新计时器
|
||||
/// </summary>
|
||||
public bool Update(float deltaTime)
|
||||
{
|
||||
if (IsOver || IsPause)
|
||||
return false;
|
||||
|
||||
_delayTimer += deltaTime;
|
||||
if (_delayTimer < DelayTime)
|
||||
return false;
|
||||
|
||||
if(_intervalTime > 0)
|
||||
_intervalTimer += deltaTime;
|
||||
if (_durationTime > 0)
|
||||
_durationTimer += deltaTime;
|
||||
|
||||
// 检测间隔执行
|
||||
if (_intervalTime > 0)
|
||||
{
|
||||
if (_intervalTimer < _intervalTime)
|
||||
return false;
|
||||
_intervalTimer = 0;
|
||||
}
|
||||
|
||||
// 检测结束条件
|
||||
if (_durationTime > 0)
|
||||
{
|
||||
if (_durationTimer >= _durationTime)
|
||||
Kill();
|
||||
}
|
||||
|
||||
// 检测结束条件
|
||||
if (_maxTriggerCount > 0)
|
||||
{
|
||||
_triggerCount++;
|
||||
if (_triggerCount >= _maxTriggerCount)
|
||||
Kill();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a9ba1e57e76e1c3498c1e678e2737ab2
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Vendored
+14
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "UniUtility",
|
||||
"rootNamespace": "",
|
||||
"references": [],
|
||||
"includePlatforms": [],
|
||||
"excludePlatforms": [],
|
||||
"allowUnsafeCode": false,
|
||||
"overrideReferences": false,
|
||||
"precompiledReferences": [],
|
||||
"autoReferenced": true,
|
||||
"defineConstraints": [],
|
||||
"versionDefines": [],
|
||||
"noEngineReferences": false
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 1ea6b676786131e4095182b742bb64ec
|
||||
AssemblyDefinitionImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5079914495c00a74e873f6490a7a5673
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
# UniFramework.Window
|
||||
|
||||
一个轻量级的基于堆栈的界面系统。
|
||||
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 32e55b8a0d57de5428a1e06cc0cc87b3
|
||||
TextScriptImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a933ee98d9388e74dba1a42e77f4f6d8
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
using YooAsset;
|
||||
|
||||
namespace UniFramework.Window
|
||||
{
|
||||
public class OpenWindowOperation : GameAsyncOperation
|
||||
{
|
||||
private enum ESteps
|
||||
{
|
||||
None,
|
||||
Waiting,
|
||||
Done,
|
||||
}
|
||||
|
||||
private readonly AssetOperationHandle _handle;
|
||||
private ESteps _steps = ESteps.None;
|
||||
|
||||
internal OpenWindowOperation(AssetOperationHandle handle)
|
||||
{
|
||||
_handle = handle;
|
||||
}
|
||||
protected override void OnStart()
|
||||
{
|
||||
_steps = ESteps.Waiting;
|
||||
}
|
||||
protected override void OnUpdate()
|
||||
{
|
||||
if (_steps == ESteps.None || _steps == ESteps.Done)
|
||||
return;
|
||||
|
||||
if (_steps == ESteps.Waiting)
|
||||
{
|
||||
if (_handle.IsValid == false)
|
||||
{
|
||||
_steps = ESteps.Done;
|
||||
Status = EOperationStatus.Failed;
|
||||
Error = $"{nameof(AssetOperationHandle)} is invalid.";
|
||||
return;
|
||||
}
|
||||
|
||||
if (_handle.IsDone == false)
|
||||
return;
|
||||
|
||||
if (_handle.AssetObject == null)
|
||||
{
|
||||
_steps = ESteps.Done;
|
||||
Status = EOperationStatus.Failed;
|
||||
Error = $"{nameof(AssetOperationHandle.AssetObject)} is null.";
|
||||
return;
|
||||
}
|
||||
|
||||
_steps = ESteps.Done;
|
||||
Status = EOperationStatus.Succeed;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 等待异步实例化结束
|
||||
/// </summary>
|
||||
public void WaitForAsyncComplete()
|
||||
{
|
||||
if (_handle != null)
|
||||
{
|
||||
if (_steps == ESteps.Done)
|
||||
return;
|
||||
_handle.WaitForAsyncComplete();
|
||||
OnUpdate();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4607e0d0ccaff3940854224460f93bbd
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Vendored
+325
@@ -0,0 +1,325 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
using YooAsset;
|
||||
|
||||
namespace UniFramework.Window
|
||||
{
|
||||
public abstract class UIWindow
|
||||
{
|
||||
public const int WINDOW_HIDE_LAYER = 2; // Ignore Raycast
|
||||
public const int WINDOW_SHOW_LAYER = 5; // UI
|
||||
|
||||
internal AssetOperationHandle Handle { private set; get;}
|
||||
private System.Action<UIWindow> _prepareCallback;
|
||||
private System.Object[] _userDatas;
|
||||
|
||||
private bool _isCreate = false;
|
||||
private GameObject _panel;
|
||||
private Canvas _canvas;
|
||||
private Canvas[] _childCanvas;
|
||||
private GraphicRaycaster _raycaster;
|
||||
private GraphicRaycaster[] _childRaycaster;
|
||||
|
||||
/// <summary>
|
||||
/// 面板的Transfrom组件
|
||||
/// </summary>
|
||||
public Transform transform
|
||||
{
|
||||
get
|
||||
{
|
||||
return _panel.transform;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 面板的游戏对象
|
||||
/// </summary>
|
||||
public GameObject gameObject
|
||||
{
|
||||
get
|
||||
{
|
||||
return _panel;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 窗口名称
|
||||
/// </summary>
|
||||
public string WindowName { private set; get; }
|
||||
|
||||
/// <summary>
|
||||
/// 窗口层级
|
||||
/// </summary>
|
||||
public int WindowLayer { private set; get; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否为全屏窗口
|
||||
/// </summary>
|
||||
public bool FullScreen { private set; get; }
|
||||
|
||||
/// <summary>
|
||||
/// 自定义数据
|
||||
/// </summary>
|
||||
public System.Object UserData
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_userDatas != null && _userDatas.Length >= 1)
|
||||
return _userDatas[0];
|
||||
else
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 自定义数据集
|
||||
/// </summary>
|
||||
public System.Object[] UserDatas
|
||||
{
|
||||
get { return _userDatas; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 窗口深度值
|
||||
/// </summary>
|
||||
public int Depth
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_canvas != null)
|
||||
return _canvas.sortingOrder;
|
||||
else
|
||||
return 0;
|
||||
}
|
||||
|
||||
set
|
||||
{
|
||||
if (_canvas != null)
|
||||
{
|
||||
if (_canvas.sortingOrder == value)
|
||||
return;
|
||||
|
||||
// 设置父类
|
||||
_canvas.sortingOrder = value;
|
||||
|
||||
// 设置子类
|
||||
int depth = value;
|
||||
for (int i = 0; i < _childCanvas.Length; i++)
|
||||
{
|
||||
var canvas = _childCanvas[i];
|
||||
if (canvas != _canvas)
|
||||
{
|
||||
depth += 5; //注意递增值
|
||||
canvas.sortingOrder = depth;
|
||||
}
|
||||
}
|
||||
|
||||
// 虚函数
|
||||
if (_isCreate)
|
||||
OnSortDepth(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <summary>
|
||||
/// 窗口可见性
|
||||
/// </summary>
|
||||
public bool Visible
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_canvas != null)
|
||||
return _canvas.gameObject.layer == WINDOW_SHOW_LAYER;
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
set
|
||||
{
|
||||
if (_canvas != null)
|
||||
{
|
||||
int setLayer = value ? WINDOW_SHOW_LAYER : WINDOW_HIDE_LAYER;
|
||||
if (_canvas.gameObject.layer == setLayer)
|
||||
return;
|
||||
|
||||
// 显示设置
|
||||
_canvas.gameObject.layer = setLayer;
|
||||
for (int i = 0; i < _childCanvas.Length; i++)
|
||||
{
|
||||
_childCanvas[i].gameObject.layer = setLayer;
|
||||
}
|
||||
|
||||
// 交互设置
|
||||
Interactable = value;
|
||||
|
||||
// 虚函数
|
||||
if (_isCreate)
|
||||
OnSetVisible(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 窗口交互性
|
||||
/// </summary>
|
||||
private bool Interactable
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_raycaster != null)
|
||||
return _raycaster.enabled;
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
set
|
||||
{
|
||||
if (_raycaster != null)
|
||||
{
|
||||
_raycaster.enabled = value;
|
||||
for (int i = 0; i < _childRaycaster.Length; i++)
|
||||
{
|
||||
_childRaycaster[i].enabled = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 是否加载完毕
|
||||
/// </summary>
|
||||
internal bool IsLoadDone { get { return Handle.IsDone; } }
|
||||
|
||||
/// <summary>
|
||||
/// 是否准备完毕
|
||||
/// </summary>
|
||||
internal bool IsPrepare { private set; get; }
|
||||
|
||||
|
||||
public void Init(string name, int layer, bool fullScreen)
|
||||
{
|
||||
WindowName = name;
|
||||
WindowLayer = layer;
|
||||
FullScreen = fullScreen;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 窗口创建
|
||||
/// </summary>
|
||||
public abstract void OnCreate();
|
||||
|
||||
/// <summary>
|
||||
/// 窗口刷新
|
||||
/// </summary>
|
||||
public abstract void OnRefresh();
|
||||
|
||||
/// <summary>
|
||||
/// 窗口更新
|
||||
/// </summary>
|
||||
public abstract void OnUpdate();
|
||||
|
||||
/// <summary>
|
||||
/// 窗口销毁
|
||||
/// </summary>
|
||||
public abstract void OnDestroy();
|
||||
|
||||
/// <summary>
|
||||
/// 当触发窗口的层级排序
|
||||
/// </summary>
|
||||
protected virtual void OnSortDepth(int depth) { }
|
||||
|
||||
/// <summary>
|
||||
/// 当因为全屏遮挡触发窗口的显隐
|
||||
/// </summary>
|
||||
protected virtual void OnSetVisible(bool visible) { }
|
||||
|
||||
internal void TryInvoke(System.Action<UIWindow> prepareCallback, System.Object[] userDatas)
|
||||
{
|
||||
_userDatas = userDatas;
|
||||
if (IsPrepare)
|
||||
prepareCallback?.Invoke(this);
|
||||
else
|
||||
_prepareCallback = prepareCallback;
|
||||
}
|
||||
internal void InternalLoad(string location, System.Action<UIWindow> prepareCallback, System.Object[] userDatas)
|
||||
{
|
||||
if (Handle != null)
|
||||
return;
|
||||
|
||||
_prepareCallback = prepareCallback;
|
||||
_userDatas = userDatas;
|
||||
Handle = YooAssets.LoadAssetAsync<GameObject>(location);
|
||||
Handle.Completed += Handle_Completed;
|
||||
}
|
||||
internal void InternalCreate()
|
||||
{
|
||||
if (_isCreate == false)
|
||||
{
|
||||
_isCreate = true;
|
||||
OnCreate();
|
||||
}
|
||||
}
|
||||
internal void InternalRefresh()
|
||||
{
|
||||
OnRefresh();
|
||||
}
|
||||
internal void InternalUpdate()
|
||||
{
|
||||
if(IsPrepare)
|
||||
{
|
||||
OnUpdate();
|
||||
}
|
||||
}
|
||||
internal void InternalDestroy()
|
||||
{
|
||||
_isCreate = false;
|
||||
|
||||
// 注销回调函数
|
||||
_prepareCallback = null;
|
||||
|
||||
// 卸载面板资源
|
||||
if (Handle != null)
|
||||
{
|
||||
Handle.Release();
|
||||
Handle = null;
|
||||
}
|
||||
|
||||
// 销毁面板对象
|
||||
if (_panel != null)
|
||||
{
|
||||
OnDestroy();
|
||||
GameObject.Destroy(_panel);
|
||||
_panel = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void Handle_Completed(AssetOperationHandle handle)
|
||||
{
|
||||
if (handle.AssetObject == null)
|
||||
return;
|
||||
|
||||
// 实例化对象
|
||||
_panel = handle.InstantiateSync(UniWindow.Desktop.transform);
|
||||
_panel.transform.localPosition = Vector3.zero;
|
||||
|
||||
// 获取组件
|
||||
_canvas = _panel.GetComponent<Canvas>();
|
||||
if (_canvas == null)
|
||||
throw new Exception($"Not found {nameof(Canvas)} in panel {WindowName}");
|
||||
_canvas.overrideSorting = true;
|
||||
_canvas.sortingOrder = 0;
|
||||
_canvas.sortingLayerName = "Default";
|
||||
|
||||
// 获取组件
|
||||
_raycaster = _panel.GetComponent<GraphicRaycaster>();
|
||||
_childCanvas = _panel.GetComponentsInChildren<Canvas>(true);
|
||||
_childRaycaster = _panel.GetComponentsInChildren<GraphicRaycaster>(true);
|
||||
|
||||
// 通知UI管理器
|
||||
IsPrepare = true;
|
||||
_prepareCallback?.Invoke(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7e1414cd524a4d24aa5653dba76dd850
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user