diff --git a/.editorconfig b/.editorconfig index f28239b..49a3a32 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,4 +1,54 @@ root = true +# All Files [*] charset = utf-8 +indent_style = space +indent_size = 2 +insert_final_newline = true +trim_trailing_whitespace = true +end_of_line = lf + +########################################## +# File Extension Settings +########################################## + +# GDScript Files +[*.{gd,gdshader,gdshaderinc}] +indent_style = tab + +# Visual Studio Solution Files +[*.sln] +indent_style = tab + +# Visual Studio XML Project Files +[*.{csproj,vbproj,vcxproj.filters,proj,projitems,shproj}] +indent_size = 2 + +# XML Configuration Files +[*.{xml,config,props,targets,nuspec,resx,ruleset,vsixmanifest,vsct}] +indent_size = 2 + +# JSON Files +[*.{json,json5,webmanifest}] +indent_size = 2 + +# YAML Files +[*.{yml,yaml}] +indent_size = 2 + +# Markdown Files +[*.{md,mdx}] +trim_trailing_whitespace = false + +# Web Files +[*.{htm,html,js,jsm,ts,tsx,cjs,cts,ctsx,mjs,mts,mtsx,css,sass,scss,less,pcss,svg,vue}] +indent_size = 2 + +# Batch Files +[*.{cmd,bat}] +end_of_line = crlf + +# Makefiles +[Makefile] +indent_style = tab diff --git a/.gitignore b/.gitignore index a00d953..3443229 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,7 @@ .idea/ .zed/ + +*.g.puml +*.g.cs +*.DotSettings.user diff --git a/Dancer.csproj b/Dancer.csproj new file mode 100644 index 0000000..96ffd75 --- /dev/null +++ b/Dancer.csproj @@ -0,0 +1,32 @@ + + + net10.0 + true + enable + false + blossomfiend + true + true + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Dancer.csproj.DotSettings b/Dancer.csproj.DotSettings new file mode 100644 index 0000000..1590d3f --- /dev/null +++ b/Dancer.csproj.DotSettings @@ -0,0 +1,12 @@ + + True + True + True + True + True + True + True + True + True + True + True \ No newline at end of file diff --git a/Dancer.sln b/Dancer.sln new file mode 100644 index 0000000..0b81def --- /dev/null +++ b/Dancer.sln @@ -0,0 +1,19 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2012 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dancer", "Dancer.csproj", "{8769203B-93C1-4144-8B58-B7213D27D87D}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + ExportDebug|Any CPU = ExportDebug|Any CPU + ExportRelease|Any CPU = ExportRelease|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {8769203B-93C1-4144-8B58-B7213D27D87D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8769203B-93C1-4144-8B58-B7213D27D87D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8769203B-93C1-4144-8B58-B7213D27D87D}.ExportDebug|Any CPU.ActiveCfg = ExportDebug|Any CPU + {8769203B-93C1-4144-8B58-B7213D27D87D}.ExportDebug|Any CPU.Build.0 = ExportDebug|Any CPU + {8769203B-93C1-4144-8B58-B7213D27D87D}.ExportRelease|Any CPU.ActiveCfg = ExportRelease|Any CPU + {8769203B-93C1-4144-8B58-B7213D27D87D}.ExportRelease|Any CPU.Build.0 = ExportRelease|Any CPU + EndGlobalSection +EndGlobal diff --git a/addons/GDQuest_GDScript_formatter/install_and_update.gd b/addons/GDQuest_GDScript_formatter/install_and_update.gd deleted file mode 100644 index 7f95d0f..0000000 --- a/addons/GDQuest_GDScript_formatter/install_and_update.gd +++ /dev/null @@ -1,233 +0,0 @@ -@tool -extends Node - -enum HttpRequestState { - IDLE, - FETCHING_RELEASE_INFO, - DOWNLOADING_BINARY, -} - -const URL_GITHUB_API_LATEST_RELEASE = "https://api.github.com/repos/gdquest/GDScript-formatter/releases/latest" - -signal installation_completed(binary_path: String) -signal installation_failed(error_message: String) - -var http_request_state := HttpRequestState.IDLE -var http_request: HTTPRequest = HTTPRequest.new() -var formatter_cache_dir: String - - -func _init(cache_dir: String) -> void: - formatter_cache_dir = cache_dir - - -func _ready() -> void: - add_child(http_request) - http_request.request_completed.connect(_on_request_completed) - - -func install_or_update_formatter() -> void: - print("Starting GDScript formatter installation...") - http_request_state = HttpRequestState.FETCHING_RELEASE_INFO - http_request.request(URL_GITHUB_API_LATEST_RELEASE) - - -func _on_request_completed( - _http_result: int, - response_code: int, - _http_headers: PackedStringArray, - body: PackedByteArray, -) -> void: - if response_code != 200: - var error_message := "HTTP request failed. Response code: " + str(response_code) - push_error(error_message) - http_request_state = HttpRequestState.IDLE - installation_failed.emit(error_message) - return - - match http_request_state: - HttpRequestState.FETCHING_RELEASE_INFO: - _process_response_latest_release(body) - HttpRequestState.DOWNLOADING_BINARY: - _process_response_download_file(body) - _: - var error_message := "Unexpected HTTP request state: " + str(http_request_state) - push_error(error_message) - http_request_state = HttpRequestState.IDLE - installation_failed.emit(error_message) - - -func _process_response_latest_release(body: PackedByteArray) -> void: - var json = JSON.parse_string(body.get_string_from_utf8()) - if not json or not json.has("assets"): - var error_message := "Failed to parse release information from GitHub API" - push_error(error_message) - http_request_state = HttpRequestState.IDLE - installation_failed.emit(error_message) - return - - print("GDScript Formatter release information loaded successfully") - - var assets = json["assets"] - var tag = json["tag_name"] - var download_url := _find_matching_asset(assets, tag) - - if download_url.is_empty(): - var error_message := "No matching binary found for current platform" - push_error(error_message) - http_request_state = HttpRequestState.IDLE - installation_failed.emit(error_message) - return - - print( - "Found compatible release, starting download...\n", - "Download URL: ", - download_url, - ) - - http_request_state = HttpRequestState.DOWNLOADING_BINARY - http_request.request(download_url) - - -func _process_response_download_file(body: PackedByteArray) -> void: - http_request_state = HttpRequestState.IDLE - - print("Download completed successfully (", body.size(), " bytes)") - - var asset_info := _get_platform_info() - if asset_info.is_empty(): - var error_message := "Failed to determine platform information" - push_error(error_message) - installation_failed.emit(error_message) - return - - print("Extracting and installing binary...") - var binary_path := _download_and_install_binary(body, asset_info) - if binary_path.is_empty(): - var error_message := "Installation failed" - push_error(error_message) - installation_failed.emit(error_message) - return - - print( - "\n".join( - [ - "GDScript formatter installed successfully!", - "Binary location: " + binary_path, - ], - ), - ) - installation_completed.emit(binary_path) - - -func _get_platform_info() -> Dictionary: - var os_name := OS.get_name().to_lower() - var processor_name := OS.get_processor_name().to_lower() - var architecture := "x86_64" - - if processor_name.contains("aarch64") or processor_name.contains("arm64"): - architecture = "aarch64" - elif processor_name.contains("x86_64") or processor_name.contains("amd64"): - architecture = "x86_64" - - var binary_name := "gdscript-formatter" - if os_name.contains("windows"): - binary_name = "gdscript-formatter.exe" - - var platform_info := { - "architecture": architecture, - "binary_name": binary_name, - } - - if os_name.contains("windows"): - platform_info["os"] = "windows" - elif os_name.contains("linux"): - platform_info["os"] = "linux" - elif os_name.contains("macos") or os_name.contains("osx"): - platform_info["os"] = "macos" - - return platform_info - - -func _find_matching_asset(assets: Array, tag: String) -> String: - var platform_info := _get_platform_info() - if platform_info.is_empty(): - return "" - - var expected_pattern := "gdscript-formatter-%s-%s-%s" % [tag, platform_info["os"], platform_info["architecture"]] - if platform_info["os"] == "windows": - expected_pattern += ".exe" - expected_pattern += ".zip" - - for asset in assets: - var asset_name: String = asset["name"] - if asset_name == expected_pattern: - return asset["browser_download_url"] - - return "" - - -func _download_and_install_binary(zip_data: PackedByteArray, platform_info: Dictionary) -> String: - var binary_name: String = platform_info["binary_name"] - # We get the contents of the zip file as a byte array. we need to write - # it to a file to be able to read it. We use a temporary file for that. - var temp_archive_path := formatter_cache_dir.path_join("temp_formatter_archive.zip") - - print("Installing to cache directory: ", formatter_cache_dir) - - # Create the gdquest cache directory if it doesn't exist - if not DirAccess.dir_exists_absolute(formatter_cache_dir): - var dir_result := DirAccess.make_dir_recursive_absolute(formatter_cache_dir) - if dir_result != OK: - push_error("Failed to create cache directory: ", formatter_cache_dir) - return "" - - var temp_file := FileAccess.open(temp_archive_path, FileAccess.WRITE) - if not temp_file: - push_error("Failed to create temporary archive file") - return "" - - temp_file.store_buffer(zip_data) - temp_file.close() - - var zip_reader := ZIPReader.new() - var err := zip_reader.open(temp_archive_path) - if err != OK: - push_error("Failed to open ZIP archive from temporary file") - zip_reader.close() - DirAccess.remove_absolute(temp_archive_path) - return "" - - var files := zip_reader.get_files() - var binary_data: PackedByteArray - var found_binary := false - var actual_binary_name := "" - - for file_path in files: - if not file_path.ends_with("/"): - binary_data = zip_reader.read_file(file_path) - actual_binary_name = file_path.get_file() - found_binary = true - break - - zip_reader.close() - - DirAccess.remove_absolute(temp_archive_path) - if not found_binary: - push_error("No executable found in ZIP archive") - return "" - - var binary_path := formatter_cache_dir.path_join(binary_name) - - var file := FileAccess.open(binary_path, FileAccess.WRITE) - if not file: - push_error("Failed to create binary file at: ", binary_path) - return "" - - file.store_buffer(binary_data) - file.close() - - if not OS.get_name().to_lower().contains("windows"): - OS.execute("chmod", ["+x", binary_path]) - - return binary_path diff --git a/addons/GDQuest_GDScript_formatter/install_and_update.gd.uid b/addons/GDQuest_GDScript_formatter/install_and_update.gd.uid deleted file mode 100644 index a1be937..0000000 --- a/addons/GDQuest_GDScript_formatter/install_and_update.gd.uid +++ /dev/null @@ -1 +0,0 @@ -uid://jmkfrj6xb72j diff --git a/addons/GDQuest_GDScript_formatter/menu.gd b/addons/GDQuest_GDScript_formatter/menu.gd deleted file mode 100644 index b7db542..0000000 --- a/addons/GDQuest_GDScript_formatter/menu.gd +++ /dev/null @@ -1,148 +0,0 @@ -## This module handles adding a menu to the script editor with formatter commands. -## It safely locates the script editor's menu bar and adds our custom menu. -@tool -extends Node - -signal menu_item_selected(command: String) - -const MENU_TEXT = "Format" -const MENU_ITEMS = { - "format_script": "Format Current Script", - "lint_script": "Lint Current Script", - "reorder_code": "Reorder Code", - "install_update": "Install or Update Formatter", - "uninstall": "Uninstall Formatter", - "report_issue": "Report Issue", - "help": "Help", -} - -var menu_button: MenuButton = null -var popup_menu: PopupMenu = null - - -func _ready() -> void: - # At the start we insert the menu in the script editor - var script_editor := EditorInterface.get_script_editor() - var last_menu_button := _find_last_menu_button(script_editor) - if not is_instance_valid(last_menu_button): - push_warning("GDScript Formatter: Could not find valid menu button in script editor. Menu will not be available. Use the command palette instead.") - return - - menu_button = MenuButton.new() - menu_button.text = MENU_TEXT - menu_button.switch_on_hover = true - menu_button.flat = false - menu_button.theme_type_variation = &"FlatMenuButton" - - popup_menu = menu_button.get_popup() - _populate_menu() - - popup_menu.id_pressed.connect(_on_menu_item_pressed) - last_menu_button.add_sibling(menu_button) - - -## Cleans up the menu from the script editor. Call this when disabling the -## plugin (in _exit_tree()). -func remove_formatter_menu() -> void: - if is_instance_valid(menu_button): - if is_instance_valid(popup_menu): - popup_menu.id_pressed.disconnect(_on_menu_item_pressed) - menu_button.queue_free() - menu_button = null - popup_menu = null - - -func update_menu(show_uninstall: bool) -> void: - if not is_instance_valid(popup_menu): - return - popup_menu.clear() - _populate_menu(show_uninstall) - - -## Searches for and returns the last menu node in the script editor top menu bar, -## or null if not found. -func _find_last_menu_button(script_editor: Control) -> MenuButton: - # The first child of the script editor should be a VBoxContainer (main container for the script editor main screen) - # Then the first child of that container should be an HBoxContainer (the menu bar) - # This is based on the current structure of Godot's script editor as of Godot 4.5 - # Note: We add multiple checks in there with null returns mainly in case something changes in a future - if script_editor.get_child_count() == 0: - return null - - var main_container := script_editor.get_child(0) - if not is_instance_valid(main_container) or not main_container is VBoxContainer: - return null - - if main_container.get_child_count() == 0: - return null - - var menu_bar := main_container.get_child(0) - if not is_instance_valid(menu_bar) or not menu_bar is HBoxContainer: - return null - - # We reached the menu bar. So now we loop through all the children look for - # the last menu button, which would be the last menu in the menu list. - # Note: Here the goal is to insert the menu after the debug menu, but we - # don't check for the button text because "debug" would only work in English - # this should work in any language. - var last_menu_button: MenuButton = null - for child in menu_bar.get_children(): - if child is MenuButton: - last_menu_button = child as MenuButton - - return last_menu_button - - -func _populate_menu(show_uninstall: bool = true) -> void: - if not is_instance_valid(popup_menu): - return - - var current_item_index := 0 - - popup_menu.add_item(MENU_ITEMS["format_script"], current_item_index) - popup_menu.set_item_metadata(current_item_index, "format_script") - popup_menu.set_item_tooltip(current_item_index, "Run the GDScript Formatter over the current script") - current_item_index += 1 - - popup_menu.add_item(MENU_ITEMS["lint_script"], current_item_index) - popup_menu.set_item_metadata(current_item_index, "lint_script") - popup_menu.set_item_tooltip(current_item_index, "Check the current script for linting issues") - current_item_index += 1 - - popup_menu.add_item(MENU_ITEMS["reorder_code"], current_item_index) - popup_menu.set_item_metadata(current_item_index, "reorder_code") - popup_menu.set_item_tooltip(current_item_index, "Reorder the code elements in the current script according to the GDScript Style Guide") - current_item_index += 1 - - popup_menu.add_separator() - - popup_menu.add_item(MENU_ITEMS["install_update"], current_item_index) - popup_menu.set_item_metadata(current_item_index, "install_update") - popup_menu.set_item_tooltip(current_item_index, "Download the latest version of the GDScript Formatter") - current_item_index += 1 - - if show_uninstall: - popup_menu.add_item(MENU_ITEMS["uninstall"], current_item_index) - popup_menu.set_item_metadata(current_item_index, "uninstall") - popup_menu.set_item_tooltip(current_item_index, "Remove the GDScript Formatter installed through this add-on from your computer") - current_item_index += 1 - - popup_menu.add_separator() - - popup_menu.add_item(MENU_ITEMS["report_issue"], current_item_index) - popup_menu.set_item_metadata(current_item_index, "report_issue") - popup_menu.set_item_tooltip(current_item_index, "Tell us about problems or bugs you found") - current_item_index += 1 - - popup_menu.add_item(MENU_ITEMS["help"], current_item_index) - popup_menu.set_item_metadata(current_item_index, "help") - popup_menu.set_item_tooltip(current_item_index, "Learn how to use the GDScript Formatter") - - -func _on_menu_item_pressed(id: int) -> void: - if not is_instance_valid(popup_menu): - return - - var command: String = popup_menu.get_item_metadata(id) - if not command.is_empty(): - menu_item_selected.emit(command) diff --git a/addons/GDQuest_GDScript_formatter/menu.gd.uid b/addons/GDQuest_GDScript_formatter/menu.gd.uid deleted file mode 100644 index 0b60bb4..0000000 --- a/addons/GDQuest_GDScript_formatter/menu.gd.uid +++ /dev/null @@ -1 +0,0 @@ -uid://cflbb5u271ldt diff --git a/addons/GDQuest_GDScript_formatter/plugin.cfg b/addons/GDQuest_GDScript_formatter/plugin.cfg deleted file mode 100644 index 79c1455..0000000 --- a/addons/GDQuest_GDScript_formatter/plugin.cfg +++ /dev/null @@ -1,7 +0,0 @@ -[plugin] - -name="GDQuest GDScript Formatter" -description="A plugin to format GDScript code in the Godot editor using the GDScript Formatter from GDQuest." -author="GDQuest" -version="0.1.0" -script="plugin.gd" diff --git a/addons/GDQuest_GDScript_formatter/plugin.gd b/addons/GDQuest_GDScript_formatter/plugin.gd deleted file mode 100644 index 567b0cc..0000000 --- a/addons/GDQuest_GDScript_formatter/plugin.gd +++ /dev/null @@ -1,741 +0,0 @@ -## This plug-in adds support for automatically formatting GDScript files on save -## and via a command in the Godot Editor, using the GDQuest GDScript Formatter. -## -## It also provides an option to install or update the formatter binary from the GitHub releases. -## -## See our website for more information on the formatter and how to use it: -## https://www.gdquest.com/library/gdscript_formatter/ -@tool -extends EditorPlugin - -const FormatterInstaller = preload("install_and_update.gd") -const FormatterMenu = preload("menu.gd") - -const EDITOR_SETTINGS_CATEGORY = "gdquest_gdscript_formatter/" -const SETTING_FORMAT_ON_SAVE = "format_on_save" -const SETTING_SHORTCUT = "shortcut" -const SETTING_USE_SPACES = "use_spaces" -const SETTING_INDENT_SIZE = "indent_size" -const SETTING_REORDER_CODE = "reorder_code" -const SETTING_SAFE_MODE = "safe_mode" -const SETTING_FORMATTER_PATH = "formatter_path" -const SETTING_LINT_ON_SAVE = "lint_on_save" -const SETTING_LINT_LINE_LENGTH = "lint_line_length" -const SETTING_LINT_IGNORED_RULES = "lint_ignored_rules" -# Directories to ignore when Format on Save is enabled -const SETTING_IGNORED_DIRECTORIES = "format_on_save_ignored_directories" - -const COMMAND_PALETTE_CATEGORY = "gdquest gdscript formatter/" -const COMMAND_PALETTE_FORMAT_SCRIPT = "Format GDScript" -const COMMAND_PALETTE_LINT_SCRIPT = "Lint GDScript" -const COMMAND_PALETTE_INSTALL_UPDATE = "Install or Update Formatter" -const COMMAND_PALETTE_UNINSTALL = "Uninstall Formatter" -const COMMAND_PALETTE_REPORT_ISSUE = "Report Issue" - -var DEFAULT_SETTINGS = { - SETTING_FORMAT_ON_SAVE: false, - SETTING_USE_SPACES: false, - SETTING_INDENT_SIZE: 4, - SETTING_REORDER_CODE: false, - SETTING_SAFE_MODE: true, - SETTING_FORMATTER_PATH: "", - SETTING_LINT_ON_SAVE: false, - SETTING_LINT_LINE_LENGTH: 100, - SETTING_LINT_IGNORED_RULES: "", - SETTING_IGNORED_DIRECTORIES: PackedStringArray(["addons/"]), -} - -## Which gutter lint icons are shown in. -## By default, gutter 0 is for breakpoints and 1 is for things like overrides. -const GUTTER_LINT_ICON_INDEX = 2 -const GUTTER_LINT_ICONS_NAME = "gdscript_formatter_lint_icons" - -var connection_list: Array[Resource] = [] -var installer: FormatterInstaller = null -var formatter_cache_dir: String -var menu: FormatterMenu = null - - -func _init() -> void: - for setting: String in DEFAULT_SETTINGS.keys(): - if not has_editor_setting(setting): - set_editor_setting(setting, DEFAULT_SETTINGS[setting]) - - if not has_editor_setting(SETTING_SHORTCUT): - var default_shortcut := InputEventKey.new() - default_shortcut.echo = false - default_shortcut.pressed = true - default_shortcut.keycode = KEY_I - default_shortcut.ctrl_pressed = true - default_shortcut.shift_pressed = false - default_shortcut.alt_pressed = true - - var shortcut := Shortcut.new() - shortcut.events.push_back(default_shortcut) - - set_editor_setting(SETTING_SHORTCUT, shortcut) - - -func _enter_tree() -> void: - formatter_cache_dir = EditorInterface.get_editor_paths().get_cache_dir().path_join("gdquest") - installer = FormatterInstaller.new(formatter_cache_dir) - add_child(installer) - installer.installation_completed.connect( - func _on_installation_completed(binary_path: String) -> void: - set_editor_setting(SETTING_FORMATTER_PATH, binary_path) - add_format_command() - remove_uninstall_command() - add_uninstall_command() - # After installing the formatter we can add the menu option to show the uninstall command - if is_instance_valid(menu): - menu.update_menu(true) - ) - installer.installation_failed.connect( - func _on_installation_failed(error_message: String) -> void: - push_error("Formatter installation failed: ", error_message) - ) - - add_format_command() - add_lint_command() - add_install_update_command() - add_uninstall_command() - add_report_issue_command() - - menu = FormatterMenu.new() - add_child(menu) - menu.menu_item_selected.connect(_on_menu_item_selected) - menu.update_menu(is_formatter_installed_locally()) - - update_shortcut() - resource_saved.connect(_on_resource_saved) - - -func _exit_tree() -> void: - resource_saved.disconnect(_on_resource_saved) - - remove_format_command() - remove_lint_command() - remove_install_update_command() - remove_uninstall_command() - remove_report_issue_command() - - installer.queue_free() - installer = null - - if is_instance_valid(menu): - menu.menu_item_selected.disconnect(_on_menu_item_selected) - menu.remove_formatter_menu() - menu.queue_free() - menu = null - - -func _shortcut_input(event: InputEvent) -> void: - if not has_command(get_editor_setting(SETTING_FORMATTER_PATH)): - return - var shortcut := get_editor_setting(SETTING_SHORTCUT) as Shortcut - if not is_instance_valid(shortcut): - return - if shortcut.matches_event(event) and event.is_pressed() and not event.is_echo(): - if format_current_script(): - get_tree().root.set_input_as_handled() - - -func format_current_script() -> bool: - if not EditorInterface.get_script_editor().is_visible_in_tree(): - return false - var current_script := EditorInterface.get_script_editor().get_current_script() - if not is_instance_valid(current_script) or not current_script is GDScript: - return false - var code_edit: CodeEdit = EditorInterface.get_script_editor().get_current_editor().get_base_editor() - - var formatted_code := format_code(current_script) - if formatted_code.is_empty(): - return false - - reload_code_edit(code_edit, formatted_code) - return true - - -func lint_current_script() -> bool: - if not EditorInterface.get_script_editor().is_visible_in_tree(): - return false - - var current_script := EditorInterface.get_script_editor().get_current_script() - if not is_instance_valid(current_script) or not current_script is GDScript: - return false - - var code_edit: CodeEdit = EditorInterface.get_script_editor().get_current_editor().get_base_editor() - - var lint_issues := lint_code(current_script) - if lint_issues.is_empty(): - print("No linting issues found.") - clear_lint_highlights(code_edit) - return true - - apply_lint_highlights(code_edit, lint_issues) - print_lint_summary(lint_issues, current_script.resource_path) - - return true - - -func update_shortcut() -> void: - for obj: Resource in connection_list: - obj.changed.disconnect(update_shortcut) - - connection_list.clear() - - var shortcut := get_editor_setting(SETTING_SHORTCUT) as Shortcut - if is_instance_valid(shortcut): - for event: InputEvent in shortcut.events: - if is_instance_valid(event): - event.changed.connect(update_shortcut) - connection_list.push_back(event) - - remove_format_command() - add_format_command() - - -func _on_resource_saved(saved_resource: Resource) -> void: - if saved_resource is not GDScript: - return - - var format_on_save := get_editor_setting(SETTING_FORMAT_ON_SAVE) as bool - var lint_on_save := get_editor_setting(SETTING_LINT_ON_SAVE) as bool - - if not format_on_save and not lint_on_save: - return - - var script := saved_resource as GDScript - - var ignored_directories := get_editor_setting(SETTING_IGNORED_DIRECTORIES) - var path = script.resource_path.trim_prefix("res://") - - var script_path_parts := path.split("/") - - for directory: String in ignored_directories: - var normalized_dir := directory.trim_prefix("res://") - var directory_parts := normalized_dir.split("/") - - var matches := true - for i in range(directory_parts.size()): - if directory_parts[i] != script_path_parts[i]: - matches = false - break - - if matches: - return - - if not has_command(get_editor_setting(SETTING_FORMATTER_PATH)) or not is_instance_valid(script): - return - - if format_on_save: - var formatted_code := format_code(script, false) - if formatted_code.is_empty(): - return - - script.source_code = formatted_code - ResourceSaver.save(script) - # The argument (keep_state parameter) tells Godot to try to preserve the - # state of the script instance, like static variables. Without this, - # attempting to reload tool scripts will fail with an error because they - # are already instantiated in the editor and instantiated scripts are - # not allowed to force reload without unloading first. - script.reload(true) - - var script_editor := EditorInterface.get_script_editor() - var open_script_editors := script_editor.get_open_script_editors() - var open_scripts := script_editor.get_open_scripts() - - if not open_scripts.has(script): - return - - if script_editor.get_current_script() == script: - reload_code_edit(script_editor.get_current_editor().get_base_editor(), formatted_code, true) - elif open_scripts.size() == open_script_editors.size(): - for i: int in range(open_scripts.size()): - if open_scripts[i] == script: - reload_code_edit(open_script_editors[i].get_base_editor(), formatted_code, true) - return - else: - push_error("GDScript Formatter error: Unknown situation, can't reload code editor in Editor. Please report this issue.") - - if lint_on_save: - var code_edit: CodeEdit = EditorInterface.get_script_editor().get_current_editor().get_base_editor() - var lint_issues := lint_code(script) - if lint_issues.is_empty(): - clear_lint_highlights(code_edit) - else: - apply_lint_highlights(code_edit, lint_issues) - print_lint_summary(lint_issues, script.resource_path) - - -func add_format_command() -> void: - if not has_command(get_editor_setting(SETTING_FORMATTER_PATH)): - push_error( - 'GDScript Formatter: The command "%s" can\'t be found in your environment.\n' % get_editor_setting(SETTING_FORMATTER_PATH) + - '\tIf you have not installed the formatter, use the install/update command from the command palette.\n' + - '\tIf you have installed the formatter, change "formatter_path" to a valid command in the "GDScript Formatter" section in Editor Settings.', - ) - return - var shortcut := get_editor_setting(SETTING_SHORTCUT) as Shortcut - EditorInterface.get_command_palette().add_command( - COMMAND_PALETTE_FORMAT_SCRIPT, - COMMAND_PALETTE_CATEGORY + COMMAND_PALETTE_FORMAT_SCRIPT, - format_current_script, - shortcut.get_as_text() if is_instance_valid(shortcut) else "None", - ) - - -func remove_format_command() -> void: - EditorInterface.get_command_palette().remove_command(COMMAND_PALETTE_CATEGORY + COMMAND_PALETTE_FORMAT_SCRIPT) - - -func add_lint_command() -> void: - if not has_command(get_editor_setting(SETTING_FORMATTER_PATH)): - return - - EditorInterface.get_command_palette().add_command( - COMMAND_PALETTE_LINT_SCRIPT, - COMMAND_PALETTE_CATEGORY + COMMAND_PALETTE_LINT_SCRIPT, - lint_current_script, - ) - - -func remove_lint_command() -> void: - EditorInterface.get_command_palette().remove_command( - COMMAND_PALETTE_CATEGORY + COMMAND_PALETTE_LINT_SCRIPT, - ) - - -func add_install_update_command() -> void: - EditorInterface.get_command_palette().add_command( - COMMAND_PALETTE_INSTALL_UPDATE, - COMMAND_PALETTE_CATEGORY + COMMAND_PALETTE_INSTALL_UPDATE, - installer.install_or_update_formatter, - ) - - -func remove_install_update_command() -> void: - EditorInterface.get_command_palette().remove_command(COMMAND_PALETTE_CATEGORY + COMMAND_PALETTE_INSTALL_UPDATE) - - -func add_uninstall_command() -> void: - if is_formatter_installed_locally(): - EditorInterface.get_command_palette().add_command( - COMMAND_PALETTE_UNINSTALL, - COMMAND_PALETTE_CATEGORY + COMMAND_PALETTE_UNINSTALL, - uninstall_formatter, - ) - - -func remove_uninstall_command() -> void: - EditorInterface.get_command_palette().remove_command(COMMAND_PALETTE_CATEGORY + COMMAND_PALETTE_UNINSTALL) - - -func add_report_issue_command() -> void: - EditorInterface.get_command_palette().add_command( - COMMAND_PALETTE_REPORT_ISSUE, - COMMAND_PALETTE_CATEGORY + COMMAND_PALETTE_REPORT_ISSUE, - report_issue, - ) - - -func remove_report_issue_command() -> void: - EditorInterface.get_command_palette().remove_command(COMMAND_PALETTE_CATEGORY + COMMAND_PALETTE_REPORT_ISSUE) - - -func is_formatter_installed_locally() -> bool: - var binary_name := "gdscript-formatter" - if OS.get_name().to_lower().contains("windows"): - binary_name = "gdscript-formatter.exe" - var binary_path := formatter_cache_dir.path_join(binary_name) - return FileAccess.file_exists(binary_path) - - -func uninstall_formatter() -> void: - var binary_name := "gdscript-formatter" - if OS.get_name().to_lower().contains("windows"): - binary_name = "gdscript-formatter.exe" - var binary_path := formatter_cache_dir.path_join(binary_name) - - if FileAccess.file_exists(binary_path): - DirAccess.remove_absolute(binary_path) - print("GDScript formatter uninstalled successfully from: ", binary_path) - set_editor_setting(SETTING_FORMATTER_PATH, DEFAULT_SETTINGS[SETTING_FORMATTER_PATH]) - - remove_format_command() - add_format_command() - remove_uninstall_command() - add_uninstall_command() - if is_instance_valid(menu): - menu.update_menu(false) - else: - push_error("GDScript formatter not found in cache directory: ", binary_path) - - -func reorder_code() -> bool: - if not EditorInterface.get_script_editor().is_visible_in_tree(): - return false - var current_script := EditorInterface.get_script_editor().get_current_script() - if not is_instance_valid(current_script) or not current_script is GDScript: - return false - var code_edit: CodeEdit = EditorInterface.get_script_editor().get_current_editor().get_base_editor() - - var formatted_code := format_code(current_script, true) - if formatted_code.is_empty(): - return false - - reload_code_edit(code_edit, formatted_code) - return true - - -func report_issue() -> void: - OS.shell_open("https://github.com/GDQuest/GDScript-formatter/issues") - - -func show_help() -> void: - OS.shell_open("https://www.gdquest.com/library/gdscript_formatter/") - - -func _on_menu_item_selected(command: String) -> void: - match command: - "format_script": - format_current_script() - "lint_script": - lint_current_script() - "reorder_code": - reorder_code() - "install_update": - installer.install_or_update_formatter() - "uninstall": - uninstall_formatter() - "report_issue": - report_issue() - "help": - show_help() - _: - push_warning("Unsupported command sent from the menu: " + command) - - -func has_command(command: String) -> bool: - var output: Array = [] - var exit_code := OS.execute(command, ["--version"], output) - return exit_code == OK - - -## Reloads the code editor with new text while preserving editor state. -## This includes cursor position, scroll position, breakpoints, bookmarks, and folds. -func reload_code_edit( - code_edit: CodeEdit, - new_text: String, - tag_saved := false, -) -> void: - var editor_state := CodeEditState.new(code_edit) - code_edit.text = new_text - if tag_saved: - code_edit.tag_saved_version() - editor_state.restore_to_editor(code_edit) - code_edit.update_minimum_size() - code_edit.text_changed.emit() - - -func get_editor_setting(setting_name: String) -> Variant: - var editor_settings := EditorInterface.get_editor_settings() - var full_setting_key := EDITOR_SETTINGS_CATEGORY + setting_name - if editor_settings.has_setting(full_setting_key): - return editor_settings.get_setting(full_setting_key) - return DEFAULT_SETTINGS[setting_name] - - -func set_editor_setting(setting_name: String, value: Variant) -> void: - var editor_settings := EditorInterface.get_editor_settings() - var full_setting_key := EDITOR_SETTINGS_CATEGORY + setting_name - editor_settings.set_setting(full_setting_key, value) - - -func has_editor_setting(setting_name: String) -> bool: - var editor_settings := EditorInterface.get_editor_settings() - var full_setting_key := EDITOR_SETTINGS_CATEGORY + setting_name - return editor_settings.has_setting(full_setting_key) - - -## Formats a GDScript file using the GDScript Formatter, -## and returns the formatted code as a string. Optionally reorders the code. -func format_code(script: GDScript, force_reorder := false) -> String: - var script_path := script.resource_path - if script_path.is_empty(): - push_error("GDScript Formatter Error: Can't format an unsaved script.") - return "" - - # This is a bit of a hack to avoid two issues: - # - # 1. Running GDScript formatter on stdin/stdout through Godot with - # OS.execute() has encoding issues with UTF-8 characters and we don't have - # control over the output encoding (it might be assuming ASCII characters) - # - # 2. If we modify a file in place using the external formatter from Godot, - # it will bring up a pop-up that warns users that the file has been changed - # outside Godot. - # - # To work around that, I save a copy of the script as a temporary file, - # format the file, and read it specifically as a UTF-8 string. - var source_file := FileAccess.open(ProjectSettings.globalize_path(script_path), FileAccess.READ) - if not source_file: - push_error("GDScript Formatter Error: Cannot read source file: " + script_path) - return "" - - # FileAccess.get_as_text() reads the file as UTF-8. We use it here and after - # formatting the temporary file. - var source_content := source_file.get_as_text() - source_file.close() - - var path_temporary_file := OS.get_temp_dir().path_join("gdscript_formatter_%d.gd" % Time.get_ticks_msec()) - var temporary_file := FileAccess.open(path_temporary_file, FileAccess.WRITE) - if temporary_file == null: - push_error("GDScript Formatter Error: Cannot create temporary file: " + path_temporary_file) - return "" - temporary_file.store_string(source_content) - temporary_file.close() - - var formatter_arguments := PackedStringArray() - if get_editor_setting(SETTING_USE_SPACES): - formatter_arguments.push_back("--use-spaces") - formatter_arguments.push_back("--indent-size=%d" % get_editor_setting(SETTING_INDENT_SIZE)) - - var should_reorder := force_reorder or get_editor_setting(SETTING_REORDER_CODE) as bool - - if should_reorder: - formatter_arguments.push_back("--reorder-code") - - if get_editor_setting(SETTING_SAFE_MODE): - formatter_arguments.push_back("--safe") - - formatter_arguments.push_back(path_temporary_file) - - var output: Array = [] - var exit_code := OS.execute( - get_editor_setting(SETTING_FORMATTER_PATH), - formatter_arguments, - output, - ) - - var formatted_content := "" - if exit_code == OK: - var result_file := FileAccess.open(path_temporary_file, FileAccess.READ) - if result_file: - formatted_content = result_file.get_as_text() - result_file.close() - else: - push_error("Format GDScript: Cannot read formatted output from temp file") - else: - push_error("Format GDScript failed: " + script_path) - push_error( - "\tExit code: " + str(exit_code) + " Output: " + - (output[0].strip_edges() if output.size() > 0 else "No output"), - ) - push_error('\tIf your script does not have any syntax errors, this might be a formatter bug.') - - if FileAccess.file_exists(path_temporary_file): - DirAccess.remove_absolute(path_temporary_file) - - return formatted_content - - -## Lints a GDScript file using the GDScript Formatter's linter, -## and returns an array of lint issues. -func lint_code(script: GDScript) -> Array: - var script_path := script.resource_path - var output: Array = [] - var formatter_arguments: Array = ["lint", ProjectSettings.globalize_path(script_path)] - - var max_line_length := get_editor_setting(SETTING_LINT_LINE_LENGTH) as int - formatter_arguments.append("--max-line-length") - formatter_arguments.append(str(max_line_length)) - - var ignored_rules := get_editor_setting(SETTING_LINT_IGNORED_RULES) as String - if not ignored_rules.is_empty(): - formatter_arguments.append("--disable") - formatter_arguments.append(ignored_rules) - - var exit_code := OS.execute(get_editor_setting(SETTING_FORMATTER_PATH), formatter_arguments, output) - if exit_code == OK: - return [] # No issues found - - if exit_code == 1: - # Parse lint output - the output is a single string with multiple lines - var issues = [] - for output_item in output: - var lines = output_item.split("\n") - for line in lines: - var trimmed_line = line.strip_edges() - if trimmed_line.is_empty(): - continue - var issue = parse_lint_issue(trimmed_line) - if issue != null and not issue.is_empty(): - issues.push_back(issue) - return issues - - push_error("Lint GDScript failed: " + script_path) - push_error("\tExit code: " + str(exit_code) + " Output: " + (output.front().strip_edges() if output.size() > 0 else "No output")) - return [] - - -## Parses a lint issue line and returns a dictionary with issue information -func parse_lint_issue(line: String) -> Dictionary: - # Expected format: filename:line:rule:severity: message - var regex = RegEx.new() - regex.compile(r"^(.*\.gd):(\d+):([^:]+):([^:]+):([\s\S]*)$") - var result = regex.search(line) - if result: - return { - "line": int(result.get_string(2)) - 1, - "rule": result.get_string(3), - "severity": result.get_string(4), - "message": result.get_string(5).strip_edges(), - } - return { } - - -## Applies lint highlighting to the code editor -func apply_lint_highlights(code_edit: CodeEdit, issues: Array) -> void: - clear_lint_highlights(code_edit) - - # Add and set up gutter for lint icons if not already present. - # We check by name to avoid conflicts with gutters added by other addons. - # Once added, the gutter is never removed so the layout doesn't shift on clear. - var has_lint_gutter := false - for i: int in code_edit.get_gutter_count(): - if code_edit.get_gutter_name(i) == GUTTER_LINT_ICONS_NAME: - has_lint_gutter = true - break - if not has_lint_gutter: - code_edit.add_gutter(GUTTER_LINT_ICON_INDEX) - code_edit.set_gutter_name(GUTTER_LINT_ICON_INDEX, GUTTER_LINT_ICONS_NAME) - code_edit.set_gutter_type(GUTTER_LINT_ICON_INDEX, CodeEdit.GutterType.GUTTER_TYPE_ICON) - const EDITOR_ICON_DEFAULT_WIDTH = 16.0 - code_edit.set_gutter_width(GUTTER_LINT_ICON_INDEX, EDITOR_ICON_DEFAULT_WIDTH * EditorInterface.get_editor_scale()) - - for issue in issues: - var line_number: int = issue.line - var severity: String = issue.severity - - var color := Color(1, 0, 0, 0.1) if severity == "error" else Color(1, 1, 0, 0.1) - code_edit.set_line_background_color(line_number, color) - var icon_name := "StatusError" if severity == "error" else "StatusWarning" - var icon := EditorInterface.get_editor_theme().get_icon(icon_name, "EditorIcons") - code_edit.set_line_gutter_icon(line_number, GUTTER_LINT_ICON_INDEX, icon) - - -## Prints a detailed summary of lint issues to the output -func print_lint_summary(issues: Array, script_path: String) -> void: - print_rich("\n[b]=== Linting Results for %s ===[/b]\n" % script_path) - print_rich("[b]Found [i]%s[/i] issue(s)\n[/b]" % issues.size()) - - for issue in issues: - var line_display = str(issue.line + 1) # Convert back to 1-based for display - var severity_label = issue.severity.to_upper() - print_rich( - "[color=%s]%s[/color] on line [color=cyan]%s[/color] ([i]%s[/i])" % [ - "red" if severity_label == "ERROR" else "yellow", - severity_label, - line_display, - issue.rule, - ], - ) - print_rich("[i]%s[/i]\n" % [issue.message]) - - print_rich("[b]=== End Linting Results ===[/b]\n") - - -## Clears all lint highlighting from the code editor. -## The lint gutter is intentionally kept so the layout does not shift. -func clear_lint_highlights(code_edit: CodeEdit) -> void: - var lint_gutter_index := -1 - for i: int in code_edit.get_gutter_count(): - if code_edit.get_gutter_name(i) == GUTTER_LINT_ICONS_NAME: - lint_gutter_index = i - break - - for line in range(code_edit.get_line_count()): - code_edit.set_line_background_color(line, Color(0, 0, 0, 0)) - if lint_gutter_index != -1: - code_edit.set_line_gutter_icon(line, lint_gutter_index, null) - - -## Data structure to hold code editor state information -class CodeEditState: - var caret_line: int - var caret_column: int - var horizontal_scroll: int - var vertical_scroll: int - var breakpoints: Dictionary[int, String] = { } - var bookmarks: Dictionary[int, String] = { } - var folds: Dictionary[int, String] = { } - var code_edit: CodeEdit - - - func _init(code_edit: CodeEdit) -> void: - self.code_edit = code_edit - caret_line = code_edit.get_caret_line() - caret_column = code_edit.get_caret_column() - horizontal_scroll = code_edit.scroll_horizontal - vertical_scroll = code_edit.scroll_vertical - - for line in code_edit.get_breakpointed_lines(): - breakpoints[line] = code_edit.get_line(line) - for line in code_edit.get_bookmarked_lines(): - bookmarks[line] = code_edit.get_line(line) - for line in code_edit.get_folded_lines(): - folds[line] = code_edit.get_line(line) - - - func restore_to_editor(code_edit: CodeEdit) -> void: - var new_line_count := code_edit.get_line_count() - - _restore_line_features(breakpoints, code_edit.set_line_as_breakpoint, new_line_count) - _restore_line_features(bookmarks, code_edit.set_line_as_bookmarked, new_line_count) - _restore_line_features(folds, func(line: int, _is_folded: bool) -> void: code_edit.fold_line(line), new_line_count) - - code_edit.set_caret_line(caret_line) - code_edit.set_caret_column(caret_column) - - code_edit.scroll_horizontal = horizontal_scroll - code_edit.scroll_vertical = vertical_scroll - - - ## Restores line-based features (breakpoints, bookmarks, folds) by finding the best matching lines - ## in the new text based on similarity to the original line text. - ## - ## Big thanks to https://github.com/Daylily-Zeleen/GDScript-Formatter for this approach. - func _restore_line_features( - stored_features: Dictionary, - set_line_func: Callable, - new_line_count: int, - ) -> void: - var stored_lines := PackedInt64Array(stored_features.keys()) - for line_index in range(stored_lines.size()): - var original_line := stored_lines[line_index] as int - var original_text := stored_features[original_line] as String - - # After formatting lines can move, so we need to find the best match for the original line - # to restore the breakpoints, bookmarks, and folds. - # We first check the same line, then we expand our search outwards until we find a match. - # We use a similarity threshold of 0.9 to account for minor changes in the line text. - # This should be sufficient for most cases, but might need adjustment for edge cases. - # If no match is found, we skip restoring this feature - if original_line < new_line_count and code_edit.get_line(original_line).similarity(original_text) > 0.9: - set_line_func.call(original_line, true) - continue - - var line_above := original_line - 1 - var line_below := original_line + 1 - while line_above >= 0 or line_below < new_line_count: - if line_below < new_line_count and code_edit.get_line(line_below).similarity(original_text) > 0.9: - set_line_func.call(line_below, true) - break - if line_above >= 0 and code_edit.get_line(line_above).similarity(original_text) > 0.9: - set_line_func.call(line_above, true) - break - - line_above -= 1 - line_below += 1 diff --git a/addons/GDQuest_GDScript_formatter/plugin.gd.uid b/addons/GDQuest_GDScript_formatter/plugin.gd.uid deleted file mode 100644 index 4820a46..0000000 --- a/addons/GDQuest_GDScript_formatter/plugin.gd.uid +++ /dev/null @@ -1 +0,0 @@ -uid://cnm61t8d7kib3 diff --git a/creatures/birb/birb.aseprite b/creatures/birb/birb.aseprite deleted file mode 100644 index 6903880..0000000 Binary files a/creatures/birb/birb.aseprite and /dev/null differ diff --git a/creatures/birb/birb.gd b/creatures/birb/birb.gd deleted file mode 100644 index 9f0addf..0000000 --- a/creatures/birb/birb.gd +++ /dev/null @@ -1,40 +0,0 @@ -extends CharacterBody2D - -@export var speed: float = 60.0 -@export var attack_distance: float = 32.0 -@export var think_time: float = 0.2 - -var _target: Player = null -var _time_thought: float = 0.0 - - -func _physics_process(delta: float) -> void: - _time_thought += delta - if _time_thought >= think_time: - _time_thought -= think_time - if _target: - var x_difference: float = _target.position.x - position.x - var distance: float = abs(x_difference) - if abs(distance - attack_distance) > speed * think_time: - var is_too_far_sgn: float = sign(distance - attack_distance) - velocity.x = sign(x_difference) * is_too_far_sgn * speed - else: - velocity.x = 0 - $AnimatedSprite2D.flip_h = x_difference < 0 - else: - velocity.x = 0 - - if not is_on_floor(): - velocity += get_gravity() * delta - - move_and_slide() - - -func _on_detection_body_entered(body: Node2D) -> void: - if body is Player: - _target = body - - -func _on_chase_body_exited(body: Node2D) -> void: - if body == _target: - _target = null diff --git a/creatures/birb/birb.gd.uid b/creatures/birb/birb.gd.uid deleted file mode 100644 index d70e1d9..0000000 --- a/creatures/birb/birb.gd.uid +++ /dev/null @@ -1 +0,0 @@ -uid://c7744j3mcamav diff --git a/creatures/birb/birb.tscn b/creatures/birb/birb.tscn deleted file mode 100644 index 48aa728..0000000 --- a/creatures/birb/birb.tscn +++ /dev/null @@ -1,49 +0,0 @@ -[gd_scene format=3 uid="uid://bosbrhc3oprau"] - -[ext_resource type="Script" uid="uid://c7744j3mcamav" path="res://creatures/birb/birb.gd" id="1_lyo8d"] -[ext_resource type="SpriteFrames" uid="uid://cyf7ij04grglc" path="res://creatures/birb/birb.aseprite" id="2_ba6cv"] - -[sub_resource type="CapsuleShape2D" id="CapsuleShape2D_feb5d"] -radius = 5.0 -height = 14.0 - -[sub_resource type="CircleShape2D" id="CircleShape2D_lyo8d"] -radius = 52.0 - -[sub_resource type="CircleShape2D" id="CircleShape2D_ba6cv"] -radius = 110.0 - -[node name="Birb" type="CharacterBody2D" unique_id=428810294] -collision_layer = 4 -script = ExtResource("1_lyo8d") -metadata/_edit_group_ = true - -[node name="AnimatedSprite2D" type="AnimatedSprite2D" parent="." unique_id=581143480] -sprite_frames = ExtResource("2_ba6cv") - -[node name="CollisionShape2D" type="CollisionShape2D" parent="." unique_id=1744954023] -position = Vector2(0, 1) -shape = SubResource("CapsuleShape2D_feb5d") - -[node name="NavigationAgent2D" type="NavigationAgent2D" parent="." unique_id=1295779953] - -[node name="Detection" type="Area2D" parent="." unique_id=151830843] -collision_layer = 0 -collision_mask = 2 -monitorable = false - -[node name="CollisionShape2D" type="CollisionShape2D" parent="Detection" unique_id=1217467707] -shape = SubResource("CircleShape2D_lyo8d") -debug_color = Color(0, 0.6, 0.69803923, 0.16862746) - -[node name="Chase" type="Area2D" parent="." unique_id=172000915] -collision_layer = 0 -collision_mask = 2 -monitorable = false - -[node name="CollisionShape2D" type="CollisionShape2D" parent="Chase" unique_id=567870323] -shape = SubResource("CircleShape2D_ba6cv") -debug_color = Color(0, 0.6, 0.69803923, 0) - -[connection signal="body_entered" from="Detection" to="." method="_on_detection_body_entered"] -[connection signal="body_exited" from="Chase" to="." method="_on_chase_body_exited"] diff --git a/player/player.gd b/player/player.gd deleted file mode 100644 index 1c5fc94..0000000 --- a/player/player.gd +++ /dev/null @@ -1,186 +0,0 @@ -extends CharacterBody2D - -class_name Player - -@export_custom(PROPERTY_HINT_NONE, "suffix:s") -var max_input_buffer_time := 0.15 -@export_custom(PROPERTY_HINT_NONE, "suffix:s⁻¹") -var grounded_speed_decay := 0.1 -@export_custom(PROPERTY_HINT_NONE, "suffix:s⁻¹") -var grounded_speed_stop_decay := 0.005 -@export_custom(PROPERTY_HINT_NONE, "suffix:px/s") -var walk_max_speed := 130.0 -@export_custom(PROPERTY_HINT_NONE, "suffix:px/s²") -var walk_accel := 600.0 -@export_custom(PROPERTY_HINT_NONE, "suffix:px/s²") -var air_accel := 200.0 -@export_custom(PROPERTY_HINT_NONE, "suffix:s") -var jump_ascent_max_time := 0.2 -@export_custom(PROPERTY_HINT_NONE, "suffix:px/s") -var jump_ascent_speed := 200.0 -@export_custom(PROPERTY_HINT_NONE, "suffix:s") -var late_jump_time_limit := 0.15 -@export_custom(PROPERTY_HINT_NONE, "suffix:px/s") -var slash_speed_boost := 90.0 -## The angle difference from perfect left/right that still counts. -@export_range(0, 360, 0.1, "radians_as_degrees") -var side_input_angle := PI / 4 -## The angle difference from perfect down that still counts. -@export_range(0, 360, 0.1, "radians_as_degrees") -var down_input_angle := PI / 4 - -var _max_input_buffer_time_usec: - get(): - return max_input_buffer_time * 1_000_000 -var _jump_ascent_remaining_time := 0.0 -var _is_jumping := false -var _jump_allowed_time := 0.0 -var _current_direction := Vector2.ZERO -var _is_facing_right := true -@onready var _playback: AnimationNodeStateMachinePlayback = %AnimationTree["parameters/playback"] - -var _input_buffer: Array[BufferedInput] = [] - - -class BufferedInput: - var direction: Vector2 - var event: InputEvent - var time: int - - -func _unhandled_input(event: InputEvent) -> void: - if event.is_echo(): - return - if (event.is_action(&"move_left") - or event.is_action(&"move_right") - or event.is_action(&"move_up") - or event.is_action(&"move_down") ): - _current_direction = Input.get_vector( - &"move_left", - &"move_right", - &"move_up", - &"move_down", - ) - if event.is_action(&"jump") or event.is_action(&"attack"): - var buffered_input := BufferedInput.new() - buffered_input.direction = _current_direction - buffered_input.event = event - buffered_input.time = Time.get_ticks_usec() - _input_buffer.push_back(buffered_input) - handle_buffered_inputs() - - -func _physics_process(delta: float) -> void: - if _current_direction.x < 0: - _is_facing_right = false - elif _current_direction.x > 0: - _is_facing_right = true - - # Walking on the floor - if is_on_floor(): - if sign(velocity.x) != sign(_current_direction.x): - velocity.x *= grounded_speed_stop_decay ** delta - else: - velocity.x *= grounded_speed_decay ** delta - var target_vel_x: float = sign(_current_direction.x) * walk_max_speed - var is_walking := target_vel_x != 0 - if not is_walking or abs(velocity.x) < walk_max_speed: - velocity.x = move_toward( - velocity.x, - target_vel_x, - walk_accel * delta, - ) - # Air control - else: - velocity.x += _current_direction.x * air_accel * delta - - # Move up while holding jump - if _jump_ascent_remaining_time > 0: - velocity.y = -jump_ascent_speed - _jump_ascent_remaining_time -= delta - if _jump_ascent_remaining_time < 0: - velocity += get_gravity() * -_jump_ascent_remaining_time - elif not is_on_floor(): - velocity += get_gravity() * delta - - # Drag while in air - if not is_on_floor() and _jump_ascent_remaining_time <= 0: - var drag_force := -0.01 * velocity * velocity.abs() - velocity += drag_force * delta - - move_and_slide() - - _jump_allowed_time = max(0, _jump_allowed_time - delta) - if is_on_floor(): - _jump_allowed_time = late_jump_time_limit - - if is_on_ceiling(): - _is_jumping = false - _jump_ascent_remaining_time = 0 - - if _is_holding_wall(): - velocity.y = min(5.0, velocity.y) - _is_facing_right = sign(get_wall_normal().x) > 0 - - -func _is_holding_wall() -> bool: - return (not is_on_floor() - and is_on_wall() - and sign(get_wall_normal().x) != sign(_current_direction.x) - and _current_direction.x != 0 ) - - -func _process(_delta: float) -> void: - handle_buffered_inputs() - %Body.scale.x = 1 if _is_facing_right else -1 - - -func handle_buffered_inputs() -> void: - var input_found := false - var current_time := Time.get_ticks_usec() - - # Clear expired input buffer items - while (not _input_buffer.is_empty() - and _input_buffer[0].time + _max_input_buffer_time_usec < current_time ): - _input_buffer.pop_front() - - # Check new commands - for i in _input_buffer.size(): - var input := _input_buffer[i] - if input.event.is_action(&"jump"): - # Grounded jump - if (input.event.is_pressed() - and _jump_allowed_time > 0 - and (not is_on_floor() or not is_input_vec_down(input.direction)) ): - input_found = true - _jump_allowed_time = 0 - _jump_ascent_remaining_time = jump_ascent_max_time - _is_jumping = true - elif (input.event.is_pressed() - and is_on_wall() ): - input_found = true - _jump_allowed_time = 0 - velocity += get_wall_normal() * 200.0 - velocity.y = min(0, velocity.y) - # Jump cuts - elif input.event.is_released() and _is_jumping: - _is_jumping = false - _jump_ascent_remaining_time = 0 - # Jump cut only once, if we're still moving up - if velocity.y < 0: - velocity.y *= 0.1 - elif input.event.is_action_pressed(&"attack"): - input_found = true - velocity.x += (1 if _is_facing_right else -1) * slash_speed_boost - _playback.travel(&"attack") - _input_buffer = _input_buffer.slice(i + 1) - break - $AnimationPlayer.play("slash") - - if input_found: - _input_buffer = _input_buffer.slice(i + 1) - break - - -func is_input_vec_down(vec: Vector2) -> bool: - return abs(vec.angle_to(Vector2.DOWN)) < down_input_angle and vec.length() > 0.1 diff --git a/player/player.gd.uid b/player/player.gd.uid deleted file mode 100644 index 7132e05..0000000 --- a/player/player.gd.uid +++ /dev/null @@ -1 +0,0 @@ -uid://bx500kvj301vt diff --git a/project.godot b/project.godot index 0ce6204..ffa8d4d 100644 --- a/project.godot +++ b/project.godot @@ -12,7 +12,12 @@ config_version=5 config/name="Dancer" run/main_scene="uid://cujd7ltkrnxpt" -config/features=PackedStringArray("4.6", "GL Compatibility") +config/features=PackedStringArray("4.6", "C#", "GL Compatibility") + +[aseprite] + +animation/layers/only_include_visible_layers_by_default=true +import/import_plugin/default_automatic_importer="Static Texture" [display] @@ -24,9 +29,13 @@ window/stretch/mode="viewport" window/stretch/aspect="keep_height" window/vsync/vsync_mode=3 +[dotnet] + +project/assembly_name="Dancer" + [editor_plugins] -enabled=PackedStringArray("res://addons/AsepriteWizard/plugin.cfg", "res://addons/GDQuest_GDScript_formatter/plugin.cfg") +enabled=PackedStringArray("res://addons/AsepriteWizard/plugin.cfg") [input] @@ -69,9 +78,11 @@ attack={ [layer_names] -2d_physics/layer_1="Floors" -2d_physics/layer_2="Player" -2d_physics/layer_3="Enemies" +2d_physics/layer_1="environment" +2d_physics/layer_2="player_hurtbox" +2d_physics/layer_3="enemy_hurtbox" +2d_physics/layer_4="player_hitbox" +2d_physics/layer_5="enemy_hitbox" [physics] diff --git a/rescaler.gd b/rescaler.gd deleted file mode 100644 index 0bf7f5c..0000000 --- a/rescaler.gd +++ /dev/null @@ -1,64 +0,0 @@ -extends Control - -#@export var target_height := 360 -@export var should_round_width_to_evens := true -enum ScalingMode { - ## Scale up to the maximum integer multiple, then linear the rest of the way. - INT_LINEAR, - ## Pure nearest neighbor. - NEAREST, - ## Pure linear. - LINEAR, -} -@export var scaling_mode: ScalingMode = ScalingMode.INT_LINEAR: - set(value): - scaling_mode = value - _update_filters() - -var _previous_factor := 1 -var _event_transform := Transform2D.IDENTITY -var _last_size := Vector2.ZERO -var _target_height: int - -func _ready() -> void: - _update_filters() - var window = get_window() - _target_height = ProjectSettings.get_setting("display/window/size/viewport_height") - window.content_scale_mode = Window.CONTENT_SCALE_MODE_DISABLED - -func _update_filters() -> void: - if not is_node_ready(): return - match scaling_mode: - ScalingMode.INT_LINEAR: - %OuterSprite.texture_filter = TEXTURE_FILTER_LINEAR - %InnerSprite.texture_filter = TEXTURE_FILTER_NEAREST - ScalingMode.NEAREST: - %OuterSprite.texture_filter = TEXTURE_FILTER_NEAREST - %InnerSprite.texture_filter = TEXTURE_FILTER_NEAREST - ScalingMode.LINEAR: - %OuterSprite.texture_filter = TEXTURE_FILTER_LINEAR - %InnerSprite.texture_filter = TEXTURE_FILTER_LINEAR - -func _input(event: InputEvent) -> void: - if Engine.is_editor_hint(): return - %InnerViewport.push_input(event.xformed_by(_event_transform)) - -func _process(_delta: float) -> void: - if _last_size != size: - _resize_viewports() - _last_size = size - -func _resize_viewports() -> void: - var factor: int = max(1, roundi(size.y / float(_target_height))) - if factor != _previous_factor: - _previous_factor = factor - print("Scaling factor switched to %s" % factor) - var rounding_mult: int = 2 if should_round_width_to_evens else 1; - var target_width: int = ceili(float(_target_height) / size.y * size.x / rounding_mult) * rounding_mult - var inner_target_size := Vector2i(target_width, _target_height) - var outer_target_size := factor * inner_target_size - - _event_transform = Transform2D.IDENTITY.scaled(Vector2(inner_target_size) / size) - %OuterViewport.size = outer_target_size - %InnerViewport.size = inner_target_size - %InnerSprite.scale = Vector2(factor, factor) diff --git a/rescaler.gd.uid b/rescaler.gd.uid deleted file mode 100644 index e9f3330..0000000 --- a/rescaler.gd.uid +++ /dev/null @@ -1 +0,0 @@ -uid://vu7n2fqv8nci diff --git a/script_templates/Node/AutoNode.cs b/script_templates/Node/AutoNode.cs new file mode 100644 index 0000000..31752d3 --- /dev/null +++ b/script_templates/Node/AutoNode.cs @@ -0,0 +1,11 @@ +// meta-name: IAutoNode enabled Node +// meta-default: true +// meta-space-indent: 2 + +namespace Dancer; + +[Meta(typeof(IAutoNode))] +public sealed partial class _CLASS_ : _BASE_ +{ + public override void _Notification(int what) => this.Notify(what); +} diff --git a/script_templates/Node/AutoNode.cs.uid b/script_templates/Node/AutoNode.cs.uid new file mode 100644 index 0000000..d70bd49 --- /dev/null +++ b/script_templates/Node/AutoNode.cs.uid @@ -0,0 +1 @@ +uid://dqlh48eqmee0s diff --git a/spring2d.gd b/spring2d.gd deleted file mode 100644 index f9fa5b7..0000000 --- a/spring2d.gd +++ /dev/null @@ -1,17 +0,0 @@ -extends Node2D - -@export var max_offset := Vector2.ONE - -var _last_global_position: Vector2 -var _local_offset: Vector2 - -func _ready() -> void: - _last_global_position = global_position - _local_offset = position - -func _process(_delta: float) -> void: - var parent_position: Vector2 = get_parent().global_position - var target_position := parent_position + _local_offset - var new_position: Vector2 = lerp(_last_global_position, target_position, 0.4) - global_position = target_position + (new_position - target_position).clamp(-max_offset, max_offset) - _last_global_position = global_position diff --git a/spring2d.gd.uid b/spring2d.gd.uid deleted file mode 100644 index e356b82..0000000 --- a/spring2d.gd.uid +++ /dev/null @@ -1 +0,0 @@ -uid://b7shvbf7iv6an diff --git a/src/Game.cs b/src/Game.cs new file mode 100644 index 0000000..3b54764 --- /dev/null +++ b/src/Game.cs @@ -0,0 +1,14 @@ +using Chickensoft.LogicBlocks.Auto; + +namespace Dancer; + +[Meta(typeof(IAutoNode))] +public sealed partial class Game : Node2D +{ + public override void _Notification(int what) => this.Notify(what); + public override void _Ready() + { + LogicBlockSerialization.Setup(); + } +} + diff --git a/src/Game.cs.uid b/src/Game.cs.uid new file mode 100644 index 0000000..540b92a --- /dev/null +++ b/src/Game.cs.uid @@ -0,0 +1 @@ +uid://cjnisd5qmc15u diff --git a/src/_assembly.cs b/src/_assembly.cs new file mode 100644 index 0000000..0b058d3 --- /dev/null +++ b/src/_assembly.cs @@ -0,0 +1,3 @@ +global using Chickensoft.AutoInject; +global using Chickensoft.Introspection; +global using Godot; diff --git a/src/_assembly.cs.uid b/src/_assembly.cs.uid new file mode 100644 index 0000000..48156a1 --- /dev/null +++ b/src/_assembly.cs.uid @@ -0,0 +1 @@ +uid://71cboxjhmfys diff --git a/src/combat/Attack.cs b/src/combat/Attack.cs new file mode 100644 index 0000000..2d61353 --- /dev/null +++ b/src/combat/Attack.cs @@ -0,0 +1,8 @@ +namespace Dancer; + +public sealed class Attack +{ + public required Node2D Attacker { get; init; } + public float Damage { get; init; } = 1f; + public Vector2 Impulse { get; init; } = Vector2.Zero; +} diff --git a/src/combat/Attack.cs.uid b/src/combat/Attack.cs.uid new file mode 100644 index 0000000..1b64215 --- /dev/null +++ b/src/combat/Attack.cs.uid @@ -0,0 +1 @@ +uid://cs5drdr0376sy diff --git a/src/combat/IAttackable.cs b/src/combat/IAttackable.cs new file mode 100644 index 0000000..7418bac --- /dev/null +++ b/src/combat/IAttackable.cs @@ -0,0 +1,6 @@ +namespace Dancer; + +public interface IAttackable +{ + public void GetAttacked(in Attack attack); +} diff --git a/src/combat/IAttackable.cs.uid b/src/combat/IAttackable.cs.uid new file mode 100644 index 0000000..ba02974 --- /dev/null +++ b/src/combat/IAttackable.cs.uid @@ -0,0 +1 @@ +uid://cu2ivuj6ulfv5 diff --git a/src/creatures/birb/Birb.cs b/src/creatures/birb/Birb.cs new file mode 100644 index 0000000..2f8308e --- /dev/null +++ b/src/creatures/birb/Birb.cs @@ -0,0 +1,169 @@ +using System; +using Chickensoft.LogicBlocks; +using Chickensoft.LogicBlocks.Auto; + +namespace Dancer; + +[Meta(typeof(IAutoNode))] +public sealed partial class Birb : CharacterBody2D, IAttackable +{ + public override void _Notification(int what) => this.Notify(what); + + [Export] public float Speed { get; set; } = 60f; + [Export] public float AttackDistance { get; set; } = 32f; + [Export] public float ThinkTime { get; set; } = 0.2f; + [Export] public float Weight { get; set; } = 20f; + [Export] public float MaxHp { get; set; } = 4f; + + [Node] private ProgressBar HealthBar { get; set; } = null!; + [Node] private AnimatedSprite2D BodySprite { get; set; } = null!; + + private float _hp; + private float _timeThought; + private Node2D? _target; + private float _targetVelocity; + + public override void _Ready() + { + _hp = MaxHp; + HealthBar.MinValue = 0f; + HealthBar.MaxValue = MaxHp; + } + + public override void _PhysicsProcess(double delta) + { + _timeThought += (float)delta; + if (_timeThought >= ThinkTime) + { + _timeThought -= ThinkTime; + if (_target is not null) + { + var xDifference = _target.Position.X - Position.X; + var distance = Mathf.Abs(xDifference); + if (Mathf.Abs(distance - AttackDistance) > Speed * ThinkTime) + _targetVelocity = Mathf.Sign(xDifference) * Mathf.Sign(distance - AttackDistance) * Speed; + else + _targetVelocity = 0f; + BodySprite.FlipH = xDifference < 0; + } + else + _targetVelocity = 0f; + } + + Velocity = Velocity with + { + X = Mathf.MoveToward(Velocity.X, _targetVelocity, (float)delta * 500f) + }; + + if (!IsOnFloor()) Velocity += GetGravity() * (float)delta; + + MoveAndSlide(); + } + + public override void _Process(double delta) + { + HealthBar.Value = _hp; + HealthBar.Visible = _hp < MaxHp; + } + + public void OnDetectionBodyEntered(Node2D body) => _target = body; + + public void OnChaseBodyExited(Node2D body) + { + if (body == _target) _target = null; + } + + public void GetAttacked(in Attack attack) + { + _hp -= attack.Damage; + Velocity += attack.Impulse / Weight; + if (_hp <= 0.01) QueueFree(); + } + + [Meta] + public sealed partial class Logic : AutoBlock + { + public sealed record Data + { + public required Birb Birb { get; set; } + public float DurationLeft { get; set; } + public Node2D? Target { get; set; } + } + + public Logic(Birb birb) + { + Set(new Data { Birb = birb }); + Preallocate(); + } + + public static class Input + { + public readonly record struct TimerFinished; + } + + [Meta, StateDiagram] + public abstract partial record Root : LogicBlockState + { + public virtual void OnPhysicsProcess(double delta) + { + } + + [Meta] + public sealed partial record Idle : Root; + + [Meta] + public abstract partial record Fight : Root + { + [Meta] + public sealed partial record Think : Fight, IGet + { + public Think() + { + this.OnEnter(() => Get().DurationLeft = (float)GD.RandRange(0.3, 0.6)); + } + + public override void OnPhysicsProcess(double delta) + { + var data = Get(); + data.DurationLeft -= (float)delta; + if (data.DurationLeft <= 0f) Input(new Input.TimerFinished()); + } + + public Type On(in Input.TimerFinished input) + { + var data = Get(); + if (data.Target is not { } target) return To(); + return target.GlobalPosition.DistanceTo(data.Birb.GlobalPosition) < + data.Birb.AttackDistance + ? To() + : To(); + } + } + + [Meta] + public sealed partial record StepToPosition : Fight; + + [Meta] + public sealed partial record PrepareStrike : Fight, IGet + { + public PrepareStrike() + { + this.OnEnter(() => Get().DurationLeft = (float)GD.RandRange(0.7, 0.9)); + } + + public override void OnPhysicsProcess(double delta) + { + var data = Get(); + data.DurationLeft -= (float)delta; + if (data.DurationLeft <= 0f) Input(new Input.TimerFinished()); + } + + public Type On(in Input.TimerFinished input) => To(); + } + + [Meta] + public sealed partial record Stab : Fight; + } + } + } +} diff --git a/src/creatures/birb/Birb.cs.uid b/src/creatures/birb/Birb.cs.uid new file mode 100644 index 0000000..c4e9276 --- /dev/null +++ b/src/creatures/birb/Birb.cs.uid @@ -0,0 +1 @@ +uid://daowp76saltic diff --git a/src/creatures/birb/birb.aseprite b/src/creatures/birb/birb.aseprite new file mode 100644 index 0000000..b28821d Binary files /dev/null and b/src/creatures/birb/birb.aseprite differ diff --git a/creatures/birb/birb.aseprite.import b/src/creatures/birb/birb.aseprite.import similarity index 57% rename from creatures/birb/birb.aseprite.import rename to src/creatures/birb/birb.aseprite.import index 5a013a1..52fb224 100644 --- a/creatures/birb/birb.aseprite.import +++ b/src/creatures/birb/birb.aseprite.import @@ -3,12 +3,12 @@ importer="aseprite_wizard.plugin.spriteframes" type="SpriteFrames" uid="uid://cyf7ij04grglc" -path="res://.godot/imported/birb.aseprite-08ecd7f619e0f36def567cf6f5194cc3.res" +path="res://.godot/imported/birb.aseprite-70cec5e9f1931c6cd2bc1e2936bb8cc0.res" [deps] -source_file="res://creatures/birb/birb.aseprite" -dest_files=["res://.godot/imported/birb.aseprite-08ecd7f619e0f36def567cf6f5194cc3.res"] +source_file="res://src/creatures/birb/birb.aseprite" +dest_files=["res://.godot/imported/birb.aseprite-70cec5e9f1931c6cd2bc1e2936bb8cc0.res"] [params] diff --git a/src/creatures/birb/birb.tscn b/src/creatures/birb/birb.tscn new file mode 100644 index 0000000..8556729 --- /dev/null +++ b/src/creatures/birb/birb.tscn @@ -0,0 +1,195 @@ +[gd_scene format=3 uid="uid://bosbrhc3oprau"] + +[ext_resource type="Script" uid="uid://daowp76saltic" path="res://src/creatures/birb/Birb.cs" id="1_lyo8d"] +[ext_resource type="SpriteFrames" uid="uid://cyf7ij04grglc" path="res://src/creatures/birb/birb.aseprite" id="2_ba6cv"] + +[sub_resource type="CapsuleShape2D" id="CapsuleShape2D_feb5d"] +radius = 5.0 +height = 14.0 + +[sub_resource type="CircleShape2D" id="CircleShape2D_lyo8d"] +radius = 52.0 + +[sub_resource type="CircleShape2D" id="CircleShape2D_ba6cv"] +radius = 110.0 + +[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_lyo8d"] +bg_color = Color(0.15, 0.15, 0.15, 0.34509805) + +[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_ba6cv"] +bg_color = Color(0.73, 0.10949998, 0.14052509, 0.8666667) + +[sub_resource type="Animation" id="Animation_lyo8d"] +length = 0.001 +step = 0.1 +tracks/0/type = "value" +tracks/0/imported = false +tracks/0/enabled = true +tracks/0/path = NodePath("BodySprite:animation") +tracks/0/interp = 1 +tracks/0/loop_wrap = true +tracks/0/keys = { +"times": PackedFloat32Array(0), +"transitions": PackedFloat32Array(1), +"update": 1, +"values": [&"idle"] +} +tracks/1/type = "value" +tracks/1/imported = false +tracks/1/enabled = true +tracks/1/path = NodePath("BodySprite:frame") +tracks/1/interp = 1 +tracks/1/loop_wrap = true +tracks/1/keys = { +"times": PackedFloat32Array(0), +"transitions": PackedFloat32Array(1), +"update": 1, +"values": [0] +} + +[sub_resource type="Animation" id="Animation_ba6cv"] +resource_name = "idle" +loop_mode = 1 +step = 0.1 +tracks/0/type = "value" +tracks/0/imported = false +tracks/0/enabled = true +tracks/0/path = NodePath("BodySprite:animation") +tracks/0/interp = 1 +tracks/0/loop_wrap = true +tracks/0/keys = { +"times": PackedFloat32Array(0), +"transitions": PackedFloat32Array(1), +"update": 1, +"values": [&"idle"] +} +tracks/1/type = "value" +tracks/1/imported = false +tracks/1/enabled = true +tracks/1/path = NodePath("BodySprite:frame") +tracks/1/interp = 1 +tracks/1/loop_wrap = true +tracks/1/keys = { +"times": PackedFloat32Array(0), +"transitions": PackedFloat32Array(1), +"update": 1, +"values": [0] +} + +[sub_resource type="Animation" id="Animation_1i6dk"] +resource_name = "prepare_attack" +step = 0.1 +tracks/0/type = "value" +tracks/0/imported = false +tracks/0/enabled = true +tracks/0/path = NodePath("BodySprite:animation") +tracks/0/interp = 1 +tracks/0/loop_wrap = true +tracks/0/keys = { +"times": PackedFloat32Array(0), +"transitions": PackedFloat32Array(1), +"update": 1, +"values": [&"prepare_attack"] +} +tracks/1/type = "value" +tracks/1/imported = false +tracks/1/enabled = true +tracks/1/path = NodePath("BodySprite:frame") +tracks/1/interp = 1 +tracks/1/loop_wrap = true +tracks/1/keys = { +"times": PackedFloat32Array(0), +"transitions": PackedFloat32Array(1), +"update": 1, +"values": [0] +} + +[sub_resource type="Animation" id="Animation_3ly8m"] +resource_name = "stab" +step = 0.1 +tracks/0/type = "value" +tracks/0/imported = false +tracks/0/enabled = true +tracks/0/path = NodePath("BodySprite:animation") +tracks/0/interp = 1 +tracks/0/loop_wrap = true +tracks/0/keys = { +"times": PackedFloat32Array(0), +"transitions": PackedFloat32Array(1), +"update": 1, +"values": [&"stab"] +} +tracks/1/type = "value" +tracks/1/imported = false +tracks/1/enabled = true +tracks/1/path = NodePath("BodySprite:frame") +tracks/1/interp = 1 +tracks/1/loop_wrap = true +tracks/1/keys = { +"times": PackedFloat32Array(0), +"transitions": PackedFloat32Array(1), +"update": 1, +"values": [0] +} + +[sub_resource type="AnimationLibrary" id="AnimationLibrary_1i6dk"] +_data = { +&"RESET": SubResource("Animation_lyo8d"), +&"idle": SubResource("Animation_ba6cv"), +&"prepare_attack": SubResource("Animation_1i6dk"), +&"stab": SubResource("Animation_3ly8m") +} + +[node name="Birb" type="CharacterBody2D" unique_id=428810294] +collision_layer = 4 +script = ExtResource("1_lyo8d") +metadata/_edit_group_ = true + +[node name="BodySprite" type="AnimatedSprite2D" parent="." unique_id=581143480] +unique_name_in_owner = true +position = Vector2(2, -4) +sprite_frames = ExtResource("2_ba6cv") +animation = &"idle" + +[node name="CollisionShape2D" type="CollisionShape2D" parent="." unique_id=1744954023] +position = Vector2(0, 1) +shape = SubResource("CapsuleShape2D_feb5d") + +[node name="Detection" type="Area2D" parent="." unique_id=151830843] +collision_layer = 0 +collision_mask = 2 +monitorable = false + +[node name="CollisionShape2D" type="CollisionShape2D" parent="Detection" unique_id=1217467707] +shape = SubResource("CircleShape2D_lyo8d") +debug_color = Color(0, 0.6, 0.69803923, 0.16862746) + +[node name="Chase" type="Area2D" parent="." unique_id=172000915] +collision_layer = 0 +collision_mask = 2 +monitorable = false + +[node name="CollisionShape2D" type="CollisionShape2D" parent="Chase" unique_id=567870323] +shape = SubResource("CircleShape2D_ba6cv") +debug_color = Color(0, 0.6, 0.69803923, 0) + +[node name="HealthBar" type="ProgressBar" parent="." unique_id=369348156] +unique_name_in_owner = true +anchors_preset = 5 +anchor_left = 0.5 +anchor_right = 0.5 +offset_left = -10.0 +offset_top = -12.0 +offset_right = 10.0 +offset_bottom = -10.0 +grow_horizontal = 2 +theme_override_styles/background = SubResource("StyleBoxFlat_lyo8d") +theme_override_styles/fill = SubResource("StyleBoxFlat_ba6cv") +value = 50.0 +show_percentage = false + +[node name="AnimationPlayer" type="AnimationPlayer" parent="." unique_id=695394949] +libraries/ = SubResource("AnimationLibrary_1i6dk") + +[connection signal="body_entered" from="Detection" to="." method="OnDetectionBodyEntered"] +[connection signal="body_exited" from="Chase" to="." method="OnChaseBodyExited"] diff --git a/game.tscn b/src/game.tscn similarity index 98% rename from game.tscn rename to src/game.tscn index e15258b..142d16f 100644 --- a/game.tscn +++ b/src/game.tscn @@ -1,8 +1,9 @@ [gd_scene format=4 uid="uid://cujd7ltkrnxpt"] -[ext_resource type="Texture2D" uid="uid://dkxcdqm8dgdq7" path="res://level/tiles_0.aseprite" id="1_80nbo"] -[ext_resource type="PackedScene" uid="uid://bosbrhc3oprau" path="res://creatures/birb/birb.tscn" id="2_fc0e3"] -[ext_resource type="PackedScene" uid="uid://ce2k04khaub8n" path="res://player/player.tscn" id="2_feb5d"] +[ext_resource type="Texture2D" uid="uid://dkxcdqm8dgdq7" path="res://src/level/tiles_0.aseprite" id="1_80nbo"] +[ext_resource type="Script" uid="uid://cjnisd5qmc15u" path="res://src/Game.cs" id="1_kc8ui"] +[ext_resource type="PackedScene" uid="uid://bosbrhc3oprau" path="res://src/creatures/birb/birb.tscn" id="2_fc0e3"] +[ext_resource type="PackedScene" uid="uid://ce2k04khaub8n" path="res://src/player/player.tscn" id="2_feb5d"] [sub_resource type="TileSetAtlasSource" id="TileSetAtlasSource_e2o6t"] texture = ExtResource("1_80nbo") @@ -96,6 +97,7 @@ terrain_set_0/terrain_0/color = Color(0.5, 0.34375, 0.25, 1) sources/2 = SubResource("TileSetAtlasSource_e2o6t") [node name="Game" type="Node2D" unique_id=1186062666] +script = ExtResource("1_kc8ui") [node name="TileMapLayer" type="TileMapLayer" parent="." unique_id=462402070] z_index = -100 diff --git a/level/tiles_0.aseprite b/src/level/tiles_0.aseprite similarity index 100% rename from level/tiles_0.aseprite rename to src/level/tiles_0.aseprite diff --git a/level/tiles_0.aseprite.import b/src/level/tiles_0.aseprite.import similarity index 58% rename from level/tiles_0.aseprite.import rename to src/level/tiles_0.aseprite.import index afcaa50..56970af 100644 --- a/level/tiles_0.aseprite.import +++ b/src/level/tiles_0.aseprite.import @@ -3,12 +3,12 @@ importer="aseprite_wizard.plugin.static-texture" type="PortableCompressedTexture2D" uid="uid://dkxcdqm8dgdq7" -path="res://.godot/imported/tiles_0.aseprite-bbd58d49bb546d7520c8a6f61f74b532.res" +path="res://.godot/imported/tiles_0.aseprite-88b641c9e3407952b30dd9ebb5ab058f.res" [deps] -source_file="res://level/tiles_0.aseprite" -dest_files=["res://.godot/imported/tiles_0.aseprite-bbd58d49bb546d7520c8a6f61f74b532.res"] +source_file="res://src/level/tiles_0.aseprite" +dest_files=["res://.godot/imported/tiles_0.aseprite-88b641c9e3407952b30dd9ebb5ab058f.res"] [params] diff --git a/src/player/Player.cs b/src/player/Player.cs new file mode 100644 index 0000000..16ae201 --- /dev/null +++ b/src/player/Player.cs @@ -0,0 +1,300 @@ +using System.Collections.Generic; + +namespace Dancer; + +using Godot; +using Chickensoft.AutoInject; +using Chickensoft.Introspection; + +[Meta(typeof(IAutoNode))] +public sealed partial class Player : CharacterBody2D +{ + public override void _Notification(int what) => this.Notify(what); + + [Export(PropertyHint.None, "suffix:s")] + public float MaxInputBufferTime { get; set; } = 0.15f; + + [Export(PropertyHint.None, "suffix:s⁻¹")] + public float GroundedSpeedDecay { get; set; } = 0.1f; + + [Export(PropertyHint.None, "suffix:s⁻¹")] + public float GroundedSpeedStopDecay { get; set; } = 0.005f; + + [Export(PropertyHint.None, "suffix:px/s")] + public float WalkMaxSpeed { get; set; } = 130.0f; + + [Export(PropertyHint.None, "suffix:px/s²")] + public float WalkAccel { get; set; } = 600.0f; + + [Export(PropertyHint.None, "suffix:px/s²")] + public float AirAccel { get; set; } = 200.0f; + + [Export(PropertyHint.None, "suffix:s")] + public float JumpAscentMaxTime { get; set; } = 0.2f; + + [Export(PropertyHint.None, "suffix:px/s")] + public float JumpAscentSpeed { get; set; } = 200.0f; + + [Export(PropertyHint.None, "suffix:s")] + public float LateJumpTimeLimit { get; set; } = 0.15f; + + [Export(PropertyHint.None, "suffix:s")] + public float SlashSpeedBoost { get; set; } = 90.0f; + + /// The angle difference from perfect left/right that still counts. + [Export(PropertyHint.Range, "0,360,0.1,radians_as_degrees")] + public float SideInputAngle { get; set; } = Mathf.Pi / 4; + + /// The angle difference from perfect down that still counts. + [Export(PropertyHint.Range, "0,360,0.1,radians_as_degrees")] + public float DownInputAngle { get; set; } = Mathf.Pi / 4; + + private ulong MaxInputBufferTimeMicroseconds => (ulong)(MaxInputBufferTime * 1_000_000); + + private float _jumpAscentRemainingTime; + private bool _isJumping; + private float _jumpAllowedTime; + private Vector2 _currentDirection = Vector2.Zero; + private bool _isFacingRight = true; + + private AnimationNodeStateMachinePlayback _playback = null!; + private List _inputBuffer = []; + + [Node] private AnimationTree AnimationTree { get; set; } = null!; + + public override void _Ready() + { + _playback = AnimationTree.Get("parameters/playback").As(); + } + + public override void _UnhandledInput(InputEvent @event) + { + if (@event.IsEcho()) + return; + + if ( + @event.IsAction("move_left") + || @event.IsAction("move_right") + || @event.IsAction("move_up") + || @event.IsAction("move_down")) + { + _currentDirection = Input.GetVector( + "move_left", + "move_right", + "move_up", + "move_down"); + } + + if (@event.IsAction("jump") || @event.IsAction("attack")) + { + _inputBuffer.Add(new() + { + Direction = _currentDirection, + Event = @event, + Time = Time.GetTicksUsec() + }); + HandleBufferedInputs(); + } + } + + public override void _PhysicsProcess(double delta) + { + var deltaF = (float)delta; + + if (_currentDirection.X < 0) + _isFacingRight = false; + else if (_currentDirection.X > 0) + _isFacingRight = true; + + // Walking on the floor + if (IsOnFloor()) + { + if (Mathf.Sign(Velocity.X) != Mathf.Sign(_currentDirection.X)) + Velocity = Velocity with { X = Velocity.X * Mathf.Pow(GroundedSpeedStopDecay, deltaF) }; + else + Velocity = Velocity with { X = Velocity.X * Mathf.Pow(GroundedSpeedDecay, deltaF) }; + + var targetVelX = Mathf.Sign(_currentDirection.X) * WalkMaxSpeed; + var isWalking = targetVelX != 0; + + if (!isWalking || Mathf.Abs(Velocity.X) < WalkMaxSpeed) + { + Velocity = Velocity with + { + X = Mathf.MoveToward(Velocity.X, targetVelX, WalkAccel * deltaF) + }; + } + } + // Air control + else + { + Velocity = Velocity with { X = Velocity.X + _currentDirection.X * AirAccel * deltaF }; + } + + // Move up while holding jump + if (_jumpAscentRemainingTime > 0) + { + Velocity = Velocity with { Y = -JumpAscentSpeed }; + _jumpAscentRemainingTime -= deltaF; + if (_jumpAscentRemainingTime < 0) + Velocity += GetGravity() * -_jumpAscentRemainingTime; + } + else if (!IsOnFloor()) + { + Velocity += GetGravity() * deltaF; + } + + // Drag while in air + if (!IsOnFloor() && _jumpAscentRemainingTime <= 0) + { + var dragForce = -0.01f * Velocity * Velocity.Abs(); + Velocity += dragForce * deltaF; + } + + MoveAndSlide(); + + _jumpAllowedTime = Mathf.Max(0, _jumpAllowedTime - deltaF); + if (IsOnFloor()) + _jumpAllowedTime = LateJumpTimeLimit; + + if (IsOnCeiling()) + { + _isJumping = false; + _jumpAscentRemainingTime = 0.0f; + } + + if (IsHoldingWall()) + { + Velocity = Velocity with { Y = Mathf.Min(5.0f, Velocity.Y) }; + _isFacingRight = Mathf.Sign(GetWallNormal().X) > 0; + } + } + + private bool IsHoldingWall() + { + return + !IsOnFloor() + && IsOnWall() + && Mathf.Sign(GetWallNormal().X) != Mathf.Sign(_currentDirection.X) + && _currentDirection.X != 0; + } + + public override void _Process(double delta) + { + HandleBufferedInputs(); + GetNode("%Body").Scale = new(_isFacingRight ? 1 : -1, 1); + } + + private void HandleBufferedInputs() + { + var inputFound = false; + var currentTime = Time.GetTicksUsec(); + + // Clear expired input buffer items + while ( + _inputBuffer.Count > 0 + && _inputBuffer[0].Time + MaxInputBufferTimeMicroseconds < currentTime) + { + _inputBuffer.RemoveAt(0); + } + + // Check new commands + for (var i = 0; i < _inputBuffer.Count; i++) + { + var input = _inputBuffer[i]; + + if (input.Event.IsAction("jump")) + { + if ( + input.Event.IsPressed() + && _jumpAllowedTime > 0 + && (!IsOnFloor() || !IsInputVecDown(input.Direction))) + { + inputFound = true; + GroundJump(); + } + else if (input.Event.IsPressed() && IsOnWall()) + { + inputFound = true; + WallJump(); + } + else if (input.Event.IsReleased() && _isJumping) + { + JumpCut(); + } + } + else if (input.Event.IsActionPressed("attack")) + { + inputFound = true; + Slash(); + } + + if (inputFound) + { + _inputBuffer = _inputBuffer.GetRange(i + 1, _inputBuffer.Count - i - 1); + break; + } + } + } + + private void GroundJump() + { + _jumpAllowedTime = 0.0f; + _jumpAscentRemainingTime = JumpAscentMaxTime; + _isJumping = true; + } + + private void WallJump() + { + _jumpAllowedTime = 0.0f; + Velocity += GetWallNormal() * 200.0f; + Velocity = Velocity with { Y = Mathf.Min(0, Velocity.Y) }; + } + + private void JumpCut() + { + _isJumping = false; + _jumpAscentRemainingTime = 0.0f; + // Jump cut only once, if we're still moving up + if (Velocity.Y < 0) + Velocity = Velocity with { Y = Velocity.Y * 0.1f }; + } + + private void Slash() + { + Velocity = Velocity with + { + X = Velocity.X + (_isFacingRight ? 1 : -1) * SlashSpeedBoost + }; + _playback.Travel("attack"); + + var instance = GD.Load("res://src/player/slash_projectile.tscn") + .Instantiate(); + AddChild(instance); + instance.GlobalTransform = GetNode("%HandAttachment").GlobalTransform; + instance.HitboxEntered += OnEnemyHit; + } + + private bool IsInputVecDown(Vector2 vec) + { + return Mathf.Abs(vec.AngleTo(Vector2.Down)) < DownInputAngle && vec.Length() > 0.1f; + } + + private void OnEnemyHit(Node2D enemy) + { + if (enemy is not IAttackable attackable) return; + attackable.GetAttacked(new() + { + Attacker = this, + Damage = 1.0f, + Impulse = Vector2.Down * 5000.0f + (enemy.Position - Position).Normalized() * 5000.0f + }); + } + + public class BufferedInput + { + public Vector2 Direction { get; init; } + public required InputEvent Event { get; init; } + public ulong Time { get; init; } + } +} diff --git a/src/player/Player.cs.uid b/src/player/Player.cs.uid new file mode 100644 index 0000000..d4c0737 --- /dev/null +++ b/src/player/Player.cs.uid @@ -0,0 +1 @@ +uid://b5iey2typf2tb diff --git a/src/player/SlashProjectile.cs b/src/player/SlashProjectile.cs new file mode 100644 index 0000000..88964e5 --- /dev/null +++ b/src/player/SlashProjectile.cs @@ -0,0 +1,17 @@ +namespace Dancer; + +using Godot; +using Chickensoft.AutoInject; +using Chickensoft.Introspection; + +[Meta(typeof(IAutoNode))] +public sealed partial class SlashProjectile : Node2D +{ + public override void _Notification(int what) => this.Notify(what); + + [Signal] + public delegate void HitboxEnteredEventHandler(Node2D other); + + public void OnAttackFinished() => QueueFree(); + public void OnHitboxBodyEntered(Node2D body) => EmitSignalHitboxEntered(body); +} diff --git a/src/player/SlashProjectile.cs.uid b/src/player/SlashProjectile.cs.uid new file mode 100644 index 0000000..e373437 --- /dev/null +++ b/src/player/SlashProjectile.cs.uid @@ -0,0 +1 @@ +uid://0n1gv56pcc74 diff --git a/src/player/attack.aseprite b/src/player/attack.aseprite new file mode 100644 index 0000000..69fd86c Binary files /dev/null and b/src/player/attack.aseprite differ diff --git a/src/player/attack.aseprite.import b/src/player/attack.aseprite.import new file mode 100644 index 0000000..ff91c5a --- /dev/null +++ b/src/player/attack.aseprite.import @@ -0,0 +1,21 @@ +[remap] + +importer="aseprite_wizard.plugin.static-texture" +type="PortableCompressedTexture2D" +uid="uid://jdmsv25yp25v" +path="res://.godot/imported/attack.aseprite-0b3d00875a10a8cf04bab0910589e119.res" + +[deps] + +source_file="res://src/player/attack.aseprite" +dest_files=["res://.godot/imported/attack.aseprite-0b3d00875a10a8cf04bab0910589e119.res"] + +[params] + +layer/exclude_layers_pattern="" +layer/only_visible_layers=true +layer/split_layers=false +first_frame_only=false +sheet/sheet_type="horizontal" +sheet/sheet_columns=12 +sheet/scale=1 diff --git a/player/hair.aseprite b/src/player/hair.aseprite similarity index 100% rename from player/hair.aseprite rename to src/player/hair.aseprite diff --git a/player/hair.aseprite.import b/src/player/hair.aseprite.import similarity index 59% rename from player/hair.aseprite.import rename to src/player/hair.aseprite.import index 21e5e94..b76d53d 100644 --- a/player/hair.aseprite.import +++ b/src/player/hair.aseprite.import @@ -3,12 +3,12 @@ importer="aseprite_wizard.plugin.static-texture" type="PortableCompressedTexture2D" uid="uid://blw6f2ktsrcmg" -path="res://.godot/imported/hair.aseprite-a1ccf5e1ff2b4f4d12f383bca2b18875.res" +path="res://.godot/imported/hair.aseprite-733fe205726c184830ebda91637ad9f5.res" [deps] -source_file="res://player/hair.aseprite" -dest_files=["res://.godot/imported/hair.aseprite-a1ccf5e1ff2b4f4d12f383bca2b18875.res"] +source_file="res://src/player/hair.aseprite" +dest_files=["res://.godot/imported/hair.aseprite-733fe205726c184830ebda91637ad9f5.res"] [params] diff --git a/player/player.aseprite b/src/player/player.aseprite similarity index 100% rename from player/player.aseprite rename to src/player/player.aseprite diff --git a/player/player.aseprite.import b/src/player/player.aseprite.import similarity index 59% rename from player/player.aseprite.import rename to src/player/player.aseprite.import index 4e0b46b..62aab65 100644 --- a/player/player.aseprite.import +++ b/src/player/player.aseprite.import @@ -3,12 +3,12 @@ importer="aseprite_wizard.plugin.static-texture" type="PortableCompressedTexture2D" uid="uid://d0dy3j0qdycqf" -path="res://.godot/imported/player.aseprite-704c4b9b828702113ecb71676625aeb4.res" +path="res://.godot/imported/player.aseprite-61ab8c4a2ca60d43d00c5a0147684013.res" [deps] -source_file="res://player/player.aseprite" -dest_files=["res://.godot/imported/player.aseprite-704c4b9b828702113ecb71676625aeb4.res"] +source_file="res://src/player/player.aseprite" +dest_files=["res://.godot/imported/player.aseprite-61ab8c4a2ca60d43d00c5a0147684013.res"] [params] diff --git a/player/player.tscn b/src/player/player.tscn similarity index 90% rename from player/player.tscn rename to src/player/player.tscn index b20d0a9..b48cfb7 100644 --- a/player/player.tscn +++ b/src/player/player.tscn @@ -1,9 +1,9 @@ [gd_scene format=3 uid="uid://ce2k04khaub8n"] -[ext_resource type="Script" uid="uid://bx500kvj301vt" path="res://player/player.gd" id="1_g1dw6"] -[ext_resource type="Texture2D" uid="uid://d0dy3j0qdycqf" path="res://player/player.aseprite" id="2_yw30f"] -[ext_resource type="Texture2D" uid="uid://blw6f2ktsrcmg" path="res://player/hair.aseprite" id="3_qjkh3"] -[ext_resource type="Script" uid="uid://b7shvbf7iv6an" path="res://spring2d.gd" id="4_yw30f"] +[ext_resource type="Script" uid="uid://b5iey2typf2tb" path="res://src/player/Player.cs" id="1_244u8"] +[ext_resource type="Script" uid="uid://bhijvek6js88u" path="res://src/spring/Spring2D.cs" id="2_mf2ua"] +[ext_resource type="Texture2D" uid="uid://d0dy3j0qdycqf" path="res://src/player/player.aseprite" id="2_yw30f"] +[ext_resource type="Texture2D" uid="uid://blw6f2ktsrcmg" path="res://src/player/hair.aseprite" id="3_qjkh3"] [sub_resource type="CapsuleShape2D" id="CapsuleShape2D_e2o6t"] radius = 4.0 @@ -130,23 +130,23 @@ advance_mode = 2 [sub_resource type="AnimationNodeStateMachineTransition" id="AnimationNodeStateMachineTransition_8t03j"] advance_mode = 2 -advance_expression = "is_on_floor() and _current_direction.x != 0.0" +advance_expression = "is_on_floor() and _currentDirection.x != 0.0" [sub_resource type="AnimationNodeStateMachineTransition" id="AnimationNodeStateMachineTransition_2ieo8"] break_loop_at_end = true advance_mode = 2 -advance_expression = "not is_on_floor() or _current_direction.x == 0.0" +advance_expression = "not is_on_floor() or _currentDirection.x == 0.0" [sub_resource type="AnimationNodeStateMachineTransition" id="AnimationNodeStateMachineTransition_ebec5"] advance_expression = "_is_on_wall()" [sub_resource type="AnimationNodeStateMachineTransition" id="AnimationNodeStateMachineTransition_yllr7"] advance_mode = 2 -advance_expression = "_is_holding_wall()" +advance_expression = "IsHoldingWall()" [sub_resource type="AnimationNodeStateMachineTransition" id="AnimationNodeStateMachineTransition_kb6p2"] advance_mode = 2 -advance_expression = "not _is_holding_wall()" +advance_expression = "not IsHoldingWall()" [sub_resource type="AnimationNodeStateMachine" id="AnimationNodeStateMachine_yllr7"] allow_transition_to_self = true @@ -166,7 +166,7 @@ physics_interpolation_mode = 1 collision_layer = 2 floor_constant_speed = true floor_max_angle = 0.24783675 -script = ExtResource("1_g1dw6") +script = ExtResource("1_244u8") [node name="CollisionShape2D" type="CollisionShape2D" parent="." unique_id=84142517] position = Vector2(0, 1) @@ -211,13 +211,16 @@ metadata/_aseprite_wizard_source_file_hash_ = "61168df4a163c039cfaab97f4fccb905" [node name="Spring2D" type="Node2D" parent="Body" unique_id=1050714188] show_behind_parent = true -script = ExtResource("4_yw30f") -max_offset = Vector2(1, 2) +script = ExtResource("2_mf2ua") [node name="Hair" type="Sprite2D" parent="Body/Spring2D" unique_id=796557000] position = Vector2(-2, 2) texture = ExtResource("3_qjkh3") +[node name="HandAttachment" type="Node2D" parent="Body" unique_id=1002134601] +unique_name_in_owner = true +position = Vector2(3, 2) + [node name="AnimationPlayer" type="AnimationPlayer" parent="." unique_id=1251324400] libraries/ = SubResource("AnimationLibrary_rgyib") diff --git a/player/ribbon.gd b/src/player/ribbon.gd similarity index 100% rename from player/ribbon.gd rename to src/player/ribbon.gd diff --git a/player/ribbon.gd.uid b/src/player/ribbon.gd.uid similarity index 100% rename from player/ribbon.gd.uid rename to src/player/ribbon.gd.uid diff --git a/src/player/slash_projectile.gd b/src/player/slash_projectile.gd new file mode 100644 index 0000000..f9b3c53 --- /dev/null +++ b/src/player/slash_projectile.gd @@ -0,0 +1,9 @@ +class_name SlashProjectile extends Node2D + +signal hitbox_entered(other: Node2D) + +func _on_attack_finished() -> void: + queue_free() + +func _on_hitbox_body_entered(body: Node2D) -> void: + hitbox_entered.emit(body) diff --git a/src/player/slash_projectile.gd.uid b/src/player/slash_projectile.gd.uid new file mode 100644 index 0000000..347e47a --- /dev/null +++ b/src/player/slash_projectile.gd.uid @@ -0,0 +1 @@ +uid://uwfp4ytugp51 diff --git a/src/player/slash_projectile.tscn b/src/player/slash_projectile.tscn new file mode 100644 index 0000000..2a69b67 --- /dev/null +++ b/src/player/slash_projectile.tscn @@ -0,0 +1,108 @@ +[gd_scene format=3 uid="uid://bikcpm0fyl4pd"] + +[ext_resource type="Texture2D" uid="uid://jdmsv25yp25v" path="res://src/player/attack.aseprite" id="1_3il12"] +[ext_resource type="Script" uid="uid://0n1gv56pcc74" path="res://src/player/SlashProjectile.cs" id="1_bi0sp"] + +[sub_resource type="Animation" id="Animation_3il12"] +length = 0.001 +tracks/0/type = "value" +tracks/0/imported = false +tracks/0/enabled = true +tracks/0/path = NodePath("Attack:frame") +tracks/0/interp = 1 +tracks/0/loop_wrap = true +tracks/0/keys = { +"times": PackedFloat32Array(0), +"transitions": PackedFloat32Array(1), +"update": 1, +"values": [0] +} +tracks/1/type = "value" +tracks/1/imported = false +tracks/1/enabled = true +tracks/1/path = NodePath("Hitbox/CollisionShape2D:disabled") +tracks/1/interp = 1 +tracks/1/loop_wrap = true +tracks/1/keys = { +"times": PackedFloat32Array(0), +"transitions": PackedFloat32Array(1), +"update": 1, +"values": [true] +} + +[sub_resource type="Animation" id="Animation_eb3da"] +resource_name = "attack" +length = 0.4 +step = 0.1 +tracks/0/type = "value" +tracks/0/imported = false +tracks/0/enabled = true +tracks/0/path = NodePath("Attack:frame") +tracks/0/interp = 1 +tracks/0/loop_wrap = true +tracks/0/keys = { +"times": PackedFloat32Array(0, 0.1, 0.2), +"transitions": PackedFloat32Array(1, 1, 1), +"update": 1, +"values": [0, 1, 2] +} +tracks/1/type = "method" +tracks/1/imported = false +tracks/1/enabled = true +tracks/1/path = NodePath(".") +tracks/1/interp = 1 +tracks/1/loop_wrap = true +tracks/1/keys = { +"times": PackedFloat32Array(0.4), +"transitions": PackedFloat32Array(1), +"values": [{ +"args": [], +"method": &"OnAttackFinished" +}] +} +tracks/2/type = "value" +tracks/2/imported = false +tracks/2/enabled = true +tracks/2/path = NodePath("Hitbox/CollisionShape2D:disabled") +tracks/2/interp = 1 +tracks/2/loop_wrap = true +tracks/2/keys = { +"times": PackedFloat32Array(0, 0.1, 0.3), +"transitions": PackedFloat32Array(1, 1, 1), +"update": 1, +"values": [true, false, true] +} + +[sub_resource type="AnimationLibrary" id="AnimationLibrary_12t1i"] +_data = { +&"RESET": SubResource("Animation_3il12"), +&"attack": SubResource("Animation_eb3da") +} + +[sub_resource type="RectangleShape2D" id="RectangleShape2D_u7cw4"] +size = Vector2(32, 10) + +[node name="SlashProjectile" type="Node2D" unique_id=541992074] +script = ExtResource("1_bi0sp") + +[node name="Attack" type="Sprite2D" parent="." unique_id=30274790] +position = Vector2(16, -3) +texture = ExtResource("1_3il12") +hframes = 3 + +[node name="AnimationPlayer" type="AnimationPlayer" parent="." unique_id=1896907748] +unique_name_in_owner = true +libraries/ = SubResource("AnimationLibrary_12t1i") +autoplay = &"attack" + +[node name="Hitbox" type="Area2D" parent="." unique_id=133086557] +collision_layer = 8 +collision_mask = 4 + +[node name="CollisionShape2D" type="CollisionShape2D" parent="Hitbox" unique_id=1668475985] +position = Vector2(21, -5) +shape = SubResource("RectangleShape2D_u7cw4") +disabled = true +debug_color = Color(0.99430805, 0, 0.2314094, 0.41960785) + +[connection signal="body_entered" from="Hitbox" to="." method="OnHitboxBodyEntered"] diff --git a/src/rescaler/Rescaler.cs b/src/rescaler/Rescaler.cs new file mode 100644 index 0000000..b065367 --- /dev/null +++ b/src/rescaler/Rescaler.cs @@ -0,0 +1,106 @@ +using System; + +namespace Dancer; + +[Meta(typeof(IAutoNode))] +public sealed partial class Rescaler : Control +{ + public override void _Notification(int what) => this.Notify(what); + + [Export] public bool ShouldRoundWidthToEvens { get; set; } = true; + + [Export] + public ScalingMode ScalingMode + { + get; + set + { + field = value; + UpdateFilters(); + } + } = ScalingMode.IntLinear; + + [Node] private TextureRect OuterSprite { get; set; } = null!; + [Node] private Sprite2D InnerSprite { get; set; } = null!; + [Node] private SubViewport OuterViewport { get; set; } = null!; + [Node] private SubViewport InnerViewport { get; set; } = null!; + + private Transform2D _eventTransform = Transform2D.Identity; + private Vector2 _lastSize; + private int _targetHeight; + private int _previousFactor; + + public override void _Ready() + { + UpdateFilters(); + var window = GetWindow(); + _targetHeight = ProjectSettings.GetSetting("display/window/size/viewport_height").AsInt32(); + window.ContentScaleMode = Window.ContentScaleModeEnum.Disabled; + } + + private void UpdateFilters() + { + if (!IsNodeReady()) return; + switch (ScalingMode) + { + case ScalingMode.IntLinear: + OuterSprite.TextureFilter = TextureFilterEnum.Linear; + InnerSprite.TextureFilter = TextureFilterEnum.Nearest; + break; + case ScalingMode.Nearest: + OuterSprite.TextureFilter = TextureFilterEnum.Nearest; + InnerSprite.TextureFilter = TextureFilterEnum.Nearest; + break; + case ScalingMode.Linear: + OuterSprite.TextureFilter = TextureFilterEnum.Linear; + InnerSprite.TextureFilter = TextureFilterEnum.Linear; + break; + default: + throw new ArgumentOutOfRangeException(); + } + } + + public override void _Input(InputEvent @event) + { + if (Engine.IsEditorHint()) return; + InnerViewport.PushInput(@event.XformedBy(_eventTransform)); + } + + public override void _Process(double delta) + { + if (_lastSize != Size) + { + ResizeViewports(); + _lastSize = Size; + } + } + + private void ResizeViewports() + { + var factor = Math.Max(1, Mathf.RoundToInt(Size.Y / _targetHeight)); + if (factor != _previousFactor) + { + _previousFactor = factor; + GD.Print($"Scaling factor switched to {factor}."); + } + + var roundingMultiplier = ShouldRoundWidthToEvens ? 2 : 1; + var targetWidth = + Mathf.CeilToInt(_targetHeight / Size.Y * Size.X / roundingMultiplier) + * roundingMultiplier; + var innerTargetSize = new Vector2I(targetWidth, _targetHeight); + var outerTargetSize = factor * innerTargetSize; + + _eventTransform = Transform2D.Identity.Scaled(innerTargetSize / Size); + OuterViewport.Size = outerTargetSize; + InnerViewport.Size = innerTargetSize; + InnerSprite.Scale = new(factor, factor); + } +} + +public enum ScalingMode +{ + IntLinear, + Nearest, + Linear, +} diff --git a/src/rescaler/Rescaler.cs.uid b/src/rescaler/Rescaler.cs.uid new file mode 100644 index 0000000..4b31919 --- /dev/null +++ b/src/rescaler/Rescaler.cs.uid @@ -0,0 +1 @@ +uid://dhepskekkv01r diff --git a/rescaler.tscn b/src/rescaler/rescaler.tscn similarity index 89% rename from rescaler.tscn rename to src/rescaler/rescaler.tscn index 3d9899d..f2ae9fc 100644 --- a/rescaler.tscn +++ b/src/rescaler/rescaler.tscn @@ -1,7 +1,7 @@ [gd_scene format=3 uid="uid://c0ltj3ishvcbj"] -[ext_resource type="Script" uid="uid://vu7n2fqv8nci" path="res://rescaler.gd" id="1_qq0d3"] -[ext_resource type="PackedScene" uid="uid://cujd7ltkrnxpt" path="res://game.tscn" id="2_wr0av"] +[ext_resource type="Script" uid="uid://dhepskekkv01r" path="res://src/rescaler/Rescaler.cs" id="1_jhxal"] +[ext_resource type="PackedScene" uid="uid://cujd7ltkrnxpt" path="res://src/game.tscn" id="2_wr0av"] [sub_resource type="ViewportTexture" id="ViewportTexture_d73y4"] viewport_path = NodePath("OuterViewport") @@ -16,7 +16,7 @@ anchor_right = 1.0 anchor_bottom = 1.0 grow_horizontal = 2 grow_vertical = 2 -script = ExtResource("1_qq0d3") +script = ExtResource("1_jhxal") [node name="OuterSprite" type="TextureRect" parent="." unique_id=2048645881] unique_name_in_owner = true diff --git a/src/spring/Spring2D.cs b/src/spring/Spring2D.cs new file mode 100644 index 0000000..3bed853 --- /dev/null +++ b/src/spring/Spring2D.cs @@ -0,0 +1,27 @@ +namespace Dancer; + +[Meta(typeof(IAutoNode))] +public sealed partial class Spring2D : Node2D +{ + public override void _Notification(int what) => this.Notify(what); + + [Export] public Vector2 MaxOffset { get; set; } = Vector2.One; + + private Vector2 _lastGlobalPosition; + private Vector2 _localOffset; + + public override void _Ready() + { + _lastGlobalPosition = GlobalPosition; + _localOffset = Position; + } + + public override void _Process(double delta) + { + if (GetParent() is not Node2D parent) return; + var targetPosition = parent.GlobalPosition + _localOffset; + var newPosition = _lastGlobalPosition.Lerp(targetPosition, 0.4f); + GlobalPosition = targetPosition + (newPosition - targetPosition).Clamp(-MaxOffset, MaxOffset); + _lastGlobalPosition = GlobalPosition; + } +} diff --git a/src/spring/Spring2D.cs.uid b/src/spring/Spring2D.cs.uid new file mode 100644 index 0000000..87354ed --- /dev/null +++ b/src/spring/Spring2D.cs.uid @@ -0,0 +1 @@ +uid://bhijvek6js88u diff --git a/vp_test.tscn b/vp_test.tscn deleted file mode 100644 index b1c3a50..0000000 --- a/vp_test.tscn +++ /dev/null @@ -1,22 +0,0 @@ -[gd_scene format=3 uid="uid://cijws3pgr2ka4"] - -[ext_resource type="PackedScene" uid="uid://cujd7ltkrnxpt" path="res://game.tscn" id="1_f4u52"] - -[node name="Control" type="Control" unique_id=961283094] -layout_mode = 3 -anchors_preset = 15 -anchor_right = 1.0 -anchor_bottom = 1.0 -grow_horizontal = 2 -grow_vertical = 2 -metadata/_edit_lock_ = true - -[node name="SubViewportContainer" type="SubViewportContainer" parent="." unique_id=822491905] -layout_mode = 0 -offset_right = 40.0 -offset_bottom = 40.0 -metadata/_edit_lock_ = true - -[node name="SubViewport" type="SubViewport" parent="SubViewportContainer" unique_id=292706412] - -[node name="Game" parent="SubViewportContainer/SubViewport" unique_id=1186062666 instance=ExtResource("1_f4u52")]