diff --git a/src/classes/Basemodule.gd b/src/classes/basemodule.gd similarity index 86% rename from src/classes/Basemodule.gd rename to src/classes/basemodule.gd index 0117e8d..947e828 100644 --- a/src/classes/Basemodule.gd +++ b/src/classes/basemodule.gd @@ -15,9 +15,9 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . -## Template for CORE modules. -## -## Provides a basic template and a common foundation for building CORE modules. +## Template for CORE modules.[br] +## [br] +## Provides a basic template and a common foundation for building CORE modules.[br] ## It provides common functions and variables used in all CORE modules. extends Node class_name CoreBaseModule @@ -30,12 +30,17 @@ var core: Core ## [br] ## Will be set before [method Node._ready] @onready var logger: CoreBaseModule = core.logger +## Reference to a matching [class CoreLoggerInstance]. +var loggeri: CoreLoggerInstance ## Marks a module as fully initialized and ready. var initialized: bool = false ## CORE's replacement for [method Object._init] and [method Node._ready] ## It's [b]strongly[/b] recommended to initialize your module here. func _initialize() -> void: initialized = true +## Called when CORE is about to cleanup +## Use this function to free any children +func _cleanup() -> void: pass ## Called by [method Core.apply_configuration]. ## This should be used to update your module configuration. func _pull_config() -> void: pass diff --git a/src/classes/Config.gd b/src/classes/config.gd similarity index 97% rename from src/classes/Config.gd rename to src/classes/config.gd index b69f180..af3dc96 100644 --- a/src/classes/Config.gd +++ b/src/classes/config.gd @@ -2,9 +2,7 @@ # Copyright (c) 2024 The StarOpenSource Project & Contributors # Licensed in the Public Domain -## The default configuration file for the CORE Framework. -## -## The [code]CoreConfiguration[/code] class holds the Framework's settings. +## The [code]CoreConfiguration[/code] class holds the Framework's settings.[br] ## The default configuration is designed to be usable without any modification. extends Node class_name CoreConfiguration diff --git a/src/classes/Loggerinstance.gd b/src/classes/loggerinstance.gd similarity index 93% rename from src/classes/Loggerinstance.gd rename to src/classes/loggerinstance.gd index fc64653..70a1639 100644 --- a/src/classes/Loggerinstance.gd +++ b/src/classes/loggerinstance.gd @@ -14,11 +14,12 @@ # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . -## Passes [code]origin[/code] for you. -## -## Pretty much a wrapper around CORE's logging implementation. -## CoreLoggerInstance's only job is to save you some effort aka. -## you not needing to pass the [code]origin[/code] argument to each + +## Passes [code]origin[/code] for you.[br] +## [br] +## Pretty much a wrapper around CORE's logging implementation.[br] +## CoreLoggerInstance's only job is to save you some effort aka.[br] +## you not needing to pass the [code]origin[/code] argument to each[br] ## and every log call, which is extremely annoying. Thank us later ;) extends Node class_name CoreLoggerInstance diff --git a/src/classes/Types.gd b/src/classes/types.gd similarity index 92% rename from src/classes/Types.gd rename to src/classes/types.gd index 5595f83..9d6c1e9 100644 --- a/src/classes/Types.gd +++ b/src/classes/types.gd @@ -15,15 +15,13 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . -## Types and enums for the CORE Framework. -## ## Contains enums and types shared across the CORE Framework. extends Node class_name CoreTypes -## Available version types, following the StarOpenSource Versioning Specification (SOSVS) v1 +## Available version types, following the StarOpenSource Versioning Specification (SOSVS) version 1 enum VersionType { RELEASE, RELEASECANDIDATE, BETA, ALPHA } -## Available log levels, followingthe StarOpenSource Logging Specification (SOSLS) v1 +## Available log levels, followingthe StarOpenSource Logging Specification (SOSLS) version 1 enum LoggerLevel { NONE, ERROR, WARN, INFO, VERB, DIAG } ## Available scene types enum SceneType { NONE, DEBUG, CUTSCENE, MENU, MAIN, BACKGROUND } diff --git a/src/Core.gd b/src/core.gd similarity index 73% rename from src/Core.gd rename to src/core.gd index 275bd45..c4a65ab 100644 --- a/src/Core.gd +++ b/src/core.gd @@ -23,14 +23,15 @@ extends Node class_name Core # Constants -## The release number -const version_release: int = 1 -## The release type +## The version number +const version_version: int = 1 +## The version type const version_type: CoreTypes.VersionType = CoreTypes.VersionType.BETA -## The release type number. Resets on every new release and release type. +## The version type number. Resets on every new version and version type. const version_typerelease: int = 4 # Modules +const modules: Array[String] = [ "logger", "misc", "sms", "logui", "erm", "storage" ] ## Use this to access CORE's logging implementation. var logger: CoreBaseModule ## Use this to access various useful functions. @@ -40,7 +41,7 @@ var sms: CoreBaseModule ## Use this to access the graphical log. Serves no importance to you (probably). var logui: CoreBaseModule ## Use this to access CORE's builtin HTTP request maker. -var edl: CoreBaseModule +var erm: CoreBaseModule ## Use this to access configuration and settings files easily. var storage: CoreBaseModule @@ -72,58 +73,40 @@ func _ready() -> void: custom_modules_node.name = "Custom Modules" add_child(custom_modules_node) +# Cleanup +# Particularily useful during testing to cleanup stuff, or if you want to do some stupid stuff with CORE during runtime +func cleanup() -> void: + logger.infof("core", "Cleaning up") + config.queue_free() + var modules_reverse: Array[String] = modules.duplicate() + modules_reverse.reverse() + for module in modules_reverse: + await get(module)._cleanup() + get(module).loggeri.queue_free() + get(module).queue_free() + for module in custom_modules_node.get_children(): unregister_custom_module(module.name) + remove_child(custom_modules_node) + custom_modules_node.queue_free() + queue_free() + # Initialize modules ## Initializes all modules during the first initialization phase.[br] ## [br] ## [b]NEVER call this yourself! You will break everything and risk a crash![/b] func initialize_modules() -> void: - # Create Nodes - logger = CoreBaseModule.new() - misc = CoreBaseModule.new() - sms = CoreBaseModule.new() - logui = CoreBaseModule.new() - edl = CoreBaseModule.new() - storage = CoreBaseModule.new() - # Set names - logger.name = "Logger" - misc.name = "Misc" - sms.name = "SceneManagementSystem" - logui.name = "LogUI" - edl.name = "EasyDownLoader" - storage.name = "Storage" - # Set scripts - logger.set_script(ResourceLoader.load(basepath + "src/Logger.gd")) - misc.set_script(ResourceLoader.load(basepath + "src/Misc.gd")) - sms.set_script(ResourceLoader.load(basepath + "src/Sms.gd")) - logui.set_script(ResourceLoader.load(basepath + "src/Logui.gd")) - edl.set_script(ResourceLoader.load(basepath + "src/Edl.gd")) - storage.set_script(ResourceLoader.load(basepath + "src/Storage.gd")) - # Set reference to self - logger.core = self - misc.core = self - sms.core = self - logui.core = self - edl.core = self - storage.core = self - # Call _initialize() (workaround as modules cannot access "core" during _init()) - logger._initialize() - misc._initialize() - sms._initialize() - logui._initialize() - edl._initialize() - storage._initialize() + for module in modules: + set(module, CoreBaseModule.new()) + get(module).name = module + get(module).set_script(load(basepath + "src/" + module + ".gd")) + get(module).core = self + get(module).loggeri = logger.get_instance(basepath.replace("res://", "") + "src/" + module + ".gd") + get(module)._initialize() # Inject modules into the SceneTree ## Injects CORE's builtin modules into the SceneTree.[br] ## [br] ## [b]NEVER call this yourself! You will break everything and risk a crash![/b] -func inject_modules() -> void: - add_child(logger) - add_child(misc) - add_child(sms) - add_child(logui) - add_child(edl) - add_child(storage) +func inject_modules() -> void: for module in modules: add_child(get(module)) # Wait for all modules to be fully initialized ## Wait for all builtin modules to be fully initialized.[br] @@ -140,12 +123,7 @@ func complete_init(no_success: bool = false) -> void: modsinit_custom = [] # Check builtin modules - if !logger.initialized: modsinit_builtin.append("logger") - if !misc.initialized: modsinit_builtin.append("misc") - if !sms.initialized: modsinit_builtin.append("sms") - if !logui.initialized: modsinit_builtin.append("logui") - if !edl.initialized: modsinit_builtin.append("edl") - if !storage.initialized: modsinit_builtin.append("storage") + for module in modules: if !get(module).initialized: modsinit_builtin.append(module) # Check custom modules for module_name in custom_modules: @@ -154,55 +132,58 @@ func complete_init(no_success: bool = false) -> void: # Print and sleep if modsinit_builtin.size() != 0 or modsinit_custom.size() != 0: print("Waiting for modules to finish initialization:") - if modsinit_builtin.size() != 0: - print(" Builtin: " + str(modsinit_builtin)) - if modsinit_custom.size() != 0: - print(" Custom: " + str(modsinit_custom)) + if modsinit_builtin.size() != 0: print(" Builtin: " + str(modsinit_builtin)) + if modsinit_custom.size() != 0: print(" Custom: " + str(modsinit_custom)) await get_tree().create_timer(1).timeout # Initialization complete await get_tree().process_frame - if !no_success: logger.infof("Core", "Initialized CORE successfully") + if !no_success: logger.infof("core", "Initialized CORE successfully") # Registers a custom module ## Registers a new custom module. -func register_custom_module(module_name: String, module_class: CoreBaseModule) -> bool: - logger.verbf("Core", "Registering new custom module \"" + module_name + "\"") +func register_custom_module(module_name: String, module_origin: String, module_class: CoreBaseModule) -> bool: + logger.verbf("core", "Registering new custom module \"" + module_name + "\"") if !config.custom_modules: - logger.errorf("Core", "Registering module failed: Custom module support is disabled.") + logger.errorf("core", "Registering module failed: Custom module support is disabled.") return false if custom_modules.has(module_name): - logger.errorf("Core", "Registering module failed: A custom module with the name \"" + module_name + "\" already exists.") + logger.errorf("core", "Registering module failed: A custom module with the name \"" + module_name + "\" already exists.") return false + logger.diagf("core", "Updating variables") module_class.name = module_name - logger.diagf("Core", "Updating variables") module_class.core = self - logger.diagf("Core", "Adding module to SceneTree") + module_class.loggeri = logger.get_instance(module_origin) + logger.diagf("core", "Adding module to SceneTree") custom_modules_node.add_child(module_class) - logger.diagf("Core", "Merging module with custom_modules") + logger.diagf("core", "Merging module with custom_modules") custom_modules.merge({ module_name: module_class }) - logger.diagf("Core", "Initializing custom module") + logger.diagf("core", "Initializing custom module") module_class._initialize() - logger.diagf("Core", "Updating custom module configuration") + logger.diagf("core", "Updating custom module configuration") module_class._pull_config() return true # Unregisters a custom module ## Unregisters a custom module, making it no longer function. func unregister_custom_module(module_name: String) -> void: - logger.verbf("Core", "Unregistering custom module \"" + module_name + "\"") + logger.verbf("core", "Unregistering custom module \"" + 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.") + logger.errorf("core", "Unregistering module failed: A custom module with the name \"" + module_name + "\" does not exist.") return - custom_modules_node.remove_child(get_custom_module(module_name)) + var module: Node = get_custom_module(module_name) + await module._cleanup() + module.loggeri.queue_free() + custom_modules_node.remove_child(module) custom_modules.erase(module_name) + module.queue_free() # Returns a custom module ## Returns a loaded custom module for access. func get_custom_module(module_name: String) -> CoreBaseModule: - logger.diagf("Core", "Getting custom module \"" + module_name + "\"") + logger.diagf("core", "Getting custom module \"" + 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.") + logger.errorf("core", "Getting module failed: A custom module with the name \"" + module_name + "\" does not exist.") return null return custom_modules[module_name] @@ -210,11 +191,12 @@ func get_custom_module(module_name: String) -> CoreBaseModule: ## Loads a (new) configuration file and applies it to all modules. func reload_configuration(new_config: CoreConfiguration = CoreConfiguration.new()) -> void: var initialized = config != null - if initialized: logger.verbf("Core", "Reloading CORE's configuration") + if initialized: logger.verbf("core", "Reloading CORE's configuration") + if config != null: config.queue_free() config = new_config if is_devmode(): # Override configuration in development mode config.logger_level = CoreTypes.LoggerLevel.VERB - if initialized: logger.verbf("Core", "Overrode configuration (development mode)") + if initialized: logger.verbf("core", "Overrode configuration (development mode)") if initialized: apply_configuration() # Call _pull_config() functions @@ -222,20 +204,16 @@ func reload_configuration(new_config: CoreConfiguration = CoreConfiguration.new( ## [br] ## [b]NEVER call this yourself unless you know what you are doing![/b] func apply_configuration() -> void: - logger.verbf("Core", "Applying configuration") - if is_devmode(): logger.warnf("Core", "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.") - edl._pull_config() + logger.verbf("core", "Applying configuration") + if is_devmode(): logger.warnf("core", "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.custom_modules: - logger.verbf("Core", "Removing all custom modules (custom modules support is disabled)") + logger.verbf("core", "Removing all custom modules (custom modules support is disabled)") for module in custom_modules: unregister_custom_module(module) - logger._pull_config() - misc._pull_config() - sms._pull_config() - logui._pull_config() + for module in modules: get(module)._pull_config() if config.custom_modules: for module in custom_modules: - logger.diagf("Core", "Updating configuration for custom module \"" + module.name + "\"") + logger.diagf("core", "Updating configuration for custom module \"" + module.name + "\"") module._pull_config() # Return development mode status @@ -254,10 +232,10 @@ func is_devmode() -> bool: ## - [code]%headless%[/code]: Returns the headless mode status func get_formatted_string(string: String) -> String: # Version strings - string = string.replace("%release%", str(version_release)) - string = string.replace("%release_type%", str(version_typerelease)) + string = string.replace("%version%", str(version_version)) + string = string.replace("%version_type%", str(version_typerelease)) var semantic_version: Array[int] = get_version_semantic() - string = string.replace("%release_semantic%", str(semantic_version[0]) + "." + str(semantic_version[1]) + "." + str(semantic_version[2])) + string = string.replace("%version_semantic%", str(semantic_version[0]) + "." + str(semantic_version[1]) + "." + str(semantic_version[2])) match(version_type): CoreTypes.VersionType.RELEASE: string = string.replace("%type%", "Release") @@ -271,7 +249,7 @@ func get_formatted_string(string: String) -> String: CoreTypes.VersionType.ALPHA: string = string.replace("%type%", "Alpha") string = string.replace("%type_technical%", "a") - _: await logger.crashf("Core", "Invalid version type " + str(version_type), true) + _: await logger.crashf("core", "Invalid version type " + str(version_type), true) # Development mode if is_devmode(): string = string.replace("%devmode%", "Enabled") else: string = string.replace("%devmode%", "Disabled") @@ -293,7 +271,7 @@ func get_version_semantic() -> Array[int]: CoreTypes.VersionType.RELEASECANDIDATE: version_type_int = 2 CoreTypes.VersionType.BETA: version_type_int = 1 CoreTypes.VersionType.ALPHA: version_type_int = 0 - return [version_release, version_type_int, version_typerelease] + return [version_version, version_type_int, version_typerelease] # Determines CORE's installation/base path ## Determines CORE's installation/base path[br] diff --git a/src/Edl.gd b/src/erm.gd similarity index 76% rename from src/Edl.gd rename to src/erm.gd index 3f11cf5..10cb627 100644 --- a/src/Edl.gd +++ b/src/erm.gd @@ -15,26 +15,33 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . -## A easy download/request maker. -## -## Allows for awaited and/or batched requests. +## Allows for awaited, batched and oneline requests. extends CoreBaseModule var list_queue: Dictionary = {} var list_active: Dictionary = {} var list_complete: Dictionary = {} +func _cleanup() -> void: + clean_queue() + clean_completed() + for child in get_children(): + if child.is_class("HTTPRequest"): + child.cancel_request() + await get_tree().process_frame + remove_child(child) + func generate_id() -> int: var id = randi() if list_queue.has(id) or list_active.has(id): return generate_id() - logger.diagf("Edl", "Generated new download id " + str(id)) + logger.diagf("erm", "Generated new download id " + str(id)) return id func awaited_request(url: String, parse_utf8: bool, method: HTTPClient.Method = HTTPClient.Method.METHOD_GET, headers: PackedStringArray = PackedStringArray([]), data: String = "") -> Dictionary: - logger.verbf("Edl", "Creating awaited request") + logger.verbf("erm", "Creating awaited request") var id: int = create_download(url, method, headers, data) start_download(id, parse_utf8) - logger.diagf("Edl", "Waiting for request " + str(id) + " to finish") + logger.diagf("erm", "Waiting for request " + str(id) + " to finish") while !is_download_complete(id): await get_tree().create_timer(0.1, true).timeout var dldata: Dictionary = list_complete[id] list_complete.erase(id) @@ -49,46 +56,48 @@ func oneline_awaited_request(url: String, return_utf8: bool = true, ignore_http_ else: return dldata["body"] 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("Edl", "Creating " + str(urls.size()) + " awaited request(s)") + logger.verbf("erm", "Creating " + str(urls.size()) + " awaited request(s)") var dldata: Array[Dictionary]= [] for url in urls: var id: int = create_download(url, method, headers, data) start_download(id, parse_utf8) - logger.diagf("Edl", "Waiting for request " + str(id) + " to finish") + logger.diagf("erm", "Waiting for request " + str(id) + " to finish") while !is_download_complete(id): await get_tree().create_timer(0.1, true).timeout dldata.append(list_complete[id]) list_complete.erase(id) return dldata func create_download(url: String, method: HTTPClient.Method = HTTPClient.Method.METHOD_GET, headers: PackedStringArray = PackedStringArray([]), body: String = "") -> int: - logger.verbf("Edl", "Creating new request\n-> URL: " + url + "\n-> Method: " + str(method) + "\nHeaders: " + str(headers.size()) + "\nBody size: " + str(body.length()) + " Characters") + logger.verbf("erm", "Creating new request\n-> URL: " + url + "\n-> Method: " + str(method) + "\nHeaders: " + str(headers.size()) + "\nBody size: " + str(body.length()) + " Characters") var id = generate_id() list_queue.merge({ id: { "url": url, "method": method, "headers": headers, "body": body } }) return id func start_download(id: int, parse_utf8: bool) -> void: - logger.verbf("Edl", "Starting request " + str(id)) + logger.verbf("erm", "Starting request " + str(id)) list_active.merge({ id: list_queue[id] }) list_queue.erase(id) - logger.diagf("Edl", "Creating new HTTPRequest \"Request #" + str(id) + "\"") + logger.diagf("erm", "Creating new HTTPRequest \"Request #" + str(id) + "\"") var download: HTTPRequest = HTTPRequest.new() download.name = "Request #" + str(id) download.accept_gzip = true download.use_threads = true - var lambda: Callable = func(result: int, http_code: int, headers: PackedStringArray, body: PackedByteArray) -> void: - logger.verbf("Edl", "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") - 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 "" } }) + 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)) + 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) - download.connect("request_completed", lambda) + remove_child(httprequest) + httprequest.queue_free() + download.connect("request_completed", lambda.bind(download)) add_child(download) download.request(list_active[id]["url"], list_active[id]["headers"], list_active[id]["method"], list_active[id]["body"]) func is_download_complete(id: int) -> bool: return list_complete.has(id) func clean_queue() -> void: - logger.verbf("Edl", "Cleaning request queue") + logger.verbf("erm", "Cleaning request queue") list_queue.clear() func clean_completed() -> void: - logger.verbf("Edl", "Cleaning completed requests") + logger.verbf("erm", "Cleaning completed requests") list_complete.clear() diff --git a/src/Logger.gd b/src/logger.gd similarity index 100% rename from src/Logger.gd rename to src/logger.gd diff --git a/src/Logui.gd b/src/logui.gd similarity index 92% rename from src/Logui.gd rename to src/logui.gd index 685de40..d922ec3 100644 --- a/src/Logui.gd +++ b/src/logui.gd @@ -30,8 +30,8 @@ var font_bold: Font func _initialize() -> void: # Load fonts into memory - font_normal = ResourceLoader.load(core.basepath + "dist/FiraCode/Regular.ttf") - font_bold = ResourceLoader.load(core.basepath + "dist/FiraCode/Bold.ttf") + font_normal = load(core.basepath + "dist/FiraCode/Regular.ttf") + font_bold = load(core.basepath + "dist/FiraCode/Bold.ttf") # Create LogUI background = ColorRect.new() background.name = "LOGUI" @@ -59,17 +59,12 @@ func _initialize() -> void: # Mark as initialized initialized = true -func _pull_config() -> void: - background.visible = !core.config.headless and core.config.logui_enabled - background.color = core.config.logui_background_color - logrtl.add_theme_font_size_override("normal_font_size", core.config.logui_font_size) - logrtl.add_theme_font_size_override("bold_font_size", core.config.logui_font_size) - func _ready() -> void: # Add to SceneTree core.sms.add_child(background) core.sms.move_child(background, 0) background.add_child(logrtl) + # Hide VScrollBar var vsbar: VScrollBar = logrtl.get_child(0, true) vsbar.set_deferred("size", Vector2i(1, 1)) @@ -79,9 +74,22 @@ func _ready() -> void: vsbar.add_theme_stylebox_override("grabber", StyleBoxEmpty.new()) vsbar.add_theme_stylebox_override("grabber_highlight", StyleBoxEmpty.new()) vsbar.add_theme_stylebox_override("grabber_pressed", StyleBoxEmpty.new()) + # Connect log_event logger.connect("log_event", func(allowed: bool, _level: CoreTypes.LoggerLevel, _origin: String, _message: String, format: String) -> void: if allowed: logrtl.text = logrtl.text + format + "\n") +func _cleanup() -> void: + background.remove_child(logrtl) + core.sms.remove_child(background) + logrtl.queue_free() + background.queue_free() + +func _pull_config() -> void: + background.visible = !core.config.headless and core.config.logui_enabled + background.color = core.config.logui_background_color + logrtl.add_theme_font_size_override("normal_font_size", core.config.logui_font_size) + logrtl.add_theme_font_size_override("bold_font_size", core.config.logui_font_size) + func _process(_delta: float) -> void: if !core.config.headless: var window_size: Vector2i = DisplayServer.window_get_size() diff --git a/src/Misc.gd b/src/misc.gd similarity index 91% rename from src/Misc.gd rename to src/misc.gd index a7e9fbc..2d1ca97 100644 --- a/src/Misc.gd +++ b/src/misc.gd @@ -22,9 +22,10 @@ extends CoreBaseModule func quit_safely(exitcode: int = 0) -> void: - logger.infof("Misc", "Shutting down (code " + str(exitcode) + ")") - logger.diagf("Misc", "Waiting for log messages to be flushed") + logger.infof("misc", "Shutting down (code " + str(exitcode) + ")") + logger.diagf("misc", "Waiting for log messages to be flushed") await get_tree().create_timer(0.25).timeout + await core.cleanup() get_tree().quit(exitcode) @warning_ignore("integer_division") @@ -48,10 +49,10 @@ func format_stringarray(array: Array[String], item_before: String = "", item_aft var output: String = "" if array.size() == 0: - logger.warnf("Misc", "Unable to format a string with a size of 0") + logger.warnf("misc", "Unable to format a string with a size of 0") return "" elif array.size() == 1: - logger.warnf("Misc", "Unable to format a string with a size of 1") + logger.warnf("misc", "Unable to format a string with a size of 1") return array[0] for item in array: diff --git a/src/Sms.gd b/src/sms.gd similarity index 64% rename from src/Sms.gd rename to src/sms.gd index 7e0222d..80c94c4 100644 --- a/src/Sms.gd +++ b/src/sms.gd @@ -21,6 +21,7 @@ extends CoreBaseModule # Objects +const scene_nodes: Array[String] = ["debug", "cutscene", "menu", "main", "background"] var scenes_debug: Node = Node.new() var scenes_cutscene: Node = Node.new() var scenes_menu: Node = Node.new() @@ -31,33 +32,34 @@ var scenes_background: Node = Node.new() var scenes: Dictionary = {} func _initialize() -> void: - scenes_debug.name = "DEBUG" - scenes_cutscene.name = "CUTSCENE" - scenes_menu.name = "MENU" - scenes_main.name = "MAIN" - scenes_background.name = "BACKGROUND" - add_child(scenes_background) - add_child(scenes_main) - add_child(scenes_menu) - add_child(scenes_cutscene) - add_child(scenes_debug) + for scene in scene_nodes: + get("scenes_" + scene).name = scene.to_upper() + add_child(get("scenes_" + scene)) # Mark as initialized initialized = true +func _cleanup() -> void: + for scene in scene_nodes: + remove_child(get("scenes_" + scene)) + get("scenes_" + scene).queue_free() + func _pull_config() -> void: if core.config.headless: # Remove all scenes - logger.verbf("Sms", "Removing all scenes (triggered by headless mode)") + if is_inside_tree(): logger.verbf("sms", "Removing all scenes (triggered by headless mode)") for scene in scenes: remove_scene(scene, true) # Add a scene to some scene collection -func add_scene(sname: String, type: CoreTypes.SceneType, sclass: Node) -> bool: +func add_scene(sname: String, sclass: Node, type: CoreTypes.SceneType) -> bool: if core.config.headless: return false - logger.verbf("Sms", "Adding scene \"" + sname + "\" of type " + str(type)) + logger.verbf("sms", "Adding scene \"" + sname + "\" of type " + str(type)) if exists(sname) != CoreTypes.SceneType.NONE: - logger.errorf("Sms", "Scene with name \"" + sname + "\" already exists") - return true + logger.errorf("sms", "Scene with name \"" + sname + "\" already exists") + return false + if typeof(sclass) != TYPE_OBJECT or !sclass.is_class("Node"): + logger.errorf("sms", "Scene class \"" + sname + "\" is not of type Node") + return false sclass.name = sname match(type): CoreTypes.SceneType.DEBUG: scenes_debug.add_child(sclass) @@ -66,27 +68,37 @@ func add_scene(sname: String, type: CoreTypes.SceneType, sclass: Node) -> bool: CoreTypes.SceneType.MAIN: scenes_main.add_child(sclass) CoreTypes.SceneType.BACKGROUND: scenes_background.add_child(sclass) CoreTypes.SceneType.NONE: - logger.errorf("Sms", "CoreTypes.SceneType.NONE is not a valid scene type") + logger.errorf("sms", "CoreTypes.SceneType.NONE is not a valid scene type") return false - _: await logger.crashf("Sms", "Invalid SceneType " + str(type), true) + _: await logger.crashf("sms", "Invalid SceneType " + str(type), true) scenes.merge({ sname: { "type": type, "class": sclass } }) return true # Remove a scene from some scene collection func remove_scene(sname: String, force_remove: bool = false) -> bool: if core.config.headless and !force_remove: return false - if force_remove: await logger.crashf("Sms", "force_remove = true is not allowed", true) - logger.verbf("Sms", "Removing scene \"" + sname + "\"") + if force_remove: await logger.crashf("sms", "force_remove = true is not allowed", true) + logger.verbf("sms", "Removing scene \"" + sname + "\"") match(exists(sname)): - CoreTypes.SceneType.DEBUG: scenes_debug.remove_child(scenes[sname]["class"]) - CoreTypes.SceneType.CUTSCENE: scenes_cutscene.remove_child(scenes[sname]["class"]) - CoreTypes.SceneType.MENU: scenes_menu.remove_child(scenes[sname]["class"]) - CoreTypes.SceneType.MAIN: scenes_main.remove_child(scenes[sname]["class"]) - CoreTypes.SceneType.BACKGROUND: scenes_background.remove_child(scenes[sname]["class"]) + CoreTypes.SceneType.DEBUG: + scenes_debug.remove_child(scenes[sname]["class"]) + scenes[sname]["class"].queue_free() + CoreTypes.SceneType.CUTSCENE: + scenes_cutscene.remove_child(scenes[sname]["class"]) + scenes[sname]["class"].queue_free() + CoreTypes.SceneType.MENU: + scenes_menu.remove_child(scenes[sname]["class"]) + scenes[sname]["class"].queue_free() + CoreTypes.SceneType.MAIN: + scenes_main.remove_child(scenes[sname]["class"]) + scenes[sname]["class"].queue_free() + CoreTypes.SceneType.BACKGROUND: + scenes_background.remove_child(scenes[sname]["class"]) + scenes[sname]["class"].queue_free() CoreTypes.SceneType.NONE: - logger.errorf("Sms", "Scene \"" + sname + "\" does not exist") + logger.errorf("sms", "Scene \"" + sname + "\" does not exist") return false - _: await logger.crashf("Sms", "Invalid SceneType " + str(exists(sname)), true) + _: await logger.crashf("sms", "Invalid SceneType " + str(exists(sname)), true) scenes.erase(sname) return true @@ -99,8 +111,8 @@ func get_scene(sname: String) -> Node: CoreTypes.SceneType.MENU: return scenes[sname]["class"] CoreTypes.SceneType.MAIN: return scenes[sname]["class"] CoreTypes.SceneType.BACKGROUND: return scenes[sname]["class"] - CoreTypes.SceneType.NONE: logger.errorf("Sms", "Scene \"" + sname + "\" does not exist") - _: await logger.crashf("Sms", "Invalid SceneType " + str(exists(sname)), true) + CoreTypes.SceneType.NONE: logger.errorf("sms", "Scene \"" + sname + "\" does not exist") + _: await logger.crashf("sms", "Invalid SceneType " + str(exists(sname)), true) return null # Return a scene collection for scene manipulation @@ -112,8 +124,8 @@ func get_scene_collection(type: CoreTypes.SceneType) -> Node: CoreTypes.SceneType.MENU: return scenes_menu CoreTypes.SceneType.MAIN: return scenes_main CoreTypes.SceneType.BACKGROUND: return scenes_background - CoreTypes.SceneType.NONE: logger.errorf("Sms", "No scene collection was found for CoreTypes.SceneType.NONE") - _: await logger.crashf("Sms", "Invalid SceneType " + str(type), true) + CoreTypes.SceneType.NONE: logger.errorf("sms", "No scene collection was found for CoreTypes.SceneType.NONE") + _: await logger.crashf("sms", "Invalid SceneType " + str(type), true) return null # Return scenes in some scene collection @@ -121,15 +133,15 @@ func get_scene_collection_list(type: CoreTypes.SceneType) -> Array[Node]: var list: Array[Node] = [] for scene in scenes: if scenes[scene]["type"] == type: - list.append(scene) + list.append(scenes[scene]["class"]) return list # Return scene count in some scene collection func get_scene_collection_count(type: CoreTypes.SceneType) -> int: var amount: int = 0 for scene in scenes: - if scene[scene]["type"] == type: - amount = amount+1 + if scenes[scene]["type"] == type: + amount += 1 return amount # Return scene existance & scene collection diff --git a/src/Storage.gd b/src/storage.gd similarity index 69% rename from src/Storage.gd rename to src/storage.gd index 7035da5..d413ac4 100644 --- a/src/Storage.gd +++ b/src/storage.gd @@ -22,40 +22,40 @@ var storage_location: String = "" func open_storage(location: String, create_new: bool = true, sanity_check: bool = true, fail_on_sanity_check: bool = false) -> bool: if is_open: - logger.errorf("Storage", "Failed to open storage: A storage file is already open") + logger.errorf("storage", "Failed to open storage: A storage file is already open") return false - logger.verbf("Storage", "Opening storage file at \"" + location + "\"") + logger.verbf("storage", "Opening storage file at \"" + location + "\"") var file: FileAccess if !FileAccess.file_exists(location): if create_new: file = FileAccess.open(location, FileAccess.WRITE) if file == null: - await logger.crashf("Storage", "Could not open storage file at \"" + location + "\": Failed with code " + str(FileAccess.get_open_error())) + await logger.crashf("storage", "Could not open storage file at \"" + location + "\": Failed with code " + str(FileAccess.get_open_error())) return false file.store_string("{}") file.close() else: - logger.errorf("Storage", "Failed to open storage: create_new is set to false") + logger.errorf("storage", "Failed to open storage: create_new is set to false") return false file = FileAccess.open(location, FileAccess.READ) var storage_temp: Variant = file.get_as_text() file.close() storage_temp = JSON.parse_string(storage_temp) if typeof(storage_temp) != TYPE_DICTIONARY: - logger.errorf("Storage", "Failed to open storage: Parsed storage file is of type " + str(typeof(storage_temp))) + logger.errorf("storage", "Failed to open storage: Parsed storage file is of type " + str(typeof(storage_temp))) return false if sanity_check: var check_result: Array[String] = perform_sanity_check(storage_temp) if check_result.size() != 0: if fail_on_sanity_check: - logger.errorf("Storage", "Sanity check failed (stopping):") + logger.errorf("storage", "Sanity check failed (stopping):") for error in check_result: - logger.errorf("Storage", "-> " + error) + logger.errorf("storage", "-> " + error) return false else: - logger.warnf("Storage", "Sanity check failed (continuing anyway):") + logger.warnf("storage", "Sanity check failed (continuing anyway):") for error in check_result: - logger.warnf("Storage", "-> " + error) + logger.warnf("storage", "-> " + error) storage = storage_temp storage_location = location is_open = true @@ -63,90 +63,90 @@ func open_storage(location: String, create_new: bool = true, sanity_check: bool func close_storage() -> bool: if !is_open: - logger.errorf("Storage", "Failed to close storage: No storage file is open") + logger.errorf("storage", "Failed to close storage: No storage file is open") return false - logger.verbf("Storage", "Closing storage file") + logger.verbf("storage", "Closing storage file") storage = {} is_open = false return true func save_storage() -> bool: if !is_open: - logger.errorf("Storage", "Failed to save storage: No storage file is open") + logger.errorf("storage", "Failed to save storage: No storage file is open") return false var file: FileAccess = FileAccess.open(storage_location, FileAccess.WRITE) if file == null: - await logger.crashf("Storage", "Could not open storage file at \"" + storage_location + "\": Failed with code " + str(FileAccess.get_open_error())) + await logger.crashf("storage", "Could not open storage file at \"" + storage_location + "\": Failed with code " + str(FileAccess.get_open_error())) return false - logger.diagf("Storage", "Writing storage file to disk") + logger.diagf("storage", "Writing storage file to disk") file.store_string(JSON.stringify(storage)) file.close() return true func nuke_storage(autosave: bool = true) -> bool: if !is_open: - logger.errorf("Storage", "Failed to nuke storage: No storage file is open") + logger.errorf("storage", "Failed to nuke storage: No storage file is open") return false - logger.warnf("Storage", "Nuking storage") + logger.warnf("storage", "Nuking storage") storage = {} if autosave: save_storage() return true -func get_key(key: String, default: Variant) -> Variant: +func get_key(key: String, default: Variant = null) -> Variant: if !is_open: - logger.errorf("Storage", "Failed to get key: No storage file is open") + logger.errorf("storage", "Failed to get key: No storage file is open") return NAN - logger.diagf("Storage", "Returning storage key \"" + key + "\" (default='" + default + "')") + logger.diagf("storage", "Returning storage key \"" + key + "\" (default='" + str(default) + "')") return storage.get(key, default) func set_key(key: String, value: Variant, overwrite: bool = true, autosave: bool = true) -> bool: if !is_open: - logger.errorf("Storage", "Failed to set key: No storage file is open") + logger.errorf("storage", "Failed to set key: No storage file is open") return false - logger.diagf("Storage", "Updating storage key \"" + key + "\" with value '" + str(value) + "' (overwrite='" + str(overwrite) + "' autosave='" + str(autosave) + "'") + logger.diagf("storage", "Updating storage key \"" + key + "\" with value '" + str(value) + "' (overwrite='" + str(overwrite) + "' autosave='" + str(autosave) + "'") storage.merge({key: value}, overwrite) if autosave: save_storage() return true func del_key(key: String, autosave: bool = true) -> bool: 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 - logger.diagf("Storage", "Deleting storage key \"" + key + "\" (autosave='" + str(autosave) + "')") + logger.diagf("storage", "Deleting storage key \"" + key + "\" (autosave='" + str(autosave) + "')") storage.erase(key) if autosave: save_storage() return true func get_dict() -> Dictionary: if !is_open: - logger.errorf("Storage", "Failed to get dictionary: No storage file is open") + logger.errorf("storage", "Failed to get dictionary: No storage file is open") return {} - logger.verbf("Storage", "Returning storage dictionary") + logger.verbf("storage", "Returning storage dictionary") return storage func save_dict(dict: Dictionary, sanity_check: bool = true, fail_on_sanity_check: bool = false, autosave: bool = true) -> bool: if !is_open: - logger.errorf("Storage", "Failed to save dictionary: No storage file is open") + logger.errorf("storage", "Failed to save dictionary: No storage file is open") return false - logger.verbf("Storage", "Saving custom dictionary as storage") + logger.verbf("storage", "Saving custom dictionary as storage") if sanity_check: var check_result: Array[String] = perform_sanity_check(dict) if check_result.size() != 0: if fail_on_sanity_check: - logger.errorf("Storage", "Sanity check failed (stopping):") + logger.errorf("storage", "Sanity check failed (stopping):") for error in check_result: - logger.errorf("Storage", "-> " + error) + logger.errorf("storage", "-> " + error) return false else: - logger.warnf("Storage", "Sanity check failed (continuing anyway):") + logger.warnf("storage", "Sanity check failed (continuing anyway):") for error in check_result: - logger.warnf("Storage", "-> " + error) + logger.warnf("storage", "-> " + error) storage = dict if autosave: save_storage() return true func perform_sanity_check(storage_check: Dictionary) -> Array[String]: - logger.verbf("Storage", "Performing a sanity check on some storage dictionary") + logger.verbf("storage", "Performing a sanity check on some storage dictionary") var errors: Array[String] = [] for key in storage_check: if typeof(key) != TYPE_STRING: @@ -155,5 +155,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: 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") + logger.verbf("storage", "Completed sanity check with " + str(errors.size()) + " errors") return errors