-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBundleLoader.fs
397 lines (324 loc) · 14.9 KB
/
BundleLoader.fs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
namespace SpriteGallery.Avalonia
#nowarn "3391"
open UnityDataTools.FileSystem
open MicroUtils
open MicroUtils.UnityFilesystem
open MicroUtils.UnityFilesystem.Parsers
open MicroUtils.UnityFilesystem.Converters
open UnityData
open MicroUtils.Interop
open SpriteGallery.Avalonia.Common
type MicroOption = MicroUtils.Types.Optional
type MicroOption<'a> = MicroUtils.Types.Optional<'a>
type BlueprintAssetReference = { AssetID : string; FileID : int64 }
[<RequireQualifiedAccess>]
module AssetLoader =
let private initReaderCache() = new System.Threading.ThreadLocal<(string * UnityBinaryFileReader)[]>((fun () -> [||]), true)
let mutable private readers = initReaderCache()
let initSerializedFileCache() = new System.Threading.ThreadLocal<SerializedFile[]>((fun () -> [||]), true)
let mutable private serializedFiles = initSerializedFileCache()
let initArchiveCache() = new System.Threading.ThreadLocal<(string * UnityArchive)[]>((fun () -> [||]), true)
let mutable private archives = initArchiveCache()
let mutable private blueprintReferencedAssets : Map<(string * int64), BlueprintAssetReference> = Map.empty
let mutable private objectCache : Map<(string * int64), ITypeTreeValue> = Map.empty
let mutable textures : Map<(string * int64), SpriteTexture> = Map.empty
let init = UnityFileSystem.Init
let cleanup() =
blueprintReferencedAssets <- Map.empty
objectCache <- Map.empty
for (_, r) in readers.Values |> Seq.collect id do
r.Dispose()
readers.Dispose()
readers <- initReaderCache()
for sf in serializedFiles.Values |> Seq.collect id do
sf.Dispose()
serializedFiles.Dispose()
serializedFiles <- initSerializedFileCache()
for (_, archive) in archives.Values |> Seq.collect id do
archive.Dispose()
archives.Dispose()
archives <-initArchiveCache()
textures <- Map.empty
UnityFileSystem.Cleanup()
let mountArchive file =
archives.Value
|> Seq.tryFind (fun (path, _) -> path = file)
|> Option.map snd
|> Option.defaultWith (fun () ->
sprintf "Mounting archive %s" file |> log
let archive = UnityFileSystem.MountArchive(file, UnityData.mountPoint)
archives.Value <-
archives.Value |> Array.append [| (file, archive) |]
archive
)
let getDependenciesMapAsync (dir : string) = async {
let dependencyJsonFile = System.IO.Path.Join(dir, "dependencylist.json")
return! UnityData.getDependenciesAsync dependencyJsonFile
}
let getRecursiveArchiveDependencies (archiveFileName : string) (dependenciesMap : Map<string, string[]>) =
let mutable dependencies = [archiveFileName]
let rec getDeps f =
dependenciesMap
|> Map.tryFind f
|> Option.iter (fun ds ->
for d in ds do
if dependencies |> Seq.contains d |> not then
dependencies <- d :: dependencies
getDeps d
)
getDeps archiveFileName
dependencies
let mountArchiveWithDependencies (archiveFile : string) =
let dir = System.IO.Path.GetDirectoryName(archiveFile)
let fileName = System.IO.Path.GetFileName(archiveFile)
let dependenciesMap =
getDependenciesMapAsync dir
|> Async.RunSynchronously
let dependenciesPaths =
getRecursiveArchiveDependencies fileName dependenciesMap
|> Seq.map (fun name -> System.IO.Path.Join(dir, name))
let dependencies =
seq {
yield!
dependenciesPaths
|> Seq.map (fun path -> mountArchive path)
}
|> Seq.toArray
mountArchive archiveFile, dependencies
let getReader path =
let r, rs = getReader (readers.Value |> Array.toList) path
readers.Value <- rs |> List.toArray
r
let getSerializedFile path =
let sfPaths =
archives.Value
|> Seq.collect (snd >> getSerializedFilePaths)
serializedFiles.Value
|> Seq.tryFind (fun sf -> sf.Path = path)
|> Option.orElseWith (fun () ->
if sfPaths |> Seq.contains path then
let sf = UnityFileSystem.OpenSerializedFile(path)
serializedFiles.Value <- serializedFiles.Value |> Array.append [| sf |]
Some sf
else None)
|> MicroOption.FromFSharpOption
let dereference (pptr : PPtr) =
objectCache
|> Map.tryFind (pptr.SerializedFilePath, pptr.PathID)
|> Option.orElseWith (fun () ->
pptr.TryDereference(getSerializedFile, getReader >> MicroOption.Some)
|> toOption
|> Option.bind (fun v -> objectCache <- objectCache |> Map.add (pptr.SerializedFilePath, pptr.PathID) v; Some v))
let getAssetBundleAsset (sf : SerializedFile) =
let sfReader = getReader sf.Path
sf.Objects
|> Seq.tryFind (fun o -> sf.GetTypeTreeRoot(o.Id).Type = "AssetBundle")
|> Option.bind (fun o -> TypeTreeValue.Get(sf, sfReader, o).TryGetValue<AssetBundle>() |> toOption)
|> Option.map (fun f -> f.Invoke())
let mutable containersMaps : Map<string, Map<int64, string>> = Map.empty
let getContainerMap (sf : SerializedFile) =
containersMaps
|> Map.tryFind sf.Path
|> function
| Some map -> map
| None ->
let map =
getAssetBundleAsset sf
|> Option.toArray
|> Seq.collect (fun ab ->
ab.ContainerMap
|> Seq.collect (fun cm -> cm.Value |> Seq.map (fun ai -> ai, cm.Key))
|> Seq.collect (fun (ai, cid) ->
ai.GetAllAssetPPtrs(ab.PreloadTable)
|> Seq.append [ai.Asset]
|> Seq.distinctBy (fun pptr -> pptr.PathID)
|> Seq.map (fun pptr -> pptr.PathID, cid)
)
)
|> Map.ofSeq
containersMaps <-
containersMaps |> Map.add (sf.Path) map
map
let getBlueprintReferencedAssets (sf : SerializedFile) =
let sfReader = getReader sf.Path
sf.Objects
|> Seq.where (fun o ->
let tt = sf.GetTypeTreeRoot(o.Id)
tt.Type = "MonoBehaviour"
&& tt.Children |> Seq.exists (fun c -> c.Name = "m_Entries" && c.Type = "Entry"))
|> Seq.choose (fun o -> TypeTreeValue.Get(sf, sfReader, o).TryGetObject() |> toOption)
|> Seq.tryFind (fun o -> o |> TypeTreeObject.tryGetField "m_Name" = Some "BlueprintReferencedAssets")
|> Option.bind (TypeTreeObject.toMap >> Map.tryFind "m_Entries")
|> Option.bind (fun o -> o.TryGetObject() |> toOption)
|> Option.bind (TypeTreeObject.toMap >> Map.tryFind "Array")
|> Option.bind (fun o -> o.TryGetArray<ITypeTreeObject>() |> toOption)
|> Option.toArray
|> Seq.collect id
|> Seq.choose (fun o ->
let assetId = o |> TypeTreeObject.tryGetField<string> "AssetId"
let fileId = o |> TypeTreeObject.tryGetField<int64> "FileId"
let asset = o |> TypeTreeObject.tryGetField<PPtr> "Asset"
match assetId, fileId, asset with
| Some assetId, Some fileId, Some pptr -> Some (pptr, (assetId, fileId))
| _ -> None)
|> Seq.toArray
let getAllBlueprintReferencedAssets() =
if blueprintReferencedAssets |> Map.isEmpty then
let objects =
archives.Value
|> Seq.collect (fun (_, a) -> a.Nodes)
|> Seq.where (fun n -> n.Flags.HasFlag(ArchiveNodeFlags.SerializedFile))
|> Seq.map (fun n -> sprintf "%s%s" mountPoint n.Path)
|> Seq.choose (fun path -> getSerializedFile path |> toOption)
|> Seq.map (fun sf -> getBlueprintReferencedAssets sf)
|> Seq.where (fun assets -> assets.Length > 0)
|> Seq.toArray
blueprintReferencedAssets <-
objects
|> Seq.collect id
|> Seq.map (fun (pptr, (assetID, fileID)) ->
(pptr.GetReferencePath(getSerializedFile), pptr.PathID), { AssetID = assetID; FileID = fileID }
)
|> Map.ofSeq
blueprintReferencedAssets
let decodeTexture (texture : Texture2D) =
let buffer = Array.zeroCreate(4 * texture.Width * texture.Height)
if Texture2DConverter.DecodeTexture2D(texture, System.Span(buffer), getReader >> MicroOption.Some) then
Some buffer
else None
let getTexture (pptr : PPtr) =
getSerializedFile pptr.SerializedFilePath
|> toOption
|> Option.bind (fileIDToPath pptr.FileID)
|> Option.bind (fun filePath ->
let key = (filePath, pptr.PathID)
textures
|> Map.tryFind key
|> Option.orElseWith (fun () ->
#if DEBUG
log $"Load texture PPtr: {pptr.SerializedFilePath} -> FileID = {pptr.FileID}, PathID = {pptr.PathID}"
#endif
dereference pptr
|> Option.bind (
function
| :? Texture2D as texture ->
decodeTexture texture
|> Option.map (fun bytes -> new SpriteTexture(bytes, Avalonia.PixelSize(texture.Width, texture.Height)))
| _ -> None))
|> Option.map (fun texture ->
textures <- textures |> Map.add key texture
texture)
)
let getSpriteObjects (sf : SerializedFile) =
sf.Objects
|> Seq.where (fun o -> sf.GetTypeTreeRoot(o.Id).Type = "Sprite")
|> Seq.where (fun o ->
let sfReader = getReader sf.Path
TypeTreeValue.Get(sf, sfReader, o)
|> function
| :? Parsers.Sprite as s ->
if s.SpriteSettings.packed && s.SpriteSettings.packingMode = SpritePackingMode.Tight then
log $"Skipping tight-packed sprite {s.Name}"
false
else true
| _ -> false
)
|> Seq.toArray
let getSpriteObjectsInArchive (archive : UnityArchive) =
archive.Nodes
|> Seq.where (fun n -> n.Flags.HasFlag(ArchiveNodeFlags.SerializedFile))
|> Seq.map (fun n -> $"{UnityData.mountPoint}{n.Path}")
|> Seq.choose (fun path -> getSerializedFile path |> toOption)
|> Seq.map (fun sf -> sf, getSpriteObjects sf)
|> Seq.collect (fun (sf, ois) -> ois |> Seq.map (fun oi -> sf.Path, oi))
|> Seq.toArray
let getSprite (objectInfo : ObjectInfo) (sf : SerializedFile) =
let sfReader = getReader sf.Path
TypeTreeValue.Get(sf, sfReader, objectInfo)
|> function
| :? Parsers.Sprite as s -> Some (s, objectInfo)
| _ -> None
|> Option.bind (fun (s, o) ->
let name =
match s.ToDictionary().TryGetValue("m_Name") with
| true, name ->
Some (name.GetValue<string>())
| _ -> None
let atlas =
s.AtlasPtr
|> toOption
|> function
| Some ap when ap <> PPtr.NullPtr ->
dereference ap
// ap.TryDereference(getSerializedFile, getReader >> MicroOption.Some)
// |> toOption
|> Option.bind (function :? Parsers.SpriteAtlas as sa -> Some sa | _ -> None)
| _ -> None
#if DEBUG
name
|> Option.defaultValue ""
|> sprintf "Load sprite \"%s\""
|> log
#endif
let renderDataKey = s.RenderDataKey |> toOption
let sprite =
match atlas with
| Some atlas ->
renderDataKey
|> Option.bind (fun rdk ->
let succ, sad = atlas.RenderDataMap.TryGetValue(rdk)
if succ then Some sad else None)
|> Option.bind (fun sad ->
if sad.SpriteSettings.packed && sad.SpriteSettings.packingMode = SpritePackingMode.Tight then
log $"Sprite {s.Name()} packingMode = Tight. Rect may not be texture rect may not be valid"
let texture = sad.Texture |> getTexture
let rect = sad.TextureRect
let multiplier = sad.DownscaleMultiplier
texture
|> Option.map (fun texture -> texture, rect, multiplier))
|> Option.bind (fun (texture, rect, multiplier) ->
try
Sprite.Create(texture, rect |> toPixelRect multiplier) |> Some
with
:? System.ArgumentOutOfRangeException ->
#if DEBUG
if System.Diagnostics.Debugger.IsAttached then
System.Diagnostics.Debugger.Break()
#endif
s.TextureRect |> toOption |> Option.map (fun rect -> Sprite.Create(texture, rect |> toPixelRect 1f))
)
| None ->
s.TexturePtr
|> toOption
|> Option.bind getTexture
|> Option.map (fun texture ->
let rect =
s.Rect
|> toOption
|> function
| Some rect -> rect |> toPixelRect 1f
| None -> Avalonia.PixelRect(Avalonia.PixelPoint(0, 0), texture.Size)
Sprite.Create(texture, rect)
)
sprite
|> Option.map (fun sprite ->
{ sprite with
Name = name |> Option.defaultValue ""
RenderDataKey = renderDataKey
SerializedFile = sf.Path
PathID = o.Id
Container =
getContainerMap sf
|> Map.tryFind o.Id
|> Option.defaultValue ""
// getAllContainerMaps()
// |> Map.tryFind (sprite.SerializedFile, o.Id)
// |> Option.map (fun c -> c.Container)
// |> Option.defaultValue ""
BlueprintReference =
getAllBlueprintReferencedAssets()
|> Map.tryFind (sf.Path, o.Id)
|> Option.map (fun assetRef -> assetRef.AssetID, assetRef.FileID)
}
)
)