RapidGameFramework
Reusable Godot managers for data-driven small games
Loading...
Searching...
No Matches
data_cache_manager.gd
Go to the documentation of this file.
1extends RefCounted
2
3
9
10var json_cache:Dictionary = {}
11var cache_hits:int = 0
12var cache_misses:int = 0
13
14
15
16func load_json(path:String) -> Dictionary:
17 var parsed = load_data(path)
18 if parsed is Dictionary:
19 return parsed
20 return {}
21
22
23
24func load_data(path:String):
25 if path == "":
26 return {}
27 if json_cache.has(path):
28 cache_hits += 1
29 return _duplicate_cached(json_cache[path])
30 cache_misses += 1
31 var file := FileAccess.open(path, FileAccess.READ)
32 if file == null:
33 json_cache[path] = {}
34 return {}
35 var parsed = JSON.parse_string(file.get_as_text())
36 if not parsed is Dictionary and not parsed is Array:
37 json_cache[path] = {}
38 return {}
39 json_cache[path] = parsed.duplicate(true)
40 return _duplicate_cached(json_cache[path])
41
42
43
44func load_array(path:String, key:String, fallback:Array = []) -> Array:
45 var data := load_json(path)
46 if data.has(key) and data[key] is Array:
47 return data[key].duplicate(true)
48 return fallback.duplicate(true)
49
50
51
52func load_root_array(path:String, fallback:Array = []) -> Array:
53 var data = load_data(path)
54 if data is Array:
55 return data.duplicate(true)
56 return fallback.duplicate(true)
57
58
59
60func invalidate(path:String) -> void:
61 json_cache.erase(path)
62
63
64
65func clear() -> void:
66 json_cache.clear()
67 cache_hits = 0
68 cache_misses = 0
69
70
71
72func get_cache_state() -> Dictionary:
73 return {
74 "entries": json_cache.size(),
75 "paths": json_cache.keys(),
76 "cache_hits": cache_hits,
77 "cache_misses": cache_misses
78 }
79
80
81
82func get_cache_stats() -> Dictionary:
83 return {
84 "entries": json_cache.size(),
85 "cache_hits": cache_hits,
86 "cache_misses": cache_misses
87 }
88
89
90func _duplicate_cached(value):
91 if value is Dictionary or value is Array:
92 return value.duplicate(true)
93 return value