Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Sources/Demos/InteractionGameplayDemo/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,13 @@
}

self.renderer = renderer

// Extensions that create pipelines must be registered after the
// renderer has initialized Metal and loaded the engine shader
// library (matches the Untold Editor's own call-site timing for
// its render extensions).
registerGizmoRenderExtension()

gameScene = GameScene()

renderer.setupCallbacks(
Expand Down Expand Up @@ -96,6 +103,9 @@
Text("WASD moves the player")
.font(.caption)
.foregroundStyle(.secondary)
Text("Space toggles edit mode: click an object to select it, drag its gizmo to move it")
.font(.caption)
.foregroundStyle(.secondary)
}
.padding(12)
.background(.regularMaterial, in: RoundedRectangle(cornerRadius: 8))
Expand Down
135 changes: 132 additions & 3 deletions Sources/Demos/InteractionGameplayDemo/GameScene.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
//

#if os(macOS)
import AppKit
import DemoUtils
import Foundation
import simd
Expand All @@ -37,16 +38,25 @@
private var currentAnimation = "idle"
private var ballAttached = false

// Gizmo click-to-select / drag state.
private var wasLeftMousePressed = false
private var isDraggingGizmo = false
private var wasSpacePressed = false

init() {
configureDemoEngine(assetBasePath: demoResourcesURL(), registerKeyboard: true, registerMouse: false)
configureDemoEngine(assetBasePath: demoResourcesURL(), registerKeyboard: true, registerMouse: true)
makeDemoCamera(name: "Gameplay Camera", eye: Constants.cameraEye, target: Constants.cameraTarget)
makeDemoSunLight(name: "Sun", pitch: -55.0, color: simd_float3(1.0, 0.94, 0.86), intensity: 1.6)
loadScene()
setSceneReady(true)
}

func update(deltaTime: Float) {
if gameMode == false { return }
// The engine only invokes this callback while gameMode == true (see
// UntoldEngine.swift's render loop); gizmo drag-flushing happens in
// handleInput() instead, which runs unconditionally every frame.
if isSceneReady() == false { return }

guard let redPlayer else { return }

if startMoving {
Expand Down Expand Up @@ -77,13 +87,132 @@
}

func handleInput() {
if gameMode == false { return }
if isSceneReady() == false { return }

let input = InputSystem.shared.keyState
defer { wasSpacePressed = input.spacePressed }

// Space toggles between gameplay (WASD movement) and edit mode (gizmo).
if input.spacePressed, !wasSpacePressed {
gameMode.toggle()

// Entering play mode: a gizmo created while editing must not keep
// drawing (or being draggable) through gameplay.
if gameMode {
activeEntity = .invalid
removeGizmo()
isDraggingGizmo = false
}
}

// Edit mode: the engine never calls update(deltaTime:) while gameMode == false,
// so the gizmo's queued drag update must be flushed here instead, where
// (unlike gameUpdate) this callback keeps running regardless of gameMode.
if gameMode == false {
applyPendingGizmoDragUpdate()
handleGizmoInput()
return
}

startMoving = input.wPressed || input.aPressed || input.sPressed || input.dPressed
}

// MARK: - Gizmo click-to-select / drag

/// Polls the mouse button state each frame (this demo has no NSEvent-based
/// mouse handling of its own) and drives the gizmo select/drag lifecycle from
/// the press/drag/release edges.
private func handleGizmoInput() {
guard let camera = CameraSystem.shared.activeCamera else { return }

let isPressed = InputSystem.shared.keyState.leftMousePressed
defer { wasLeftMousePressed = isPressed }

if isPressed, !wasLeftMousePressed {
gizmoMouseDown(cameraEntityId: camera)
} else if isPressed, isDraggingGizmo {
if let ray = currentMouseRay(cameraEntityId: camera) {
queueGizmoDragUpdate(ray: GizmoDragRay(origin: ray.origin, direction: ray.direction))
}
} else if !isPressed, wasLeftMousePressed, isDraggingGizmo {
endGizmoDrag()
isDraggingGizmo = false
}
}

private func gizmoMouseDown(cameraEntityId: EntityID) {
guard let ray = currentMouseRay(cameraEntityId: cameraEntityId) else { return }
let dragRay = GizmoDragRay(origin: ray.origin, direction: ray.direction)

// Prefer an existing gizmo handle over re-selecting a scene entity.
if let gizmoHit = pickEntity(
rayOrigin: ray.origin,
rayDirection: ray.direction,
options: ScenePickOptions(gizmoOnly: true)
), hitGizmoToolAxis(entityId: gizmoHit.entityId) {
processGizmoAction(entityId: gizmoHit.entityId)
beginGizmoDrag(ray: dragRay)
isDraggingGizmo = true
return
}

if let hit = pickEntity(rayOrigin: ray.origin, rayDirection: ray.direction, options: ScenePickOptions()) {
activeEntity = hit.entityId
createGizmo(mode: .translate)
} else {
activeEntity = .invalid
removeGizmo()
}
}

/// Builds a world-space ray from the current mouse position using only
/// public engine API (no private renderer/camera internals).
private func currentMouseRay(cameraEntityId: EntityID) -> (origin: simd_float3, direction: simd_float3)? {
// `update`/`handleInput` are always invoked from the renderer's main-thread
// callbacks (see CLAUDE.md: the simulation thread is the main thread on
// macOS/iOS), so this call is safe even though GameScene itself isn't
// statically @MainActor-isolated.
let windowSize: CGSize? = MainActor.assumeIsolated {
NSApp.keyWindow?.contentView?.bounds.size
}
guard let viewSize = windowSize, viewSize.width > 0, viewSize.height > 0 else { return nil }

let viewport = renderInfo.viewPort ?? simd_float2(Float(viewSize.width), Float(viewSize.height))
let scale = simd_float2(viewport.x / Float(viewSize.width), viewport.y / Float(viewSize.height))

let input = InputSystem.shared
let mouseLocation = simd_float2(input.mouseX, input.mouseY) * scale

let rayDirection = rayDirectionInWorldSpace(
uMouseLocation: mouseLocation,
uViewPortDim: viewport,
uPerspectiveSpace: renderInfo.perspectiveSpace,
uViewSpace: cameraViewMatrix(entityId: cameraEntityId)
)

return (getPosition(entityId: cameraEntityId), rayDirection)
}

/// Reconstructs the camera's view matrix from public transform accessors,
/// mirroring `updateCameraViewMatrix`'s internal construction exactly.
private func cameraViewMatrix(entityId: EntityID) -> simd_float4x4 {
var view = getMatrix4x4FromQuaternion(q: getRotationQuaternion(entityId: entityId))

let xAxis = getRightAxisVector(entityId: entityId)
let yAxis = getUpAxisVector(entityId: entityId)
let zAxis = getForwardAxisVector(entityId: entityId)
let position = getPosition(entityId: entityId)

view.columns.3 = simd_float4(
-simd_dot(xAxis, position),
-simd_dot(yAxis, position),
-simd_dot(zAxis, position),
1.0
)

return view
}

private func loadScene() {
loadStadium { [weak self] entity, success in
self?.stadium = entity
Expand Down
16 changes: 16 additions & 0 deletions Sources/UntoldEngine/ECS/Components.swift
Original file line number Diff line number Diff line change
Expand Up @@ -826,6 +826,22 @@ public class GizmoComponent: Component {
public required init() {}
}

public class GizmoHandleComponent: Component {
public var mode: TransformManipulationMode = .none
public var axis: TransformAxis = .none

public required init() {}
}

public class GizmoHitProxyComponent: Component {
public required init() {}
}

/// Marks the dot at the gizmo's centre, which is drawn and never picked.
public class GizmoCenterComponent: Component {
public required init() {}
}

// MARK: - Asset Instance Components

/// Attached to the root entity of an imported USDZ asset instance.
Expand Down
Loading
Loading