commit 97faa07aab0fdf9849ab261ae49065684ce5514e Author: BasicArray <> Date: Sun Aug 9 06:24:25 2026 +0000 Initial commit diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..1df6c35 --- /dev/null +++ b/.clang-format @@ -0,0 +1,199 @@ +# Commented out parameters are those with the same value as base LLVM style. +# We can uncomment them if we want to change their value, or enforce the +# chosen value in case the base style changes (last sync: Clang 14.0). +--- +### General config, applies to all languages ### +BasedOnStyle: LLVM +AccessModifierOffset: -4 +AlignAfterOpenBracket: DontAlign +# AlignArrayOfStructures: None +# AlignConsecutiveMacros: None +# AlignConsecutiveAssignments: None +# AlignConsecutiveBitFields: None +# AlignConsecutiveDeclarations: None +# AlignEscapedNewlines: Right +AlignOperands: DontAlign +AlignTrailingComments: false +# AllowAllArgumentsOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: false +# AllowShortEnumsOnASingleLine: true +# AllowShortBlocksOnASingleLine: Never +# AllowShortCaseLabelsOnASingleLine: false +# AllowShortFunctionsOnASingleLine: All +# AllowShortLambdasOnASingleLine: All +# AllowShortIfStatementsOnASingleLine: Never +# AllowShortLoopsOnASingleLine: false +# AlwaysBreakAfterDefinitionReturnType: None +# AlwaysBreakAfterReturnType: None +# AlwaysBreakBeforeMultilineStrings: false +# AlwaysBreakTemplateDeclarations: MultiLine +# AttributeMacros: +# - __capability +# BinPackArguments: true +# BinPackParameters: true +# BraceWrapping: +# AfterCaseLabel: false +# AfterClass: false +# AfterControlStatement: Never +# AfterEnum: false +# AfterFunction: false +# AfterNamespace: false +# AfterObjCDeclaration: false +# AfterStruct: false +# AfterUnion: false +# AfterExternBlock: false +# BeforeCatch: false +# BeforeElse: false +# BeforeLambdaBody: false +# BeforeWhile: false +# IndentBraces: false +# SplitEmptyFunction: true +# SplitEmptyRecord: true +# SplitEmptyNamespace: true +# BreakBeforeBinaryOperators: None +# BreakBeforeConceptDeclarations: true +# BreakBeforeBraces: Attach +# BreakBeforeInheritanceComma: false +# BreakInheritanceList: BeforeColon +# BreakBeforeTernaryOperators: true +# BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: AfterColon +# BreakStringLiterals: true +ColumnLimit: 0 +# CommentPragmas: '^ IWYU pragma:' +# QualifierAlignment: Leave +# CompactNamespaces: false +ConstructorInitializerIndentWidth: 8 +ContinuationIndentWidth: 8 +Cpp11BracedListStyle: false +# DeriveLineEnding: true +# DerivePointerAlignment: false +# DisableFormat: false +# EmptyLineAfterAccessModifier: Never +# EmptyLineBeforeAccessModifier: LogicalBlock +# ExperimentalAutoDetectBinPacking: false +# PackConstructorInitializers: BinPack +ConstructorInitializerAllOnOneLineOrOnePerLine: true +# AllowAllConstructorInitializersOnNextLine: true +# FixNamespaceComments: true +# ForEachMacros: +# - foreach +# - Q_FOREACH +# - BOOST_FOREACH +# IfMacros: +# - KJ_IF_MAYBE +# IncludeBlocks: Preserve +IncludeCategories: + - Regex: '".*"' + Priority: 1 + - Regex: '^<.*\.h>' + Priority: 2 + - Regex: '^<.*' + Priority: 3 +# IncludeIsMainRegex: '(Test)?$' +# IncludeIsMainSourceRegex: '' +# IndentAccessModifiers: false +IndentCaseLabels: true +# IndentCaseBlocks: false +# IndentGotoLabels: true +# IndentPPDirectives: None +# IndentExternBlock: AfterExternBlock +# IndentRequires: false +IndentWidth: 4 +# IndentWrappedFunctionNames: false +# InsertTrailingCommas: None +# JavaScriptQuotes: Leave +# JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: false +# LambdaBodyIndentation: Signature +# MacroBlockBegin: '' +# MacroBlockEnd: '' +# MaxEmptyLinesToKeep: 1 +# NamespaceIndentation: None +# PenaltyBreakAssignment: 2 +# PenaltyBreakBeforeFirstCallParameter: 19 +# PenaltyBreakComment: 300 +# PenaltyBreakFirstLessLess: 120 +# PenaltyBreakOpenParenthesis: 0 +# PenaltyBreakString: 1000 +# PenaltyBreakTemplateDeclaration: 10 +# PenaltyExcessCharacter: 1000000 +# PenaltyReturnTypeOnItsOwnLine: 60 +# PenaltyIndentedWhitespace: 0 +# PointerAlignment: Right +# PPIndentWidth: -1 +# ReferenceAlignment: Pointer +# ReflowComments: true +# RemoveBracesLLVM: false +# SeparateDefinitionBlocks: Leave +# ShortNamespaceLines: 1 +# SortIncludes: CaseSensitive +# SortJavaStaticImport: Before +# SortUsingDeclarations: true +# SpaceAfterCStyleCast: false +# SpaceAfterLogicalNot: false +# SpaceAfterTemplateKeyword: true +# SpaceBeforeAssignmentOperators: true +# SpaceBeforeCaseColon: false +# SpaceBeforeCpp11BracedList: false +# SpaceBeforeCtorInitializerColon: true +# SpaceBeforeInheritanceColon: true +# SpaceBeforeParens: ControlStatements +# SpaceBeforeParensOptions: +# AfterControlStatements: true +# AfterForeachMacros: true +# AfterFunctionDefinitionName: false +# AfterFunctionDeclarationName: false +# AfterIfMacros: true +# AfterOverloadedOperator: false +# BeforeNonEmptyParentheses: false +# SpaceAroundPointerQualifiers: Default +# SpaceBeforeRangeBasedForLoopColon: true +# SpaceInEmptyBlock: false +# SpaceInEmptyParentheses: false +# SpacesBeforeTrailingComments: 1 +# SpacesInAngles: Never +# SpacesInConditionalStatement: false +# SpacesInContainerLiterals: true +# SpacesInCStyleCastParentheses: false +## Godot TODO: We'll want to use a min of 1, but we need to see how to fix +## our comment capitalization at the same time. +SpacesInLineCommentPrefix: + Minimum: 0 + Maximum: -1 +# SpacesInParentheses: false +# SpacesInSquareBrackets: false +# SpaceBeforeSquareBrackets: false +# BitFieldColonSpacing: Both +# StatementAttributeLikeMacros: +# - Q_EMIT +# StatementMacros: +# - Q_UNUSED +# - QT_REQUIRE_VERSION +TabWidth: 4 +# UseCRLF: false +UseTab: Always +# WhitespaceSensitiveMacros: +# - STRINGIZE +# - PP_STRINGIZE +# - BOOST_PP_STRINGIZE +# - NS_SWIFT_NAME +# - CF_SWIFT_NAME +--- +### C++ specific config ### +Language: Cpp +Standard: c++17 +--- +### ObjC specific config ### +Language: ObjC +# ObjCBinPackProtocolList: Auto +ObjCBlockIndentWidth: 4 +# ObjCBreakBeforeNestedBlockParam: true +# ObjCSpaceAfterProperty: false +# ObjCSpaceBeforeProtocolList: true +--- +### Java specific config ### +Language: Java +# BreakAfterJavaFieldAnnotations: false +JavaImportGroups: ['org.godotengine', 'android', 'androidx', 'com.android', 'com.google', 'java', 'javax'] +... diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..d8a9005 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,27 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +indent_style = tab +insert_final_newline = true +trim_trailing_whitespace = true + +[{*.gradle,AndroidManifest.xml}] +indent_style = space +indent_size = 4 + +[{*.py,SConstruct,SCsub}] +indent_style = space +indent_size = 4 + +# YAML requires indentation with spaces instead of tabs. +[*.{yml,yaml}] +indent_style = space +indent_size = 2 + +[{*.cmake,CMakeLists.txt}] +indent_style = space +ij_continuation_indent_size = 4 +ij_cmake_force_commands_case = 1 + diff --git a/.gdignore b/.gdignore new file mode 100644 index 0000000..e69de29 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..8ad74f7 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Normalize EOL for all files that Git considers text files. +* text=auto eol=lf diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..92f12af --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,44 @@ +name: Bug report +description: Report a bug with the godot-cpp template +body: + +- type: markdown + attributes: + value: | + - Write a descriptive issue title above. + - Search [open](https://github.com/godotengine/godot-cpp-template/issues) and [closed](https://github.com/godotengine/godot-cpp-template/issues?q=is%3Aissue+is%3Aclosed) issues to ensure it has not already been reported. +- type: input + attributes: + label: Godot version + description: > + Specify the Git commit hash of your Godot build. + placeholder: v4.0.stable.official [92bee43ad] + validations: + required: true + +- type: input + attributes: + label: godot-cpp version + description: > + Specify the Git commit hash of the godot-cpp submodule in your project. You can run `git status` inside the folder to check it. + placeholder: v4.0.stable.official [9d1c396c5] + validations: + required: true + +- type: input + attributes: + label: System information + description: | + Specify the OS version. + placeholder: Windows 10 + validations: + required: true + +- type: textarea + attributes: + label: Issue description + description: | + Describe your issue briefly. What doesn't work, and how do you expect it to work instead? + You can include images or videos with drag and drop, and format code blocks or logs with ``` tags. + validations: + required: true \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..f787bec --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,14 @@ +blank_issues_enabled: false + +contact_links: + - name: Godot proposals + url: https://github.com/godotengine/godot-proposals + about: Please submit feature proposals on the Godot proposals repository, not here. + + - name: Godot documentation repository + url: https://github.com/godotengine/godot-docs + about: Please report issues with documentation on the Godot documentation repository, not here. + + - name: Godot community channels + url: https://godotengine.org/community + about: Please ask for technical support on one of the other community channels, not here. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..ccd68da --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,88 @@ +# For syntax, see https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax +# This workflow is automatically triggered for every push and pull request, to verify that everything still builds. + +name: Continuous Integration +on: + workflow_call: + push: + pull_request: + merge_group: + +jobs: + build: + strategy: + fail-fast: false + matrix: + # Test a few selected combinations of parameters ("test case matrix"). + # While it would be nice to test all needed combinations, in practice this would a waste of CI usage time. + # By building just with a few combinations, we only need a few runners, + # while still achieving adequate coverage. + # To make a full build with all combinations, use the make_build.yml workflow instead. + include: + - target: { platform: linux, arch: x86_64, os: ubuntu-22.04 } + target-type: template_debug + float-precision: double + - target: { platform: windows, arch: x86_64, os: windows-latest } + target-type: template_release + float-precision: single + - target: { platform: macos, arch: universal, os: macos-latest } + target-type: template_debug + float-precision: single + - target: { platform: android, arch: arm64, os: ubuntu-22.04 } + target-type: template_debug + float-precision: single + - target: { platform: web, arch: wasm32, os: ubuntu-22.04 } + target-type: template_release + float-precision: double + + runs-on: ${{ matrix.target.os }} + steps: + # Clone this repository + - name: Checkout + uses: actions/checkout@v4 + with: + submodules: true + + # Lint + #- name: Setup clang-format + # shell: bash + # run: | + # python -m pip install clang-format + #- name: Run clang-format + # shell: bash + # run: | + # clang-format src/** --dry-run --Werror + + # Add linux x86_32 toolchain + - name: Install multilib support + if: ${{ matrix.target.platform == 'linux' && matrix.target.arch == 'x86_32' }} + run: | + sudo apt-get update && sudo apt-get install -y gcc-multilib g++-multilib + + # Setup dependencies + - name: Setup godot-cpp + uses: ./godot-cpp/.github/actions/setup-godot-cpp + with: + platform: ${{ matrix.target.platform }} + em-version: 3.1.62 + + # Build GDExtension (with caches) + + - name: Restore .scons_cache + uses: ./godot-cpp/.github/actions/godot-cache-restore + with: + scons-cache: ${{ github.workspace }}/.scons-cache/ + cache-name: ${{ matrix.target.platform }}_${{ matrix.target.arch }}_${{ matrix.float-precision }}_${{ matrix.target-type }} + + - name: Build GDExtension Debug Build + shell: sh + env: + SCONS_CACHE: ${{ github.workspace }}/.scons-cache/ + run: | + scons target=${{ matrix.target-type }} platform=${{ matrix.target.platform }} arch=${{ matrix.target.arch }} precision=${{ matrix.float-precision }} + + - name: Save .scons_cache + uses: ./godot-cpp/.github/actions/godot-cache-save + with: + scons-cache: ${{ github.workspace }}/.scons-cache/ + cache-name: ${{ matrix.target.platform }}_${{ matrix.target.arch }}_${{ matrix.float-precision }}_${{ matrix.target-type }} diff --git a/.github/workflows/make_build.yml b/.github/workflows/make_build.yml new file mode 100644 index 0000000..9e91738 --- /dev/null +++ b/.github/workflows/make_build.yml @@ -0,0 +1,104 @@ +# For syntax, see https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax +# This workflow is triggered manually on the "Actions" tab on GitHub, and can be used to create releases. + +name: Make a GDExtension build for all supported platforms +on: + workflow_dispatch: + +jobs: + build: + strategy: + fail-fast: false + matrix: + # A build is made for every possible combination of parameters + # You can add or remove entries from the arrays of each parameter to customize which builds you want to run. + # See https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/running-variations-of-jobs-in-a-workflow + target: + [ + { platform: linux, arch: x86_64, os: ubuntu-22.04 }, + { platform: linux, arch: x86_32, os: ubuntu-22.04 }, + { platform: linux, arch: arm64, os: ubuntu-22.04-arm }, + { platform: linux, arch: arm32, os: ubuntu-22.04-arm }, + { platform: windows, arch: x86_64, os: windows-latest }, + { platform: windows, arch: x86_32, os: windows-latest }, + { platform: windows, arch: arm64, os: windows-latest }, + { platform: macos, arch: universal, os: macos-latest }, + { platform: android, arch: x86_64, os: ubuntu-22.04 }, + { platform: android, arch: x86_32, os: ubuntu-22.04 }, + { platform: android, arch: arm64, os: ubuntu-22.04 }, + { platform: android, arch: arm32, os: ubuntu-22.04 }, + { platform: ios, arch: arm64, os: macos-latest }, + { platform: web, arch: wasm32, os: ubuntu-22.04 }, + ] + target-type: [template_debug, template_release] + float-precision: [single] + + runs-on: ${{ matrix.target.os }} + steps: + # Clone this repository + - name: Checkout + uses: actions/checkout@v4 + with: + submodules: true + + # Add linux x86_32 toolchain + - name: Install multilib support + if: ${{ matrix.target.platform == 'linux' && matrix.target.arch == 'x86_32' }} + run: | + sudo apt-get update && sudo apt-get install -y gcc-multilib g++-multilib + + # Setup dependencies + - name: Setup godot-cpp + uses: ./godot-cpp/.github/actions/setup-godot-cpp + with: + platform: ${{ matrix.target.platform }} + em-version: 3.1.62 + + # Build GDExtension (with caches) + + - name: Restore .scons_cache + uses: ./godot-cpp/.github/actions/godot-cache-restore + with: + scons-cache: ${{ github.workspace }}/.scons-cache/ + cache-name: ${{ matrix.target.platform }}_${{ matrix.target.arch }}_${{ matrix.float-precision }}_${{ matrix.target-type }} + + - name: Build GDExtension Debug Build + shell: sh + env: + SCONS_CACHE: ${{ github.workspace }}/.scons-cache/ + run: | + scons target=${{ matrix.target-type }} platform=${{ matrix.target.platform }} arch=${{ matrix.target.arch }} precision=${{ matrix.float-precision }} + + - name: Save .scons_cache + uses: ./godot-cpp/.github/actions/godot-cache-save + with: + scons-cache: ${{ github.workspace }}/.scons-cache/ + cache-name: ${{ matrix.target.platform }}_${{ matrix.target.arch }}_${{ matrix.float-precision }}_${{ matrix.target-type }} + + # Clean up compilation files + - name: Windows - Delete compilation files + if: ${{ matrix.target.platform == 'windows' }} + shell: pwsh + run: | + Remove-Item bin/* -Include *.exp,*.lib,*.pdb -Force + + # Upload the build + - name: Upload Artifact + uses: actions/upload-artifact@v4 + with: + name: godot-cpp-template-${{ matrix.target.platform }}-${{ matrix.target.arch }}-${{ matrix.float-precision }}-${{ matrix.target-type }} + path: | + ${{ github.workspace }}/bin/** + + # Merges all the build artifacts together into a single godot-cpp-template artifact. + # If you comment out this step, all the builds will be uploaded individually. + merge: + runs-on: ubuntu-22.04 + needs: build + steps: + - name: Merge Artifacts + uses: actions/upload-artifact/merge@v4 + with: + name: godot-cpp-template + pattern: godot-cpp-template-* + delete-merged: true diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8257026 --- /dev/null +++ b/.gitignore @@ -0,0 +1,52 @@ +# Godot auto generated files +*.gen.* +.godot/ + +# Ignore library files but not the gdextension file +/bin/** +!project/bin/*.gdextension + +# Ignore scons database +.sconsign*.dblite + +# Ignore custom.py +custom.py + +# Ignore generated compile_commands.json +compile_commands.json + +# Ignore files generated for documentation +/src/gen + +# Binaries +*.o +*.os +*.so +*.obj +*.bc +*.pyc +*.dblite +*.pdb +*.lib +*.config +*.creator +*.creator.user +*.files +*.includes +*.idb +*.exp + +# Other stuff +*.log + +# VSCode +.vscode/* +!.vscode/extensions.json +.DS_Store + +# Jetbrains +.idea/ + +# Cmake +cmake-build* +CMakeUserPresets.json diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..1c0d850 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,4 @@ +[submodule "godot-cpp"] + path = godot-cpp + url = https://github.com/godotengine/godot-cpp.git + branch = 4.3 diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 0000000..d1f137b --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,6 @@ +{ + "recommendations": [ + "ms-vscode.cpptools-extension-pack", + "ms-python.python" + ] +} \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..5c8ddc7 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,90 @@ +# Using the same minimum as the godot-cpp project +cmake_minimum_required(VERSION 3.17) + +# Silence unused variable warning when specified from toolchain +if(CMAKE_C_COMPILER) +endif() + +set(LIBNAME "EXTENSION-NAME") # "The name of the library" +set(GODOT_PROJECT_DIR "project" CACHE STRING "The directory of a Godot project folder") + +# Make sure all the dependencies are satisfied +find_package(Python3 3.4 REQUIRED) +find_program(GIT git REQUIRED) + +# Ensure godot-cpp submodule has been updated +if(NOT EXISTS "${CMAKE_CURRENT_LIST_DIR}/godot-cpp/src") + message(NOTICE "godot-cpp bindings source not found") + message(NOTICE "initializing/updating the godot-cpp submodule...") + + # update the c++ bindings submodule to populate it with the necessary source for the library + execute_process( + COMMAND git submodule update --init godot-cpp + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} + COMMAND_ERROR_IS_FATAL ANY + ) +endif() +add_subdirectory(godot-cpp SYSTEM) + +# When compiling for emscripten, this toolchainhack needs to be included. +# set(CMAKE_PROJECT__INCLUDE ${godot-cpp_SOURCE_DIR}/cmake/emsdkHack.cmake) + +# Create the gen directory at configure time so IDEs can see generated headers immediately after generate_bindings +file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/godot-cpp/gen/include") + +# Add godot-cpp's module path and include the exported functions. +# This is made available for documentation generation +set(CMAKE_MODULE_PATH "${CMAKE_MODULE_PATH};${godot-cpp_SOURCE_DIR}/cmake") +include(GodotCPPModule) + +# The godot-cpp target has some of useful properties attached that can be retrieved like so. +get_target_property(GODOTCPP_SUFFIX godot::cpp GODOTCPP_SUFFIX) +get_target_property(GODOTCPP_PLATFORM godot::cpp GODOTCPP_PLATFORM) + +# Now we can specify our own project which will inherit any global cmake properties or variables that have been defined. +project(godot-cpp-template + VERSION 1.0 + DESCRIPTION "This repository serves as a quickstart template for GDExtension development with Godot 4.0+." + HOMEPAGE_URL "https://github.com/enetheru/godot-cpp-template/tree/main" + LANGUAGES CXX +) + +add_library(${LIBNAME} SHARED) + +target_sources(${LIBNAME} + PRIVATE + src/register_types.cpp + src/register_types.h + src/example_class.cpp + src/example_class.h +) + +# Fetch a list of the xml files to use for documentation and add to our target +file(GLOB_RECURSE DOC_XML LIST_DIRECTORIES NO CONFIGURE_DEPENDS "${PROJECT_SOURCE_DIR}/doc_classes/*.xml") + +# conditionally add doc data to compile output +if(DOC_XML) + if(GODOTCPP_TARGET MATCHES "editor|template_debug") + target_doc_sources(${LIBNAME} "${DOC_XML}") + endif() +endif() + +target_link_libraries(${LIBNAME} PRIVATE godot-cpp) + +# Require at least C++17 for this target +set_property(TARGET ${LIBNAME} PROPERTY CXX_STANDARD 17) + +set_target_properties(${LIBNAME} + PROPERTIES + # The generator expression here prevents msvc from adding a Debug or Release subdir. + RUNTIME_OUTPUT_DIRECTORY "$<1:${PROJECT_SOURCE_DIR}/bin/${GODOTCPP_PLATFORM}>" + + PREFIX "" + OUTPUT_NAME "${LIBNAME}${GODOTCPP_SUFFIX}" +) + +set(GODOT_PROJECT_BINARY_DIR "${PROJECT_SOURCE_DIR}/${GODOT_PROJECT_DIR}/bin/${GODOTCPP_PLATFORM}") + +add_custom_command(TARGET ${LIBNAME} POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy "$" "${GODOT_PROJECT_BINARY_DIR}/$" +) diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..fdddb29 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,24 @@ +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to diff --git a/README.md b/README.md new file mode 100644 index 0000000..38872b5 --- /dev/null +++ b/README.md @@ -0,0 +1,56 @@ +# godot-cpp template +This repository serves as a quickstart template for GDExtension development with Godot 4.0+. + +## Contents +* Preconfigured source files for C++ development of the GDExtension ([src/](./src/)) +* An empty Godot project in [project/](./project), to test the GDExtension +* godot-cpp as a submodule (`godot-cpp/`) +* GitHub Issues template ([.github/ISSUE_TEMPLATE.yml](./.github/ISSUE_TEMPLATE.yml)) +* GitHub CI/CD workflows to publish your library packages when creating a release ([.github/workflows/builds.yml](./.github/workflows/builds.yml)) +* An SConstruct file with various functions, such as boilerplate for [Adding documentation](https://docs.godotengine.org/en/stable/tutorials/scripting/cpp/gdextension_docs_system.html) + +## Usage - Template + +To use this template, log in to GitHub and click the green "Use this template" button at the top of the repository page. This will let you create a copy of this repository with a clean git history. + +To get started with your new GDExtension, do the following: + +* clone your repository to your local computer +* initialize the godot-cpp git submodule via `git submodule update --init` +* change the name of the compiled library file inside the [SConstruct](./SConstruct) file by modifying the `libname` string. + * change the paths of the to be loaded library name inside the [project/bin/example.gdextension](./project/bin/example.gdextension) file, by replacing `EXTENSION-NAME` with the name you chose for `libname`. +* change the `entry_symbol` string inside [project/bin/example.gdextension](./project/bin/example.gdextension) file. + * rename the `example_library_init` function in [src/register_types.cpp](./src/register_types.cpp) to the same name you chose for `entry_symbol`. +* change the name of the `project/bin/example.gdextension` file + +Now, you can build the project with the following command: + +```shell +scons +``` + +If the build command worked, you can test it with the [project](./project) project. Import it into Godot, open it, and launch the main scene. You should see it print the following line in the console: + +``` +Type: 24 +``` + +### Configuring an IDE +You can develop your own extension with any text editor and by invoking scons on the command line, but if you want to work with an IDE (Integrated Development Environment), you can use a compilation database file called `compile_commands.json`. Most IDEs should automatically identify this file, and self-configure appropriately. +To generate the database file, you can run one of the following commands in the project root directory: +```shell +# Generate compile_commands.json while compiling +scons compiledb=yes + +# Generate compile_commands.json without compiling +scons compiledb=yes compile_commands.json +``` + +## Usage - Actions + +This repository comes with continuous integration (CI) through a GitHub action that tests building the GDExtension. +It triggers automatically for each pushed change. You can find and edit it in [builds.yml](.github/workflows/ci.yml). + +There is also a workflow ([make_build.yml](.github/workflows/make_build.yml)) that builds the GDExtension for all supported platforms that you can use to create releases. +You can trigger this workflow manually from the `Actions` tab on GitHub. +After it is complete, you can find the file `godot-cpp-template.zip` in the `Artifacts` section of the workflow run. diff --git a/SConstruct b/SConstruct new file mode 100644 index 0000000..1ea6854 --- /dev/null +++ b/SConstruct @@ -0,0 +1,64 @@ +#!/usr/bin/env python +import os +import sys + +from methods import print_error + + +libname = "EXTENSION-NAME" +projectdir = "project" + +localEnv = Environment(tools=["default"], PLATFORM="") + +# Build profiles can be used to decrease compile times. +# You can either specify "disabled_classes", OR +# explicitly specify "enabled_classes" which disables all other classes. +# Modify the example file as needed and uncomment the line below or +# manually specify the build_profile parameter when running SCons. + +# localEnv["build_profile"] = "build_profile.json" + +customs = ["custom.py"] +customs = [os.path.abspath(path) for path in customs] + +opts = Variables(customs, ARGUMENTS) +opts.Update(localEnv) + +Help(opts.GenerateHelpText(localEnv)) + +env = localEnv.Clone() + +if not (os.path.isdir("godot-cpp") and os.listdir("godot-cpp")): + print_error("""godot-cpp is not available within this folder, as Git submodules haven't been initialized. +Run the following command to download godot-cpp: + + git submodule update --init --recursive""") + sys.exit(1) + +env = SConscript("godot-cpp/SConstruct", {"env": env, "customs": customs}) + +env.Append(CPPPATH=["src/"]) +sources = Glob("src/*.cpp") + +if env["target"] in ["editor", "template_debug"]: + try: + doc_data = env.GodotCPPDocData("src/gen/doc_data.gen.cpp", source=Glob("doc_classes/*.xml")) + sources.append(doc_data) + except AttributeError: + print("Not including class reference as we're targeting a pre-4.3 baseline.") + +# .dev doesn't inhibit compatibility, so we don't need to key it. +# .universal just means "compatible with all relevant arches" so we don't need to key it. +suffix = env['suffix'].replace(".dev", "").replace(".universal", "") + +lib_filename = "{}{}{}{}".format(env.subst('$SHLIBPREFIX'), libname, suffix, env.subst('$SHLIBSUFFIX')) + +library = env.SharedLibrary( + "bin/{}/{}".format(env['platform'], lib_filename), + source=sources, +) + +copy = env.Install("{}/bin/{}/".format(projectdir, env["platform"]), library) + +default_args = [library, copy] +Default(*default_args) diff --git a/build_profile.json b/build_profile.json new file mode 100644 index 0000000..d172f52 --- /dev/null +++ b/build_profile.json @@ -0,0 +1,9 @@ +{ + "_": "This is an example build profile and not used by default. See the SConstruct file for more information.", + "type": "feature_profile", + "enabled_classes": [ + "Node3D", + "ImageTexture", + "OS" + ] +} diff --git a/doc_classes/ExampleClass.xml b/doc_classes/ExampleClass.xml new file mode 100644 index 0000000..92f54e3 --- /dev/null +++ b/doc_classes/ExampleClass.xml @@ -0,0 +1,20 @@ + + + + Example class. + + + An example class. + + + + + + + + + Print the type of the variant. + + + + diff --git a/godot-cpp b/godot-cpp new file mode 160000 index 0000000..6388e26 --- /dev/null +++ b/godot-cpp @@ -0,0 +1 @@ +Subproject commit 6388e26dd8a42071f65f764a3ef3d9523dda3d6e diff --git a/methods.py b/methods.py new file mode 100644 index 0000000..a8bc0a4 --- /dev/null +++ b/methods.py @@ -0,0 +1,52 @@ +import os +import sys +from enum import Enum + +# Colors are disabled in non-TTY environments such as pipes. This means +# that if output is redirected to a file, it won't contain color codes. +# Colors are always enabled on continuous integration. +_colorize = bool(sys.stdout.isatty() or os.environ.get("CI")) + + +class ANSI(Enum): + """ + Enum class for adding ansi colorcodes directly into strings. + Automatically converts values to strings representing their + internal value, or an empty string in a non-colorized scope. + """ + + RESET = "\x1b[0m" + + BOLD = "\x1b[1m" + ITALIC = "\x1b[3m" + UNDERLINE = "\x1b[4m" + STRIKETHROUGH = "\x1b[9m" + REGULAR = "\x1b[22;23;24;29m" + + BLACK = "\x1b[30m" + RED = "\x1b[31m" + GREEN = "\x1b[32m" + YELLOW = "\x1b[33m" + BLUE = "\x1b[34m" + MAGENTA = "\x1b[35m" + CYAN = "\x1b[36m" + WHITE = "\x1b[37m" + + PURPLE = "\x1b[38;5;93m" + PINK = "\x1b[38;5;206m" + ORANGE = "\x1b[38;5;214m" + GRAY = "\x1b[38;5;244m" + + def __str__(self) -> str: + global _colorize + return str(self.value) if _colorize else "" + + +def print_warning(*values: object) -> None: + """Prints a warning message with formatting.""" + print(f"{ANSI.YELLOW}{ANSI.BOLD}WARNING:{ANSI.REGULAR}", *values, ANSI.RESET, file=sys.stderr) + + +def print_error(*values: object) -> None: + """Prints an error message with formatting.""" + print(f"{ANSI.RED}{ANSI.BOLD}ERROR:{ANSI.REGULAR}", *values, ANSI.RESET, file=sys.stderr) diff --git a/project/bin/example.gdextension b/project/bin/example.gdextension new file mode 100644 index 0000000..8be121f --- /dev/null +++ b/project/bin/example.gdextension @@ -0,0 +1,57 @@ +[configuration] + +entry_symbol = "example_library_init" +compatibility_minimum = "4.1" +reloadable = false + +[libraries] +; Relative paths ensure that our GDExtension can be placed anywhere in the project directory. +macos.single.debug = "./macos/libEXTENSION-NAME.macos.template_debug.dylib" +macos.double.debug = "./macos/libEXTENSION-NAME.macos.template_debug.double.dylib" +macos.single.release = "./macos/libEXTENSION-NAME.macos.template_release.dylib" +macos.double.release = "./macos/libEXTENSION-NAME.macos.template_release.double.dylib" + +ios.arm64.single.debug = "./ios/libEXTENSION-NAME.ios.template_debug.arm64.dylib" +ios.arm64.double.debug = "./ios/libEXTENSION-NAME.ios.template_debug.arm64.double.dylib" +ios.arm64.single.release = "./ios/libEXTENSION-NAME.ios.template_release.arm64.dylib" +ios.arm64.double.release = "./ios/libEXTENSION-NAME.ios.template_release.arm64.double.dylib" + +windows.x86_32.single.debug = "./windows/EXTENSION-NAME.windows.template_debug.x86_32.dll" +windows.x86_32.double.debug = "./windows/EXTENSION-NAME.windows.template_debug.x86_32.double.dll" +windows.x86_32.single.release = "./windows/EXTENSION-NAME.windows.template_release.x86_32.dll" +windows.x86_32.double.release = "./windows/EXTENSION-NAME.windows.template_release.x86_32.double.dll" + +windows.x86_64.single.debug = "./windows/EXTENSION-NAME.windows.template_debug.x86_64.dll" +windows.x86_64.double.debug = "./windows/EXTENSION-NAME.windows.template_debug.x86_64.double.dll" +windows.x86_64.single.release = "./windows/EXTENSION-NAME.windows.template_release.x86_64.dll" +windows.x86_64.double.release = "./windows/EXTENSION-NAME.windows.template_release.x86_64.double.dll" + +linux.x86_64.single.debug = "./linux/libEXTENSION-NAME.linux.template_debug.x86_64.so" +linux.x86_64.double.debug = "./linux/libEXTENSION-NAME.linux.template_debug.x86_64.double.so" +linux.x86_64.single.release = "./linux/libEXTENSION-NAME.linux.template_release.x86_64.so" +linux.x86_64.double.release = "./linux/libEXTENSION-NAME.linux.template_release.x86_64.double.so" + +linux.arm64.single.debug = "./linux/libEXTENSION-NAME.linux.template_debug.arm64.so" +linux.arm64.double.debug = "./linux/libEXTENSION-NAME.linux.template_debug.arm64.double.so" +linux.arm64.single.release = "./linux/libEXTENSION-NAME.linux.template_release.arm64.so" +linux.arm64.double.release = "./linux/libEXTENSION-NAME.linux.template_release.arm64.double.so" + +linux.rv64.single.debug = "./linux/libEXTENSION-NAME.linux.template_debug.rv64.so" +linux.rv64.double.debug = "./linux/libEXTENSION-NAME.linux.template_debug.rv64.double.so" +linux.rv64.single.release = "./linux/libEXTENSION-NAME.linux.template_release.rv64.so" +linux.rv64.double.release = "./linux/libEXTENSION-NAME.linux.template_release.rv64.double.so" + +android.x86_64.single.debug = "./android/libEXTENSION-NAME.android.template_debug.x86_64.so" +android.x86_64.double.debug = "./android/libEXTENSION-NAME.android.template_debug.x86_64.double.so" +android.x86_64.single.release = "./android/libEXTENSION-NAME.android.template_release.x86_64.so" +android.x86_64.double.release = "./android/libEXTENSION-NAME.android.template_release.x86_64.double.so" + +android.arm64.single.debug = "./android/libEXTENSION-NAME.android.template_debug.arm64.so" +android.arm64.double.debug = "./android/libEXTENSION-NAME.android.template_debug.arm64.double.so" +android.arm64.single.release = "./android/libEXTENSION-NAME.android.template_release.arm64.so" +android.arm64.double.release = "./android/libEXTENSION-NAME.android.template_release.arm64.double.so" + +web.wasm32.single.debug = "./web/libEXTENSION-NAME.web.template_debug.wasm32.nothreads.wasm" +web.wasm32.double.debug = "./web/libEXTENSION-NAME.web.template_debug.wasm32.double.nothreads.wasm" +web.wasm32.single.release = "./web/libEXTENSION-NAME.web.template_release.wasm32.nothreads.wasm" +web.wasm32.double.release = "./web/libEXTENSION-NAME.web.template_release.wasm32.double.nothreads.wasm" diff --git a/project/example.gd b/project/example.gd new file mode 100644 index 0000000..02cfc52 --- /dev/null +++ b/project/example.gd @@ -0,0 +1,6 @@ +extends Node + + +func _ready() -> void: + var example := ExampleClass.new() + example.print_type(example) diff --git a/project/example.tscn b/project/example.tscn new file mode 100644 index 0000000..8fea2ee --- /dev/null +++ b/project/example.tscn @@ -0,0 +1,6 @@ +[gd_scene load_steps=2 format=3 uid="uid://dh0oj81pufivs"] + +[ext_resource type="Script" path="res://example.gd" id="1_jdh55"] + +[node name="Node" type="Node"] +script = ExtResource("1_jdh55") diff --git a/project/icon.svg b/project/icon.svg new file mode 100644 index 0000000..adc26df --- /dev/null +++ b/project/icon.svg @@ -0,0 +1 @@ + diff --git a/project/icon.svg.import b/project/icon.svg.import new file mode 100644 index 0000000..c8d2b12 --- /dev/null +++ b/project/icon.svg.import @@ -0,0 +1,37 @@ +[remap] + +importer="texture" +type="CompressedTexture2D" +uid="uid://dbx66sovxd1" +path="res://.godot/imported/icon.svg-218a8f2b3041327d8a5756f3a245f83b.ctex" +metadata={ +"vram_texture": false +} + +[deps] + +source_file="res://icon.svg" +dest_files=["res://.godot/imported/icon.svg-218a8f2b3041327d8a5756f3a245f83b.ctex"] + +[params] + +compress/mode=0 +compress/high_quality=false +compress/lossy_quality=0.7 +compress/hdr_compression=1 +compress/normal_map=0 +compress/channel_pack=0 +mipmaps/generate=false +mipmaps/limit=-1 +roughness/mode=0 +roughness/src_normal="" +process/fix_alpha_border=true +process/premult_alpha=false +process/normal_map_invert_y=false +process/hdr_as_srgb=false +process/hdr_clamp_exposure=false +process/size_limit=0 +detect_3d/compress_to=1 +svg/scale=1.0 +editor/scale_with_editor_scale=false +editor/convert_colors_with_editor_theme=false diff --git a/project/project.godot b/project/project.godot new file mode 100644 index 0000000..9c5c174 --- /dev/null +++ b/project/project.godot @@ -0,0 +1,15 @@ +; Engine configuration file. +; It's best edited using the editor UI and not directly, +; since the parameters that go here are not all obvious. +; +; Format: +; [section] ; section goes between [] +; param=value ; assign values to parameters + +config_version=5 + +[application] + +config/name="godot cpp template" +config/features=PackedStringArray("4.1", "Forward Plus") +config/icon="res://icon.svg" diff --git a/src/example_class.cpp b/src/example_class.cpp new file mode 100644 index 0000000..177f9b5 --- /dev/null +++ b/src/example_class.cpp @@ -0,0 +1,9 @@ +#include "example_class.h" + +void ExampleClass::_bind_methods() { + godot::ClassDB::bind_method(D_METHOD("print_type", "variant"), &ExampleClass::print_type); +} + +void ExampleClass::print_type(const Variant &p_variant) const { + print_line(vformat("Type: %d", p_variant.get_type())); +} diff --git a/src/example_class.h b/src/example_class.h new file mode 100644 index 0000000..76c6d55 --- /dev/null +++ b/src/example_class.h @@ -0,0 +1,20 @@ +#pragma once + +#include "godot_cpp/classes/ref_counted.hpp" +#include "godot_cpp/classes/wrapped.hpp" +#include "godot_cpp/variant/variant.hpp" + +using namespace godot; + +class ExampleClass : public RefCounted { + GDCLASS(ExampleClass, RefCounted) + +protected: + static void _bind_methods(); + +public: + ExampleClass() = default; + ~ExampleClass() override = default; + + void print_type(const Variant &p_variant) const; +}; diff --git a/src/register_types.cpp b/src/register_types.cpp new file mode 100644 index 0000000..2760920 --- /dev/null +++ b/src/register_types.cpp @@ -0,0 +1,38 @@ +#include "register_types.h" + +#include +#include +#include +#include + +#include "example_class.h" + +using namespace godot; + +void initialize_gdextension_types(ModuleInitializationLevel p_level) +{ + if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) { + return; + } + GDREGISTER_CLASS(ExampleClass); +} + +void uninitialize_gdextension_types(ModuleInitializationLevel p_level) { + if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) { + return; + } +} + +extern "C" +{ + // Initialization + GDExtensionBool GDE_EXPORT example_library_init(GDExtensionInterfaceGetProcAddress p_get_proc_address, GDExtensionClassLibraryPtr p_library, GDExtensionInitialization *r_initialization) + { + GDExtensionBinding::InitObject init_obj(p_get_proc_address, p_library, r_initialization); + init_obj.register_initializer(initialize_gdextension_types); + init_obj.register_terminator(uninitialize_gdextension_types); + init_obj.set_minimum_library_initialization_level(MODULE_INITIALIZATION_LEVEL_SCENE); + + return init_obj.init(); + } +} \ No newline at end of file diff --git a/src/register_types.h b/src/register_types.h new file mode 100644 index 0000000..e6fe2b0 --- /dev/null +++ b/src/register_types.h @@ -0,0 +1,7 @@ +#ifndef EXAMPLE_REGISTER_TYPES_H +#define EXAMPLE_REGISTER_TYPES_H + +void initialize_gdextension_types(); +void uninitialize_gdextension_types(); + +#endif // EXAMPLE_REGISTER_TYPES_H \ No newline at end of file