Code Monkey home page Code Monkey logo

gd's Introduction

Godot 4.2.1 + Go Go Reference

This module provides a safe and simple way to work with Godot 4.2.1, in Go via the GDExtension interface.

You can support the project and prioritise issues here

package main

import (
	"fmt"

	"grow.graphics/gd"
	"grow.graphics/gd/gdextension"
)

type HelloWorld struct {
	gd.Class[HelloWorld, gd.Node2D]
}

// Ready implements the Godot Node2D _ready interface (virtual function).
func (h *HelloWorld) Ready(gd.Context) {
	fmt.Println("Hello World from Go!")
}

func main() {
	godot, ok := gdextension.Link()
	if !ok {
		return
	}
	gdextension.RegisterClass[HelloWorld](godot)
}

Getting Started

The module includes a drop-in replacement for the go command called gd that makes it easy to work with projects that run within Godot. It enables you to start developing a new project from a single main.go file, to install it, make sure that your $GOPATH/bin is in your $PATH and run:

	go install grow.graphics/gd/cmd/gd@master

Now when you can run gd run, gd test on the main package in your project's directory, things will work as expected. The tool will create a "graphics" subdirectory where you can manage your assets via the Godot Editor.

Running the command without any arguments will startup the editor.

NOTE On linux, gd will download Godot for you automatically!

Design Principles

Godot classes are exported by the gd package and can be referred to by their standard Godot names, for example gd.Object is an Object reference. There's no inheritance, so to access the 'super' class, you need to call Super() on your custom 'Class'. All Godot classes have methods to cast to the classes they extend for example AsObject() or AsNode2D().

Methods have been renamed to follow Go conventions, so instead of underscores, methods are named as PascalCase. Keep this in mind when referring to the Godot documentation.

https://docs.godotengine.org/en/latest/index.html

Semi-Automatic Memory Management

Godot types are preferred over Go types, in order to keep allocations optional. All values are tied to a [gd.Context] type, which is either:

(a) a function argument and any values associated with it will be freed
    when the function returns.
(b) builtin to the class you are extending, and any values associated 
    with it will be freed when the class is destroyed by Godot.

This module aims to offer memory safety for race-free extensions, if you discover a way to unintentionally do something unsafe (like double free, use-after-free or a segfault), using methods on types exported by the root gd package please open an issue.

Recommendations

Start with a main.go file, model your project in Go using structs to represent the world, space or state of your project. Go is an excellent language for textual representation. Use the gd command to launch the Godot editor when you want to create visual representation of your structures. The Godot editor is an excellent tool for importing media, managing assets and designing the visual and spatial aspects of a project. Don't forget to write tests!

Where Do I Find?

* Godot Class            -> gd.{ClassName}
* Godot Class Method     -> gd.{ClassName}.{pascal(MethodName)}
* Godot Utility Function -> gd.Context.{pascal(UtilityName)} OR gd.{pascal(UtilityName)} (pure)
* Godot Enum             -> gd.{EnumName}
* Godot Enum Value       -> gd.{EnumName}{EnumValueName}
* Godot Singleton        -> gd.{ClassName}(gd.Context) // function returns the singleton, they cannot be stored.

Performance

It's feasible to write high performance code using this module, keep to Godot types where possible and avoid escaping memory to the heap in frequently called functions.

Zero Allocations

Benchmarking shows method calls from Go -> Godot do not allocate in practice.

Allocations are currently unavoidable for GDScript -> Go calls (but not for class virtual method overrides such as Ready or Process, which should be allocation free).

We've got some ideas to reduce allocations for GDScript -> Go calls, when arguments fit entirely within registers. TBA.

Examples

Run make in the example/src directory or manually build a C-shared library:

cd example/src
make # go build -o ./bin/example.so -buildmode=c-shared

NOTE: the first time you build a project, it will take a little while to compile. After this, subsequent builds will be quite a bit faster!

Now open the example project in Godot from a terminal and you will be able to see Go printing things to the console.

There is also a pong example in the examples repo.

Testing

To run the go tests for this module cd internal && gd test.

Known Limitations

  • No support for indexed properties
  • No support for Godot functions with varargs.
  • No support for script extensions.
  • 64bit support only.
  • Not tested on Windows.
  • No planned support for Web export or proprietary consoles.
  • Android/MetaQuest not working right now (support is planned).

See Also

Licensing

This project is licensed under an MIT license (the same license as Godot), you can use it in any manner you can use the Godot engine. If you use this for a commercially successful project, please consider financially supporting us.

gd's People

Contributors

bmixo avatar splizard avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

gd's Issues

return string value panic: toUnsafe: unsupported type string

return value panic

gd.Scripting:

LogIn gd.Method `gd:"LogIn(userName,passWord) result"`

And go Go function method is:

func (h HelloWorld) LogIn(userName, passWord string) (result string) {
return "xxx"
}

Login asasas asasasas
panic: toUnsafe: unsupported type string

goroutine 17 [running, locked to thread]:
github.com/readykit/gd.toResult({0x7ffd950c6e80?, 0xc0000890c0?}, 0x0?)
        C:/Users/Bmixo/go/pkg/mod/github.com/readykit/[email protected]/functions.go:943 +0x759
github.com/readykit/gd.(*unsafeExtensionServer).call(0x7ffd95075560?, 0x52340?, 0x1e, 0x1e60ffbff0, 0x7ffd94d47788?)
        C:/Users/Bmixo/go/pkg/mod/github.com/readykit/[email protected]/export.go:341 +0x23f
github.com/readykit/gd.method_call_ptr(0x7ffd94d47618?, 0xc000086000?, 0x0?, 0xc000052301?)
        C:/Users/Bmixo/go/pkg/mod/github.com/readykit/[email protected]/callbacks.go:81 +0xc3

current example doesn't work

hey there, great initiative!

the provided example breaks.

steps i took

  • cloned the repo
  • cd gd/example/src
  • make
  • cd ..
  • godot4 .
Godot Engine v4.0.alpha14.official.106b68050 - https://godotengine.org
MESA-INTEL: warning: Performance support disabled, consider sysctl dev.i915.perf_stream_paranoid=0
Vulkan API 1.2.0 - Using Vulkan Device #0: Intel - Intel(R) UHD Graphics (TGL GT1)
../mesa-22.1.7/src/intel/isl/isl.c:2216: FINISHME: ../mesa-22.1.7/src/intel/isl/isl.c:isl_surf_supports_ccs: CCS for 3D textures is disabled, but a workaround is available.
 
SCRIPT ERROR: Parse Error: "HelloWorld" was not found in the current scope.
          at: GDScript::reload (res://Node2D.gd:3)
ERROR: Cannot get class 'ExtendedNode'.
   at: instantiate (core/object/class_db.cpp:325)
WARNING: Node ExtendedNode of type ExtendedNode cannot be created. A placeholder will be created instead.
     at: instantiate (scene/resources/packed_scene.cpp:201)

editor panic on windows github.com/readykit/gd.BelongsTo(...)

after i change example.gdextension file into this

[configuration]

entry_symbol = "loadExtension"

[libraries]

windows.64 = "bin/example.so"

run godot.windows.tools.x86_64.exe .

get result output

lookup _enter_tree false
lookup _input false
lookup _shortcut_input false
lookup _unhandled_input false
lookup _unhandled_key_input false
lookup _process false
lookup _physics_process false
lookup _ready true
ExtendedNode
Object
[Performance TextServerManager NavigationMeshGenerator ProjectSettings IP Geometry2D Geometry3D ResourceLoader ResourceSaver OS Engine ClassDB Marshalls TranslationServer Input InputMap EngineDebugger Time NativeExtensionManager ResourceUID WorkerThreadPool JavaClassWrapper JavaScript ThemeDB DisplayServer RenderingServer AudioServer PhysicsServer2D PhysicsServer3D NavigationServer2D NavigationServer3D XRServer CameraServer]
Scene is ready!
Hello World!
sin= 0.9974949866040544
rotation= 0
rotation= 3.140000104904175
position= {50 25}
position= {100 25}
{<nil> {0x7ffb78bceea8 2485739323648 {{} {} -1} {<nil>}}}
ERROR: Index p_screen = 1 is out of bounds (get_screen_count() = 1).
   at: DisplayServerWindows::window_set_current_screen (platform\windows\display_server_windows.cpp:823)
free &{0xc00005e060 2486104823552 {{} {} 0} {0xc0000200d8}}
<DisplayServer#2550136957>
lookup _draw false

but when i try to use godot editor to open the exaple project,the godot editor panic

free &{0xc000086098 0 {{} {} 0} {0xc000086068}}
WARNING: Blend file import is enabled in the project settings, but no Blender path is configured in the editor settings. Blend files will not be imported.
     at: _editor_init (modules\gltf\register_types.cpp:75)
WARNING: FBX file import is enabled in the project settings, but no FBX2glTF path is configured in the editor settings. FBX files will not be imported.
     at: _editor_init (modules\gltf\register_types.cpp:99)
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x0 pc=0x7ffb76200add]

goroutine 17 [running, locked to thread]:
github.com/readykit/gd.BelongsTo(...)
        C:/Users/Bmixo/Desktop/gd/extension.go:36
main.glob..func2(0x0)
        C:/Users/Bmixo/Desktop/gd/example/src/main.go:41 +0x1d
github.com/readykit/gd.(*extensionClassHandlerFor[...]).new(0xc00006a0c0, {0xc00006a0c0}, 0xc000059e00?)
        C:/Users/Bmixo/Desktop/gd/extension.go:220 +0x184
github.com/readykit/gd.(*extensionClassHandlerFor[...]).create(0xc00007de20?)
        C:/Users/Bmixo/Desktop/gd/extension.go:238 +0x26
github.com/readykit/gd.create_instance_func(...)
        C:/Users/Bmixo/Desktop/gd/callbacks.go:43

Return Parameters

When i create and register the following class:

type Test struct {
	gd.Class[Test, gd.Node]
}

func (r *Test) Test(gd.Context) {
	fmt.Println("Hello Test")
}

func (r *Test) Test2(context gd.Context, seed gd.Int) gd.String {
	fmt.Println("Hello Test 2", seed)
	return context.String("Test 2 Result")
}

I can instantiate the class and call the Test() method.
The Test2 method is not found though.

When i checked the source i saw that methods with a return parameter are implemented but disabled and when i enabled them the method could be called from godot but it always returned an empty string.

Is that part still work in progress or is there another preferred way to return data back to godot?

GDExtension support

This library appears to be developed with Alpha versions of the 4.0 branch back when it was still using GDNative.
Now that the API is stable, is there a chance to update this repo to make it work with the current master branch that uses GDExtension?

Also was c.go file generated or written by hand?
Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.