From e6a88d0d932119bbdcb55023547520adf8cdd490 Mon Sep 17 00:00:00 2001 From: Untold Engine Date: Thu, 3 Dec 2026 11:39:13 -0700 Subject: [PATCH] [Patch] Wire gizmo rotate mode into the ray-based drag pipeline beginGizmoDrag/updateGizmoDrag discarded .rotate handles immediately, so the documented generic drag lifecycle never actually turned an entity. Rotate now derives its angle from a ray/rotation-plane intersection and feeds it through the existing snapping accumulator and applyGizmoRotation, matching translate/scale. Fixes #1435 --- .../InteractionGameplayDemo/GameScene.swift | 23 +++- .../UntoldEngine/Systems/GizmoSystem.swift | 114 +++++++++++++++++- .../UntoldEngineTests/GizmoSystemTests.swift | 31 +++++ docs/API/UsingGizmoSystem.md | 2 + 4 files changed, 165 insertions(+), 5 deletions(-) diff --git a/Sources/Demos/InteractionGameplayDemo/GameScene.swift b/Sources/Demos/InteractionGameplayDemo/GameScene.swift index 40a99d30a..8904fc913 100644 --- a/Sources/Demos/InteractionGameplayDemo/GameScene.swift +++ b/Sources/Demos/InteractionGameplayDemo/GameScene.swift @@ -42,6 +42,8 @@ private var wasLeftMousePressed = false private var isDraggingGizmo = false private var wasSpacePressed = false + private var wasTabPressed = false + private var gizmoMode: GizmoMode = .translate init() { configureDemoEngine(assetBasePath: demoResourcesURL(), registerKeyboard: true, registerMouse: true) @@ -111,6 +113,15 @@ if gameMode == false { applyPendingGizmoDragUpdate() handleGizmoInput() + + // Tab cycles the gizmo tool (translate -> rotate -> scale) while an + // entity is selected, so rotate/scale are reachable from the keyboard. + if input.tabPressed, !wasTabPressed, activeEntity != .invalid { + gizmoMode = nextGizmoMode(after: gizmoMode) + createGizmo(mode: gizmoMode) + } + wasTabPressed = input.tabPressed + return } @@ -158,13 +169,23 @@ if let hit = pickEntity(rayOrigin: ray.origin, rayDirection: ray.direction, options: ScenePickOptions()) { activeEntity = hit.entityId - createGizmo(mode: .translate) + gizmoMode = .translate + createGizmo(mode: gizmoMode) } else { activeEntity = .invalid removeGizmo() } } + /// Translate -> rotate -> scale -> translate, for the Tab-key tool cycle. + private func nextGizmoMode(after mode: GizmoMode) -> GizmoMode { + switch mode { + case .translate: return .rotate + case .rotate: return .scale + case .scale: return .translate + } + } + /// 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)? { diff --git a/Sources/UntoldEngine/Systems/GizmoSystem.swift b/Sources/UntoldEngine/Systems/GizmoSystem.swift index 9ad19ec3b..303b8ab80 100644 --- a/Sources/UntoldEngine/Systems/GizmoSystem.swift +++ b/Sources/UntoldEngine/Systems/GizmoSystem.swift @@ -75,10 +75,20 @@ private struct GizmoDragState { /// the entity. let usesHandleOverride: Bool var appliedAxisAmount: Float = 0.0 + /// For `.rotate`: where the ray met the rotation plane when the drag began, + /// as a direction from the gizmo's center. Angles are measured from this. + var rotationStartDirection: simd_float3? + /// For `.rotate`: the raw (unsnapped) turn applied so far, so each frame + /// only feeds its own increment into the snapping accumulator. + var appliedRotationDegrees: Float = 0.0 var isAxisDriven: Bool { mode == .translate || mode == .scale } + + var isRotationDriven: Bool { + mode == .rotate + } } /// A rotation drag in progress: the whole turn so far, and the part of it @@ -209,9 +219,33 @@ public func beginGizmoDrag(ray: GizmoDragRay) { } let axisDirection = gizmoAxisDirection(for: handleComponent.axis, entityId: activeEntity, space: gizmoTransformSpace) + let normalizedRayDirection = normalizeOrNil(ray.direction) ?? ray.direction + if handleComponent.mode == .rotate { beginGizmoRotationDrag() + guard let referenceDirection = gizmoRotationPlaneDirection( + axis: axisDirection, + planePoint: gizmoRootWorldPosition(), + rayOrigin: ray.origin, + rayDirection: normalizedRayDirection + ) else { + gizmoDragState = nil + return + } + + gizmoDragState = GizmoDragState( + mode: .rotate, + axis: handleComponent.axis, + axisWorldDirection: axisDirection, + startAxisParameter: 0, + targets: gizmoTransformTargets().map(GizmoTargetStart.init(entityId:)), + startGizmoWorldPosition: gizmoRootWorldPosition(), + usesHandleOverride: false, + rotationStartDirection: referenceDirection + ) + return } + guard handleComponent.mode == .translate || handleComponent.mode == .scale, simd_length_squared(axisDirection) > 0.0001 else { @@ -219,7 +253,6 @@ public func beginGizmoDrag(ray: GizmoDragRay) { return } - let normalizedRayDirection = normalizeOrNil(ray.direction) ?? ray.direction guard let startParameter = closestParameterOnAxis( axisPoint: gizmoRootWorldPosition(), axisDirection: axisDirection, @@ -242,13 +275,46 @@ public func beginGizmoDrag(ray: GizmoDragRay) { } func updateGizmoDrag(ray: GizmoDragRay) { - guard var state = gizmoDragState, - state.isAxisDriven - else { + guard var state = gizmoDragState else { return } let normalizedRayDirection = normalizeOrNil(ray.direction) ?? ray.direction + + if state.isRotationDriven { + guard let startDirection = state.rotationStartDirection, + let currentDirection = gizmoRotationPlaneDirection( + axis: state.axisWorldDirection, + planePoint: state.startGizmoWorldPosition, + rayOrigin: ray.origin, + rayDirection: normalizedRayDirection + ) + else { + return + } + + // The ray reports the total turn since the drag began; only this + // frame's slice of it feeds the snapping accumulator. + let totalDegrees = signedAngleDegrees(from: startDirection, to: currentDirection, axis: state.axisWorldDirection) + let incrementalDegrees = totalDegrees - state.appliedRotationDegrees + guard incrementalDegrees.isFinite else { + return + } + + let snappedDelta = snappedGizmoRotationDelta(degrees: incrementalDegrees) + if snappedDelta != 0 { + applyGizmoRotation(axis: state.axisWorldDirection, degrees: snappedDelta) + } + + state.appliedRotationDegrees = totalDegrees + gizmoDragState = state + return + } + + guard state.isAxisDriven else { + return + } + guard let currentParameter = closestParameterOnAxis( axisPoint: state.startGizmoWorldPosition, axisDirection: state.axisWorldDirection, @@ -537,6 +603,46 @@ private func closestParameterOnAxis( return parameter.isFinite ? parameter : nil } +/// Where a ray meets the plane through `planePoint` perpendicular to `axis`, +/// as a unit direction from `planePoint` — the point on a rotation ring a +/// drag ray is pointing at. +private func gizmoRotationPlaneDirection( + axis: simd_float3, + planePoint: simd_float3, + rayOrigin: simd_float3, + rayDirection: simd_float3 +) -> simd_float3? { + guard let normal = normalizeOrNil(axis), let direction = normalizeOrNil(rayDirection) else { + return nil + } + + let denominator = simd_dot(normal, direction) + guard abs(denominator) > 0.0001 else { + return nil + } + + let distance = simd_dot(normal, planePoint - rayOrigin) / denominator + guard distance.isFinite else { + return nil + } + + let intersection = rayOrigin + direction * distance + return normalizeOrNil(intersection - planePoint) +} + +/// The signed turn in degrees from `from` to `to`, both already in the plane +/// perpendicular to `axis`: positive turns right-handed about `axis`. +private func signedAngleDegrees(from: simd_float3, to: simd_float3, axis: simd_float3) -> Float { + guard let normalizedAxis = normalizeOrNil(axis) else { + return 0 + } + + let dotValue = simd_dot(from, to) + let crossValue = simd_cross(from, to) + let angleRadians = atan2(simd_dot(crossValue, normalizedAxis), dotValue) + return angleRadians.isFinite ? radiansToDegrees(radians: angleRadians) : 0 +} + private func applyGizmoHandleColor(entityId: EntityID, color: simd_float4) { guard let renderComponent = scene.get(component: RenderComponent.self, for: entityId) else { return diff --git a/Tests/UntoldEngineTests/GizmoSystemTests.swift b/Tests/UntoldEngineTests/GizmoSystemTests.swift index 1ee750c1b..bfb6dbbc8 100644 --- a/Tests/UntoldEngineTests/GizmoSystemTests.swift +++ b/Tests/UntoldEngineTests/GizmoSystemTests.swift @@ -555,6 +555,37 @@ final class GizmoSystemTests: XCTestCase { XCTAssertEqual(getPosition(entityId: parentEntityIdGizmo), SIMD3(2, 0, 0)) } + /// Regression test: `beginGizmoDrag`/`updateGizmoDrag` used to discard `.rotate` + /// drags entirely (the ray→angle path was never wired in), so a rotate handle + /// never turned the entity even though the documented drag lifecycle implies it + /// works uniformly across translate/rotate/scale. + func test_axisGizmoDrag_rotatesFromCurrentRayConstraint() { + let active = makeEntity(name: "RotatedBox", pos: .zero) + activeEntity = active + createGizmo(mode: .rotate) + + let yHandle = findGizmoHandle(mode: .rotate, axis: .y) + guard yHandle != .invalid else { + XCTFail("Expected y-axis rotate handle.") + return + } + + activeHitGizmoEntity = yHandle + // A ray through (1, 0, 0) on the rotation plane... + beginGizmoDrag( + ray: GizmoDragRay(origin: SIMD3(1, 5, 0), direction: SIMD3(0, -1, 0)) + ) + // ...dragged to a ray through (0, 0, 1): a quarter turn about Y. + updateGizmoDrag( + ray: GizmoDragRay(origin: SIMD3(0, 5, 1), direction: SIMD3(0, -1, 0)) + ) + + let expected = simd_quatf(angle: -Float.pi / 2, axis: SIMD3(0, 1, 0)) + let actual = getRotationQuaternion(entityId: active) + XCTAssertEqual(actual.real, expected.real, accuracy: 0.001) + assertNearlyEqual(actual.imag, expected.imag, accuracy: 0.001) + } + func test_axisGizmoDrag_translationTracksAbsoluteAxisPositionForAllAxes() { let axes: [TransformAxis] = [.x, .y, .z] diff --git a/docs/API/UsingGizmoSystem.md b/docs/API/UsingGizmoSystem.md index 5b3c17ec5..47d832bfb 100644 --- a/docs/API/UsingGizmoSystem.md +++ b/docs/API/UsingGizmoSystem.md @@ -92,6 +92,8 @@ endGizmoDrag() `queueGizmoDragUpdate`/`applyPendingGizmoDragUpdate` exist so a high-frequency input callback (mouse move, touch move) doesn't have to directly mutate transforms off the simulation's update cadence — queue the latest ray, and let the engine apply it once per frame. +This same ray-based lifecycle drives `.rotate` too: each ray is intersected with the rotation ring's plane, and the angle swept since `beginGizmoDrag` turns the entity about that handle's axis. You don't need a different calling convention for rotate handles — the same `beginGizmoDrag`/`queueGizmoDragUpdate`/`applyPendingGizmoDragUpdate`/`endGizmoDrag` sequence works for translate, rotate, and scale alike. + If more than one entity is selected, populate `gizmoTargets` with all of them before calling `beginGizmoDrag`; the gizmo then moves/rotates/scales every target together, anchored at their combined bounds. With a single selection, just set `activeEntity` as shown above. **Call `applyPendingGizmoDragUpdate()` from your input-polling callback, not your gameplay-update callback.** If your app has a `setupCallbacks(gameUpdate:handleInput:)`-style split (as the demos do), be aware that the engine only invokes `gameUpdate` while `gameMode == true` — it is skipped entirely while paused/editing. `handleInput`, by contrast, runs every frame regardless of `gameMode`. Since a gizmo is typically only active while `gameMode == false` (see below), putting `applyPendingGizmoDragUpdate()` inside `gameUpdate` means it silently never runs during a drag. Call it from `handleInput` (or wherever your per-frame polling happens unconditionally) instead.