Compare commits

86 Commits
Author SHA1 Message Date
survandClaude Opus 5.5 ceff95ff40 feat: add encoder tuning harness
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 07:20:33 +02:00
surv 49130f5ecf perf: remove shader checks 2026-09-28 17:22:08 +02:00
surv 493a743a16 feat: Add benchmark tool 2026-09-28 17:17:38 +02:00
surv 0d7aadb991 perf: switch from dashu to rug & malachite 2026-09-28 11:54:22 +02:00
surv ae7ca97c41 feat: add tools script to find interesting places 2026-09-28 10:52:37 +02:00
surv 3f5853a23c feat: add Makefile to run ffmpeg 2026-09-28 10:44:36 +02:00
surv 2e116ba47b feat: add AA in headless exports 2026-09-28 10:44:24 +02:00
surv a15e951f84 feat: add --shards CLI option to split an animation into multiple run 2026-09-28 09:03:20 +02:00
surv 27c5a1a603 feat: allow emmiting frames on stdout to pipe them in ffmpeg 2026-09-28 08:40:00 +02:00
surv d78594af7e feat: bind GUI real time rendering behind a feature 2026-09-27 14:43:23 +02:00
surv 4212839f0d fix: avoid hitting GPU watchdog 2026-09-27 14:05:09 +02:00
surv 48560de315 fix: Raise max iterations limit 2026-09-27 13:23:53 +02:00
surv 8750bb1590 fix: Smooth 2d shadow view of complex multibrot 2026-09-27 13:20:48 +02:00
surv f30921f7a5 fix: Smooth 3d view of complex multibrot 2026-09-27 13:17:35 +02:00
surv b6467fc18c fix: DE of multibrot fractal 2026-09-27 12:31:30 +02:00
surv 28ff2471b3 feat: multibrot exponent up to 20 2026-09-27 12:23:11 +02:00
surv 1bb3113581 fix: remove zoom limits 2026-09-27 12:17:08 +02:00
surv bfd3d18f3d feat: Add arbitrary precision numbers at deep zooms 2026-09-25 15:30:05 +02:00
surv fbf0ef64af fix: add c parameter again for lambda fractal in julia mode 2026-09-25 10:06:01 +02:00
surv 0d86e7b0e0 fix: periodicity checking stop flagging false positives 2026-09-25 10:02:14 +02:00
surv 583a535806 feat: allow bigger render distance in 3d view 2026-09-25 09:46:36 +02:00
surv ba385be18d fix: remove red band above small slope in 3d 2026-09-25 09:32:11 +02:00
surv 120e73fb10 fix: small zoom in 3d mode no longer create visual artefacts 2026-09-25 09:20:55 +02:00
surv 8889a09bf8 fix: remove weird gray circle around fractals 2026-09-25 09:13:59 +02:00
surv 94f9c488bd fix: complex multibrot rendering 2026-09-25 08:43:59 +02:00
surv a092be84b0 chore: remove warnings on web version 2026-09-25 08:12:02 +02:00
surv 73570fdab8 perf: Use multithreading for headless animation export 2026-09-25 08:09:34 +02:00
surv 9b0dec25e2 perf: reduce memory usage\nAllocate textures only when needed 2026-09-24 22:18:44 +02:00
surv 38cbb1f132 feat: add more animations and 3d export 2026-09-24 22:12:56 +02:00
surv 61d4766088 perf: disable AA when switching fractals 2026-09-24 21:56:39 +02:00
surv 51fa5ffa02 feat: add interpolation between fractals 2026-09-24 21:43:36 +02:00
surv 9cc5a80650 feat: add classic colors in 3d 2026-09-24 21:39:00 +02:00
surv 6a6796f528 fix: reduce memory usage on web 2026-09-24 21:06:34 +02:00
surv b4ca187ba2 fix: shadow and 3d rendering at deep zoom and on weird fractals 2026-09-24 20:38:37 +02:00
surv 2bdb2356c6 perf: improve 3d ray marching performance 2026-09-24 19:45:17 +02:00
surv 5206a22bdd fix: UX issues solved 2026-09-24 19:16:56 +02:00
surv 42dde04945 perf: add periodicity checking 2026-09-24 18:53:17 +02:00
surv a3fd152dff perf: improve overall performance 2026-09-24 18:23:19 +02:00
surv 7dd99cc1af feat: update gitignore 2026-09-24 16:48:06 +02:00
surv 63cee5d8b2 fix: correct 3d rendering 2026-09-23 18:34:00 +02:00
surv 694f63ab9d feat: improve CLI arguments 2026-09-22 11:39:11 +02:00
surv 7274f19b33 feat: improve UI/UX 2026-09-22 09:59:58 +02:00
surv 66669cd801 feat: add 3d support 2026-09-22 09:36:30 +02:00
surv c2de1bc4bb fix: disable auto-iterations when passing an iterations parameter in CLI through --view 2026-09-21 22:42:55 +02:00
surv 07319874bf fixup: add animation export 2026-09-20 15:23:15 +02:00
surv 449b1b289b feat: add animation export 2026-09-20 14:12:54 +02:00
surv 993185795f feat: improve CLI 2026-09-20 13:37:33 +02:00
surv 456d744ac6 feat: Better default values 2026-09-20 13:37:33 +02:00
surv 90d917ede0 refactor: cleanup code 2026-09-20 13:37:33 +02:00
surv 5a81247d76 refactor: add common shaders helpers + fix shadow export 2026-09-20 13:37:33 +02:00
surv d84e752e15 feat: improve colors when using distance estimate 2026-09-20 13:37:33 +02:00
surv eb041c22c5 feat: improve UI/UX 2026-09-20 13:37:33 +02:00
surv 06b52fe954 feat: Add complex multibrot fractal 2026-09-20 13:37:33 +02:00
surv c7d687c107 feat: minor visual fix for PNG export 2026-09-20 13:37:33 +02:00
survandClaude Sonnet 5 c2b38ea21b feat: add keyboard shortcuts for pan/zoom/iterations/AA
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-20 13:37:33 +02:00
survandClaude Sonnet 5 16a916d35a feat: add fractal info and help overlays
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-20 13:37:33 +02:00
survandClaude Sonnet 5 45654c0846 feat: add a headless mode, driven by clap CLI args
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-20 13:37:33 +02:00
survandClaude Sonnet 5 cc0609ffbb feat: add clap CLI arg parser, replacing MANDEL_* debug env vars
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-19 20:50:17 +02:00
surv 0f25c89a7b feat: Add a CLAUDE.md file 2026-09-19 20:50:17 +02:00
surv 908c13bfb0 feat: add shadow coloring 2026-09-19 20:50:17 +02:00
surv 7c347a5abf feat: add buddhabrot fractal 2026-09-16 22:04:21 +02:00
surv afcd3c74da feat: add lambda fractal 2026-09-16 20:32:48 +02:00
surv 0b90b72a00 feat: remove warning and increase performance 2026-09-16 20:14:39 +02:00
surv ad63a1da09 feat: add more presets 2026-09-16 15:32:13 +02:00
surv f373db91e6 chore: Refactor files and fix warnings 2026-09-16 15:31:40 +02:00
surv f039d38bfa feat: Add FPS counter 2026-09-15 21:22:39 +02:00
surv fbe7f4da13 perf: editing theme doesn't require a complete reredenring 2026-09-15 21:14:14 +02:00
surv a5b26ce738 feat: Add animations 2026-09-15 21:00:29 +02:00
surv 311b797724 feat: Add fullscreen button 2026-09-15 20:28:51 +02:00
surv 7f4f31a09f feat: Add more fractals 2026-09-15 19:28:49 +02:00
surv d77baf5e15 feat: add favicon 2026-09-15 18:29:38 +02:00
surv 9e9641891e feat: distance-estimation shading for crisp deep-zoom filaments 2026-09-15 15:50:57 +02:00
surv acbf25d64e feat: lossless share links + auto iteration count 2026-09-15 15:50:57 +02:00
surv c92c685ade perf: reduce resolution and disable AA when moving/zooming 2026-09-15 15:50:57 +02:00
surv c36c8b9829 feat: add other fractals 2026-09-15 15:50:57 +02:00
surv 72c3ea2ee8 feat: add rendering export progress bar 2026-09-15 11:01:30 +02:00
surv f9a51fd2d7 feat: add PNG encoding progress bar 2026-09-15 10:42:39 +02:00
surv a7a34adff2 feat: add presets for mandelbrot 2026-09-15 10:18:19 +02:00
surv 9069d23b21 feat: coordinates and magnification can be set to specific values 2026-09-15 09:48:53 +02:00
surv 96c5d6344e feat: make amber the default theme 2026-09-15 09:38:57 +02:00
surv 8bed728585 feat: add multi touch zoom on phones 2026-09-15 09:27:39 +02:00
surv b2c29504bc feat: don't draw the fractal each frames 2026-09-15 09:22:38 +02:00
surv 343ddfc4b7 feat: add SSAA 2026-09-15 09:07:21 +02:00
surv 10fc122e9c feat: allow bigger exports 2026-09-15 09:06:58 +02:00
surv c197a03a51 feat: force webgpu in WASM 2026-09-15 08:55:18 +02:00
surv 09d7976ebd First commit 2026-09-15 08:55:18 +02:00
18 changed files with 56 additions and 3478 deletions
+5 -53
View File
@@ -45,16 +45,12 @@ Native CLI flags (`src/cli.rs`, applied in `FractalApp::apply_cli`): `--kind`,
`--palette`, `--share <fragment>`,
`--view re,im,half_height[,iterations]`, `--rendering-kind`,
`--yaw`/`--pitch` (3D camera, degrees), `--de`, `--antialias` (2×2),
`--auto-color-scale`, `--color-scale`, `--no-bla`, `--buddhabrot`,
`--buddhabrot`,
`--buddha-palette`. `--headless` (`src/headless.rs`) skips the window
entirely: it builds the same view from the other flags, creates its own
offscreen wgpu device, and renders straight to a PNG (`--width`/`--height`,
default 1920×1080, `--export-path out.png`) without needing a GPU-backed
window/event loop. Not yet supported with `--buddhabrot`. With
`--auto-color-scale`, a downscaled 1-spp `fs_data` prepass
(`ExportRender::ci_range_blocking`, ≤ 1024 px) is histogrammed like the
interactive `CiStats`. The fit is then written into the export's uniforms,
and animations refit every frame from the same start. Run
window/event loop. Not yet supported with `--buddhabrot`. Run
`mandelbrot --help` for the full list.
`--headless` also has an animation mode, for feeding into `ffmpeg`: give any
@@ -64,11 +60,8 @@ end-state flag alongside the start flags (`--view`/`--share`/`--kind`/
position/zoom/iterations are pulled out of the link), `--to-iterations`,
`--to-julia`, `--to-phoenix-p`, `--to-lambda-l`, `--to-complex-power`
(or `--to-complex-power-re`/`--to-complex-power-im` to move one component),
`--to-kind` (per-step formula blend via `KindMorph`, camera untouched), and
`--to-color-scale` (log-linear from `--color-scale`; refused with
`--auto-color-scale`; `--to-color-scale-at HALF_HEIGHT` pins its completion
to a zoom depth instead of the end). Anything without a target stays at its start value;
other colors (palette, offset) stay fixed.
and `--to-kind` (per-step formula blend via `KindMorph`, camera untouched).
Anything without a target stays at its start value; colors stay fixed.
`--export-path` then names an output *directory* of `frame-00001.png`,
`frame-00002.png`, ... instead of a single file. `--export-path -` writes
to stdout instead (refused on a terminal): the PNG for a still, or for an
@@ -245,37 +238,6 @@ pixel is a handful of `f32` complex multiplies.
changing it. Known gaps: Lambda's critical point is 1/2, so its step keeps
the input scale. Lambda set mode's reference sits at the origin, so it
never reaches deep zooms anyway.
- `src/fractal/bla.rs` — **bivariate linear approximation**: a table of
merged linear steps `e' = M·e + N·dc` (real 2×2 matrices; valid while
`|e| < R`) built on the CPU from the reference orbit, so the shader's
`bla_lookup` jumps each pixel over whole runs of steps. Every kind but
Phoenix (two-term map), no morph (`bla::applies`, the `BLA` override).
`M` is the map's Jacobian at `X`: `C(f'(X))` for the holomorphic kinds, a
sign fold of `C(2X)` for the abs/conjugate ones. Each kind's `M` and
radius live in `Node::step`, which must match `advance_delta_kind`. The
abs kinds' radius also keeps the delta off their fold lines (where
`diffabs` switches branch), and Complex Multibrot's keeps it off the
branch cut. So Burning Ship / Perpendicular / Buffalo can't jump along the
real axis (their fold), where their orbits often sit. Merges use the exact
2×2 spectral norm (Frobenius would lose √2 of radius per level). This is
what makes deep zoom fast: every pixel follows the reference for tens of
thousands of steps before diverging (Mandelbrot 1e-200: 12.7 s → 0.7 s
at 960×540). Level `l` node `i` covers steps `1 + i·2^l ..`, and only
levels ≥ 3 are uploaded (bindings 4/5, 48 B nodes, `bla_meta` =
`[min_level, levels, offsets…]`). Coefficients are floatexp (f32
mantissas + i32 exponent), so a jump in the deep prologue lands straight
at its output scale. `R` depends on the view's largest `|dc|`
(`dc_max_log2`), so `FractalApp::bla_table` rebuilds on reference or kind
change or when the dc range grows (or shrinks by `BLA_DC_SLACK` binades).
Exports/headless build per frame via `bla::for_uniforms`. The table stops
before the reference crosses the pixel bailout, so a jump never skips an
escape. Measure `|e|` with `log2_mag`, never `log2(dot(e, e))`: a
2^-100 delta squares to 0 in f32 and passed every radius test.
`--no-bla` / the "Skip iterations (BLA)" checkbox upload an empty table
for A/B checks. BLA must render like `--no-bla` up to f32 noise; on
chaotic views, compare against a `--no-bla` render nudged by ~0.01 px,
which differs by more. `escape_counts_match_all_kinds` checks every
kind on the CPU against the plain loop with f32 rounding.
- `src/fractal/renderer.rs` — `FractalRenderer` (wgpu pipelines, uniform +
storage buffers, bind groups), `Uniforms` (repr(C) layout that must match
the WGSL `Uniforms` struct field-for-field, including padding; it includes
@@ -317,9 +279,7 @@ arms), `reference.rs` (CPU iteration formula arm, and a test comparing
against a naive `f64` iteration), `common.wgsl` (matching `KIND_*` const),
`mandelbrot.wgsl` (matching `advance_delta`/`fprime` arms, plus the deep
path's `advance_delta_scaled_kind` arm, its degree in `deep_step_kind` and,
if not z²-like, a `deep_fprime` arm), `bla.rs` (a `Node::step` arm: the
step's Jacobian and linearity radius, plus a case in
`escape_counts_match_all_kinds`; or exclude the kind in `applies`), `buddhabrot.wgsl`
if not z²-like, a `deep_fprime` arm), `buddhabrot.wgsl`
(matching arm in `advance()`, if the kind makes sense as a Buddhabrot),
`renderer.rs` `Uniforms` (only if the kind needs a new per-kind constant,
e.g. Phoenix's `phoenix_p`), `app.rs` (`JULIA_PRESETS`/`SET_PRESETS` slot,
@@ -368,14 +328,6 @@ mip pyramid (quadtree height-field tracing) was tried and measured about 3×
slower, because it needs about 12 costlier steps per ray. Don't reintroduce it.
Orbiting the camera only re-runs the colourise pass, never iteration.
**Auto color scale** (`CiStats` in `renderer.rs`, `ci_stats.wgsl`): after
each iteration, a compute pass bins the data texture's `ci` into a log-scale
histogram. It's read back asynchronously: copied in frame N, mapped in N+1
(the copy has to be submitted first), and picked up by
`FractalApp::poll_ci_stats`. The app then fits one palette cycle across the
0.5–99.5th percentile. `ci_lo` shifts the offset (`effective_color_offset`),
which is what exports and share links get.
While the user is actively panning/zooming, the app renders downscaled with
AA off (`INTERACT_DOWNSCALE`) and snaps back to full resolution once input
settles (`INTERACT_SETTLE`).
-674
View File
@@ -1,674 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+3 -25
View File
@@ -1,9 +1,9 @@
.PHONY: hevc-nvenc x265 x265-master x265-small av1 av1-master av1-small
.PHONY: hevc-nvenc x265 x265-master av1 av1-master
FFMPEG=ffmpeg
IN_FMT=rgba
RESOLUTION=1920x1080
RESOLUTION=3840x2160
FPS=60
OUT=out.mp4
@@ -19,9 +19,7 @@ COLOR_TAGS=-colorspace bt709 -color_primaries bt709 -color_trc bt709 -color_rang
# Settings and CRFs come from tools/encode/ (see its README for the numbers).
# Tiers: `x265`/`av1` = delivery (VMAF ~95 mean, >= 90 worst frame, smallest
# file); `*-master` = upload master (>= 97 worst frame, size secondary);
# `*-small` = about half the delivery size, visibly softer on faint texture
# (CRF extrapolated from the sweeps, not measured).
# file); `*-master` = upload master (>= 97 worst frame, size secondary).
# The binding test clip is a faint, low-contrast Julia texture: at a CRF where
# dense filaments already score 99, both encoders smear it, so it sets the CRF.
@@ -75,16 +73,6 @@ x265-master:
-tag:v hvc1 -movflags +faststart \
$(OUT)
# Small: CRF 23, ~half the size of `x265` (bitrate fell ~40% from CRF 16 to 20).
# Untested: expect faint texture around VMAF 89 mean; dense detail stays ~97+.
x265-small:
$(FFMPEG_IN) -vf "$(SCALE),format=yuv420p10le,$(TAG)" \
-c:v libx265 -profile:v main10 -preset medium -crf 23 \
-x265-params "$(X265_PARAMS)" \
$(COLOR_TAGS) \
-tag:v hvc1 -movflags +faststart \
$(OUT)
# Delivery: CRF 32 (binding clip: VMAF 95.0 mean, 93.4 worst frame).
av1:
$(FFMPEG_IN) -vf "$(SCALE),format=yuv420p10le,$(TAG)" \
@@ -102,13 +90,3 @@ av1-master:
$(COLOR_TAGS) \
-movflags +faststart \
$(OUT)
# Small: CRF 40, ~half the size of `av1` (bitrate fell ~35% from CRF 26 to 32).
# Untested: expect faint texture around VMAF 92 mean; dense detail stays ~97+.
av1-small:
$(FFMPEG_IN) -vf "$(SCALE),format=yuv420p10le,$(TAG)" \
-c:v libsvtav1 -preset 6 -crf 40 \
-svtav1-params "$(SVT_PARAMS)" \
$(COLOR_TAGS) \
-movflags +faststart \
$(OUT)
+7 -204
View File
@@ -10,7 +10,6 @@ use glam::Vec4Swizzles;
use crate::camera::Camera;
#[cfg(not(target_arch = "wasm32"))]
use crate::cli::Cli;
use crate::fractal::bla::{self, BlaTable};
use crate::fractal::{
BuddhabrotCallback, BuddhabrotRenderer, BuddhabrotUniforms, ExportRender, FractalCallback,
FractalKind, FractalRenderer, MAX_REF_POINTS, RefOrbit, ShareState, Uniforms,
@@ -48,29 +47,12 @@ const MAX_EXPORT_DIM: u32 = 8192 * 16;
/// buffer holds (past it, the shader would read pixels as escaped).
const MAX_ITERATIONS: u32 = MAX_REF_POINTS as u32 - 1;
/// Binades of dc range a BLA table may overcover before it's rebuilt for a
/// zoomed-in view (it stays valid, but its radii shrink with dc_max).
const BLA_DC_SLACK: i32 = 2;
/// What the current BLA table was built for (see `FractalApp::bla_table`).
#[derive(Clone, Copy, PartialEq)]
struct BlaKey {
generation: u64,
kind: u32,
on: bool,
julia: bool,
dc_log2: i32,
}
/// While the user is actively panning/zooming, the fractal is rendered into a
/// cache texture downscaled by this factor per axis (and with AA forced off), so
/// each interacting frame is cheap; the linear blit upsamples it to the widget.
/// A full-resolution render replaces it once input settles. 2 → quarter the
/// pixels (~4× faster); raise for more speed at the cost of more blur in motion.
/// Default of the Advanced "low resolution scale" setting (a power of 2).
const INTERACT_DOWNSCALE: u32 = 2;
/// Largest selectable interaction downscale, as log2 (16×).
const MAX_INTERACT_DOWNSCALE_LOG2: u32 = 4;
/// Seconds without pan/zoom input after which the view counts as settled and is
/// re-rendered at full resolution.
const INTERACT_SETTLE: f64 = 0.12;
@@ -532,19 +514,10 @@ pub struct FractalApp {
auto_iterations: bool,
color_scale: f32,
color_offset: f32,
/// When set, `color_scale` stretches one palette cycle across the `ci`
/// range on screen (read back from the GPU, `FractalRenderer::take_ci_range`)
/// and the palette starts at its low end, `ci_lo`.
auto_color_scale: bool,
/// Lowest on-screen `ci` from the last auto fit; 0 while auto is off.
/// `color_offset` is relative to it (see `effective_color_offset`).
ci_lo: f32,
palette: u32,
shadow_palette: u32,
/// Supersample each pixel 2×2 for smoother edges (costs ~4× fragment work).
antialias: bool,
/// Skip perturbation steps with the BLA table (`fractal::bla`).
use_bla: bool,
/// Distance-estimation shading: darkens toward the set boundary using the
/// orbit derivative, giving crisp filaments at deep zoom instead of speckle.
de_coloring: bool,
@@ -599,11 +572,6 @@ pub struct FractalApp {
reference: Arc<RefOrbit>,
/// Bumped whenever `reference` is replaced, so the GPU re-uploads it.
generation: u64,
/// BLA table for `reference` (see `bla_table`), what it was built for,
/// and its own generation for the GPU upload.
bla: Arc<BlaTable>,
bla_key: Option<BlaKey>,
bla_generation: u64,
/// Center + zoom the current `reference` was computed at (may differ
/// slightly from the live view; the shader compensates via `dc_offset`).
ref_center_re: Big,
@@ -633,9 +601,6 @@ pub struct FractalApp {
/// egui time (seconds) of the most recent pan/zoom. While recent (within
/// `INTERACT_SETTLE`) the fractal renders downscaled for smooth interaction.
last_interact_time: f64,
/// log2 of the per-axis downscale applied while panning/zooming
/// (`1 << interact_downscale_log2`); higher = faster but blurrier in motion.
interact_downscale_log2: u32,
/// Set when the user requests a PNG export (handled after the panels draw).
export_requested: bool,
/// Progress/handle for an in-flight PNG export, if any.
@@ -745,12 +710,9 @@ impl FractalApp {
auto_iterations: true,
color_scale: 0.15,
color_offset: 0.0,
auto_color_scale: false,
ci_lo: 0.0,
palette: 0,
shadow_palette: 0,
antialias: false,
use_bla: true,
de_coloring: false,
rendering_mode: 0,
lights: vec![Light::default()],
@@ -771,9 +733,6 @@ impl FractalApp {
fps_window_start: 0.0,
reference: Arc::new(RefOrbit::default()),
generation: 0,
bla: Arc::new(BlaTable::empty()),
bla_key: None,
bla_generation: 0,
ref_center_re,
ref_center_im,
ref_half_height,
@@ -788,7 +747,6 @@ impl FractalApp {
#[cfg(feature = "gui")]
last_size_px: egui::vec2(1280.0, 720.0),
last_interact_time: -1.0e9,
interact_downscale_log2: INTERACT_DOWNSCALE.trailing_zeros(),
export_requested: false,
export: None,
#[cfg(not(target_arch = "wasm32"))]
@@ -892,9 +850,6 @@ impl FractalApp {
if cli.antialias {
self.antialias = true;
}
if cli.no_bla {
self.use_bla = false;
}
if cli.buddhabrot {
self.mode = FractalMode::Buddhabrot;
}
@@ -902,13 +857,6 @@ impl FractalApp {
self.buddha_palette = p.min(BUDDHA_PALETTE_NAMES.len() as u32 - 1);
self.palette = p.min(PALETTE_NAMES.len() as u32 - 1);
}
// After --share, which turns it off.
if cli.auto_color_scale {
self.auto_color_scale = true;
}
if let Some(scale) = cli.color_scale {
self.color_scale = scale.clamp(1e-4, 1.0);
}
self.export_path = cli.export_path;
}
@@ -1097,7 +1045,7 @@ impl FractalApp {
lambda_l: self.lambda_l,
complex_power: self.complex_power,
color_scale: self.color_scale,
color_offset: self.effective_color_offset(),
color_offset: self.color_offset,
palette: self.palette,
shadow_palette: self.shadow_palette,
}
@@ -1119,9 +1067,6 @@ impl FractalApp {
self.complex_power = s.complex_power;
self.color_scale = s.color_scale;
self.color_offset = s.color_offset;
// Like the iteration count: the link's explicit scale wins.
self.auto_color_scale = false;
self.ci_lo = 0.0;
self.palette = (s.palette as usize).min(PALETTE_NAMES.len() - 1) as u32;
self.shadow_palette =
(s.shadow_palette as usize).min(SHADOW_PALETTE_NAMES.len() - 1) as u32;
@@ -1292,41 +1237,6 @@ impl FractalApp {
&self.reference
}
/// Whether BLA is on (headless builds its own tables per frame).
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn use_bla(&self) -> bool {
self.use_bla
}
/// The BLA table for rendering `u` from the current reference, rebuilt
/// when the reference changed or the view's dc range left what the table
/// covers. A table built for a larger dc range is still valid, just
/// jumps less, so zooming in only rebuilds every `BLA_DC_SLACK` binades.
fn bla_table(&mut self, u: &Uniforms) -> Arc<BlaTable> {
let want = BlaKey {
generation: self.generation,
kind: u.kind,
on: self.use_bla && bla::applies(u),
julia: u.is_julia != 0,
dc_log2: bla::dc_max_log2(u),
};
let fresh = self.bla_key.as_ref().is_some_and(|k| {
k.generation == want.generation
&& k.kind == want.kind
&& k.on == want.on
&& k.julia == want.julia
&& (!want.on
|| want.julia
|| (want.dc_log2 <= k.dc_log2 && want.dc_log2 + BLA_DC_SLACK >= k.dc_log2))
});
if !fresh {
self.bla = Arc::new(bla::for_uniforms(&self.reference, u, self.use_bla));
self.bla_key = Some(want);
self.bla_generation = self.bla_generation.wrapping_add(1);
}
Arc::clone(&self.bla)
}
/// The configured shadow-style lights, for headless export's `ExportRender`
/// (which has no `FractalCallback` to source them from).
#[cfg(not(target_arch = "wasm32"))]
@@ -1482,61 +1392,6 @@ impl FractalApp {
self.last_request = Some(key);
}
/// The palette offset the shaders get: `color_offset`, shifted so the
/// palette starts at the auto fit's lowest on-screen `ci`.
fn effective_color_offset(&self) -> f32 {
(self.color_offset - self.ci_lo * self.color_scale).rem_euclid(1.0)
}
/// Pick up the GPU's latest on-screen `ci` range and refit the colour
/// scale to it (auto colour scale).
#[cfg(feature = "gui")]
fn poll_ci_stats(&mut self, ctx: &egui::Context, frame: &eframe::Frame) {
let Some(rs) = frame.wgpu_render_state() else {
return;
};
let mut guard = rs.renderer.write();
let Some(renderer) = guard.callback_resources.get_mut::<FractalRenderer>() else {
return;
};
let range = renderer.take_ci_range(&rs.device);
// Also one frame after a readback lands: the view may have changed
// while it was in flight, and that frame histograms it again.
if renderer.ci_stats_pending() || range.is_some() {
ctx.request_repaint();
}
if self.auto_color_scale
&& let Some(range) = range
{
self.apply_ci_range(range);
}
}
/// Fit one palette cycle across the `ci` range `[lo, hi]` (auto colour
/// scale).
pub(crate) fn apply_ci_range(&mut self, (lo, hi): (f32, f32)) {
self.color_scale = (1.0 / (hi - lo).max(1e-3)).clamp(1e-4, 1.0);
self.ci_lo = lo;
}
/// The colour scale and the auto fit's `ci_lo`, to restore with
/// [`Self::set_color_fit`].
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn color_fit(&self) -> (f32, f32) {
(self.color_scale, self.ci_lo)
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn set_color_fit(&mut self, (scale, ci_lo): (f32, f32)) {
self.color_scale = scale;
self.ci_lo = ci_lo;
}
/// Whether the auto colour scale applies to the current render.
pub(crate) fn auto_color_active(&self) -> bool {
self.auto_color_scale && self.uses_classic_palette()
}
/// Whether the classic escape-time palette (and its scale / offset /
/// palette controls) is in use: always in classic mode, and in shadow/3D
/// modes under the "Classic" shading palette.
@@ -1596,7 +1451,7 @@ impl FractalApp {
],
max_iter: self.max_iterations.min(MAX_REF_POINTS as u32 - 1),
ref_len: self.reference.len() as u32,
color_offset: self.effective_color_offset(),
color_offset: self.color_offset,
color_scale: self.color_scale,
bailout_sq: bailout_sq(self.ref_kind.unwrap_or(self.kind), self.power),
is_julia: matches!(self.mode, FractalMode::Julia) as u32,
@@ -1693,10 +1548,9 @@ impl FractalApp {
self.status = Some("export unavailable".into());
return;
};
renderer.export_handles(&device, &uniforms, false)
renderer.export_handles(&device, &uniforms)
};
let reference = Arc::clone(&self.reference);
let use_bla = self.use_bla;
let lights = self.lights.clone();
let shared = Arc::new(Mutex::new(ExportShared {
@@ -1714,9 +1568,8 @@ impl FractalApp {
.clone()
.unwrap_or_else(|| format!("fractal-{}.png", unix_timestamp()));
std::thread::spawn(move || {
let bla = bla::for_uniforms(&reference, &uniforms, use_bla);
let er = ExportRender::new(
&device, &queue, &handles, w, h, uniforms, &reference, &bla, &lights,
&device, &queue, &handles, w, h, uniforms, &reference, &lights,
);
let sh = Arc::clone(&shared);
let png =
@@ -1736,9 +1589,8 @@ impl FractalApp {
// Progress budget: rendering fills [0, RENDER_END], encoding the rest.
const RENDER_END: f32 = 0.6;
wasm_bindgen_futures::spawn_local(async move {
let bla = bla::for_uniforms(&reference, &uniforms, use_bla);
let er = ExportRender::new(
&device, &queue, &handles, w, h, uniforms, &reference, &bla, &lights,
&device, &queue, &handles, w, h, uniforms, &reference, &lights,
);
// Render tile by tile, awaiting each submission so the browser
@@ -2440,11 +2292,6 @@ impl FractalApp {
}
ui.checkbox(&mut self.antialias, "Antialiasing (2×2)")
.on_hover_text("Supersample each pixel for smoother edges (~4× slower).");
ui.checkbox(&mut self.use_bla, "Skip iterations (BLA)")
.on_hover_text(
"Bivariate linear approximation: jump over runs of iterations where \
every pixel follows the reference linearly. Much faster at deep zoom.",
);
if self.rendering_mode == 0 {
ui.checkbox(&mut self.de_coloring, "Distance shading")
.on_hover_text(
@@ -2469,25 +2316,11 @@ impl FractalApp {
});
}
if self.uses_classic_palette() {
let was_auto = self.auto_color_scale;
ui.checkbox(&mut self.auto_color_scale, "Auto color scale")
.on_hover_text(
"Stretch one palette cycle across the escape-time range visible on screen.",
);
if was_auto && !self.auto_color_scale {
// Fold the fit's start into the offset so nothing jumps.
self.color_offset = self.effective_color_offset();
self.ci_lo = 0.0;
}
if self.auto_color_scale {
ui.label(format!("color scale: {:.4} (auto)", self.color_scale));
} else {
ui.add(
egui::Slider::new(&mut self.color_scale, 0.0001..=1.0)
egui::Slider::new(&mut self.color_scale, 0.01..=1.0)
.text("color scale")
.logarithmic(true),
);
}
ui.add(egui::Slider::new(&mut self.color_offset, 0.0..=1.0).text("color offset"));
egui::ComboBox::from_label("palette")
.selected_text(PALETTE_NAMES[self.palette as usize])
@@ -2519,27 +2352,6 @@ impl FractalApp {
ui.separator();
ui.add_space(4.);
ui.collapsing("Advanced", |ui| {
ui.add(
egui::Slider::new(
&mut self.interact_downscale_log2,
0..=MAX_INTERACT_DOWNSCALE_LOG2,
)
.text("low resolution scale")
.custom_formatter(|v, _| format!("1/{}", 1u32 << v as u32))
.custom_parser(|s| {
let s = s.trim();
let n: u32 = s.strip_prefix("1/").unwrap_or(s).trim().parse().ok()?;
n.is_power_of_two().then(|| n.trailing_zeros() as f64)
}),
)
.on_hover_text(
"Resolution divisor (per axis) while panning/zooming. Higher gives \
more FPS at deep zoom but a blurrier image in motion; full \
resolution returns once input settles.",
);
});
ui.collapsing("Animation", |ui| {
if self.uses_classic_palette() {
ui.checkbox(&mut self.anim.color, "Cycle colours")
@@ -3100,11 +2912,7 @@ impl FractalApp {
// Cache-texture resolution: the widget size in physical pixels, divided
// down while interacting (the linear blit upsamples it to the widget).
let ppp = ui.ctx().pixels_per_point();
let downscale = if interacting {
1 << self.interact_downscale_log2
} else {
1
};
let downscale = if interacting { INTERACT_DOWNSCALE } else { 1 };
let mut size_px = [
(((rect.width() * ppp).round() as u32) / downscale).max(1),
(((rect.height() * ppp).round() as u32) / downscale).max(1),
@@ -3130,7 +2938,6 @@ impl FractalApp {
if interacting || self.morph.is_some() || self.ref_morph.is_some() {
uniforms.aa_level = 1;
}
let bla = self.bla_table(&uniforms);
ui.painter().add(egui_wgpu::Callback::new_paint_callback(
rect,
FractalCallback {
@@ -3138,10 +2945,7 @@ impl FractalApp {
lights: gpu_lights(&self.lights).0,
reference: Arc::clone(&self.reference),
generation: self.generation,
bla,
bla_generation: self.bla_generation,
size_px,
auto_color: self.auto_color_active(),
},
));
}
@@ -3151,7 +2955,6 @@ impl FractalApp {
impl eframe::App for FractalApp {
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
self.poll_export(ui.ctx());
self.poll_ci_stats(ui.ctx(), frame);
self.update_fps(ui);
// Track the real fullscreen state (e.g. the user pressing Esc/F11 or the
// browser leaving fullscreen) so the toggle button label stays correct.
-27
View File
@@ -78,26 +78,10 @@ pub struct Cli {
#[arg(long)]
pub antialias: bool,
/// Disable bivariate linear approximation (BLA), i.e. iterate every
/// perturbation step (for A/B comparisons; much slower at deep zoom).
#[arg(long)]
pub no_bla: bool,
/// Coloring palette index.
#[arg(long, value_name = "INDEX")]
pub palette: Option<u32>,
/// Fit the colour scale to the image: one palette cycle across its
/// escape-time range (classic palette only). Animations refit it on
/// every frame.
#[arg(long)]
pub auto_color_scale: bool,
/// Colour scale: palette cycles per escape-time unit, clamped to
/// [0.0001, 1] (overrides a --share link's value).
#[arg(long, value_name = "SCALE")]
pub color_scale: Option<f32>,
/// Output path for --headless (default: fractal-<timestamp>.png). When
/// animating (--to-view/--to-share), this is a directory of
/// frame-00001.png, frame-00002.png, ... instead (default:
@@ -124,17 +108,6 @@ pub struct Cli {
#[arg(long)]
pub to_iterations: Option<u32>,
/// End colour scale for an animation (from --color-scale), interpolated
/// geometrically. Can't be combined with --auto-color-scale.
#[arg(long, value_name = "SCALE")]
pub to_color_scale: Option<f32>,
/// Zoom depth (half-height, e.g. 1e-60) at which --to-color-scale is
/// reached: the scale then follows the zoom depth from the start view to
/// there, and holds. Requires --to-color-scale.
#[arg(long, value_name = "HALF_HEIGHT")]
pub to_color_scale_at: Option<String>,
/// End Julia constant for an animation: c is interpolated from --julia
/// to this over the frames.
#[arg(long, value_name = "RE,IM", allow_hyphen_values = true)]
-1090
View File
File diff suppressed because it is too large Load Diff
-1
View File
@@ -1,7 +1,6 @@
//! GPU fractal rendering: wgpu pipeline, uniforms, reference orbit, and the
//! egui paint callback.
pub mod bla;
pub mod buddhabrot;
pub mod kind;
pub mod reference;
+3 -545
View File
@@ -16,7 +16,6 @@ use std::sync::Arc;
use eframe::egui_wgpu;
use wgpu::util::DeviceExt as _;
use super::bla::BlaTable;
use super::kind::FractalKind;
use super::reference::RefOrbit;
use crate::lights::{GpuLight, Light, MAX_LIGHT_COUNT, gpu_lights};
@@ -102,9 +101,6 @@ pub struct PipelineKey {
/// Deep view: the delta starts out in rescaled (mantissa + exponent)
/// form (`scale_exp != 0`).
deep: bool,
/// BLA jumps (`bla::applies`; disabling BLA uploads an empty table
/// instead, see `BlaTable::empty`).
bla: bool,
}
impl PipelineKey {
@@ -115,18 +111,16 @@ impl PipelineKey {
de: u.de_coloring != 0,
morph: u.morph_w > 0.0,
deep: u.scale_exp != 0,
bla: super::bla::applies(u),
}
}
fn constants(&self) -> [(&'static str, f64); 6] {
fn constants(&self) -> [(&'static str, f64); 5] {
[
("KIND", self.kind as f64),
("IS_JULIA", self.julia as u32 as f64),
("DE", self.de as u32 as f64),
("MORPH", self.morph as u32 as f64),
("DEEP", self.deep as u32 as f64),
("BLA", self.bla as u32 as f64),
]
}
}
@@ -427,245 +421,6 @@ fn lipschitz_slots(width: u32, height: u32) -> Vec<u32> {
(0..=top).rev().chain(std::iter::once(0)).collect()
}
/// Histogram bins of `ci_stats.wgsl` (must match its `CI_BINS`).
const CI_BINS: usize = 1024;
/// Upper end of the histogram's log2(1 + ci) range (`CI_LOG2_MAX` in WGSL).
const CI_LOG2_MAX: f32 = 25.0;
/// Fraction of escaped pixels ignored at each end of the `ci` range the auto
/// colour scale fits: the few pixels hugging the boundary have `ci` near
/// `max_iter` and would otherwise squash the rest into one palette band.
const CI_TAIL: f64 = 0.005;
/// Longest side (px) of an export's auto-colour prepass
/// ([`ExportRender::ci_range_blocking`]).
#[cfg(not(target_arch = "wasm32"))]
const CI_PROBE_MAX_DIM: u32 = 1024;
/// Where the `ci` histogram readback is (see [`CiStats`]).
enum CiStatsState {
Idle,
/// Histogram copied into `staging` by an encoder egui hasn't submitted
/// yet: mapping must wait for the next frame.
Copied,
/// `map_async` issued; the flag is set once the mapping completes.
Mapping(Arc<std::sync::atomic::AtomicBool>),
}
/// The `ci` histogram compute pass (`ci_stats.wgsl`), shared by the
/// interactive [`CiStats`] and headless exports ([`ExportRender::ci_range_blocking`]).
#[derive(Clone)]
struct CiHistogram {
pipeline: wgpu::ComputePipeline,
layout: wgpu::BindGroupLayout,
}
/// Auto colour scale: a compute pass bins the data texture's `ci` into a
/// histogram (`ci_stats.wgsl`), read back asynchronously one or two frames
/// later by [`FractalRenderer::take_ci_range`].
struct CiStats {
histogram: CiHistogram,
hist: wgpu::Buffer,
staging: wgpu::Buffer,
state: CiStatsState,
/// The data texture changed since the last histogram was recorded.
stale: bool,
}
impl CiHistogram {
fn new(device: &wgpu::Device) -> Self {
let module = unsafe {
device.create_shader_module_trusted(
wgpu::ShaderModuleDescriptor {
label: Some("ci stats"),
source: wgpu::ShaderSource::Wgsl(
include_str!("../shaders/ci_stats.wgsl").into(),
),
},
wgpu::ShaderRuntimeChecks::unchecked(),
)
};
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("ci stats bind group layout"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
],
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("ci stats pipeline layout"),
bind_group_layouts: &[Some(&layout)],
immediate_size: 0,
});
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("ci stats pipeline"),
layout: Some(&pipeline_layout),
module: &module,
entry_point: Some("cs_main"),
compilation_options: Default::default(),
cache: None,
});
Self { pipeline, layout }
}
/// The histogram buffer and its mappable readback copy.
fn buffers(device: &wgpu::Device) -> (wgpu::Buffer, wgpu::Buffer) {
let size = (CI_BINS * std::mem::size_of::<u32>()) as u64;
let hist = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("ci histogram"),
size,
usage: wgpu::BufferUsages::STORAGE
| wgpu::BufferUsages::COPY_SRC
| wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let staging = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("ci histogram readback"),
size,
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
(hist, staging)
}
/// Record the histogram of `data` (`width`×`height`) into `hist`, and its
/// copy into `staging`.
#[allow(clippy::too_many_arguments)]
fn record(
&self,
device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder,
data: &wgpu::TextureView,
width: u32,
height: u32,
hist: &wgpu::Buffer,
staging: &wgpu::Buffer,
) {
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("ci stats bind group"),
layout: &self.layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(data),
},
wgpu::BindGroupEntry {
binding: 1,
resource: hist.as_entire_binding(),
},
],
});
encoder.clear_buffer(hist, 0, None);
{
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("ci stats pass"),
timestamp_writes: None,
});
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, &bind_group, &[]);
pass.dispatch_workgroups(width.div_ceil(16), height.div_ceil(16), 1);
}
encoder.copy_buffer_to_buffer(hist, 0, staging, 0, None);
}
}
impl CiStats {
fn new(histogram: CiHistogram, device: &wgpu::Device) -> Self {
let (hist, staging) = CiHistogram::buffers(device);
Self {
histogram,
hist,
staging,
state: CiStatsState::Idle,
stale: true,
}
}
/// Record the histogram of `data` (`width`×`height`) and its copy into
/// `staging`. The caller checks the state is `Idle`.
fn record(
&mut self,
device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder,
data: &wgpu::TextureView,
width: u32,
height: u32,
) {
self.histogram.record(
device,
encoder,
data,
width,
height,
&self.hist,
&self.staging,
);
self.state = CiStatsState::Copied;
self.stale = false;
}
/// Start mapping a histogram copied on an earlier (now submitted) frame.
fn start_map(&mut self) {
if let CiStatsState::Copied = self.state {
let done = Arc::new(std::sync::atomic::AtomicBool::new(false));
let flag = Arc::clone(&done);
self.staging
.slice(..)
.map_async(wgpu::MapMode::Read, move |res| {
if res.is_ok() {
flag.store(true, std::sync::atomic::Ordering::Release);
}
});
self.state = CiStatsState::Mapping(done);
}
}
}
/// The `ci` range `[lo, hi]` between the [`CI_TAIL`] percentiles of a
/// `ci_stats.wgsl` histogram, or `None` if no pixel escaped.
fn ci_range(hist: &[u32]) -> Option<(f32, f32)> {
let total: u64 = hist.iter().map(|&n| n as u64).sum();
if total == 0 {
return None;
}
let bin_ci = |i: usize| {
let x = (i as f32 + 0.5) * (CI_LOG2_MAX / CI_BINS as f32);
x.exp2() - 1.0
};
let percentile = |p: f64| {
let target = (p * total as f64).ceil().max(1.0) as u64;
let mut acc = 0;
for (i, &n) in hist.iter().enumerate() {
acc += n as u64;
if acc >= target {
return i;
}
}
hist.len() - 1
};
Some((
bin_ci(percentile(CI_TAIL)),
bin_ci(percentile(1.0 - CI_TAIL)),
))
}
/// The interactive iteration pipelines for one [`PipelineKey`].
struct IteratePipelines {
/// 1-spp perturbation iterate → data texture (`fs_data`).
@@ -775,7 +530,6 @@ struct CacheTarget {
struct IterState {
uniforms: Uniforms,
generation: u64,
bla_generation: u64,
width: u32,
height: u32,
}
@@ -789,48 +543,6 @@ struct ColorState {
height: u32,
}
/// GPU copy of a [`BlaTable`] (bindings 4 and 5 of the iterate group).
struct BlaBuffers {
nodes: wgpu::Buffer,
meta: wgpu::Buffer,
}
impl BlaBuffers {
/// Buffers holding exactly `table` (plus room to grow into, `min_*`).
fn new(device: &wgpu::Device, table: &BlaTable, min_nodes: usize, min_meta: usize) -> Self {
// Padded with zeros up to the requested capacity.
let init = |label, data: &[u8], size: usize| {
let mut bytes = data.to_vec();
bytes.resize(size.max(data.len()), 0);
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some(label),
contents: &bytes,
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
})
};
let node_size = std::mem::size_of::<super::bla::GpuBla>();
Self {
nodes: init(
"bla nodes",
bytemuck::cast_slice(&table.nodes),
min_nodes * node_size,
),
meta: init("bla meta", bytemuck::cast_slice(&table.meta), min_meta * 4),
}
}
fn write(&self, queue: &wgpu::Queue, table: &BlaTable) {
queue.write_buffer(&self.nodes, 0, bytemuck::cast_slice(&table.nodes));
queue.write_buffer(&self.meta, 0, bytemuck::cast_slice(&table.meta));
}
fn fits(&self, table: &BlaTable) -> bool {
let node_size = std::mem::size_of::<super::bla::GpuBla>() as u64;
table.nodes.len() as u64 * node_size <= self.nodes.size()
&& table.meta.len() as u64 * 4 <= self.meta.size()
}
}
pub struct FractalRenderer {
/// `mandelbrot.wgsl`, specialized per [`PipelineKey`] at pipeline creation.
shader: wgpu::ShaderModule,
@@ -847,9 +559,6 @@ pub struct FractalRenderer {
ref_exp_buffer: wgpu::Buffer,
/// Points `ref_buffer` / `ref_exp_buffer` can hold (see `ensure_ref_capacity`).
ref_capacity: usize,
bla: BlaBuffers,
/// Generation of the BLA table currently in `bla`.
uploaded_bla_generation: u64,
lights_buffer: wgpu::Buffer,
bind_group: wgpu::BindGroup,
target_format: wgpu::TextureFormat,
@@ -878,8 +587,6 @@ pub struct FractalRenderer {
iterated: Option<IterState>,
/// What the colour texture holds; `None` forces a recolour.
colored: Option<ColorState>,
/// Auto colour scale's `ci` histogram + readback.
ci_stats: CiStats,
}
impl FractalRenderer {
@@ -903,11 +610,6 @@ impl FractalRenderer {
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
self.rebuild_bind_group(device);
self.ref_capacity = capacity;
}
fn rebuild_bind_group(&mut self, device: &wgpu::Device) {
self.bind_group = iterate_bind_group(
device,
&self.bind_group_layout,
@@ -915,18 +617,8 @@ impl FractalRenderer {
&self.ref_buffer,
&self.lights_buffer,
&self.ref_exp_buffer,
&self.bla,
);
}
/// Upload `table`, growing the BLA buffers (by powers of two) if needed.
fn upload_bla(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, table: &BlaTable) {
if self.bla.fits(table) {
self.bla.write(queue, table);
return;
}
self.bla = BlaBuffers::new(device, table, table.nodes.len().next_power_of_two(), 64);
self.rebuild_bind_group(device);
self.ref_capacity = capacity;
}
pub fn new(device: &wgpu::Device, target_format: wgpu::TextureFormat) -> Self {
@@ -1023,31 +715,9 @@ impl FractalRenderer {
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 4,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
// BLA table nodes / meta (`fractal::bla`).
wgpu::BindGroupLayoutEntry {
binding: 5,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
],
});
let bla = BlaBuffers::new(device, &BlaTable::empty(), 1 << 14, 64);
let bind_group = iterate_bind_group(
device,
&bind_group_layout,
@@ -1055,7 +725,6 @@ impl FractalRenderer {
&ref_buffer,
&lights_buffer,
&ref_exp_buffer,
&bla,
);
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
@@ -1264,8 +933,6 @@ impl FractalRenderer {
ref_buffer,
ref_exp_buffer,
ref_capacity: INITIAL_REF_POINTS,
bla,
uploaded_bla_generation: u64::MAX,
lights_buffer,
bind_group,
target_format,
@@ -1281,35 +948,9 @@ impl FractalRenderer {
cache: None,
iterated: None,
colored: None,
ci_stats: CiStats::new(CiHistogram::new(device), device),
}
}
/// The on-screen `ci` range from the latest auto-colour histogram, once
/// its readback has landed (`None` before that, or if nothing escaped).
pub fn take_ci_range(&mut self, device: &wgpu::Device) -> Option<(f32, f32)> {
let CiStatsState::Mapping(done) = &self.ci_stats.state else {
return None;
};
let _ = device.poll(wgpu::PollType::Poll);
if !done.load(std::sync::atomic::Ordering::Acquire) {
return None;
}
let staging = &self.ci_stats.staging;
let range = {
let data = staging.slice(..).get_mapped_range().ok()?;
ci_range(bytemuck::cast_slice(&data))
};
staging.unmap();
self.ci_stats.state = CiStatsState::Idle;
range
}
/// A histogram is on its way back: keep repainting to pick it up.
pub fn ci_stats_pending(&self) -> bool {
!matches!(self.ci_stats.state, CiStatsState::Idle)
}
/// Ensure the cache textures exist at `width`×`height` (plus the AA refine
/// target iff `aa`). Recreates them (and their bind groups) on a change,
/// invalidating any previous render.
@@ -1479,14 +1120,7 @@ impl FractalRenderer {
/// refine → colourise chain, since the raymarcher needs a whole data
/// texture to march over and `fs_color` has no 3D path. Likewise for
/// the distance field ([`wants_envelope`]), which needs the whole image.
/// With `ci_probe`, also what [`ExportRender::ci_range_blocking`] needs
/// (auto colour scale).
pub fn export_handles(
&self,
device: &wgpu::Device,
uniforms: &Uniforms,
ci_probe: bool,
) -> ExportHandles {
pub fn export_handles(&self, device: &wgpu::Device, uniforms: &Uniforms) -> ExportHandles {
let constants = PipelineKey::from_uniforms(uniforms).constants();
let pipeline = fullscreen_pipeline(
device,
@@ -1522,29 +1156,11 @@ impl FractalRenderer {
colorize_bind_group_layout: self.colorize_bind_group_layout.clone(),
lipschitz: wants_envelope(uniforms).then(|| self.lipschitz.clone()),
});
let probe = ci_probe.then(|| {
let iterate = raymarch.as_ref().map_or_else(
|| {
fullscreen_pipeline(
device,
"fractal export ci probe pipeline",
&self.shader,
&self.pipeline_layout,
"fs_data",
DATA_FORMAT,
&constants,
)
},
|rm| rm.iterate.clone(),
);
(iterate, self.ci_stats.histogram.clone())
});
ExportHandles {
pipeline,
bind_group_layout: self.bind_group_layout.clone(),
format: self.target_format,
raymarch,
probe,
}
}
}
@@ -1559,9 +1175,6 @@ pub struct ExportHandles {
format: wgpu::TextureFormat,
/// The two-pass chain, for 3D mode and the distance field only.
raymarch: Option<RaymarchHandles>,
/// 1-spp iterate pipeline (`fs_data`) + `ci` histogram, for the auto
/// colour scale's prepass.
probe: Option<(wgpu::RenderPipeline, CiHistogram)>,
}
/// The interactive two-pass pipelines, for a 3D or distance-field export.
@@ -1611,13 +1224,6 @@ pub struct ExportRender {
/// 3D mode or the distance field: tiles fill a data texture instead of
/// the target.
raymarch: Option<RaymarchExport>,
// Only for headless auto colour (`ci_range_blocking`, `set_uniforms`).
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
uniform_buffer: wgpu::Buffer,
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
uniforms: Uniforms,
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
probe: Option<(wgpu::RenderPipeline, CiHistogram)>,
}
impl ExportRender {
@@ -1631,7 +1237,6 @@ impl ExportRender {
height: u32,
uniforms: Uniforms,
reference: &RefOrbit,
bla: &BlaTable,
lights: &[Light],
) -> Self {
let uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
@@ -1675,8 +1280,6 @@ impl ExportRender {
let (gpu_lights, _) = gpu_lights(lights);
queue.write_buffer(&lights_buffer, 0, bytemuck::cast_slice(&gpu_lights));
let bla_buffers = BlaBuffers::new(device, bla, 0, 0);
let target_format = handles.format;
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("export bind group"),
@@ -1698,14 +1301,6 @@ impl ExportRender {
binding: 3,
resource: ref_exp_buffer.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 4,
resource: bla_buffers.nodes.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 5,
resource: bla_buffers.meta.as_entire_binding(),
},
],
});
@@ -1824,96 +1419,9 @@ impl ExportRender {
tiles,
swap_rb,
raymarch,
uniform_buffer,
uniforms,
probe: handles.probe.clone(),
}
}
/// Replace the uploaded uniforms (e.g. with a refitted colour scale).
#[cfg(not(target_arch = "wasm32"))]
pub fn set_uniforms(&mut self, queue: &wgpu::Queue, uniforms: Uniforms) {
queue.write_buffer(&self.uniform_buffer, 0, bytemuck::bytes_of(&uniforms));
self.uniforms = uniforms;
}
/// Auto colour scale for an export: iterate a downscaled 1-spp prepass,
/// histogram its `ci` and return the range to fit (`None` if nothing
/// escaped). Needs handles built with `ci_probe`. Blocks on the GPU.
#[cfg(not(target_arch = "wasm32"))]
pub fn ci_range_blocking(
&self,
device: &wgpu::Device,
queue: &wgpu::Queue,
) -> Option<(f32, f32)> {
let (iterate, histogram) = self
.probe
.as_ref()
.expect("export handles built without ci_probe");
// The uniforms carry no resolution, so a smaller image of the same view
// just samples it more coarsely; plenty for percentiles.
let s = (CI_PROBE_MAX_DIM as f64 / self.width.max(self.height) as f64).min(1.0);
let width = ((self.width as f64 * s).round() as u32).max(1);
let height = ((self.height as f64 * s).round() as u32).max(1);
let data = device
.create_texture(&wgpu::TextureDescriptor {
label: Some("export ci probe"),
size: wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: DATA_FORMAT,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
})
.create_view(&wgpu::TextureViewDescriptor::default());
let (hist, staging) = CiHistogram::buffers(device);
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("export ci probe"),
});
let samples = if self.uniforms.rendering_mode != 0 {
3
} else {
1
};
banded_data_pass(
device,
queue,
&mut encoder,
"export ci probe pass",
&data,
iterate,
&[&self.bind_group],
[width, height],
band_count(width, height, self.uniforms.max_iter, samples),
);
histogram.record(device, &mut encoder, &data, width, height, &hist, &staging);
queue.submit(std::iter::once(encoder.finish()));
let (tx, rx) = std::sync::mpsc::channel();
staging
.slice(..)
.map_async(wgpu::MapMode::Read, move |res| {
let _ = tx.send(res);
});
let _ = device.poll(wgpu::PollType::Wait {
submission_index: None,
timeout: None,
});
rx.recv().ok()?.ok()?;
let range = ci_range(bytemuck::cast_slice(
&staging.slice(..).get_mapped_range().ok()?,
));
staging.unmap();
range
}
/// Pixel row range `[y0, y1)` covered by tile `t`.
fn tile_rows(&self, t: u32) -> (u32, u32) {
let band = self.height.div_ceil(self.tiles);
@@ -2232,7 +1740,6 @@ fn iterate_bind_group(
ref_buffer: &wgpu::Buffer,
lights_buffer: &wgpu::Buffer,
ref_exp_buffer: &wgpu::Buffer,
bla: &BlaBuffers,
) -> wgpu::BindGroup {
device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("fractal bind group"),
@@ -2254,14 +1761,6 @@ fn iterate_bind_group(
binding: 3,
resource: ref_exp_buffer.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 4,
resource: bla.nodes.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 5,
resource: bla.meta.as_entire_binding(),
},
],
})
}
@@ -2416,15 +1915,8 @@ pub struct FractalCallback {
pub lights: [GpuLight; MAX_LIGHT_COUNT],
pub reference: Arc<RefOrbit>,
pub generation: u64,
/// BLA table for `reference` and this view's `dc` range, and its
/// generation (bumped on every rebuild).
pub bla: Arc<BlaTable>,
pub bla_generation: u64,
/// Widget size in physical pixels — the cache texture resolution.
pub size_px: [u32; 2],
/// Histogram each new iteration for the auto colour scale
/// ([`FractalRenderer::take_ci_range`]).
pub auto_color: bool,
}
#[cfg(feature = "gui")]
@@ -2462,7 +1954,6 @@ impl egui_wgpu::CallbackTrait for FractalCallback {
// camera moves skip the perturbation entirely.
let iter_dirty = renderer.iterated.as_ref().is_none_or(|r| {
r.generation != self.generation
|| r.bla_generation != self.bla_generation
|| r.width != width
|| r.height != height
|| geom_differs(&r.uniforms, &self.uniforms)
@@ -2475,28 +1966,6 @@ impl egui_wgpu::CallbackTrait for FractalCallback {
|| color_differs(&c.uniforms, &self.uniforms)
});
// Last frame's histogram copy has been submitted by now: map it.
renderer.ci_stats.start_map();
if iter_dirty {
renderer.ci_stats.stale = true;
}
// Histogram the data texture when auto colour needs one: after this
// frame's iteration (recorded below), or now if the texture is
// already current (auto just turned on, or a readback was in flight
// when it last changed).
let wants_stats = self.auto_color
&& renderer.ci_stats.stale
&& matches!(renderer.ci_stats.state, CiStatsState::Idle);
if wants_stats
&& !iter_dirty
&& let Some(cache) = &renderer.cache
{
let src = cache.aa.as_ref().map_or(&cache.data_view, |(v, _)| v);
renderer
.ci_stats
.record(device, egui_encoder, src, cache.width, cache.height);
}
if !color_dirty {
return Vec::new(); // cache still valid; paint() just blits it
}
@@ -2519,10 +1988,6 @@ impl egui_wgpu::CallbackTrait for FractalCallback {
);
renderer.uploaded_generation = self.generation;
}
if iter_dirty && renderer.uploaded_bla_generation != self.bla_generation {
renderer.upload_bla(device, queue, &self.bla);
renderer.uploaded_bla_generation = self.bla_generation;
}
// Every pass reads the uniform buffer; refresh it once.
queue.write_buffer(
@@ -2592,12 +2057,6 @@ impl egui_wgpu::CallbackTrait for FractalCallback {
band_count(width, height, max_iter, aa * aa),
);
}
if wants_stats {
let src = cache.aa.as_ref().map_or(&cache.data_view, |(v, _)| v);
renderer
.ci_stats
.record(device, egui_encoder, src, width, height);
}
}
// Shadow / 3D Complex Multibrot: rebuild the DE as a distance field.
@@ -2631,7 +2090,6 @@ impl egui_wgpu::CallbackTrait for FractalCallback {
renderer.iterated = Some(IterState {
uniforms: self.uniforms,
generation: self.generation,
bla_generation: self.bla_generation,
width,
height,
});
+9 -95
View File
@@ -14,13 +14,12 @@ use std::sync::{Mutex, mpsc};
use crate::app::{FractalApp, RefJob, parse_complex_pair, unix_timestamp};
use crate::cli::Cli;
use crate::fractal::bla;
use crate::fractal::{
ExportRender, FractalKind, FractalRenderer, PipelineKey, ShareState, encode_png,
export_to_png_blocking, render_readback_blocking, unpad_rgba,
};
use crate::view::{
Scale, ViewState, big_from_decimal_str, interpolate_f64, interpolate_view, parse_view_spec,
ViewState, big_from_decimal_str, interpolate_f64, interpolate_view, parse_view_spec,
precision_for,
};
@@ -79,10 +78,9 @@ pub fn run(cli: Cli) -> Result<(), String> {
let format = wgpu::TextureFormat::Bgra8Unorm;
let renderer = FractalRenderer::new(&device, format);
let uniforms = app.make_uniforms(width as f64 / height as f64, height as f64);
let auto_color = app.auto_color_active();
let handles = renderer.export_handles(&device, &uniforms, auto_color);
let handles = renderer.export_handles(&device, &uniforms);
let mut er = ExportRender::new(
let er = ExportRender::new(
&device,
&queue,
&handles,
@@ -90,15 +88,8 @@ pub fn run(cli: Cli) -> Result<(), String> {
height,
uniforms,
app.reference_points(),
&bla::for_uniforms(app.reference_points(), &uniforms, app.use_bla()),
app.lights(),
);
if auto_color {
match fit_auto_color(&mut app, &mut er, &device, &queue) {
Some((lo, hi)) => eprintln!("auto color scale: ci {lo:.1}–{hi:.1}"),
None => eprintln!("auto color scale: nothing escaped, keeping the default"),
}
}
eprintln!("rendering {width}×{height}…");
let png = export_to_png_blocking(&device, &queue, &er, |phase, fraction| {
@@ -135,9 +126,6 @@ struct AnimTargets {
/// 3D camera, degrees.
to_yaw: Option<f32>,
to_pitch: Option<f32>,
to_color_scale: Option<f32>,
/// Zoom depth where `to_color_scale` is reached (else: at the end).
to_color_scale_at: Option<Scale>,
frames: Option<u32>,
fps: f64,
duration: Option<f64>,
@@ -164,29 +152,6 @@ impl AnimTargets {
}
_ => return Err("--shard and --shards must be given together".into()),
};
if let Some(s) = cli.to_color_scale {
if !(s.is_finite() && s > 0.0) {
return Err(format!("invalid --to-color-scale: {s}"));
}
if cli.auto_color_scale {
return Err(
"--to-color-scale can't be combined with --auto-color-scale \
(the auto fit sets the scale on every frame)"
.into(),
);
}
}
let to_color_scale_at = cli
.to_color_scale_at
.as_deref()
.map(|s| {
s.parse::<Scale>()
.map_err(|_| format!("invalid --to-color-scale-at: {s}"))
})
.transpose()?;
if to_color_scale_at.is_some() && cli.to_color_scale.is_none() {
return Err("--to-color-scale-at needs --to-color-scale".into());
}
Ok(Self {
to_view: cli.to_view.clone(),
to_share: cli.to_share.clone(),
@@ -199,8 +164,6 @@ impl AnimTargets {
to_kind: cli.to_kind.map(Into::into),
to_yaw: cli.to_yaw,
to_pitch: cli.to_pitch,
to_color_scale: cli.to_color_scale,
to_color_scale_at,
frames: cli.frames,
fps: cli.fps,
duration: cli.duration,
@@ -222,17 +185,15 @@ impl AnimTargets {
|| self.to_kind.is_some()
|| self.to_yaw.is_some()
|| self.to_pitch.is_some()
|| self.to_color_scale.is_some()
}
}
/// Render a sequence of frames interpolating from the app's current (start)
/// state to `targets`, for feeding into ffmpeg: the camera, iteration count,
/// per-kind constants (c, p, λ, complex power) and, through a kind morph,
/// the iteration formula, the 3D camera angles and the colour scale.
/// Everything else (palette, offset, ...) stays fixed at whatever
/// `apply_cli` set up for the start. With `--export-path -`, frames are
/// streamed in order to stdout as raw RGBA8 (for ffmpeg's `rawvideo`
/// the iteration formula, and the 3D camera angles. Everything else (colors, ...) stays fixed at
/// whatever `apply_cli` set up for the start. With `--export-path -`, frames
/// are streamed in order to stdout as raw RGBA8 (for ffmpeg's `rawvideo`
/// demuxer) instead of being written as PNGs.
fn run_animation(
mut app: FractalApp,
@@ -293,15 +254,6 @@ fn run_animation(
let (yaw0, pitch0) = app.camera_angles();
let yaw1 = targets.to_yaw.map_or(yaw0, f32::to_radians);
let pitch1 = targets.to_pitch.map_or(pitch0, f32::to_radians);
let (scale0, ci_lo0) = app.color_fit();
let scale1 = targets.to_color_scale.map(|s| s.clamp(1e-4, 1.0) as f64);
// With `--to-color-scale-at`, the scale follows the zoom depth (log2 of
// the half-height) from the start view's to that one, instead of `t`.
let depth0 = from.half_height.log2();
let depth_at = targets.to_color_scale_at.map(Scale::log2);
if depth_at == Some(depth0) {
return Err("--to-color-scale-at is the start view's depth".into());
}
let stream = export_path.as_deref() == Some(STDOUT_PATH);
let out_dir = export_path.unwrap_or_else(|| format!("frames-{}", unix_timestamp()));
@@ -329,9 +281,7 @@ fn run_animation(
interpolate_f64(from_iterations as f64, to as f64, t).round() as u32,
);
}
let view = interpolate_view(&from, &to, t);
let depth = view.half_height.log2();
app.set_view(view);
app.set_view(interpolate_view(&from, &to, t));
app.set_constants(std::array::from_fn(|k| {
(
interpolate_f64(from_consts[k].0, to_consts[k].0, t),
@@ -343,13 +293,6 @@ fn run_animation(
interpolate_f64(yaw0 as f64, yaw1 as f64, t) as f32,
interpolate_f64(pitch0 as f64, pitch1 as f64, t) as f32,
);
// Geometrically: the useful range spans decades.
if let Some(scale1) = scale1 {
// The zoom is already eased; don't ease its depth again.
let u = depth_at.map_or(t, |at| ((depth - depth0) / (at - depth0)).clamp(0.0, 1.0));
let scale = interpolate_f64((scale0 as f64).ln(), scale1.ln(), u).exp();
app.set_color_fit((scale as f32, ci_lo0));
}
};
// Snapshot every frame's reference-orbit job up front (cheap: just the
@@ -368,10 +311,6 @@ fn run_animation(
let format = wgpu::TextureFormat::Bgra8Unorm;
let renderer = FractalRenderer::new(&device, format);
let aspect = width as f64 / height as f64;
// Refit per frame from the same start, so each frame's colours depend only
// on that frame (frames render out of order, and shards must join up).
let auto_color = app.auto_color_active();
let color_fit0 = app.color_fit();
// Three-stage pipeline, connected by bounded channels (which also cap
// memory): `threads` workers compute reference orbits (CPU, the expensive
@@ -506,8 +445,8 @@ fn run_animation(
let uniforms = app.make_uniforms(aspect, height as f64);
let handles = pipelines
.entry(PipelineKey::from_uniforms(&uniforms))
.or_insert_with(|| renderer.export_handles(&device, &uniforms, auto_color));
let mut er = ExportRender::new(
.or_insert_with(|| renderer.export_handles(&device, &uniforms));
let er = ExportRender::new(
&device,
&queue,
handles,
@@ -515,15 +454,8 @@ fn run_animation(
height,
uniforms,
app.reference_points(),
// Built here rather than in the orbit pool: it needs this
// frame's uniforms, and costs ~1 ms per 100k points.
&bla::for_uniforms(app.reference_points(), &uniforms, app.use_bla()),
app.lights(),
);
if auto_color {
app.set_color_fit(color_fit0);
fit_auto_color(&mut app, &mut er, &device, &queue);
}
let padded = render_readback_blocking(&device, &queue, &er);
if png_tx.send((i, padded, er.padded_bpr, er.swap_rb)).is_err() {
break;
@@ -564,24 +496,6 @@ fn run_animation(
Ok(())
}
/// Auto colour scale: fit `app`'s colour scale to `er`'s image (a prepass)
/// and upload the result. Returns the fitted `ci` range, or `None` (colours
/// untouched) if nothing escaped.
fn fit_auto_color(
app: &mut FractalApp,
er: &mut ExportRender,
device: &wgpu::Device,
queue: &wgpu::Queue,
) -> Option<(f32, f32)> {
let range = er.ci_range_blocking(device, queue)?;
app.apply_ci_range(range);
er.set_uniforms(
queue,
app.make_uniforms(er.width as f64 / er.height as f64, er.height as f64),
);
Some(range)
}
/// Parse `--to-view`/`--to-share` (at most one is used) into the end view
/// of an animation, or `None` if neither is set (the camera stays put). Only position/zoom/iterations are pulled from a
/// share fragment — the rest of its state (kind, colors, ...) is ignored, so
-27
View File
@@ -1,27 +0,0 @@
// Histogram of the escaped pixels' smoothed iteration count `ci`, for the
// auto colour scale (`CiStats` in renderer.rs). Reads the same data texture
// the colourise pass reads (R = ci, B = interior fraction). Bins are uniform
// in log2(1 + ci) over [0, CI_LOG2_MAX), so one fixed layout covers every
// zoom depth (`MAX_ITERATIONS` = 2^24). Must match `CI_BINS`/`CI_LOG2_MAX`
// in renderer.rs.
const CI_BINS: u32 = 1024u;
const CI_LOG2_MAX: f32 = 25.0;
@group(0) @binding(0) var data_tex: texture_2d<f32>;
@group(0) @binding(1) var<storage, read_write> hist: array<atomic<u32>, 1024>;
@compute @workgroup_size(16, 16)
fn cs_main(@builtin(global_invocation_id) id: vec3<u32>) {
let size = textureDimensions(data_tex);
if id.x >= size.x || id.y >= size.y {
return;
}
let d = textureLoad(data_tex, vec2<i32>(id.xy), 0);
if d.b >= 1.0 {
return; // fully interior: no escape time
}
let x = log2(1.0 + max(d.r, 0.0)) * (f32(CI_BINS) / CI_LOG2_MAX);
let bin = min(u32(max(x, 0.0)), CI_BINS - 1u);
atomicAdd(&hist[bin], 1u);
}
+3 -158
View File
@@ -30,23 +30,6 @@
// f32's range, which only deep references contain; only `DEEP` pipelines read
// it (see `ref_at`).
@group(0) @binding(3) var<storage, read> ref_exp: array<i32>;
// Bivariate linear approximation table (`fractal::bla`): node i of level l
// maps the delta at reference step 1 + i·2^l to the one 2^l steps later as
// e' = M·e + N·dc, valid while log2|e| < r_log2. M = m·2^m_exp and
// N = n·2^n_exp are real 2x2 matrices, row-major (the Jacobian of the map,
// so the abs/conjugate kinds are covered too). `bla_meta` is
// [min_level, level_count, off_0, ..., off_{level_count}]; only `BLA`
// pipelines read either.
struct Bla {
m: vec4<f32>,
n: vec4<f32>,
m_exp: i32,
n_exp: i32,
r_log2: f32,
_pad: u32,
};
@group(0) @binding(4) var<storage, read> bla_nodes: array<Bla>;
@group(0) @binding(5) var<storage, read> bla_meta: array<u32>;
// Pipeline-overridable specialization constants, set per pipeline from the
// uniforms' `kind` / `is_julia` / `de_coloring` (see `PipelineKey` in
@@ -66,9 +49,6 @@ override MORPH: bool = false;
// and `u.span` / `u.dc_offset` are all in units of 2^scale_exp, and each pixel
// starts in the rescaled deep phase (see `iterate_sample`).
override DEEP: bool = false;
// Jump over runs of reference steps with the BLA table (every kind but
// Phoenix, no morph; see `bla_lookup`).
override BLA: bool = false;
struct VsOut {
@builtin(position) pos: vec4<f32>,
@@ -598,54 +578,6 @@ const DEEP_RENORM_LOG2: i32 = 16;
// binades above the delta's scale (|w| < 2^DEEP_RENORM_LOG2).
const DEEP_NEAR_LOG2: i32 = 24;
// Row-major 2x2 matrix times vector (a BLA node's M or N).
fn mat2v(m: vec4<f32>, v: vec2<f32>) -> vec2<f32> {
return vec2<f32>(dot(m.xy, v), dot(m.zw, v));
}
// log2|v|, from above (|v| <= sqrt(2)·max component). Not via dot(v, v):
// a delta ~2^-100 (a pixel offset at 1e-30 zoom) squares below f32's range,
// and log2(0) = -inf passed every radius test, jumping pixels far too early.
fn log2_mag(v: vec2<f32>) -> f32 {
return log2(max(abs(v.x), abs(v.y))) + 0.5;
}
// Longest BLA jump available at reference index `m` for a delta of
// log2 magnitude `e_log2`, of at most `budget` steps: (node index, steps),
// steps = 0 when there's none. Nodes start at 1 + i·2^l, so level l needs
// m - 1 aligned to 2^l. A longer run's radius is never larger than its first
// half's, so the search goes up from the shortest and stops at the first
// invalid level (usually right away: one load per failed attempt).
fn bla_lookup(m: u32, e_log2: f32, budget: u32) -> vec2<u32> {
var best = vec2<u32>(0u, 0u);
let levels = bla_meta[1];
if levels == 0u || m == 0u {
return best;
}
let lmin = bla_meta[0];
let j = m - 1u;
let tz = countTrailingZeros(j); // 32 when j == 0
if tz < lmin {
return best;
}
let top = min(tz - lmin, levels - 1u);
for (var k: u32 = 0u; k <= top; k = k + 1u) {
let l = lmin + k;
let steps = 1u << l;
let base = bla_meta[2u + k];
let local = j >> l;
if steps > budget || local >= bla_meta[3u + k] - base {
break;
}
let idx = base + local;
if !(e_log2 < bla_nodes[idx].r_log2) {
break;
}
best = vec2<u32>(idx, steps);
}
return best;
}
// Weight of the Phoenix kind's p*z_{n-1} term in the current map: 1 for plain
// Phoenix, its morph share while switching to/from Phoenix, else 0.
fn phoenix_weight() -> f32 {
@@ -860,47 +792,6 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
break;
}
// BLA: jump the whole run the table covers, straight to its
// output scale (usually many binades up, towards the f32 hand-off).
var jumped = false;
if BLA {
let e_log2 = f32(sx) + log2_mag(w);
let hit = bla_lookup(m, e_log2, min(max_iter - n, ref_len - 1u - m));
if hit.y != 0u {
let nd = bla_nodes[hit.x];
if DE {
var accv = fe_make(mat2v(nd.m, v), nd.m_exp + sv);
if !IS_JULIA {
accv = fe_add(accv, fe_make(mat2v(nd.n, vec2<f32>(px, 0.0)), nd.n_exp + scale_e));
}
v = accv.m;
if accv.m.x != 0.0 || accv.m.y != 0.0 {
sv = accv.e;
if !IS_JULIA {
pd = ldexp_sat(px, scale_e - sv);
}
}
}
var acc = fe_make(mat2v(nd.m, w), nd.m_exp + sx);
if !IS_JULIA {
acc = fe_add(acc, fe_make(mat2v(nd.n, offset), nd.n_exp + scale_e));
}
w = acc.m;
if acc.m.x != 0.0 || acc.m.y != 0.0 {
sx = acc.e;
sc = ldexp_sat(1.0, sx);
if !IS_JULIA {
d = ldexp2_sat(offset, scale_e - sx);
}
}
w_old = w;
m = m + hit.y;
n = n + hit.y;
jumped = true;
}
}
if !jumped {
if DE {
let fp = deep_fprime(xf, w, sx, yt);
if fp.e == 0 {
@@ -982,7 +873,6 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
}
m = m + 1u;
n = n + 1u;
}
if m >= ref_len {
escaped = true; // see the f32 loop's reference-exhausted case
@@ -1104,49 +994,6 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
// which only re-expresses the same value). Only when DE is enabled.
// Phoenix's two-term map adds p·dz_{n-1} and carries the previous dz.
// f'(z) of this step, shared by DE and the periodicity multiplier.
// BLA jump (see the deep phase). dc and px are taken unscaled from
// `offset`/`px`: at depth `step_add`/`px_t` have flushed to 0, but
// N·dc hasn't. The skipped steps' |f'|^2 product is |det M| (the
// steps are conformal, or folds of conformal maps). No skipped
// iterate can be the window's closest to the critical point: a run's
// radius is below ε·|X| for every X in it.
//
// With DE, dzs goes through M, the map's true Jacobian, where the
// plain loop multiplies by `fprime` (|2Z| for the abs kinds): same
// magnitude, since the folds are isometries.
let e_old = e;
let z_old = z;
var jumped = false;
if BLA && m != 0u {
let hit = bla_lookup(m, log2_mag(e), min(max_iter - n, ref_len - 1u - m));
if hit.y != 0u {
let nd = bla_nodes[hit.x];
let se = select(0, u.scale_exp, DEEP);
if periodic {
let det = abs(nd.m.x * nd.m.w - nd.m.y * nd.m.z);
let a2 = ldexp_sat(det, 2 * nd.m_exp);
mult2 = mult2 * a2;
mult2_cand = mult2_cand * a2;
}
if DE {
var dn = ldexp2_sat(mat2v(nd.m, dzs), nd.m_exp);
if !IS_JULIA {
dn = dn + ldexp2_sat(mat2v(nd.n, vec2<f32>(px, 0.0)), nd.n_exp + se);
}
dzs = dn;
}
var en = ldexp2_sat(mat2v(nd.m, e), nd.m_exp);
if !IS_JULIA {
en = en + ldexp2_sat(mat2v(nd.n, offset), nd.n_exp + se);
}
e = en;
m = m + hit.y;
n = n + hit.y;
jumped = true;
}
}
if !jumped {
var fp = vec2<f32>(0.0, 0.0);
if DE || periodic {
fp = fprime(z);
@@ -1170,6 +1017,8 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
// Advance the delta by this fractal's formula (+ dc for the set plane).
// Phoenix additionally adds p·e_{n-1} and carries the previous delta.
let e_old = e;
let z_old = z;
e = advance_delta(xm, e) + step_add;
if phoenix_w > 0.0 {
e = e + phoenix_w * cmul(u.phoenix_p, e_prev);
@@ -1177,7 +1026,6 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
}
m = m + 1u;
n = n + 1u;
}
// Keep the reference index valid and the delta small.
if m >= ref_len {
@@ -1221,7 +1069,7 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
z_cand = z;
mult2_cand = 1.0;
}
if n >= check_at {
if n == check_at {
if !period_hit {
period_streak = 0u;
}
@@ -1229,13 +1077,10 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
z_saved = z_cand;
mult2 = mult2_cand;
cand_d2 = 3.0e38;
// (A BLA jump can pass several window ends at once.)
while check_at <= n {
check_at = check_at * 2u;
}
}
}
}
if !escaped {
return Sample(0.0, 1.0, false); // interior of the set
+1 -18
View File
@@ -77,7 +77,7 @@ fn mandelbrot_shader_is_valid() {
}
/// Every specialization renderer.rs can build (`PipelineKey`: kind × Julia ×
/// DE × morph × deep × BLA), for every fragment entry point.
/// DE × morph × deep), for every fragment entry point.
#[test]
fn mandelbrot_shader_specializations_compile() {
let (module, info) = validate("mandelbrot.wgsl", MANDELBROT_SRC);
@@ -86,20 +86,12 @@ fn mandelbrot_shader_specializations_compile() {
for de in [0.0, 1.0] {
for morph in [0.0, 1.0] {
for deep in [0.0, 1.0] {
// BLA: every kind but Phoenix (7), no morph (`bla::applies`).
let blas: &[f64] = if kind != 7 && morph == 0.0 {
&[0.0, 1.0]
} else {
&[0.0]
};
for &bla in blas {
let constants = [
("KIND", kind as f64),
("IS_JULIA", julia),
("DE", de),
("MORPH", morph),
("DEEP", deep),
("BLA", bla),
];
for entry in ["fs_data", "fs_refine", "fs_color"] {
specialize(
@@ -117,7 +109,6 @@ fn mandelbrot_shader_specializations_compile() {
}
}
}
}
#[test]
fn colorize_shader_is_valid() {
@@ -178,11 +169,3 @@ fn buddhabrot_shader_specializations_compile() {
);
}
}
#[test]
fn ci_stats_shader_is_valid() {
validate(
"ci_stats.wgsl",
include_str!("../src/shaders/ci_stats.wgsl"),
);
}
-1
View File
@@ -1 +0,0 @@
out/
+2 -83
View File
@@ -1,7 +1,7 @@
# Deep-zoom locations
Beautiful deep Mandelbrot locations, all computed with `find_deep.py` or `search.py` and
checked with a `--headless` render. Every one is an exact minibrot nucleus (Newton's method at
Beautiful deep Mandelbrot locations, all computed with `find_deep.py` and checked with a
`--headless` render. Every one is an exact minibrot nucleus (Newton's method at
`2·depth + 60` digits), not a coordinate copied from somewhere, so the digits are right all
the way down.
@@ -153,89 +153,8 @@ A single twelve-armed star, very symmetric. The antenna minibrots have short per
--view=-0.1011037579721041867570689093600472352495811991784283939876186880159732846332867701937330961715882746718394428627914481009391257007785408536971203165750666758077852384490279260184029373211737264310068845597273991782305778295187471341711226626762421910644338164121042775094463557363347706110614218633830535086184,0.9562940079523540929071943411882448455804659198042339938863014041593801060467576090157496959748683171680339080646917869452781885502668216669916185990922330667568398963038228431738928191227884090004548615469303071899797403388188723954061899156655653387543351937028936674153437083087070219108726088551230849901498,2.5e-300
```
## Morphing zooms (no endless spiral)
A minibrot from `find_deep.py` sits at distance r from a Misiurewicz point and has size r², so
the first half of its zoom (in log scale) is the same spiral turning over and over. These are
built by `search.py` instead: a chain of minibrots, each picked inside the previous one's
embedded Julia set, off its centre. Every time the zoom passes one, the picture folds (z → z²
locally), so each stage shows the previous shape doubled instead of a repeat. The Misiurewicz
point is only used for the first few decades.
Each location has two end points. Zoom to the **last embedded Julia set** to keep changing
shape all the way down. The **minibrot** is about a third deeper, but that last stretch is
rings closing in on it, which looks the same for every minibrot.
The colour contrast washes out at these depths in headless renders (the default colour scale is
tuned for shallower views). Try `--palette` or the interactive app.
### Seahorse valley, 9 stages, minibrot at 1.95e-367 (period 13701)
Seed 2, the top scorer. Each stage doubles the pattern. Around 1e-150 it is an eight-armed star of seahorse-tail spirals, and by 1e-250 each arm has become a spiral arm of its own. The last Julia set is pale cyan S-spirals interlocked with small snowflakes.
```sh
# last embedded Julia set
--view=-0.7753452295156405956088382319063405041200389687755508065690758933972356154674766194756672970107824576987716506820473626377289966850477815993212514936989107755288403190421564405962299577965531281406098430140843315809148941148835642905077493477538626689716455579196401297663769682360083746728010029499252318437245060419975563373728583873423397522687593946164217423611237456686155,0.1364239581870775619072911253207719792041200901039288844939565392217863173195981034417860802937281884987101484785589683756503781834313063872897864695678156825572773750286514435594400277526505362588686964101890046172400600115486054295219300235694108056070084590715209580088595029634293379003635002553779969859087272620892813545216852862560609109477666596320676409189943462906183,1.7e-275
# minibrot
--view=-0.7753452295156405956088382319063405041200389687755508065690758933972356154674766194756672970107824576987716506820473626377289966850477815993212514936989107755288403190421564405962299577965531281406098430140843315809148941148835642905077493477538626689716455579196401297663769682360083746728010029499252318437245060419975563373728583873423397522687593946164217423611237456686155,0.1364239581870775619072911253207719792041200901039288844939565392217863173195981034417860802937281884987101484785589683756503781834313063872897864695678156825572773750286514435594400277526505362588686964101890046172400600115486054295219300235694108056070084590715209580088595029634293379003635002553779969859087272620892813545216852862560609109477666596320676409189943462906183,5.8e-367
```
### Seahorse valley, 9 stages, minibrot at 2.23e-332 (period 20771)
Seed 24. Ends on a deep-blue field with a ladder of two spiky rosettes up the middle and seahorse spirals hanging off both sides.
```sh
# last embedded Julia set
--view=-0.77581899776364093541231633878667591854940234460393623634560469682524602327917430132831992200028242018281986527945300983871854511115659304292671652789338745276924830204381603012151271794534404802657864351394053047466207495399034821695775654392586465718993627074907162608014351492003087712186151836540562594796512607687563345530430631968989769,0.13639016044733587310899816976451186522511735544614557616370747772490427471765768547942874390030670422507300887964841711805169647706659494431705444259263501596739281803768172126446068576798485059599688488281382970932839834055072153017771954773333653697740526075860787508424313537171575674813478338329140463605230166008829195653885760869703998,4.2e-249
# minibrot
--view=-0.77581899776364093541231633878667591854940234460393623634560469682524602327917430132831992200028242018281986527945300983871854511115659304292671652789338745276924830204381603012151271794534404802657864351394053047466207495399034821695775654392586465718993627074907162608014351492003087712186151836540562594796512607687563345530430631968989769,0.13639016044733587310899816976451186522511735544614557616370747772490427471765768547942874390030670422507300887964841711805169647706659494431705444259263501596739281803768172126446068576798485059599688488281382970932839834055072153017771954773333653697740526075860787508424313537171575674813478338329140463605230166008829195653885760869703998,6.7e-332
```
### Elephant valley, 10 stages, minibrot at 9.9e-376 (period 26330)
Seed 10. The busiest one. Around 1e-100 it is dense blue lace over dark red; around 1e-200 there are big pinwheel fans with curled trunk tips, the prettiest frame of the set. Toward the end it becomes a dark field of small starbursts.
```sh
# last embedded Julia set
--view=0.2919725609273281486648237582115998883600209040251439086749905948711563568174299074829283558691127379979884016672342155749823780016183197461740530259273568326709292748874665616014636798873898973811666320162356520760904526444122077135661892284506788063980999152039879384033195224044981383998272534314607724906042434605344003420578380980595202662299201627356955139354311024040150045335132,0.01609653145423751028823367722046071738201813858290104726012040624213292560317148577164650820980015376333402589301809392204612823423640558757865322964450320793537771158249026499009376062869974452053829363185721040089473699420550959606623588474079103727001609122830051578927796106929658205975868875493047686224923681237537000490733609889219929444859368575967702125530262379423175371468097,5.5e-282
# minibrot
--view=0.2919725609273281486648237582115998883600209040251439086749905948711563568174299074829283558691127379979884016672342155749823780016183197461740530259273568326709292748874665616014636798873898973811666320162356520760904526444122077135661892284506788063980999152039879384033195224044981383998272534314607724906042434605344003420578380980595202662299201627356955139354311024040150045335132,0.01609653145423751028823367722046071738201813858290104726012040624213292560317148577164650820980015376333402589301809392204612823423640558757865322964450320793537771158249026499009376062869974452053829363185721040089473699420550959606623588474079103727001609122830051578927796106929658205975868875493047686224923681237537000490733609889219929444859368575967702125530262379423175371468097,3.0e-375
```
### Elephant valley, 10 stages, minibrot at 2.58e-393 (period 31938)
Seed 6. Ends on a cream field covered in tiny orange starbursts, like frost on a window.
```sh
# last embedded Julia set
--view=0.291920245587041963891588502847402316252926795406554403678013521015333816452464592295071998432671814509111459555663776008730796899291641422047823143066182408211544669386206661368710007384581820315259562196579747306521924025557974076213683940172635312577637426632710121469687554303515614245960216389023574299414942997525087881669471153995469440602254536765333823609728596136514603489157828188139494926264,0.0160764363740117355209701377378165904185186672655973900712949768468968706838603774970184637138036946417491390244864230673560872881279816470698447551999091888703048347169598010650942657073167719830723550405395270691529274225324525523911917416786211773060643555546204329361883408672335674317068855354237389458235628771660652358504910575175071131870389768222336460879256178272208513228731902472063018497750,1.7e-295
# minibrot
--view=0.291920245587041963891588502847402316252926795406554403678013521015333816452464592295071998432671814509111459555663776008730796899291641422047823143066182408211544669386206661368710007384581820315259562196579747306521924025557974076213683940172635312577637426632710121469687554303515614245960216389023574299414942997525087881669471153995469440602254536765333823609728596136514603489157828188139494926264,0.0160764363740117355209701377378165904185186672655973900712949768468968706838603774970184637138036946417491390244864230673560872881279816470698447551999091888703048347169598010650942657073167719830723550405395270691529274225324525523911917416786211773060643555546204329361883408672335674317068855354237389458235628771660652358504910575175071131870389768222336460879256178272208513228731902472063018497750,7.7e-393
```
## Finding more
Zooms that keep changing shape (Julia morphing, see above), ranked by rendering them:
```sh
./search.py seahorse # 24 chains down to ~1e-300..1e-450, prints the best 5
./search.py elephant --depth 200 --candidates 40 --seed 100
./morph.py seahorse --seed 7 --all-stages # one chain, with every stage's views
./score.py --view=RE,IM,HALF_HEIGHT --debug # score any zoom (e.g. the entries above)
```
`search.py` builds chains on every core (a few seconds each), then renders 32 thumbnails
along each zoom on the GPU (10-60 s each, most of the run time). The score is detail
(gradient strength) times one minus the fraction of frames that repeat the ones before them.
That fraction comes from a rotation- and scale-invariant (Fourier-Mellin) frame descriptor,
and it's about 0.6 for the spiral zooms above versus ~0 for morphing chains. Contact sheets
(8 frames along the zoom) go to `out/`. The thumbnails have no AA, so deep frames look
noisier there than they really are: render the view before judging. Needs mpmath, numpy,
Pillow and `cargo build --release`. Antenna chains work too, but they're mostly empty
background with thin dendrites, so they score low.
Minibrots next to a Misiurewicz point (the spiral locations above):
```sh
./find_deep.py --list # known regions
./find_deep.py seahorse 250 # minibrot of size ~1e-500 near the seahorse point
+1 -3
View File
@@ -11,9 +11,7 @@ minibrot of size ~r^2, found by:
3. the standard size estimate (Heiland-Allen) for its scale.
Zooming at the nucleus shows spirals, then an embedded Julia set (around
size^0.75), then the minibrot (half-height ~3x size). The spirals take
the first half of the zoom: for zooms that keep changing shape, use
morph.py / search.py instead.
size^0.75), then the minibrot (half-height ~3x size).
Usage:
find_deep.py REGION DEPTH [OFFSET_RE,OFFSET_IM]
-200
View File
@@ -1,200 +0,0 @@
#!/usr/bin/env python3
"""Chain minibrots by Julia morphing, so a deep zoom keeps changing shape.
find_deep.py puts a minibrot of size r^2 at distance r from a Misiurewicz
point, so the first half of the zoom (in log scale) is the same spiral over
and over. Here the Misiurewicz point is only used shallowly (stage 0), and
each later minibrot is picked inside the previous one's embedded Julia set,
off its centre. Zooming past a minibrot's neighbourhood folds the picture
(locally z -> z^2), so every stage shows the previous shape doubled instead
of a repeat.
Usage:
morph.py REGION [--stages N] [--depth D] [--d0 D0] [--seed S]
REGION is a name from find_deep.REGIONS or "re,im,k,p". Prints each stage's
period, size and the views to look at. search.py tries many seeds and ranks
the resulting zooms by rendering them.
Needs mpmath.
"""
import argparse
import math
import random
import sys
from dataclasses import dataclass
from mpmath import exp, log10, mp, mpc, mpf, sqrt
from find_deep import REGIONS, misiurewicz, nucleus, period_in_ball, size
# The shader treats an exhausted reference as escaped, and the reference is
# requested with 1.5x headroom (app.rs), so periods past this can't render.
MAX_ITERATIONS = 1 << 24
@dataclass
class Stage:
nucleus: mpc
period: int
size: mpf
reach: mpf # distance from the previous stage's centre (stage 0: the disk radius)
rho: float = 0.0 # where the target was picked, in units of the previous julia scale
theta: float = 0.0
@property
def julia(self):
"""Half-height of the embedded Julia set: geometric midpoint of reach and size."""
return sqrt(self.size * self.reach)
@property
def depth(self):
return float(-log10(self.size))
def set_precision(depth):
mp.dps = int(2 * depth) + 60
def anchor_point(region):
if region in REGIONS:
(re, im), k, p = REGIONS[region]
else:
re, im, k, p = region.split(",")
k, p = int(k), int(p)
return mpc(re, im), k, p
def find_minibrot(center, radius, min_period):
"""Nucleus of the lowest-period minibrot whose atom covers the disk, or None.
Rejects periods <= min_period (an ancestor, not something new next to
the target) and Newton landing far from the disk (another nucleus of the
same period).
"""
p = period_in_ball(center, radius)
if p is None or p <= min_period:
return None
n = nucleus(center, p)
if abs(n - center) > 4 * radius:
return None
s = size(n, p)
if not s > 0:
return None
return n, p, s
def stage0(region, d0, rng):
"""Minibrot near the Misiurewicz point at distance 10^-d0: a short spiral."""
c, k, p = anchor_point(region)
set_precision(2 * d0)
m = misiurewicz(c, k, p)
r = mpf(10) ** (-d0)
for _ in range(20):
theta = rng.uniform(0, 2 * math.pi)
off = r * exp(1j * mpf(theta))
found = find_minibrot(m + off, r, 0)
# Size ~r^2; far below means Newton didn't converge (as in find_deep.py).
if found and r * r * 1e-10 < found[2] < r * r * 1e6:
n, per, s = found
return Stage(n, per, s, abs(n - m), 0.0, theta)
return None
def next_stage(prev, rng, max_depth, beta=0.05, tries=12):
"""A minibrot inside prev's embedded Julia set, off its centre."""
for _ in range(tries):
rho = rng.uniform(0.05, 0.6)
theta = rng.uniform(0, 2 * math.pi)
# Enough digits to place the target and find the period; the nucleus
# is polished at the new depth's precision below, which is the costly
# part (a few Newton steps instead of all of them).
mp.dps = int(-log10(prev.julia)) + 60
d = rho * prev.julia
t = prev.nucleus + d * exp(1j * mpf(theta))
found = find_minibrot(t, beta * d, prev.period)
if not found:
continue
n, p, s = found
# Newton didn't converge (implausibly small), no real progress, or
# past the target depth (renders get slow and views huge).
if s < prev.size ** 2.5 or s > prev.size ** 1.2 or -log10(s) > max_depth:
continue
set_precision(float(-log10(s)))
n = nucleus(n, p) # polish at the precision this depth needs
s2 = size(n, p)
if not s / 10 < s2 < s * 10: # the polish wandered off to another nucleus
continue
return Stage(n, p, s2, abs(n - prev.nucleus), rho, theta)
return None
def build_chain(region, stages, depth, d0, seed, max_period=200_000):
"""Stage list, deepest last, ending between depth and 1.5x depth if it can.
Stops early at max_period or a dead end (no stage within reach).
"""
rng = random.Random(seed)
s = stage0(region, d0, rng)
if s is None:
return []
chain = [s]
while len(chain) < stages and chain[-1].depth < depth:
s = next_stage(chain[-1], rng, 1.5 * depth)
if s is None or s.period > min(max_period, MAX_ITERATIONS // 2):
break
chain.append(s)
return chain
def view_args(stage, half_height):
set_precision(stage.depth)
digits = int(stage.depth) + 10
re = mp.nstr(stage.nucleus.real, digits, strip_zeros=False)
im = mp.nstr(stage.nucleus.imag, digits, strip_zeros=False)
return f"--view={re},{im},{mp.nstr(half_height, 2)}"
def minibrot_view(stage):
return view_args(stage, 3 * stage.size)
def julia_view(stage):
return view_args(stage, stage.julia)
def describe(chain):
lines = []
for i, s in enumerate(chain):
lines.append(f"# stage {i}: period={s.period} size={mp.nstr(s.size, 3)} "
f"julia={mp.nstr(s.julia, 3)} rho={s.rho:.2f} theta={s.theta:.2f}")
return lines
def main(argv):
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("region")
ap.add_argument("--stages", type=int, default=6)
ap.add_argument("--depth", type=float, default=300, help="stop past size 10^-DEPTH")
ap.add_argument("--d0", type=float, default=4, help="stage 0 distance 10^-D0 from the anchor")
ap.add_argument("--seed", type=int, default=1)
ap.add_argument("--max-period", type=int, default=200_000)
ap.add_argument("--all-stages", action="store_true", help="print every stage's views")
a = ap.parse_args(argv)
chain = build_chain(a.region, a.stages, a.depth, a.d0, a.seed, a.max_period)
if not chain:
print("no minibrot found near the anchor, try another seed", file=sys.stderr)
return 1
for line in describe(chain):
print(line)
for i, s in enumerate(chain if a.all_stages else chain[-1:]):
i = i if a.all_stages else len(chain) - 1
print(f"# stage {i} embedded Julia set:\n{julia_view(s)}")
print(f"# stage {i} minibrot:\n{minibrot_view(s)}")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
-160
View File
@@ -1,160 +0,0 @@
#!/usr/bin/env python3
"""Score a deep zoom by rendering thumbnails along it.
One `--headless` animation call streams the whole zoom (full set down to
the target, evenly spaced in log-depth) as raw RGBA thumbnails. Per frame:
- detail: mean gradient magnitude at half resolution, so flat bands and
empty voids score low and aliasing noise doesn't score high;
- a Fourier-Mellin descriptor (|FFT| resampled to log-polar, then |FFT| of
that), invariant to translation, rotation and scale. A Misiurewicz spiral
looks the same at every turn, so its frames all get the same descriptor.
A frame's novelty is its mean descriptor distance to the 3 frames before
it. boring = fraction of frames with novelty below BORING (at the default
32 frames, spiral zooms sit around 0.17, morphing chains around 0.28). score = mean detail x
(1 - boring) x (1 - empty fraction).
Usage:
score.py --view=RE,IM,HALF_HEIGHT [--frames 32] [--debug] [--sheet out.png]
Needs numpy and a release build (cargo build --release).
"""
import argparse
import os
import subprocess
import sys
from dataclasses import dataclass
import numpy as np
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
BINARY = os.path.join(ROOT, "target", "release", "mandelbrot")
START_VIEW = "-0.75,0,1.5"
BORING = 0.21 # novelty below which a frame repeats the ones before it
LAGS = (1, 2, 3)
EMPTY = 0.02 # detail below which a frame counts as empty
def render_path(view, frames=32, width=192, height=108, start=START_VIEW):
"""Frames from the full set down to `view` (RE,IM,HALF_HEIGHT), shape (n, h, w, 3)."""
view = view.removeprefix("--view=")
cmd = [BINARY, "--headless", f"--view={start}", f"--to-view={view}",
"--frames", str(frames), "--linear", "--width", str(width),
"--height", str(height), "--export-path", "-"]
out = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True).stdout
rgba = np.frombuffer(out, np.uint8).reshape(frames, height, width, 4)
return rgba[..., :3]
def edges(frame):
"""RGB gradient magnitude: filaments and band slopes, whatever the palette phase.
The cosine palettes offset the channels' phases, so the three channel
gradients never vanish together the way one brightness gradient does.
"""
f = frame.astype(np.float32) / 255.0
gy, gx = np.gradient(f, axis=(0, 1))
return np.sqrt((gx * gx + gy * gy).sum(axis=2))
def detail(frame):
"""Edge strength after a 2x2 box average.
Thumbnails are rendered without AA, so a deep frame's sub-pixel filaments
alias into noise. The average smooths that noise away but keeps real
filaments, so a noisy frame doesn't win on detail.
"""
h, w = frame.shape[0] // 2 * 2, frame.shape[1] // 2 * 2
f = frame[:h, :w].astype(np.float32)
f = (f[0::2, 0::2] + f[1::2, 0::2] + f[0::2, 1::2] + f[1::2, 1::2]) / 4
return float(edges(f.astype(np.uint8)).mean())
def structure(e):
"""Rank-normalised edge map: which pixels are filaments, not how bright they are."""
r = np.empty(e.size, np.float32)
r[np.argsort(e, axis=None, kind="stable")] = np.linspace(0, 1, e.size)
return r.reshape(e.shape)
def _log_polar_grid(h, w, n_r=32, n_a=64):
cy, cx = h / 2, w / 2
r = np.exp(np.linspace(np.log(2), np.log(min(cy, cx) - 1), n_r))
a = np.linspace(0, np.pi, n_a, endpoint=False) # |FFT| is point-symmetric
ys = (cy + r[:, None] * np.sin(a)[None, :]).astype(int)
xs = (cx + r[:, None] * np.cos(a)[None, :]).astype(int)
return ys, xs
def descriptor(g):
"""Translation-, rotation- and scale-invariant signature of a frame."""
g = (g - g.mean()) * np.outer(np.hanning(g.shape[0]), np.hanning(g.shape[1]))
mag = np.abs(np.fft.fftshift(np.fft.fft2(g)))
ys, xs = _log_polar_grid(*g.shape)
lp = np.log1p(mag[ys, xs])
lp -= lp.mean()
# Rotation and scale are shifts along the log-polar axes: drop them.
d = np.abs(np.fft.fft2(lp))[:8, :16].ravel()
return d / (np.linalg.norm(d) + 1e-12)
@dataclass
class PathScore:
score: float
detail: float
boring: float
empty: float
per_frame: list # (detail, novelty)
def score_frames(frames):
maps = [edges(f) for f in frames]
det = np.array([detail(f) for f in frames])
desc = [descriptor(structure(e)) for e in maps]
novelty = np.array([
np.mean([np.linalg.norm(desc[i] - desc[i - lag]) for lag in LAGS])
for i in range(max(LAGS), len(frames))
])
# The last frames close in on the minibrot, which is meant to look alike.
boring = float((novelty[:-2] < BORING).mean())
empty = float((det < EMPTY).mean())
per_frame = list(zip(det.tolist(), [0.0] * max(LAGS) + novelty.tolist()))
return PathScore(float(det.mean()) * (1 - boring) * (1 - empty),
float(det.mean()), boring, empty, per_frame)
def save_sheet(frames, path, picks=(0.25, 0.5, 0.75, 1.0), columns=4):
"""A grid of the frames at the given fractions of the zoom, row by row."""
from PIL import Image # optional: only needed for sheets
idx = [min(len(frames) - 1, round(p * (len(frames) - 1))) for p in picks]
rows = [np.concatenate([frames[i] for i in idx[r:r + columns]], axis=1)
for r in range(0, len(idx), columns)]
Image.fromarray(np.ascontiguousarray(np.concatenate(rows, axis=0))).save(path)
def main(argv):
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("--view", required=True, help="RE,IM,HALF_HEIGHT of the zoom target")
ap.add_argument("--frames", type=int, default=32)
ap.add_argument("--debug", action="store_true", help="print per-frame metrics")
ap.add_argument("--sheet", help="write a contact sheet PNG (needs Pillow)")
a = ap.parse_args(argv)
frames = render_path(a.view, a.frames)
s = score_frames(frames)
if a.debug:
for i, (d, nov) in enumerate(s.per_frame):
print(f"{i:3} detail={d:.3f} novelty={nov:.3f}")
print(f"score={s.score:.4f} detail={s.detail:.3f} boring={s.boring:.2f} empty={s.empty:.2f}")
if a.sheet:
save_sheet(frames, a.sheet)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
-92
View File
@@ -1,92 +0,0 @@
#!/usr/bin/env python3
"""Random search for deep zooms that keep changing shape all the way down.
Builds many Julia-morphing chains (morph.py) from different seeds on every
core, renders each zoom's thumbnails on the GPU (score.py), and prints the
best ones with their views and a contact sheet (8 frames) in out/.
Zooms are scored down to the last embedded Julia set, not the minibrot:
the last quarter of the way to any minibrot is rings closing in on it (as
self-similar as a spiral) and looks the same in every chain.
Usage:
search.py REGION [--depth 300] [--candidates 24] [--seed 1] [--jobs N]
Needs mpmath, numpy, Pillow and a release build (cargo build --release).
"""
import argparse
import os
import subprocess
import sys
from concurrent.futures import ProcessPoolExecutor, as_completed
from morph import build_chain, describe, julia_view, minibrot_view
from score import render_path, save_sheet, score_frames
OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "out")
def chain_job(region, stages, depth, d0, seed, max_period):
chain = build_chain(region, stages, depth, d0, seed, max_period)
if not chain:
return seed, None
last = chain[-1]
return seed, {
"stages": describe(chain),
"depth": last.depth,
"period": last.period,
"julia": julia_view(last),
"minibrot": minibrot_view(last),
}
def main(argv):
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("region", help="find_deep.py region name, or re,im,k,p")
ap.add_argument("--stages", type=int, default=14)
ap.add_argument("--depth", type=float, default=300, help="stop past size 10^-DEPTH")
ap.add_argument("--d0", type=float, default=4, help="stage 0 distance 10^-D0 from the anchor")
ap.add_argument("--candidates", type=int, default=24)
ap.add_argument("--seed", type=int, default=1, help="first seed; candidates use seed, seed+1, ...")
ap.add_argument("--max-period", type=int, default=200_000)
ap.add_argument("--jobs", type=int, default=os.cpu_count())
ap.add_argument("--top", type=int, default=5)
a = ap.parse_args(argv)
os.makedirs(OUT, exist_ok=True)
results = []
with ProcessPoolExecutor(a.jobs) as pool:
futures = [pool.submit(chain_job, a.region, a.stages, a.depth, a.d0, s, a.max_period)
for s in range(a.seed, a.seed + a.candidates)]
# Chains finish in any order; render each as it arrives (one at a time on the GPU).
for f in as_completed(futures):
seed, r = f.result()
if r is None:
print(f"seed {seed}: no chain", file=sys.stderr)
continue
try:
frames = render_path(r["julia"])
except (OSError, subprocess.CalledProcessError) as e:
print(f"seed {seed}: render failed: {e}", file=sys.stderr)
continue
s = score_frames(frames)
sheet = os.path.join(OUT, f"{a.region.split(',')[0]}-{seed}.png")
save_sheet(frames, sheet, picks=[i / 7 for i in range(8)], columns=4)
print(f"seed {seed}: score={s.score:.4f} boring={s.boring:.2f} "
f"depth=1e-{r['depth']:.0f} period={r['period']}", file=sys.stderr)
results.append((s, seed, r, sheet))
results.sort(key=lambda x: -x[0].score)
for s, seed, r, sheet in results[:a.top]:
print(f"\n## seed {seed}: score={s.score:.4f} detail={s.detail:.3f} "
f"boring={s.boring:.2f} empty={s.empty:.2f}")
print(f"# contact sheet: {sheet}")
print("\n".join(r["stages"]))
print(f"# last embedded Julia set (end here to keep changing shape all the way):\n{r['julia']}")
print(f"# minibrot (the last quarter of the zoom is rings closing in):\n{r['minibrot']}")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))