Skip to content

Commit fb6918e

Browse files
committed
added: unload feature for URLCaching.
1 parent f73d28f commit fb6918e

13 files changed

Lines changed: 232 additions & 53 deletions

File tree

Assets/Autoya/Backyard/PersistImplementation.cs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,26 @@ public static void Persist_URLCaching_Load<T>(string domain, string url, Func<by
166166
autoya.mainthreadDispatcher.Commit(cor);
167167
}
168168

169+
public static bool Persist_URLCaching_IsLoaded(string domain, string url)
170+
{
171+
if (autoya._autoyaURLCache == null)
172+
{
173+
autoya._autoyaURLCache = new URLCache(autoya._autoyaFilePersistence);
174+
}
175+
176+
return autoya._autoyaURLCache.IsLoaded(domain, url, out var path);
177+
}
178+
179+
public static void Persist_URLCaching_Unload(string domain, string url, bool destroyLoadedObject = false)
180+
{
181+
if (autoya._autoyaURLCache == null)
182+
{
183+
autoya._autoyaURLCache = new URLCache(autoya._autoyaFilePersistence);
184+
}
185+
186+
autoya._autoyaURLCache.Unload(domain, url, destroyLoadedObject);
187+
}
188+
169189
public static void Persist_URLCaching_Purge(string domain, string url)
170190
{
171191
if (autoya._autoyaURLCache == null)

Assets/Autoya/Persistence/URLCaching/URLCaching.cs

Lines changed: 95 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -26,31 +26,53 @@ public URLCache(FilePersistence fp)
2626

2727
private Hashtable cachingLock = new Hashtable();
2828

29-
private Dictionary<string, UnityEngine.Object> pathObjectCache = new Dictionary<string, UnityEngine.Object>();
29+
// オンメモリキャッシュ
30+
private Dictionary<string, UnityEngine.Object> pathObjectOnMemoryCache = new Dictionary<string, UnityEngine.Object>();
3031

31-
public void PurgeCache(string storePath, string urlWithoutHash)
32+
/*
33+
urlに紐づく対象をファイルとオンメモリキャッシュから削除する
34+
*/
35+
public void PurgeCache(string storePath, string urlWithoutHash, bool destroyLoadedObject = false)
3236
{
3337
var deleteTargetPath = Path.Combine(storePath, GenerateFolderAndFilePath(urlWithoutHash, string.Empty, storePath).url);
3438

3539
var filePaths = filePersist.FileNamesInDomain(deleteTargetPath);
36-
if (filePaths.Any())
40+
if (!filePaths.Any())
3741
{
38-
// remove from hard cache.
39-
filePersist.DeleteByDomain(deleteTargetPath);
42+
return;
43+
}
4044

41-
// remove from on memory cache.
42-
var filePath = Path.Combine(deleteTargetPath, Path.GetFileName(filePaths[0]));
43-
if (pathObjectCache.ContainsKey(filePath))
45+
// remove from hard cache.
46+
filePersist.DeleteByDomain(deleteTargetPath);
47+
48+
// remove from on memory cache.
49+
var filePath = Path.Combine(deleteTargetPath, Path.GetFileName(filePaths[0]));
50+
if (pathObjectOnMemoryCache.ContainsKey(filePath))
51+
{
52+
UnityEngine.Object obj = null;
53+
if (destroyLoadedObject)
54+
{
55+
obj = pathObjectOnMemoryCache[filePath];
56+
}
57+
58+
pathObjectOnMemoryCache.Remove(filePath);
59+
60+
if (destroyLoadedObject)
4461
{
45-
pathObjectCache.Remove(filePath);
62+
GameObject.Destroy(obj);
4663
}
4764
}
4865
}
4966

67+
/*
68+
ドメイン単位で消す。
69+
*/
5070
public void ClearCaching(string storePath)
5171
{
5272
filePersist.DeleteByDomain(storePath);
53-
pathObjectCache = new Dictionary<string, UnityEngine.Object>();
73+
74+
// TODO: ドメイン単位で消せると嬉しいが、現在は全部のオンメモリキャッシュを消している。
75+
pathObjectOnMemoryCache = new Dictionary<string, UnityEngine.Object>();
5476
}
5577

5678
private UrlAndHash GenerateFolderAndFilePath(string urlWithoutHash, string hashSource, string storePath)
@@ -94,9 +116,7 @@ public IEnumerator LoadFromURLAs<T>(string storePath, string url, Func<byte[], T
94116
}
95117
}
96118

97-
/*
98-
URLから取得したAssetをT型のインスタンスに変形させる手順を提供する。
99-
*/
119+
// 指定したkeyパラメータをurlのqueryパラメータの代わりに使用する = urlで取得したものをkeyパラメータに依存したパスにキャッシュする。
100120
public IEnumerator LoadFromURLAs<T>(string storePath, string key, string url, Func<byte[], T> bytesToTConverter, Action<T> onLoaded, Action<int, string> onLoadFailed, Dictionary<string, string> requestHeader = null, int timeout = (int)BackyardSettings.HTTP_TIMEOUT_SEC) where T : UnityEngine.Object
101121
{
102122
// urlでない場合、urlとして扱うためのパラメータを足す。
@@ -118,6 +138,62 @@ public IEnumerator LoadFromURLAs<T>(string storePath, string key, string url, Fu
118138
}
119139
}
120140

141+
/*
142+
メモリにload済であればtrueを返す。
143+
loadされていなければfalseを返す。
144+
*/
145+
public bool IsLoaded(string storePath, string url, out string fileUniquePath)
146+
{
147+
var urlBase = new Uri(url);
148+
var pathWithoutHash = urlBase.Authority + urlBase.LocalPath;
149+
var hash = Convert.ToBase64String(Encoding.UTF8.GetBytes(urlBase.Query));
150+
151+
// ファイルパス、ファイル名を生成する
152+
var targetFolderNameAndHash = GenerateFolderAndFilePath(pathWithoutHash, hash, storePath);
153+
var targetFolderName = targetFolderNameAndHash.url;
154+
var targetFileName = targetFolderNameAndHash.url + "_" + targetFolderNameAndHash.hash;
155+
156+
// フォルダ、ファイルがあるかどうかチェックする
157+
var folderPath = Path.Combine(storePath, targetFolderName);
158+
var existFolderPaths = filePersist.FileNamesInDomain(folderPath);
159+
160+
fileUniquePath = Path.Combine(folderPath, targetFileName);
161+
162+
// オンメモリキャッシュに対象が存在するかどうか
163+
if (pathObjectOnMemoryCache.ContainsKey(fileUniquePath))
164+
{
165+
return true;
166+
}
167+
168+
return false;
169+
}
170+
171+
/*
172+
ロード済のオンメモリから削除する。
173+
*/
174+
public void Unload(string storePath, string urlWithoutHash, bool destroyLoadedObject = false)
175+
{
176+
if (IsLoaded(storePath, urlWithoutHash, out var fileUniquePath))
177+
{
178+
// remove from on memory cache.
179+
UnityEngine.Object obj = null;
180+
if (destroyLoadedObject)
181+
{
182+
obj = pathObjectOnMemoryCache[fileUniquePath];
183+
}
184+
185+
pathObjectOnMemoryCache.Remove(fileUniquePath);
186+
187+
if (destroyLoadedObject)
188+
{
189+
GameObject.Destroy(obj);
190+
}
191+
}
192+
}
193+
194+
/*
195+
urlに対してキャッシュされるpathを返す
196+
*/
121197
public string PathOf(string storePath, string url)
122198
{
123199
var urlBase = new Uri(url);
@@ -206,7 +282,6 @@ public IEnumerator ExecuteExpiration(string storePath, int expirationDayCount, i
206282

207283
private IEnumerator Load<T>(string url, string pathWithoutHash, string hash, string storePath, Func<byte[], T> bytesToTConverter, Action<T> onLoaded, Action<int, string> onLoadFailed, Dictionary<string, string> requestHeader = null, double timeout = BackyardSettings.HTTP_TIMEOUT_SEC) where T : UnityEngine.Object
208284
{
209-
210285
// ファイルパス、ファイル名を生成する
211286
var targetFolderNameAndHash = GenerateFolderAndFilePath(pathWithoutHash, hash, storePath);
212287
var targetFolderName = targetFolderNameAndHash.url;
@@ -219,9 +294,9 @@ private IEnumerator Load<T>(string url, string pathWithoutHash, string hash, str
219294
var fileUniquePath = Path.Combine(folderPath, targetFileName);
220295

221296
// キャッシュに対象が存在するかどうか
222-
if (pathObjectCache.ContainsKey(fileUniquePath))
297+
if (pathObjectOnMemoryCache.ContainsKey(fileUniquePath))
223298
{
224-
var cached = pathObjectCache[fileUniquePath] as T;
299+
var cached = pathObjectOnMemoryCache[fileUniquePath] as T;
225300
onLoaded(cached);
226301
yield break;
227302
}
@@ -237,7 +312,7 @@ private IEnumerator Load<T>(string url, string pathWithoutHash, string hash, str
237312
// 待機完了、オンメモリのキャッシュにあるかどうかチェックし、あれば返す。なければダウンロードに移行する。
238313

239314
UnityEngine.Object _object;
240-
if (pathObjectCache.TryGetValue(fileUniquePath, out _object))
315+
if (pathObjectOnMemoryCache.TryGetValue(fileUniquePath, out _object))
241316
{
242317
onLoaded(_object as T);
243318
yield break;
@@ -268,7 +343,7 @@ private IEnumerator Load<T>(string url, string pathWithoutHash, string hash, str
268343
// 読み出し成功したのでオンメモリに載せる。
269344
var tObj = bytesToTConverter(bytes);
270345

271-
pathObjectCache[fileUniquePath] = tObj;
346+
pathObjectOnMemoryCache[fileUniquePath] = tObj;
272347
lock (writeLock)
273348
{
274349
cachingLock.Remove(targetFolderName);
@@ -364,8 +439,8 @@ private IEnumerator Load<T>(string url, string pathWithoutHash, string hash, str
364439
// 型に対しての返還式を取り出し、byteからT型を生成する。
365440
var obj = bytesToTConverter(bytes);
366441

367-
// キャッシュを行う
368-
pathObjectCache[fileUniquePath] = obj;
442+
// オンメモリへのキャッシュを行う
443+
pathObjectOnMemoryCache[fileUniquePath] = obj;
369444

370445
lock (writeLock)
371446
{

Assets/AutoyaTests/Tests/Persistence/URLCachingImplementationTests.cs

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -574,6 +574,7 @@ public IEnumerator Timeout()
574574
// large picture.
575575
var imagePath = "https://upload.wikimedia.org/wikipedia/commons/2/2e/Zhao_Chang_-_Picture_of_the_New_Year_-_Google_Art_Project.jpg";
576576
var loadedFailed = false;
577+
577578
Autoya.Persist_URLCaching_Load<Sprite>(
578579
AutoyaURLCachingTestsFileDomain,
579580
imagePath,
@@ -600,7 +601,7 @@ public IEnumerator Timeout()
600601
yield return WaitUntil(
601602
() => loadedFailed,
602603
() => { throw new TimeoutException("timeout."); },
603-
1000
604+
10
604605
);
605606
}
606607

@@ -773,5 +774,58 @@ public IEnumerator ExecuteExpirationForManyFiles()
773774
Assert.False(File.Exists(path), "should not exist.");
774775
}
775776
}
777+
778+
[MTest]
779+
public IEnumerator Unload()
780+
{
781+
// store one image.
782+
var loaded = false;
783+
var imagePath = "https://upload.wikimedia.org/wikipedia/commons/thumb/9/9e/2016-06-14_Orange_and_white_tabby_cat_born_in_2016_茶トラ白ねこ_DSCF6526☆彡.jpg/400px-2016-06-14_Orange_and_white_tabby_cat_born_in_2016_茶トラ白ねこ_DSCF6526☆彡.jpg?a=b";
784+
785+
Autoya.Persist_URLCaching_Load(
786+
AutoyaURLCachingTestsFileDomain,
787+
imagePath,
788+
bytes =>
789+
{
790+
// return sprite from bytes.
791+
var tex = new Texture2D(1, 1);
792+
tex.LoadImage(bytes);
793+
var newSprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(.5f, .5f));
794+
return newSprite;
795+
},
796+
cached =>
797+
{
798+
loaded = true;
799+
},
800+
(code, reason) =>
801+
{
802+
loaded = true;
803+
Fail();
804+
}
805+
);
806+
807+
yield return WaitUntil(
808+
() => loaded,
809+
() => { throw new TimeoutException("timeout for making cache."); }
810+
);
811+
812+
var pathOfCachedImage = Autoya.Persist_URLCaching_PathOf(AutoyaURLCachingTestsFileDomain, imagePath);
813+
Assert.True(File.Exists(pathOfCachedImage), "not exist.");
814+
815+
// キャッシュ done.
816+
817+
Autoya.Persist_URLCaching_Unload(
818+
AutoyaURLCachingTestsFileDomain,
819+
imagePath,
820+
true
821+
);
822+
823+
var isLoaded = Autoya.Persist_URLCaching_IsLoaded(
824+
AutoyaURLCachingTestsFileDomain,
825+
imagePath
826+
);
827+
828+
Assert.True(!isLoaded, "failed to unload.");
829+
}
776830
}
777831

Assets/Editor/AssetGraph-1.4-release/UnityEngine.AssetGraph/Cache/TemporalSettingFiles/AssetReferenceDB.asset

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,6 @@ MonoBehaviour:
1313
m_Name: AssetReferenceDB
1414
m_EditorClassIdentifier:
1515
m_assets:
16-
- m_assetDatabaseId: 526cdb84319594850bae31788e91464d
17-
m_importFrom: Assets/Autoya/Persistence/URLCaching/URLCaching.cs
18-
m_exportTo:
19-
m_variantName:
2016
- m_assetDatabaseId: 269a7412e7d2a4bee9fa6e819ae61e8a
2117
m_importFrom: Assets/Autoya/Manifest/ShouldGitIgnore/Resources/BuildManifest.json
2218
m_exportTo:
@@ -25,8 +21,4 @@ MonoBehaviour:
2521
m_importFrom: Assets/Editor/AssetGraph-1.4-release/UnityEngine.AssetGraph/Cache/TemporalSettingFiles/AssetReferenceDB.asset
2622
m_exportTo:
2723
m_variantName:
28-
- m_assetDatabaseId: ec5ec1496f4ed40b9a67e5b76a534e22
29-
m_importFrom: Assets/AutoyaTests/RuntimeData/AssetBundles/MainResources/nestedPrefab.prefab
30-
m_exportTo:
31-
m_variantName:
3224
m_version: 2

Assets/Plugins/UDP/Android/udp.aar.meta

Lines changed: 4 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Assets/Plugins/UDP/Android/udpsandbox.aar.meta

Lines changed: 4 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Assets/Plugins/UDP/Android/utils.aar.meta

Lines changed: 4 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)