### start() Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotApp.md Example of starting the Godot instance and checking for success. ```swift let app = GodotApp(packFile: "game.pck") if app.start() { print("Godot started successfully") } else { print("Failed to start Godot") } ``` -------------------------------- ### Initialization (GodotApp) Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/README.md Example of initializing and starting the GodotApp. ```swift let app = GodotApp(packFile: "game.pck") app.registerEventHandler { event in ... } app.start() ``` -------------------------------- ### Runtime Configuration Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/configuration.md Demonstrates changing the launch scene or source before starting the Godot app. ```swift let app = GodotApp(packFile: "game.pck") // Change scene before starting app.configureLaunch(scene: "res://levels/level_02.tscn") // Or use a different pack file entirely app.configureLaunch(source: "dlc.pck", scene: "res://dlc/menu.tscn") app.start() ``` -------------------------------- ### Start Drawing Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotAppViewHandle.md Enables rendering for the Godot instance. ```swift handle.startDrawing() ``` -------------------------------- ### configureLaunch(source:scene:) Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotApp.md Example of configuring the launch source and scene before starting the Godot app. ```swift app.configureLaunch(source: "game.pck", scene: "res://main.tscn") app.start() ``` -------------------------------- ### Create and Start a Godot App Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/QUICK_REFERENCE.md Demonstrates how to create a GodotApp instance and start it within a SwiftUI view. ```swift import SwiftUI import SwiftGodotKit struct ContentView: View { @State var app = GodotApp(packFile: "game.pck") var body: some View { GodotAppView() .environment(\.godotApp, app) .onAppear { app.start() } } } ``` -------------------------------- ### start() Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotInstance.md Starts the Godot instance initialization. Must be called after creation and before iteration. ```swift public func start() -> Bool ``` ```swift let instance = GodotInstance.create(args: args) if let instance, instance.start() { print("Instance started") } ``` -------------------------------- ### Run the Standalone Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/StandaloneExample/README.md Copies the Godot library and runs the Swift package. ```bash $cp .build/*/*/libgodot.dylib . $swift run ``` -------------------------------- ### start() Method Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotApp.md Starts the Godot instance and begins rendering. Returns true if successful, false otherwise. ```swift @discardableResult public func start() -> Bool ``` -------------------------------- ### startDrawing() Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotApp.md Example of re-enabling rendering. ```swift app.startDrawing() ``` -------------------------------- ### resume() Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotApp.md Example of resuming the Godot instance. ```swift app.resume() ``` -------------------------------- ### GodotApp Initialization Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotApp.md Example of how to initialize the GodotApp with specific parameters. ```swift import SwiftGodotKit let app = GodotApp( packFile: "game.pck", godotPackPath: Bundle.main.resourcePath, renderingDriver: "metal", renderingMethod: "mobile", displayDriver: "embedded" ) ``` -------------------------------- ### Example for GodotStartupFailureEvent Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/Events.md Example of how to register an event handler to catch startup failures. ```swift app.registerEventHandler { event in if case .startupFailure(let failure) = event { print("Startup failed: \(failure.reason)") print("Source: \(failure.sourcePath)") } } ``` -------------------------------- ### Complete SwiftGodotKit Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/Events.md A comprehensive example demonstrating event handling in SwiftGodotKit. ```swift import SwiftGodotKit let app = GodotApp(packFile: "game.pck") let eventToken = app.registerEventHandler { event in switch event { case .startupFailure(let failure): print("❌ Startup failed: \(failure.reason)") print(" Path: \(failure.sourcePath)") case .warning(let warning): print("⚠️ Warning: \(warning.code)") print(" \(warning.detail)") case .bridge(let bridge): print("🌉 Bridge: \(bridge.state)") case .windowBinding(let binding): print("🪟 Window binding: \(binding.state)") if let name = binding.nodeName { print(" Window: \(name)") } case .lifecycle(let lifecycle): print("♻️ Lifecycle: \(lifecycle.label)") } } app.start() ``` -------------------------------- ### Change Scene Before Starting Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/QUICK_REFERENCE.md Illustrates how to configure a specific scene to launch before starting the Godot app. ```swift app.configureLaunch(scene: "res://levels/level_01.tscn") app.start() ``` -------------------------------- ### processKeyEvent() Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotView.md Example showing how keyDown and keyUp events are processed. ```swift override func keyDown(with event: NSEvent) { processKeyEvent(event: event, pressed: true) } override func keyUp(with event: NSEvent) { processKeyEvent(event: event, pressed: false) } ``` -------------------------------- ### Configuration Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/OVERVIEW.md Example of initializing GodotApp with various configuration options. ```swift let app = GodotApp( packFile: "game.pck", godotPackPath: Bundle.main.resourcePath, renderingDriver: "metal", renderingMethod: "mobile", displayDriver: "embedded", extraArgs: ["--debug-gdscript"] ) ``` -------------------------------- ### resizeWindow() Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotView.md Example showing automatic call to resizeWindow() when bounds change. ```swift override var bounds: CGRect { didSet { resizeWindow() // Called automatically } } ``` -------------------------------- ### Initialize Swift Package Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/StandaloneExample/README.md Initializes a new Swift Package named StandaloneExample. ```bash swift package init -n StandaloneExample ``` -------------------------------- ### GodotAppDelegate Registration Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotAppDelegate.md Example of registering the delegate with the system when the app starts. ```swift app.start() // Sets: NSApplication.shared.delegate = appDelegate ``` -------------------------------- ### Window Binding Event Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/Events.md Example of how to handle a GodotWindowBindingEvent. ```swift app.registerEventHandler { event in if case .windowBinding(let binding) = event { print("Window \(binding.nodeName ?? \"unnamed\") -> \(binding.state)") print("Owns window: \(binding.ownsWindow)") print("Platform: \(binding.platform)") } } ``` -------------------------------- ### Startup Failure: projectFileMissing Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/errors.md Example showing how a missing project.godot file in a specified directory triggers a startupFailure event with the projectFileMissing code. ```swift let app = GodotApp(packFile: "dummy") app.configureLaunch(source: "/empty/directory") app.start() // Emits startupFailure(.projectFileMissing) ``` -------------------------------- ### displayServerNotEmbedded Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/errors.md Shows how starting the GodotApp with a displayDriver other than 'embedded' triggers the displayServerNotEmbedded warning. ```swift // Occurs if app is started with displayDriver != "embedded" let app = GodotApp(packFile: "game.pck", displayDriver: "macos") GodotAppView() // displayDriver mismatch // Emits warning(.displayServerNotEmbedded) ``` -------------------------------- ### configureLaunch(source:scene:) Method Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotApp.md Pre-configures the launch source and/or scene before starting the instance. Must be called before start(). ```swift public func configureLaunch(source: String? = nil, scene: String? = nil) ``` -------------------------------- ### runOnGodotThread Before Instance Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/errors.md Demonstrates calling runOnGodotThread before starting the GodotApp instance, which will result in the closure being ignored and a warning being emitted. ```swift let app = GodotApp(packFile: "game.pck") app.runOnGodotThread { // This won't execute } // Emits warning(.runOnGodotThreadBeforeInstance) app.start() ``` -------------------------------- ### onReady Callback Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotAppView.md Example of using the onReady callback to access the scene root. ```swift GodotAppView( onReady: { handle in if let root = handle.getRoot() { print("Scene root type: \(type(of: root))") } } ) ``` -------------------------------- ### Lifecycle Event Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/Events.md Example of how to handle a GodotLifecycleEvent. ```swift app.registerEventHandler { event in if case .lifecycle(let lifecycle) = event { print("Lifecycle: \(lifecycle.label) (notification: \(lifecycle.notification))") } } ``` -------------------------------- ### UIGodotWindow startGodotInstance() method Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/PlatformViews.md Starts the Godot instance on this view. Includes registration of callbacks, creation of native surface, starting Godot, creating CADisplayLink, retrieving display server, resizing window, and polling bridge/readiness. ```swift func startGodotInstance() { } ``` -------------------------------- ### Get Root Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotAppViewHandle.md Returns the root node of the scene tree if available. ```swift if let root = handle.getRoot() { root.queueFreeNode() } ``` -------------------------------- ### Create a New Window Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotWindow.md Example of creating a new Godot Window within a SwiftUI view. ```swift import SwiftUI import SwiftGodotKit import SwiftGodot struct GameUIWindow: View { @State var app = GodotApp(packFile: "game.pck") var body: some View { VStack { Text("Overlay Window") GodotWindow { print("Window created: \(window.title)") } .padding() } .environment(\.godotApp, app) } } ``` -------------------------------- ### pause() Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotApp.md Example of pausing the Godot instance. ```swift app.pause() ``` -------------------------------- ### Load Project Directory Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/configuration.md Example of initializing GodotApp by specifying a project directory and a project file within it. ```swift let app = GodotApp(packFile: "project.godot", godotPackPath: "/path/to/my_game") app.configureLaunch(source: "/path/to/my_game") ``` -------------------------------- ### Startup Failure: instanceCreationFailed Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/errors.md Example demonstrating how a failure to create a Godot instance triggers a startupFailure event with the instanceCreationFailed code. ```swift let app = GodotApp(packFile: "game.pck") app.start() // Emits startupFailure(.instanceCreationFailed) // if libgodot binding fails ``` -------------------------------- ### processEvent() Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotView.md Example showing how mouseDown and mouseUp events are processed, including right-click emulation. ```swift override func mouseDown(with event: NSEvent) { if event.modifierFlags.contains(.control) { processEvent(event: event, index: .right, pressed: true, outOfStream: false) } else { processEvent(event: event, index: .left, pressed: true, outOfStream: false) } } override func mouseUp(with event: NSEvent) { // Handle mouse up processEvent(event: event, index: mouseDownControl ? .right : .left, pressed: false, outOfStream: false) } ``` -------------------------------- ### applicationDidBecomeActive Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotAppDelegate.md Example of when applicationDidBecomeActive is invoked. ```swift // Called automatically by the system // app.applicationDidBecomeActive() is invoked ``` -------------------------------- ### Example for GodotWarningEvent Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/Events.md Example of how to register an event handler to catch warnings. ```swift app.registerEventHandler { event in if case .warning(let warning) = event { print("⚠️ \(warning.code): \(warning.detail)") } } ``` -------------------------------- ### Startup Failure: sourcePathMissing Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/errors.md Example demonstrating how a missing pack file or project directory triggers a startupFailure event with the sourcePathMissing code. ```swift let app = GodotApp(packFile: "nonexistent.pck") app.start() // Emits startupFailure(.sourcePathMissing) ``` -------------------------------- ### Load PCK File Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/configuration.md Example of initializing GodotApp by specifying a PCK file. ```swift GodotApp(packFile: "game.pck") ``` -------------------------------- ### applicationDidResignActive Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotAppDelegate.md Example of when applicationDidResignActive is invoked. ```swift // Called automatically by the system // app.applicationDidResignActive() is invoked ``` -------------------------------- ### stop() Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotApp.md Example of stopping the Godot instance. ```swift app.stop() ``` -------------------------------- ### SwiftUI Integration Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/README.md Example of how to integrate SwiftGodotKit into an existing iOS project using SwiftUI, including adding a Godot PCK file and displaying the Godot view. ```swift import SwiftUI import SwiftGodot import SwiftGodotKit struct ContentView: View { @State var app = GodotApp(packFile: "game.pck") var body: some View { VStack { Text("Game is below:") GodotAppView() .padding() } .environment(\.godotApp, app) } } ``` -------------------------------- ### Create GodotApp Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/OVERVIEW.md Example of creating a GodotApp instance and integrating it into a SwiftUI view. ```swift import SwiftGodotKit struct GameView: View { @State var app = GodotApp(packFile: "game.pck") var body: some View { VStack { GodotAppView() } .environment(\.godotApp, app) .onAppear { app.start() } } } ``` -------------------------------- ### Is Ready Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotAppViewHandle.md Checks whether the Godot scene has finished loading and is ready for interaction. ```swift if handle.isReady() { print("Scene is ready") } else { print("Scene is still loading") } ``` -------------------------------- ### Single GodotApp Instance Initialization Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/OVERVIEW.md Demonstrates how to create and start a single GodotApp instance to manage the embedded Godot engine. ```swift let app = GodotApp(packFile: "game.pck") app.start() ``` -------------------------------- ### Mock GodotApp in Tests Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/QUICK_REFERENCE.md Example of creating a mock GodotApp for testing purposes. ```swift class MockGodotApp: GodotApp { override func start() -> Bool { // Simulate success or failure return true } } // Use in tests let app = MockGodotApp(packFile: "test.pck") ``` -------------------------------- ### Example for GodotBridgeEvent Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/Events.md Example of how to register an event handler to catch bridge state changes. ```swift app.registerEventHandler { event in if case .bridge(let bridge) = event { print("Bridge state: \(bridge.state)") } } ``` -------------------------------- ### Resume Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotAppViewHandle.md Resumes the paused Godot instance. ```swift handle.resume() ``` -------------------------------- ### onMessage Callback Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotAppView.md Example of using the onMessage callback to receive messages from the Godot scene. ```swift GodotAppView( onMessage: { message in if let score = Int(message["score"]) { print("Score: \(score)") } } ) ``` -------------------------------- ### Integration with Views Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotAppViewHandle.md Shows how GodotAppViewHandle is typically obtained through view callbacks. ```swift GodotAppView( onReady: { handle in print("View is ready: \(handle.isReady())") }, onMessage: { message in // Handle messages from Godot } ) ``` -------------------------------- ### Startup Failure: sceneMissing Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/errors.md Example illustrating how a nonexistent scene path triggers a startupFailure event with the sceneMissing code. ```swift let app = GodotApp(packFile: "game.pck") app.configureLaunch(scene: "/nonexistent/main.tscn") app.start() // Emits startupFailure(.sceneMissing) ``` -------------------------------- ### Event Handler Pattern Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/errors.md An example of registering an event handler to catch and process various events, including startup failures, warnings, and window binding events. ```swift app.registerEventHandler { event in switch event { case .startupFailure(let failure): showErrorAlert("Startup Failed", failure.reason.rawValue) case .warning(let warning): logWarning("Warning: \(warning.code) - \(warning.detail)") case .windowBinding(let binding) where binding.state == .missingNamedWindow: logWarning("Window \(binding.nodeName ?? "unknown") not found") case .bridge, .windowBinding, .lifecycle: // Info-level events; log if needed break } } ``` -------------------------------- ### iOS: UIGodotAppView - startGodotInstance() Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/PlatformViews.md Initializes and starts the Godot engine on this view. ```swift func startGodotInstance() ``` -------------------------------- ### runOnGodotThread(async:_:) Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotApp.md Example of executing a closure on the Godot main thread to access the SceneTree. ```swift app.runOnGodotThread { if let mainLoop = Engine.getMainLoop() as? SceneTree { print("Game tree root: \(mainLoop.root)") } } ``` -------------------------------- ### Test Event Handlers Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/QUICK_REFERENCE.md Example of testing event handling within GodotApp. ```swift func testEventHandling() { let app = GodotApp(packFile: "game.pck") var receivedEvent: GodotAppEvent? app.registerEventHandler { event in receivedEvent = event } // Simulate event app.emitRuntimeEvent(.lifecycle(GodotLifecycleEvent(label: "test", notification: 0))) XCTAssertNotNil(receivedEvent) } ``` -------------------------------- ### GodotAppDelegate Creation Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotAppDelegate.md Example of how GodotAppDelegate is created during GodotApp initialization. ```swift let app = GodotApp(packFile: "game.pck") // On macOS: appDelegate = GodotAppDelegate() // appDelegate.app = app ``` -------------------------------- ### Bind to a Named Window Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotWindow.md Example of binding a GodotWindow to a pre-existing Godot Window node named "PauseMenu". ```swift struct PauseMenuWindow: View { @State var app = GodotApp(packFile: "game.pck") var body: some View { GodotWindow( node: "PauseMenu", callback: { window in window.visible = true } ) .environment(\.godotApp, app) } } ``` -------------------------------- ### Warning: globalScriptCacheMissing Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/errors.md Example showing how to register an event handler to detect and log a warning when the global script cache is missing. ```swift let app = GodotApp(packFile: "dummy") app.configureLaunch(source: "/path/to/project") app.registerEventHandler { event in if case .warning(let warning) = event, warning.code == .globalScriptCacheMissing { print("Cache missing; Godot will rebuild it") } } app.start() ``` -------------------------------- ### Error Handling Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/OVERVIEW.md Example of registering an event handler to specifically catch startup failures and warnings. ```swift app.registerEventHandler { event in if case .startupFailure(let failure) = event { // Handle startup error } else if case .warning(let warning) = event { // Handle non-fatal warning } } ``` -------------------------------- ### Control Rendering Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/QUICK_REFERENCE.md Example of controlling the rendering process (stop/start drawing) via the view handle. ```swift GodotAppView( onReady: { handle in // Stop rendering temporarily handle.stopDrawing() // Resume handle.startDrawing() } ) ``` -------------------------------- ### Pause/Resume Rendering Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/QUICK_REFERENCE.md Provides code examples for pausing and resuming the Godot rendering process, as well as controlling drawing without pausing logic. ```swift // Pause the Godot instance app.pause() // Resume app.resume() // Control rendering without pausing logic app.stopDrawing() app.startDrawing() ``` -------------------------------- ### Monitor All Events Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/QUICK_REFERENCE.md Example of registering an event handler to monitor all events emitted by the Godot app and how to unregister it. ```swift let eventToken = app.registerEventHandler { event in switch event { case .startupFailure(let failure): print("Failed to start: \(failure.reason)") case .warning(let warning): print("Warning: \(warning.code)") case .bridge(let bridge): print("Bridge state: \(bridge.state)") case .windowBinding(let binding): print("Window \(binding.nodeName ?? \"unnamed\"): \(binding.state)") case .lifecycle(let lifecycle): print("Lifecycle: \(lifecycle.label)") } } // Later, unregister app.unregisterEventHandler(eventToken) ``` -------------------------------- ### Communicate with Godot (Swift) Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/OVERVIEW.md Example of sending a message from Swift to the Godot game. ```swift var msg = VariantDictionary() msg["action"] = Variant("jump") msg["power"] = Variant(5.0) app.emitMessage(msg) ``` -------------------------------- ### Send Message from Swift to Godot Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/QUICK_REFERENCE.md Example of sending a message (as a VariantDictionary) from Swift to the Godot engine. ```swift var message = VariantDictionary() message["command"] = Variant("attack") message["target"] = Variant("enemy_01") message["power"] = Variant(10.0) app.emitMessage(message) ``` -------------------------------- ### Handle Startup Failures Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/QUICK_REFERENCE.md Demonstrates how to specifically handle different types of startup failures using an event handler. ```swift app.registerEventHandler { event in if case .startupFailure(let failure) = event { switch failure.reason { case .sourcePathMissing: showAlert("Pack file not found at: \(failure.sourcePath)") case .projectFileMissing: showAlert("project.godot not found") case .sceneMissing: showAlert("Scene not found: \(failure.scene ?? \"unknown\")") case .instanceCreationFailed: showAlert("Failed to initialize Godot") } } } ``` -------------------------------- ### SwiftUI Environment Integration Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotApp.md Example of how to access the GodotApp instance in SwiftUI views. ```swift public extension EnvironmentValues { @Entry var godotApp: GodotApp? = nil } struct ContentView: View { @State var app = GodotApp(packFile: "game.pck") var body: some View { VStack { GodotAppView() .environment(\.godotApp, app) } } } ``` -------------------------------- ### Compiling libgodot (Legacy) Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/README.md Instructions for compiling libgodot for older setups, producing a shared library. ```bash cd libgodot scons target=template_debug dev_build=yes library_type=shared_library debug_symbols=yes ``` -------------------------------- ### UI Integration (GodotAppView) Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/README.md Example of integrating GodotAppView into a SwiftUI environment. ```swift GodotAppView( onReady: { handle in ... }, onMessage: { msg in ... } ) .environment(\.godotApp, app) ``` -------------------------------- ### Pause Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotAppViewHandle.md Pauses the Godot instance. The view will stop rendering and updating. ```swift handle.pause() ``` -------------------------------- ### Handle Events Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/OVERVIEW.md Example of registering an event handler to process various events from the Godot app, such as startup failures and warnings. ```swift app.registerEventHandler { event in switch event { case .startupFailure(let failure): print("Error: \(failure.reason)") case .warning(let warning): print("Warning: \(warning.detail)") default: break } } ``` -------------------------------- ### Event Handling for Window Binding Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotWindow.md Example of registering an event handler to receive window binding events. ```swift let token = app.registerEventHandler { if case .windowBinding(let bindingEvent) = event { switch bindingEvent.state { case .bound: print("Window bound: \(bindingEvent.nodeName ?? "new")") case .missingNamedWindow: print("Window not found: \(bindingEvent.nodeName ?? "unknown")") case .nativeSurfaceUnsupported: print("Window does not support native surface rendering") case .detached: print("Window detached") case .rebound: print("Window rebound") } } } ``` -------------------------------- ### Initialize with Custom Settings Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/QUICK_REFERENCE.md Shows how to initialize GodotApp with custom settings like rendering driver and extra arguments. ```swift let app = GodotApp( packFile: "game.pck", godotPackPath: Bundle.main.bundlePath, renderingDriver: "metal", renderingMethod: "mobile", displayDriver: "embedded", extraArgs: ["--verbose"] ) ``` -------------------------------- ### stopDrawing() Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotApp.md Example of disabling rendering. ```swift app.stopDrawing() ``` -------------------------------- ### Monitor Startup Failures Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/QUICK_REFERENCE.md Demonstrates how to enable event monitoring to catch `.startupFailure` events, which helps in diagnosing crashes that occur during `app.start()`. ```swift app.registerEventHandler { event in if case .startupFailure = event { print("Startup failed; check paths and configuration") } } app.start() ``` -------------------------------- ### Access the Scene Root Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/QUICK_REFERENCE.md Shows how to get the root node of the loaded Godot scene using the handle provided in the onReady callback. ```swift GodotAppView( onReady: { handle in if let root = handle.getRoot() { // Access root node print("Root node type: \(type(of: root))") } } ) ``` -------------------------------- ### Communicate with Godot (GDScript) Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/OVERVIEW.md Example of receiving messages in GDScript from Swift and sending messages back to Swift. ```gdscript func _ready(): var bridge = get_tree().root.find_child("__swiftgodotkit_bridge__") bridge.messageFromHost.connect(_on_host_message) func _on_host_message(message: Dictionary): if message["action"] == "jump": perform_jump(message["power"]) func send_to_host(data: Dictionary): bridge.emitMessageToHost(data) ``` -------------------------------- ### With Extra Arguments Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/configuration.md Initializes GodotApp and passes additional command-line arguments to the Godot engine. ```swift let app = GodotApp( packFile: "game.pck", extraArgs: [ "--debug-gdscript", "--verbose", "-l", "en_US" ] ) ``` -------------------------------- ### Minimal (macOS) Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/configuration.md Initializes GodotApp with a minimal configuration, loading 'game.pck' from the app's resources. ```swift let app = GodotApp(packFile: "game.pck") ``` -------------------------------- ### Check if View is Ready Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/QUICK_REFERENCE.md Demonstrates how to check if the Godot scene view is ready using the handle. ```swift GodotAppView( onReady: { handle in if handle.isReady() { print("Scene is loaded and ready") } } ) ``` -------------------------------- ### Retry Mechanism Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/QUICK_REFERENCE.md Implements a retry mechanism for starting the Godot app, attempting to start it multiple times with a delay if it fails. ```swift func startGameWithRetry(maxAttempts: Int = 3) { var attempts = 0 let tryStart = { attempts += 1 if !app.start() && attempts < maxAttempts { DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { tryStart() } } } tryStart() } ``` -------------------------------- ### Warning: skippedSceneValidationUri Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/errors.md Example showing a scene configured with a custom URI scheme that triggers a skippedSceneValidationUri warning. ```swift app.configureLaunch(scene: "godot://custom/scene.tscn") // Emits warning(.skippedSceneValidationUri) ``` -------------------------------- ### Display Subwindows Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/QUICK_REFERENCE.md Shows how to display Godot subwindows or overlay UI elements on top of the main game view using GodotWindow. ```swift struct WindowedUI: View { @State var app = GodotApp(packFile: "game.pck") var body: some View { ZStack { // Main game GodotAppView() // Overlay windows VStack { HStack { GodotWindow(node: "PauseMenu") .frame(width: 300, height: 400) Spacer() } Spacer() } .padding() } .environment(\.godotApp, app) } } ``` -------------------------------- ### create(args:) Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotInstance.md Creates a new Godot instance with the given command-line arguments. ```swift public static func create(args: [String]) -> GodotInstance? ``` ```swift let args = [ "--main-pack", "/path/to/game.pck", "--rendering-driver", "metal", "--display-driver", "embedded" ] if let instance = GodotInstance.create(args: args) { print("Instance created") } else { print("Failed to create instance") } ``` -------------------------------- ### Warning: limitedSceneValidation Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/errors.md Example demonstrating how to detect and log a warning when scene validation is limited due to loading from a pack file. ```swift let app = GodotApp(packFile: "game.pck") app.configureLaunch(scene: "levels/main.tscn") // Relative scene app.registerEventHandler { event in if case .warning(let warning) = event, warning.code == .limitedSceneValidation { print("Can't validate scene path for PCK; Godot will handle it") } } app.start() ``` -------------------------------- ### Handle Scene Loading Delays Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/QUICK_REFERENCE.md Provides a solution for scenes that might not be fully ready immediately after `onReady`, suggesting a small delay before accessing the root node. ```swift GodotAppView( onReady: { handle in // Scene might not be fully ready yet DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { if let root = handle.getRoot() { // Now it's ready } } } ) ``` -------------------------------- ### Custom Path Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/configuration.md Initializes GodotApp, specifying a custom directory for the pack file. ```swift let app = GodotApp( packFile: "levels.pck", godotPackPath: "/Users/dev/games/my_game/exports" ) ``` -------------------------------- ### Packaging libgodot.xcframework Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/README.md Command to run the packaging script to create the libgodot.xcframework for macOS and iOS. ```bash cd SwiftGodotKit/scripts make # runs make-libgodot.xcframework ../SwiftGodot ../godot .. ``` -------------------------------- ### Typical usage Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotInstance.md Demonstrates the typical lifecycle of a GodotInstance. ```swift let instance = GodotInstance.create(args: [ "--main-pack", "game.pck", "--rendering-driver", "metal" ])? instance?.start() // In render loop: if instance?.isStarted() ?? false { instance?.iteration() } // On app termination: if let instance { GodotInstance.destroy(instance: instance) } ``` -------------------------------- ### GodotStartupFailureEvent Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/Events.md Emitted when the Godot instance fails to start. ```swift public struct GodotStartupFailureEvent { public enum Reason: String { case sourcePathMissing case projectFileMissing case sceneMissing case instanceCreationFailed } public let reason: Reason public let sourcePath: String public let scene: String? } ``` -------------------------------- ### Custom Rendering Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/configuration.md Initializes GodotApp with custom rendering driver and method settings. ```swift let app = GodotApp( packFile: "game.pck", renderingDriver: "vulkan", renderingMethod: "forward_plus" ) ``` -------------------------------- ### Stop Drawing Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotAppViewHandle.md Disables rendering without pausing game logic. ```swift handle.stopDrawing() ``` -------------------------------- ### NSGodotWindow initGodotWindow() method Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/PlatformViews.md Initializes the Godot window for macOS, similar to UIGodotWindow but specifically for the embedded display driver. ```swift func initGodotWindow() { } ``` -------------------------------- ### Creating a New Window Workflow Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/PlatformViews.md Describes the process of creating a new Godot window when no binding exists. ```text User creates GodotWindow(node: nil) ↓ initGodotWindow() checks: instance exists? started? ↓ No binding yet? Create new Window() ↓ Add to scene tree root ↓ Set native surface ↓ Emit GodotWindowBindingEvent(.bound) ↓ Call user callback with window ``` -------------------------------- ### Initialization Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotAppView.md Creates a view that renders a Godot scene. ```swift public init( source: String? = nil, scene: String? = nil, onReady: ((GodotAppViewHandle) -> Void)? = nil, onMessage: ((VariantDictionary) -> Void)? = nil ) ``` -------------------------------- ### Pause from View Handle Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/QUICK_REFERENCE.md Shows how to pause and resume the Godot app's logic and rendering using the view handle. ```swift GodotAppView( onReady: { handle in // Pause handle.pause() // Resume handle.resume() } ) ``` -------------------------------- ### GDScript Usage for Sending Messages to Host Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/HostBridge.md Example of how to send a message from GDScript to the host using the bridge. ```gdscript func send_message_to_host(action: String): var bridge = get_tree().root.find_child("__swiftgodotkit_bridge__", true, false) if bridge: bridge.emitMessageToHost({"action": action}) ``` -------------------------------- ### GDScript Usage for Receiving Host Messages Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/HostBridge.md Example of how to connect to and receive messages from the host bridge in GDScript. ```gdscript extends Node func _ready(): var bridge = get_tree().root.find_child("__swiftgodotkit_bridge__", true, false) if bridge: bridge.messageFromHost.connect(_on_message_from_host) func _on_message_from_host(message: Dictionary): if message.has("action"): print("Host action: ", message["action"]) ``` -------------------------------- ### Scene to Specific View Message Routing Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/HostBridge.md Example of sending a message from the scene to the host, which can be routed to a specific view. ```swift // Scene to specific view (automatic if previously sent from that view) bridge.emitMessageToHost({ "response": "pong", "__swiftgodotkit_view_id": 1 }) ``` -------------------------------- ### Cloning Repositories for SwiftGodotKit Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/README.md Instructions for cloning the necessary repositories (SwiftGodot, SwiftGodotKit, and godot engine) with specific branches for API compatibility. ```bash git clone git@github.com:migueldeicaza/SwiftGodot -b swiftgodotkit # provides the Swift API surface git clone git@github.com/migueldeicaza/SwiftGodotKit # this package git clone git@github.com/migueldeicaza/godot -b swiftgodotkit-4.6 # libgodot-enabled engine sources ``` -------------------------------- ### GodotStartupFailureEvent Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/types.md Describes a Godot startup failure. ```swift public struct GodotStartupFailureEvent { public enum Reason: String { case sourcePathMissing case projectFileMissing case sceneMissing case instanceCreationFailed } public let reason: Reason public let sourcePath: String public let scene: String? public init(reason: Reason, sourcePath: String, scene: String? = nil) } ``` -------------------------------- ### Host to Specific View Message Routing Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/HostBridge.md Example of sending a message from the host to a specific view using its view ID. ```swift // Host to specific view var message = VariantDictionary() message["type"] = Variant("player_update") app.emitMessage(message, from: viewHandle.viewId) ``` -------------------------------- ### Event Handling Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/README.md Example of registering an event handler in SwiftGodotKit to process various event types. ```swift app.registerEventHandler { event in switch event { case .startupFailure(let failure): ... case .warning(let warning): ... case .bridge(let bridge): ... // ... } } ``` -------------------------------- ### Load Different Packs Based on Device Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/QUICK_REFERENCE.md Dynamically selects the Godot game pack file based on the detected device model (e.g., iPhone vs. iPad) for optimized loading. ```swift let packFile = if UIDevice.current.model.contains("iPad") { "game_ipad.pck" } else { "game_iphone.pck" } let app = GodotApp(packFile: packFile) ``` -------------------------------- ### windowNativeSurfaceUnsupported Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/errors.md Illustrates a scenario where a GodotWindow node lacks the set_native_surface method, triggering the windowNativeSurfaceUnsupported warning. ```swift GodotWindow(node: "MyWindow") // Window in Godot lacks set_native_surface // Emits warning(.windowNativeSurfaceUnsupported) ``` -------------------------------- ### Emit Message Example Source: https://github.com/migueldeicaza/swiftgodotkit/blob/main/_autodocs/api-reference/GodotAppViewHandle.md Sends a message from this view to the Godot scene. The message is automatically tagged with this view's ID for routing. ```swift var msg = VariantDictionary() msg["type"] = Variant("player_action") msg["button"] = Variant("attack") handle.emitMessage(msg) ```