diff --git a/docs/notes/render-video.md b/docs/notes/render-video.md index 6bfd3a9b6..6b99b3074 100644 --- a/docs/notes/render-video.md +++ b/docs/notes/render-video.md @@ -13,7 +13,10 @@ FlightFit a move flown by hand -> keys FrameRenderer one frame: every model drawn by its own renderer, composited FrameSink where frames go: image files, a GIF, or an encoder process GifWriter animated GIF: a palette per frame, ordered dither, LZW +ShotFrames a moment of the project -> what FrameRenderer draws +RenderOutput frame count, size, encoder choice and the sink of an export RenderSession the mode: viewport interaction, preview, playback, export +RenderCli `spirula render`: the same export with no window RenderPanel.cpp, RenderTimeline.cpp its panel and its timeline ``` @@ -426,6 +429,198 @@ ignored and missing ones take their defaults, so it can grow without a version bump. Sources are listed by path: opening a project opens the ones it names that are not open, and those open besides join it. +### Key by key + +`project_to_json` / `project_from_json` (`RenderProject.cpp`) are the +definition; this is what they read. Only `format` and `keyframes` are +needed. A name it does not know takes the default, and a number out of range +is clamped. + +**Coordinates.** Positions are in the primary model's (`sources[0]`) own +file coordinates or, when `placement` is given, in the frame that placement +moved the model into; opening the project moves them back. A rotation is +camera-to-world as a quaternion `[w, x, y, z]` with OpenGL camera axes: +x right, y up, looking down -z. + +| Key | Default | Meaning | +|---|---|---| +| `format` | (required) | `"spirula-render"` | +| `version` | `1` | | +| `up` | `[0, 0, 1]` | Which way is up for `look_at` keys and the 3D transitions | +| `background` | `[0, 0, 0]` | RGB, 0..1 | +| `end` | `0` | A loop's end, in seconds; 0 is one average key spacing after the last key | +| `placement` | identity | Row-major 3x4 `[sR\|t]`: the editor placement the keys were laid out against | +| `keyframes` | `[]` | The camera's path (below) | +| `sources` | `[]` | The models; `[0]` is the primary one (below) | +| `shots` | `[]` | Which model is shown when; empty shows `sources[0]` throughout (below) | +| `output`, `motion` | | Below | +| `fade_in`, `fade_out` | none | `{"colour": "none"\|"black"\|"white", "seconds": 1}` | + +**`keyframes[]`**, sorted by `time` on load. A video lasts until the last +key, or until `end` when it loops, and needs at least two keys. + +| Key | Default | Meaning | +|---|---|---| +| `time` | `0` | Seconds | +| `position` | `[0, 0, 0]` | | +| `rotation` | `[1, 0, 0, 0]` | Normalized on load | +| `look_at` | | A point to aim at; replaces `rotation` (which is then worked out from `position`, `up` and `roll`) | +| `roll` | `0` | Degrees about the view axis, with `look_at` | +| `lens` | | This key's own lens. The first key always has one; between keys with one, the lens glides | +| `hold` | `false` | The camera comes to rest here instead of passing through | +| `looks` | | `[{"source": i, "style": {...}}]`: a model's style from this key on, mixed between keys | + +**`lens`** + +| Key | Default | Meaning | +|---|---|---| +| `projection` | `perspective` | `perspective`, `fisheye`, `equisolid`, `equirectangular`, `orthographic` | +| `focal` | `0.866` | fx / image width. Perspective: FOV = 2 atan(0.5 / focal), so 0.866 is 60 degrees across, and 35 mm-equivalent = 36 x focal | +| `ortho_distance` | `1` | Orthographic: the distance its view width is taken at, world units | +| `distortion` | `0` | 0 none, 1 OpenCV, 2 thin prism | +| `coefficients` | 8 zeros | That model's coefficients, in its order | + +**`sources[]`**: `{"path": ..., "style": {...}}`. A splat `.ply`, a point +cloud or a mesh, kind by file. The CLI tries a relative path from the +current folder, then beside the project. At most 8 models. + +| `style` key | Default | For | +|---|---|---| +| `points` | `circle` | Points: `square`, `circle`, `gaussian`, `sphere` | +| `point_px` | `3` | Points: pixels at 1080 lines | +| `sphere_radius` | `0.004` | `sphere` points: share of the scene's size | +| `cameras` | `false` | A reconstruction's own cameras | +| `shade`, `flat`, `colour` | `true`, `false`, `true` | Meshes | +| `sh_degree` | `-1` | Splats: -1 is all the file has | +| `primitive` | automatic | Splats: a `--primitive` name, e.g. `3dgut` | + +**`shots[]`**, sorted by `start`: from `start` on, `source` (an index into +`sources`, or -1 for the background alone) is shown, coming in by +`transition` over `duration` seconds. + +| Key | Default | Meaning | +|---|---|---| +| `start` | `0` | Seconds | +| `source` | `0` | | +| `transition` | `cut` | `cut`, `crossfade`, `dip`, `wipe`, `iris`, `zoom`, and in 3D `sweep`, `grow`, `dust`, `spiral`, `scatter`, `rain`, `dissolve`, `ripple` | +| `duration` | `1` | Seconds | +| `params` | per transition | Two settings, below | +| `colour` | per transition | RGB 0..1: a dip's colour, a sweep's glow | +| `camera` | per transition | Move relative to the screen rather than the world's `up` | +| `exit` | | `{transition, duration, offset, params, colour, camera}`: leave its own way, `offset` seconds after the next shot starts (after the video's end, for the last shot) | + +A `dip` may only end the last shot. + +| Transition | `params[0]` | `params[1]` | +|---|---|---| +| `wipe` | direction, degrees (0) | softness (0.03) | +| `iris` | | softness (0.03) | +| `zoom` | strength (0.5) | | +| `sweep` | 1 down, 0 up (0) | glow (0.6) | +| `dust` | 0 fall, 1 rise, 2 blow away (0) | turbulence (0.5) | +| `spiral` | turns (1.25) | spread (1) | +| `scatter` | distance (1) | randomness (0.5) | +| `rain` | height (1.2) | stagger (0.7) | +| `dissolve` | sparkle (0.6) | | +| `ripple` | height (0.25) | width (0.3) | + +**`output`** + +| Key | Default | Meaning | +|---|---|---| +| `kind` | `video` | `video`, `frames` (a folder of images), `photo` | +| `width`, `height` | `1920`, `1080` | 16..16384; rounded to even for MP4 | +| `fps` | `30` | 1..240 | +| `codec` | `h264` | `h264`, `h265`, `av1` (MP4), `av1_webm`, `gif` | +| `quality` | `1` | 0 best, 1 standard, 2 smallest | +| `image_format` | `png` | Frames and photos: `png`, `png_alpha`, `jpeg` | +| `jpeg_quality` | `95` | 10..100 | +| `path` | | Where to write; the extension is made to fit `kind` and `codec`. From the CLI a relative path is from the current folder | + +**`motion`** + +| Key | Default | Meaning | +|---|---|---| +| `curve` | `spline` | `spline` (smooth through every key), `catmull_rom`, `linear` | +| `ease` | `true` | Start from rest and come to rest | +| `constant_speed` | `false` | The same speed all the way along | +| `loop` | `false` | Return to the first key; the video ends where it began | +| `tension` | `0` | `catmull_rom` only: 0 loose .. 1 a stop at every key | + +### An example + +A six-second orbit of a splat model, aimed at one point, at 720p: + +```json +{ + "format": "spirula-render", + "version": 1, + "up": [0, -1, 0], + "sources": [{"path": "splat_30000.ply"}], + "output": {"kind": "video", "width": 1280, "height": 720, "fps": 30, + "codec": "h264", "path": "orbit.mp4"}, + "fade_in": {"colour": "black", "seconds": 0.5}, + "keyframes": [ + {"time": 0, "position": [3.7, -0.6, 0.2], "look_at": [-0.3, 0.4, 0.2], + "lens": {"projection": "perspective", "focal": 0.8}}, + {"time": 3, "position": [-0.3, -0.6, 4.2], "look_at": [-0.3, 0.4, 0.2]}, + {"time": 6, "position": [-4.3, -0.6, 0.2], "look_at": [-0.3, 0.4, 0.2], "hold": true} + ] +} +``` + +To cut to a mesh and back, add it as a second source and say when each is +shown; the camera path stays the same: + +```json + "sources": [{"path": "splat_30000.ply"}, {"path": "mesh.obj"}], + "shots": [ + {"start": 0, "source": 0}, + {"start": 2.5, "source": 1, "transition": "crossfade", "duration": 1}, + {"start": 4.5, "source": 0, "transition": "dust", "duration": 1.5, "params": [0, 0.5]} + ] +``` + +The easiest way to find positions is to set a few keys in the GUI and save: +the saved file lists every key in this form. + +## From the command line + +`spirula render ` is mainly for projects generated outside +Spirula, by a script or another tool, in the format above; one saved by the +mode works too. It renders the way the mode's export does, through the same +`frame_spec` (`ShotFrames.cpp`), renderers, encoder choice and sinks +(`RenderOutput.cpp`): a CLI render and a GUI export of one project write the +same frames. The options override what the file says: + +``` +spirula render shot.json -o out.mp4 [--overwrite] + --model PATH the first model, instead of the one the file names + --kind video|frames|photo, --size WxH, --fps N, --quality 0|1|2 + --codec h264|h265|av1|av1-webm|gif (or av1_webm, as in the file; + a codec alone makes it a video) + --time S a photo's moment; the first key otherwise + --ffmpeg EXE which ffmpeg; `ffmpeg` on the PATH otherwise +``` + +Models are opened as a fresh GUI session opens them: in the file's own +coordinates, with no placement from the editor (keys laid out against a +`placement` are moved back by it), and a path that is not there is looked +for beside the project. Where no flag says otherwise, the `-o` extension +picks a photo or a video, the image format (`.jpg`, `.png`) and the +container (`.mp4`, `.webm`, `.gif`). An output that is already +there is replaced only with `--overwrite`. A frame that does not render +fails the whole render rather than leaving a broken frame in it; Ctrl+C +stops it, encoder probes included, and removes a half-written video. Exit +codes: 0 written, 1 failed, 2 a usage or project error, 130 stopped. + +OpenGL composites the frames and draws points and meshes, so the command +needs a GL context. `HeadlessGl` makes one from a hidden GLFW window, which +needs a display: on a server, run it under `xvfb-run`. Everything draws into +FBOs and `glx::set_proc_loader` takes any loader, so a display-less EGL +context on Linux would be one more `HeadlessGl::create` path; Windows and +macOS have no desktop-GL EGL and keep the window. + ## Testing `render_project_test` covers the pure half: the path through its keys, holds, diff --git a/src/app/Main.cpp b/src/app/Main.cpp index 17cb7c8e3..fced334f2 100644 --- a/src/app/Main.cpp +++ b/src/app/Main.cpp @@ -81,6 +81,7 @@ const std::vector& tools() { static const std::vector kTools = { #ifdef SS_TOOL_GUI {app::kToolGui, &cmsg::tool_gui, spirula_gui_main}, + {app::kToolRender, &cmsg::tool_render, spirula_render_main}, #endif #ifdef SS_TOOL_SFM {app::kToolSfm, &cmsg::tool_sfm, spirula_sfm_main}, diff --git a/src/app/README.md b/src/app/README.md index c5664b9c4..5fceac270 100644 --- a/src/app/README.md +++ b/src/app/README.md @@ -89,7 +89,7 @@ GUI (Basic Options) for remote monitoring. | `gui/ViewportPanel.h/.cpp` | Native viewport with two backends behind the browser-identical NavCamera navigation: **Preview** = GL point cloud + frusta as soon as the dataset parses (PreviewRenderer), **Engine** = RenderWorker once training starts, with all four web-viewer camera models (Pinhole / Fisheye-equidistant / Fisheye-equisolid / Equirectangular; `fovToIntrinsics` + per-model FOV ranges ported from viewer.html). One control row floating over the image's top-left corner (child windows submitted before the image, so the picture keeps the pane's height) -- the **Options** toggle, buffer picker, Reset view, point/triangle count and grid legend -- and the Options panel under it (`draw_options`), whose sections, all open by default, hold navigation (mode, speed, centre, saved views), lens, overlays (camera frusta with a live **frustum-size slider**, `ViewRequest::cam_size_scale`; grid, region, mesh shading) and rendering (render scale + live-refresh throttle, 0.15 s; a viewer's primitive, SH and colour space). The panel stays open beside a wide image and closes on an outside click over a narrow one. Linked panes share the navigation mode and speed. Initial framing: seed-point centroid target, median camera distance, camera-centroid direction. **Double-click centering** (viewer.html `recenterAt`): pan laterally so the 3D point under the cursor sits on the optical axis and make it the orbit pivot (rotate toward it when behind the camera plane, >180° models); preview mode picks the nearest displayed point along the cursor ray (3% angular cone, `PreviewRenderer::pick_point`), engine mode attaches `pick_px/py` to the next render and gets the point back in the ViewResult — depth-channel readback, no extra VRAM or render pass; all four display camera models via `viewer_pixel_ray`. | | `gui/CompareView.h/.cpp` + `gui/SplatViewer.h/.cpp` | **Up to four finished models under one camera** — the viewer screen, including a finished mesh beside its splats, is this. SplatViewer loads a file (3DGS PLY / point cloud / mesh, auto-detected) on a worker thread; splats land in an **engine scene slot** (`engine_scene_set_data_3dgs` / `engine_scene_activate`, Engine.h) so several stay resident and the RenderWorker binds one per render — a pointer swap instead of a per-pane re-upload. CompareView lays the panes out (1 / 2 / 3 / 2x2 by count), owns the ONE engine mutex every pane's worker takes, links the navigation, and gives each pane a similarity from its model's own normalized frame into the shared one — applied to the CAMERA, not the geometry, so the per-model position / rotation / size controls are free. That similarity defaults to "sit in the first model's frame", which is what aligns two reconstructions of one scene exactly and what places a mesh in its splats' frame. Design: `docs/notes/compare-view.md`. | | `gui/NavCamera.h/.cpp` | 1:1 port of viewer.html's `cam`/`quat`/`Nav`: quaternion camera, four modes (Turntable / Trackball / First Person / Free Fly), same sensitivities and mappings for **mouse** (LMB orbit-or-look, RMB/MMB/Shift pan, wheel dolly), **keyboard** (WASD/arrows, E/Q up-down or Fly-roll, active while the pointer is over the viewport), **gamepad** (GLFW gamepad API: left stick move, right stick look, triggers up-down/roll -- including the browser quirk that triggers only translate while the left stick is deflected), and **touch** via the OS's pointer/gesture emulation (single finger = orbit; system pinch/pan gestures arrive as wheel; GLFW exposes no raw multitouch). Keep in sync with viewer.html's Nav. The initial pose replicates `cam.reset()` verbatim (target = client-frame origin = the CAMERA-POSE center via center_method="poses", pos=[0,0,1], orbit(0,-250)) -- verified pixel-equivalent against a `/render` fetch from `spirula train`'s web viewer at the client's default c2w. `SS_NAV_DEBUG=1` logs per-frame mouse-drag nav decisions (button/pan/target/pos) to stderr. | -| `gui/PreviewRenderer.h/.cpp` + `gui/GlLoader.h/.cpp` | Offscreen-FBO GL renderer for the dataset preview (sparse points, vertex-colored + per-input camera frusta as center+offset lines scaled by a uniform). Frustum wireframes are built from each camera's TRUE model + distortion via `frustum_template` — a C++ port of `viewer/js/dataset.js` `frustumTemplate`/`generateRay`/`undistort` (itself a port of `fill_frustum_segments_kernel` / `projection_utils.cuh`): pinhole = classic border pyramid, wide models (fisheye/equisolid/equirect) = dome/globe with dimmed interior gridlines, Newton undistortion with the `is_valid_distortion` bail-out + bisect-toward-center for out-of-domain border pixels. (Before this, frusta were tan-based pinhole pyramids — a ~200° THIN_PRISM_FISHEYE dataset drew as giant crisscrossing triangles.) The display-side vertex shader implements the same camera models as the engine viewer (pinhole / fisheye-equidistant / equisolid / equirectangular; `u_s` = fx/(W/2), fy/(H/2), linear view-distance depth), so the preview -> engine transition at training start keeps pose AND intrinsics with no jump (ViewportPanel `maybe_frame` re-frames only when the dataset identity changes; navigation done in the preview carries into training, verified pixel-aligned at fisheye 333°). The projection function is shared with the fragment shader, which **re-projects the interpolated view-space position and discards fragments whose reprojection error exceeds 5% of the viewport** — the web viewer LINE_FS seam fix, killing the full-width streaks that segments crossing the equirect ±180° seam / fisheye backward point / pinhole near plane used to rasterize as. That check alone still keeps ~5%-viewport stubs at both ends of a wrapped segment (the error vanishes at the endpoints), which stack into ladder artifacts at the equirect edges — so line vertices also carry `a_delta` (this-endpoint − other-endpoint, pre-scale) and the vertex shader kills the WHOLE segment when its chord crosses the equirect seam half-plane (x=0, z>0 view space); same mechanism as the web viewer's `aDelta`/`vKill`. Optional **grid + axes** (viewport "grid" checkbox): power-of-10 ground grid + colored positive half-axes generated in the **training (saved-splat) frame** — lines mark round coordinates of the exported model — then mapped into the preview's normalized frame; the cell decade adapts to the nav distance and the finite line patch recenters on the orbit target (lattice-snapped, with hysteresis), cell edges subdivided 4x so they curve correctly under the non-pinhole projections; depth-tested like all preview geometry (`ensure_grid`). GlLoader = minimal namespaced (`glx::`) proc loader via glfwGetProcAddress; no GLEW/GLAD. | +| `gui/PreviewRenderer.h/.cpp` + `gui/GlLoader.h/.cpp` | Offscreen-FBO GL renderer for the dataset preview (sparse points, vertex-colored + per-input camera frusta as center+offset lines scaled by a uniform). Frustum wireframes are built from each camera's TRUE model + distortion via `frustum_template` — a C++ port of `viewer/js/dataset.js` `frustumTemplate`/`generateRay`/`undistort` (itself a port of `fill_frustum_segments_kernel` / `projection_utils.cuh`): pinhole = classic border pyramid, wide models (fisheye/equisolid/equirect) = dome/globe with dimmed interior gridlines, Newton undistortion with the `is_valid_distortion` bail-out + bisect-toward-center for out-of-domain border pixels. (Before this, frusta were tan-based pinhole pyramids — a ~200° THIN_PRISM_FISHEYE dataset drew as giant crisscrossing triangles.) The display-side vertex shader implements the same camera models as the engine viewer (pinhole / fisheye-equidistant / equisolid / equirectangular; `u_s` = fx/(W/2), fy/(H/2), linear view-distance depth), so the preview -> engine transition at training start keeps pose AND intrinsics with no jump (ViewportPanel `maybe_frame` re-frames only when the dataset identity changes; navigation done in the preview carries into training, verified pixel-aligned at fisheye 333°). The projection function is shared with the fragment shader, which **re-projects the interpolated view-space position and discards fragments whose reprojection error exceeds 5% of the viewport** — the web viewer LINE_FS seam fix, killing the full-width streaks that segments crossing the equirect ±180° seam / fisheye backward point / pinhole near plane used to rasterize as. That check alone still keeps ~5%-viewport stubs at both ends of a wrapped segment (the error vanishes at the endpoints), which stack into ladder artifacts at the equirect edges — so line vertices also carry `a_delta` (this-endpoint − other-endpoint, pre-scale) and the vertex shader kills the WHOLE segment when its chord crosses the equirect seam half-plane (x=0, z>0 view space); same mechanism as the web viewer's `aDelta`/`vKill`. Optional **grid + axes** (viewport "grid" checkbox): power-of-10 ground grid + colored positive half-axes generated in the **training (saved-splat) frame** — lines mark round coordinates of the exported model — then mapped into the preview's normalized frame; the cell decade adapts to the nav distance and the finite line patch recenters on the orbit target (lattice-snapped, with hysteresis), cell edges subdivided 4x so they curve correctly under the non-pinhole projections; depth-tested like all preview geometry (`ensure_grid`). GlLoader = minimal namespaced (`glx::`) proc loader via glfwGetProcAddress, or whatever `set_proc_loader` gave it (`render/HeadlessGl` for `spirula render`); no GLEW/GLAD. | | `gui/RoiEditor.h/.cpp` | **The region a dataset trains in**, drawn over its point cloud: boxes, ellipsoids, cylinders and outlines (extruded polygons drawn from above) added to, cut from or overlapped with each other (`data/RoiDocument.h`), with quick starts (box around the scene, cylinder or ellipsoid around an orbited subject, an outline drawn in the current view), an Adjust mode where hovering the selected shape lights the side under the pointer and dragging pushes or pulls that side alone, then Move / Resize (stretch or scale) / Rotate, every side also settable by number, undo, and the combined region shown live as the trainer will see it (boundary mesh, dimmed points, counts). Saves `/roi/.json`, which the trainer picks up unless told otherwise; opened beside Partition on the dataset screen and from the training screen's region row. docs/notes/roi-editor.md | | `gui/TrainRunner.h/.cpp` | TrainerSession on a worker thread: phases Idle→Loading→Ready→Preparing→Training→Done, pause/stop, metric history for plots, optional ViewerServer. Lifetime rule: viewport detaches before the session is replaced. | | `gui/PresetFile.h/.cpp` | The half of a saved preset that is the same whatever it is a preset OF: the `/presets` folder (one sub-folder per kind), the header every file carries (`spirula_preset` / `kind` / `name` / `description`), the probe that says which kind a dropped file is, and the listing that fills a dropdown. A file with no `kind` reads as a **train** preset -- they predate the key, and a run's `config.json` has never had one. `delete_preset_file()` refuses any path whose kind does not match, so nothing else can be removed through it. Written with `data/JsonWrite.h` (the writing half of `data/Json.h`: the commas, the indent and the string escape, once). | diff --git a/src/app/Tools.h b/src/app/Tools.h index 02b08cdbb..179637f46 100644 --- a/src/app/Tools.h +++ b/src/app/Tools.h @@ -56,6 +56,7 @@ constexpr const char* kToolSam = "sam"; constexpr const char* kToolGeometry = "geometry"; constexpr const char* kToolDense = "dense"; constexpr const char* kToolGui = "gui"; +constexpr const char* kToolRender = "render"; constexpr const char* kToolEncode = "encode"; constexpr const char* kToolE57 = "e57"; constexpr const char* kToolLidar = "lidar"; @@ -84,6 +85,8 @@ int spirula_dense_main(int argc, char** argv); #endif #ifdef SS_TOOL_GUI int spirula_gui_main(int argc, char** argv); +// Needs GL, so only where the window is built. +int spirula_render_main(int argc, char** argv); #endif #ifdef SS_TOOL_E57 int spirula_e57_main(int argc, char** argv); diff --git a/src/app/gui/CompareView.cpp b/src/app/gui/CompareView.cpp index 09e14ca62..60d812910 100644 --- a/src/app/gui/CompareView.cpp +++ b/src/app/gui/CompareView.cpp @@ -8,6 +8,7 @@ #include "app/gui/edit/MeshDoc.h" #include "app/gui/edit/PointsDoc.h" #include "app/gui/edit/SplatDoc.h" +#include "app/gui/render/ModelSource.h" #include "checkpoint/SplatPly.h" #include "core/Camera.h" #include "core/HostMemory.h" @@ -767,20 +768,10 @@ void CompareView::feed_render() { si.uid = m.uid; si.pane = i; si.name = display_name(m.src.file().empty() ? m.path : m.src.file()); + si.view = render::source_view_of(m.src); render::SourceView& v = si.view; - v.key = m.src.scene_key(); - spirula::Sim3 file_to_norm; - switch (m.src.kind()) { - case SplatViewer::Kind::Points: { - v.kind = render::SourceView::Points; - v.ds = &m.src.points(); - v.post = &m.src.post(); - double T[16], A[16]; - for (int k = 0; k < 16; k++) T[k] = v.ds->train_to_normalized[k]; - dsparse::invert_affine4x4(T, A); - double a[12]; - for (int k = 0; k < 12; k++) a[k] = A[k]; - file_to_norm = spirula::Sim3::from_3x4(a); + switch (v.kind) { + case render::SourceView::Points: { // Up as the pane shows it: the parsers' guess while it levels // the cameras, else the file's own +Z, which a measured or // hand-placed frame is known to have. @@ -790,25 +781,10 @@ void CompareView::feed_render() { si.up[k] = level ? v.ds->normalized_rotation[6 + k] : (k == 2 ? 1.0 : 0.0); break; } - case SplatViewer::Kind::Mesh: - v.kind = render::SourceView::Mesh; - v.mesh = &m.src.mesh(); + case render::SourceView::Mesh: si.dataset = run_dataset(m.src.file()); - for (int k = 0; k < 12; k++) v.mesh_t2n[k] = m.src.mesh_to_normalized()[k]; - file_to_norm = spirula::Sim3::from_3x4(m.src.mesh_to_normalized()); break; - default: { - v.kind = render::SourceView::Splats; - float t[12]; - m.src.to_view_frame(t); - file_to_norm = spirula::Sim3::from_3x4(t); - v.cfg = m.src.render_config(); - v.hooks = m.src.make_hooks(); - v.file = m.src.file(); - v.sh_max = m.src.sh_degree(); - v.gamut = m.src.gamut(); - v.transfer = m.src.transfer(); - v.linear = m.src.linear_color(); + default: si.dataset = run_dataset(v.file); // Splats deleted in the editor stay deleted in the render, // even while an effect rewrites the others. @@ -822,12 +798,10 @@ void CompareView::feed_render() { v.alive = _alive; } break; - } } - v.file_to_norm = file_to_norm; float e[12]; m.panel.edit_transform(e); - v.norm_to_world = file_to_norm.inverse() * spirula::Sim3::from_3x4(e); + v.norm_to_world = v.norm_to_world * spirula::Sim3::from_3x4(e); out.push_back(std::move(si)); } for (render::SourceInfo& si : out) { diff --git a/src/app/gui/GlLoader.cpp b/src/app/gui/GlLoader.cpp index ca9069497..d8615224a 100644 --- a/src/app/gui/GlLoader.cpp +++ b/src/app/gui/GlLoader.cpp @@ -51,6 +51,12 @@ void (*RenderbufferStorage)(GLenum, GLenum, GLsizei, GLsizei) = nullptr; void (*DeleteRenderbuffers)(GLsizei, const GLuint*) = nullptr; void (*ActiveTexture)(GLenum) = nullptr; +namespace { +ProcLoader g_loader = nullptr; +} + +void set_proc_loader(ProcLoader loader) { g_loader = loader; } + bool init() { static bool done = false, ok = false; if (done) return ok; @@ -58,7 +64,7 @@ bool init() { bool all = true; auto load = [&](auto& fn, const char* name) { fn = reinterpret_cast>( - glfwGetProcAddress(name)); + g_loader ? g_loader(name) : (void*)glfwGetProcAddress(name)); if (!fn) all = false; }; load(CreateShader, "glCreateShader"); diff --git a/src/app/gui/GlLoader.h b/src/app/gui/GlLoader.h index 1a0594520..a383d33a1 100644 --- a/src/app/gui/GlLoader.h +++ b/src/app/gui/GlLoader.h @@ -94,9 +94,12 @@ namespace glx { using glSizeiptr = std::ptrdiff_t; -// Load all pointers below via glfwGetProcAddress. Returns false if any is -// missing. Idempotent; call with a current GL context. +// Load all pointers below through the proc loader, glfwGetProcAddress unless +// one was set first. Returns false if any is missing. Idempotent; call with a +// current GL context. bool init(); +using ProcLoader = void* (*)(const char* name); +void set_proc_loader(ProcLoader loader); extern GLuint (*CreateShader)(GLenum type); extern void (*ShaderSource)(GLuint shader, GLsizei count, const char* const* string, const GLint* length); diff --git a/src/app/gui/render/HeadlessGl.cpp b/src/app/gui/render/HeadlessGl.cpp new file mode 100644 index 000000000..4e3685230 --- /dev/null +++ b/src/app/gui/render/HeadlessGl.cpp @@ -0,0 +1,59 @@ +#include "app/gui/render/HeadlessGl.h" + +#include "app/gui/GlLoader.h" +#include "app/gui/VulkanPrime.h" + +#include + +namespace gui::render { + +namespace { + +std::string g_glfw_error; + +void on_glfw_error(int, const char* text) { g_glfw_error = text ? text : ""; } + +void* glfw_proc(const char* name) { return (void*)glfwGetProcAddress(name); } + +} // namespace + +std::unique_ptr HeadlessGl::create(std::string& err) { + // Before any GL context (VulkanPrime.h). + prime_vulkan_driver(); + glfwSetErrorCallback(on_glfw_error); + if (!glfwInit()) { + err = g_glfw_error; + return nullptr; + } + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); + glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); +#ifdef __APPLE__ + glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE); +#endif + glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); + GLFWwindow* w = glfwCreateWindow(16, 16, "spirula render", nullptr, nullptr); + if (!w) { + err = g_glfw_error; + glfwTerminate(); + return nullptr; + } + glfwMakeContextCurrent(w); + glx::set_proc_loader(glfw_proc); + if (!glx::init()) { + err = "OpenGL 3.2 functions missing"; + glfwDestroyWindow(w); + glfwTerminate(); + return nullptr; + } + std::unique_ptr gl(new HeadlessGl()); + gl->_window = w; + return gl; +} + +HeadlessGl::~HeadlessGl() { + if (_window) glfwDestroyWindow((GLFWwindow*)_window); + glfwTerminate(); +} + +} // namespace gui::render diff --git a/src/app/gui/render/HeadlessGl.h b/src/app/gui/render/HeadlessGl.h new file mode 100644 index 000000000..bad06d221 --- /dev/null +++ b/src/app/gui/render/HeadlessGl.h @@ -0,0 +1,27 @@ +#pragma once + +// A current OpenGL 3.2-core context with nothing on screen, for renders with +// no window (`spirula render`). Everything draws into its own FBOs, so the +// context needs no surface; today it is a hidden GLFW window, which needs a +// display. A display-less backend (EGL) would be another create() path. + +#include +#include + +namespace gui::render { + +class HeadlessGl { +public: + // Current on the calling thread, glx's loader pointed at it; null with + // `err` set when no context can be made. + static std::unique_ptr create(std::string& err); + ~HeadlessGl(); + HeadlessGl(const HeadlessGl&) = delete; + HeadlessGl& operator=(const HeadlessGl&) = delete; + +private: + HeadlessGl() = default; + void* _window = nullptr; +}; + +} // namespace gui::render diff --git a/src/app/gui/render/ModelSource.cpp b/src/app/gui/render/ModelSource.cpp new file mode 100644 index 000000000..11ce48334 --- /dev/null +++ b/src/app/gui/render/ModelSource.cpp @@ -0,0 +1,50 @@ +#include "app/gui/render/ModelSource.h" + +#include "data/DatasetParser.h" + +namespace gui::render { + +SourceView source_view_of(SplatViewer& m) { + SourceView v; + v.key = m.scene_key(); + spirula::Sim3 file_to_norm; + switch (m.kind()) { + case SplatViewer::Kind::Points: { + v.kind = SourceView::Points; + v.ds = &m.points(); + v.post = &m.post(); + double T[16], A[16]; + for (int k = 0; k < 16; k++) T[k] = v.ds->train_to_normalized[k]; + dsparse::invert_affine4x4(T, A); + double a[12]; + for (int k = 0; k < 12; k++) a[k] = A[k]; + file_to_norm = spirula::Sim3::from_3x4(a); + break; + } + case SplatViewer::Kind::Mesh: + v.kind = SourceView::Mesh; + v.mesh = &m.mesh(); + for (int k = 0; k < 12; k++) v.mesh_t2n[k] = m.mesh_to_normalized()[k]; + file_to_norm = spirula::Sim3::from_3x4(m.mesh_to_normalized()); + break; + default: { + v.kind = SourceView::Splats; + float t[12]; + m.to_view_frame(t); + file_to_norm = spirula::Sim3::from_3x4(t); + v.cfg = m.render_config(); + v.hooks = m.make_hooks(); + v.file = m.file(); + v.sh_max = m.sh_degree(); + v.gamut = m.gamut(); + v.transfer = m.transfer(); + v.linear = m.linear_color(); + break; + } + } + v.file_to_norm = file_to_norm; + v.norm_to_world = file_to_norm.inverse(); + return v; +} + +} // namespace gui::render diff --git a/src/app/gui/render/ModelSource.h b/src/app/gui/render/ModelSource.h new file mode 100644 index 000000000..bc90e9598 --- /dev/null +++ b/src/app/gui/render/ModelSource.h @@ -0,0 +1,15 @@ +#pragma once + +// A loaded model as the render sees it: its kind, renderer settings and the +// frames between its file, its renderer and the project's world. Whoever +// shows it adds its placement and edits (CompareView, `spirula render`). + +#include "app/gui/SplatViewer.h" +#include "app/gui/render/FrameRenderer.h" + +namespace gui::render { + +// Ready `m`'s view, with `norm_to_world` the file's own frame: no placement. +SourceView source_view_of(SplatViewer& m); + +} // namespace gui::render diff --git a/src/app/gui/render/RenderCli.cpp b/src/app/gui/render/RenderCli.cpp new file mode 100644 index 000000000..1fdb94abc --- /dev/null +++ b/src/app/gui/render/RenderCli.cpp @@ -0,0 +1,399 @@ +// `spirula render `: a camera project, mostly one generated +// outside Spirula, rendered with no window through the same frames, renderers +// and sinks as Render mode's export (docs/notes/render-video.md). + +#include "app/Tools.h" +#include "app/gui/SplatViewer.h" +#include "app/gui/Subprocess.h" +#include "app/gui/render/FrameRenderer.h" +#include "app/gui/render/HeadlessGl.h" +#include "app/gui/render/ModelSource.h" +#include "app/gui/render/RenderOutput.h" +#include "app/gui/render/RenderProject.h" +#include "app/gui/render/ShotFrames.h" +#include "app/gui/render/Trajectory.h" +#include "engine/Engine.h" +#include "i18n/catalog/Render.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; +namespace msg = spirula::i18n::msg::render; +using spirula::i18n::format; + +namespace gui::render { +namespace { + +std::atomic g_stop{false}; + +void on_signal(int) { g_stop = true; } + +double now_s() { + using namespace std::chrono; + return duration(steady_clock::now().time_since_epoch()).count(); +} + +void sleep_ms(int ms) { std::this_thread::sleep_for(std::chrono::milliseconds(ms)); } + +int stopped() { + std::fprintf(stderr, "%s\n", msg::render_cancelled.get()); + return 130; +} + +struct Options { + std::string project, output, model, ffmpeg = "ffmpeg"; + int kind = -1, width = 0, height = 0, codec = -1, quality = -1; + double fps = 0.0, time = -1.0; + bool overwrite = false; +}; + +// 0 parsed, 1 help shown, 2 a usage error (already printed). +int parse(int argc, char** argv, Options& o) { + auto bad = [](const std::string& a) { + std::fprintf(stderr, "%s\n", format(msg::cli_bad_option, {a}).c_str()); + return 2; + }; + for (int i = 1; i < argc; i++) { + const std::string a = argv[i]; + const char* v = i + 1 < argc ? argv[i + 1] : nullptr; + auto take = [&]() { i++; return std::string(v); }; + if (a == "-h" || a == "--help") { + std::printf("%s\n", format(msg::cli_usage, {app::program_name()}).c_str()); + return 1; + } else if (a == "--overwrite") { + o.overwrite = true; + } else if (a == "-o" || a == "--output" || a == "--model" || a == "--kind" || + a == "--size" || a == "--fps" || a == "--codec" || a == "--quality" || + a == "--time" || a == "--ffmpeg") { + if (!v) return bad(a); + const std::string s = take(); + if (a == "-o" || a == "--output") o.output = s; + else if (a == "--model") o.model = s; + else if (a == "--ffmpeg") o.ffmpeg = s; + else if (a == "--kind") { + o.kind = s == "photo" ? (int)OutputKind::Photo : s == "video" ? (int)OutputKind::Video + : s == "frames" ? (int)OutputKind::Frames : -1; + if (o.kind < 0) return bad(a + " " + s); + } else if (a == "--size") { + if (std::sscanf(s.c_str(), "%dx%d", &o.width, &o.height) != 2 || o.width < 16 || + o.height < 16) + return bad(a + " " + s); + } else if (a == "--fps") { + o.fps = std::atof(s.c_str()); + if (o.fps <= 0.0) return bad(a + " " + s); + } else if (a == "--codec") { + o.codec = s == "h264" ? (int)Codec::H264 : s == "h265" ? (int)Codec::H265 + : s == "av1" ? (int)Codec::Av1 : s == "gif" ? (int)Codec::Gif + : s == "av1-webm" || s == "av1_webm" ? (int)Codec::Av1Webm : -1; + if (o.codec < 0) return bad(a + " " + s); + } else if (a == "--quality") { + o.quality = std::atoi(s.c_str()); + if (o.quality < 0 || o.quality > 2 || s.size() != 1) return bad(a + " " + s); + } else { + o.time = std::atof(s.c_str()); + } + } else if (!a.empty() && a[0] != '-' && o.project.empty()) { + o.project = a; + } else { + return bad(a); + } + } + if (o.project.empty()) { + std::fprintf(stderr, "%s\n", format(msg::cli_usage, {app::program_name()}).c_str()); + return 2; + } + return 0; +} + +// A model named relative to the project's own folder, when not to the +// working one. +std::string resolve_model(const std::string& path, const std::string& project) { + std::error_code ec; + if (path.empty() || fs::exists(fs::u8path(path), ec)) return path; + const fs::path beside = fs::u8path(project).parent_path() / fs::u8path(path); + return fs::exists(beside, ec) ? beside.u8string() : path; +} + +// What `-o`'s extension says, where no flag did: a photo or a video, the +// image format, the container. Before fit_output_path, which would rename it. +void follow_extension(Output& o, const Options& opt) { + std::string ext = fs::u8path(opt.output).extension().string(); + for (char& c : ext) c = (char)std::tolower((unsigned char)c); + const bool jpeg = ext == ".jpg" || ext == ".jpeg"; + const bool image = jpeg || ext == ".png"; + const bool video = ext == ".mp4" || ext == ".gif" || ext == ".webm"; + if (opt.kind < 0 && opt.codec < 0) { + if (image && o.kind == OutputKind::Video) o.kind = OutputKind::Photo; + else if (video && o.kind != OutputKind::Video) o.kind = OutputKind::Video; + } + if (image && o.kind != OutputKind::Video) { + if (jpeg) o.format = ImageFormat::Jpeg; + else if (o.format == ImageFormat::Jpeg) o.format = ImageFormat::Png; + } + if (o.kind == OutputKind::Video && opt.codec < 0) { + if (ext == ".gif") o.codec = Codec::Gif; + else if (ext == ".webm") o.codec = Codec::Av1Webm; + else if (ext == ".mp4" && (o.codec == Codec::Gif || o.codec == Codec::Av1Webm)) + o.codec = Codec::H264; + } +} + +struct Models { + std::mutex engine; + std::vector> viewers; + ~Models() { + for (auto& v : viewers) v->close(); + } +}; + +void remove_partial(const Output& o) { + if (o.kind != OutputKind::Video) return; + std::error_code ec; + fs::remove(fs::u8path(o.path), ec); +} + +enum Pass { kWritten = 0, kRenderFailed, kSinkFailed, kStopped }; + +// Every frame into a fresh sink; `err` says why when it did not finish. +Pass render_all(const RenderProject& p, FrameRenderer& fr, const std::vector& rt, + const Encoder& e, double photo_time, std::string& err) { + const Output& o = p.output; + const bool photo = o.kind == OutputKind::Photo; + const int frames = frame_count(p); + int W = 0, H = 0; + output_size(o, W, H); + const Trajectory tr(p); + std::unique_ptr sink = open_output_sink(p, e, frames); + const double first = p.keys.front().time; + auto time_of = [&](int i) { + return photo ? photo_time : std::min(first + i / std::max(o.fps, 1.0), p.duration()); + }; + auto give_up = [&](Pass why) { + sink->cancel(); + remove_partial(o); + return why; + }; + // Each frame goes to the renderers before the one before it is read + // back and written, so the two overlap as in the mode's export. + fr.request(frame_spec(p, tr, fr, rt, time_of(0), W, H, photo)); + double said = now_s(); + for (int i = 0; i < frames; i++) { + while (!fr.poll(0.25)) + if (g_stop) return give_up(kStopped); + err = fr.take_error(); + if (!err.empty()) { + err = format(msg::render_error, {err}); + return give_up(kRenderFailed); + } + if (i + 1 < frames) fr.request(frame_spec(p, tr, fr, rt, time_of(i + 1), W, H, photo)); + std::vector px; + fr.read(px, sink->channels() == 4); + if (!sink->push(std::move(px))) { + err = sink->error(); + return give_up(kSinkFailed); + } + if (g_stop) return give_up(kStopped); + if (frames > 1 && (now_s() - said >= 1.0 || i + 1 == frames)) { + said = now_s(); + std::printf("%s\n", + format(msg::cli_progress, {(long long)(i + 1), (long long)frames}).c_str()); + } + } + fr.abandon(); + if (!sink->finish()) { + err = sink->error(); + remove_partial(o); + return kSinkFailed; + } + return kWritten; +} + +int run(const Options& opt) { + RenderProject p; + try { + p = load_project(opt.project); + } catch (const std::exception& e) { + std::fprintf(stderr, "%s\n", + format(msg::cli_project_unreadable, {opt.project, e.what()}).c_str()); + return 2; + } + // Laid out against a moved model; the models open unmoved, as in the mode. + if (!p.placement.is_identity(1e-9)) { + transform_project(p, p.placement.inverse()); + p.placement = spirula::Sim3(); + } + Output& o = p.output; + if (opt.kind >= 0) o.kind = (OutputKind)opt.kind; + if (opt.codec >= 0) { + o.codec = (Codec)opt.codec; + if (opt.kind < 0) o.kind = OutputKind::Video; + } + if (opt.width > 0) { o.width = opt.width; o.height = opt.height; } + if (opt.fps > 0.0) o.fps = opt.fps; + if (opt.quality >= 0) o.quality = opt.quality; + if (!opt.output.empty()) { + o.path = opt.output; + follow_extension(o, opt); + } + if (!opt.model.empty() && !p.sources.empty()) p.sources[0].path = opt.model; + if (p.sources.empty() && !opt.model.empty()) p.sources.push_back(Source{opt.model, {}}); + for (Source& s : p.sources) s.path = resolve_model(s.path, opt.project); + + if (p.keys.empty()) { + std::fprintf(stderr, "%s\n", msg::cli_no_keys.get()); + return 2; + } + const bool photo = o.kind == OutputKind::Photo; + if (!photo && p.duration() <= p.keys.front().time) { + std::fprintf(stderr, "%s\n", msg::need_two_keys.get()); + return 2; + } + if (o.path.empty()) { + std::fprintf(stderr, "%s\n", msg::cli_no_output.get()); + return 2; + } + fit_output_path(o); + if (!opt.overwrite && existing_output(o) > 0) { + std::fprintf(stderr, "%s\n", format(msg::cli_output_exists, {o.path}).c_str()); + return 2; + } + if (p.sources.empty() || p.sources[0].path.empty()) { + std::fprintf(stderr, "%s\n", msg::cli_no_model.get()); + return 2; + } + if ((int)p.sources.size() > kMaxEngineScenes) { + std::fprintf(stderr, "%s\n", format(msg::cli_too_many_models, + {(long long)p.sources.size(), (long long)kMaxEngineScenes}).c_str()); + return 2; + } + for (const Source& s : p.sources) { + std::error_code ec; + if (!fs::exists(fs::u8path(s.path), ec)) { + std::fprintf(stderr, "%s\n", format(msg::project_model_missing, {s.path}).c_str()); + return 2; + } + } + + // Asked while the models load; a photo or frames need no encoder. + std::vector ff_encoders; + int gpu_codecs = 0, gpu_max[3][2] = {}; + std::thread probe; + const bool mp4 = output_is_mp4(o); + if (mp4) + probe = std::thread([&] { + ff_encoders = probe_ffmpeg_encoders(opt.ffmpeg, g_stop); + if (!g_stop) gpu_codecs = probe_builtin_encoder(gpu_max, g_stop); + }); + struct Joiner { + std::thread& t; + ~Joiner() { if (t.joinable()) t.join(); } + } joiner{probe}; + + std::string err; + std::unique_ptr gl = HeadlessGl::create(err); + if (!gl) { + std::fprintf(stderr, "%s\n", format(msg::cli_no_gl, {err}).c_str()); + return 1; + } + + Models models; + { + std::lock_guard lk(models.engine); + engine_reset(); + } + for (size_t i = 0; i < p.sources.size(); i++) { + auto v = std::make_unique(); + v->open(p.sources[i].path, (int)i, &models.engine, 0); + models.viewers.push_back(std::move(v)); + } + for (size_t i = 0; i < models.viewers.size(); i++) { + SplatViewer& v = *models.viewers[i]; + while (v.state() == SplatViewer::State::Loading) { + if (g_stop) return stopped(); + sleep_ms(20); + } + for (const std::string& line : v.drain_log()) std::printf("%s\n", line.c_str()); + if (!v.ready()) { + std::fprintf(stderr, "%s\n", + format(msg::cli_model_failed, {p.sources[i].path, v.error()}).c_str()); + return 1; + } + } + + Pass rc = kRenderFailed; + { + FrameRenderer fr; + struct GlRelease { + FrameRenderer& fr; + ~GlRelease() { fr.destroy_gl(); } + } release{fr}; + std::vector views; + std::vector rt; + for (auto& v : models.viewers) { + rt.push_back((int)views.size()); + views.push_back(source_view_of(*v)); + } + fr.set_sources(views); + // Effects that rewrite splats need them read first. + for (bool ready = false; !ready;) { + ready = true; + for (int i = 0; i < fr.source_count(); i++) ready = fr.effects_ready(i) && ready; + if (g_stop) return stopped(); + if (!ready) sleep_ms(20); + } + + Encoder e; + if (mp4) { + if (probe.joinable()) probe.join(); + if (g_stop) return stopped(); + int W = 0, H = 0; + output_size(o, W, H); + const bool gpu = builtin_encodes(gpu_codecs, gpu_max, o.codec, W, H); + e = pick_encoder(o, gpu, opt.ffmpeg, &ff_encoders); + if (e.kind == Encoder::None) { + std::fprintf(stderr, "%s\n", msg::no_encoder.get()); + return 1; + } + } + const double photo_time = opt.time >= 0.0 ? opt.time : p.keys.front().time; + rc = render_all(p, fr, rt, e, photo_time, err); + if (rc == kSinkFailed && e.kind == Encoder::BuiltIn && command_exists(opt.ffmpeg)) { + // The GPU would not do it after all: ffmpeg, from the first frame. + std::printf("%s\n", format(msg::encoder_fallback, + {err.substr(0, err.find('\n'))}).c_str()); + e = pick_encoder(o, false, opt.ffmpeg, &ff_encoders); + if (e.kind != Encoder::None) rc = render_all(p, fr, rt, e, photo_time, err); + } + } + if (rc == kStopped) return stopped(); + if (rc != kWritten) { + std::fprintf(stderr, "%s\n", format(msg::render_failed, {err}).c_str()); + return 1; + } + std::printf("%s\n", format(msg::render_saved, {o.path}).c_str()); + return 0; +} + +} // namespace +} // namespace gui::render + +int spirula_render_main(int argc, char** argv) { + app::set_program_name(argv[0], "spirula render"); + gui::render::Options o; + const int parsed = gui::render::parse(argc, argv, o); + if (parsed) return parsed == 1 ? 0 : 2; + std::signal(SIGINT, gui::render::on_signal); + std::signal(SIGTERM, gui::render::on_signal); + return gui::render::run(o); +} diff --git a/src/app/gui/render/RenderOutput.cpp b/src/app/gui/render/RenderOutput.cpp new file mode 100644 index 000000000..616582f1d --- /dev/null +++ b/src/app/gui/render/RenderOutput.cpp @@ -0,0 +1,142 @@ +#include "app/gui/render/RenderOutput.h" + +#include "app/AppPaths.h" +#include "app/gui/Subprocess.h" + +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +namespace gui::render { + +int frame_count(const RenderProject& p) { + if (p.output.kind == OutputKind::Photo || p.keys.empty()) return 1; + const double span = std::max(0.0, p.duration() - p.keys.front().time); + const long n = std::lround(span * std::max(p.output.fps, 1.0)); + // A loop's last frame would be its first again. + return (int)std::max(1L, p.looped() ? n : n + 1); +} + +bool output_is_mp4(const Output& o) { return o.kind == OutputKind::Video && o.codec != Codec::Gif; } + +void output_size(const Output& o, int& W, int& H) { + W = std::max(16, o.width); + H = std::max(16, o.height); + if (output_is_mp4(o)) { W += W & 1; H += H & 1; } +} + +int existing_output(const Output& o) { + std::error_code ec; + const fs::path out = fs::u8path(o.path); + if (o.kind != OutputKind::Frames) return fs::exists(out, ec) ? 1 : 0; + int n = 0; + if (fs::is_directory(out, ec)) + for (const auto& e : fs::directory_iterator(out, ec)) { + const std::string name = e.path().filename().string(); + const std::string ext = e.path().extension().string(); + if (name.rfind("frame_", 0) == 0 && (ext == ".png" || ext == ".jpg")) n++; + } + return n; +} + +// It encodes two frames with each codec, since a device can list a codec and +// still refuse a session. +int probe_builtin_encoder(int max[3][2], const std::atomic& cancel) { +#ifdef SS_TOOL_ENCODE + int codecs = 0; + const int code = run_process({app::exe_path(), "encode", "--probe"}, "", + [&](const std::string& line) { + // "h264 4096 4096": a codec and the largest frame it takes. + char name[16] = {}; + int w = 0, h = 0; + if (std::sscanf(line.c_str(), "%15s %d %d", name, &w, &h) < 1) return; + const int c = std::string(name) == "h264" ? 0 : std::string(name) == "h265" ? 1 + : std::string(name) == "av1" ? 2 : -1; + if (c < 0) return; + codecs |= 1 << c; + max[c][0] = w > 0 ? w : 4096; + max[c][1] = h > 0 ? h : 4096; + }, cancel); + return code == 0 ? codecs : 0; +#else + (void)max; + (void)cancel; + return 0; +#endif +} + +std::vector probe_ffmpeg_encoders(const std::string& ffmpeg, + const std::atomic& cancel) { + std::vector lines; + if (command_exists(ffmpeg)) + run_process({ffmpeg, "-hide_banner", "-encoders"}, "", + [&](const std::string& line) { lines.push_back(line); }, cancel); + return parse_ffmpeg_encoders(lines); +} + +bool builtin_encodes(int codecs, const int max[3][2], Codec codec, int width, int height) { + // WebM is ffmpeg's; the GPU encoder writes MP4 only. + if (codec == Codec::Gif || codec == Codec::Av1Webm) return false; + const int c = (int)codec; + return (codecs & (1 << c)) && width <= max[c][0] && height <= max[c][1]; +} + +Encoder pick_encoder(const Output& o, bool gpu, const std::string& ffmpeg, + const std::vector* ffmpeg_encoders) { + Encoder e; + Encoder ff; + if (command_exists(ffmpeg)) { + const std::vector& want = ffmpeg_encoders_for(o.codec); + if (!ffmpeg_encoders) { + if (!want.empty()) ff = {Encoder::Ffmpeg, ffmpeg, want[0]}; + } else { + for (const std::string& name : want) + if (std::find(ffmpeg_encoders->begin(), ffmpeg_encoders->end(), name) != + ffmpeg_encoders->end()) { + ff = {Encoder::Ffmpeg, ffmpeg, name}; + break; + } + } + } + // The GPU for H.264 and H.265. Its AV1 predicts only from key frames + // (src/video/README.md), so an AV1 encoder in ffmpeg makes the smaller file. + const bool gpu_first = o.codec != Codec::Av1 || ff.kind == Encoder::None; + if (gpu && gpu_first) { + e.kind = Encoder::BuiltIn; + e.exe = app::exe_path(); + return e; + } + if (ff.kind != Encoder::None) return ff; + if (gpu) { + e.kind = Encoder::BuiltIn; + e.exe = app::exe_path(); + } + return e; +} + +std::unique_ptr open_output_sink(const RenderProject& p, const Encoder& e, int frames) { + const Output& o = p.output; + int W = 0, H = 0; + output_size(o, W, H); + if (output_is_mp4(o)) { + std::error_code ec; + const fs::path parent = fs::u8path(o.path).parent_path(); + if (!parent.empty()) fs::create_directories(parent, ec); + const bool sphere = !p.keys.empty() && p.lens_at(0).projection == Projection::Equirect; + return open_pipe_sink(encoder_argv(e, W, H, o.fps, o.codec, o.quality, sphere, o.path)); + } + if (o.kind == OutputKind::Video) return open_gif_sink(o.path, W, H, o.fps, frames, o.quality); + std::string path = o.path; + if (o.kind == OutputKind::Frames) { + // A folder: the frames are numbered inside it. + path = (fs::u8path(o.path) / + (o.format == ImageFormat::Jpeg ? "frame_%05d.jpg" : "frame_%05d.png")).string(); + } + return open_image_sink(path, W, H, o.format, o.jpeg_quality); +} + +} // namespace gui::render diff --git a/src/app/gui/render/RenderOutput.h b/src/app/gui/render/RenderOutput.h new file mode 100644 index 000000000..a80dc79bf --- /dev/null +++ b/src/app/gui/render/RenderOutput.h @@ -0,0 +1,43 @@ +#pragma once + +// What an export of a RenderProject writes and with what: how many frames, +// at what size, which encoder, and the sink they go into. Shared by the +// render mode and `spirula render`. + +#include "app/gui/render/FrameSink.h" +#include "app/gui/render/RenderProject.h" + +#include +#include +#include +#include + +namespace gui::render { + +// Frames the output has: one a photo, a loop's last left out. +int frame_count(const RenderProject& p); +// The size frames are rendered at: at least 16, even for an encoder. +void output_size(const Output& o, int& W, int& H); +bool output_is_mp4(const Output& o); +// What a render would replace: frame files in the folder for frames, else 1 +// when the file is there. +int existing_output(const Output& o); + +// Blocking until done or `cancel`. What `spirula encode --probe` says this GPU +// encodes: a bit per Codec up to Av1 and each one's largest frame; else 0. +int probe_builtin_encoder(int max[3][2], const std::atomic& cancel); +// ffmpeg's encoders, empty when there is no ffmpeg. +std::vector probe_ffmpeg_encoders(const std::string& ffmpeg, + const std::atomic& cancel); +bool builtin_encodes(int codecs, const int max[3][2], Codec codec, int width, int height); + +// `gpu`: the built-in encoder takes this output. `ffmpeg_encoders` null when +// not known yet, which assumes the usual first choice. +Encoder pick_encoder(const Output& o, bool gpu, const std::string& ffmpeg, + const std::vector* ffmpeg_encoders); + +// The sink for `p`'s output: an encoder for an MP4 or WebM (`e`), a GIF, +// numbered frames in a folder, or one photo. +std::unique_ptr open_output_sink(const RenderProject& p, const Encoder& e, int frames); + +} // namespace gui::render diff --git a/src/app/gui/render/RenderSession.cpp b/src/app/gui/render/RenderSession.cpp index 74d81f135..2a75b4c2c 100644 --- a/src/app/gui/render/RenderSession.cpp +++ b/src/app/gui/render/RenderSession.cpp @@ -2,6 +2,8 @@ // the export; the panel is RenderPanel.cpp, the timeline RenderTimeline.cpp. #include "app/gui/render/RenderSession.h" +#include "app/gui/render/RenderOutput.h" +#include "app/gui/render/ShotFrames.h" #include "app/AppPaths.h" #include "app/gui/Layout.h" @@ -63,11 +65,6 @@ void rotate_quat(const Sim3& s, const double q[4], double out[4]) { quat_from_matrix3(M, out); } -double smooth(double u) { - u = std::clamp(u, 0.0, 1.0); - return u * u * (3.0 - 2.0 * u); -} - std::string seconds_text(double s) { char b[32]; std::snprintf(b, sizeof b, "%.1f", s); @@ -1892,345 +1889,11 @@ void RenderSession::draw_viewport_overlay(const ViewportOverlay& v) { // Frames // =========================================================================== -// The frame a 3D transition moves `source` in: the world's up, or the -// camera's -- down the picture for what falls, round its middle for what -// turns or ripples, about the view's own axis at the scene's depth. -bool RenderSession::fx_frame(Transition kind, bool camera, int source, const FrameSpec& f, - LayerFx& x) { - SceneCore core; - if (source < 0 || !_frames.scene_core(source, core)) return false; - for (int k = 0; k < 3; k++) x.centre[k] = core.centre[k]; - x.radius = core.radius; - const bool seen = camera && transition_has_camera(kind); - FxView view; - if (seen) { - const CameraState& cam = f.cam; - double R[9]; - quat_to_matrix3(cam.rot, R); - const double right[3] = {R[0], R[3], R[6]}, cup[3] = {R[1], R[4], R[7]}, - back[3] = {R[2], R[5], R[8]}; - double depth = 0.0; - for (int k = 0; k < 3; k++) depth -= (core.centre[k] - cam.pos[k]) * back[k]; - depth = std::max(depth, 0.5 * core.radius); - if (kind == Transition::Spiral || kind == Transition::Ripple) { - for (int k = 0; k < 3; k++) { - x.centre[k] = cam.pos[k] - back[k] * depth; - x.up[k] = kind == Transition::Spiral ? -back[k] : back[k]; - x.e1[k] = right[k]; - x.e2[k] = cup[k]; - } - } else { - for (int k = 0; k < 3; k++) { - x.up[k] = cup[k]; - x.e1[k] = right[k]; - x.e2[k] = back[k]; - } - } - // What the picture takes in: only that is ordered, and the moves are - // as wide as the picture at the scene's depth, so a long lens or a - // camera up close still sees the change from its start. - const double hx = 0.5 * std::min(lens_fov(cam.lens), 360.0) * kPi / 180.0; - const double aspect = (double)std::max(f.height, 1) / std::max(f.width, 1); - const bool pinhole = cam.lens.projection == Projection::Perspective; - const bool ortho = cam.lens.projection == Projection::Orthographic; - const double hy = pinhole || ortho ? std::atan(std::tan(hx) * aspect) : hx * aspect; - for (int k = 0; k < 3; k++) { - view.pos[k] = cam.pos[k]; - view.fwd[k] = -back[k]; - view.right[k] = right[k]; - view.up[k] = cup[k]; - } - if (ortho) { - view.orthographic = true; - view.tx = 0.5 * cam.lens.ortho_distance / cam.lens.focal * 1.1; - view.ty = view.tx * aspect; - } else if (pinhole) { - view.tx = std::tan(hx) * 1.1; - view.ty = std::tan(hy) * 1.1; - } else { - view.cone = std::min(std::max(hx, hy) * 1.1, kPi); - } - const double a = std::clamp(std::min(hx, hy), 5.0 * kPi / 180.0, kPi / 3.0); - const double radius = ortho ? std::min(view.tx, view.ty) / 1.1 : depth * std::tan(a); - x.radius = std::clamp(radius, 0.05 * core.radius, core.radius); - } else { - double n = 0.0; - for (int k = 0; k < 3; k++) n += _project.up[k] * _project.up[k]; - n = std::sqrt(std::max(n, 1e-24)); - for (int k = 0; k < 3; k++) x.up[k] = _project.up[k] / n; - // Any two across up, the same two every frame. - double a[3] = {1, 0, 0}; - if (std::fabs(x.up[0]) > 0.9) { a[0] = 0; a[1] = 1; } - double e1[3] = {a[1]*x.up[2] - a[2]*x.up[1], a[2]*x.up[0] - a[0]*x.up[2], - a[0]*x.up[1] - a[1]*x.up[0]}; - const double n1 = std::sqrt(e1[0]*e1[0] + e1[1]*e1[1] + e1[2]*e1[2]); - for (int k = 0; k < 3; k++) x.e1[k] = e1[k] / std::max(n1, 1e-12); - x.e2[0] = x.up[1]*x.e1[2] - x.up[2]*x.e1[1]; - x.e2[1] = x.up[2]*x.e1[0] - x.up[0]*x.e1[2]; - x.e2[2] = x.up[0]*x.e1[1] - x.up[1]*x.e1[0]; - } - return _frames.scene_quantiles(source, x.centre, x.up, x.e1, x.e2, x.q, seen ? &view : nullptr); -} - -namespace { - -// A sweep's level when `k` of the elements are behind it, world frame: in -// step with the elements rather than the distance, so a far sky costs no -// more of it than the rest; led in and out past the first and the last. -double sweep_level(const LayerFx& x, double k) { - const double base = x.centre[0]*x.up[0] + x.centre[1]*x.up[1] + x.centre[2]*x.up[2]; - const double span = std::max((double)(fx_quantile(x.q.qh, 0.98f) - fx_quantile(x.q.qh, 0.02f)), - 1e-9 * x.radius); - constexpr double m = 0.06; - const double kk = -m + k * (1.0 + 2.0 * m); - if (kk < 0.0) return base + x.q.qh[0] + kk / m * 0.08 * span; - if (kk > 1.0) return base + x.q.qh[kFxQuantiles - 1] + (kk - 1.0) / m * 0.08 * span; - return base + fx_quantile(x.q.qh, (float)kk); -} - -void set_sweep(LayerSpec& l, const LayerFx& x, double k, bool keep_below, float glow, - const float colour[3]) { - l.clip = keep_below ? 1 : 2; - for (int d = 0; d < 3; d++) l.clip_n[d] = x.up[d]; - l.level = sweep_level(x, k); - const double span = fx_quantile(x.q.qh, 0.98f) - fx_quantile(x.q.qh, 0.02f); - l.glow = (float)(0.07 * std::max(span, 1e-9 * x.radius) * std::clamp(glow, 0.0f, 1.0f)); - for (int d = 0; d < 3; d++) l.glow_col[d] = colour[d]; -} - -} // namespace - -// One layer's own way in or out, `u` through it, composited on its own -// (mode 3) with the whole change to itself. At the video's start or end -// (`edge`) a dip is from or into its colour. -void RenderSession::side_effect(FrameSpec& f, LayerSpec& l, Transition kind, double u, bool in, - const float param[2], const float colour[3], bool camera, - bool edge) { - if (l.source < 0) return; - const double v = in ? u : 1.0 - u; // how much of it there is - // Arriving from nothing, on its way at once rather than easing in. - const double shown = in ? 1.0 - (1.0 - u) * (1.0 - u) : smooth(v); - switch (kind) { - case Transition::Cut: - if (!in && u >= 1.0) l.source = -1; - break; - case Transition::Crossfade: - l.opacity = (float)shown; - break; - case Transition::Dip: { - for (int k = 0; k < 3; k++) f.tint[0][k] = colour[k]; - // From its colour at the start, into it at the end; elsewhere - // through it, the model there from the middle on. - const double amount = edge ? (in ? 1.0 - smooth(u) : smooth(u)) - : u < 0.5 ? smooth(u * 2.0) : 1.0 - smooth(u * 2.0 - 1.0); - f.tint[0][3] = (float)std::max((double)f.tint[0][3], amount); - if (!edge && (in ? u < 0.5 : u >= 0.5)) l.opacity = 0.0f; - break; - } - case Transition::Wipe: { - const double ang = param[0] * kPi / 180.0; - l.mask = 1; - l.mask_t = (float)u; - l.mask_out = !in; - l.mask_dir[0] = (float)std::cos(ang); - l.mask_dir[1] = (float)-std::sin(ang); - l.mask_soft = std::max(param[1], 0.002f); - break; - } - case Transition::Iris: - l.mask = 2; - l.mask_t = (float)(in ? shown : smooth(u)); - l.mask_out = !in; - l.mask_soft = std::max(param[1], 0.002f); - break; - case Transition::Zoom: { - // Arriving from far and smeared, or rushing past the camera; in - // sight for all but the far end of it. - const double z = std::clamp(param[0], 0.05f, 2.0f), r = 1.0 - v; - l.zoom = (float)(in ? 1.0 / (1.0 + 2.0 * z * r * r) : 1.0 + 2.0 * z * r * r); - l.zoom_blur = (float)(z * r); - l.opacity = (float)smooth(std::clamp(v / 0.45, 0.0, 1.0)); - break; - } - case Transition::Grow: - l.grow = (float)(0.02 + 0.98 * smooth(v)); - l.fade_in = (float)std::min(1.0, v * 2.5); - break; - default: { - LayerFx x; - if (!fx_frame(kind, camera, l.source, f, x)) { - l.opacity = (float)shown; - break; - } - if (kind == Transition::Sweep) { - // The level passes it: what is left of it on the far side. - const bool down = param[0] >= 0.5f; - set_sweep(l, x, smooth(down ? 1.0 - u : u), in != down, param[1], colour); - break; - } - x.kind = (int)kind; - x.incoming = in; - x.t = fx_solo_time((int)kind, in, (float)u, param); - x.p[0] = param[0]; - x.p[1] = param[1]; - l.fx = x; - break; - } - } -} - FrameSpec RenderSession::frame_spec(double t, int W, int H, bool photo) { - FrameSpec f; - f.cam = trajectory().at(t); - f.width = W; - f.height = H; - for (int k = 0; k < 3; k++) f.up[k] = _project.up[k]; - for (int k = 0; k < 3; k++) f.background[k] = _project.background[k]; - f.transparent = _project.output.kind != OutputKind::Video && - _project.output.format == ImageFormat::PngAlpha; - - // Which shot, and how far into its transition. - std::vector shots = _project.shots; - if (shots.empty()) shots.push_back(Shot{}); - const int n = (int)shots.size(); - // Shots name the project's models; the layers are the open ones. With no - // shots it is the model on screen throughout. - auto layer_of = [&](int i) { - if (i < 0 || i >= n) return -1; - return _project.shots.empty() ? (_sources.empty() ? -1 : 0) : rt(shots[(size_t)i].source); - }; - const ShotMix m = shot_mix(shots, t, _project.duration()); - const Shot& sh = shots[(size_t)std::max(m.in, 0)]; - const int B = layer_of(m.in), A = layer_of(m.out); - f.b.source = B; - f.mix = 1.0f; - if (m.own) { - // Leaving its own way: each layer on its own, over its own time. - f.mode = 3; - f.a.source = A; - if (m.in >= 0) - side_effect(f, f.b, sh.transition, m.u_in, true, sh.param, sh.colour, sh.camera, - m.in == 0); - if (m.out >= 0) { - const ShotExit& e = shots[(size_t)m.out].exit; - side_effect(f, f.a, e.transition, m.u_out, false, e.param, e.colour, e.camera, - m.out == n - 1); - } - } else if (m.u_in < 1.0 && (A < 0 || B < 0)) { - // Nothing on one side, from the start or into a gap: the one there - // has the whole change to itself, arriving or leaving. - f.mode = 3; - f.a.source = A; - if (B >= 0) - side_effect(f, f.b, sh.transition, m.u_in, true, sh.param, sh.colour, sh.camera, - m.in == 0); - else - side_effect(f, f.a, sh.transition, m.u_in, false, sh.param, sh.colour, sh.camera, - false); - } else if (m.u_in < 1.0) { - const double u = m.u_in; - const float su = (float)smooth(u); - switch (sh.transition) { - case Transition::Crossfade: - f.a.source = A; - f.mix = su; - break; - case Transition::Dip: - for (int k = 0; k < 3; k++) f.tint[0][k] = sh.colour[k]; - if (u < 0.5) { f.b.source = A; f.tint[0][3] = (float)smooth(u * 2.0); } - else f.tint[0][3] = (float)(1.0 - smooth(u * 2.0 - 1.0)); - break; - case Transition::Wipe: { - // The edge travels this way across the picture, y down. - const double ang = sh.param[0] * kPi / 180.0; - f.a.source = A; - f.mask = 1; - f.mix = (float)u; - f.wipe_dir[0] = (float)std::cos(ang); - f.wipe_dir[1] = (float)-std::sin(ang); - f.soft = std::max(sh.param[1], 0.002f); - break; - } - case Transition::Iris: - f.a.source = A; - f.mask = 2; - f.mix = su; - f.soft = std::max(sh.param[1], 0.002f); - break; - case Transition::Zoom: - f.a.source = A; - f.mode = 2; - f.mix = (float)u; - f.zoom = std::clamp(sh.param[0], 0.05f, 2.0f); - break; - case Transition::Grow: - f.a.source = A; - f.mix = (float)smooth(std::min(1.0, u * 1.5)); - f.b.grow = (float)(0.02 + 0.98 * smooth(u)); - f.b.fade_in = (float)std::min(1.0, u * 2.5); - break; - default: { - // In 3D, both in the incoming model's frame -- the outgoing - // one's when nothing comes in. Until it is read, a crossfade. - LayerFx x; - if (!fx_frame(sh.transition, sh.camera, B >= 0 ? B : A, f, x)) { - f.a.source = A; - f.mix = su; - break; - } - f.mode = 1; - f.a.source = A; - f.mix = su; - if (sh.transition == Transition::Sweep) { - // A level; the new model on one side of it, the old on - // the other, the band at the cut lit. - const bool down = sh.param[0] >= 0.5f; - const double k = smooth(down ? 1.0 - u : u); - set_sweep(f.a, x, k, down, sh.param[1], sh.colour); - set_sweep(f.b, x, k, !down, sh.param[1], sh.colour); - break; - } - for (int layer = 0; layer < 2; layer++) { - LayerFx& lx = layer ? f.b.fx : f.a.fx; - lx = x; - lx.kind = (int)sh.transition; - lx.incoming = layer == 1; - lx.t = (float)u; - lx.p[0] = sh.param[0]; - lx.p[1] = sh.param[1]; - } - break; - } - } - } - - // Each model as the keys around this moment have it. - for (LayerSpec* l : {&f.a, &f.b}) { - if (l->source < 0) continue; - _project.look_at(project_source_of(l->source), t, trajectory().key_times(), l->style[0], - l->style[1], l->style_mix); - l->variants = l->style_mix > 0.0f ? 2 : 1; - } - - // The fades, over everything; a photo has none. - if (!photo) { - const double T = _project.duration(); - auto fade = [&](const Fade& fd, double into) { - if (fd.colour == FadeColour::None || fd.seconds <= 1e-6) return; - const double amount = 1.0 - smooth(into / fd.seconds); - if (amount <= 0.0) return; - const float c = fd.colour == FadeColour::White ? 1.0f : 0.0f; - if (amount > f.tint[1][3]) { - f.tint[1][0] = f.tint[1][1] = f.tint[1][2] = c; - f.tint[1][3] = (float)amount; - } - }; - fade(_project.fade_in, t - (_project.keys.empty() ? 0.0 : _project.keys.front().time)); - fade(_project.fade_out, T - t); - } - return f; + return render::frame_spec(_project, trajectory(), _frames, _rt, t, W, H, photo); } + void RenderSession::preview_size(float box_w, float box_h, int& W, int& H) const { const double aspect = (double)_project.output.width / std::max(_project.output.height, 1); double w = std::max(64.0f, box_w), h = w / aspect; @@ -2353,90 +2016,30 @@ void RenderSession::probe_encoder() { _ffmpeg_probe = 1; const std::string ffmpeg = _ffmpeg; _probe = std::thread([this, ffmpeg] { - std::atomic cancel{false}; - std::vector lines; - if (command_exists(ffmpeg)) - run_process({ffmpeg, "-hide_banner", "-encoders"}, "", - [&](const std::string& line) { lines.push_back(line); }, cancel); - _ffmpeg_encoders = parse_ffmpeg_encoders(lines); + const std::atomic cancel{false}; + _ffmpeg_encoders = probe_ffmpeg_encoders(ffmpeg, cancel); _ffmpeg_probe = 2; -#ifdef SS_TOOL_ENCODE - int codecs = 0; - const int code = run_process({app::exe_path(), "encode", "--probe"}, "", - [&](const std::string& line) { - // "h264 4096 4096": a codec and the largest frame it takes. - char name[16] = {}; - int w = 0, h = 0; - if (std::sscanf(line.c_str(), "%15s %d %d", name, &w, &h) < 1) return; - const int c = std::string(name) == "h264" ? 0 : std::string(name) == "h265" ? 1 - : std::string(name) == "av1" ? 2 : -1; - if (c < 0) return; - codecs |= 1 << c; - _encoder_max[c][0] = w > 0 ? w : 4096; - _encoder_max[c][1] = h > 0 ? h : 4096; - }, cancel); + const int codecs = probe_builtin_encoder(_encoder_max, cancel); _encoder_codecs = codecs; - _encoder_probe = code == 0 && codecs ? 2 : 3; -#else - _encoder_probe = 3; -#endif + _encoder_probe = codecs ? 2 : 3; }); } bool RenderSession::builtin_encodes(Codec codec, int width, int height) const { - // WebM is ffmpeg's; the GPU encoder writes MP4 only. - if (codec == Codec::Gif || codec == Codec::Av1Webm || _encoder_probe.load() != 2) - return false; - const int c = (int)codec; - return (_encoder_codecs.load() & (1 << c)) && width <= _encoder_max[c][0] && - height <= _encoder_max[c][1]; + return _encoder_probe.load() == 2 && + render::builtin_encodes(_encoder_codecs.load(), _encoder_max, codec, width, height); } Encoder RenderSession::pick_encoder() { - Encoder e; const Output& o = _project.output; - int W = std::max(16, o.width), H = std::max(16, o.height); - W += W & 1; - H += H & 1; + int W = 0, H = 0; + output_size(o, W, H); const bool gpu = !_fallback_tried && builtin_encodes(o.codec, W, H); - Encoder ff; - if (command_exists(_ffmpeg)) { - const std::vector& want = ffmpeg_encoders_for(o.codec); - // Until ffmpeg has said what it has, the usual first choice. - if (_ffmpeg_probe.load() != 2) { - if (!want.empty()) ff = {Encoder::Ffmpeg, _ffmpeg, want[0]}; - } else { - for (const std::string& name : want) - if (std::find(_ffmpeg_encoders.begin(), _ffmpeg_encoders.end(), name) != - _ffmpeg_encoders.end()) { - ff = {Encoder::Ffmpeg, _ffmpeg, name}; - break; - } - } - } - // The GPU for H.264 and H.265. Its AV1 predicts only from key frames - // (src/video/README.md), so an AV1 encoder in ffmpeg makes the smaller file. - const bool gpu_first = o.codec != Codec::Av1 || ff.kind == Encoder::None; - if (gpu && gpu_first) { - e.kind = Encoder::BuiltIn; - e.exe = app::exe_path(); - return e; - } - if (ff.kind != Encoder::None) return ff; - if (gpu) { - e.kind = Encoder::BuiltIn; - e.exe = app::exe_path(); - } - return e; + return render::pick_encoder(o, gpu, _ffmpeg, + _ffmpeg_probe.load() == 2 ? &_ffmpeg_encoders : nullptr); } -int RenderSession::frame_count() const { - if (_project.output.kind == OutputKind::Photo || _project.keys.empty()) return 1; - const double span = std::max(0.0, _project.duration() - _project.keys.front().time); - const long n = std::lround(span * std::max(_project.output.fps, 1.0)); - // A loop's last frame would be its first again. - return (int)std::max(1L, _project.looped() ? n : n + 1); -} +int RenderSession::frame_count() const { return render::frame_count(_project); } void RenderSession::start_export(bool no_builtin, bool confirmed) { if (_job.state != Job::Idle || _project.keys.empty()) return; @@ -2456,21 +2059,9 @@ void RenderSession::start_export(bool no_builtin, bool confirmed) { } // Something already there: asked first, and started again on a yes. if (!confirmed) { - std::error_code ec; - const fs::path out = fs::u8path(o.path); - _overwrite_frames = 0; - if (o.kind == OutputKind::Frames) { - if (fs::is_directory(out, ec)) - for (const auto& e : fs::directory_iterator(out, ec)) { - const std::string name = e.path().filename().string(); - const std::string ext = e.path().extension().string(); - if (name.rfind("frame_", 0) == 0 && (ext == ".png" || ext == ".jpg")) - _overwrite_frames++; - } - _ask_overwrite = _overwrite_frames > 0; - } else { - _ask_overwrite = fs::exists(out, ec); - } + const int there = existing_output(o); + _overwrite_frames = o.kind == OutputKind::Frames ? there : 0; + _ask_overwrite = there > 0; if (_ask_overwrite) return; } _playing = false; @@ -2479,38 +2070,20 @@ void RenderSession::start_export(bool no_builtin, bool confirmed) { // A preview frame still in flight is not one of the export's. _frames.abandon(); _fallback_tried = no_builtin; - int W = std::max(16, o.width), H = std::max(16, o.height); - const bool mp4 = o.kind == OutputKind::Video && o.codec != Codec::Gif; - if (mp4) { W += W & 1; H += H & 1; } _job.photo = photo; _job.frames = frame_count(); _job.path = o.path; - if (mp4) { - std::error_code ec; - const fs::path parent = fs::u8path(o.path).parent_path(); - if (!parent.empty()) fs::create_directories(parent, ec); - const Encoder e = pick_encoder(); + Encoder e; + if (output_is_mp4(o)) { + e = pick_encoder(); if (e.kind == Encoder::None) { _status = msg::no_encoder.get(); _status_err = true; return; } _job.builtin = e.kind == Encoder::BuiltIn; - const bool sphere = !_project.keys.empty() && - _project.lens_at(0).projection == Projection::Equirect; - _job.sink = open_pipe_sink(encoder_argv(e, W, H, o.fps, o.codec, o.quality, sphere, - o.path)); - } else if (o.kind == OutputKind::Video) { - _job.sink = open_gif_sink(o.path, W, H, o.fps, _job.frames, o.quality); - } else { - std::string path = o.path; - if (o.kind == OutputKind::Frames) { - // A folder: the frames are numbered inside it. - path = (fs::u8path(o.path) / - (o.format == ImageFormat::Jpeg ? "frame_%05d.jpg" : "frame_%05d.png")).string(); - } - _job.sink = open_image_sink(path, W, H, o.format, o.jpeg_quality); } + _job.sink = open_output_sink(_project, e, _job.frames); _job.state = Job::Preparing; _job.started = now_s(); if (!no_builtin) _job_clock.start(progress_now()); @@ -2537,8 +2110,8 @@ void RenderSession::cancel_export() { void RenderSession::poll_export() { Job& j = _job; const Output& o = _project.output; - int W = std::max(16, o.width), H = std::max(16, o.height); - if (o.kind == OutputKind::Video && o.codec != Codec::Gif) { W += W & 1; H += H & 1; } + int W = 0, H = 0; + output_size(o, W, H); if (j.state == Job::Preparing) { // Effects that rewrite splats need them read first. bool ready = true; diff --git a/src/app/gui/render/RenderSession.h b/src/app/gui/render/RenderSession.h index fb9214bd1..b3683d518 100644 --- a/src/app/gui/render/RenderSession.h +++ b/src/app/gui/render/RenderSession.h @@ -231,9 +231,6 @@ class RenderSession : public ViewportInteractor { // ---- frames ---- FrameSpec frame_spec(double t, int W, int H, bool photo); - bool fx_frame(Transition kind, bool camera, int source, const FrameSpec& f, LayerFx& x); - void side_effect(FrameSpec& f, LayerSpec& l, Transition kind, double u, bool in, - const float param[2], const float colour[3], bool camera, bool edge); void preview_size(float box_w, float box_h, int& W, int& H) const; void request_preview(); diff --git a/src/app/gui/render/ShotFrames.cpp b/src/app/gui/render/ShotFrames.cpp new file mode 100644 index 000000000..744c851c9 --- /dev/null +++ b/src/app/gui/render/ShotFrames.cpp @@ -0,0 +1,380 @@ +#include "app/gui/render/ShotFrames.h" + +#include "data/CameraMath.h" + +#include +#include + +namespace gui::render { + +namespace { + +constexpr double kPi = 3.14159265358979323846; + +double smooth(double u) { + u = std::clamp(u, 0.0, 1.0); + return u * u * (3.0 - 2.0 * u); +} + +struct Builder { + const RenderProject& p; + const Trajectory& tr; + FrameRenderer& fr; + const std::vector& rt; + + int layer(int i) const { return i >= 0 && i < (int)rt.size() ? rt[(size_t)i] : -1; } + int source_of(int runtime) const { + for (int i = 0; i < (int)rt.size(); i++) + if (rt[(size_t)i] == runtime) return i; + return -1; + } + bool fx_frame(Transition kind, bool camera, int source, const FrameSpec& f, LayerFx& x); + void side_effect(FrameSpec& f, LayerSpec& l, Transition kind, double u, bool in, + const float param[2], const float colour[3], bool camera, bool edge); + FrameSpec build(double t, int W, int H, bool photo); +}; + +// The frame a 3D transition moves `source` in: the world's up, or the +// camera's -- down the picture for what falls, round its middle for what +// turns or ripples, about the view's own axis at the scene's depth. +bool Builder::fx_frame(Transition kind, bool camera, int source, const FrameSpec& f, + LayerFx& x) { + SceneCore core; + if (source < 0 || !fr.scene_core(source, core)) return false; + for (int k = 0; k < 3; k++) x.centre[k] = core.centre[k]; + x.radius = core.radius; + const bool seen = camera && transition_has_camera(kind); + FxView view; + if (seen) { + const CameraState& cam = f.cam; + double R[9]; + quat_to_matrix3(cam.rot, R); + const double right[3] = {R[0], R[3], R[6]}, cup[3] = {R[1], R[4], R[7]}, + back[3] = {R[2], R[5], R[8]}; + double depth = 0.0; + for (int k = 0; k < 3; k++) depth -= (core.centre[k] - cam.pos[k]) * back[k]; + depth = std::max(depth, 0.5 * core.radius); + if (kind == Transition::Spiral || kind == Transition::Ripple) { + for (int k = 0; k < 3; k++) { + x.centre[k] = cam.pos[k] - back[k] * depth; + x.up[k] = kind == Transition::Spiral ? -back[k] : back[k]; + x.e1[k] = right[k]; + x.e2[k] = cup[k]; + } + } else { + for (int k = 0; k < 3; k++) { + x.up[k] = cup[k]; + x.e1[k] = right[k]; + x.e2[k] = back[k]; + } + } + // What the picture takes in: only that is ordered, and the moves are + // as wide as the picture at the scene's depth, so a long lens or a + // camera up close still sees the change from its start. + const double hx = 0.5 * std::min(lens_fov(cam.lens), 360.0) * kPi / 180.0; + const double aspect = (double)std::max(f.height, 1) / std::max(f.width, 1); + const bool pinhole = cam.lens.projection == Projection::Perspective; + const bool ortho = cam.lens.projection == Projection::Orthographic; + const double hy = pinhole || ortho ? std::atan(std::tan(hx) * aspect) : hx * aspect; + for (int k = 0; k < 3; k++) { + view.pos[k] = cam.pos[k]; + view.fwd[k] = -back[k]; + view.right[k] = right[k]; + view.up[k] = cup[k]; + } + if (ortho) { + view.orthographic = true; + view.tx = 0.5 * cam.lens.ortho_distance / cam.lens.focal * 1.1; + view.ty = view.tx * aspect; + } else if (pinhole) { + view.tx = std::tan(hx) * 1.1; + view.ty = std::tan(hy) * 1.1; + } else { + view.cone = std::min(std::max(hx, hy) * 1.1, kPi); + } + const double a = std::clamp(std::min(hx, hy), 5.0 * kPi / 180.0, kPi / 3.0); + const double radius = ortho ? std::min(view.tx, view.ty) / 1.1 : depth * std::tan(a); + x.radius = std::clamp(radius, 0.05 * core.radius, core.radius); + } else { + double n = 0.0; + for (int k = 0; k < 3; k++) n += p.up[k] * p.up[k]; + n = std::sqrt(std::max(n, 1e-24)); + for (int k = 0; k < 3; k++) x.up[k] = p.up[k] / n; + // Any two across up, the same two every frame. + double a[3] = {1, 0, 0}; + if (std::fabs(x.up[0]) > 0.9) { a[0] = 0; a[1] = 1; } + double e1[3] = {a[1]*x.up[2] - a[2]*x.up[1], a[2]*x.up[0] - a[0]*x.up[2], + a[0]*x.up[1] - a[1]*x.up[0]}; + const double n1 = std::sqrt(e1[0]*e1[0] + e1[1]*e1[1] + e1[2]*e1[2]); + for (int k = 0; k < 3; k++) x.e1[k] = e1[k] / std::max(n1, 1e-12); + x.e2[0] = x.up[1]*x.e1[2] - x.up[2]*x.e1[1]; + x.e2[1] = x.up[2]*x.e1[0] - x.up[0]*x.e1[2]; + x.e2[2] = x.up[0]*x.e1[1] - x.up[1]*x.e1[0]; + } + return fr.scene_quantiles(source, x.centre, x.up, x.e1, x.e2, x.q, seen ? &view : nullptr); +} + + +// A sweep's level when `k` of the elements are behind it, world frame: in +// step with the elements rather than the distance, so a far sky costs no +// more of it than the rest; led in and out past the first and the last. +double sweep_level(const LayerFx& x, double k) { + const double base = x.centre[0]*x.up[0] + x.centre[1]*x.up[1] + x.centre[2]*x.up[2]; + const double span = std::max((double)(fx_quantile(x.q.qh, 0.98f) - fx_quantile(x.q.qh, 0.02f)), + 1e-9 * x.radius); + constexpr double m = 0.06; + const double kk = -m + k * (1.0 + 2.0 * m); + if (kk < 0.0) return base + x.q.qh[0] + kk / m * 0.08 * span; + if (kk > 1.0) return base + x.q.qh[kFxQuantiles - 1] + (kk - 1.0) / m * 0.08 * span; + return base + fx_quantile(x.q.qh, (float)kk); +} + +void set_sweep(LayerSpec& l, const LayerFx& x, double k, bool keep_below, float glow, + const float colour[3]) { + l.clip = keep_below ? 1 : 2; + for (int d = 0; d < 3; d++) l.clip_n[d] = x.up[d]; + l.level = sweep_level(x, k); + const double span = fx_quantile(x.q.qh, 0.98f) - fx_quantile(x.q.qh, 0.02f); + l.glow = (float)(0.07 * std::max(span, 1e-9 * x.radius) * std::clamp(glow, 0.0f, 1.0f)); + for (int d = 0; d < 3; d++) l.glow_col[d] = colour[d]; +} + + +// One layer's own way in or out, `u` through it, composited on its own +// (mode 3) with the whole change to itself. At the video's start or end +// (`edge`) a dip is from or into its colour. +void Builder::side_effect(FrameSpec& f, LayerSpec& l, Transition kind, double u, bool in, + const float param[2], const float colour[3], bool camera, + bool edge) { + if (l.source < 0) return; + const double v = in ? u : 1.0 - u; // how much of it there is + // Arriving from nothing, on its way at once rather than easing in. + const double shown = in ? 1.0 - (1.0 - u) * (1.0 - u) : smooth(v); + switch (kind) { + case Transition::Cut: + if (!in && u >= 1.0) l.source = -1; + break; + case Transition::Crossfade: + l.opacity = (float)shown; + break; + case Transition::Dip: { + for (int k = 0; k < 3; k++) f.tint[0][k] = colour[k]; + // From its colour at the start, into it at the end; elsewhere + // through it, the model there from the middle on. + const double amount = edge ? (in ? 1.0 - smooth(u) : smooth(u)) + : u < 0.5 ? smooth(u * 2.0) : 1.0 - smooth(u * 2.0 - 1.0); + f.tint[0][3] = (float)std::max((double)f.tint[0][3], amount); + if (!edge && (in ? u < 0.5 : u >= 0.5)) l.opacity = 0.0f; + break; + } + case Transition::Wipe: { + const double ang = param[0] * kPi / 180.0; + l.mask = 1; + l.mask_t = (float)u; + l.mask_out = !in; + l.mask_dir[0] = (float)std::cos(ang); + l.mask_dir[1] = (float)-std::sin(ang); + l.mask_soft = std::max(param[1], 0.002f); + break; + } + case Transition::Iris: + l.mask = 2; + l.mask_t = (float)(in ? shown : smooth(u)); + l.mask_out = !in; + l.mask_soft = std::max(param[1], 0.002f); + break; + case Transition::Zoom: { + // Arriving from far and smeared, or rushing past the camera; in + // sight for all but the far end of it. + const double z = std::clamp(param[0], 0.05f, 2.0f), r = 1.0 - v; + l.zoom = (float)(in ? 1.0 / (1.0 + 2.0 * z * r * r) : 1.0 + 2.0 * z * r * r); + l.zoom_blur = (float)(z * r); + l.opacity = (float)smooth(std::clamp(v / 0.45, 0.0, 1.0)); + break; + } + case Transition::Grow: + l.grow = (float)(0.02 + 0.98 * smooth(v)); + l.fade_in = (float)std::min(1.0, v * 2.5); + break; + default: { + LayerFx x; + if (!fx_frame(kind, camera, l.source, f, x)) { + l.opacity = (float)shown; + break; + } + if (kind == Transition::Sweep) { + // The level passes it: what is left of it on the far side. + const bool down = param[0] >= 0.5f; + set_sweep(l, x, smooth(down ? 1.0 - u : u), in != down, param[1], colour); + break; + } + x.kind = (int)kind; + x.incoming = in; + x.t = fx_solo_time((int)kind, in, (float)u, param); + x.p[0] = param[0]; + x.p[1] = param[1]; + l.fx = x; + break; + } + } +} + +FrameSpec Builder::build(double t, int W, int H, bool photo) { + FrameSpec f; + f.cam = tr.at(t); + f.width = W; + f.height = H; + for (int k = 0; k < 3; k++) f.up[k] = p.up[k]; + for (int k = 0; k < 3; k++) f.background[k] = p.background[k]; + f.transparent = p.output.kind != OutputKind::Video && + p.output.format == ImageFormat::PngAlpha; + + // Which shot, and how far into its transition. + std::vector shots = p.shots; + if (shots.empty()) shots.push_back(Shot{}); + const int n = (int)shots.size(); + // Shots name the project's models; the layers are the open ones. With no + // shots it is the model on screen throughout. + auto layer_of = [&](int i) { + if (i < 0 || i >= n) return -1; + return p.shots.empty() ? (fr.source_count() == 0 ? -1 : 0) : layer(shots[(size_t)i].source); + }; + const ShotMix m = shot_mix(shots, t, p.duration()); + const Shot& sh = shots[(size_t)std::max(m.in, 0)]; + const int B = layer_of(m.in), A = layer_of(m.out); + f.b.source = B; + f.mix = 1.0f; + if (m.own) { + // Leaving its own way: each layer on its own, over its own time. + f.mode = 3; + f.a.source = A; + if (m.in >= 0) + side_effect(f, f.b, sh.transition, m.u_in, true, sh.param, sh.colour, sh.camera, + m.in == 0); + if (m.out >= 0) { + const ShotExit& e = shots[(size_t)m.out].exit; + side_effect(f, f.a, e.transition, m.u_out, false, e.param, e.colour, e.camera, + m.out == n - 1); + } + } else if (m.u_in < 1.0 && (A < 0 || B < 0)) { + // Nothing on one side, from the start or into a gap: the one there + // has the whole change to itself, arriving or leaving. + f.mode = 3; + f.a.source = A; + if (B >= 0) + side_effect(f, f.b, sh.transition, m.u_in, true, sh.param, sh.colour, sh.camera, + m.in == 0); + else + side_effect(f, f.a, sh.transition, m.u_in, false, sh.param, sh.colour, sh.camera, + false); + } else if (m.u_in < 1.0) { + const double u = m.u_in; + const float su = (float)smooth(u); + switch (sh.transition) { + case Transition::Crossfade: + f.a.source = A; + f.mix = su; + break; + case Transition::Dip: + for (int k = 0; k < 3; k++) f.tint[0][k] = sh.colour[k]; + if (u < 0.5) { f.b.source = A; f.tint[0][3] = (float)smooth(u * 2.0); } + else f.tint[0][3] = (float)(1.0 - smooth(u * 2.0 - 1.0)); + break; + case Transition::Wipe: { + // The edge travels this way across the picture, y down. + const double ang = sh.param[0] * kPi / 180.0; + f.a.source = A; + f.mask = 1; + f.mix = (float)u; + f.wipe_dir[0] = (float)std::cos(ang); + f.wipe_dir[1] = (float)-std::sin(ang); + f.soft = std::max(sh.param[1], 0.002f); + break; + } + case Transition::Iris: + f.a.source = A; + f.mask = 2; + f.mix = su; + f.soft = std::max(sh.param[1], 0.002f); + break; + case Transition::Zoom: + f.a.source = A; + f.mode = 2; + f.mix = (float)u; + f.zoom = std::clamp(sh.param[0], 0.05f, 2.0f); + break; + case Transition::Grow: + f.a.source = A; + f.mix = (float)smooth(std::min(1.0, u * 1.5)); + f.b.grow = (float)(0.02 + 0.98 * smooth(u)); + f.b.fade_in = (float)std::min(1.0, u * 2.5); + break; + default: { + // In 3D, both in the incoming model's frame -- the outgoing + // one's when nothing comes in. Until it is read, a crossfade. + LayerFx x; + if (!fx_frame(sh.transition, sh.camera, B >= 0 ? B : A, f, x)) { + f.a.source = A; + f.mix = su; + break; + } + f.mode = 1; + f.a.source = A; + f.mix = su; + if (sh.transition == Transition::Sweep) { + // A level; the new model on one side of it, the old on + // the other, the band at the cut lit. + const bool down = sh.param[0] >= 0.5f; + const double k = smooth(down ? 1.0 - u : u); + set_sweep(f.a, x, k, down, sh.param[1], sh.colour); + set_sweep(f.b, x, k, !down, sh.param[1], sh.colour); + break; + } + for (int layer = 0; layer < 2; layer++) { + LayerFx& lx = layer ? f.b.fx : f.a.fx; + lx = x; + lx.kind = (int)sh.transition; + lx.incoming = layer == 1; + lx.t = (float)u; + lx.p[0] = sh.param[0]; + lx.p[1] = sh.param[1]; + } + break; + } + } + } + + // Each model as the keys around this moment have it. + for (LayerSpec* l : {&f.a, &f.b}) { + if (l->source < 0) continue; + p.look_at(source_of(l->source), t, tr.key_times(), l->style[0], + l->style[1], l->style_mix); + l->variants = l->style_mix > 0.0f ? 2 : 1; + } + + // The fades, over everything; a photo has none. + if (!photo) { + const double T = p.duration(); + auto fade = [&](const Fade& fd, double into) { + if (fd.colour == FadeColour::None || fd.seconds <= 1e-6) return; + const double amount = 1.0 - smooth(into / fd.seconds); + if (amount <= 0.0) return; + const float c = fd.colour == FadeColour::White ? 1.0f : 0.0f; + if (amount > f.tint[1][3]) { + f.tint[1][0] = f.tint[1][1] = f.tint[1][2] = c; + f.tint[1][3] = (float)amount; + } + }; + fade(p.fade_in, t - (p.keys.empty() ? 0.0 : p.keys.front().time)); + fade(p.fade_out, T - t); + } + return f; +} +} // namespace + +FrameSpec frame_spec(const RenderProject& p, const Trajectory& tr, FrameRenderer& fr, + const std::vector& rt, double t, int W, int H, bool photo) { + return Builder{p, tr, fr, rt}.build(t, W, H, photo); +} + +} // namespace gui::render diff --git a/src/app/gui/render/ShotFrames.h b/src/app/gui/render/ShotFrames.h new file mode 100644 index 000000000..c7b6640bc --- /dev/null +++ b/src/app/gui/render/ShotFrames.h @@ -0,0 +1,20 @@ +#pragma once + +// What one moment of a RenderProject asks the FrameRenderer for: the camera, +// which shots are on screen and how far through their transitions, each +// model's look, and the fades. Shared by the render mode and `spirula render`. + +#include "app/gui/render/FrameRenderer.h" +#include "app/gui/render/RenderProject.h" +#include "app/gui/render/Trajectory.h" + +#include + +namespace gui::render { + +// `rt[i]`: the renderer's layer showing project source i, -1 when none. `fr` +// is asked where the models are, for the 3D transitions. +FrameSpec frame_spec(const RenderProject& p, const Trajectory& tr, FrameRenderer& fr, + const std::vector& rt, double t, int W, int H, bool photo); + +} // namespace gui::render diff --git a/src/app/gui/render/TransitionFx.h b/src/app/gui/render/TransitionFx.h index c8f1c29ec..19e9a5149 100644 --- a/src/app/gui/render/TransitionFx.h +++ b/src/app/gui/render/TransitionFx.h @@ -249,11 +249,12 @@ float fx_sat(float x) { return clamp(x, 0.0, 1.0); } float fx_smooth(float a, float b, float x) { return smoothstep(a, b, x); } float fx_local(float t, float s0, float w) { return fx_sat((t - s0 * (1.0 - w)) / w); } float fx_phase(float t, float a, float b) { return fx_sat((t - a) / (b - a)); } -float fx_hashu(uint x) { +uint fx_pcg(uint x) { x = x * 747796405u + 2891336453u; x = ((x >> ((x >> 28u) + 4u)) ^ x) * 277803737u; - return float((x >> 22u) ^ x) * (1.0 / 4294967296.0); + return (x >> 22u) ^ x; } +float fx_hashu(uint x) { return float(fx_pcg(x)) * (1.0 / 4294967296.0); } // fx_cdf, once per table: GLSL 1.50 passes no uniform array by reference. float fx_cdf_h(float v) { if (!(v > u_fx_qh[0])) return 0.0; @@ -288,7 +289,11 @@ float fx_cdf_r(float v) { float span = u_fx_qr[hi] - u_fx_qr[lo]; return (float(lo) + (span > 0.0 ? (v - u_fx_qr[lo]) / span : 0.5)) / 32.0; } -float fx_h3(vec3 c) { return fract(sin(dot(c, vec3(127.1, 311.7, 74.7))) * 43758.5453); } +// Integer hash of a cell: a sin() hash differs between GPU drivers. +float fx_h3(vec3 c) { + uvec3 u = uvec3(ivec3(c)); + return fx_hashu(u.x ^ fx_pcg(u.y ^ fx_pcg(u.z))); +} // Smooth over space, for a mesh, whose shared vertices must move together. float fx_noise(vec3 x) { vec3 i = floor(x), f = fract(x); diff --git a/src/i18n/catalog/Cli.h b/src/i18n/catalog/Cli.h index 174e92b64..7033e244c 100644 --- a/src/i18n/catalog/Cli.h +++ b/src/i18n/catalog/Cli.h @@ -159,6 +159,20 @@ SS_MSG(tool_partition, NL("een reconstructie splitsen in apart te trainen delen en ze samenvoegen"), RU("разбить реконструкцию на части для раздельного обучения и объединить их"), TR("bir yeniden oluşturmayı ayrı eğitilecek parçalara böl ve birleştir")); +SS_MSG(tool_render, + EN("render a camera project (.json) to a video, frames or a photo"), + JA("カメラプロジェクト(.json)を動画・連番画像・写真にレンダリングする"), + ZH_HANS("将相机项目(.json)渲染为视频、帧序列或照片"), + ZH_HANT("將相機專案(.json)算繪為影片、影格序列或相片"), + KO("카메라 프로젝트(.json)를 동영상, 프레임 또는 사진으로 렌더링"), + DE("ein Kameraprojekt (.json) als Video, Einzelbilder oder Foto rendern"), + FR("rendre un projet caméra (.json) en vidéo, en images ou en photo"), + ES("renderizar un proyecto de cámara (.json) como vídeo, fotogramas o foto"), + PT("renderizar um projeto de câmera (.json) como vídeo, quadros ou foto"), + IT("renderizzare un progetto camera (.json) in video, fotogrammi o foto"), + NL("een cameraproject (.json) renderen naar een video, beelden of een foto"), + RU("отрендерить проект камеры (.json) в видео, кадры или фото"), + TR("bir kamera projesini (.json) videoya, karelere veya fotoğrafa render etmek")); SS_MSG(tool_encode, EN("encode raw RGB frames into a video on the GPU"), JA("生のRGBフレームをGPUで動画にエンコードする"), diff --git a/src/i18n/catalog/Render.h b/src/i18n/catalog/Render.h index b4540d701..b3256fc59 100644 --- a/src/i18n/catalog/Render.h +++ b/src/i18n/catalog/Render.h @@ -5467,6 +5467,176 @@ SS_MSG(pv_through_hint, RU("Вид камеры, {0} × {1}. Перетаскивание поворачивает, правой кнопкой — сдвиг, колесо — движение, Ctrl и колесо — зум."), TR("Kamera görünümü, {0} × {1}. Sürükleyerek döndürün, sağ sürükleyerek kaydırın, tekerlekle ilerleyin, Ctrl ve tekerlekle yakınlaştırın.")); + +// =========================================================================== +// `spirula render` +// =========================================================================== + +SS_MSG(cli_usage, + EN("Usage: {0} [-o PATH] [--overwrite] [options]\n- --model PATH, --kind video|frames|photo, --size WxH, --fps N\n- --codec h264|h265|av1|av1-webm|gif, --quality 0|1|2, --time S, --ffmpeg EXE\n- Needs a display for OpenGL; on a server, use xvfb-run."), + JA("使い方: {0} [-o PATH] [--overwrite] [options]\n- --model PATH, --kind video|frames|photo, --size WxH, --fps N\n- --codec h264|h265|av1|av1-webm|gif, --quality 0|1|2, --time S, --ffmpeg EXE\n- OpenGL にはディスプレイが必要です。サーバーでは xvfb-run を使ってください。"), + ZH_HANS("用法: {0} [-o PATH] [--overwrite] [options]\n- --model PATH, --kind video|frames|photo, --size WxH, --fps N\n- --codec h264|h265|av1|av1-webm|gif, --quality 0|1|2, --time S, --ffmpeg EXE\n- OpenGL 需要显示器;在服务器上请用 xvfb-run。"), + ZH_HANT("用法: {0} [-o PATH] [--overwrite] [options]\n- --model PATH, --kind video|frames|photo, --size WxH, --fps N\n- --codec h264|h265|av1|av1-webm|gif, --quality 0|1|2, --time S, --ffmpeg EXE\n- OpenGL 需要顯示器;在伺服器上請用 xvfb-run。"), + KO("사용법: {0} [-o PATH] [--overwrite] [options]\n- --model PATH, --kind video|frames|photo, --size WxH, --fps N\n- --codec h264|h265|av1|av1-webm|gif, --quality 0|1|2, --time S, --ffmpeg EXE\n- OpenGL에는 디스플레이가 필요합니다. 서버에서는 xvfb-run을 쓰세요."), + DE("Aufruf: {0} [-o PATH] [--overwrite] [options]\n- --model PATH, --kind video|frames|photo, --size WxH, --fps N\n- --codec h264|h265|av1|av1-webm|gif, --quality 0|1|2, --time S, --ffmpeg EXE\n- OpenGL braucht ein Display; auf einem Server xvfb-run verwenden."), + FR("utilisation : {0} [-o PATH] [--overwrite] [options]\n- --model PATH, --kind video|frames|photo, --size WxH, --fps N\n- --codec h264|h265|av1|av1-webm|gif, --quality 0|1|2, --time S, --ffmpeg EXE\n- OpenGL exige un écran ; sur un serveur, utilisez xvfb-run."), + ES("uso: {0} [-o PATH] [--overwrite] [options]\n- --model PATH, --kind video|frames|photo, --size WxH, --fps N\n- --codec h264|h265|av1|av1-webm|gif, --quality 0|1|2, --time S, --ffmpeg EXE\n- OpenGL necesita una pantalla; en un servidor, use xvfb-run."), + PT("uso: {0} [-o PATH] [--overwrite] [options]\n- --model PATH, --kind video|frames|photo, --size WxH, --fps N\n- --codec h264|h265|av1|av1-webm|gif, --quality 0|1|2, --time S, --ffmpeg EXE\n- O OpenGL precisa de uma tela; em um servidor, use xvfb-run."), + IT("uso: {0} [-o PATH] [--overwrite] [options]\n- --model PATH, --kind video|frames|photo, --size WxH, --fps N\n- --codec h264|h265|av1|av1-webm|gif, --quality 0|1|2, --time S, --ffmpeg EXE\n- OpenGL richiede un display; su un server, usa xvfb-run."), + NL("gebruik: {0} [-o PATH] [--overwrite] [options]\n- --model PATH, --kind video|frames|photo, --size WxH, --fps N\n- --codec h264|h265|av1|av1-webm|gif, --quality 0|1|2, --time S, --ffmpeg EXE\n- OpenGL heeft een beeldscherm nodig; gebruik op een server xvfb-run."), + RU("использование: {0} [-o PATH] [--overwrite] [options]\n- --model PATH, --kind video|frames|photo, --size WxH, --fps N\n- --codec h264|h265|av1|av1-webm|gif, --quality 0|1|2, --time S, --ffmpeg EXE\n- OpenGL нужен дисплей; на сервере используйте xvfb-run."), + TR("kullanım: {0} [-o PATH] [--overwrite] [options]\n- --model PATH, --kind video|frames|photo, --size WxH, --fps N\n- --codec h264|h265|av1|av1-webm|gif, --quality 0|1|2, --time S, --ffmpeg EXE\n- OpenGL için ekran gerekir; sunucuda xvfb-run kullanın.")); + +SS_MSG(cli_bad_option, + EN("Unknown option or missing value: {0}"), + JA("不明なオプションまたは値がありません: {0}"), + ZH_HANS("未知选项或缺少值:{0}"), + ZH_HANT("未知選項或缺少值:{0}"), + KO("알 수 없는 옵션이거나 값이 없습니다: {0}"), + DE("Unbekannte Option oder fehlender Wert: {0}"), + FR("Option inconnue ou valeur manquante : {0}"), + ES("Opción desconocida o valor ausente: {0}"), + PT("Opção desconhecida ou valor ausente: {0}"), + IT("Opzione sconosciuta o valore mancante: {0}"), + NL("Onbekende optie of ontbrekende waarde: {0}"), + RU("Неизвестный параметр или нет значения: {0}"), + TR("Bilinmeyen seçenek veya eksik değer: {0}")); + +SS_MSG(cli_project_unreadable, + EN("Cannot read the camera project {0}: {1}"), + JA("カメラプロジェクト {0} を読めません: {1}"), + ZH_HANS("无法读取相机项目 {0}:{1}"), + ZH_HANT("無法讀取相機專案 {0}:{1}"), + KO("카메라 프로젝트 {0}을(를) 읽을 수 없습니다: {1}"), + DE("Das Kameraprojekt {0} lässt sich nicht lesen: {1}"), + FR("Impossible de lire le projet caméra {0} : {1}"), + ES("No se puede leer el proyecto de cámara {0}: {1}"), + PT("Não é possível ler o projeto de câmera {0}: {1}"), + IT("Impossibile leggere il progetto camera {0}: {1}"), + NL("Kan het cameraproject {0} niet lezen: {1}"), + RU("Не удаётся прочитать проект камеры {0}: {1}"), + TR("{0} kamera projesi okunamıyor: {1}")); + +SS_MSG(cli_no_keys, + EN("The camera project has no keyframes."), + JA("カメラプロジェクトにキーフレームがありません。"), + ZH_HANS("相机项目中没有关键帧。"), + ZH_HANT("相機專案中沒有關鍵影格。"), + KO("카메라 프로젝트에 키프레임이 없습니다."), + DE("Das Kameraprojekt hat keine Keyframes."), + FR("Le projet caméra n’a aucune image clé."), + ES("El proyecto de cámara no tiene fotogramas clave."), + PT("O projeto de câmera não tem quadros-chave."), + IT("Il progetto camera non ha fotogrammi chiave."), + NL("Het cameraproject heeft geen keyframes."), + RU("В проекте камеры нет ключевых кадров."), + TR("Kamera projesinde anahtar kare yok.")); + +SS_MSG(cli_no_output, + EN("No output path: the project has none, so give one with -o."), + JA("出力先がありません。プロジェクトに無いので -o で指定してください。"), + ZH_HANS("没有输出路径:项目中未设置,请用 -o 指定。"), + ZH_HANT("沒有輸出路徑:專案中未設定,請用 -o 指定。"), + KO("출력 경로가 없습니다. 프로젝트에 없으니 -o로 지정하세요."), + DE("Kein Ausgabepfad: Das Projekt hat keinen, also mit -o angeben."), + FR("Aucun chemin de sortie : le projet n’en a pas, indiquez-le avec -o."), + ES("No hay ruta de salida: el proyecto no tiene ninguna; indíquela con -o."), + PT("Sem caminho de saída: o projeto não tem um; informe com -o."), + IT("Nessun percorso di output: il progetto non ne ha, indicalo con -o."), + NL("Geen uitvoerpad: het project heeft er geen, geef er een met -o."), + RU("Нет пути вывода: в проекте его нет, укажите его через -o."), + TR("Çıktı yolu yok: projede tanımlı değil, -o ile verin.")); + +SS_MSG(cli_no_model, + EN("The camera project names no model; give one with --model."), + JA("カメラプロジェクトにモデルが指定されていません。--model で指定してください。"), + ZH_HANS("相机项目中没有指定模型;请用 --model 指定。"), + ZH_HANT("相機專案中沒有指定模型;請用 --model 指定。"), + KO("카메라 프로젝트에 모델이 없습니다. --model로 지정하세요."), + DE("Das Kameraprojekt nennt kein Modell; mit --model angeben."), + FR("Le projet caméra ne cite aucun modèle ; indiquez-en un avec --model."), + ES("El proyecto de cámara no nombra ningún modelo; indique uno con --model."), + PT("O projeto de câmera não indica nenhum modelo; informe um com --model."), + IT("Il progetto camera non indica alcun modello; indicane uno con --model."), + NL("Het cameraproject noemt geen model; geef er een met --model."), + RU("В проекте камеры не указана модель; укажите её через --model."), + TR("Kamera projesinde model belirtilmemiş; --model ile verin.")); + +SS_MSG(cli_output_exists, + EN("{0} is already there. Add --overwrite to replace it."), + JA("{0} は既にあります。置き換えるには --overwrite を付けてください。"), + ZH_HANS("{0} 已存在。加上 --overwrite 以替换。"), + ZH_HANT("{0} 已存在。加上 --overwrite 以取代。"), + KO("{0}이(가) 이미 있습니다. 바꾸려면 --overwrite를 붙이세요."), + DE("{0} ist schon vorhanden. Mit --overwrite wird es ersetzt."), + FR("{0} existe déjà. Ajoutez --overwrite pour le remplacer."), + ES("{0} ya existe. Añada --overwrite para sustituirlo."), + PT("{0} já existe. Adicione --overwrite para substituí-lo."), + IT("{0} esiste già. Aggiungi --overwrite per sostituirlo."), + NL("{0} bestaat al. Voeg --overwrite toe om het te vervangen."), + RU("{0} уже существует. Добавьте --overwrite, чтобы заменить."), + TR("{0} zaten var. Değiştirmek için --overwrite ekleyin.")); + +SS_MSG(cli_no_gl, + EN("Cannot open an OpenGL context: {0}\nWith no display, run under xvfb-run."), + JA("OpenGL コンテキストを開けません: {0}\nディスプレイが無い場合は xvfb-run で実行してください。"), + ZH_HANS("无法打开 OpenGL 上下文:{0}\n没有显示器时,请用 xvfb-run 运行。"), + ZH_HANT("無法開啟 OpenGL 環境:{0}\n沒有顯示器時,請用 xvfb-run 執行。"), + KO("OpenGL 컨텍스트를 열 수 없습니다: {0}\n디스플레이가 없으면 xvfb-run으로 실행하세요."), + DE("Kein OpenGL-Kontext möglich: {0}\nOhne Display mit xvfb-run starten."), + FR("Impossible d’ouvrir un contexte OpenGL : {0}\nSans écran, lancez-le avec xvfb-run."), + ES("No se puede abrir un contexto OpenGL: {0}\nSin pantalla, ejecútelo con xvfb-run."), + PT("Não é possível abrir um contexto OpenGL: {0}\nSem tela, execute com xvfb-run."), + IT("Impossibile aprire un contesto OpenGL: {0}\nSenza display, avvialo con xvfb-run."), + NL("Kan geen OpenGL-context openen: {0}\nZonder beeldscherm draaien met xvfb-run."), + RU("Не удаётся открыть контекст OpenGL: {0}\nБез дисплея запускайте через xvfb-run."), + TR("OpenGL bağlamı açılamıyor: {0}\nEkran yoksa xvfb-run ile çalıştırın.")); + +SS_MSG(cli_model_failed, + EN("Cannot open the model {0}: {1}"), + JA("モデル {0} を開けません: {1}"), + ZH_HANS("无法打开模型 {0}:{1}"), + ZH_HANT("無法開啟模型 {0}:{1}"), + KO("모델 {0}을(를) 열 수 없습니다: {1}"), + DE("Das Modell {0} lässt sich nicht öffnen: {1}"), + FR("Impossible d’ouvrir le modèle {0} : {1}"), + ES("No se puede abrir el modelo {0}: {1}"), + PT("Não é possível abrir o modelo {0}: {1}"), + IT("Impossibile aprire il modello {0}: {1}"), + NL("Kan het model {0} niet openen: {1}"), + RU("Не удаётся открыть модель {0}: {1}"), + TR("{0} modeli açılamıyor: {1}")); + +SS_MSG(cli_too_many_models, + EN("The project names {0} models; at most {1} can be rendered together."), + JA("プロジェクトには {0} 個のモデルがあります。同時にレンダリングできるのは {1} 個までです。"), + ZH_HANS("项目列出了 {0} 个模型;最多只能同时渲染 {1} 个。"), + ZH_HANT("專案列出了 {0} 個模型;最多只能同時算繪 {1} 個。"), + KO("프로젝트에 모델이 {0}개 있습니다. 함께 렌더링할 수 있는 것은 최대 {1}개입니다."), + DE("Das Projekt nennt {0} Modelle; höchstens {1} lassen sich zusammen rendern."), + FR("Le projet cite {0} modèles ; {1} au plus peuvent être rendus ensemble."), + ES("El proyecto nombra {0} modelos; como máximo se pueden renderizar {1} juntos."), + PT("O projeto lista {0} modelos; no máximo {1} podem ser renderizados juntos."), + IT("Il progetto elenca {0} modelli; al massimo {1} si possono renderizzare insieme."), + NL("Het project noemt {0} modellen; er kunnen er hoogstens {1} samen worden gerenderd."), + RU("В проекте {0} моделей; вместе можно рендерить не больше {1}."), + TR("Proje {0} model içeriyor; en fazla {1} tanesi birlikte render edilebilir.")); + +SS_MSG(cli_progress, + EN("Frame {0} of {1}"), + JA("フレーム {0} / {1}"), + ZH_HANS("第 {0} 帧,共 {1} 帧"), + ZH_HANT("第 {0} 格,共 {1} 格"), + KO("프레임 {0} / {1}"), + DE("Bild {0} von {1}"), + FR("Image {0} sur {1}"), + ES("Fotograma {0} de {1}"), + PT("Quadro {0} de {1}"), + IT("Fotogramma {0} di {1}"), + NL("Beeld {0} van {1}"), + RU("Кадр {0} из {1}"), + TR("Kare {0} / {1}")); + } // namespace render } // namespace msg } // namespace i18n