Move modules to CoreLoggerInstance

This commit is contained in:
JeremyStar™ 2024-04-08 21:30:24 +02:00
parent 39bc3f5872
commit 6bae282326
Signed by: JeremyStarTM
GPG key ID: E366BAEF67E4704D
6 changed files with 90 additions and 106 deletions

View file

@ -59,6 +59,9 @@ var custom_modules: Dictionary = {}
## Contains the node holding all custom modules as children.[br] ## Contains the node holding all custom modules as children.[br]
## [b]Danger: [i]Don't modify this.[/i][/b] ## [b]Danger: [i]Don't modify this.[/i][/b]
var custom_modules_node: Node var custom_modules_node: Node
## The CORE Object's logger instance.
## [b]Danger: [i]Don't modify this.[/i][/b]
var loggeri: CoreLoggerInstance
# +++ initialization +++ # +++ initialization +++
## Handles the preinitialization part. Does stuff like checking the engine version, loading the config and loading all modules into memory. ## Handles the preinitialization part. Does stuff like checking the engine version, loading the config and loading all modules into memory.
@ -77,6 +80,7 @@ func _ready() -> void:
inject_modules() inject_modules()
custom_modules_node.name = "Custom Modules" custom_modules_node.name = "Custom Modules"
add_child(custom_modules_node) add_child(custom_modules_node)
loggeri = logger.get_instance(basepath + "src/core.gd")
## Initializes all built-in modules during the preinitialization phase.[br] ## Initializes all built-in modules during the preinitialization phase.[br]
## [b]Danger: [i]Don't call this.[/i][/b] ## [b]Danger: [i]Don't call this.[/i][/b]
@ -122,37 +126,37 @@ func complete_init(no_success_message: bool = false) -> void:
# Initialization complete # Initialization complete
await get_tree().process_frame await get_tree().process_frame
if !no_success_message: logger.infof("core", "Initialized CORE successfully") if !no_success_message: loggeri.info("Initialized CORE successfully")
# +++ custom module support +++ # +++ custom module support +++
## Registers a new custom module. ## Registers a new custom module.
func register_custom_module(module_name: String, module_origin: String, module_class: CoreBaseModule) -> bool: func register_custom_module(module_name: String, module_origin: String, module_class: CoreBaseModule) -> bool:
logger.verbf("core", "Registering new custom module \"" + module_name + "\"") loggeri.verb("Registering new custom module \"" + module_name + "\"")
if !config.custom_modules: if !config.custom_modules:
logger.errorf("core", "Registering module failed: Custom module support is disabled.") loggeri.error("Registering module failed: Custom module support is disabled.")
return false return false
if custom_modules.has(module_name): if custom_modules.has(module_name):
logger.errorf("core", "Registering module failed: A custom module with the name \"" + module_name + "\" already exists.") loggeri.error("Registering module failed: A custom module with the name \"" + module_name + "\" already exists.")
return false return false
logger.diagf("core", "Updating variables") loggeri.diag("Updating variables")
module_class.name = module_name module_class.name = module_name
module_class.core = self module_class.core = self
module_class.loggeri = logger.get_instance(module_origin) module_class.loggeri = logger.get_instance(module_origin)
logger.diagf("core", "Adding module to SceneTree") loggeri.diag("Adding module to SceneTree")
custom_modules_node.add_child(module_class) custom_modules_node.add_child(module_class)
logger.diagf("core", "Merging module with custom_modules") loggeri.diag("Merging module with custom_modules")
custom_modules.merge({ module_name: module_class }) custom_modules.merge({ module_name: module_class })
logger.diagf("core", "Initializing custom module") loggeri.diag("Initializing custom module")
module_class._initialize() module_class._initialize()
logger.diagf("core", "Updating custom module configuration") loggeri.diag("Updating custom module configuration")
module_class._pull_config() module_class._pull_config()
return true return true
## Unregisters a custom module, making it no longer available. ## Unregisters a custom module, making it no longer available.
func unregister_custom_module(module_name: String) -> void: func unregister_custom_module(module_name: String) -> void:
logger.verbf("core", "Unregistering custom module \"" + module_name + "\"") loggeri.verb("Unregistering custom module \"" + module_name + "\"")
if !custom_modules.has(module_name): if !custom_modules.has(module_name):
logger.errorf("core", "Unregistering module failed: A custom module with the name \"" + module_name + "\" does not exist.") loggeri.error("Unregistering module failed: A custom module with the name \"" + module_name + "\" does not exist.")
return return
var module: Node = get_custom_module(module_name) var module: Node = get_custom_module(module_name)
await module._cleanup() await module._cleanup()
@ -164,9 +168,9 @@ func unregister_custom_module(module_name: String) -> void:
## Returns a registered custom module.[br] ## Returns a registered custom module.[br]
## Please note that you can't get CORE's built-in modules with this function. ## Please note that you can't get CORE's built-in modules with this function.
func get_custom_module(module_name: String) -> CoreBaseModule: func get_custom_module(module_name: String) -> CoreBaseModule:
logger.diagf("core", "Getting custom module \"" + module_name + "\"") loggeri.diag("Getting custom module \"" + module_name + "\"")
if !custom_modules.has(module_name): if !custom_modules.has(module_name):
logger.errorf("core", "Getting module failed: A custom module with the name \"" + module_name + "\" does not exist.") loggeri.error("Getting module failed: A custom module with the name \"" + module_name + "\" does not exist.")
return null return null
return custom_modules[module_name] return custom_modules[module_name]
@ -174,34 +178,34 @@ func get_custom_module(module_name: String) -> CoreBaseModule:
## Loads a (new) configuration object and applies it to all modules. ## Loads a (new) configuration object and applies it to all modules.
func reload_configuration(new_config: CoreConfiguration = CoreConfiguration.new()) -> void: func reload_configuration(new_config: CoreConfiguration = CoreConfiguration.new()) -> void:
var initialized = config != null var initialized = config != null
if initialized: logger.verbf("core", "Reloading CORE's configuration") if initialized: loggeri.verb("Reloading CORE's configuration")
if config != null: config.queue_free() if config != null: config.queue_free()
config = new_config config = new_config
if is_devmode(): # Override configuration in development mode if is_devmode(): # Override configuration in development mode
config.logger_level = CoreTypes.LoggerLevel.VERB config.logger_level = CoreTypes.LoggerLevel.VERB
if initialized: logger.verbf("core", "Overrode configuration (development mode)") if initialized: loggeri.verb("Overrode configuration (development mode)")
if initialized: apply_configuration() if initialized: apply_configuration()
## Applies the a configuration.[br] ## Applies the a configuration.[br]
## [b]Danger: [i]Don't call this.[/i][/b] ## [b]Danger: [i]Don't call this.[/i][/b]
func apply_configuration() -> void: func apply_configuration() -> void:
logger.verbf("core", "Applying configuration") if loggeri != null: loggeri.verb("Applying configuration")
if is_devmode(): logger.warnf("core", "The CORE Framework is in development mode. Here be dragons!") if is_devmode(): if loggeri != null: loggeri.warn("The CORE Framework is in development mode. Here be dragons!")
if config.headless: logger.warnf("core", "CORE is in headless mode. Certain modules will not work as expected.") if config.headless: loggeri.warn("CORE is in headless mode. Certain modules will not work as expected.")
if !config.custom_modules: if !config.custom_modules:
logger.verbf("core", "Removing all custom modules (custom modules support is disabled)") if loggeri != null: loggeri.verb("Removing all custom modules (custom modules support is disabled)")
for module in custom_modules: unregister_custom_module(module) for module in custom_modules: unregister_custom_module(module)
for module in modules: get(module)._pull_config() for module in modules: get(module)._pull_config()
if config.custom_modules: if config.custom_modules:
for module in custom_modules: for module in custom_modules:
logger.diagf("core", "Updating configuration for custom module \"" + module.name + "\"") if loggeri != null: loggeri.diag("Updating configuration for custom module \"" + module.name + "\"")
module._pull_config() module._pull_config()
# +++ etc ++ # +++ etc ++
## Makes sure that CORE does not leak memory on shutdown/unload.[br] ## Makes sure that CORE does not leak memory on shutdown/unload.[br]
## Unloads all custom modules, built-in modules, frees any of CORE's classes and lastly itself. ## Unloads all custom modules, built-in modules, frees any of CORE's classes and lastly itself.
func cleanup() -> void: func cleanup() -> void:
logger.infof("core", "Cleaning up") loggeri.info("Cleaning up")
config.queue_free() config.queue_free()
var modules_reverse: Array[String] = modules.duplicate() var modules_reverse: Array[String] = modules.duplicate()
modules_reverse.reverse() modules_reverse.reverse()
@ -247,7 +251,7 @@ func get_formatted_string(string: String) -> String:
CoreTypes.VersionType.ALPHA: CoreTypes.VersionType.ALPHA:
string = string.replace("%version_type%", "Alpha") string = string.replace("%version_type%", "Alpha")
string = string.replace("%version_type_technical%", "a") string = string.replace("%version_type_technical%", "a")
_: await logger.crashf("core", "Invalid version type " + str(version_type), true) _: await loggeri.crash("Invalid version type " + str(version_type))
# Development mode # Development mode
if is_devmode(): string = string.replace("%devmode%", "Enabled") if is_devmode(): string = string.replace("%devmode%", "Enabled")
else: string = string.replace("%devmode%", "Disabled") else: string = string.replace("%devmode%", "Disabled")

View file

@ -57,11 +57,11 @@ func _cleanup() -> void:
## [/codeblock] ## [/codeblock]
## [b]Note: [i]Using the [code]await[/code] keyword is required for this function.[/i][/b] ## [b]Note: [i]Using the [code]await[/code] keyword is required for this function.[/i][/b]
func awaited_request(url: String, parse_utf8: bool, method: HTTPClient.Method = HTTPClient.Method.METHOD_GET, headers: PackedStringArray = PackedStringArray([]), data: String = "") -> Dictionary: func awaited_request(url: String, parse_utf8: bool, method: HTTPClient.Method = HTTPClient.Method.METHOD_GET, headers: PackedStringArray = PackedStringArray([]), data: String = "") -> Dictionary:
logger.verbf("erm", "Creating awaited request") loggeri.verb("Creating awaited request")
if !await is_url_allowed(url): return {} if !await is_url_allowed(url): return {}
var id: int = create_request(url, method, headers, data) var id: int = create_request(url, method, headers, data)
start_request(id, parse_utf8) start_request(id, parse_utf8)
logger.diagf("erm", "Waiting for request " + str(id) + " to finish") loggeri.diag("Waiting for request " + str(id) + " to finish")
while !is_request_completed(id): await get_tree().create_timer(0.1, true).timeout while !is_request_completed(id): await get_tree().create_timer(0.1, true).timeout
var dldata: Dictionary = list_complete[id] var dldata: Dictionary = list_complete[id]
list_complete.erase(id) list_complete.erase(id)
@ -96,7 +96,7 @@ func oneline_awaited_request(url: String, return_utf8: bool = true, ignore_http_
## [/codeblock] ## [/codeblock]
## [b]Note: [i]Using the [code]await[/code] keyword is required for this function.[/i][/b] ## [b]Note: [i]Using the [code]await[/code] keyword is required for this function.[/i][/b]
func batch_awaited_request(urls: PackedStringArray, parse_utf8: bool, method: HTTPClient.Method = HTTPClient.Method.METHOD_GET, headers: PackedStringArray = PackedStringArray([]), data: String = "") -> Array[Dictionary]: func batch_awaited_request(urls: PackedStringArray, parse_utf8: bool, method: HTTPClient.Method = HTTPClient.Method.METHOD_GET, headers: PackedStringArray = PackedStringArray([]), data: String = "") -> Array[Dictionary]:
logger.verbf("erm", "Creating " + str(urls.size()) + " awaited request(s)") loggeri.verb("Creating " + str(urls.size()) + " awaited request(s)")
var dldata: Array[Dictionary] = [] var dldata: Array[Dictionary] = []
for url in urls: for url in urls:
if !await is_url_allowed(url): continue if !await is_url_allowed(url): continue
@ -111,7 +111,7 @@ func batch_awaited_request(urls: PackedStringArray, parse_utf8: bool, method: HT
func _batch_awaited_request(url: String, parse_utf8: bool, method: HTTPClient.Method = HTTPClient.Method.METHOD_GET, headers: PackedStringArray = PackedStringArray([]), data: String = "") -> int: func _batch_awaited_request(url: String, parse_utf8: bool, method: HTTPClient.Method = HTTPClient.Method.METHOD_GET, headers: PackedStringArray = PackedStringArray([]), data: String = "") -> int:
var id: int = create_request(url, method, headers, data) var id: int = create_request(url, method, headers, data)
start_request(id, parse_utf8) start_request(id, parse_utf8)
logger.diagf("erm", "Waiting for request " + str(id) + " to finish") loggeri.diag("Waiting for request " + str(id) + " to finish")
while !is_request_completed(id): await get_tree().create_timer(0.1, true).timeout while !is_request_completed(id): await get_tree().create_timer(0.1, true).timeout
return id return id
@ -121,15 +121,15 @@ func _batch_awaited_request(url: String, parse_utf8: bool, method: HTTPClient.Me
func generate_id() -> int: func generate_id() -> int:
var id = randi() var id = randi()
if list_queue.has(id) or list_active.has(id): if list_queue.has(id) or list_active.has(id):
logger.warnf("erm", "New download id '" + str(id) + "' is already taken") loggeri.warn("New download id '" + str(id) + "' is already taken")
return generate_id() return generate_id()
logger.diagf("erm", "Generated new download id " + str(id)) loggeri.diag("Generated new download id " + str(id))
return id return id
## Creates a new request and stores it in the queue. Returns the download id.[br] ## Creates a new request and stores it in the queue. Returns the download id.[br]
## [b]Warning: [i]You'll probably not need this. Only use this function when implementing your own downloading method.[/i][/b] ## [b]Warning: [i]You'll probably not need this. Only use this function when implementing your own downloading method.[/i][/b]
func create_request(url: String, method: HTTPClient.Method = HTTPClient.Method.METHOD_GET, headers: PackedStringArray = PackedStringArray([]), body: String = "") -> int: func create_request(url: String, method: HTTPClient.Method = HTTPClient.Method.METHOD_GET, headers: PackedStringArray = PackedStringArray([]), body: String = "") -> int:
logger.verbf("erm", "Creating new request\n-> URL: " + url + "\n-> Method: " + str(method) + "\nHeaders: " + str(headers.size()) + "\nBody size: " + str(body.length()) + " Characters") loggeri.verb("Creating new request\n-> URL: " + url + "\n-> Method: " + str(method) + "\nHeaders: " + str(headers.size()) + "\nBody size: " + str(body.length()) + " Characters")
var id = generate_id() var id = generate_id()
list_queue.merge({ id: { "url": url, "method": method, "headers": headers, "body": body } }) list_queue.merge({ id: { "url": url, "method": method, "headers": headers, "body": body } })
return id return id
@ -138,16 +138,16 @@ func create_request(url: String, method: HTTPClient.Method = HTTPClient.Method.M
## [b]Note: [i]Using the [code]await[/code] keyword is required for this function.[/i][/b][br] ## [b]Note: [i]Using the [code]await[/code] keyword is required for this function.[/i][/b][br]
## [b]Warning: [i]You'll probably not need this. Only use this function when implementing your own downloading method.[/i][/b] ## [b]Warning: [i]You'll probably not need this. Only use this function when implementing your own downloading method.[/i][/b]
func start_request(id: int, parse_utf8: bool) -> void: func start_request(id: int, parse_utf8: bool) -> void:
logger.verbf("erm", "Starting request " + str(id)) loggeri.verb("Starting request " + str(id))
list_active.merge({ id: list_queue[id] }) list_active.merge({ id: list_queue[id] })
list_queue.erase(id) list_queue.erase(id)
logger.diagf("erm", "Creating new HTTPRequest \"Request #" + str(id) + "\"") loggeri.diag("Creating new HTTPRequest \"Request #" + str(id) + "\"")
var download: HTTPRequest = HTTPRequest.new() var download: HTTPRequest = HTTPRequest.new()
download.name = "Request #" + str(id) download.name = "Request #" + str(id)
download.accept_gzip = true download.accept_gzip = true
download.use_threads = true download.use_threads = true
var lambda: Callable = func(result: int, http_code: int, headers: PackedStringArray, body: PackedByteArray, httprequest: HTTPRequest) -> void: var lambda: Callable = func(result: int, http_code: int, headers: PackedStringArray, body: PackedByteArray, httprequest: HTTPRequest) -> void:
logger.verbf("erm", "Request " + str(id) + " completed\nResult: " + str(result) + "\nHTTP response code: " + str(http_code) + "\nHeaders: " + str(headers.size()) + "\nBody size: " + str(body.size()) + " Bytes // " + str(core.misc.byte2mib(body.size(), true)) + " MiB\nParse body as UTF-8: " + str(parse_utf8)) loggeri.verb("Request " + str(id) + " completed\nResult: " + str(result) + "\nHTTP response code: " + str(http_code) + "\nHeaders: " + str(headers.size()) + "\nBody size: " + str(body.size()) + " Bytes // " + str(core.misc.byte2mib(body.size(), true)) + " MiB\nParse body as UTF-8: " + str(parse_utf8))
list_complete.merge({ id: { "result": result, "http_code": http_code, "headers": headers, "body": body, "body_utf8": body.get_string_from_utf8() if parse_utf8 else "" } }) list_complete.merge({ id: { "result": result, "http_code": http_code, "headers": headers, "body": body, "body_utf8": body.get_string_from_utf8() if parse_utf8 else "" } })
list_active.erase(id) list_active.erase(id)
remove_child(httprequest) remove_child(httprequest)
@ -161,14 +161,14 @@ func is_url_allowed(url: String) -> bool:
if url.begins_with("http://"): if url.begins_with("http://"):
match(config_unsecure_requests): match(config_unsecure_requests):
CoreTypes.BlockadeLevel.BLOCK: CoreTypes.BlockadeLevel.BLOCK:
logger.errorf("erm", "Blocked unsecure url '" + url + "'") loggeri.error("Blocked unsecure url '" + url + "'")
return false return false
CoreTypes.BlockadeLevel.WARN: logger.warnf("erm", "Requesting unsecure url '" + url + "'") CoreTypes.BlockadeLevel.WARN: loggeri.warn("Requesting unsecure url '" + url + "'")
CoreTypes.BlockadeLevel.IGNORE: pass CoreTypes.BlockadeLevel.IGNORE: pass
_: await logger.crashf("erm", "Invalid BlockadeLevel '" + str(config_unsecure_requests) + "'") _: await loggeri.crash("Invalid BlockadeLevel '" + str(config_unsecure_requests) + "'")
elif url.begins_with("https://"): pass elif url.begins_with("https://"): pass
else: else:
logger.errorf("erm", "Invalid url '" + url + "'") loggeri.error("Invalid url '" + url + "'")
return false return false
return true return true
@ -177,10 +177,10 @@ func is_request_completed(id: int) -> bool: return list_complete.has(id)
## Cleans the request queue. ## Cleans the request queue.
func clean_queue() -> void: func clean_queue() -> void:
logger.verbf("erm", "Cleaning request queue") loggeri.verb("Cleaning request queue")
list_queue.clear() list_queue.clear()
## Cleans the completed requests list. ## Cleans the completed requests list.
func clean_completed() -> void: func clean_completed() -> void:
logger.verbf("erm", "Cleaning completed requests") loggeri.verb("Cleaning completed requests")
list_complete.clear() list_complete.clear()

View file

@ -193,26 +193,6 @@ STACKTRACE
# Shutdown # Shutdown
await core.misc.quit_safely(69) await core.misc.quit_safely(69)
# Deprecated functions, will be removed soon
## Deprecated framework call
## @deprecated
func diagf(origin: String, message: String) -> void: _log(CoreTypes.LoggerLevel.DIAG, core.basepath.replace("res://", "") + "src/" + origin + ".gd", message)
## Deprecated framework call
## @deprecated
func verbf(origin: String, message: String) -> void: _log(CoreTypes.LoggerLevel.VERB, core.basepath.replace("res://", "") + "src/" + origin + ".gd", message)
## Deprecated framework call
## @deprecated
func infof(origin: String, message: String) -> void: _log(CoreTypes.LoggerLevel.INFO, core.basepath.replace("res://", "") + "src/" + origin + ".gd", message)
## Deprecated framework call
## @deprecated
func warnf(origin: String, message: String) -> void: _log(CoreTypes.LoggerLevel.WARN, core.basepath.replace("res://", "") + "src/" + origin + ".gd", message)
## Deprecated framework call
## @deprecated
func errorf(origin: String, message: String) -> void: _log(CoreTypes.LoggerLevel.ERROR, core.basepath.replace("res://", "") + "src/" + origin + ".gd", message)
## Deprecated framework call
## @deprecated
func crashf(origin: String, message: String) -> void: crash(core.basepath.replace("res://", "") + "src/" + origin + ".gd", message)
# +++ etc +++ # +++ etc +++
## Checks if the specified log level is allowed by the current configuration. ## Checks if the specified log level is allowed by the current configuration.
func is_level_allowed(level: CoreTypes.LoggerLevel) -> bool: func is_level_allowed(level: CoreTypes.LoggerLevel) -> bool:

View file

@ -72,10 +72,10 @@ func format_stringarray(array: Array[String], item_before: String = "", item_aft
var output: String = "" var output: String = ""
if array.size() == 0: if array.size() == 0:
logger.warnf("misc", "Unable to format a string with a size of 0") loggeri.warn("Unable to format a string with a size of 0")
return "" return ""
elif array.size() == 1: elif array.size() == 1:
logger.warnf("misc", "Unable to format a string with a size of 1") loggeri.warn("Unable to format a string with a size of 1")
return array[0] return array[0]
for item in array: for item in array:
@ -129,7 +129,7 @@ func get_center(parent_size: Vector2, child_size: Vector2) -> Vector2:
## Using [method SceneTree.quit] directly may cause various issues.[br] ## Using [method SceneTree.quit] directly may cause various issues.[br]
## [b]Note: [i]Using the [code]await[/code] keyword is required for this function.[/i][/b] ## [b]Note: [i]Using the [code]await[/code] keyword is required for this function.[/i][/b]
func quit_safely(exitcode: int = 0) -> void: func quit_safely(exitcode: int = 0) -> void:
logger.infof("misc", "Shutting down (code " + str(exitcode) + ")") loggeri.info("Shutting down (code " + str(exitcode) + ")")
await get_tree().create_timer(0.25).timeout await get_tree().create_timer(0.25).timeout
await core.cleanup() await core.cleanup()
get_tree().quit(exitcode) get_tree().quit(exitcode)

View file

@ -59,19 +59,19 @@ func _cleanup() -> void:
func _pull_config() -> void: func _pull_config() -> void:
if core.config.headless: if core.config.headless:
# Remove all scenes # Remove all scenes
if is_inside_tree(): logger.verbf("sms", "Removing all scenes (triggered by headless mode)") if is_inside_tree(): loggeri.verb("Removing all scenes (triggered by headless mode)")
for scene in scenes: remove_scene(scene, true) for scene in scenes: remove_scene(scene, true)
# +++ scene management +++ # +++ scene management +++
## Adds a scene to some scene collection. ## Adds a scene to some scene collection.
func add_scene(sname: String, sclass: Node, type: CoreTypes.SceneType) -> bool: func add_scene(sname: String, sclass: Node, type: CoreTypes.SceneType) -> bool:
if core.config.headless: return false if core.config.headless: return false
logger.verbf("sms", "Adding scene \"" + sname + "\" of type " + str(type)) loggeri.verb("Adding scene \"" + sname + "\" of type " + str(type))
if exists(sname) != CoreTypes.SceneType.NONE: if exists(sname) != CoreTypes.SceneType.NONE:
logger.errorf("sms", "Scene with name \"" + sname + "\" already exists") loggeri.error("Scene with name \"" + sname + "\" already exists")
return false return false
if typeof(sclass) != TYPE_OBJECT or !sclass.is_class("Node"): if typeof(sclass) != TYPE_OBJECT or !sclass.is_class("Node"):
logger.errorf("sms", "Scene class \"" + sname + "\" is not of type Node") loggeri.error("Scene class \"" + sname + "\" is not of type Node")
return false return false
sclass.name = sname sclass.name = sname
match(type): match(type):
@ -81,9 +81,9 @@ func add_scene(sname: String, sclass: Node, type: CoreTypes.SceneType) -> bool:
CoreTypes.SceneType.MAIN: scenes_main.add_child(sclass) CoreTypes.SceneType.MAIN: scenes_main.add_child(sclass)
CoreTypes.SceneType.BACKGROUND: scenes_background.add_child(sclass) CoreTypes.SceneType.BACKGROUND: scenes_background.add_child(sclass)
CoreTypes.SceneType.NONE: CoreTypes.SceneType.NONE:
logger.errorf("sms", "CoreTypes.SceneType.NONE is not a valid scene type") loggeri.error("CoreTypes.SceneType.NONE is not a valid scene type")
return false return false
_: await logger.crashf("sms", "Invalid SceneType " + str(type), true) _: await loggeri.crash("Invalid SceneType " + str(type))
scenes.merge({ sname: { "type": type, "class": sclass } }) scenes.merge({ sname: { "type": type, "class": sclass } })
return true return true
@ -91,8 +91,8 @@ func add_scene(sname: String, sclass: Node, type: CoreTypes.SceneType) -> bool:
## [b]Danger: [i]Don't set [code]force_remove[/code] to [code]true[/code], thanks![/i][/b] ## [b]Danger: [i]Don't set [code]force_remove[/code] to [code]true[/code], thanks![/i][/b]
func remove_scene(sname: String, force_remove: bool = false) -> bool: func remove_scene(sname: String, force_remove: bool = false) -> bool:
if core.config.headless and !force_remove: return false if core.config.headless and !force_remove: return false
if force_remove: await logger.crashf("sms", "force_remove = true is not allowed", true) if force_remove: await loggeri.crash("force_remove = true is not allowed")
logger.verbf("sms", "Removing scene \"" + sname + "\"") loggeri.verb("Removing scene \"" + sname + "\"")
match(exists(sname)): match(exists(sname)):
CoreTypes.SceneType.DEBUG: CoreTypes.SceneType.DEBUG:
scenes_debug.remove_child(scenes[sname]["class"]) scenes_debug.remove_child(scenes[sname]["class"])
@ -110,9 +110,9 @@ func remove_scene(sname: String, force_remove: bool = false) -> bool:
scenes_background.remove_child(scenes[sname]["class"]) scenes_background.remove_child(scenes[sname]["class"])
scenes[sname]["class"].queue_free() scenes[sname]["class"].queue_free()
CoreTypes.SceneType.NONE: CoreTypes.SceneType.NONE:
logger.errorf("sms", "Scene \"" + sname + "\" does not exist") loggeri.error("Scene \"" + sname + "\" does not exist")
return false return false
_: await logger.crashf("sms", "Invalid SceneType " + str(exists(sname)), true) _: await loggeri.crash("Invalid SceneType " + str(exists(sname)))
scenes.erase(sname) scenes.erase(sname)
return true return true
@ -128,8 +128,8 @@ func get_scene(sname: String) -> Node:
CoreTypes.SceneType.MENU: return scenes[sname]["class"] CoreTypes.SceneType.MENU: return scenes[sname]["class"]
CoreTypes.SceneType.MAIN: return scenes[sname]["class"] CoreTypes.SceneType.MAIN: return scenes[sname]["class"]
CoreTypes.SceneType.BACKGROUND: return scenes[sname]["class"] CoreTypes.SceneType.BACKGROUND: return scenes[sname]["class"]
CoreTypes.SceneType.NONE: logger.errorf("sms", "Scene \"" + sname + "\" does not exist") CoreTypes.SceneType.NONE: loggeri.error("Scene \"" + sname + "\" does not exist")
_: await logger.crashf("sms", "Invalid SceneType " + str(exists(sname)), true) _: await loggeri.crash("Invalid SceneType " + str(exists(sname)))
return null return null
## Returns a scene collection node.[br] ## Returns a scene collection node.[br]
@ -143,8 +143,8 @@ func get_scene_collection(type: CoreTypes.SceneType) -> Node:
CoreTypes.SceneType.MENU: return scenes_menu CoreTypes.SceneType.MENU: return scenes_menu
CoreTypes.SceneType.MAIN: return scenes_main CoreTypes.SceneType.MAIN: return scenes_main
CoreTypes.SceneType.BACKGROUND: return scenes_background CoreTypes.SceneType.BACKGROUND: return scenes_background
CoreTypes.SceneType.NONE: logger.errorf("sms", "No scene collection was found for CoreTypes.SceneType.NONE") CoreTypes.SceneType.NONE: loggeri.error("No scene collection was found for CoreTypes.SceneType.NONE")
_: await logger.crashf("sms", "Invalid SceneType " + str(type), true) _: await loggeri.crash("Invalid SceneType " + str(type))
return null return null
## Returns a list of all loaded scenes in some scene collection. ## Returns a list of all loaded scenes in some scene collection.

View file

@ -34,40 +34,40 @@ var storage_location: String = ""
## Opens a storage file into memory. ## Opens a storage file into memory.
func open_storage(location: String, create_new: bool = true, sanity_check: bool = true, fail_on_sanity_check: bool = false) -> bool: func open_storage(location: String, create_new: bool = true, sanity_check: bool = true, fail_on_sanity_check: bool = false) -> bool:
if is_open: if is_open:
logger.errorf("storage", "Failed to open storage: A storage file is already open") loggeri.error("Failed to open storage: A storage file is already open")
return false return false
logger.verbf("storage", "Opening storage file at \"" + location + "\"") loggeri.verb("Opening storage file at \"" + location + "\"")
var file: FileAccess var file: FileAccess
if !FileAccess.file_exists(location): if !FileAccess.file_exists(location):
if create_new: if create_new:
file = FileAccess.open(location, FileAccess.WRITE) file = FileAccess.open(location, FileAccess.WRITE)
if file == null: if file == null:
await logger.crashf("storage", "Could not open storage file at \"" + location + "\": Failed with code " + str(FileAccess.get_open_error())) await loggeri.crash("Could not open storage file at \"" + location + "\": Failed with code " + str(FileAccess.get_open_error()))
return false return false
file.store_string("{}") file.store_string("{}")
file.close() file.close()
else: else:
logger.errorf("storage", "Failed to open storage: create_new is set to false") loggeri.error("Failed to open storage: create_new is set to false")
return false return false
file = FileAccess.open(location, FileAccess.READ) file = FileAccess.open(location, FileAccess.READ)
var storage_temp: Variant = file.get_as_text() var storage_temp: Variant = file.get_as_text()
file.close() file.close()
storage_temp = JSON.parse_string(storage_temp) storage_temp = JSON.parse_string(storage_temp)
if typeof(storage_temp) != TYPE_DICTIONARY: if typeof(storage_temp) != TYPE_DICTIONARY:
logger.errorf("storage", "Failed to open storage: Parsed storage file is of type " + str(typeof(storage_temp))) loggeri.error("Failed to open storage: Parsed storage file is of type " + str(typeof(storage_temp)))
return false return false
if sanity_check: if sanity_check:
var check_result: Array[String] = perform_sanity_check(storage_temp) var check_result: Array[String] = perform_sanity_check(storage_temp)
if check_result.size() != 0: if check_result.size() != 0:
if fail_on_sanity_check: if fail_on_sanity_check:
logger.errorf("storage", "Sanity check failed (stopping):") loggeri.error("Sanity check failed (stopping):")
for error in check_result: for error in check_result:
logger.errorf("storage", "-> " + error) loggeri.error("-> " + error)
return false return false
else: else:
logger.warnf("storage", "Sanity check failed (continuing anyway):") loggeri.warn("Sanity check failed (continuing anyway):")
for error in check_result: for error in check_result:
logger.warnf("storage", "-> " + error) loggeri.warn("-> " + error)
storage = storage_temp storage = storage_temp
storage_location = location storage_location = location
is_open = true is_open = true
@ -76,9 +76,9 @@ func open_storage(location: String, create_new: bool = true, sanity_check: bool
## Closes the active storage file. ## Closes the active storage file.
func close_storage() -> bool: func close_storage() -> bool:
if !is_open: if !is_open:
logger.errorf("storage", "Failed to close storage: No storage file is open") loggeri.error("Failed to close storage: No storage file is open")
return false return false
logger.verbf("storage", "Closing storage file") loggeri.verb("Closing storage file")
storage = {} storage = {}
is_open = false is_open = false
return true return true
@ -86,13 +86,13 @@ func close_storage() -> bool:
## Saves the active storage file to disk. ## Saves the active storage file to disk.
func save_storage() -> bool: func save_storage() -> bool:
if !is_open: if !is_open:
logger.errorf("storage", "Failed to save storage: No storage file is open") loggeri.error("Failed to save storage: No storage file is open")
return false return false
var file: FileAccess = FileAccess.open(storage_location, FileAccess.WRITE) var file: FileAccess = FileAccess.open(storage_location, FileAccess.WRITE)
if file == null: if file == null:
await logger.crashf("storage", "Could not open storage file at \"" + storage_location + "\": Failed with code " + str(FileAccess.get_open_error())) await loggeri.crash("Could not open storage file at \"" + storage_location + "\": Failed with code " + str(FileAccess.get_open_error()))
return false return false
logger.diagf("storage", "Writing storage file to disk") loggeri.diag("Writing storage file to disk")
file.store_string(JSON.stringify(storage)) file.store_string(JSON.stringify(storage))
file.close() file.close()
return true return true
@ -101,9 +101,9 @@ func save_storage() -> bool:
## Removes all keys from the active storage file. The nuclear option basically. ## Removes all keys from the active storage file. The nuclear option basically.
func nuke_storage(autosave: bool = true) -> bool: func nuke_storage(autosave: bool = true) -> bool:
if !is_open: if !is_open:
logger.errorf("storage", "Failed to nuke storage: No storage file is open") loggeri.error("Failed to nuke storage: No storage file is open")
return false return false
logger.warnf("storage", "Nuking storage") loggeri.warn("Nuking storage")
storage = {} storage = {}
if autosave: save_storage() if autosave: save_storage()
return true return true
@ -111,17 +111,17 @@ func nuke_storage(autosave: bool = true) -> bool:
## Returns a storage key. Can also return a default value if unset. ## Returns a storage key. Can also return a default value if unset.
func get_key(key: String, default: Variant = null) -> Variant: func get_key(key: String, default: Variant = null) -> Variant:
if !is_open: if !is_open:
logger.errorf("storage", "Failed to get key: No storage file is open") loggeri.error("Failed to get key: No storage file is open")
return NAN return NAN
logger.diagf("storage", "Returning storage key \"" + key + "\" (default='" + str(default) + "')") loggeri.diag("Returning storage key \"" + key + "\" (default='" + str(default) + "')")
return storage.get(key, default) return storage.get(key, default)
## Updates a storage key with the specified value. ## Updates a storage key with the specified value.
func set_key(key: String, value: Variant, overwrite: bool = true, autosave: bool = true) -> bool: func set_key(key: String, value: Variant, overwrite: bool = true, autosave: bool = true) -> bool:
if !is_open: if !is_open:
logger.errorf("storage", "Failed to set key: No storage file is open") loggeri.error("Failed to set key: No storage file is open")
return false return false
logger.diagf("storage", "Updating storage key \"" + key + "\" with value '" + str(value) + "' (overwrite='" + str(overwrite) + "' autosave='" + str(autosave) + "'") loggeri.diag("Updating storage key \"" + key + "\" with value '" + str(value) + "' (overwrite='" + str(overwrite) + "' autosave='" + str(autosave) + "'")
storage.merge({key: value}, overwrite) storage.merge({key: value}, overwrite)
if autosave: save_storage() if autosave: save_storage()
return true return true
@ -131,7 +131,7 @@ func del_key(key: String, autosave: bool = true) -> bool:
if !is_open: if !is_open:
logger.errof("storage", "Failed to delete key: No storage file is open") logger.errof("storage", "Failed to delete key: No storage file is open")
return false return false
logger.diagf("storage", "Deleting storage key \"" + key + "\" (autosave='" + str(autosave) + "')") loggeri.diag("Deleting storage key \"" + key + "\" (autosave='" + str(autosave) + "')")
storage.erase(key) storage.erase(key)
if autosave: save_storage() if autosave: save_storage()
return true return true
@ -141,30 +141,30 @@ func del_key(key: String, autosave: bool = true) -> bool:
## pass your modified [class Dictionary to [method safe_dict]. ## pass your modified [class Dictionary to [method safe_dict].
func get_dict() -> Dictionary: func get_dict() -> Dictionary:
if !is_open: if !is_open:
logger.errorf("storage", "Failed to get dictionary: No storage file is open") loggeri.error("Failed to get dictionary: No storage file is open")
return {} return {}
logger.verbf("storage", "Returning storage dictionary") loggeri.verb("Returning storage dictionary")
return storage return storage
# +++ raw manipulation +++ # +++ raw manipulation +++
## Saves a arbitrary dictionary as a [param storage] [class Dictionary] with sanity checking ([code]sanity_check[/code] and [code]fail_on_sanity_check[/code]). ## Saves a arbitrary dictionary as a [param storage] [class Dictionary] with sanity checking ([code]sanity_check[/code] and [code]fail_on_sanity_check[/code]).
func save_dict(dict: Dictionary, sanity_check: bool = true, fail_on_sanity_check: bool = false, autosave: bool = true) -> bool: func save_dict(dict: Dictionary, sanity_check: bool = true, fail_on_sanity_check: bool = false, autosave: bool = true) -> bool:
if !is_open: if !is_open:
logger.errorf("storage", "Failed to save dictionary: No storage file is open") loggeri.error("Failed to save dictionary: No storage file is open")
return false return false
logger.verbf("storage", "Saving custom dictionary as storage") loggeri.verb("Saving custom dictionary as storage")
if sanity_check: if sanity_check:
var check_result: Array[String] = perform_sanity_check(dict) var check_result: Array[String] = perform_sanity_check(dict)
if check_result.size() != 0: if check_result.size() != 0:
if fail_on_sanity_check: if fail_on_sanity_check:
logger.errorf("storage", "Sanity check failed (stopping):") loggeri.error("Sanity check failed (stopping):")
for error in check_result: for error in check_result:
logger.errorf("storage", "-> " + error) loggeri.error("-> " + error)
return false return false
else: else:
logger.warnf("storage", "Sanity check failed (continuing anyway):") loggeri.warn("Sanity check failed (continuing anyway):")
for error in check_result: for error in check_result:
logger.warnf("storage", "-> " + error) loggeri.warn("-> " + error)
storage = dict storage = dict
if autosave: save_storage() if autosave: save_storage()
return true return true
@ -172,7 +172,7 @@ func save_dict(dict: Dictionary, sanity_check: bool = true, fail_on_sanity_check
# +++ etc +++ # +++ etc +++
## Performs sanity checks on a [class Dictionary] to determine if it can be saved and loaded using this module. ## Performs sanity checks on a [class Dictionary] to determine if it can be saved and loaded using this module.
func perform_sanity_check(storage_check: Dictionary) -> Array[String]: func perform_sanity_check(storage_check: Dictionary) -> Array[String]:
logger.verbf("storage", "Performing a sanity check on some storage dictionary") loggeri.verb("Performing a sanity check on some storage dictionary")
var errors: Array[String] = [] var errors: Array[String] = []
for key in storage_check: for key in storage_check:
if typeof(key) != TYPE_STRING: if typeof(key) != TYPE_STRING:
@ -181,5 +181,5 @@ func perform_sanity_check(storage_check: Dictionary) -> Array[String]:
if typeof(storage_check[key]) != TYPE_NIL and typeof(storage_check[key]) != TYPE_STRING and typeof(storage_check[key]) != TYPE_INT and typeof(storage_check[key]) != TYPE_FLOAT and typeof(storage_check[key]) != TYPE_BOOL and typeof(storage_check[key]) != TYPE_ARRAY and typeof(storage_check[key]) != TYPE_DICTIONARY: if typeof(storage_check[key]) != TYPE_NIL and typeof(storage_check[key]) != TYPE_STRING and typeof(storage_check[key]) != TYPE_INT and typeof(storage_check[key]) != TYPE_FLOAT and typeof(storage_check[key]) != TYPE_BOOL and typeof(storage_check[key]) != TYPE_ARRAY and typeof(storage_check[key]) != TYPE_DICTIONARY:
errors.append("The value of \"" + key + "\" is not null, a string, an integer, a float, boolean, array or dictionary (type '" + type_string(typeof(key)) + "')") errors.append("The value of \"" + key + "\" is not null, a string, an integer, a float, boolean, array or dictionary (type '" + type_string(typeof(key)) + "')")
logger.verbf("storage", "Completed sanity check with " + str(errors.size()) + " errors") loggeri.verb("Completed sanity check with " + str(errors.size()) + " errors")
return errors return errors