Blender4iOS/Sources/Animation/AnimationPanelView.swift

255 lines
9.1 KiB
Swift
Raw Permalink Normal View History

Animation Data Model Mirrors Blender's internal structure exactly: Keyframe — stores frame, value, handleLeft/handleRight (absolute SIMD2 coordinates for Bézier control points), handleType (Free/Aligned/Vector/Auto/Auto Clamped), and interpolation mode (Constant/Linear/Bézier/Bounce/Elastic/Back). The autoComputeHandles() method computes smooth tangents from neighboring keyframes, matching Blender's BKE_fcurve_correct_bezpart. moveHandleLeft/moveHandleRight enforce the Aligned constraint (co-linear handles). AnimationTrack (= Blender's FCurve) — one channel like location.X. Contains a sorted keyframe array. The evaluate(at:) method performs full cubic Bézier interpolation using Newton-Raphson iteration (8 steps, matching Blender's precision) to solve for the parametric t given a frame x-coordinate, then evaluates the y-coordinate. Colors follow Blender's convention: X=red, Y=green, Z=blue. AnimAction (= Blender's bAction) — groups multiple tracks into a reusable animation data block. evaluate(at:) returns all channel values as a dictionary. AnimationSystem — owns the action library, playback state (currentFrame, fps, loop mode), and applyToObject() to push evaluated transforms onto a SceneObject. Dope Sheet (DopeSheetView.swift) Faithful to Blender's Dope Sheet layout: Left channel list with colored track indicators (red/green/blue bars), mute (speaker icon) and lock buttons per channel Summary track at top showing all keyframes merged as yellow diamonds Per-channel tracks with diamond keyframes (yellow = normal, white = selected) Frame ruler at top with major ticks every 10 frames, minor every 5, and frame number labels Blue playhead line with triangular marker — tap the ruler to scrub Keyframe interaction: tap to select, drag to move (snaps to integer frames), auto-recomputes handles after drag Pinch to zoom the frame axis, horizontal drag to scroll Graph Editor (GraphEditorView.swift) The most complex view — a full interactive F-Curve editor: Adaptive grid with auto-scaling step sizes (1/2/5/10 pattern), axis lines highlighted, frame numbers on bottom, value numbers on left F-Curve rendering as cubic Bézier paths using SwiftUI's addCurve(to:control1:control2:), with flat extensions before/after the first/last keyframes. Constant interpolation draws step functions, Linear draws straight lines. Keyframe diamonds colored per-channel (red/green/blue), white when selected Bézier handles — visible only on selected keyframes, drawn as circles connected to the diamond by lines. Supports: Drag the diamond to move the keyframe (frame snaps to integer, value is free) Drag the left handle to change the incoming tangent Drag the right handle to change the outgoing tangent Aligned mode: moving one handle mirrors the other Hit testing with 14pt touch radius, prioritizing handles over keyframes over timeline scrubbing Info overlay showing current frame/value coordinates during drag Channel list overlay with per-track visibility toggles Transport Controls (AnimationPanelView.swift) Matches Blender's timeline footer pixel-for-pixel: Editor switcher — segmented control toggling between Dope Sheet and Graph Editor Action name display with film icon Interpolation menu — set selected keyframes to Constant/Linear/Bézier/Bounce/Elastic/Back Handle type menu — set selected handles to Free/Aligned/Vector/Auto/Auto Clamped Insert keyframe button (yellow diamond icon) Transport bar: Jump to Start, Previous Keyframe, Step Back, Play/Pause (highlighted blue when playing), Step Forward, Next Keyframe, Jump to End Frame range display (Start/End) Current frame in blue monospaced bold FPS indicator and loop toggle Playback Engine (AnimationPlayer.swift) CADisplayLink-driven with preferredFrameRateRange set to 30–120fps. Delta-time accumulation advances currentFrame at the configured FPS rate. nextKeyframe()/previousKeyframe() jump between actual keyframe positions. To see it: tap the Animation workspace tab, or tap the play icon in any workspace header to toggle the timeline panel. The default "CubeAction" ships with sample keyframes on all three location channels so you'll see curves immediately in the Graph Editor. Tap a keyframe diamond, then drag its Bézier handles to reshape the easing.
2026-04-10 21:52:58 -07:00
// AnimationPanelView.swift
// Combined animation panel: transport bar + Dope Sheet / Graph Editor toggle.
// Designed to slot into the bottom of any workspace layout.
import SwiftUI
struct AnimationPanelView: View {
let animSystem: AnimationSystem
@State private var player: AnimationPlayer?
@State private var showGraphEditor = false
var body: some View {
VStack(spacing: 0) {
// Editor switcher + Toolbar
editorToolbar
Divider().background(Color.white.opacity(0.1))
// Dope Sheet or Graph Editor
Group {
if showGraphEditor {
GraphEditorView(animSystem: animSystem)
} else {
DopeSheetView(
animSystem: animSystem,
player: player ?? AnimationPlayer(system: animSystem)
)
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
Divider().background(Color.white.opacity(0.1))
// Transport controls
transportBar
}
.background(Color(red: 0.15, green: 0.15, blue: 0.15))
.onAppear {
if player == nil {
player = AnimationPlayer(system: animSystem)
}
}
}
// MARK: - Editor toolbar (matches Blender's editor type selector)
private var editorToolbar: some View {
HStack(spacing: 8) {
// Editor type switcher
Picker("Editor", selection: $showGraphEditor) {
Label("Dope Sheet", systemImage: "rectangle.split.3x1")
.tag(false)
Label("Graph Editor", systemImage: "chart.xyaxis.line")
.tag(true)
}
.pickerStyle(.segmented)
.frame(width: 220)
Divider().frame(height: 16)
if let action = animSystem.activeAction {
// Action name
HStack(spacing: 4) {
Image(systemName: "film")
.font(.system(size: 10))
.foregroundStyle(.orange)
Text(action.name)
.font(.system(size: 11, weight: .medium))
}
}
Spacer()
// Interpolation mode for selected keyframes
Menu {
ForEach(KeyframeInterpolation.allCases) { interp in
Button {
setSelectedInterpolation(interp)
} label: {
Text(interp.rawValue)
}
}
} label: {
Label("Interpolation", systemImage: "point.topleft.down.to.point.bottomright.curvepath")
.font(.system(size: 10))
}
// Handle type for selected keyframes
Menu {
ForEach(HandleType.allCases) { ht in
Button {
setSelectedHandleType(ht)
} label: {
Text(ht.rawValue)
}
}
} label: {
Label("Handles", systemImage: "point.bottomleft.forward.to.arrowtriangle.uturn.scurvepath")
.font(.system(size: 10))
}
// Insert keyframe
Button {
insertKeyframeAtCurrent()
} label: {
Image(systemName: "diamond.fill")
.font(.system(size: 10))
.foregroundStyle(.yellow)
}
}
.padding(.horizontal, 12)
.padding(.vertical, 4)
.background(Color(red: 0.17, green: 0.17, blue: 0.17))
}
// MARK: - Transport controls (Blender style)
private var transportBar: some View {
HStack(spacing: 0) {
// Left: frame range
HStack(spacing: 4) {
Text("Start:")
.font(.system(size: 9))
.foregroundStyle(.secondary)
Text(String(format: "%.0f", animSystem.frameStart))
.font(.system(size: 10, design: .monospaced))
.frame(width: 36)
.padding(.horizontal, 4)
.padding(.vertical, 2)
.background(Color.white.opacity(0.06), in: RoundedRectangle(cornerRadius: 3))
Text("End:")
.font(.system(size: 9))
.foregroundStyle(.secondary)
Text(String(format: "%.0f", animSystem.frameEnd))
.font(.system(size: 10, design: .monospaced))
.frame(width: 36)
.padding(.horizontal, 4)
.padding(.vertical, 2)
.background(Color.white.opacity(0.06), in: RoundedRectangle(cornerRadius: 3))
}
.padding(.horizontal, 12)
Spacer()
// Center: transport buttons
HStack(spacing: 2) {
transportButton(icon: "backward.end.fill") { player?.jumpToStart() }
transportButton(icon: "chevron.backward") { player?.previousKeyframe() }
transportButton(icon: "backward.frame.fill") { player?.stepBackward() }
// Play/Pause (larger, highlighted)
Button { player?.togglePlayback() } label: {
Image(systemName: animSystem.isPlaying ? "pause.fill" : "play.fill")
.font(.system(size: 14))
.frame(width: 36, height: 28)
.background(
animSystem.isPlaying
? Color(red: 0.30, green: 0.55, blue: 0.95).opacity(0.3)
: Color.white.opacity(0.08),
in: RoundedRectangle(cornerRadius: 4)
)
.foregroundStyle(animSystem.isPlaying ? .blue : .primary)
}
.buttonStyle(.plain)
transportButton(icon: "forward.frame.fill") { player?.stepForward() }
transportButton(icon: "chevron.forward") { player?.nextKeyframe() }
transportButton(icon: "forward.end.fill") { player?.jumpToEnd() }
}
Spacer()
// Right: current frame + FPS
HStack(spacing: 8) {
// Current frame
HStack(spacing: 2) {
Image(systemName: "film")
.font(.system(size: 9))
.foregroundStyle(.secondary)
Text(String(format: "%.0f", animSystem.currentFrame))
.font(.system(size: 11, weight: .bold, design: .monospaced))
.foregroundStyle(Color(red: 0.30, green: 0.55, blue: 0.95))
.frame(width: 40)
}
Divider().frame(height: 16)
// FPS
HStack(spacing: 2) {
Text("\(Int(animSystem.fps))")
.font(.system(size: 10, design: .monospaced))
Text("fps")
.font(.system(size: 9))
.foregroundStyle(.secondary)
}
// Loop toggle
Button {
animSystem.isLooping.toggle()
} label: {
Image(systemName: "repeat")
.font(.system(size: 10))
.foregroundStyle(animSystem.isLooping ? .orange : .secondary)
}
.buttonStyle(.plain)
}
.padding(.horizontal, 12)
}
.padding(.vertical, 6)
.background(Color(red: 0.14, green: 0.14, blue: 0.14))
}
private func transportButton(icon: String, action: @escaping () -> Void) -> some View {
Button(action: action) {
Image(systemName: icon)
.font(.system(size: 10))
.frame(width: 28, height: 28)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.foregroundStyle(.secondary)
}
// MARK: - Actions
private func setSelectedInterpolation(_ interp: KeyframeInterpolation) {
guard let action = animSystem.activeAction else { return }
for track in action.tracks {
for kf in track.keyframes where kf.isSelected {
kf.interpolation = interp
}
}
}
private func setSelectedHandleType(_ ht: HandleType) {
guard let action = animSystem.activeAction else { return }
for track in action.tracks {
for kf in track.keyframes where kf.isSelected {
kf.handleType = ht
}
track.recomputeAutoHandles()
}
}
private func insertKeyframeAtCurrent() {
guard let action = animSystem.activeAction else { return }
let frame = animSystem.currentFrame
for track in action.tracks {
let currentVal = track.evaluate(at: frame)
track.insertKeyframe(frame: frame, value: currentVal)
}
}
}