Demo Porting Rules¶
This guide is for contributors porting Godot demos or writing Kanama gameplay code. It records rules learned from the Platformer, Match-3, FPS, and Racing ports.
Starting a Session¶
Read CONTRIBUTING.md before changing code and confirm the current task from
the issue, pull request, or maintainer handoff. When you finish a slice, run the
relevant validation and commit both Kanama and demo-repo changes if both repos
changed.
Check the original GDScript and scene files before inventing a Kotlin shape. If a port exposes missing framework support, prefer fixing Kanama over adding a port-specific workaround that changes the original semantics.
High-Risk Changes¶
Use extra review time for final audit design, FFM marshalling core changes, Array/Dictionary/Variant policy, ownership/refcount semantics, or review of large risky changes before release. These areas are where small mistakes can corrupt data at the Godot/Kotlin boundary.
Extra review can help, but keep the scope narrow: read-only ABI sweeps, ownership-policy review, Array/Dictionary/Variant policy comparison, or reviewing a specific FFM change before commit. Broad ABI fixes should have a precise owner and a focused integration review.
Script Classes¶
Kanama scripts are normal Kotlin objects attached to Godot objects:
package fps
@ScriptClass(attachTo = "CharacterBody3D")
class Player(godotObject: GodotHandle) :
KanamaScript<CharacterBody3D>(godotObject, ::CharacterBody3D) {
@OnReady
fun ready() {
val camera = self.requireAs("Camera3D", ::Camera3D)
}
}
Use a named package in demo scripts. The Kotlin this value is the JVM script
object, not the Godot node. Prefer KanamaScript<Self> for new scripts so
self is typed to the attachTo class. Use selfAs(::NodeType) for another
compatible wrapper on the same Godot object. Treat
selfAs(godotObject, ::NodeType) as legacy compatibility syntax; new ports
should use KanamaScript<T>.
If a script directly extends KanamaScript<...>, keep the generic type aligned
with @ScriptClass(attachTo = "..."). KSP emits a warning for mismatches. Treat
that warning as a likely porting mistake unless the script intentionally wants a
looser self type.
@ScriptClass(attachTo = "...") names the Godot base class the script is
attached to. @GlobalClass makes a script usable as a typed value in Godot's
inspector, including custom resource scripts such as Weapon and node scripts
such as Vehicle.
A script class that extends another script class of the project (GDScript
extends Vehicle) inherits its exports, signals, lifecycle handlers and public
functions: do not add forwarding overrides. Override only what the subclass
changes; an override without annotations keeps the base's role
(override fun ready() of a base @OnReady open fun ready() is still the
_ready handler). See Scripts.
Exports and Scene Data¶
Keep exported properties aligned with the original GDScript type:
@Export
var crosshair: TextureRect? = null
@Export
var target: Vehicle? = null
Keep readable GDScript-style defaults when Kanama supports them. For example,
prefer Math.toRadians(-60.0) over a long radian literal when porting
deg_to_rad(-60.0); KSP preserves that as a static inspector default.
Godot may serialize exported object references as NodePath(...) in .tscn
files, but that does not mean the Kotlin property should be a NodePath. If
the GDScript declared @export var crosshair: TextureRect, keep the Kotlin
property as TextureRect?. Use NodePath only when the original script
exposed a path value intentionally.
For GDScript PackedStringArray exports used as string lists, use
List<String> in Kotlin. Kanama exports that as Array[String] and accepts
scene-authored PackedStringArray values during load.
When the original GDScript configures an instantiated scene before
add_child(...), keep that flow. Object.set(...) values are applied to the
Kanama script instance once Godot creates it:
val bullet = bulletScene?.instantiate()
bullet?.call("set", "velocity", direction * speed)
bullet?.call("set", "shooter", self)
parent.addChild(bullet)
For custom resources, use same-project @GlobalClass resource scripts and
typed collections:
@ScriptClass(attachTo = "Resource")
@GlobalClass
class Weapon(val godotObject: GodotHandle) {
@Export
var crosshair: Texture2D? = null
}
@Export
var weapons: List<Weapon> = emptyList()
Kanama resolves live Kotlin script resource instances when reading exported resource references, so inspector-authored fields are preserved.
For runtime-created custom resources, do not translate GDScript
DataMap.new() into ResourceLoader.load("res://...kt").call("new"). Generic
Kanama script resources do not expose the GDScript-only new API. Create a
plain Resource, attach the loaded script with setScript, and resolve the
typed Kotlin instance:
val script = ResourceLoader.load("res://kotlin-src/DataMap.kt") ?: error("missing script")
val owner = Resource.create()
owner.setScript(script)
val map = owner.kotlinScriptInstance<DataMap>() ?: error("missing DataMap")
Keeping only map is enough: a script object that extends KanamaScript keeps
its resource alive, so owner may be closed or dropped once the
script object is in hand.
Treat Kanama .kt scripts as trusted executable project code. This is the
same security model as GDScript, C#, native GDExtensions, and editor plugins;
do not run untrusted Godot projects with their addons/extensions enabled.
Use @ExportGroup("...") and @ExportSubgroup("...") on the first exported
property in a group when matching grouped GDScript inspector layout.
Use annotation constants for inspector metadata instead of private magic numbers in gameplay scripts:
@ExportRange(0.0, 100.0, 1.0)
var health = 100L
Use the typed hint annotation that matches the original @export_* (see
Exports and Resources).
Mobile Runtime Warmup¶
Android can expose first-use hitches that are hard to see on desktop. When a mobile control path can trigger a scene, audio stream, particle effect, or generated mesh for the first time, load or cache that work during startup or a noninteractive pause screen instead of doing it on the first button press.
Prefer a small project-owned warmup helper for demo ports. Cache
PackedScenes that are instantiated during combat, keep frequently played
AudioStreams warm, and avoid synchronous load(...) calls in gameplay
callbacks. For generated visuals such as aiming arcs or trajectory ribbons,
reuse or throttle mesh generation rather than committing a new mesh every frame.
Keep desktop warmup lighter than mobile warmup unless the demo has a measured
desktop hitch. Loading and caching PackedScene or AudioStream resources is
safe on a pause screen, but adding hidden scene instances to a paused tree and
immediately queueFree()-ing them can defer renderer/physics cleanup until the
player resumes. On desktop Forward+/Metal this can show up as a crash or
shader/resource teardown noise on the first unpause. Gate heavy instance pools
or instantiate-and-free warmup behind mobile feature checks, and keep desktop
startup to resource caches unless a targeted smoke test proves the heavier path
is needed.
Resource and Tween Ownership¶
Follow the one rule in
Godot API → Resource Ownership:
close() releases your reference and never destroys an object someone else
still holds. Which wrappers are yours is fixed by how you got them:
- Owned — close it.
X.create(),ResourceLoader.load…, and everyRefCounted-typed method return, including plain getters such asmeshInstance.getMesh()oranimationPlayer.getAnimation("walk"). Not closing one keeps the reference until the garbage collector drops the wrapper, so ported demos still close them: the demos are the examples people copy, and Web has no collector fallback yet. - Borrowed — never close it. A view you minted around a handle you already
had:
Resource.fromHandle(...), or a script-class constructor over an existing object. - Engine-owned and live — use the Godot lifecycle. A running
TweenfromcreateTween():kill()it, do notclose()it. Nodes are not refcounted at all;queueFree()them.
For tweens that means:
// Correct: Godot owns and runs the active tween; the Tweener it hands back is
// yours, so close it once configured.
val tween = self.createTween() ?: return
tween.tweenProperty(icon, "modulate", Color.WHITE, 0.2).close()
// Wrong: releasing the live tween itself.
tween.close()
Every Tweener fluent setter returns the non-null self type
(setTrans(...): PropertyTweener, Godot marks these returns meta: "required"; a null from the
engine throws IllegalStateException instead), so chain them with .:
tweener.setTrans(Tween.TransitionType.BACK).setEase(Tween.EaseType.OUT). The call still
collapses to the same wrapper when the engine hands back the receiver.
If the script tracks a tween to cancel it later, use kill() and drop the
Kotlin reference. Closing active tweens early can show up as native renderer
crashes on desktop Metal/MoltenVK rather than as a clean Kotlin exception.
Handing a created resource to a node is safe to follow with close(): the
setter takes its own reference, so after meshInstance.setMesh(mesh) a
mesh.close() (or use { } around the whole handoff) releases only yours
(issue #91 is what happened before that contract held).
RefCounted.close() needs no opt-in: @ManualGodotLifetimeApi is deprecated
and no longer applied, so drop any @OptIn for it from a port. The rule above
is what scripts/demo_parity_audit.py in the demos repository enforces — it
fails a close() on a borrowed view (fromHandle) or on a live Tween, and
never flags closing an owned return. A from* downcast (fromObject,
fromResource) is owned: it takes its own reference, so closing
it is correct (and forgetting it is a late release).
Signals and Callbacks¶
Scene-connected methods need to be callable from Godot:
@GodotName("_on_body_entered")
fun onBodyEntered(body: GodotObject) {
collect()
}
The string is the method name stored in the scene connection. Methods named with a leading underscore are just ordinary scene callback names unless they are Godot lifecycle methods.
Use lifecycle annotations for Godot lifecycle hooks:
@OnReady
fun ready() {
...
}
@OnPhysicsProcess
fun physicsProcess(delta: Double) {
...
}
Declare custom signals with @Signal and emit them through the generated
helper:
@Signal
fun healthUpdated(value: Long) = Unit
PlayerSignals.healthUpdated(this, health)
Animation call-track methods and custom signals are separate concepts. If GDScript declares a signal and an animation track calls a method that emits it, map both pieces explicitly:
signal stepped
func _step() -> void:
stepped.emit()
@GodotName("_step")
fun step() {
CharacterSkinSignals.stepped(this)
}
@Signal
fun stepped() = Unit
Signals are instance-scoped. A receiver knows which object emitted the signal
through the scene connection or explicit connect call, not only by the
signal name.
Use the typed signal handles: the engine signal properties and the
KSP-generated handles of Kanama script signals, connected with connect { }
inside a script so the lambda is bound to it:
area.bodyEntered.connect { body -> ... } // body: Node3D
timer.timeout.connect { onTimeout() }
events.flagReached.connect { onFlagReached() } // events: the Events script object
events.killPlaneTouched.emit(body)
launch { animationPlayer.animationFinished.await() }
EventsNames.Signals / Area3D.Signals constants with signal(name) remain
for the cases the typed handles do not cover (a GDScript-declared signal, or a
script signal argument without a typed decode).
Avoid raw string signal and method names in demo ports when generated constants exist. Raw strings are acceptable only for dynamic GDScript/engine calls that Kanama cannot type yet, and the parity audit should record why.
Do not use GodotObject.call("get", ...), GodotObject.call("set", ...), or
string method calls in demo gameplay code when the target is a known Godot
class or known Kanama script. Add or use a typed Kanama wrapper first, then
update the demo to call the typed method/property. Accept dynamic calls only at
true dynamic boundaries, such as untyped Godot callback bodies, intentionally
duck-typed damage receivers, mixed GDScript/Kanama edges, or smoke-test probes.
For AnimationTree parameter paths, use AnimationMixer.getParameter,
setParameter, and getStateMachinePlayback. Keep the parameter path strings
as named constants close to the original GDScript, but do not leak raw
Object.get/Object.set calls into demo scripts.
For known Kanama scripts attached to nodes, resolve the script instance with
script<T>(path) (a delegate), asScript<T>() or kotlinScriptInstance<T>() and call the Kotlin
method directly; test GDScript's body is Player with body.isScript<Player>(). Do not call
script methods through GodotObject.call("method_name") unless the original is
intentionally duck typed.
For GDScript await get_tree().process_frame, use nextFrame() inside the
script's launch { }; for await get_tree().create_timer(t).timeout, wait(t).
They are the Kanama equivalents of yielding until a later frame while continuing
on the main thread.
Do not schedule engine-wide follow-up work in a coroutine owned by the scene
being destroyed. In particular, after SceneTree.unloadCurrentScene(), do not
launch { ... SceneTree.quit() ... } from a script attached
to that scene. The scene unload can free the script and cancel the coroutine
before the quit runs. Use MainThread.postAfterFrames(...) for this kind of
process-level handoff.
Porting Style¶
Keep the Kotlin port close to the original GDScript. Preserve original comments whenever they are still applicable, especially comments that explain gameplay rules, timing, scene relationships, resource ownership, exported inspector values, or non-obvious Godot behavior. These ports are examples for new Kanama users, so comments from the source demo are part of the teaching surface. Avoid copying only comments that became false after the port or comments that merely describe syntax already obvious in Kotlin.
Before calling a demo port done, do a side-by-side parity audit against the
original GDScript files. Check lifecycle callbacks, signal wiring, emitted
signal names, comments, queue/pool ownership, tween ownership, resource
ownership, input/action names, animation names, exported defaults, type checks,
dynamic call/signal usage, and self access.
Do not hide live scene instances behind companion-object singleton facades unless the original project used a true singleton/autoload with matching semantics. Prefer the original node/autoload lookup flow, then call the typed Kanama script instance from that node.
Do not embed environment-gated smoke-test branches in normal gameplay scripts.
Put smoke behavior in dedicated Smoke.kt or SmokeQuit.kt scripts/nodes so
the gameplay port stays close to the source demo. Where a smoke has to reach
several gameplay classes, register one Smoke autoload that finds them from
outside, and keep every hook, probe and environment read in it: the demos'
demoParityAudit fails on a smoke/probe member, @GodotName, or environment or
command-line read in a gameplay class. The Web harness calls the autoload's
methods by name through the export manifest.
When the original GDScript calls Godot math, random, or value-type helpers,
prefer the Kanama/Godot wrapper (GD, Mathf, Vector3.moveToward,
Vector3.signedAngleTo, etc.) over hand-written Kotlin math inside the demo.
If the wrapper is missing, add it to Kanama first instead of adding a local
helper in the port.
Put demo gameplay scripts under kotlin-src/. Once a scene is rewired to
Kotlin, remove stale gameplay .gd files and their .uid files so Godot does
not resolve old script UIDs back to the original implementation. Keep the
Kanama tools plugin scripts.
Do not hard-code scene paths, resource paths, or inspector values as a workaround for missing wrappers or marshalling support unless the user asks for a temporary workaround. Real demo ports should drive real framework fixes.
Do not make required autoloads or scene nodes optional just to avoid a crash.
If the original GDScript directly uses an autoload such as Events, use the
generated Autoloads.Events (typed to the autoload's Kotlin script, scene root
class or extends class); it fails loudly, naming the autoload, when the node is
missing:
EventsSignals.flagReached(Autoloads.Events) // GDScript: Events.flag_reached.emit()
Silent fallback should not be the default in Kanama examples. Kotlin's value
here is compile-time and early-runtime protection, so required scene
relationships should use typed wrappers, generated names, requireAs(...), or
explicit error(...) paths that expose misconfigured scenes immediately.
Optional lookup belongs only where the original GDScript behavior was optional.
Preserve original type checks. If GDScript says body is Player, do not
broaden it to hasMethod("damage"), isInGroup("damageables"), or a generic
node check unless the original code used that broader rule. When Kanama cannot
express a script class check directly yet, centralize the closest equivalent in
a small helper and document why it matches the original scene's intent.
Remaining Deviations in the Reference Ports¶
The rules above are the target, and the current ports do not all meet them. Each
deviation below is a gap in Kanama that a port worked around, not a licence to
copy the workaround (as of kanama-demos main 556051c):
- Local value-type math.
Basis * BasisandTransform3D * Transform3Ddo not exist on the value types (onlyTransform3D * Vector3,Basis * Vector3andQuaternion * Quaternionhave operators), sotps-demo-kanamawritescomposeTransforms/composeBasesin bothPlayer.ktandRedRobot.kt. Add the operator to Kanama instead of copying the helper. - Type checks. GDScript's
is Playerhas no one-line Kotlin spelling yet.tps-demo-kanamacentralizes the closest equivalent inNode.isPlayerNode()(TpsScenes.kt), which also matches a node by name ("Player"or a numeric name). That is a name heuristic, not the original type check. - Multiplayer effects. The TPS port calls the
@Rpc(callLocal = true)functions for jump, shoot, hit and explode as plain local functions rather than through the generated*Rpcssenders, so those effects do not reach other peers. Use the generated*Rpcssenders (see Multiplayer).
Parity Audit against the Original¶
The side-by-side audit needs the original GDScript, and the demo repository does
not carry it: the ports replace the GDScript in place. Clone the upstream project
listed in the kanama-demos README under "Sources And Licenses" and compare
against it. Nothing in the repository pins the upstream commit a port is based on
(the kanama-demos README table and
godot-4-3d-character-controller-tutorial/UPSTREAM_ATTRIBUTION.md record the
upstream repository and license, not a commit), so name the
upstream commit you audited against in the pull request.
Some .gd files legitimately remain after a port. They are not gameplay
scripts to port, and they are the exceptions to "remove stale gameplay .gd
files": the touch-control glue the demos add for mobile (mobile_controls.gd,
mobile_dpad.gd, responsive_background.gd, none of which exist upstream), the
Bunnymark GDScript baselines, and the character-controller lesson_reference/
scripts. Starter-Kit-3D-Platformer also keeps scripts/audio.gd (the Audio
autoload) and scripts/main.gd in GDScript on desktop; its Web build overrides
Main with web/kotlin-src/Main.kt.
Build and Smoke Checklist¶
For a Kanama demo checked out beside the Kanama repo, build scripts with:
../kanama/gradlew -p ../kanama-demos/<DemoName> buildScripts
The Godot editor can also run the same flow through the Kanama tools plugin's
Build Scripts button.
For public demo repo changes, run the aggregate guardrails from the demo repo:
./gradlew check
That task runs the parity audit, runtime node/RPC guardrail, and replicated script-property guardrail across the public demo set.
Validate with the active Godot preview baseline and any compatibility build needed by the task:
/path/to/godot/bin/godot.macos.editor.arm64
Headless smoke tests should load the real scene and exercise a small behavior slice, such as signal wiring, exported resource hydration, typed object exports, or physics entry points. Manual playtesting is still required for feel-sensitive demos such as FPS and Racing.
Known shutdown diagnostics such as RID leaks, particle shader cleanup logs, or lingering embedded game audio are tracked separately. Record them, but do not treat them as proof that a gameplay port failed unless they leave a process alive or break repeatable validation.
Before chasing shutdown leaks, find the owned wrapper that was never closed:
project-owned warmup caches, Tweener wrappers left open after configuration,
resource read-backs kept only for a check, pooled nodes that will not be
reused, and active AudioStreamPlayers that should stop before
unloadCurrentScene(). Do not close a borrowed view or a live engine-owned
object to silence a warning.
Resource-returning getters hand back an owned wrapper even though the node
keeps its own reference. Do not write checks such as crosshair.texture != null
and discard the wrapper. Store it, check it, and close it:
val texture = crosshair.texture
check(texture != null)
texture?.close()
The same holds for a resource you only touch briefly, such as an animation on
a scene-owned AnimationPlayer: the getter still transferred a reference, so
release it when you are done instead of leaving it to leak:
animationPlayer.getAnimation("walk")?.use { it.setLoopMode(Animation.LoopMode.LINEAR) }
If a shutdown warning still names a scene resource after every owned wrapper is closed, look at the scene lifetime (active playback, a node freed after the tree) or document the residual warning; do not release a handle you did not take.