diff --git a/Sources/Demos/InteractionGameplayDemo/AppDelegate.swift b/Sources/Demos/InteractionGameplayDemo/AppDelegate.swift index 71d12813e..b5fba1786 100644 --- a/Sources/Demos/InteractionGameplayDemo/AppDelegate.swift +++ b/Sources/Demos/InteractionGameplayDemo/AppDelegate.swift @@ -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( @@ -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)) diff --git a/Sources/Demos/InteractionGameplayDemo/GameScene.swift b/Sources/Demos/InteractionGameplayDemo/GameScene.swift index 55586ba9f..40a99d30a 100644 --- a/Sources/Demos/InteractionGameplayDemo/GameScene.swift +++ b/Sources/Demos/InteractionGameplayDemo/GameScene.swift @@ -14,6 +14,7 @@ // #if os(macOS) + import AppKit import DemoUtils import Foundation import simd @@ -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 { @@ -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 diff --git a/Sources/UntoldEngine/ECS/Components.swift b/Sources/UntoldEngine/ECS/Components.swift index 6d855c0ec..df6189285 100644 --- a/Sources/UntoldEngine/ECS/Components.swift +++ b/Sources/UntoldEngine/ECS/Components.swift @@ -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. diff --git a/Sources/UntoldEngine/Renderer/GizmoRenderPass.swift b/Sources/UntoldEngine/Renderer/GizmoRenderPass.swift new file mode 100644 index 000000000..110ebe4ce --- /dev/null +++ b/Sources/UntoldEngine/Renderer/GizmoRenderPass.swift @@ -0,0 +1,328 @@ +// +// GizmoRenderPass.swift +// UntoldEngine +// +// Copyright (C) Untold Engine Studios +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// +// Rendering for the gizmo system (Systems/GizmoSystem.swift, GizmoGroup.swift, +// GizmoPalette.swift). The gizmo's drag/pick logic lives there; this file is the +// GPU side: a dedicated unlit pipeline and a render pass drawn into its own, +// every-frame-cleared depth buffer (renderInfo.gizmoRenderPassDescriptor) so the +// gizmo is never occluded by scene geometry. It is opt-in — register +// `GizmoRenderExtension` (via `registerGizmoRenderExtension()`) to enable it; apps +// that don't call it pay nothing and draw nothing into the gizmo layer. + +import CShaderTypes +import Metal +import MetalKit + +// MARK: Gizmo Vertex Descriptor + +func createGizmoVertexDescriptor() -> MTLVertexDescriptor? { + // tell the gpu how data is organized + vertexDescriptor.gizmo = MDLVertexDescriptor() + + vertexDescriptor.gizmo.attributes[Int(modelPassVerticesIndex.rawValue)] = MDLVertexAttribute( + name: MDLVertexAttributePosition, + format: .float4, + offset: 0, + bufferIndex: Int(modelPassVerticesIndex.rawValue) + ) + + vertexDescriptor.gizmo.layouts[Int(modelPassVerticesIndex.rawValue)] = MDLVertexBufferLayout( + stride: MemoryLayout.stride + ) + + guard let vertexDescriptor = MTKMetalVertexDescriptorFromModelIO(vertexDescriptor.gizmo) else { + return nil + } + + return vertexDescriptor +} + +// MARK: Gizmo Pipeline + +func InitGizmoPipeline() -> RenderPipeline? { + CreatePipeline( + vertexShader: "vertexGizmoShader", + fragmentShader: "fragmentGizmoShader", + vertexDescriptor: createGizmoVertexDescriptor(), + colorFormats: [renderInfo.colorPixelFormat], + depthFormat: renderInfo.depthPixelFormat, + name: "Gizmo Pipeline" + ) +} + +public extension RenderPipelineType { + static let gizmo: RenderPipelineType = "gizmo" +} + +/// Registers the `.gizmo` pipeline with the given registry. +/// +/// Exposed on its own (not only through `GizmoRenderExtension.registerPipelines`) so +/// a host that already owns a `RenderExtension` registering its own gizmo render pass +/// (as the Untold Editor does, with its own selection/play-mode gating) can pull in +/// just the pipeline without also getting `GizmoRenderExtension`'s pass. +public func registerGizmoPipeline(_ registry: RenderPipelineRegistry) { + registry.registerRenderPipeline(.gizmo, initBlock: InitGizmoPipeline) +} + +// MARK: Gizmo Pass Execution + +public extension RenderPasses { + /// Draws every entity tagged `GizmoComponent` (skipping hit-proxy-only handles) + /// into the dedicated gizmo render target with its own cleared depth buffer, so + /// the gizmo is never occluded by scene geometry. No-op if no gizmo is active. + static let gizmoExecution: RenderPassExecution = { commandBuffer in + if activeEntity == .invalid { + return + } + + guard let gizmoPipeline = PipelineManager.shared.renderPipelinesByType[.gizmo] else { + handleError(.pipelineStateNulled, "gizmoPipeline is nil") + return + } + + if gizmoPipeline.success == false { + handleError(.pipelineStateNulled, gizmoPipeline.name!) + return + } + guard let camera = CameraSystem.shared.activeCamera, let cameraComponent = scene.get(component: CameraComponent.self, for: camera) else { + handleError(.noActiveCamera) + return + } + // The pass below fully redraws every gizmo handle from scratch each time it + // runs, so the color attachment must be cleared first — loading the previous + // frame's content here would leave every prior frame's gizmo pixels on + // screen, smearing a trail across the drag instead of showing only the + // current position. + renderInfo.gizmoRenderPassDescriptor.colorAttachments[Int(colorTarget.rawValue)] + .loadAction = .clear + + renderInfo.gizmoRenderPassDescriptor.depthAttachment.loadAction = .clear + + let encoderDescriptor = renderInfo.gizmoRenderPassDescriptor! + + guard let renderEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: encoderDescriptor) + else { + handleError(.renderPassCreationFailed, "Gizmo Pass") + return + } + + defer { + // Make sure no matter what we end the encoding at the end of the function + renderEncoder.popDebugGroup() + renderEncoder.endEncoding() + } + + renderEncoder.label = "Gizmo Pass" + + renderEncoder.pushDebugGroup("Gizmo Pass") + + renderEncoder.setRenderPipelineState(gizmoPipeline.pipelineState!) + renderEncoder.setDepthStencilState(gizmoPipeline.depthState) + renderEncoder.setDepthBias(0.01, slopeScale: 1.0, clamp: 0.0) + renderEncoder.waitForFence(renderInfo.fence, before: .vertex) + + // Create a component query for entities with both Transform and Render components + + let transformId = getComponentId(for: WorldTransformComponent.self) + let renderId = getComponentId(for: RenderComponent.self) + let gizmoId = getComponentId(for: GizmoComponent.self) + + let entities = queryEntitiesWithComponentIds([transformId, renderId, gizmoId], in: scene) + + guard gizmoActive, parentEntityIdGizmo != .invalid else { + return + } + + guard scene.get(component: WorldTransformComponent.self, for: parentEntityIdGizmo) != nil, + scene.get(component: LocalTransformComponent.self, for: parentEntityIdGizmo) != nil + else { + return + } + + // Keep gizmo size approximately constant in screen space by scaling the root only. + // Child handles keep fixed local offsets, so cones/cubes stay attached to shafts. + updateGizmoScreenSpaceScale(cameraEntityId: camera) + + // Iterate over the entities found by the component query + for entityId in entities { + if hasComponent(entityId: entityId, componentType: GizmoHitProxyComponent.self) { + continue + } + + guard let renderComponent = scene.get(component: RenderComponent.self, for: entityId) else { + handleError(.noRenderComponent, entityId) + continue + } + + guard let worldTransformComponent = scene.get(component: WorldTransformComponent.self, for: entityId) else { + handleError(.noWorldTransformComponent, entityId) + continue + } + for mesh in renderComponent.mesh { + // update uniforms + var modelUniforms = Uniforms() + + var modelMatrix = simd_mul(worldTransformComponent.space, mesh.localSpace) + + let viewMatrix: simd_float4x4 = cameraComponent.viewSpace + + let modelViewMatrix = simd_mul(viewMatrix, modelMatrix) + + let upperModelMatrix: matrix_float3x3 = matrix3x3_upper_left(modelMatrix) + + let inverseUpperModelMatrix: matrix_float3x3 = upperModelMatrix.inverse + + let normalMatrix: matrix_float3x3 = inverseUpperModelMatrix.transpose + + modelUniforms.modelViewMatrix = modelViewMatrix + + modelUniforms.normalMatrix = normalMatrix + + modelUniforms.viewMatrix = viewMatrix + + modelUniforms.modelMatrix = modelMatrix + + modelUniforms.cameraPosition = cameraComponent.localPosition + + modelUniforms.projectionMatrix = renderInfo.perspectiveSpace + + renderEncoder.setVertexBytes( + &modelUniforms, length: MemoryLayout.stride, index: Int(modelPassUniformIndex.rawValue) + ) + + renderEncoder.setFragmentBytes( + &modelUniforms, length: MemoryLayout.stride, index: Int(modelPassUniformIndex.rawValue) + ) + + renderEncoder.setVertexBuffer( + mesh.metalKitMesh.vertexBuffers[Int(modelPassVerticesIndex.rawValue)].buffer, + offset: 0, index: Int(modelPassVerticesIndex.rawValue) + ) + + for subMesh in mesh.submeshes { + var materialParameters = MaterialParametersUniform() + materialParameters.specular = subMesh.material!.specular + materialParameters.specularTint = subMesh.material!.specularTint + materialParameters.subsurface = subMesh.material!.subsurface + materialParameters.anisotropic = subMesh.material!.anisotropic + materialParameters.sheen = subMesh.material!.sheen + materialParameters.sheenTint = subMesh.material!.sheenTint + materialParameters.clearCoat = subMesh.material!.clearCoat + materialParameters.clearCoatGloss = subMesh.material!.clearCoatGloss + materialParameters.baseColor = subMesh.material!.baseColorValue + materialParameters.roughness = subMesh.material!.roughnessValue + materialParameters.metallic = subMesh.material!.metallicValue + materialParameters.ior = subMesh.material!.ior + materialParameters.edgeTint = subMesh.material!.edgeTint + materialParameters.interactWithLight = subMesh.material!.interactWithLight + materialParameters.emmissive = subMesh.material!.emissiveValue + + renderEncoder.setFragmentBytes( + &materialParameters, length: MemoryLayout.stride, + index: Int(modelPassFragmentMaterialParameterIndex.rawValue) + ) + + renderEncoder.drawIndexedPrimitives( + type: subMesh.metalKitSubmesh.primitiveType, + indexCount: subMesh.metalKitSubmesh.indexCount, + indexType: subMesh.metalKitSubmesh.indexType, + indexBuffer: subMesh.metalKitSubmesh.indexBuffer.buffer, + indexBufferOffset: subMesh.metalKitSubmesh.indexBuffer.offset + ) + } + } + } + + renderEncoder.updateFence(renderInfo.fence, after: .fragment) + } + + /// Clears the gizmo render target without drawing anything into it. + /// + /// `gizmoExecution` leaves the texture untouched whenever there is nothing to + /// draw (no active entity, or the gizmo isn't active): it returns before ever + /// opening a render pass, so the GPU never gets a chance to clear the color + /// attachment. Since the pre-composite pass samples this same texture whenever + /// the engine isn't in game mode (`preCompShader.metal`, `fragmentPreCompositeShader`) + /// and overrides the pixel wherever it is lit, a gizmo that was visible and then + /// deselected would otherwise ghost on screen forever — the stale, previously + /// rendered pixels never get cleared. `GizmoRenderExtension` calls this whenever + /// no gizmo is active, closing that gap. + static let clearGizmoLayerExecution: RenderPassExecution = { commandBuffer in + renderInfo.gizmoRenderPassDescriptor.colorAttachments[Int(colorTarget.rawValue)] + .loadAction = .clear + + renderInfo.gizmoRenderPassDescriptor.depthAttachment.loadAction = .clear + + let encoderDescriptor = renderInfo.gizmoRenderPassDescriptor! + + guard let renderEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: encoderDescriptor) + else { + handleError(.renderPassCreationFailed, "Clear Gizmo Layer Pass") + return + } + + renderEncoder.label = "Clear Gizmo Layer Pass" + + renderEncoder.pushDebugGroup("Clear Gizmo Layer Pass") + + renderEncoder.waitForFence(renderInfo.fence, before: .vertex) + + renderEncoder.updateFence(renderInfo.fence, after: .fragment) + renderEncoder.popDebugGroup() + renderEncoder.endEncoding() + } +} + +// MARK: Gizmo Render Extension + +/// Opt-in `RenderExtension` that draws the gizmo (see `Systems/GizmoSystem.swift`) +/// through its own pipeline and render target, every frame, clearing the layer +/// whenever no gizmo is active so a deselected gizmo never ghosts on screen. +/// +/// Register once at startup with `registerGizmoRenderExtension()`. A host that +/// needs its own gating (for example an editor that only draws the gizmo outside +/// of play mode) should not register this extension — it would add a second, +/// differently-gated `"untold.gizmo"` pass alongside its own. Instead, call +/// `registerGizmoPipeline(_:)` directly from that host's own `registerPipelines(_:)` +/// to get just the `.gizmo` pipeline, and drive `RenderPasses.gizmoExecution`/ +/// `RenderPasses.clearGizmoLayerExecution` from the host's own pass. +public final class GizmoRenderExtension: RenderExtension, @unchecked Sendable { + public static let shared = GizmoRenderExtension() + + public let id = "untold.gizmo" + + private init() {} + + public func registerPipelines(_ registry: RenderPipelineRegistry) { + registerGizmoPipeline(registry) + } + + public func buildGraph( + _ builder: inout RenderGraphBuilder, + context _: RenderGraphBuildContext + ) { + builder.addPass(id: "untold.gizmo", stage: .beforeComposite) { context in + if gizmoActive, parentEntityIdGizmo != .invalid { + RenderPasses.gizmoExecution(context.commandBuffer) + } else { + RenderPasses.clearGizmoLayerExecution(context.commandBuffer) + } + } + } +} + +/// Registers `GizmoRenderExtension`, enabling the gizmo render pass. Call once at +/// startup, at the same point the app configures its renderer (the same timing +/// other `RenderExtension`s are registered at) and before the renderer finishes +/// initializing pipelines. +@discardableResult +public func registerGizmoRenderExtension() -> RenderExtensionRegistrationResult { + RenderExtensionRegistry.shared.register(GizmoRenderExtension.shared) +} diff --git a/Sources/UntoldEngine/Systems/GizmoGroup.swift b/Sources/UntoldEngine/Systems/GizmoGroup.swift new file mode 100644 index 000000000..4b32f3310 --- /dev/null +++ b/Sources/UntoldEngine/Systems/GizmoGroup.swift @@ -0,0 +1,283 @@ +// +// GizmoGroup.swift +// UntoldEngine +// +// Copyright (C) Untold Engine Studios +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// +import Foundation +import simd + +// With several entities selected one gizmo stands in the middle of them and +// works on all: a move carries each by the same distance, a turn takes them +// round the gizmo, and a scale grows them and their distance from it. + +/// Where an entity stood and how big it was when a drag began. A drag works +/// from there, so what it did so far never adds up with what it does next. +struct GizmoTargetStart { + let entityId: EntityID + let localPosition: simd_float3 + /// Where it stood in the world. A scale of several entities reads it, + /// and those all keep a world transform: see `hasBothTransforms`. + let worldPosition: simd_float3 + let scale: simd_float3 + + init(entityId: EntityID) { + self.entityId = entityId + localPosition = getLocalPosition(entityId: entityId) + worldPosition = getPosition(entityId: entityId) + scale = getScale(entityId: entityId) + } +} + +/// The box along the world's axes around what an entity and everything under +/// it draw: each one's own bounds, carried into the world by the transform the +/// renderer draws it with. Nil when nothing under the entity draws anything. +func worldBoundsOfRenderableHierarchy(entityId: EntityID) -> (min: simd_float3, max: simd_float3)? { + var minimum = simd_float3(repeating: .greatestFiniteMagnitude) + var maximum = simd_float3(repeating: -.greatestFiniteMagnitude) + var found = false + var pending = [entityId] + var visited = 0 + + // The depth of a scene is small; the count only guards against a cycle. + while let current = pending.popLast(), visited < 100_000 { + visited += 1 + pending.append(contentsOf: getEntityChildren(parentId: current)) + + guard hasComponent(entityId: current, componentType: RenderComponent.self) + || hasComponent(entityId: current, componentType: GaussianComponent.self), + let local = scene.get(component: LocalTransformComponent.self, for: current), + let world = scene.get(component: WorldTransformComponent.self, for: current) + else { + continue + } + + let box = local.boundingBox + for corner in 0 ..< 8 { + let point = simd_float4( + corner & 1 == 0 ? box.min.x : box.max.x, + corner & 2 == 0 ? box.min.y : box.max.y, + corner & 4 == 0 ? box.min.z : box.max.z, + 1 + ) + let moved = simd_mul(world.space, point) + let position = simd_float3(moved.x, moved.y, moved.z) + guard position.x.isFinite, position.y.isFinite, position.z.isFinite else { + continue + } + minimum = simd_min(minimum, position) + maximum = simd_max(maximum, position) + found = true + } + } + + return found ? (minimum, maximum) : nil +} + +/// Whether an entity keeps both of its transforms: its place under its +/// parent, which the gizmo writes, and its place in the world, which a turn +/// and a scale of several entities start from. The engine gives an entity the +/// two together and takes them away together, so one without the other is +/// not an entity the gizmo can work on. +public func hasBothTransforms(_ entityId: EntityID) -> Bool { + hasComponent(entityId: entityId, componentType: LocalTransformComponent.self) + && hasComponent(entityId: entityId, componentType: WorldTransformComponent.self) +} + +/// The entities a drag of the gizmo works on: the active one, or with several +/// selected every one of them that is still in the scene with both of its +/// transforms. +public func gizmoTransformTargets() -> [EntityID] { + guard activeEntity != .invalid else { + return [] + } + let several = gizmoTargets.filter(hasBothTransforms) + guard several.count > 1, several.contains(activeEntity) else { + return [activeEntity] + } + return several +} + +/// Where the gizmo stands for several entities: the middle of the box, along +/// the world's axes, around everything they draw. One that draws nothing +/// counts as the point where it stands. +func gizmoGroupAnchorWorldPosition(of targets: [EntityID]) -> simd_float3? { + var minimum = simd_float3(repeating: .greatestFiniteMagnitude) + var maximum = simd_float3(repeating: -.greatestFiniteMagnitude) + var found = false + + for target in targets { + if let box = worldBoundsOfRenderableHierarchy(entityId: target) { + minimum = simd_min(minimum, box.min) + maximum = simd_max(maximum, box.max) + found = true + } else if hasComponent(entityId: target, componentType: WorldTransformComponent.self) { + let position = getPosition(entityId: target) + minimum = simd_min(minimum, position) + maximum = simd_max(maximum, position) + found = true + } + } + return found ? (minimum + maximum) * 0.5 : nil +} + +/// Puts the gizmo back in the middle of the entities it moves, which a turn +/// or a scale may have shifted. With one entity the gizmo stays where it is. +func reanchorGizmoOnTargets() { + let targets = gizmoTransformTargets() + guard gizmoActive, parentEntityIdGizmo != .invalid, targets.count > 1, + let anchor = gizmoGroupAnchorWorldPosition(of: targets) + else { + return + } + translateTo(entityId: parentEntityIdGizmo, position: anchor) +} + +/// A point of the world as the entity's parent measures it, which is how the +/// entity's position is kept. +func localPosition(ofWorld position: simd_float3, for entityId: EntityID) -> simd_float3 { + guard let parent = parentInSceneGraph(of: entityId), + let parentSpace = scene.get(component: WorldTransformComponent.self, for: parent)?.space + else { + return position + } + + let determinant = simd_determinant(parentSpace) + guard determinant.isFinite, abs(determinant) > 1e-12 else { + // A parent squashed flat has no way back: the entity stays where it is. + return getLocalPosition(entityId: entityId) + } + let local = simd_mul(parentSpace.inverse, simd_float4(position, 1)) + return simd_float3(local.x, local.y, local.z) +} + +// MARK: - Moving + +/// Moves the targets of a drag to where they stood plus `translation`, a +/// movement in world space that each takes in its parent's measure. +func translateGizmoTargets(_ starts: [GizmoTargetStart], byWorld translation: simd_float3) { + for start in starts { + let local = localTranslation(ofWorld: translation, for: start.entityId) + translateTo(entityId: start.entityId, position: start.localPosition + local) + } +} + +/// Moves what the gizmo works on by `translation`, from where it is now. +public func applyGizmoTranslation(byWorld translation: simd_float3) { + for target in gizmoTransformTargets() { + translateBy(entityId: target, position: localTranslation(ofWorld: translation, for: target)) + } +} + +// MARK: - Turning + +/// Turns the targets together by `degrees` about `axis`, the world's, through +/// `pivot`: each goes round the pivot and turns by the same angle itself. +func rotateGizmoTargets(_ targets: [EntityID], around pivot: simd_float3, axis: simd_float3, degrees: Float) { + guard degrees.isFinite, degrees != 0, simd_length_squared(axis) > 0.0001 else { + return + } + let turn = simd_quatf(angle: degreesToRadians(degrees: degrees), axis: simd_normalize(axis)) + + // Where each one goes is taken before any of them moves. + let destinations = targets.map { pivot + simd_act(turn, getPosition(entityId: $0) - pivot) } + for (target, destination) in zip(targets, destinations) { + applyGizmoRotationDelta(entityId: target, axis: axis, degrees: degrees) + translateTo(entityId: target, position: localPosition(ofWorld: destination, for: target)) + } +} + +/// Turns what the gizmo works on: the active entity about itself, as ever, +/// or several entities round the gizmo. +public func applyGizmoRotation(axis: simd_float3, degrees: Float) { + let targets = gizmoTransformTargets() + guard targets.count > 1 else { + applyGizmoRotationDelta(entityId: activeEntity, axis: axis, degrees: degrees) + return + } + rotateGizmoTargets(targets, around: gizmoRootWorldPosition(), axis: axis, degrees: degrees) +} + +// MARK: - Scaling + +/// The smallest a scale may get, as the engine keeps it for one entity. +let gizmoMinimumScale: Float = 0.01 + +/// How much several entities grow for a drag of `amount` along the gizmo's +/// axis: a drag of one unit doubles them, and one back by half halves them. +func gizmoGroupScaleFactor(forAmount amount: Float) -> Float { + guard amount.isFinite else { + return 1 + } + return max(gizmoMinimumScale, 1 + amount) +} + +/// The scale of an entity grown by `factor` along `axis`, the world's. An +/// entity keeps its scale along its own axes, so each of them takes the +/// share of the growth that the world's axis has along it. +func gizmoScale(_ scale: simd_float3, of entityId: EntityID, grownBy factor: Float, along axis: simd_float3) -> simd_float3 { + guard let local = scene.get(component: LocalTransformComponent.self, for: entityId) else { + return scale + } + let axisForParent = localAxis(ofWorld: axis, for: entityId) + let toOwnSpace = simd_transpose(transformQuaternionToMatrix3x3(q: local.rotation)) + let own = simd_mul(toOwnSpace, axisForParent) + let length = simd_length(own) + guard length.isFinite, length > 0.0001 else { + return scale + } + + let share = simd_abs(own / length) + let grown = scale * (simd_float3(repeating: 1) + share * (factor - 1)) + return simd_max(grown, simd_float3(repeating: gizmoMinimumScale)) +} + +/// Scales the targets together by `factor` along `axis`, the world's, from +/// `pivot`: each grows along the axis, and so does its distance from the +/// pivot. A light keeps its size and only moves. +func scaleGizmoTargets(_ starts: [GizmoTargetStart], from pivot: simd_float3, axis: simd_float3, factor: Float) { + guard factor.isFinite, simd_length_squared(axis) > 0.0001 else { + return + } + let direction = simd_normalize(axis) + + for start in starts { + let offset = start.worldPosition - pivot + let destination = start.worldPosition + direction * ((factor - 1) * simd_dot(offset, direction)) + translateTo(entityId: start.entityId, position: localPosition(ofWorld: destination, for: start.entityId)) + + if hasComponent(entityId: start.entityId, componentType: LightComponent.self) == false { + scaleTo( + entityId: start.entityId, + scale: gizmoScale(start.scale, of: start.entityId, grownBy: factor, along: direction) + ) + } + } +} + +/// Scales what the gizmo works on by `amount` more along `axis`, the world +/// direction of the `handle` dragged: the active entity as ever, or several +/// entities from the gizmo. +public func applyGizmoScale(axis: simd_float3, amount: Float, handle: TransformAxis) { + let targets = gizmoTransformTargets() + guard targets.count > 1 else { + if hasComponent(entityId: activeEntity, componentType: LightComponent.self) { + // The engine takes the axis as which components of the scale to change. + handleLightScaleInput(projectedAmount: amount, axis: worldDirection(for: handle)) + } else { + // The engine takes the axis as the entity's parent sees it. + applyWorldSpaceScaleDelta(entityId: activeEntity, worldAxis: localAxis(ofWorld: axis, for: activeEntity), projectedAmount: amount) + } + return + } + scaleGizmoTargets( + targets.map(GizmoTargetStart.init(entityId:)), + from: gizmoRootWorldPosition(), + axis: axis, + factor: gizmoGroupScaleFactor(forAmount: amount) + ) +} diff --git a/Sources/UntoldEngine/Systems/GizmoPalette.swift b/Sources/UntoldEngine/Systems/GizmoPalette.swift new file mode 100644 index 000000000..e0edc2a49 --- /dev/null +++ b/Sources/UntoldEngine/Systems/GizmoPalette.swift @@ -0,0 +1,50 @@ +// +// GizmoPalette.swift +// UntoldEngine +// +// Copyright (C) Untold Engine Studios +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// +import Foundation +import simd + +/// The colours of the transform gizmo, from the redesign spec: red for X, +/// green for Y, blue for Z and a white centre. +/// +/// The spec names them as they look on the screen. The gizmo is drawn into +/// the scene before the tone map and the display's curve, so each is handed to +/// the engine as the light that curve turns back into the colour. +enum GizmoPalette { + static let x = linear(hex: 0xFF5A5A) + static let y = linear(hex: 0x5CE08C) + static let z = linear(hex: 0x4C8DFF) + static let center = linear(hex: 0xFFFFFF) + + /// The engine keeps a gizmo's pixel only when it is brighter than this, + /// by the weights below; a darker colour would not be drawn at all. + static let engineLuminanceFloor: Float = 0.1 + + /// The light of a colour written as `0xRRGGBB` for the screen. + static func linear(hex: UInt32) -> simd_float4 { + simd_float4( + linear(fromDisplay: Float((hex >> 16) & 0xFF) / 255), + linear(fromDisplay: Float((hex >> 8) & 0xFF) / 255), + linear(fromDisplay: Float(hex & 0xFF) / 255), + 1 + ) + } + + /// The sRGB curve, from what the screen shows to the light behind it. + static func linear(fromDisplay value: Float) -> Float { + value <= 0.04045 ? value / 12.92 : pow((value + 0.055) / 1.055, 2.4) + } + + /// How bright the engine takes a colour to be when it decides whether a + /// pixel is the gizmo's. + static func engineLuminance(of color: simd_float4) -> Float { + simd_dot(simd_float3(color.x, color.y, color.z), simd_float3(0.299, 0.587, 0.114)) + } +} diff --git a/Sources/UntoldEngine/Systems/GizmoSystem.swift b/Sources/UntoldEngine/Systems/GizmoSystem.swift new file mode 100644 index 000000000..9ad19ec3b --- /dev/null +++ b/Sources/UntoldEngine/Systems/GizmoSystem.swift @@ -0,0 +1,1167 @@ +// +// GizmoSystem.swift +// UntoldEngine +// +// Copyright (C) Untold Engine Studios +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import Foundation +import simd + +private enum GizmoDimensions { + static let axisLength: Float = 0.9 + static let shaftRadius: Float = 0.01 + static let arrowHeight: Float = 0.2 + static let arrowRadius: Float = 0.09 + static let scaleCubeExtent: Float = 0.16 + static let rotateRingRadius: Float = 0.9 + static let rotateRingThickness: Float = 0.01 + static let rotateHitRingThickness: Float = 0.08 + static let rotateRingSegments: Int = 48 + static let rotateHitRingSegments: Int = 36 + static let directionHandleRadius: Float = 0.08 + static let directionHandleHitRadius: Float = 0.2 + static let directionHandleOffsetY: Float = -1.0 + static let centerDiameter: Float = 0.12 +} + +public enum GizmoMode: String { + case translate + case rotate + case scale + + public init(name: String) { + switch name { + case "rotateGizmo": + self = .rotate + case "scaleGizmo": + self = .scale + default: + self = .translate + } + } +} + +private struct GizmoHandleDescriptor { + let mode: TransformManipulationMode + let axis: TransformAxis +} + +public struct GizmoDragRay { + public let origin: simd_float3 + public let direction: simd_float3 + + public init(origin: simd_float3, direction: simd_float3) { + self.origin = origin + self.direction = direction + } +} + +private struct GizmoDragState { + let mode: TransformManipulationMode + let axis: TransformAxis + let axisWorldDirection: simd_float3 + let startAxisParameter: Float + /// What the drag works on, as it stood when the drag began: the active + /// entity, or with several selected every one the gizmo moves. + let targets: [GizmoTargetStart] + let startGizmoWorldPosition: simd_float3 + /// When the gizmo sits on a handle backed by a `GizmoHandleOverrideProvider` + /// (e.g. a spline's control point), the drag moves the override instead of + /// the entity. + let usesHandleOverride: Bool + var appliedAxisAmount: Float = 0.0 + + var isAxisDriven: Bool { + mode == .translate || mode == .scale + } +} + +/// A rotation drag in progress: the whole turn so far, and the part of it +/// already applied, so snapping quantizes the turn rather than each frame. +private struct GizmoRotationDrag { + var accumulatedDegrees: Float = 0 + var appliedDegrees: Float = 0 +} + +private final class GizmoDragRuntimeState: @unchecked Sendable { + let lock = NSLock() + var dragState: GizmoDragState? + var pendingDragRay: GizmoDragRay? + var rotationDrag: GizmoRotationDrag? +} + +private let gizmoDragRuntimeState = GizmoDragRuntimeState() + +private var gizmoDragState: GizmoDragState? { + get { + gizmoDragRuntimeState.lock.lock() + defer { gizmoDragRuntimeState.lock.unlock() } + return gizmoDragRuntimeState.dragState + } + set { + gizmoDragRuntimeState.lock.lock() + gizmoDragRuntimeState.dragState = newValue + gizmoDragRuntimeState.lock.unlock() + } +} + +private var pendingGizmoDragRay: GizmoDragRay? { + get { + gizmoDragRuntimeState.lock.lock() + defer { gizmoDragRuntimeState.lock.unlock() } + return gizmoDragRuntimeState.pendingDragRay + } + set { + gizmoDragRuntimeState.lock.lock() + gizmoDragRuntimeState.pendingDragRay = newValue + gizmoDragRuntimeState.lock.unlock() + } +} + +private var gizmoRotationDrag: GizmoRotationDrag? { + get { + gizmoDragRuntimeState.lock.lock() + defer { gizmoDragRuntimeState.lock.unlock() } + return gizmoDragRuntimeState.rotationDrag + } + set { + gizmoDragRuntimeState.lock.lock() + gizmoDragRuntimeState.rotationDrag = newValue + gizmoDragRuntimeState.lock.unlock() + } +} + +/// The nearest multiple of `step`, matching the editor's `EditorSnapSettings.quantize`. +private func quantize(_ amount: Float, step: Float) -> Float { + guard step > 0, amount.isFinite else { + return amount + } + return (amount / step).rounded() * step +} + +/// The amount a translate/scale drag lands on: the nearest step from +/// `gizmoSnapProvider`, or the amount itself when there is no provider or no +/// snapping for this mode. +private func snappedAxisAmount(_ amount: Float, for mode: TransformManipulationMode) -> Float { + guard let step = gizmoSnapProvider?.snapStep(for: mode), step > 0, amount.isFinite else { + return amount + } + return quantize(amount, step: step) +} + +public func gizmoRootWorldPosition() -> simd_float3 { + guard parentEntityIdGizmo != .invalid else { + return activeEntity == .invalid ? .zero : getPosition(entityId: activeEntity) + } + + return getPosition(entityId: parentEntityIdGizmo) +} + +func gizmoWorldScaleForScreenSize( + cameraEntityId: EntityID, + gizmoWorldPosition: simd_float3, + viewport: simd_float2? = renderInfo.viewPort +) -> Float? { + guard cameraEntityId != .invalid, + let viewport, + viewport.y > 0.0 + else { + return nil + } + + let distanceToCamera = length(getCameraPosition(entityId: cameraEntityId) - gizmoWorldPosition) + let worldScale = 2.0 * distanceToCamera * tan(fov * 0.5) * (gizmoDesiredScreenSize / viewport.y) + guard worldScale.isFinite, worldScale > 0.0 else { + return nil + } + + return worldScale +} + +@discardableResult +public func updateGizmoScreenSpaceScale(cameraEntityId: EntityID) -> Bool { + guard gizmoActive, + parentEntityIdGizmo != .invalid, + let worldScale = gizmoWorldScaleForScreenSize( + cameraEntityId: cameraEntityId, + gizmoWorldPosition: gizmoRootWorldPosition() + ) + else { + return false + } + + scaleTo(entityId: parentEntityIdGizmo, scale: simd_float3(repeating: worldScale)) + return true +} + +public func beginGizmoDrag(ray: GizmoDragRay) { + guard activeEntity != .invalid, + parentEntityIdGizmo != .invalid, + let handleComponent = scene.get(component: GizmoHandleComponent.self, for: activeHitGizmoEntity) + else { + gizmoDragState = nil + return + } + + let axisDirection = gizmoAxisDirection(for: handleComponent.axis, entityId: activeEntity, space: gizmoTransformSpace) + if handleComponent.mode == .rotate { + beginGizmoRotationDrag() + } + guard handleComponent.mode == .translate || handleComponent.mode == .scale, + simd_length_squared(axisDirection) > 0.0001 + else { + gizmoDragState = nil + return + } + + let normalizedRayDirection = normalizeOrNil(ray.direction) ?? ray.direction + guard let startParameter = closestParameterOnAxis( + axisPoint: gizmoRootWorldPosition(), + axisDirection: axisDirection, + rayOrigin: ray.origin, + rayDirection: normalizedRayDirection + ) else { + gizmoDragState = nil + return + } + + gizmoDragState = GizmoDragState( + mode: handleComponent.mode, + axis: handleComponent.axis, + axisWorldDirection: axisDirection, + startAxisParameter: startParameter, + targets: gizmoTransformTargets().map(GizmoTargetStart.init(entityId:)), + startGizmoWorldPosition: gizmoRootWorldPosition(), + usesHandleOverride: handleComponent.mode == .translate && gizmoHandleOverrideProvider?.activeOverrideWorldPosition() != nil + ) +} + +func updateGizmoDrag(ray: GizmoDragRay) { + guard var state = gizmoDragState, + state.isAxisDriven + else { + return + } + + let normalizedRayDirection = normalizeOrNil(ray.direction) ?? ray.direction + guard let currentParameter = closestParameterOnAxis( + axisPoint: state.startGizmoWorldPosition, + axisDirection: state.axisWorldDirection, + rayOrigin: ray.origin, + rayDirection: normalizedRayDirection + ) else { + return + } + + // With snapping on, the whole drag lands on a step; the increments follow. + let axisAmount = snappedAxisAmount(currentParameter - state.startAxisParameter, for: state.mode) + let incrementalAmount = axisAmount - state.appliedAxisAmount + guard incrementalAmount.isFinite else { + return + } + + switch state.mode { + case .translate: + let translation = state.axisWorldDirection * axisAmount + if state.usesHandleOverride, gizmoHandleOverrideProvider?.moveOverride(toWorld: state.startGizmoWorldPosition + translation) == true { + // handled by the override provider + } else { + // The gizmo moves in world space; an entity's position is its parent's. + translateGizmoTargets(state.targets, byWorld: translation) + } + translateTo(entityId: parentEntityIdGizmo, position: state.startGizmoWorldPosition + translation) + + case .scale: + if state.targets.count > 1 { + // Several entities grow together, from where they stood. + scaleGizmoTargets( + state.targets, + from: state.startGizmoWorldPosition, + axis: state.axisWorldDirection, + factor: gizmoGroupScaleFactor(forAmount: axisAmount) + ) + } else if hasComponent(entityId: activeEntity, componentType: LightComponent.self) { + // The engine takes the axis as which components of the scale to change. + handleLightScaleInput(projectedAmount: incrementalAmount, axis: worldDirection(for: state.axis)) + } else { + // The engine takes the axis as the entity's parent sees it. + applyWorldSpaceScaleDelta( + entityId: activeEntity, + worldAxis: localAxis(ofWorld: state.axisWorldDirection, for: activeEntity), + projectedAmount: incrementalAmount + ) + } + + default: + break + } + + state.appliedAxisAmount = axisAmount + gizmoDragState = state +} + +public func queueGizmoDragUpdate(ray: GizmoDragRay) { + pendingGizmoDragRay = ray +} + +@discardableResult +public func applyPendingGizmoDragUpdate() -> Bool { + guard let ray = pendingGizmoDragRay else { + return false + } + + pendingGizmoDragRay = nil + updateGizmoDrag(ray: ray) + return true +} + +public func endGizmoDrag() { + gizmoDragState = nil + pendingGizmoDragRay = nil + gizmoRotationDrag = nil + reanchorGizmoOnTargets() +} + +public func hasActiveAxisGizmoDrag() -> Bool { + gizmoDragState?.isAxisDriven == true +} + +func applyGizmoRotationDelta(entityId: EntityID, axis: simd_float3, degrees: Float) { + guard entityId != .invalid, + degrees.isFinite, + simd_length_squared(axis) > 0.0001, + let localTransform = scene.get(component: LocalTransformComponent.self, for: entityId) + else { + return + } + + // `axis` is the world's; the rotation is stored relative to the parent. + let axisForParent = localAxis(ofWorld: simd_normalize(axis), for: entityId) + let delta = simd_quatf(angle: degreesToRadians(degrees: degrees), axis: simd_normalize(axisForParent)) + let currentRotation = normalizedRotationOrIdentity(localTransform.rotation) + localTransform.rotation = simd_normalize(simd_mul(delta, currentRotation)) + translateTo(entityId: entityId, position: localTransform.position) + syncStoredAxisRotationsFromQuaternion(entityId: entityId) + if entityId == activeEntity { + syncGizmoOrientation() + } +} + +private func normalizedRotationOrIdentity(_ rotation: simd_quatf) -> simd_quatf { + let lengthSquared = rotation.real * rotation.real + simd_length_squared(rotation.vector) + guard lengthSquared.isFinite, lengthSquared > 0.0001 else { + return simd_quatf(real: 1.0, imag: .zero) + } + + return simd_normalize(rotation) +} + +private func syncStoredAxisRotationsFromQuaternion(entityId: EntityID) { + guard let localTransform = scene.get(component: LocalTransformComponent.self, for: entityId) else { + return + } + + let euler = transformQuaternionToEulerAngles(q: localTransform.rotation) + localTransform.rotationX = euler.pitch + localTransform.rotationY = euler.yaw + localTransform.rotationZ = euler.roll +} + +/// The entity's parent, or nil for a root. An entity outside the scene graph +/// has none, which the engine's `getEntityParent` would report as an error. +public func parentInSceneGraph(of entityId: EntityID) -> EntityID? { + guard hasComponent(entityId: entityId, componentType: ScenegraphComponent.self), + let parent = getEntityParent(entityId: entityId), + parent != .invalid + else { + return nil + } + return parent +} + +/// A movement in world space as the entity's parent measures it. An entity's +/// position is relative to its parent, so under a parent that is turned or +/// scaled the same movement has other numbers: half a turn around Y reverses +/// its X and Z, a parent twice the size halves it. +func localTranslation(ofWorld translation: simd_float3, for entityId: EntityID) -> simd_float3 { + guard let parent = parentInSceneGraph(of: entityId), + let parentSpace = scene.get(component: WorldTransformComponent.self, for: parent)?.space + else { + return translation + } + + let determinant = simd_determinant(parentSpace) + guard determinant.isFinite, abs(determinant) > 1e-12 else { + // A parent squashed flat has no way back; its turn alone still has. + return simd_act(entityWorldRotation(entityId: parent).inverse, translation) + } + let local = simd_mul(parentSpace.inverse, simd_float4(translation, 0)) + return simd_float3(local.x, local.y, local.z) +} + +/// An axis of the world as the entity's parent sees it, for a turn that is +/// stored relative to the parent. +func localAxis(ofWorld axis: simd_float3, for entityId: EntityID) -> simd_float3 { + guard let parent = parentInSceneGraph(of: entityId) else { + return axis + } + return simd_act(entityWorldRotation(entityId: parent).inverse, axis) +} + +/// The entity's rotation in world space: its own composed with its ancestors', +/// from the local transforms, so it is right before the frame's world update. +func entityWorldRotation(entityId: EntityID) -> simd_quatf { + var rotation = simd_quatf(real: 1, imag: .zero) + var current: EntityID? = entityId + var depth = 0 + while let id = current, id != .invalid, depth < 64 { + if let local = scene.get(component: LocalTransformComponent.self, for: id) { + rotation = simd_normalize(simd_mul(normalizedRotationOrIdentity(local.rotation), rotation)) + } + current = parentInSceneGraph(of: id) + depth += 1 + } + return rotation +} + +/// The world direction of a gizmo axis: the world's axis, or in Local space +/// the entity's own, which its world rotation turns the world axis into. +public func gizmoAxisDirection(for axis: TransformAxis, entityId: EntityID, space: TransformSpace) -> simd_float3 { + let direction = worldDirection(for: axis) + guard space == .local, entityId != .invalid, simd_length_squared(direction) > 0 else { + return direction + } + return simd_normalize(simd_act(entityWorldRotation(entityId: entityId), direction)) +} + +/// The rotation the gizmo root has: the entity's own in Local space, so the +/// handles lie along the entity's axes, and none in World space. +public func gizmoRootRotation() -> simd_quatf { + guard activeEntity != .invalid, gizmoTransformSpace == .local else { + return simd_quatf(real: 1, imag: .zero) + } + return entityWorldRotation(entityId: activeEntity) +} + +/// Turns the gizmo to the entity's own axes in Local space, and back to the +/// world's in World space. +public func syncGizmoOrientation() { + guard parentEntityIdGizmo != .invalid, activeEntity != .invalid else { return } + rotateTo(entityId: parentEntityIdGizmo, rotation: gizmoRootRotation()) +} + +/// The gizmo follows a turn of its entity made elsewhere than on the gizmo: +/// the Inspector's fields, the sun's elevation and azimuth, a reset. Its +/// axes turn with the entity in Local space, and the direction handle of a +/// light goes along the new emission. Nothing happens for another entity. +public func syncGizmoToTurn(of entityId: EntityID) { + guard entityId != .invalid, entityId == activeEntity, gizmoActive else { return } + syncGizmoOrientation() + syncLightDirectionHandleToActiveLight(entityId: entityId) +} + +/// Starts accumulating a rotation drag, so snapping can quantize the whole +/// turn rather than each frame's part of it. +func beginGizmoRotationDrag() { + gizmoRotationDrag = GizmoRotationDrag() +} + +/// The rotation to apply for this frame's `degrees`: the amount itself, or +/// with rotation snapping on, the steps the accumulated turn has crossed. +public func snappedGizmoRotationDelta(degrees: Float) -> Float { + guard degrees.isFinite else { + return 0 + } + guard var drag = gizmoRotationDrag, let step = gizmoSnapProvider?.snapStep(for: .rotate) else { + return degrees + } + drag.accumulatedDegrees += degrees + let target = quantize(drag.accumulatedDegrees, step: step) + let delta = target - drag.appliedDegrees + drag.appliedDegrees = target + gizmoRotationDrag = drag + return delta +} + +/// The world's axis for a handle's axis; also what names a component of a +/// scale to the engine's light scale handler. +func worldDirection(for axis: TransformAxis) -> simd_float3 { + switch axis { + case .x: + return simd_float3(1.0, 0.0, 0.0) + case .y: + return simd_float3(0.0, 1.0, 0.0) + case .z: + return simd_float3(0.0, 0.0, 1.0) + case .none: + return .zero + } +} + +private func normalizeOrNil(_ value: simd_float3) -> simd_float3? { + let lengthSquared = simd_length_squared(value) + guard lengthSquared.isFinite, lengthSquared > 0.0001 else { + return nil + } + return value / sqrt(lengthSquared) +} + +private func closestParameterOnAxis( + axisPoint: simd_float3, + axisDirection: simd_float3, + rayOrigin: simd_float3, + rayDirection: simd_float3 +) -> Float? { + guard let axis = normalizeOrNil(axisDirection), + let ray = normalizeOrNil(rayDirection) + else { + return nil + } + + let w = axisPoint - rayOrigin + let axisRayDot = simd_dot(axis, ray) + let axisPointDot = simd_dot(axis, w) + let rayPointDot = simd_dot(ray, w) + let denominator = 1.0 - axisRayDot * axisRayDot + + guard abs(denominator) > 0.0001 else { + return nil + } + + let parameter = (axisRayDot * rayPointDot - axisPointDot) / denominator + return parameter.isFinite ? parameter : nil +} + +private func applyGizmoHandleColor(entityId: EntityID, color: simd_float4) { + guard let renderComponent = scene.get(component: RenderComponent.self, for: entityId) else { + return + } + + for meshIndex in renderComponent.mesh.indices { + for subMeshIndex in renderComponent.mesh[meshIndex].submeshes.indices { + guard var material = renderComponent.mesh[meshIndex].submeshes[subMeshIndex].material else { + continue + } + + material.baseColorValue = color + material.emissiveValue = simd_float3(color.x, color.y, color.z) + material.interactWithLight = false + renderComponent.mesh[meshIndex].submeshes[subMeshIndex].material = material + } + } +} + +private func gizmoAnchorWorldPosition(entityId: EntityID) -> simd_float3 { + guard let worldTransform = scene.get(component: WorldTransformComponent.self, for: entityId) else { + return getPosition(entityId: entityId) + } + + @inline(__always) + func localBoundsCenter(for target: EntityID) -> simd_float3? { + guard let localTransform = scene.get(component: LocalTransformComponent.self, for: target) else { + return nil + } + return (localTransform.boundingBox.min + localTransform.boundingBox.max) * 0.5 + } + + var localCenter: simd_float3? + + if hasComponent(entityId: entityId, componentType: RenderComponent.self) { + localCenter = localBoundsCenter(for: entityId) + } else { + // Imported USD roots often have no RenderComponent, while renderable children carry bounds. + // Match highlight behavior by anchoring from children's effective local bounds. + var minBounds = simd_float3(Float.greatestFiniteMagnitude, Float.greatestFiniteMagnitude, Float.greatestFiniteMagnitude) + var maxBounds = simd_float3(-Float.greatestFiniteMagnitude, -Float.greatestFiniteMagnitude, -Float.greatestFiniteMagnitude) + var foundRenderableChild = false + + let children = getEntityChildren(parentId: entityId) + for childId in children { + guard hasComponent(entityId: childId, componentType: RenderComponent.self), + let childTransform = scene.get(component: LocalTransformComponent.self, for: childId) + else { + continue + } + + let translatedMin = childTransform.boundingBox.min + childTransform.position + let translatedMax = childTransform.boundingBox.max + childTransform.position + minBounds = simd_min(minBounds, translatedMin) + maxBounds = simd_max(maxBounds, translatedMax) + foundRenderableChild = true + } + + if foundRenderableChild { + localCenter = (minBounds + maxBounds) * 0.5 + } + } + + guard let localCenter else { + return getPosition(entityId: entityId) + } + + let modelMatrix = simd_mul(worldTransform.space, matrix4x4Translation(localCenter.x, localCenter.y, localCenter.z)) + return simd_float3(modelMatrix.columns.3.x, modelMatrix.columns.3.y, modelMatrix.columns.3.z) +} + +@discardableResult +private func createGizmoHandle( + parentId: EntityID, + name: String, + meshes: [Mesh], + localPosition: simd_float3, + color: simd_float4, + descriptor: GizmoHandleDescriptor, + rotation: (angle: Float, axis: simd_float3)? = nil, + isHitProxy: Bool = false +) -> EntityID { + let handle = createEntity() + setEntityName(entityId: handle, name: name) + setEntityMeshDirect(entityId: handle, meshes: meshes, assetName: name) + setParent(childId: handle, parentId: parentId) + translateTo(entityId: handle, position: localPosition) + if let rotation { + rotateTo(entityId: handle, angle: rotation.angle, axis: rotation.axis) + } + registerComponent(entityId: handle, componentType: GizmoComponent.self) + registerComponent(entityId: handle, componentType: GizmoHandleComponent.self) + if let handleComponent = scene.get(component: GizmoHandleComponent.self, for: handle) { + handleComponent.mode = descriptor.mode + handleComponent.axis = descriptor.axis + } + if isHitProxy { + registerComponent(entityId: handle, componentType: GizmoHitProxyComponent.self) + } + applyGizmoHandleColor(entityId: handle, color: color) + return handle +} + +/// The white dot where the gizmo's axes meet. It shows where the gizmo is +/// and is no handle: picking passes through it. +@discardableResult +private func makeGizmoCenter() -> EntityID { + let center = createEntity() + setEntityName(entityId: center, name: "gizmoCenter") + setEntityMeshDirect( + entityId: center, + meshes: BasicPrimitives.createSphere(extent: GizmoDimensions.centerDiameter, segments: [24, 12]), + assetName: "gizmoCenter" + ) + setParent(childId: center, parentId: parentEntityIdGizmo) + translateTo(entityId: center, position: .zero) + registerComponent(entityId: center, componentType: GizmoComponent.self) + registerComponent(entityId: center, componentType: GizmoCenterComponent.self) + setEntityPickParticipation(entityId: center, enabled: false) + applyGizmoHandleColor(entityId: center, color: GizmoPalette.center) + return center +} + +@discardableResult +private func makeDirectionHandle() -> EntityID { + let handleColor = simd_float4(1.0, 1.0, 0.0, 1.0) + let localPosition = initialLightDirectionHandleOffset() + let visibleHandle = createGizmoHandle( + parentId: parentEntityIdGizmo, + name: "directionHandle", + meshes: BasicPrimitives.createSphere(extent: GizmoDimensions.directionHandleRadius, segments: [24, 12]), + localPosition: localPosition, + color: handleColor, + descriptor: GizmoHandleDescriptor(mode: .lightRotate, axis: .none) + ) + + createGizmoHandle( + parentId: parentEntityIdGizmo, + name: "directionHandleHitProxy", + meshes: BasicPrimitives.createSphere(extent: GizmoDimensions.directionHandleHitRadius, segments: [16, 8]), + localPosition: localPosition, + color: simd_float4(0.0, 0.0, 0.0, 0.0), + descriptor: GizmoHandleDescriptor(mode: .lightRotate, axis: .none), + isHitProxy: true + ) + + return visibleHandle +} + +/// Where the light direction handle sits under the gizmo root: along the +/// light's emission, which its rotation turns the local -Z into, in the +/// root's own frame. In World space the root is not turned and the offset is +/// the emission itself; in Local space the root is turned with the entity, +/// so the offset is the emission as the entity sees it, straight along -Z. +private func initialLightDirectionHandleOffset() -> simd_float3 { + guard activeEntity != .invalid else { + return simd_float3(0.0, GizmoDimensions.directionHandleOffsetY, 0.0) + } + + let emission = simd_act(entityWorldRotation(entityId: activeEntity), simd_float3(0.0, 0.0, -1.0)) + let offset = simd_act(gizmoRootRotation().inverse, emission) + let handleDirection = simd_length_squared(offset) > 0.0001 ? simd_normalize(offset) : simd_float3(0.0, -1.0, 0.0) + return handleDirection * abs(GizmoDimensions.directionHandleOffsetY) +} + +/// Repositions the light direction handle (and its hit proxy) to match the given light +/// entity's current orientation. Call this after changing a light's rotation through any +/// path other than dragging the handle itself (e.g. editing the Orientation fields in the +/// Inspector), so the gizmo doesn't go stale relative to the light it represents. +public func syncLightDirectionHandleToActiveLight(entityId: EntityID) { + guard entityId != .invalid, + entityId == activeEntity, + gizmoActive, + parentEntityIdGizmo != .invalid, + hasComponent(entityId: entityId, componentType: LightComponent.self) + else { + return + } + + let localPosition = initialLightDirectionHandleOffset() + + for handle in getEntityChildren(parentId: parentEntityIdGizmo) { + guard let handleComponent = scene.get(component: GizmoHandleComponent.self, for: handle), + handleComponent.mode == .lightRotate, handleComponent.axis == .none + else { + continue + } + translateTo(entityId: handle, position: localPosition) + } +} + +private func rotationFromYAxis(to direction: simd_float3) -> (angle: Float, axis: simd_float3)? { + let up = simd_float3(0.0, 1.0, 0.0) + let dirLength = simd_length(direction) + if dirLength < 0.0001 { + return nil + } + + let dir = simd_normalize(direction) + let dotValue = simd_dot(up, dir) + let clampedDot = max(-1.0, min(1.0, dotValue)) + let angleRadians = acos(clampedDot) + + if angleRadians < 0.0001 { + return nil + } + + var axis = simd_cross(up, dir) + if simd_length(axis) < 0.0001 { + axis = simd_float3(1.0, 0.0, 0.0) + } else { + axis = simd_normalize(axis) + } + + let angleDegrees = angleRadians * (180.0 / Float.pi) + return (angleDegrees, axis) +} + +private func makeRotationRing( + handleName: String, + color: simd_float4, + axisA: simd_float3, + axisB: simd_float3, + startAngle: Float = 0.0, + sweepAngle: Float = 2.0 * Float.pi +) { + let fullTurn = 2.0 * Float.pi + let normalizedSweep = max(0.0001, abs(sweepAngle)) + let segmentCount = max(1, Int(round(Float(GizmoDimensions.rotateRingSegments) * (normalizedSweep / fullTurn)))) + let radius = GizmoDimensions.rotateRingRadius + let delta = sweepAngle / Float(segmentCount) + let segmentLength = 2.0 * radius * sin(abs(delta) * 0.5) * 0.9 + + @inline(__always) + func makeRingSegmentMesh() -> [Mesh] { + BasicPrimitives.createCylinder( + height: segmentLength, + radius: GizmoDimensions.rotateRingThickness, + segments: [12, 1] + ) + } + + for i in 0 ..< segmentCount { + let theta = startAngle + (Float(i) + 0.5) * delta + let c = cos(theta) + let s = sin(theta) + + let localPos = axisA * (radius * c) + axisB * (radius * s) + let tangent = axisA * -s + axisB * c + let rotation = rotationFromYAxis(to: tangent) + + createGizmoHandle( + parentId: parentEntityIdGizmo, + name: handleName, + meshes: makeRingSegmentMesh(), + localPosition: localPos, + color: color, + descriptor: GizmoHandleDescriptor(mode: .rotate, axis: axisForRotationHandleName(handleName)), + rotation: rotation + ) + } +} + +private func makeRotationHitRing( + handleName: String, + axisA: simd_float3, + axisB: simd_float3, + startAngle: Float = 0.0, + sweepAngle: Float = 2.0 * Float.pi +) { + let fullTurn = 2.0 * Float.pi + let normalizedSweep = max(0.0001, abs(sweepAngle)) + let segmentCount = max(1, Int(round(Float(GizmoDimensions.rotateHitRingSegments) * (normalizedSweep / fullTurn)))) + let radius = GizmoDimensions.rotateRingRadius + let delta = sweepAngle / Float(segmentCount) + let segmentLength = 2.0 * radius * sin(abs(delta) * 0.5) + let descriptor = GizmoHandleDescriptor(mode: .rotate, axis: axisForRotationHandleName(handleName)) + + @inline(__always) + func makeHitSegmentMesh() -> [Mesh] { + BasicPrimitives.createCylinder( + height: segmentLength, + radius: GizmoDimensions.rotateHitRingThickness, + segments: [16, 1] + ) + } + + for i in 0 ..< segmentCount { + let theta = startAngle + (Float(i) + 0.5) * delta + let c = cos(theta) + let s = sin(theta) + + let localPos = axisA * (radius * c) + axisB * (radius * s) + let tangent = axisA * -s + axisB * c + let rotation = rotationFromYAxis(to: tangent) + + createGizmoHandle( + parentId: parentEntityIdGizmo, + name: "\(handleName)HitProxy", + meshes: makeHitSegmentMesh(), + localPosition: localPos, + color: simd_float4(0.0, 0.0, 0.0, 0.0), + descriptor: descriptor, + rotation: rotation, + isHitProxy: true + ) + } +} + +private func axisForRotationHandleName(_ handleName: String) -> TransformAxis { + switch handleName { + case "xAxisRotate": + return .x + case "yAxisRotate": + return .y + case "zAxisRotate": + return .z + default: + return .none + } +} + +func makeTranslateGizmo() { + @inline(__always) + func makeShaftMeshes() -> [Mesh] { + BasicPrimitives.createCylinder( + height: GizmoDimensions.axisLength, + radius: GizmoDimensions.shaftRadius, + segments: [16, 1] + ) + } + + @inline(__always) + func makeArrowMeshes() -> [Mesh] { + BasicPrimitives.createCone( + height: GizmoDimensions.arrowHeight, + radius: GizmoDimensions.arrowRadius, + segments: [20, 1] + ) + } + + let halfShaft = GizmoDimensions.axisLength * 0.5 + let tipOffset = GizmoDimensions.axisLength + GizmoDimensions.arrowHeight + + // X axis + let xColor = GizmoPalette.x + let yColor = GizmoPalette.y + let zColor = GizmoPalette.z + + createGizmoHandle( + parentId: parentEntityIdGizmo, + name: "xAxisTranslate", + meshes: makeShaftMeshes(), + localPosition: simd_float3(halfShaft, 0.0, 0.0), + color: xColor, + descriptor: GizmoHandleDescriptor(mode: .translate, axis: .x), + rotation: (90.0, simd_float3(0.0, 0.0, 1.0)) + ) + createGizmoHandle( + parentId: parentEntityIdGizmo, + name: "xAxisTranslate", + meshes: makeArrowMeshes(), + localPosition: simd_float3(tipOffset, 0.0, 0.0), + color: xColor, + descriptor: GizmoHandleDescriptor(mode: .translate, axis: .x), + rotation: (-90.0, simd_float3(0.0, 0.0, 1.0)) + ) + + // Y axis + createGizmoHandle( + parentId: parentEntityIdGizmo, + name: "yAxisTranslate", + meshes: makeShaftMeshes(), + localPosition: simd_float3(0.0, halfShaft, 0.0), + color: yColor, + descriptor: GizmoHandleDescriptor(mode: .translate, axis: .y) + ) + createGizmoHandle( + parentId: parentEntityIdGizmo, + name: "yAxisTranslate", + meshes: makeArrowMeshes(), + localPosition: simd_float3(0.0, tipOffset, 0.0), + color: yColor, + descriptor: GizmoHandleDescriptor(mode: .translate, axis: .y) + ) + + // Z axis + createGizmoHandle( + parentId: parentEntityIdGizmo, + name: "zAxisTranslate", + meshes: makeShaftMeshes(), + localPosition: simd_float3(0.0, 0.0, halfShaft), + color: zColor, + descriptor: GizmoHandleDescriptor(mode: .translate, axis: .z), + rotation: (90.0, simd_float3(1.0, 0.0, 0.0)) + ) + createGizmoHandle( + parentId: parentEntityIdGizmo, + name: "zAxisTranslate", + meshes: makeArrowMeshes(), + localPosition: simd_float3(0.0, 0.0, tipOffset), + color: zColor, + descriptor: GizmoHandleDescriptor(mode: .translate, axis: .z), + rotation: (90.0, simd_float3(1.0, 0.0, 0.0)) + ) +} + +func makeScaleGizmo() { + @inline(__always) + func makeShaftMeshes() -> [Mesh] { + BasicPrimitives.createCylinder( + height: GizmoDimensions.axisLength, + radius: GizmoDimensions.shaftRadius, + segments: [16, 1] + ) + } + + @inline(__always) + func makeTipCubeMeshes() -> [Mesh] { + BasicPrimitives.createCube(extent: GizmoDimensions.scaleCubeExtent) + } + + let halfShaft = GizmoDimensions.axisLength * 0.5 + let cubeCenterOffset = GizmoDimensions.axisLength + (GizmoDimensions.scaleCubeExtent * 0.5) + + // X axis + let xColor = GizmoPalette.x + let yColor = GizmoPalette.y + let zColor = GizmoPalette.z + + createGizmoHandle( + parentId: parentEntityIdGizmo, + name: "xAxisScale", + meshes: makeShaftMeshes(), + localPosition: simd_float3(halfShaft, 0.0, 0.0), + color: xColor, + descriptor: GizmoHandleDescriptor(mode: .scale, axis: .x), + rotation: (90.0, simd_float3(0.0, 0.0, 1.0)) + ) + createGizmoHandle( + parentId: parentEntityIdGizmo, + name: "xAxisScale", + meshes: makeTipCubeMeshes(), + localPosition: simd_float3(cubeCenterOffset, 0.0, 0.0), + color: xColor, + descriptor: GizmoHandleDescriptor(mode: .scale, axis: .x) + ) + + // Y axis + createGizmoHandle( + parentId: parentEntityIdGizmo, + name: "yAxisScale", + meshes: makeShaftMeshes(), + localPosition: simd_float3(0.0, halfShaft, 0.0), + color: yColor, + descriptor: GizmoHandleDescriptor(mode: .scale, axis: .y) + ) + createGizmoHandle( + parentId: parentEntityIdGizmo, + name: "yAxisScale", + meshes: makeTipCubeMeshes(), + localPosition: simd_float3(0.0, cubeCenterOffset, 0.0), + color: yColor, + descriptor: GizmoHandleDescriptor(mode: .scale, axis: .y) + ) + + // Z axis + createGizmoHandle( + parentId: parentEntityIdGizmo, + name: "zAxisScale", + meshes: makeShaftMeshes(), + localPosition: simd_float3(0.0, 0.0, halfShaft), + color: zColor, + descriptor: GizmoHandleDescriptor(mode: .scale, axis: .z), + rotation: (90.0, simd_float3(1.0, 0.0, 0.0)) + ) + createGizmoHandle( + parentId: parentEntityIdGizmo, + name: "zAxisScale", + meshes: makeTipCubeMeshes(), + localPosition: simd_float3(0.0, 0.0, cubeCenterOffset), + color: zColor, + descriptor: GizmoHandleDescriptor(mode: .scale, axis: .z) + ) +} + +func makeRotationGizmo() { + let xColor = GizmoPalette.x + let yColor = GizmoPalette.y + let zColor = GizmoPalette.z + let positiveArcStart: Float = 0.0 + let positiveArcSweep = Float.pi * 0.5 + + // X-axis rotation ring (YZ plane) + makeRotationRing( + handleName: "xAxisRotate", + color: xColor, + axisA: simd_float3(0.0, 1.0, 0.0), + axisB: simd_float3(0.0, 0.0, 1.0), + startAngle: positiveArcStart, + sweepAngle: positiveArcSweep + ) + makeRotationHitRing( + handleName: "xAxisRotate", + axisA: simd_float3(0.0, 1.0, 0.0), + axisB: simd_float3(0.0, 0.0, 1.0), + startAngle: positiveArcStart, + sweepAngle: positiveArcSweep + ) + + // Y-axis rotation ring (XZ plane) + makeRotationRing( + handleName: "yAxisRotate", + color: yColor, + axisA: simd_float3(1.0, 0.0, 0.0), + axisB: simd_float3(0.0, 0.0, 1.0), + startAngle: positiveArcStart, + sweepAngle: positiveArcSweep + ) + makeRotationHitRing( + handleName: "yAxisRotate", + axisA: simd_float3(1.0, 0.0, 0.0), + axisB: simd_float3(0.0, 0.0, 1.0), + startAngle: positiveArcStart, + sweepAngle: positiveArcSweep + ) + + // Z-axis rotation ring (XY plane) + makeRotationRing( + handleName: "zAxisRotate", + color: zColor, + axisA: simd_float3(1.0, 0.0, 0.0), + axisB: simd_float3(0.0, 1.0, 0.0), + startAngle: positiveArcStart, + sweepAngle: positiveArcSweep + ) + makeRotationHitRing( + handleName: "zAxisRotate", + axisA: simd_float3(1.0, 0.0, 0.0), + axisB: simd_float3(0.0, 1.0, 0.0), + startAngle: positiveArcStart, + sweepAngle: positiveArcSweep + ) +} + +public func createGizmo(name: String) { + createGizmo(mode: GizmoMode(name: name)) +} + +public func createGizmo(mode: GizmoMode) { + removeGizmo() + directionHandleEntityId = .invalid + + if activeEntity == .invalid { + return + } + + // create parent gizmo entity + parentEntityIdGizmo = createEntity() + + registerTransformComponent(entityId: parentEntityIdGizmo) + registerSceneGraphComponent(entityId: parentEntityIdGizmo) + registerComponent(entityId: parentEntityIdGizmo, componentType: GizmoComponent.self) + + // With several selected the gizmo stands in the middle of them. + let targets = gizmoTransformTargets() + let anchor = gizmoHandleOverrideProvider?.activeOverrideWorldPosition() + ?? (targets.count > 1 ? gizmoGroupAnchorWorldPosition(of: targets) : nil) + ?? gizmoAnchorWorldPosition(entityId: activeEntity) + translateTo(entityId: parentEntityIdGizmo, position: anchor) + + switch mode { + case .translate: + makeTranslateGizmo() + case .rotate: + makeRotationGizmo() + case .scale: + makeScaleGizmo() + } + makeGizmoCenter() + + // The handle that aims a light is for that light alone. + if targets.count <= 1, hasComponent(entityId: activeEntity, componentType: LightComponent.self) { + directionHandleEntityId = makeDirectionHandle() + } + + gizmoActive = true + syncGizmoOrientation() + + if let cameraEntityId = CameraSystem.shared.activeCamera { + updateGizmoScreenSpaceScale(cameraEntityId: cameraEntityId) + } +} + +public func processGizmoAction(entityId: EntityID) { + if entityId == .invalid { + return + } + + guard let handleComponent = scene.get(component: GizmoHandleComponent.self, for: entityId) else { + activeHitGizmoEntity = .invalid + gizmoHoverMode = .none + gizmoHoverAxis = .none + return + } + + activeHitGizmoEntity = entityId + gizmoHoverAxis = handleComponent.axis + gizmoHoverMode = handleComponent.mode +} + +public func hitGizmoToolAxis(entityId: EntityID) -> Bool { + if entityId == .invalid { + return false + } + + return scene.get(component: GizmoHandleComponent.self, for: entityId) != nil +} + +public func removeGizmo() { + if parentEntityIdGizmo != .invalid { + destroyEntity(entityId: parentEntityIdGizmo) + parentEntityIdGizmo = .invalid + } + + directionHandleEntityId = .invalid + gizmoActive = false +} diff --git a/Sources/UntoldEngine/Systems/RegistrationSystem.swift b/Sources/UntoldEngine/Systems/RegistrationSystem.swift index 7a351a187..ec811ad2f 100644 --- a/Sources/UntoldEngine/Systems/RegistrationSystem.swift +++ b/Sources/UntoldEngine/Systems/RegistrationSystem.swift @@ -237,6 +237,18 @@ private func registerComponentCleanupHandlers() { removeEntityGizmo(entityId: entityId) } + ComponentRegistry.register(componentType: GizmoHandleComponent.self, handlerId: "gizmoHandle", priority: 30) { entityId in + removeEntityGizmoHandle(entityId: entityId) + } + + ComponentRegistry.register(componentType: GizmoHitProxyComponent.self, handlerId: "gizmoHitProxy", priority: 30) { entityId in + removeEntityGizmoHitProxy(entityId: entityId) + } + + ComponentRegistry.register(componentType: GizmoCenterComponent.self, handlerId: "gizmoCenter", priority: 30) { entityId in + removeEntityGizmoCenter(entityId: entityId) + } + ComponentRegistry.register(componentType: PickInteractionComponent.self, handlerId: "pickInteraction", priority: 30) { entityId in removeEntityPickInteraction(entityId: entityId) } @@ -6277,6 +6289,24 @@ func removeEntityGizmo(entityId: EntityID) { } } +func removeEntityGizmoHandle(entityId: EntityID) { + if scene.get(component: GizmoHandleComponent.self, for: entityId) != nil { + scene.remove(component: GizmoHandleComponent.self, from: entityId) + } +} + +func removeEntityGizmoHitProxy(entityId: EntityID) { + if scene.get(component: GizmoHitProxyComponent.self, for: entityId) != nil { + scene.remove(component: GizmoHitProxyComponent.self, from: entityId) + } +} + +func removeEntityGizmoCenter(entityId: EntityID) { + if scene.get(component: GizmoCenterComponent.self, for: entityId) != nil { + scene.remove(component: GizmoCenterComponent.self, from: entityId) + } +} + func removeEntityPickInteraction(entityId: EntityID) { if scene.get(component: PickInteractionComponent.self, for: entityId) != nil { scene.remove(component: PickInteractionComponent.self, from: entityId) diff --git a/Sources/UntoldEngine/Utils/Globals.swift b/Sources/UntoldEngine/Utils/Globals.swift index abfa6f033..e7546d680 100644 --- a/Sources/UntoldEngine/Utils/Globals.swift +++ b/Sources/UntoldEngine/Utils/Globals.swift @@ -1131,6 +1131,17 @@ private final class RuntimeGlobalsStore: @unchecked Sendable { private var hdrDirectoryURLValue: URL? private var assetBasePathValue: URL? private var activeEntityValue: EntityID = .invalid + private var gizmoActiveValue: Bool = false + private var activeHitGizmoEntityValue: EntityID = .invalid + private var parentEntityIdGizmoValue: EntityID = .invalid + private var directionHandleEntityIdValue: EntityID = .invalid + private var gizmoDesiredScreenSizeValue: Float = 96.0 + private var gizmoTargetsValue: [EntityID] = [] + private var gizmoTransformSpaceValue: TransformSpace = .world + private var gizmoHoverModeValue: TransformManipulationMode = .none + private var gizmoHoverAxisValue: TransformAxis = .none + private var gizmoSnapProviderValue: GizmoSnapProvider? + private var gizmoHandleOverrideProviderValue: GizmoHandleOverrideProvider? private var enableEngineMetricsValue: Bool = false private var bypassPostProcessingValue: Bool = false private var xrFoveatedRenderingEnabledValue: Bool = true @@ -1612,6 +1623,160 @@ private final class RuntimeGlobalsStore: @unchecked Sendable { } } + var gizmoActive: Bool { + get { + lock.lock() + let value = gizmoActiveValue + lock.unlock() + return value + } + set { + lock.lock() + gizmoActiveValue = newValue + lock.unlock() + } + } + + var activeHitGizmoEntity: EntityID { + get { + lock.lock() + let value = activeHitGizmoEntityValue + lock.unlock() + return value + } + set { + lock.lock() + activeHitGizmoEntityValue = newValue + lock.unlock() + } + } + + var parentEntityIdGizmo: EntityID { + get { + lock.lock() + let value = parentEntityIdGizmoValue + lock.unlock() + return value + } + set { + lock.lock() + parentEntityIdGizmoValue = newValue + lock.unlock() + } + } + + var directionHandleEntityId: EntityID { + get { + lock.lock() + let value = directionHandleEntityIdValue + lock.unlock() + return value + } + set { + lock.lock() + directionHandleEntityIdValue = newValue + lock.unlock() + } + } + + var gizmoDesiredScreenSize: Float { + get { + lock.lock() + let value = gizmoDesiredScreenSizeValue + lock.unlock() + return value + } + set { + lock.lock() + gizmoDesiredScreenSizeValue = newValue + lock.unlock() + } + } + + var gizmoTargets: [EntityID] { + get { + lock.lock() + let value = gizmoTargetsValue + lock.unlock() + return value + } + set { + lock.lock() + gizmoTargetsValue = newValue + lock.unlock() + } + } + + var gizmoTransformSpace: TransformSpace { + get { + lock.lock() + let value = gizmoTransformSpaceValue + lock.unlock() + return value + } + set { + lock.lock() + gizmoTransformSpaceValue = newValue + lock.unlock() + } + } + + var gizmoHoverMode: TransformManipulationMode { + get { + lock.lock() + let value = gizmoHoverModeValue + lock.unlock() + return value + } + set { + lock.lock() + gizmoHoverModeValue = newValue + lock.unlock() + } + } + + var gizmoHoverAxis: TransformAxis { + get { + lock.lock() + let value = gizmoHoverAxisValue + lock.unlock() + return value + } + set { + lock.lock() + gizmoHoverAxisValue = newValue + lock.unlock() + } + } + + var gizmoSnapProvider: GizmoSnapProvider? { + get { + lock.lock() + let value = gizmoSnapProviderValue + lock.unlock() + return value + } + set { + lock.lock() + gizmoSnapProviderValue = newValue + lock.unlock() + } + } + + var gizmoHandleOverrideProvider: GizmoHandleOverrideProvider? { + get { + lock.lock() + let value = gizmoHandleOverrideProviderValue + lock.unlock() + return value + } + set { + lock.lock() + gizmoHandleOverrideProviderValue = newValue + lock.unlock() + } + } + var enableEngineMetrics: Bool { get { lock.lock() @@ -2024,6 +2189,91 @@ public enum TransformAxis { case x, y, z, none } +/// The axes a gizmo drag resolves along: the world's, or the target entity's own. +public enum TransformSpace: CaseIterable { + case world + case local +} + +/// Gizmo session state. Mirrors `activeEntity`'s thread-safe global pattern. +public var gizmoActive: Bool { + get { RuntimeGlobalsStore.shared.gizmoActive } + set { RuntimeGlobalsStore.shared.gizmoActive = newValue } +} + +public var activeHitGizmoEntity: EntityID { + get { RuntimeGlobalsStore.shared.activeHitGizmoEntity } + set { RuntimeGlobalsStore.shared.activeHitGizmoEntity = newValue } +} + +public var parentEntityIdGizmo: EntityID { + get { RuntimeGlobalsStore.shared.parentEntityIdGizmo } + set { RuntimeGlobalsStore.shared.parentEntityIdGizmo = newValue } +} + +public var directionHandleEntityId: EntityID { + get { RuntimeGlobalsStore.shared.directionHandleEntityId } + set { RuntimeGlobalsStore.shared.directionHandleEntityId = newValue } +} + +public var gizmoDesiredScreenSize: Float { + get { RuntimeGlobalsStore.shared.gizmoDesiredScreenSize } + set { RuntimeGlobalsStore.shared.gizmoDesiredScreenSize = newValue } +} + +/// Entities the active gizmo is manipulating (more than one when multiple entities are selected). +public var gizmoTargets: [EntityID] { + get { RuntimeGlobalsStore.shared.gizmoTargets } + set { RuntimeGlobalsStore.shared.gizmoTargets = newValue } +} + +/// Local vs. world axis resolution for the active gizmo drag. Host apps that offer a +/// space toggle (as the Editor does) should keep this in sync with their own UI state. +public var gizmoTransformSpace: TransformSpace { + get { RuntimeGlobalsStore.shared.gizmoTransformSpace } + set { RuntimeGlobalsStore.shared.gizmoTransformSpace = newValue } +} + +/// Mode/axis the pointer is currently hovering or dragging, written by `processGizmoAction`. +/// Host apps observe these to drive hover/drag highlighting instead of the gizmo system +/// reaching into app-specific UI state. +public var gizmoHoverMode: TransformManipulationMode { + get { RuntimeGlobalsStore.shared.gizmoHoverMode } + set { RuntimeGlobalsStore.shared.gizmoHoverMode = newValue } +} + +public var gizmoHoverAxis: TransformAxis { + get { RuntimeGlobalsStore.shared.gizmoHoverAxis } + set { RuntimeGlobalsStore.shared.gizmoHoverAxis = newValue } +} + +/// Lets a host app define its own snapping policy (e.g. grid/angle snapping driven by +/// user-facing settings). Return `nil` for a mode to mean "no snapping" for that mode. +/// Leaving `gizmoSnapProvider` unset means the gizmo never snaps. +public protocol GizmoSnapProvider { + func snapStep(for mode: TransformManipulationMode) -> Float? +} + +public var gizmoSnapProvider: GizmoSnapProvider? { + get { RuntimeGlobalsStore.shared.gizmoSnapProvider } + set { RuntimeGlobalsStore.shared.gizmoSnapProvider = newValue } +} + +/// Lets a host app redirect a gizmo drag to something other than the target entity's own +/// transform (e.g. dragging a scripted entity's exposed control point). When the provider +/// (or its returned position) is `nil`, the gizmo falls through to the plain transform-drag +/// path. +public protocol GizmoHandleOverrideProvider { + func activeOverrideWorldPosition() -> simd_float3? + @discardableResult + func moveOverride(toWorld position: simd_float3) -> Bool +} + +public var gizmoHandleOverrideProvider: GizmoHandleOverrideProvider? { + get { RuntimeGlobalsStore.shared.gizmoHandleOverrideProvider } + set { RuntimeGlobalsStore.shared.gizmoHandleOverrideProvider = newValue } +} + /// mtk view color /// Graphite Gray let mtkBackgroundColor = MTLClearColorMake(40.0 / 255.0, 40.0 / 255.0, 45.0 / 255.0, 1.0) diff --git a/Tests/UntoldEngineTests/GizmoGroupTests.swift b/Tests/UntoldEngineTests/GizmoGroupTests.swift new file mode 100644 index 000000000..d6e4200d8 --- /dev/null +++ b/Tests/UntoldEngineTests/GizmoGroupTests.swift @@ -0,0 +1,472 @@ +// +// GizmoGroupTests.swift +// UntoldEngine +// +// Copyright (C) Untold Engine Studios +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +// These unit tests were jump-started with AI assistance — then refined by humans. If you spot an issue, please submit an issue. + +import ModelIO +import simd +@testable import UntoldEngine +import XCTest + +private struct TestSnapProvider: GizmoSnapProvider { + var translateStep: Float? + var rotateStep: Float? + + func snapStep(for mode: TransformManipulationMode) -> Float? { + switch mode { + case .translate, .scale: + return translateStep + case .rotate: + return rotateStep + default: + return nil + } + } +} + +/// One gizmo on several entities: it moves them by the same distance, turns +/// them round itself and scales them from itself. +@MainActor +final class GizmoGroupTests: XCTestCase { + /// Which kind of gizmo `select(_:)` creates, replacing the editor's + /// `EditorViewportSettings.shared.tool`. + private var currentMode: GizmoMode = .translate + /// The entities the (now absent) `SelectionManager` would have tracked, + /// kept here only so `selectionBounds()` can reproduce + /// `SelectionManager.selectionBounds()`. + private var selectedEntities: [EntityID] = [] + + override func setUp() { + super.setUp() + resetEngineTestState() + + guard let device = MTLCreateSystemDefaultDevice() else { + XCTFail("Metal device is not available.") + return + } + renderInfo.device = device + vertexDescriptor.model = MDLVertexDescriptor() + + gizmoTargets = [] + gizmoSnapProvider = nil + currentMode = .translate + selectedEntities = [] + } + + override func tearDown() { + endGizmoDrag() + removeGizmo() + gizmoTargets = [] + activeHitGizmoEntity = .invalid + gizmoSnapProvider = nil + selectedEntities = [] + super.tearDown() + } + + // MARK: - Helpers + + private func makeBox(_ name: String, at position: simd_float3 = .zero, halfExtent: Float = 0.5) -> EntityID { + let entity = createEntity() + setEntityName(entityId: entity, name: name) + registerTransformComponent(entityId: entity) + registerSceneGraphComponent(entityId: entity) + registerComponent(entityId: entity, componentType: RenderComponent.self) + scene.get(component: LocalTransformComponent.self, for: entity)?.boundingBox = ( + min: simd_float3(repeating: -halfExtent), + max: simd_float3(repeating: halfExtent) + ) + translateTo(entityId: entity, position: position) + return entity + } + + /// A box under a parent turned half around Y and moved away, so that the + /// parent's X and Z point the other way. + private func makeBoxUnderATurnedParent(_ name: String, atWorld position: simd_float3) -> EntityID { + let parent = createEntity() + registerTransformComponent(entityId: parent) + registerSceneGraphComponent(entityId: parent) + translateTo(entityId: parent, position: simd_float3(5, 0, 0)) + rotateTo(entityId: parent, rotation: simd_quatf(angle: .pi, axis: simd_float3(0, 1, 0))) + + let child = makeBox(name) + setParent(childId: child, parentId: parent) + translateTo(entityId: child, position: localPosition(ofWorld: position, for: child)) + return child + } + + private func handle(_ mode: TransformManipulationMode, _ axis: TransformAxis) -> EntityID { + getEntityChildren(parentId: parentEntityIdGizmo).first(where: { + guard let handle = scene.get(component: GizmoHandleComponent.self, for: $0) else { return false } + return handle.mode == mode && handle.axis == axis + }) ?? .invalid + } + + /// A ray that meets the X axis through the gizmo at `amount` along it. + private func rayOnX(at amount: Float) -> GizmoDragRay { + GizmoDragRay(origin: simd_float3(amount, 50, 0), direction: simd_float3(0, -1, 0)) + } + + private func assertNearlyEqual(_ lhs: simd_float3, _ rhs: simd_float3, accuracy: Float = 0.001, message: String = "", file: StaticString = #filePath, line: UInt = #line) { + XCTAssertEqual(lhs.x, rhs.x, accuracy: accuracy, message, file: file, line: line) + XCTAssertEqual(lhs.y, rhs.y, accuracy: accuracy, message, file: file, line: line) + XCTAssertEqual(lhs.z, rhs.z, accuracy: accuracy, message, file: file, line: line) + } + + /// What an entity's own X axis points along in the world. + private func worldXAxis(of entityId: EntityID) -> simd_float3 { + simd_act(entityWorldRotation(entityId: entityId), simd_float3(1, 0, 0)) + } + + /// Mirrors the editor's `SelectionManager.selectEntities`/`inspectEntity`: + /// one entity becomes the sole active entity, several become + /// `gizmoTargets` with the last one active, and a gizmo for + /// `currentMode` is (re)created on the result — same as the editor's + /// `createGizmo(forTool:)` call from `selectEntity`/`activateSeveral`. + private func select(_ entities: [EntityID]) { + selectedEntities = entities.filter { $0 != .invalid } + + if selectedEntities.count > 1 { + gizmoTargets = selectedEntities + activeEntity = selectedEntities.last ?? .invalid + } else { + gizmoTargets = [] + activeEntity = selectedEntities.first ?? .invalid + } + + if activeEntity != .invalid { + createGizmo(mode: currentMode) + } else { + removeGizmo() + } + } + + /// What `SelectionManager.selectionBounds()` computed: the box around + /// what the selection draws. + private func selectionBounds() -> (min: simd_float3, max: simd_float3)? { + var bounds: (min: simd_float3, max: simd_float3)? + for entity in selectedEntities { + guard let box = worldBoundsOfRenderableHierarchy(entityId: entity) else { continue } + bounds = bounds.map { (simd_min($0.min, box.min), simd_max($0.max, box.max)) } ?? box + } + return bounds + } + + // MARK: - What the gizmo works on + + func test_withOneEntity_theGizmoWorksOnTheActiveOne() { + let box = makeBox("Box") + activeEntity = box + + XCTAssertEqual(gizmoTransformTargets(), [box]) + } + + func test_withNoActiveEntity_itWorksOnNothing() { + gizmoTargets = [makeBox("First"), makeBox("Second")] + activeEntity = .invalid + + XCTAssertEqual(gizmoTransformTargets(), []) + } + + func test_withSeveral_itWorksOnAllOfThem() { + let first = makeBox("First"), second = makeBox("Second") + select([first, second]) + + XCTAssertEqual(gizmoTransformTargets(), [first, second]) + } + + func test_targetsLeftFromAnotherSelection_areNotMoved() { + let first = makeBox("First"), second = makeBox("Second"), other = makeBox("Other") + gizmoTargets = [first, second] + activeEntity = other + + XCTAssertEqual(gizmoTransformTargets(), [other]) + } + + func test_anEntityThatLeftTheScene_isNoTarget() { + let first = makeBox("First"), second = makeBox("Second"), third = makeBox("Third") + select([first, second, third]) + + destroyEntity(entityId: first) + finalizePendingDestroys() + + XCTAssertEqual(gizmoTransformTargets(), [second, third]) + } + + func test_anEntityWithoutItsPlaceInTheWorld_isNoTargetAmongSeveral() { + let first = makeBox("First"), second = makeBox("Second"), third = makeBox("Third") + select([first, second, third]) + + // The engine takes an entity's two transforms away together; a turn + // and a scale of several start from the one taken here. + scene.remove(component: WorldTransformComponent.self, from: first) + + XCTAssertFalse(hasBothTransforms(first)) + XCTAssertEqual(gizmoTransformTargets(), [second, third]) + } + + func test_anEntityTheEngineMade_hasBothTransforms_untilItLeavesTheScene() { + let entity = createEntity() + XCTAssertTrue(hasBothTransforms(entity), "the engine gives an entity the two together") + + destroyEntity(entityId: entity) + finalizePendingDestroys() + + XCTAssertFalse(hasBothTransforms(entity)) + } + + // MARK: - Moving + + func test_aDragOfTheMoveGizmo_carriesEveryEntityTheSameWay() { + let first = makeBox("First", at: simd_float3(-2, 0, 0)) + let second = makeBox("Second", at: simd_float3(2, 1, 0)) + select([first, second]) + let gizmoStart = getPosition(entityId: parentEntityIdGizmo) + + activeHitGizmoEntity = handle(.translate, .x) + XCTAssertNotEqual(activeHitGizmoEntity, .invalid) + beginGizmoDrag(ray: rayOnX(at: 0)) + updateGizmoDrag(ray: rayOnX(at: 3)) + updateGizmoDrag(ray: rayOnX(at: 1.5)) + + assertNearlyEqual(getPosition(entityId: first), simd_float3(-0.5, 0, 0)) + assertNearlyEqual(getPosition(entityId: second), simd_float3(3.5, 1, 0)) + assertNearlyEqual(getPosition(entityId: parentEntityIdGizmo), gizmoStart + simd_float3(1.5, 0, 0)) + } + + func test_anEntityUnderATurnedParent_goesTheSameWayInTheWorld() { + let root = makeBox("Root", at: simd_float3(-2, 0, 0)) + let child = makeBoxUnderATurnedParent("Child", atWorld: simd_float3(2, 0, 3)) + assertNearlyEqual(getPosition(entityId: child), simd_float3(2, 0, 3)) + select([root, child]) + + activeHitGizmoEntity = handle(.translate, .x) + beginGizmoDrag(ray: rayOnX(at: 0)) + updateGizmoDrag(ray: rayOnX(at: 2)) + + assertNearlyEqual(getPosition(entityId: root), simd_float3(0, 0, 0)) + assertNearlyEqual(getPosition(entityId: child), simd_float3(4, 0, 3)) + } + + func test_movingWithSnapping_landsAllOfThemOnTheSameSteps() { + gizmoSnapProvider = TestSnapProvider(translateStep: 0.5, rotateStep: nil) + let first = makeBox("First", at: simd_float3(-2, 0, 0)) + let second = makeBox("Second", at: simd_float3(2.2, 0, 0)) + select([first, second]) + + activeHitGizmoEntity = handle(.translate, .x) + beginGizmoDrag(ray: rayOnX(at: 0)) + updateGizmoDrag(ray: rayOnX(at: 1.3)) + + assertNearlyEqual(getPosition(entityId: first), simd_float3(-0.5, 0, 0), message: "1.3 is nearest to three steps of a half") + assertNearlyEqual(getPosition(entityId: second), simd_float3(3.7, 0, 0)) + } + + func test_aMoveFromTheKeys_carriesAllOfThem() { + let first = makeBox("First", at: simd_float3(-2, 0, 0)) + let second = makeBoxUnderATurnedParent("Second", atWorld: simd_float3(2, 0, 0)) + select([first, second]) + + applyGizmoTranslation(byWorld: simd_float3(0, 0, 1.5)) + + assertNearlyEqual(getPosition(entityId: first), simd_float3(-2, 0, 1.5)) + assertNearlyEqual(getPosition(entityId: second), simd_float3(2, 0, 1.5)) + } + + func test_aMoveFromTheKeys_withOneEntity_movesThatOne() { + let box = makeBox("Box", at: simd_float3(1, 0, 0)) + let other = makeBox("Other", at: simd_float3(5, 0, 0)) + select([box]) + + applyGizmoTranslation(byWorld: simd_float3(0, 2, 0)) + + assertNearlyEqual(getPosition(entityId: box), simd_float3(1, 2, 0)) + assertNearlyEqual(getPosition(entityId: other), simd_float3(5, 0, 0)) + } + + // MARK: - Turning + + func test_aTurn_takesThemRoundTheGizmo_andTurnsEachTheSame() { + let first = makeBox("First", at: simd_float3(-2, 0, 0)) + let second = makeBox("Second", at: simd_float3(2, 0, 0)) + currentMode = .rotate + select([first, second]) + assertNearlyEqual(gizmoRootWorldPosition(), .zero) + + applyGizmoRotation(axis: simd_float3(0, 1, 0), degrees: 90) + + // A quarter turn about Y takes +X to -Z. + assertNearlyEqual(getPosition(entityId: first), simd_float3(0, 0, 2)) + assertNearlyEqual(getPosition(entityId: second), simd_float3(0, 0, -2)) + assertNearlyEqual(worldXAxis(of: first), simd_float3(0, 0, -1)) + assertNearlyEqual(worldXAxis(of: second), simd_float3(0, 0, -1)) + } + + func test_aTurn_underATurnedParent_isTheSameTurnInTheWorld() { + let root = makeBox("Root", at: simd_float3(-2, 0, 0)) + let child = makeBoxUnderATurnedParent("Child", atWorld: simd_float3(2, 0, 0)) + let childAxisBefore = worldXAxis(of: child) + assertNearlyEqual(childAxisBefore, simd_float3(-1, 0, 0)) + currentMode = .rotate + select([root, child]) + + applyGizmoRotation(axis: simd_float3(0, 1, 0), degrees: 90) + + assertNearlyEqual(getPosition(entityId: root), simd_float3(0, 0, 2)) + assertNearlyEqual(getPosition(entityId: child), simd_float3(0, 0, -2)) + assertNearlyEqual(worldXAxis(of: child), simd_float3(0, 0, 1), message: "its own X pointed to -X, and turned a quarter like the rest") + } + + func test_smallTurns_addUpToTheWholeTurn() { + let first = makeBox("First", at: simd_float3(-2, 0, 0)) + let second = makeBox("Second", at: simd_float3(2, 0, 0)) + currentMode = .rotate + select([first, second]) + + for _ in 0 ..< 36 { + applyGizmoRotation(axis: simd_float3(0, 0, 1), degrees: 5) + } + + // Half a turn about Z. + assertNearlyEqual(getPosition(entityId: first), simd_float3(2, 0, 0), accuracy: 0.01) + assertNearlyEqual(getPosition(entityId: second), simd_float3(-2, 0, 0), accuracy: 0.01) + XCTAssertEqual(simd_distance(getPosition(entityId: first), getPosition(entityId: second)), 4, accuracy: 0.01, "they keep their distance") + } + + func test_aTurn_withOneEntity_turnsItWhereItStands() { + let box = makeBox("Box", at: simd_float3(3, 0, 0)) + currentMode = .rotate + select([box]) + + applyGizmoRotation(axis: simd_float3(0, 1, 0), degrees: 90) + + assertNearlyEqual(getPosition(entityId: box), simd_float3(3, 0, 0)) + assertNearlyEqual(worldXAxis(of: box), simd_float3(0, 0, -1)) + } + + // MARK: - Scaling + + func test_theFactor_isOneMoreThanTheDrag_andNeverNothing() { + XCTAssertEqual(gizmoGroupScaleFactor(forAmount: 0), 1) + XCTAssertEqual(gizmoGroupScaleFactor(forAmount: 1), 2) + XCTAssertEqual(gizmoGroupScaleFactor(forAmount: -0.5), 0.5) + XCTAssertEqual(gizmoGroupScaleFactor(forAmount: -3), gizmoMinimumScale) + XCTAssertEqual(gizmoGroupScaleFactor(forAmount: .nan), 1) + } + + func test_aDragOfTheScaleGizmo_growsThem_andTheirDistanceFromIt() { + let first = makeBox("First", at: simd_float3(-2, 0, 0)) + let second = makeBox("Second", at: simd_float3(2, 1, 0)) + currentMode = .scale + select([first, second]) + let pivot = gizmoRootWorldPosition() + assertNearlyEqual(pivot, simd_float3(0, 0.5, 0)) + + activeHitGizmoEntity = handle(.scale, .x) + XCTAssertNotEqual(activeHitGizmoEntity, .invalid) + beginGizmoDrag(ray: rayOnX(at: 0)) + updateGizmoDrag(ray: rayOnX(at: 0.4)) + updateGizmoDrag(ray: rayOnX(at: 1)) + + // Twice the size along X, from where they stood: not 1.4 times and then more. + assertNearlyEqual(getPosition(entityId: first), simd_float3(-4, 0, 0)) + assertNearlyEqual(getPosition(entityId: second), simd_float3(4, 1, 0)) + assertNearlyEqual(getScale(entityId: first), simd_float3(2, 1, 1)) + assertNearlyEqual(getScale(entityId: second), simd_float3(2, 1, 1)) + } + + func test_aTurnedEntity_growsAlongItsOwnAxisThatLiesAlongTheGizmos() { + let first = makeBox("First", at: simd_float3(-2, 0, 0)) + let turned = makeBox("Turned", at: simd_float3(2, 0, 0)) + // A quarter turn about Y: its own Z lies along the world's X. + rotateTo(entityId: turned, rotation: simd_quatf(angle: .pi / 2, axis: simd_float3(0, 1, 0))) + currentMode = .scale + select([first, turned]) + + activeHitGizmoEntity = handle(.scale, .x) + beginGizmoDrag(ray: rayOnX(at: 0)) + updateGizmoDrag(ray: rayOnX(at: 0.5)) + + assertNearlyEqual(getScale(entityId: first), simd_float3(1.5, 1, 1)) + assertNearlyEqual(getScale(entityId: turned), simd_float3(1, 1, 1.5)) + } + + func test_aLight_movesWithTheRest_andKeepsItsSize() { + let box = makeBox("Box", at: simd_float3(-2, 0, 0)) + let light = makeBox("Light", at: simd_float3(2, 0, 0)) + registerComponent(entityId: light, componentType: LightComponent.self) + currentMode = .scale + select([box, light]) + + activeHitGizmoEntity = handle(.scale, .x) + beginGizmoDrag(ray: rayOnX(at: 0)) + updateGizmoDrag(ray: rayOnX(at: 1)) + + assertNearlyEqual(getPosition(entityId: light), simd_float3(4, 0, 0)) + assertNearlyEqual(getScale(entityId: light), simd_float3(1, 1, 1)) + assertNearlyEqual(getScale(entityId: box), simd_float3(2, 1, 1)) + } + + func test_aScaleFromTheKeys_growsThemFromWhereTheyAre() { + let first = makeBox("First", at: simd_float3(-2, 0, 0)) + let second = makeBox("Second", at: simd_float3(2, 0, 0)) + currentMode = .scale + select([first, second]) + + applyGizmoScale(axis: simd_float3(1, 0, 0), amount: 0.5, handle: .x) + applyGizmoScale(axis: simd_float3(1, 0, 0), amount: 0.5, handle: .x) + + assertNearlyEqual(getScale(entityId: first), simd_float3(2.25, 1, 1)) + assertNearlyEqual(getPosition(entityId: second), simd_float3(4.5, 0, 0)) + } + + func test_aScaleFromTheKeys_withOneEntity_isTheEnginesOwn() { + let box = makeBox("Box", at: simd_float3(3, 0, 0)) + currentMode = .scale + select([box]) + + applyGizmoScale(axis: simd_float3(1, 0, 0), amount: 0.5, handle: .x) + + assertNearlyEqual(getScale(entityId: box), simd_float3(1.5, 1, 1)) + assertNearlyEqual(getPosition(entityId: box), simd_float3(3, 0, 0)) + } + + // MARK: - Where the gizmo stands afterwards + + func test_afterADrag_theGizmoIsBackInTheMiddle() { + let first = makeBox("First", at: simd_float3(-2, 0, 0)) + let second = makeBox("Second", at: simd_float3(2, 0, 0), halfExtent: 1) + currentMode = .rotate + select([first, second]) + let pivot = gizmoRootWorldPosition() + assertNearlyEqual(pivot, simd_float3(0.25, 0, 0)) + + applyGizmoRotation(axis: simd_float3(0, 1, 0), degrees: 90) + assertNearlyEqual(gizmoRootWorldPosition(), pivot, message: "during the drag it stays where they turn around") + endGizmoDrag() + + let bounds = selectionBounds() + XCTAssertNotNil(bounds) + if let bounds { + assertNearlyEqual(gizmoRootWorldPosition(), (bounds.min + bounds.max) * 0.5) + } + } + + // MARK: - A point as the parent measures it + + func test_aPointOfTheWorld_asTheParentMeasuresIt() { + let child = makeBoxUnderATurnedParent("Child", atWorld: simd_float3(4, 0, 0)) + + // The parent stands at (5, 0, 0), turned half around Y. + assertNearlyEqual(localPosition(ofWorld: simd_float3(4, 2, 3), for: child), simd_float3(1, 2, -3)) + + let root = makeBox("Root") + assertNearlyEqual(localPosition(ofWorld: simd_float3(4, 2, 3), for: root), simd_float3(4, 2, 3)) + } +} diff --git a/Tests/UntoldEngineTests/GizmoPaletteTests.swift b/Tests/UntoldEngineTests/GizmoPaletteTests.swift new file mode 100644 index 000000000..0b344e515 --- /dev/null +++ b/Tests/UntoldEngineTests/GizmoPaletteTests.swift @@ -0,0 +1,49 @@ +// +// GizmoPaletteTests.swift +// UntoldEngine +// +// Copyright (C) Untold Engine Studios +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +// These unit tests were jump-started with AI assistance — then refined by humans. If you spot an issue, please submit an issue. + +import simd +@testable import UntoldEngine +import XCTest + +/// The gizmo's colours are the spec's, handed to the engine as light. +final class GizmoPaletteTests: XCTestCase { + /// The sRGB curve the other way, from light to what the screen shows. + private func display(fromLinear value: Float) -> Float { + value <= 0.0031308 ? value * 12.92 : 1.055 * pow(value, 1 / 2.4) - 0.055 + } + + private func assertShows(_ color: simd_float4, as hex: UInt32, file: StaticString = #filePath, line: UInt = #line) { + XCTAssertEqual(Int((display(fromLinear: color.x) * 255).rounded()), Int((hex >> 16) & 0xFF), "red", file: file, line: line) + XCTAssertEqual(Int((display(fromLinear: color.y) * 255).rounded()), Int((hex >> 8) & 0xFF), "green", file: file, line: line) + XCTAssertEqual(Int((display(fromLinear: color.z) * 255).rounded()), Int(hex & 0xFF), "blue", file: file, line: line) + XCTAssertEqual(color.w, 1, file: file, line: line) + } + + func test_theColours_areTheSpecsOnTheScreen() { + assertShows(GizmoPalette.x, as: 0xFF5A5A) + assertShows(GizmoPalette.y, as: 0x5CE08C) + assertShows(GizmoPalette.z, as: 0x4C8DFF) + assertShows(GizmoPalette.center, as: 0xFFFFFF) + } + + func test_theCurve_holdsAtItsEnds() { + XCTAssertEqual(GizmoPalette.linear(fromDisplay: 0), 0) + XCTAssertEqual(GizmoPalette.linear(fromDisplay: 1), 1, accuracy: 0.0001) + XCTAssertEqual(GizmoPalette.linear(fromDisplay: 0.5), 0.2140, accuracy: 0.0005) + } + + func test_everyColour_isBrightEnoughForTheEngineToDrawIt() { + for color in [GizmoPalette.x, GizmoPalette.y, GizmoPalette.z, GizmoPalette.center] { + XCTAssertGreaterThan(GizmoPalette.engineLuminance(of: color), GizmoPalette.engineLuminanceFloor * 1.5) + } + } +} diff --git a/Tests/UntoldEngineTests/GizmoRenderPassTests.swift b/Tests/UntoldEngineTests/GizmoRenderPassTests.swift new file mode 100644 index 000000000..3aea77549 --- /dev/null +++ b/Tests/UntoldEngineTests/GizmoRenderPassTests.swift @@ -0,0 +1,137 @@ +// +// GizmoRenderPassTests.swift +// UntoldEngineTests +// +// Copyright (C) Untold Engine Studios +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +// Covers Renderer/GizmoRenderPass.swift: pipeline registration and the render +// extension's bookkeeping. This is the piece that can silently "succeed" with +// no crash and no visible gizmo if the pipeline never actually comes up (e.g. a +// missing shader library, or a host that forgets to call +// `registerGizmoRenderExtension()`), so these tests check the registration +// outcome directly rather than relying on a GPU image diff. + +@testable import UntoldEngine +import XCTest + +@MainActor +final class GizmoRenderPassTests: XCTestCase { + private var originalDevice: MTLDevice? + private var originalLibrary: MTLLibrary? + private var originalColorPixelFormat: MTLPixelFormat? + private var originalDepthPixelFormat: MTLPixelFormat? + + override func setUp() { + super.setUp() + resetEngineTestState() + + originalDevice = renderInfo.device + originalLibrary = renderInfo.library + originalColorPixelFormat = renderInfo.colorPixelFormat + originalDepthPixelFormat = renderInfo.depthPixelFormat + + guard let device = MTLCreateSystemDefaultDevice() else { + XCTFail("Metal device is not available.") + return + } + + renderInfo.device = device + renderInfo.colorPixelFormat = .rgba16Float + renderInfo.depthPixelFormat = .depth32Float + + // The gizmo pipeline's shaders ("vertexGizmoShader"/"fragmentGizmoShader") + // live in the engine's bundled metallib (resolved via + // RenderShaderLibraryReference.engine -> renderInfo.library), the same + // path `UntoldRenderer.create()` uses in a real app. Load it the same way + // here so pipeline creation has a real chance to succeed in a headless + // test, rather than mocking it away. + do { + renderInfo.library = try device.makeLibraryFromBundle() + } catch { + XCTFail("Failed to load the engine metallib: \(error)") + } + } + + override func tearDown() { + renderInfo.device = originalDevice + renderInfo.library = originalLibrary + renderInfo.colorPixelFormat = originalColorPixelFormat + renderInfo.depthPixelFormat = originalDepthPixelFormat + RenderExtensionRegistry.shared.removeAll() + // Scoped to the synthetic owner used by + // test_registerGizmoPipeline_createsAWorkingGizmoPipeline below so that + // test's unscoped-vs-owned pipeline bookkeeping never leaks into another + // test that registers `.gizmo` through `GizmoRenderExtension` (owned by + // "untold.gizmo") — PipelineManager treats those as two different owners. + PipelineManager.shared.removePipelines(ownerID: directPipelineRegistrationOwnerID) + super.tearDown() + } + + private let directPipelineRegistrationOwnerID = "test.gizmo.directRegistration" + + func test_GizmoRenderExtension_hasStableId() { + XCTAssertEqual(GizmoRenderExtension.shared.id, "untold.gizmo") + } + + /// The single most valuable test here: proves the `.gizmo` pipeline actually + /// comes up successfully given the same renderInfo state a real app has by the + /// time it registers render extensions. A regression here (e.g. a shader + /// rename, a vertex-descriptor mismatch) would otherwise silently leave + /// `renderPipelinesByType[.gizmo]` either missing or `.success == false`, and + /// nothing would crash — the gizmo would just never draw. + func test_registerGizmoPipeline_createsAWorkingGizmoPipeline() { + // Scoped under a synthetic owner id (rather than calling + // `registerGizmoPipeline` completely unscoped) so the pipeline this test + // creates can be cleanly removed in tearDown and never conflicts with + // `GizmoRenderExtension`'s own, separately-owned registration in another test. + PipelineManager.shared.registerPipelines(ownerID: directPipelineRegistrationOwnerID) { registry in + registerGizmoPipeline(registry) + } + + let pipeline = PipelineManager.shared.renderPipelinesByType[.gizmo] + XCTAssertNotNil(pipeline, "Expected a .gizmo pipeline to be registered") + XCTAssertEqual(pipeline?.success, true, "Expected the .gizmo pipeline to report success") + XCTAssertNotNil(pipeline?.pipelineState) + } + + func test_registerGizmoRenderExtension_returnsRegistered() { + XCTAssertEqual(registerGizmoRenderExtension(), .registered) + + // Re-registering the same shared instance is the hot-swap path (same id), + // which RenderExtensionRegistry treats as a `.replaced`-style re-registration + // rather than a conflict, so calling this more than once across the test + // suite (or across app restarts) is safe. + XCTAssertEqual(registerGizmoRenderExtension(), .registered) + + let pipeline = PipelineManager.shared.renderPipelinesByType[.gizmo] + XCTAssertEqual(pipeline?.success, true) + + RenderExtensionRegistry.shared.unregister(id: GizmoRenderExtension.shared.id) + } + + /// `GizmoRenderExtension.buildGraph` must register its "untold.gizmo" pass + /// exactly once per call. `RenderGraphBuilder` flags a second `addPass` call + /// for the same id, issued while the same extension id is the current + /// registrant, as a conflict — so a clean (empty) conflict/error report after + /// one `buildGraph` call proves it isn't double-adding the pass. This checks + /// the bookkeeping only; it does not execute any GPU draw calls. + func test_GizmoRenderExtension_buildGraph_addsAPassOnlyOnce() { + var builder = RenderGraphBuilder() + let context = RenderGraphBuildContext( + viewport: SIMD2(640, 480), + immersionStyle: .none, + currentEye: 0 + ) + + builder.beginExtensionRegistration(id: GizmoRenderExtension.shared.id) + GizmoRenderExtension.shared.buildGraph(&builder, context: context) + let report = builder.endExtensionRegistration() + + XCTAssertTrue(report.conflicts.isEmpty, "buildGraph should not register a conflicting/duplicate pass") + XCTAssertTrue(report.validationErrors.isEmpty) + } +} diff --git a/Tests/UntoldEngineTests/GizmoSpaceTests.swift b/Tests/UntoldEngineTests/GizmoSpaceTests.swift new file mode 100644 index 000000000..fd4c987fa --- /dev/null +++ b/Tests/UntoldEngineTests/GizmoSpaceTests.swift @@ -0,0 +1,101 @@ +// +// GizmoSpaceTests.swift +// UntoldEngine +// +// Copyright (C) Untold Engine Studios +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +// These unit tests were jump-started with AI assistance — then refined by humans. If you spot an issue, please submit an issue. + +import simd +@testable import UntoldEngine +import XCTest + +private struct TestSnapProvider: GizmoSnapProvider { + var translateStep: Float? + var rotateStep: Float? + + func snapStep(for mode: TransformManipulationMode) -> Float? { + switch mode { + case .translate, .scale: + return translateStep + case .rotate: + return rotateStep + default: + return nil + } + } +} + +/// The gizmo's axes in Local space and the snapping of a rotation drag. +@MainActor +final class GizmoSpaceTests: XCTestCase { + override func setUp() { + super.setUp() + resetEngineTestState() + activeEntity = .invalid + gizmoSnapProvider = nil + } + + override func tearDown() { + endGizmoDrag() + gizmoSnapProvider = nil + super.tearDown() + } + + private func entity(rotatedBy degrees: Float, about axis: simd_float3, parent: EntityID? = nil) -> EntityID { + let entity = createEntity() + registerComponent(entityId: entity, componentType: LocalTransformComponent.self) + registerComponent(entityId: entity, componentType: WorldTransformComponent.self) + registerComponent(entityId: entity, componentType: ScenegraphComponent.self) + if let parent { + setParent(childId: entity, parentId: parent) + } + if degrees != 0 { + applyGizmoRotationDelta(entityId: entity, axis: axis, degrees: degrees) + } + return entity + } + + private func assertEqual(_ vector: simd_float3, _ expected: simd_float3, file: StaticString = #filePath, line: UInt = #line) { + XCTAssertEqual(vector.x, expected.x, accuracy: 0.0001, file: file, line: line) + XCTAssertEqual(vector.y, expected.y, accuracy: 0.0001, file: file, line: line) + XCTAssertEqual(vector.z, expected.z, accuracy: 0.0001, file: file, line: line) + } + + func test_localAxis_followsTheEntitysRotation_worldAxisDoesNot() { + let entity = entity(rotatedBy: 90, about: simd_float3(0, 1, 0)) + assertEqual(gizmoAxisDirection(for: .x, entityId: entity, space: .local), simd_float3(0, 0, -1)) + assertEqual(gizmoAxisDirection(for: .y, entityId: entity, space: .local), simd_float3(0, 1, 0)) + assertEqual(gizmoAxisDirection(for: .x, entityId: entity, space: .world), simd_float3(1, 0, 0)) + } + + func test_localAxis_includesTheParentsRotation() { + let parent = entity(rotatedBy: 90, about: simd_float3(0, 1, 0)) + let child = entity(rotatedBy: 0, about: simd_float3(0, 1, 0), parent: parent) + assertEqual(gizmoAxisDirection(for: .x, entityId: child, space: .local), simd_float3(0, 0, -1)) + } + + func test_rotationSnap_appliesWholeStepsOfTheAccumulatedTurn() { + gizmoSnapProvider = TestSnapProvider(translateStep: nil, rotateStep: 15) + beginGizmoRotationDrag() + + XCTAssertEqual(snappedGizmoRotationDelta(degrees: 4), 0, "4° is nearer to 0 than to 15") + XCTAssertEqual(snappedGizmoRotationDelta(degrees: 4), 15, "8° accumulated rounds to the first step") + XCTAssertEqual(snappedGizmoRotationDelta(degrees: 4), 0, "12° stays on it") + XCTAssertEqual(snappedGizmoRotationDelta(degrees: 4), 0, "16° too") + XCTAssertEqual(snappedGizmoRotationDelta(degrees: 8), 15, "24° accumulated rounds to the second") + + endGizmoDrag() + XCTAssertEqual(snappedGizmoRotationDelta(degrees: 4), 4, "No drag, no accumulation") + } + + func test_rotationSnap_off_passesTheRawDelta() { + beginGizmoRotationDrag() + XCTAssertEqual(snappedGizmoRotationDelta(degrees: 4), 4) + XCTAssertEqual(snappedGizmoRotationDelta(degrees: -2.5), -2.5) + } +} diff --git a/Tests/UntoldEngineTests/GizmoSystemTests.swift b/Tests/UntoldEngineTests/GizmoSystemTests.swift new file mode 100644 index 000000000..1ee750c1b --- /dev/null +++ b/Tests/UntoldEngineTests/GizmoSystemTests.swift @@ -0,0 +1,790 @@ +// +// GizmoSystemTests.swift +// UntoldEngine +// +// Copyright (C) Untold Engine Studios +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +// These unit tests were jump-started with AI assistance — then refined by humans. If you spot an issue, please submit an issue. + +import ModelIO +@testable import UntoldEngine +import XCTest + +@MainActor +final class GizmoSystemTests: XCTestCase { + private var originalParentGizmo: EntityID! + private var originalGizmoActive: Bool! + private var originalActiveHitGizmoEntity: EntityID! + private var originalDirectionHandleEntityId: EntityID! + private var originalActiveCamera: EntityID? + private var originalViewport: simd_float2? + + override func setUp() { + super.setUp() + resetEngineTestState() + + originalParentGizmo = parentEntityIdGizmo + originalGizmoActive = gizmoActive + originalActiveHitGizmoEntity = activeHitGizmoEntity + originalDirectionHandleEntityId = directionHandleEntityId + originalActiveCamera = CameraSystem.shared.activeCamera + originalViewport = renderInfo.viewPort + + // Put engine in a clean state + parentEntityIdGizmo = .invalid + gizmoActive = false + activeHitGizmoEntity = .invalid + directionHandleEntityId = .invalid + + guard let device = MTLCreateSystemDefaultDevice() else { + assertionFailure("Metal device is not available.") + return + } + + renderInfo.device = device + vertexDescriptor.model = MDLVertexDescriptor() + } + + override func tearDown() { + if parentEntityIdGizmo != .invalid { + removeGizmo() + } + endGizmoDrag() + parentEntityIdGizmo = originalParentGizmo + gizmoActive = originalGizmoActive + activeHitGizmoEntity = originalActiveHitGizmoEntity + directionHandleEntityId = originalDirectionHandleEntityId + CameraSystem.shared.activeCamera = originalActiveCamera + renderInfo.viewPort = originalViewport + + super.tearDown() + } + + // MARK: - Helpers + + private func makeEntity(name: String? = nil, + pos: SIMD3? = nil, + isLight: Bool = false) -> EntityID + { + let e = createEntity() + if !hasComponent(entityId: e, componentType: LocalTransformComponent.self) { + registerTransformComponent(entityId: e) + } + if let name { setEntityName(entityId: e, name: name) } + if let p = pos { translateTo(entityId: e, position: p) } + if isLight { registerComponent(entityId: e, componentType: LightComponent.self) } + return e + } + + private func makeCamera(eye: SIMD3, target: SIMD3 = .zero) -> EntityID { + let camera = createEntity() + createGameCamera(entityId: camera) + cameraLookAt(entityId: camera, eye: eye, target: target, up: cameraUpDefault) + CameraSystem.shared.activeCamera = camera + return camera + } + + private func makeGizmoHandle(mode: TransformManipulationMode, axis: TransformAxis) -> EntityID { + let e = makeEntity(name: "metadataHandle") + registerComponent(entityId: e, componentType: GizmoComponent.self) + let handle = scene.assign(to: e, component: GizmoHandleComponent.self) + handle?.mode = mode + handle?.axis = axis + return e + } + + private func findGizmoHandle(mode: TransformManipulationMode, axis: TransformAxis) -> EntityID { + getEntityChildren(parentId: parentEntityIdGizmo).first(where: { + guard let handle = scene.get(component: GizmoHandleComponent.self, for: $0) else { return false } + return handle.mode == mode && handle.axis == axis + }) ?? .invalid + } + + private func rayThroughGizmoAxis(_ axis: TransformAxis, amount: Float) -> GizmoDragRay { + switch axis { + case .x: + return GizmoDragRay(origin: SIMD3(amount, 1.0, 0.0), direction: SIMD3(0.0, -1.0, 0.0)) + case .y: + return GizmoDragRay(origin: SIMD3(1.0, amount, 0.0), direction: SIMD3(-1.0, 0.0, 0.0)) + case .z: + return GizmoDragRay(origin: SIMD3(0.0, 1.0, amount), direction: SIMD3(0.0, -1.0, 0.0)) + case .none: + return GizmoDragRay(origin: SIMD3(0.0, 1.0, 0.0), direction: SIMD3(0.0, -1.0, 0.0)) + } + } + + private func vector(for axis: TransformAxis, amount: Float) -> SIMD3 { + switch axis { + case .x: + return SIMD3(amount, 0.0, 0.0) + case .y: + return SIMD3(0.0, amount, 0.0) + case .z: + return SIMD3(0.0, 0.0, amount) + case .none: + return .zero + } + } + + private func component(of vector: SIMD3, along axis: TransformAxis) -> Float { + switch axis { + case .x: + return vector.x + case .y: + return vector.y + case .z: + return vector.z + case .none: + return 0.0 + } + } + + private func assertNearlyEqual(_ lhs: simd_float3, _ rhs: simd_float3, accuracy: Float = 0.0001, file: StaticString = #filePath, line: UInt = #line) { + XCTAssertEqual(lhs.x, rhs.x, accuracy: accuracy, file: file, line: line) + XCTAssertEqual(lhs.y, rhs.y, accuracy: accuracy, file: file, line: line) + XCTAssertEqual(lhs.z, rhs.z, accuracy: accuracy, file: file, line: line) + } + + // MARK: - createGizmo() + + func test_createGizmo_noActiveEntity_doesNothing() { + activeEntity = .invalid + createGizmo(name: "translateGizmo") + + XCTAssertEqual(parentEntityIdGizmo, .invalid, "No gizmo should be created without an active entity.") + XCTAssertFalse(gizmoActive, "gizmoActive should remain false.") + } + + func test_createGizmo_createsParentAndActivatesAtActiveEntityPosition() { + // Arrange: active entity at a known spot + let active = makeEntity(name: "Cube", pos: SIMD3(1, 2, 3)) + activeEntity = active + + // Act + createGizmo(name: "translateGizmo") + + // Assert + XCTAssertNotEqual(parentEntityIdGizmo, .invalid, "Gizmo parent should be created.") + XCTAssertTrue(gizmoActive, "gizmoActive should be true after creation.") + + // Must have these components + XCTAssertTrue(hasComponent(entityId: parentEntityIdGizmo, componentType: GizmoComponent.self), + "Gizmo parent must have GizmoComponent.") + + XCTAssertTrue(hasComponent(entityId: parentEntityIdGizmo, componentType: LocalTransformComponent.self), + "Gizmo parent must have Transform.") + XCTAssertTrue(hasComponent(entityId: parentEntityIdGizmo, componentType: ScenegraphComponent.self), + "Gizmo parent must have SceneGraph.") + + // Position should match active entity + XCTAssertEqual(getPosition(entityId: parentEntityIdGizmo), + getPosition(entityId: active), + "Gizmo should be placed at active entity's position.") + } + + func test_createGizmo_appliesScreenSpaceScaleImmediatelyForFarEntity() throws { + renderInfo.viewPort = simd_float2(1280.0, 720.0) + let camera = makeCamera(eye: simd_float3(0.0, 0.0, 0.0)) + let active = makeEntity(name: "FarCube", pos: SIMD3(0.0, 0.0, -60.0)) + activeEntity = active + + createGizmo(name: "translateGizmo") + + let expectedScale = gizmoWorldScaleForScreenSize( + cameraEntityId: camera, + gizmoWorldPosition: getPosition(entityId: parentEntityIdGizmo), + viewport: renderInfo.viewPort + ) + XCTAssertNotNil(expectedScale) + XCTAssertEqual(getScale(entityId: parentEntityIdGizmo).x, try XCTUnwrap(expectedScale), accuracy: 0.0001) + XCTAssertGreaterThan(getScale(entityId: parentEntityIdGizmo).x, 1.0) + } + + func test_createGizmo_overridesNameForLightEntities() { + let light = makeEntity(name: "KeyLight", pos: SIMD3(0, 0, 0), isLight: true) + activeEntity = light + + // Passing any name; LightComponent should force "translateGizmo_light" internally. + createGizmo(name: "translateGizmo") + + XCTAssertNotEqual(parentEntityIdGizmo, .invalid, "Gizmo should be created for lights too.") + XCTAssertTrue(gizmoActive) + } + + func test_createGizmo_usesMeshLocalOffsetForAnchorPosition() { + let active = makeEntity(name: "ImportedChild", pos: SIMD3(0, 0, 0)) + var meshes = BasicPrimitives.createCube() + XCTAssertFalse(meshes.isEmpty, "Expected primitive mesh for test setup.") + + let meshOffset = simd_float3(3.0, 4.0, 5.0) + meshes[0].localSpace = matrix4x4Translation(meshOffset.x, meshOffset.y, meshOffset.z) + meshes[0].worldSpace = meshes[0].localSpace + + let dummyURL = URL(fileURLWithPath: "/tmp/gizmo-anchor-test") + associateMeshesToEntity(entityId: active, meshes: meshes) + registerRenderComponent(entityId: active, meshes: meshes, url: dummyURL, assetName: "ImportedChild") + + activeEntity = active + createGizmo(name: "translateGizmo") + + XCTAssertEqual(getLocalPosition(entityId: parentEntityIdGizmo), meshOffset, + "Gizmo should anchor at rendered mesh pivot when entity transform is zero.") + } + + func test_createGizmo_usesRenderableChildrenBounds_whenSelectedEntityHasNoRenderComponent() { + let parent = makeEntity(name: "ImportedRoot", pos: SIMD3(0, 0, 0)) + let child = makeEntity(name: "ImportedChild", pos: SIMD3(0, 0, 0)) + setParent(childId: child, parentId: parent) + + var meshes = BasicPrimitives.createCube() + XCTAssertFalse(meshes.isEmpty, "Expected primitive mesh for test setup.") + + let meshOffset = simd_float3(6.0, 2.0, -3.0) + meshes[0].localSpace = matrix4x4Translation(meshOffset.x, meshOffset.y, meshOffset.z) + meshes[0].worldSpace = meshes[0].localSpace + + let dummyURL = URL(fileURLWithPath: "/tmp/gizmo-parent-anchor-test") + associateMeshesToEntity(entityId: child, meshes: meshes) + registerRenderComponent(entityId: child, meshes: meshes, url: dummyURL, assetName: "ImportedChild") + + activeEntity = parent + createGizmo(name: "translateGizmo") + + XCTAssertEqual(getLocalPosition(entityId: parentEntityIdGizmo), meshOffset, + "Gizmo should anchor from renderable child bounds when selected entity is a non-render root.") + } + + // MARK: - hitGizmoToolAxis() + + func test_hitGizmoToolAxis_usesHandleMetadata() { + let valid = makeGizmoHandle(mode: .translate, axis: .x) + XCTAssertTrue(hitGizmoToolAxis(entityId: valid), "Expected metadata handle to be recognized.") + + let legacyNameOnly = makeEntity(name: "xAxisTranslate") + XCTAssertFalse(hitGizmoToolAxis(entityId: legacyNameOnly), "Names alone should not make an entity a gizmo handle.") + + let invalid = makeEntity(name: "randomNode") + XCTAssertFalse(hitGizmoToolAxis(entityId: invalid), "Non-gizmo nodes should return false.") + XCTAssertFalse(hitGizmoToolAxis(entityId: .invalid), "Invalid entity must return false.") + } + + // MARK: - processGizmoAction() + + func test_processGizmoAction_setsAxisAndModeForKnownHandles() { + let cases: [(TransformManipulationMode, TransformAxis)] = [ + (.translate, .x), + (.translate, .y), + (.translate, .z), + (.rotate, .x), + (.rotate, .y), + (.rotate, .z), + (.scale, .x), + (.scale, .y), + (.scale, .z), + (.lightRotate, .none), + ] + + for (expMode, expAxis) in cases { + let e = makeGizmoHandle(mode: expMode, axis: expAxis) + processGizmoAction(entityId: e) + + XCTAssertEqual(gizmoHoverAxis, expAxis) + XCTAssertEqual(gizmoHoverMode, expMode) + } + + // Unknown handle → reset to none + let unknown = makeEntity(name: "notAGizmoPart") + processGizmoAction(entityId: unknown) + XCTAssertEqual(gizmoHoverAxis, .none) + XCTAssertEqual(gizmoHoverMode, .none) + } + + /// Regression for a real bug: `processGizmoAction` used to only reset + /// `activeHitGizmoEntity` on a miss, never set it on a hit. Since `beginGizmoDrag` + /// reads that global to find which handle to drag, every drag silently failed. + func test_processGizmoAction_setsActiveHitGizmoEntityOnHit() { + let handle = makeGizmoHandle(mode: .translate, axis: .x) + activeHitGizmoEntity = .invalid + + processGizmoAction(entityId: handle) + + XCTAssertEqual(activeHitGizmoEntity, handle) + } + + func test_processGizmoAction_resetsActiveHitGizmoEntityOnMiss() { + let notAHandle = makeEntity(name: "notAGizmoPart") + activeHitGizmoEntity = notAHandle + + processGizmoAction(entityId: notAHandle) + + XCTAssertEqual(activeHitGizmoEntity, .invalid) + } + + func test_processGizmoAction_earlyReturnOnInvalid() { + // Seed with values that should remain unchanged + let handle = makeGizmoHandle(mode: .translate, axis: .x) + processGizmoAction(entityId: handle) + XCTAssertEqual(gizmoHoverAxis, .x) + XCTAssertEqual(gizmoHoverMode, .translate) + + // Act + processGizmoAction(entityId: .invalid) + + // Assert + XCTAssertEqual(gizmoHoverAxis, .x, "Should not modify axis when entity is invalid.") + XCTAssertEqual(gizmoHoverMode, .translate, "Should not modify mode when entity is invalid.") + } + + // MARK: - removeGizmo() + + func test_removeGizmo_destroysAndResets() { + // Create an active entity and then a gizmo + let active = makeEntity(name: "Box", pos: SIMD3(0, 0, 0)) + activeEntity = active + createGizmo(name: "translateGizmo") + + let gizmoParent = parentEntityIdGizmo + XCTAssertNotEqual(gizmoParent, .invalid) + + // Act + removeGizmo() + + // Assert: back to defaults and parent entity gone + XCTAssertEqual(parentEntityIdGizmo, .invalid) + XCTAssertFalse(gizmoActive) + } + + func test_createGizmo_addsTypedHandleMetadataToChildren() { + let active = makeEntity(name: "Box", pos: SIMD3(0, 0, 0)) + activeEntity = active + + createGizmo(mode: .translate) + + // Every child is a handle but the dot at the centre, which is only drawn. + let children = getEntityChildren(parentId: parentEntityIdGizmo) + .filter { hasComponent(entityId: $0, componentType: GizmoCenterComponent.self) == false } + XCTAssertFalse(children.isEmpty) + XCTAssertTrue(children.allSatisfy { hitGizmoToolAxis(entityId: $0) }) + XCTAssertTrue(children.contains { + guard let handle = scene.get(component: GizmoHandleComponent.self, for: $0) else { return false } + return handle.mode == .translate && handle.axis == .x + }) + } + + func test_everyGizmo_hasAWhiteCenterThatIsDrawnAndNeverPicked() { + let active = makeEntity(name: "Box", pos: SIMD3(2, 0, 0)) + activeEntity = active + + for mode in [GizmoMode.translate, .rotate, .scale] { + createGizmo(mode: mode) + + let centers = getEntityChildren(parentId: parentEntityIdGizmo) + .filter { hasComponent(entityId: $0, componentType: GizmoCenterComponent.self) } + XCTAssertEqual(centers.count, 1, "\(mode)") + guard let center = centers.first else { continue } + + XCTAssertTrue(hasComponent(entityId: center, componentType: GizmoComponent.self), "drawn with the gizmo") + XCTAssertFalse(hitGizmoToolAxis(entityId: center), "no handle") + XCTAssertFalse(getEntityPickParticipation(entityId: center), "picking passes through it") + assertNearlyEqual(getPosition(entityId: center), getPosition(entityId: parentEntityIdGizmo)) + + let material = scene.get(component: RenderComponent.self, for: center)?.mesh.first?.submeshes.first?.material + XCTAssertEqual(material?.baseColorValue, GizmoPalette.center) + removeGizmo() + } + } + + func test_theHandles_takeTheColoursOfTheSpec() { + let active = makeEntity(name: "Box", pos: SIMD3(0, 0, 0)) + activeEntity = active + createGizmo(mode: .translate) + + let expected: [TransformAxis: simd_float4] = [.x: GizmoPalette.x, .y: GizmoPalette.y, .z: GizmoPalette.z] + for (axis, color) in expected { + let handle = findGizmoHandle(mode: .translate, axis: axis) + let material = scene.get(component: RenderComponent.self, for: handle)?.mesh.first?.submeshes.first?.material + XCTAssertEqual(material?.baseColorValue, color, "\(axis)") + XCTAssertEqual(material?.interactWithLight, false, "\(axis)") + } + } + + func test_createRotateGizmo_addsHiddenHitProxyHandlesForEveryAxis() { + let active = makeEntity(name: "RotatableBox", pos: SIMD3(0, 0, 0)) + activeEntity = active + + createGizmo(mode: .rotate) + + let children = getEntityChildren(parentId: parentEntityIdGizmo) + for axis in [TransformAxis.x, .y, .z] { + let proxies = children.filter { + guard hasComponent(entityId: $0, componentType: GizmoHitProxyComponent.self), + let handle = scene.get(component: GizmoHandleComponent.self, for: $0) + else { + return false + } + return handle.mode == .rotate && handle.axis == axis + } + + XCTAssertFalse(proxies.isEmpty, "Expected hidden rotate hit proxies for \(axis)-axis.") + } + } + + func test_createGizmo_addsHiddenHitProxyForLightDirectionHandle() { + let light = makeEntity(name: "DirectionalLight", pos: SIMD3(0, 0, 0), isLight: true) + activeEntity = light + + createGizmo(mode: .translate) + + let children = getEntityChildren(parentId: parentEntityIdGizmo) + let proxies = children.filter { + guard hasComponent(entityId: $0, componentType: GizmoHitProxyComponent.self), + let handle = scene.get(component: GizmoHandleComponent.self, for: $0) + else { + return false + } + + return handle.mode == .lightRotate && handle.axis == .none + } + + XCTAssertFalse(proxies.isEmpty, "Expected hidden hit proxy for the light direction handle.") + } + + func test_createGizmo_placesLightDirectionHandleAlongCurrentLightEmissionAfterReselect() { + let light = makeEntity(name: "DirectionalLight", pos: SIMD3(0, 0, 0), isLight: true) + activeEntity = light + rotateTo(entityId: light, angle: 35.0, axis: SIMD3(0.0, 1.0, 0.0)) + rotateTo(entityId: light, angle: -20.0, axis: SIMD3(1.0, 0.0, 0.0)) + + createGizmo(mode: .translate) + removeGizmo() + + createGizmo(mode: .translate) + + let directionHandle = findGizmoHandle(mode: .lightRotate, axis: .none) + guard directionHandle != .invalid else { + XCTFail("Expected light direction handle.") + return + } + + let expectedOffset = simd_normalize(getLightEmissionDirection(entityId: light)) + assertNearlyEqual(getLocalPosition(entityId: directionHandle), expectedOffset, accuracy: 0.0002) + } + + func test_createGizmo_placesLightDirectionHandleFromLocalRotationWhenWorldTransformIsStale() { + let light = makeEntity(name: "DirectionalLight", pos: SIMD3(0, 0, 0), isLight: true) + activeEntity = light + + guard let localTransform = scene.get(component: LocalTransformComponent.self, for: light) else { + XCTFail("Expected LocalTransformComponent for light.") + return + } + + localTransform.rotation = simd_quatf( + angle: degreesToRadians(degrees: 90.0), + axis: SIMD3(0.0, 1.0, 0.0) + ) + + createGizmo(mode: .translate) + + let directionHandle = findGizmoHandle(mode: .lightRotate, axis: .none) + guard directionHandle != .invalid else { + XCTFail("Expected light direction handle.") + return + } + + assertNearlyEqual(getLocalPosition(entityId: directionHandle), SIMD3(-1.0, 0.0, 0.0), accuracy: 0.0002) + } + + func test_createGizmo_placesAreaLightDirectionHandleAlongAreaEmission() { + let area = createEntity() + createAreaLight(entityId: area) + activeEntity = area + + createGizmo(mode: .translate) + + let directionHandle = findGizmoHandle(mode: .lightRotate, axis: .none) + guard directionHandle != .invalid else { + XCTFail("Expected light direction handle.") + return + } + + let expectedOffset = simd_normalize(getLightEmissionDirection(entityId: area)) + assertNearlyEqual(getLocalPosition(entityId: directionHandle), expectedOffset, accuracy: 0.0002) + assertNearlyEqual(expectedOffset, simd_float3(0.0, -1.0, 0.0), accuracy: 0.0002) + } + + func test_gizmoRootWorldPosition_usesGizmoParentWhenAvailable() { + let active = makeEntity(name: "OffsetBox", pos: SIMD3(1, 2, 3)) + activeEntity = active + createGizmo(mode: .translate) + translateTo(entityId: parentEntityIdGizmo, position: SIMD3(9, 8, 7)) + + XCTAssertEqual(gizmoRootWorldPosition(), SIMD3(9, 8, 7)) + } + + func test_axisGizmoDrag_translatesFromCurrentRayConstraint() { + let active = makeEntity(name: "DraggedBox", pos: SIMD3(0, 0, 0)) + activeEntity = active + createGizmo(mode: .translate) + + let xHandle = findGizmoHandle(mode: .translate, axis: .x) + guard xHandle != .invalid else { + XCTFail("Expected x-axis translate handle.") + return + } + + activeHitGizmoEntity = xHandle + beginGizmoDrag( + ray: GizmoDragRay( + origin: SIMD3(0, 1, 0), + direction: SIMD3(0, -1, 0) + ) + ) + updateGizmoDrag( + ray: GizmoDragRay( + origin: SIMD3(2, 1, 0), + direction: SIMD3(0, -1, 0) + ) + ) + + XCTAssertEqual(getLocalPosition(entityId: active), SIMD3(2, 0, 0)) + XCTAssertEqual(getPosition(entityId: parentEntityIdGizmo), SIMD3(2, 0, 0)) + } + + func test_axisGizmoDrag_translationTracksAbsoluteAxisPositionForAllAxes() { + let axes: [TransformAxis] = [.x, .y, .z] + + for axis in axes { + let startPosition = SIMD3(0.25, -0.5, 1.0) + let active = makeEntity(name: "AbsoluteTranslate-\(axis)", pos: startPosition) + activeEntity = active + createGizmo(mode: .translate) + + let handle = findGizmoHandle(mode: .translate, axis: axis) + guard handle != .invalid else { + XCTFail("Expected translate handle for axis \(axis).") + return + } + + activeHitGizmoEntity = handle + let startAxisAmount = component(of: startPosition, along: axis) + beginGizmoDrag(ray: rayThroughGizmoAxis(axis, amount: startAxisAmount)) + updateGizmoDrag(ray: rayThroughGizmoAxis(axis, amount: startAxisAmount + 1.5)) + updateGizmoDrag(ray: rayThroughGizmoAxis(axis, amount: startAxisAmount - 0.75)) + + let expectedEntityPosition = startPosition + vector(for: axis, amount: -0.75) + let expectedGizmoPosition = startPosition + vector(for: axis, amount: -0.75) + assertNearlyEqual(getLocalPosition(entityId: active), expectedEntityPosition) + assertNearlyEqual(getPosition(entityId: parentEntityIdGizmo), expectedGizmoPosition) + + endGizmoDrag() + removeGizmo() + } + } + + /// A child under a parent turned half around Y, as an object exported with + /// its orientation converted: the parent's X and Z point the other way. + private func makeChildOfATurnedParent() -> EntityID { + let parent = makeEntity(name: "TurnedParent", pos: SIMD3(5, 0, 0)) + rotateTo(entityId: parent, rotation: simd_quatf(angle: .pi, axis: SIMD3(0, 1, 0))) + let child = makeEntity(name: "Child") + setParent(childId: child, parentId: parent) + translateTo(entityId: child, position: SIMD3(1, 0, 0)) + return child + } + + func test_axisGizmoDrag_underATurnedParent_movesTheEntityWithTheGizmo() { + let axes: [TransformAxis] = [.x, .y, .z] + + for axis in axes { + let child = makeChildOfATurnedParent() + let startWorldPosition = getPosition(entityId: child) + assertNearlyEqual(startWorldPosition, SIMD3(4, 0, 0)) + activeEntity = child + createGizmo(mode: .translate) + + let handle = findGizmoHandle(mode: .translate, axis: axis) + guard handle != .invalid else { + XCTFail("Expected translate handle for axis \(axis).") + return + } + + activeHitGizmoEntity = handle + let startAxisAmount = component(of: startWorldPosition, along: axis) + beginGizmoDrag(ray: rayThroughGizmoAxis(axis, amount: startAxisAmount)) + updateGizmoDrag(ray: rayThroughGizmoAxis(axis, amount: startAxisAmount + 1.5)) + + let expected = startWorldPosition + vector(for: axis, amount: 1.5) + assertNearlyEqual(getPosition(entityId: parentEntityIdGizmo), expected) + assertNearlyEqual(getPosition(entityId: child), expected) + + endGizmoDrag() + removeGizmo() + } + } + + func test_localTranslation_isTheWorldMovementAsTheParentMeasuresIt() { + let child = makeChildOfATurnedParent() + assertNearlyEqual(localTranslation(ofWorld: SIMD3(1, 2, 3), for: child), SIMD3(-1, 2, -3)) + + let root = makeEntity(name: "Root", pos: SIMD3(3, 0, 0)) + assertNearlyEqual(localTranslation(ofWorld: SIMD3(1, 2, 3), for: root), SIMD3(1, 2, 3)) + + // A parent twice the size halves what its child has to move. + let bigParent = makeEntity(name: "BigParent") + scaleTo(entityId: bigParent, scale: SIMD3(repeating: 2)) + let smallChild = makeEntity(name: "SmallChild") + setParent(childId: smallChild, parentId: bigParent) + assertNearlyEqual(localTranslation(ofWorld: SIMD3(1, 2, 3), for: smallChild), SIMD3(0.5, 1, 1.5)) + } + + func test_axisGizmoDrag_underATurnedParent_scalesTheAxisThatLiesAlongTheHandle() { + // Under a parent turned a quarter around Y the child's own Z lies along the world's X. + let parent = makeEntity(name: "QuarterTurnedParent") + rotateTo(entityId: parent, rotation: simd_quatf(angle: .pi / 2, axis: SIMD3(0, 1, 0))) + let child = makeEntity(name: "ScaledChild") + setParent(childId: child, parentId: parent) + activeEntity = child + createGizmo(mode: .scale) + + let xHandle = findGizmoHandle(mode: .scale, axis: .x) + guard xHandle != .invalid else { + XCTFail("Expected x-axis scale handle.") + return + } + + activeHitGizmoEntity = xHandle + beginGizmoDrag(ray: rayThroughGizmoAxis(.x, amount: 0)) + updateGizmoDrag(ray: rayThroughGizmoAxis(.x, amount: 0.5)) + + let scale = scene.get(component: LocalTransformComponent.self, for: child)?.scale ?? .zero + assertNearlyEqual(scale, SIMD3(1.0, 1.0, 1.5)) + } + + func test_rotationDelta_underATurnedParent_turnsAboutTheWorldAxis() { + let child = makeChildOfATurnedParent() + + applyGizmoRotationDelta(entityId: child, axis: SIMD3(1, 0, 0), degrees: 90) + + // A quarter turn about the world's X carries what pointed up to the world's Z. + let worldRotation = entityWorldRotation(entityId: child) + let parentRotation = simd_quatf(angle: .pi, axis: SIMD3(0, 1, 0)) + let upBefore = simd_act(parentRotation, SIMD3(0, 1, 0)) + let quarterTurn = simd_quatf(angle: .pi / 2, axis: SIMD3(1, 0, 0)) + assertNearlyEqual(simd_act(worldRotation, SIMD3(0, 1, 0)), simd_act(quarterTurn, upBefore)) + assertNearlyEqual(simd_act(worldRotation, SIMD3(0, 1, 0)), SIMD3(0, 0, 1)) + } + + func test_axisGizmoDrag_scalesFromCurrentRayConstraint() { + let active = makeEntity(name: "ScaledBox", pos: SIMD3(0, 0, 0)) + activeEntity = active + createGizmo(mode: .scale) + + let xHandle = findGizmoHandle(mode: .scale, axis: .x) + guard xHandle != .invalid else { + XCTFail("Expected x-axis scale handle.") + return + } + + activeHitGizmoEntity = xHandle + beginGizmoDrag( + ray: GizmoDragRay( + origin: SIMD3(0, 1, 0), + direction: SIMD3(0, -1, 0) + ) + ) + updateGizmoDrag( + ray: GizmoDragRay( + origin: SIMD3(0.5, 1, 0), + direction: SIMD3(0, -1, 0) + ) + ) + + let scale = scene.get(component: LocalTransformComponent.self, for: active)?.scale + XCTAssertEqual(scale, SIMD3(1.5, 1.0, 1.0)) + } + + func test_axisGizmoDrag_scaleTracksAbsoluteAxisPositionForAllAxes() { + let axes: [TransformAxis] = [.x, .y, .z] + + for axis in axes { + let active = makeEntity(name: "AbsoluteScale-\(axis)", pos: SIMD3(0, 0, 0)) + activeEntity = active + createGizmo(mode: .scale) + + let handle = findGizmoHandle(mode: .scale, axis: axis) + guard handle != .invalid else { + XCTFail("Expected scale handle for axis \(axis).") + return + } + + activeHitGizmoEntity = handle + beginGizmoDrag(ray: rayThroughGizmoAxis(axis, amount: 0.0)) + updateGizmoDrag(ray: rayThroughGizmoAxis(axis, amount: 0.4)) + updateGizmoDrag(ray: rayThroughGizmoAxis(axis, amount: 1.25)) + + let expectedScale = SIMD3(repeating: 1.0) + vector(for: axis, amount: 1.25) + guard let scale = scene.get(component: LocalTransformComponent.self, for: active)?.scale else { + XCTFail("Expected LocalTransformComponent for scaled entity.") + return + } + assertNearlyEqual(scale, expectedScale) + + endGizmoDrag() + removeGizmo() + } + } + + func test_applyGizmoRotationDelta_repeatedYAxisRotationsStayOnYAxis() { + let active = makeEntity(name: "RepeatedYRotation", pos: SIMD3(0, 0, 0)) + + applyGizmoRotationDelta(entityId: active, axis: SIMD3(0, 1, 0), degrees: 30) + applyGizmoRotationDelta(entityId: active, axis: SIMD3(0, 1, 0), degrees: 15) + + let orientation = getLocalOrientation(entityId: active) + let forward = simd_normalize(orientation * SIMD3(0, 0, 1)) + let expectedForward = simd_normalize( + simd_quatf(angle: Float.pi / 4, axis: SIMD3(0, 1, 0)).act(SIMD3(0, 0, 1)) + ) + + assertNearlyEqual(forward, expectedForward, accuracy: 0.0002) + XCTAssertEqual(forward.y, 0.0, accuracy: 0.0002) + } + + func test_applyGizmoRotationDelta_afterExistingRotationUsesWorldAxis() { + let active = makeEntity(name: "WorldAxisRotation", pos: SIMD3(0, 0, 0)) + + applyGizmoRotationDelta(entityId: active, axis: SIMD3(1, 0, 0), degrees: 45) + let beforeUp = getLocalOrientation(entityId: active) * SIMD3(0, 1, 0) + + applyGizmoRotationDelta(entityId: active, axis: SIMD3(0, 1, 0), degrees: 30) + let afterUp = getLocalOrientation(entityId: active) * SIMD3(0, 1, 0) + + let expectedAfterUp = simd_quatf(angle: Float.pi / 6, axis: SIMD3(0, 1, 0)).act(beforeUp) + assertNearlyEqual(afterUp, expectedAfterUp, accuracy: 0.0002) + } + + func test_applyGizmoRotationDelta_usesExplicitWorldAxisForEveryAxis() { + let cases: [(TransformAxis, SIMD3, Float)] = [ + (.x, SIMD3(1.0, 0.0, 0.0), 20.0), + (.y, SIMD3(0.0, 1.0, 0.0), -35.0), + (.z, SIMD3(0.0, 0.0, 1.0), 50.0), + ] + + for (axisName, axisVector, degrees) in cases { + let active = makeEntity(name: "WorldRotation-\(axisName)", pos: SIMD3(0, 0, 0)) + + applyGizmoRotationDelta(entityId: active, axis: axisVector, degrees: degrees) + + let orientation = getLocalOrientation(entityId: active) + let expected = simd_quatf(angle: degreesToRadians(degrees: degrees), axis: axisVector) + assertNearlyEqual(simd_mul(orientation, SIMD3(1.0, 0.0, 0.0)), expected.act(SIMD3(1.0, 0.0, 0.0)), accuracy: 0.0002) + assertNearlyEqual(simd_mul(orientation, SIMD3(0.0, 1.0, 0.0)), expected.act(SIMD3(0.0, 1.0, 0.0)), accuracy: 0.0002) + assertNearlyEqual(simd_mul(orientation, SIMD3(0.0, 0.0, 1.0)), expected.act(SIMD3(0.0, 0.0, 1.0)), accuracy: 0.0002) + } + } +} diff --git a/docs/API/UsingGizmoSystem.md b/docs/API/UsingGizmoSystem.md new file mode 100644 index 000000000..5b3c17ec5 --- /dev/null +++ b/docs/API/UsingGizmoSystem.md @@ -0,0 +1,169 @@ +# Using the Gizmo System + +The gizmo system gives any app built on UntoldEngine the same translate/rotate/scale manipulator the Untold Editor uses to let a user drag, turn, or resize a selected entity in the 3D viewport. The engine owns gizmo geometry, hit-testing math, drag-to-transform math, *and* rendering — the gizmo draws through its own dedicated render pass (it's intentionally excluded from the normal model/shadow passes so it's never occluded by scene geometry). Your app just needs to opt into that pass once at startup, and turn its platform's input events (mouse, touch, spatial pinch) into world-space rays to feed the gizmo. + +## Basic Setup + +**Opt into gizmo rendering once, right after creating your renderer** (same timing as any other render extension): + +```swift +guard let renderer = UntoldRenderer.create() else { /* ... */ } +registerGizmoRenderExtension() +``` + +Without this call the gizmo's logic/picking/drag all work, but nothing will ever be visible on screen — this registers the `.gizmo` pipeline and adds its render pass to the graph. It's a no-op draw whenever no gizmo is active, so it's safe to register unconditionally at startup even if the app doesn't always use gizmos. + +Then, to show a gizmo: pick the entity to manipulate, set it as `activeEntity`, and create the gizmo: + +```swift +activeEntity = selectedEntityId +createGizmo(mode: .translate) +``` + +`GizmoMode` is `.translate`, `.rotate`, or `.scale`. Call `createGizmo(mode:)` again with a different mode to switch tools, or `removeGizmo()` to tear the current one down (e.g. when the selection is cleared, or when gameplay resumes and the gizmo shouldn't be visible anymore — see "Gizmos and play/edit mode" below). + +The gizmo's on-screen size is kept constant automatically (the render pass itself calls `updateGizmoScreenSpaceScale` every frame) — you don't need to call it yourself. + +## Troubleshooting: gizmo not visible + +`registerGizmoRenderExtension()` can fail (shader/pipeline issues, a conflicting +pipeline owner, etc.) without crashing anything — the gizmo's logic/picking/drag +still work, it just never draws. Walk this path if a gizmo you expect to see isn't +showing up: + +- **Check the registration's return value — don't ignore it.** + ```swift + if registerGizmoRenderExtension() != .registered { + Logger.log(message: "⚠️ Failed to register the gizmo render extension — the transform gizmo will not be visible") + } + ``` +- **Confirm it's actually called on every platform target your app ships.** A + single shared setup path that only runs on one platform (e.g. macOS but not + iOS/visionOS) is an easy miss — verify the call site is reached on each target, + not just the one you tested on. +- **If registration succeeds but the gizmo still never shows, confirm + `createGizmo(mode:)` is actually being reached.** Setting `activeEntity` alone + draws nothing — a selection flow gated behind a UI "tool mode" can set + `activeEntity` while the current tool/mode never calls `createGizmo`. Trace the + call path from your selection code to the actual `createGizmo` call. + +## Picking a gizmo handle + +Gizmo handles are tagged with `GizmoComponent`, and the engine's picking system already knows how to raycast against only them. Use `ScenePickOptions(gizmoOnly: true)` (or `isGizmoActive: true` on your normal pick call, which automatically prefers gizmo handles over scene entities unless the user is holding Shift): + +```swift +if let hit = pickEntity(rayOrigin: rayOrigin, rayDirection: rayDirection, + options: ScenePickOptions(gizmoOnly: true)) { + // see processGizmoAction below — it records this hit for you +} +``` + +Check whether a hit entity is actually a gizmo handle (as opposed to a scene entity) with `hitGizmoToolAxis(entityId:)`: + +```swift +if hitGizmoToolAxis(entityId: hit.entityId) { + // let the drag handlers below take over instead of re-selecting +} +``` + +Call `processGizmoAction(entityId:)` with the hit handle before starting a drag. It does two things: records `activeHitGizmoEntity` (which `beginGizmoDrag` reads to know which handle is being dragged — skipping this call means `beginGizmoDrag` silently fails), and writes the `gizmoHoverMode`/`gizmoHoverAxis` globals, which your own UI can read to drive hover/active highlighting: + +```swift +processGizmoAction(entityId: hit.entityId) +let highlightedAxis = gizmoHoverAxis // .x, .y, .z, or .none +``` + +## Dragging + +Feed rays into the drag lifecycle from your platform input code — mouse-down/drag/up, touch-begin/move/end, or a spatial-pinch sequence, whatever your app uses. `beginGizmoDrag` only works after `processGizmoAction(entityId:)` has been called with the hit handle (see "Picking a gizmo handle" above) — it drags whatever handle `processGizmoAction` most recently recorded: + +```swift +// On drag start, after processGizmoAction(entityId: hit.entityId): +beginGizmoDrag(ray: GizmoDragRay(origin: rayOrigin, direction: rayDirection)) + +// On every drag-move event: +queueGizmoDragUpdate(ray: GizmoDragRay(origin: rayOrigin, direction: rayDirection)) +// then, once per frame (e.g. from your onUpdate callback): +applyPendingGizmoDragUpdate() + +// On drag end: +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. + +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. + +## Optional: snapping + +By default the gizmo never snaps. To offer grid/angle snapping, conform to `GizmoSnapProvider` and assign it: + +```swift +struct MySnapProvider: GizmoSnapProvider { + func snapStep(for mode: TransformManipulationMode) -> Float? { + switch mode { + case .translate: return 0.25 // snap to quarter-unit grid + case .rotate: return 15.0 // snap to 15-degree steps + default: return nil // no snapping for scale/lightRotate + } + } +} + +gizmoSnapProvider = MySnapProvider() +``` + +Returning `nil` (or leaving `gizmoSnapProvider` unset) means no snapping for that mode. + +## Optional: local vs. world axes + +By default the gizmo's handles are aligned to the world's axes. To let the user toggle to the entity's own local axes: + +```swift +gizmoTransformSpace = .local // or .world +``` + +## Optional: redirecting a drag away from the entity's transform + +Most apps just want the gizmo to move/rotate/scale the target entity's transform, which is the default behavior. If your app has entities whose "position" is really some other property — a spline control point, a light's target, anything exposed through your own component system — you can redirect translate drags to that property instead by conforming to `GizmoHandleOverrideProvider`: + +```swift +struct MyHandleOverride: GizmoHandleOverrideProvider { + func activeOverrideWorldPosition() -> simd_float3? { + // Return the current world position of whatever you want the gizmo + // to represent, or nil to fall back to the plain transform-drag path. + myControlPoint?.worldPosition + } + + @discardableResult + func moveOverride(toWorld position: simd_float3) -> Bool { + guard let point = myControlPoint else { return false } + point.worldPosition = position + return true + } +} + +gizmoHandleOverrideProvider = MyHandleOverride() +``` + +Leave this unset for ordinary entity dragging. + +## Gizmos and play/edit mode + +The gizmo render pass draws whenever a gizmo is active (`gizmoActive`/`parentEntityIdGizmo != .invalid`), regardless of whatever play/pause state your app's gameplay logic is in — the engine has no opinion on that distinction. If your app has a play-mode/edit-mode split (as the Untold Editor does) and a gizmo was left active when play mode starts, it will keep rendering and keep responding to drags during gameplay unless you explicitly tear it down. + +Call `removeGizmo()` and reset `activeEntity = .invalid` at the moment gameplay resumes, so the gizmo disappears cleanly instead of lingering over a running scene: + +```swift +if enteringPlayMode { + removeGizmo() + activeEntity = .invalid +} +``` + +## What you don't need to build + +- Gizmo rendering: once you call `registerGizmoRenderExtension()` at startup, handles (built from `BasicPrimitives` meshes) draw automatically through their own dedicated pass whenever a gizmo is active, and the pass clears itself cleanly to avoid a stale "ghost" gizmo when none is active. They're excluded from the normal model/shadow passes, static batching, and bounds computation (via `GizmoComponent`/`GizmoHandleComponent`/`GizmoHitProxyComponent`/`GizmoCenterComponent`) so they're never occluded by or confused with scene geometry. +- Picking a gizmo handle apart from the rest of the scene: `ScenePickOptions(gizmoOnly:)` already filters for you on both the CPU and GPU picking backends. +- Cleanup: destroying the gizmo's parent entity (or calling `removeGizmo()`) tears down all its handles through the normal `destroyEntity`/`ComponentRegistry` cleanup path — no manual bookkeeping required. diff --git a/docs/Extensions/UnderstandingRenderingExtensions.md b/docs/Extensions/UnderstandingRenderingExtensions.md index 6dced7b37..fb1b17d5d 100644 --- a/docs/Extensions/UnderstandingRenderingExtensions.md +++ b/docs/Extensions/UnderstandingRenderingExtensions.md @@ -145,6 +145,12 @@ For a full worked build (package layout, install/uninstall, a complete procedural draw), follow [Creating a Rendering Extension Plugin](CreatingRenderingExtensionPlugin.md). +For a real, in-repo example of this model, see `GizmoRenderExtension` +(`Sources/UntoldEngine/Renderer/GizmoRenderPass.swift`) — it owns a dedicated +unlit pipeline (`.gizmo`) and its own, every-frame-cleared render target so the +transform gizmo is never occluded by scene geometry, and clears that target +itself whenever no gizmo is active instead of leaving stale pixels on screen. + ## One boundary that applies to both models Neither path can **sample the engine's already-composited frame as a texture