Files
breeze/design/figure-preview/figure_preview.zi
T
waozi 313cffba7c
Cloudflare Pages / Build and verify the site (push) Failing after 2m27s
Review exact Blender poses and improve practice figure motion
2026-11-20 12:16:00 -03:00

589 lines
24 KiB
Ziran

// A live preview of the shared practice figure: pick the woman or the man,
// a practice and one of its items, play, pause, scrub or slow it down, turn
// and zoom. The poses are the practices' own (preview_practices.zi); the
// figures are practices' CC0 VRoid models (shared/figure). Breeze's current
// flat figure shows when asked.
//
// figure_preview opens the window
// figure_preview --capture DIR writes the review frames to DIR and exits
// figure_preview --audit lists every awkward moment of the motion
// figure_preview --video DIR PRACTICE ITEM FROM TO [man]
// writes 30 frames a second of a stretch
//
// FIGURE_PRACTICES names a practices checkout; otherwise the preview asks
// `ziran pkg path practices --locked` beside its own manifest.
#import "figure_math"
#import "figure_joints"
#import "preview_practices"
#import "preview_capture"
#import "preview_flat"
#import "preview_figure"
#import "preview_motion"
#import "kryon/scene"
#import "kryon/scene_gpu"
#import "kryon/session"
#import "kryon/geometry"
#import "kryon/frame_snapshot"
#import "kryon/style_sheet"
#import "kryon/bitmap_image"
#import "kryon/desktop_runtime"
#import "kryon/drawing_props"
Desktop :: #import "kryon/desktop_loop";
Box :: #import "kryon/box";
Button :: #import "kryon/button";
Dropdown :: #import "kryon/dropdown";
Image :: #import "kryon/image";
Segmented :: #import "kryon/segmented_control";
Slider :: #import "kryon/slider";
Text :: #import "kryon/text";
Toggle :: #import "kryon/toggle";
Raster :: #import "std/image";
Timer :: #import "std/timer_linux";
#import "std/c_string"
#import "std/byte_text_linux"
#import "std/math"
#import "std/float_text"
#import "std/number_text"
#import "std/process_capture_linux"
#import "std/vec"
libc :: #system_library "libc";
PreviewGetEnvironment :: (name: *u8) -> *u8 #foreign libc "getenv";
PreviewWorkingDirectory :: (output: *u8, size: usize) -> *u8 #foreign libc "getcwd";
PreviewChangeDirectory :: (path: *u8) -> s32 #foreign libc "chdir";
PreviewFlushOutput :: (stream: *void) -> s32 #foreign libc "fflush";
PreviewState :: struct {
practice: s32
item: s32
seconds: float64
playing: bool
speed: float64
// Shows Breeze's current flat figure on the stage.
current: bool
// Shows the man instead of the woman.
man: bool
turn: float64
lift: float64
zoom: float64
dragging: bool
drag_x: float32
drag_y: float32
}
preview_state: PreviewState = .{playing = true, speed = 1.0, zoom = 1.0};
preview_figure: PreviewFigure;
PREVIEW_TIMING_SAMPLES :: 30
PreviewFrameTiming :: struct {
intervals: [PREVIEW_TIMING_SAMPLES]float64
count: s64
last_paint: s64
last_seconds: float64
max_step: float64
visible_frames: s64
focused_frames: s64
minimized_frames: s64
draw_ms: float64
stage_ms: float64
pose_ms: float64
render_ms: float64
prepare_ms: float64
submit_ms: float64
readback_ms: float64
}
preview_timing: PreviewFrameTiming;
preview_last_draw_ms: float64;
preview_backdrops: PreviewBackdrops;
preview_library: PreviewLibrary;
preview_picture: Raster.Image;
preview_texture: Texture2D;
preview_owner: Session;
preview_painted_key: u64;
preview_failed: bool;
preview_clock: s64;
// Changing labels alternate between two buffers, so each frame's text is
// its own and never an edit of the last frame's.
preview_page: s32;
preview_time_text: [2][32]u8;
preview_practices_path: [1024]u8;
preview_practices_length: s64;
main :: (argc: s32, argv: **u8) -> s32 {
practices := PreviewPracticesPath()
if practices.count == 0 {
print("figure preview: no practices checkout; set FIGURE_PRACTICES or lock the package\n")
return 1
}
if !PreviewBackdropsLoad(*preview_backdrops, practices) || !PreviewLibraryLoad(*preview_library, practices) {
print("figure preview: could not read the backdrops or the practices in %\n", practices)
return 1
}
preview_state.item = PreviewDefaultItem(*preview_library, preview_state.practice)
if argc >= 2 && TextFromCString(argv[1]) == "--review-spans" {
PreviewReviewSpans(*preview_library)
return 0
}
if argc >= 2 && TextFromCString(argv[1]) == "--review-items" {
for practice: cast(s32)0..3 {
for item: cast(s32)0..PreviewItemCount(*preview_library, practice) - 1 {
print("item\t%\t%\t%\t%\n", practice, item, PreviewDuration(*preview_library, practice, item),
PreviewItemName(*preview_library, practice, item))
}
}
return 0
}
if argc >= 2 && TextFromCString(argv[1]) == "--stream" {
if argc < 10 || argc > 11 || (argc == 11 && TextFromCString(argv[10]) != "man") {
print("usage: --stream PRACTICE ITEM FROM TO FPS WIDTH HEIGHT FD [man]\n")
return 1
}
values: [8]float64
for index: 0..7 {
value, ok := ParseFloat64(TextFromCString(argv[index + 2]))
if !ok {
return 1
}
values[index] = value
}
man := argc >= 11 && TextFromCString(argv[10]) == "man"
return PreviewStream(*preview_backdrops, *preview_library, practices, cast(s32)values[0], cast(s32)values[1],
values[2], values[3], values[4], cast(s32)values[5], cast(s32)values[6], cast(s32)values[7], man)
}
if argc >= 2 && TextFromCString(argv[1]) == "--review-points" {
PreviewReviewPoints(*preview_library)
return 0
}
if argc >= 2 && TextFromCString(argv[1]) == "--clothing-audit" {
return PreviewAuditClothing(*preview_library, practices)
}
if argc >= 2 && TextFromCString(argv[1]) == "--sole-audit" {
return PreviewAuditSoles(*preview_library, practices)
}
if argc >= 2 && TextFromCString(argv[1]) == "--audit" {
return ifx PreviewAudit(*preview_library) == 0 then 0 else 1
}
if argc >= 7 && TextFromCString(argv[1]) == "--video" {
// --video DIR PRACTICE ITEM FROM TO [man]: frames at 30 a second.
values: [4]float64
for index: 0..3 {
value, ok := ParseFloat64(TextFromCString(argv[index + 3]))
values[index] = ifx ok then value else 0.0
}
man := argc >= 8 && TextFromCString(argv[7]) == "man"
return PreviewVideo(*preview_backdrops, *preview_library, TextFromCString(argv[2]), practices, cast(s32)values[0],
cast(s32)values[1], values[2], values[3], man)
}
if argc >= 6 && TextFromCString(argv[1]) == "--trace" {
values: [4]float64
for index: 0..3 {
value, ok := ParseFloat64(TextFromCString(argv[index + 2]))
values[index] = ifx ok then value else 0.0
}
PreviewTrace(*preview_library, cast(s32)values[0], cast(s32)values[1], values[2], values[3])
return 0
}
if argc >= 6 && TextFromCString(argv[1]) == "--shot" {
// --shot DIR PRACTICE ITEM SECONDS... [man] [turn=DEGREES]
times: [32]float64
count: s64
man := false
turn: float64
for index: 5..argc - 1 {
word := TextFromCString(argv[index])
if word == "man" {
man = true
} else if word.count > 5 && word[:5] == "turn=" {
degrees, ok := ParseFloat64(word[5:])
if !ok || !Finite64(degrees) {
return 1
}
turn = degrees * (FIGURE_PI / 180.0)
} else if count < 32 {
value, ok := ParseFloat64(word)
if !ok || !Finite64(value) {
return 1
}
times[count] = value
count += 1
}
}
practice_number, practice_ok := ParseFloat64(TextFromCString(argv[3]))
item_number, item_ok := ParseFloat64(TextFromCString(argv[4]))
if !practice_ok || !item_ok || count == 0 {
return 1
}
return PreviewShots(*preview_backdrops, *preview_library, TextFromCString(argv[2]), practices,
cast(s32)practice_number, cast(s32)item_number, times[0:count], man, turn)
}
if argc >= 2 && TextFromCString(argv[1]) == "--rig-pose" {
if argc < 5 || argc > 6 || (argc == 6 && TextFromCString(argv[5]) != "man") {
return 1
}
practice, practice_ok := ParseFloat64(TextFromCString(argv[2]))
item, item_ok := ParseFloat64(TextFromCString(argv[3]))
seconds, time_ok := ParseFloat64(TextFromCString(argv[4]))
if !practice_ok || !Finite64(practice) || practice < 0 || practice > 3 ||
!item_ok || !Finite64(item) || item < 0 ||
item >= cast(float64)PreviewItemCount(*preview_library, cast(s32)practice) || !time_ok || !Finite64(seconds) {
return 1
}
practice_index := cast(s32)practice
item_index := cast(s32)item
if cast(float64)practice_index != practice || cast(float64)item_index != item {
return 1
}
return PreviewRigPose(*preview_library, practices, practice_index, item_index, seconds, argc == 6)
}
if argc >= 3 && TextFromCString(argv[1]) == "--capture" {
return PreviewCapture(*preview_backdrops, *preview_library, TextFromCString(argv[2]), practices)
}
return Desktop.RunTitled(PreviewDraw, 1360, 900, "Figure preview")
}
PreviewDraw :: (session: Session, viewport: Rectangle) -> s32 {
draw_started := Timer.MonotonicNanoseconds()
defer {
preview_last_draw_ms = cast(float64)(Timer.MonotonicNanoseconds() - draw_started) / 1000000.0
}
input := CaptureFrameInput(session)
state := *preview_state
panel_width: float32 = 360.0
area := Rectangle.{viewport.x, viewport.y, viewport.width - panel_width, viewport.height}
panel := Rectangle.{viewport.x + area.width, viewport.y, panel_width, viewport.height}
Box.Draw(session, Box.Props.{.key = 1, .bounds = area, .fill = .{243, 237, 225, 255}})
Box.Draw(session, Box.Props.{.key = 2, .bounds = panel, .fill = .{232, 225, 211, 255}})
duration := PreviewDuration(*preview_library, state.practice, state.item)
now := Timer.MonotonicNanoseconds()
elapsed := ifx preview_clock == 0 then 0 else now - preview_clock
preview_clock = now
if state.playing {
// A stalled frame never jumps the figure ahead by more than a moment.
state.seconds += FigureClamp(cast(float64)elapsed / 1000000000.0, 0.0, 0.1) * state.speed
if state.seconds >= duration {
// A completed demonstration holds its final pose. Wrapping to
// time zero teleported a travelling stance across the stage.
state.seconds = duration
state.playing = false
}
DesktopRequestFrame()
}
if !state.playing {
preview_timing = .{}
}
// Turn and tilt by dragging over her; zoom with the wheel.
pointer := input.pointer
inside := pointer.x >= area.x && pointer.x < area.x + area.width && pointer.y >= area.y &&
pointer.y < area.y + area.height
if pointer.pressed && inside {
state.dragging = true
state.drag_x = pointer.x
state.drag_y = pointer.y
}
if state.dragging {
state.turn -= cast(float64)(pointer.x - state.drag_x) * 0.008
state.lift = FigureClamp(state.lift + cast(float64)(pointer.y - state.drag_y) * 0.006, -1.2, 1.45)
state.drag_x = pointer.x
state.drag_y = pointer.y
DesktopRequestFrame()
if !pointer.down {
state.dragging = false
}
}
if inside && input.wheel != 0.0 {
state.zoom = FigureClamp(state.zoom * Pow(0.88, cast(float64)input.wheel), 0.25, 3.0)
}
PreviewPaintStage(session, area)
x := panel.x + 20.0
width := panel.width - 40.0
y := panel.y + 18.0
Text.Draw(session, Text.Props.{.key = 10, .bounds = .{x, y, width, 30.0}, .text = "Figure preview",
.size = 22})
y += 42.0
options: [4]Segmented.SegmentOption
options[0].label = "Tai Chi"
options[1].label = "Sun"
options[2].label = "Workout"
options[3].label = "Astral"
chosen := Segmented.Draw(session, Segmented.Props.{.key = 11, .bounds = .{x, y, width, 40.0},
.selected_index = state.practice, .has_selection = true}, options[:]).selected_index
if chosen != state.practice && chosen >= 0 && chosen <= 3 {
state.practice = chosen
state.item = PreviewDefaultItem(*preview_library, chosen)
state.seconds = 0.0
}
y += 52.0
items: [PREVIEW_ITEM_LIMIT]Dropdown.Option
count := PreviewItemCount(*preview_library, state.practice)
for index: cast(s32)0..count - 1 {
items[index].label = PreviewItemName(*preview_library, state.practice, index)
}
picked := Dropdown.Draw(session, Dropdown.Props.{.key = 12, .bounds = .{x, y, width, 40.0},
.selected_index = state.item}, items[0:count]).selected_index
if picked != state.item && picked >= 0 && picked < count {
state.item = picked
state.seconds = 0.0
}
y += 54.0
if Button.Draw(session, Button.Props.{.key = 13, .bounds = .{x, y, width * 0.48, 40.0},
.label = ifx state.playing then "Pause" else "Play"}) != 0 {
if !state.playing && state.seconds >= duration {
state.seconds = 0.0
}
state.playing = !state.playing
preview_clock = 0
DesktopRequestFrame()
}
if Button.Draw(session, Button.Props.{.key = 14, .bounds = .{x + width * 0.52, y, width * 0.48, 40.0},
.label = "Front view"}) != 0 {
state.turn = 0.0
state.lift = 0.0
state.zoom = 1.0
}
y += 54.0
preview_page = 1 - preview_page
at := Slider.Draw(session, Slider.Props.{.key = cast(u64)(15 + preview_page * 1000), .bounds = .{x, y, width, 56.0},
.label = "Time", .value_text = PreviewSeconds(state.seconds, duration, preview_time_text[preview_page][:]), .value = cast(float32)state.seconds,
.min = 0.0, .max = cast(float32)duration})
if at.changed {
state.seconds = cast(float64)at.value
state.playing = false
}
y += 62.0
speed_digits: [32]u8
speed := Slider.Draw(session, Slider.Props.{.key = 16, .bounds = .{x, y, width, 64.0}, .label = "Speed",
.value_text = FormatDecimal(state.speed, 2, speed_digits[:]), .value = cast(float32)state.speed,
.min = 0.05, .max = 2.0})
if speed.changed {
state.speed = cast(float64)speed.value
}
y += 62.0
people: [2]Segmented.SegmentOption
people[0].label = "Woman"
people[1].label = "Man"
person := Segmented.Draw(session, Segmented.Props.{.key = 29, .bounds = .{x, y, width, 40.0},
.selected_index = ifx state.man then 1 else 0, .has_selection = true}, people[:]).selected_index
if person == 0 || person == 1 {
state.man = person == 1
}
y += 50.0
state.current = Toggle.Draw(session, Toggle.Props.{.key = 23, .bounds = .{x, y, width, 40.0},
.label = "Current flat figure", .value = state.current}).value
y += 56.0
note := "The figures are pixiv's CC0 VRoid sample models."
if !preview_figure.loaded {
note = "The figure could not be loaded."
}
if preview_failed {
note = "The stage could not be painted."
}
Text.Draw(session, Text.Props.{.key = 21, .bounds = .{x, y, width, 66.0}, .text = note, .size = 14})
y += 70.0
Text.Draw(session, Text.Props.{.key = 22, .bounds = .{x, y, width, 44.0},
.text = "Drag over the stage to turn around it; scroll to zoom.", .size = 14})
if state.practice == PREVIEW_ASTRAL && preview_library.astral_even {
y += 46.0
Text.Draw(session, Text.Props.{.key = 24, .bounds = .{x, y, width, 44.0},
.text = "These practices have no astral session timings yet; steps are 20 s apart.", .size = 14})
}
return 0
}
PreviewPaintStage :: (session: Session, area: Rectangle) {
state := *preview_state
if area.width < 16.0 || area.height < 16.0 {
return
}
if !state.current {
unused PreviewFigureUse(*preview_figure, TextView(preview_practices_path[0:preview_practices_length]), state.man)
}
moving := state.playing || state.dragging
scale := FigureMin(760.0 / cast(float64)area.height, 1.0)
width := cast(s32)(cast(float64)area.width * scale)
height := cast(s32)(cast(float64)area.height * scale)
if width < 16 || height < 16 {
return
}
key := PreviewKey(width, height)
if key != preview_painted_key || preview_texture.id == 0 {
started := Timer.MonotonicNanoseconds()
moment := PreviewSample(*preview_library, state.practice, state.item, state.seconds)
view := PreviewViewOf(*moment, state.turn, state.lift, state.zoom, cast(float64)width / cast(float64)height)
preview_failed = !PreviewStage(*preview_backdrops, state.practice, *moment, view, state.current,
*preview_figure, width, height, *preview_picture, state.seconds)
if !preview_failed {
texture := preview_texture
if texture.id != 0 && (texture.width != width || texture.height != height ||
preview_owner.slot != session.slot || preview_owner.epoch != session.epoch) {
BitmapImageRelease(preview_owner, texture)
texture = .{}
}
if texture.id == 0 {
texture = BitmapImageCreate(session, width, height, preview_picture.pixels[:])
preview_owner = session
} else if !BitmapImageUpdate(session, texture, preview_picture.pixels[:]) {
preview_failed = true
}
preview_texture = texture
preview_painted_key = key
if state.playing && !preview_failed {
PreviewTiming(started, width, height)
}
}
}
if preview_texture.id != 0 {
Image.Draw(session, Image.Props.{.key = 3, .bounds = area, .texture = preview_texture, .smooth = !moving,
.alt_text = "The practice stage"})
}
}
// Everything the picture depends on; the backdrop alone does not move.
PreviewKey :: (width: s32, height: s32) -> u64 {
state := *preview_state
digest: u64 = 1469598103934665603
moving := ifx state.current || preview_figure.loaded then 1.0 else 0.0
values: [9]float64 = .[cast(float64)state.practice, cast(float64)state.item, state.seconds * moving,
(state.turn + state.lift * 7.0 + state.zoom * 13.0) * moving, moving, cast(float64)width,
cast(float64)height, ifx state.current then 1.0 else 0.0, ifx state.man then 1.0 else 0.0]
for value: values {
bits := cast(u64)(value * 1000003.0 + 0.5)
digest = digest * 1099511628211 + bits
}
return digest
}
PreviewSeconds :: (seconds: float64, duration: float64, output: []u8) -> string {
first: [16]u8
second: [16]u8
a := FormatDecimal(seconds, 1, first[:])
b := FormatDecimal(duration, 1, second[:])
length: s64
for byte: a {
if length < output.count {
output[length] = byte
length += 1
}
}
joiner := " / "
for byte: joiner {
if length < output.count {
output[length] = byte
length += 1
}
}
for byte: b {
if length < output.count {
output[length] = byte
length += 1
}
}
return TextView(output[0:length])
}
// Time between rendered animation frames includes the desktop host's present
// and wait. Stage time includes sampling, skinning, rasterization and upload.
PreviewTiming :: (started: s64, width: s32, height: s32) {
timing := *preview_timing
state := *preview_state
if state.seconds < timing.last_seconds {
<<timing = .{}
}
if timing.last_paint != 0 {
timing.intervals[timing.count] = cast(float64)(started - timing.last_paint) / 1000000.0
timing.max_step = FigureMax(timing.max_step, 1000.0 * (state.seconds - timing.last_seconds))
timing.draw_ms += preview_last_draw_ms
if WindowVisibleHost() { timing.visible_frames += 1 }
if WindowFocusedHost() { timing.focused_frames += 1 }
if WindowMinimizedHost() { timing.minimized_frames += 1 }
timing.stage_ms += cast(float64)(Timer.MonotonicNanoseconds() - started) / 1000000.0
if !state.current {
timing.pose_ms += preview_figure.pose_ms
timing.render_ms += preview_figure.render_ms
timing.prepare_ms += preview_figure.prepare_ms
timing.submit_ms += preview_figure.submit_ms
timing.readback_ms += preview_figure.readback_ms
}
timing.count += 1
if timing.count == PREVIEW_TIMING_SAMPLES {
sorted: [PREVIEW_TIMING_SAMPLES]float64
for at: 0..PREVIEW_TIMING_SAMPLES - 1 {
value := timing.intervals[at]
spot := at
while spot > 0 && sorted[spot - 1] > value {
sorted[spot] = sorted[spot - 1]
spot -= 1
}
sorted[spot] = value
}
renderer := "Cairo"
if !state.current {
renderer = ifx preview_figure.accelerated then TextFromCString(*preview_figure.gpu.capabilities.renderer[0]) else "CPU"
}
count := cast(float64)PREVIEW_TIMING_SAMPLES
print("figure preview timing: %x%, p50 % ms, p95 % ms, draw % ms, stage % ms, pose % ms, raster % ms, prepare % ms, submit % ms, readback % ms, max step % ms, visible %/%, focused %, minimized %, renderer %\n",
width, height, (sorted[14] + sorted[15]) * 0.5, sorted[28], timing.draw_ms / count, timing.stage_ms / count,
timing.pose_ms / count, timing.render_ms / count, timing.prepare_ms / count,
timing.submit_ms / count, timing.readback_ms / count, timing.max_step, timing.visible_frames,
PREVIEW_TIMING_SAMPLES, timing.focused_frames, timing.minimized_frames, renderer)
unused PreviewFlushOutput(null)
<<timing = .{}
}
}
timing.last_paint = started
timing.last_seconds = state.seconds
}
PreviewPracticesPath :: () -> string {
variable: [32]u8
unused CopyCString("FIGURE_PRACTICES", variable[:])
named := PreviewGetEnvironment(*variable[0])
if named != null {
text := TextFromCString(named)
if text.count > 0 && text.count < 1024 {
return PreviewKeepPath(text)
}
}
// Ask beside the manifest, so the lock names the pinned checkout, then
// come back: capture paths stay relative to where the preview started.
started: [4096]u8
here := PreviewWorkingDirectory(*started[0], 4096)
unused Desktop.DesktopStartBeside("preview_practices.zi")
output: [1100]u8
arguments: [5]string = .["ziran", "pkg", "path", "practices", "--locked"]
result := CaptureOutput(arguments[:], output[:])
// A desktop launcher's PATH may not include the user's own commands.
home_name: [8]u8
unused CopyCString("HOME", home_name[:])
home := PreviewGetEnvironment(*home_name[0])
installed: [1100]u8
if (result.error || result.code != 0) && home != null {
arguments[0] = PreviewJoin(installed[:], TextFromCString(home), "/.local/bin/ziran")
result = CaptureOutput(arguments[:], output[:])
}
if here != null {
unused PreviewChangeDirectory(*started[0])
}
if result.error || result.code != 0 || result.length <= 1 {
return ""
}
length := result.length
while length > 0 && (output[length - 1] == 10 || output[length - 1] == 13) {
length -= 1
}
return PreviewKeepPath(TextView(output[0:length]))
}
#scope_file
PreviewKeepPath :: (text: string) -> string {
if text.count >= 1024 {
return ""
}
for index: 0..text.count - 1 {
preview_practices_path[index] = text[index]
}
preview_practices_length = text.count
return TextView(preview_practices_path[0:preview_practices_length])
}