diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 81e32c18a9..c7a2edd8e0 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -123,6 +123,24 @@ jobs: path: | playwright-report/ examples/*/*/dist/ + skeleton-browser-integration: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version: 24.x + cache: "npm" + cache-dependency-path: | + package-lock.json + - run: npm ci + - run: npm run test:skeleton:browser -- --reporter=html + - name: Upload report + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + if: ${{ !cancelled() }} + with: + name: skeleton-browser-integration-results + path: playwright-report/ # Builds Python package and runs Python tests # diff --git a/docs/datasource/catmaid/index.rst b/docs/datasource/catmaid/index.rst new file mode 100644 index 0000000000..f8057e051c --- /dev/null +++ b/docs/datasource/catmaid/index.rst @@ -0,0 +1,66 @@ +.. _catmaid-datasource: + +CATMAID +======= + +The CATMAID data service driver exposes skeletons from a CATMAID project, +including spatially indexed skeleton loading and optional editing. + +URL syntax +---------- + +- :file:`catmaid://https://{host}/{project-id}` +- :file:`catmaid://http://{host}/{project-id}` + +Browser authentication +---------------------- + +Neuroglancer first requests CATMAID's anonymous API token so public projects +continue to load without interaction. If the anonymous account cannot access a +project, Neuroglancer asks for a personal CATMAID API token. + +Open the CATMAID server, use the account menu to obtain an API token, and paste +it into the Neuroglancer prompt. The token is cached for the current browser tab +under the CATMAID base URL, allowing other projects on the same server to reuse +it. A rejected token is removed automatically and requested again. Tokens are +not included in datasource URLs or serialized viewer state. + +Because an API token has the same permissions as its CATMAID account, use HTTPS +for authenticated deployments and do not share the token. + +Python authentication +--------------------- + +Python-hosted viewers obtain credentials on the Python server. Configure a +token before adding CATMAID layers: + +.. code-block:: python + + import neuroglancer + + neuroglancer.set_catmaid_token( + "https://catmaid.example", + "your-api-token", + ) + +Pass ``None`` as the token to remove a configured value. Deployments may +instead set ``CATMAID_CREDENTIALS`` to a JSON object keyed by CATMAID base +URL: + +.. code-block:: shell + + export CATMAID_CREDENTIALS='{"https://catmaid.example": "your-api-token"}' + +Tokens configured with ``set_catmaid_token`` take precedence over the +environment. If neither is present, the Python provider attempts anonymous +access. + +Server requirements +------------------- + +The CATMAID deployment must allow the Neuroglancer origin to make cross-origin +``GET`` and ``POST`` requests and must allow the ``Authorization`` and +``Content-Type`` request headers. Project read and edit access is determined +by the CATMAID account associated with the token. Separately, Neuroglancer only +enables editing when the linked stack metadata sets ``read_only`` to +``false``; see :ref:`skeleton-editing-sources`. diff --git a/docs/datasource/index.rst b/docs/datasource/index.rst index 280477ef18..40033b1eb2 100644 --- a/docs/datasource/index.rst +++ b/docs/datasource/index.rst @@ -127,5 +127,6 @@ Data services :maxdepth: 1 boss/index + catmaid/index dvid/index render/index diff --git a/docs/user-guide/annotation_shaders.rst b/docs/user-guide/annotation_shaders.rst index a92421aa59..608dd4edf1 100644 --- a/docs/user-guide/annotation_shaders.rst +++ b/docs/user-guide/annotation_shaders.rst @@ -71,7 +71,7 @@ interpolation**) will help us do that. .. code-block:: glsl - #uicontrol float red invlerp(range=[10,30], window=[0,1000]) + #uicontrol invlerp red(range=[10,30], window=[0,1000]) void main() { vec3 mycolor = vec3(red(), 0.0, 0.0); setColor(mycolor); @@ -94,7 +94,7 @@ property goes from low to high. .. code-block:: glsl - #uicontrol float intensity invlerp(range=[10,30], window=[0,1000]) + #uicontrol invlerp intensity(range=[10,30], window=[0,1000]) #uicontrol vec3 mycolor color(default="red") void main() { setColor(intensity()*mycolor); @@ -166,7 +166,7 @@ we might use the ``invlerp`` control again. .. code-block:: glsl - #uicontrol float intensity invlerp(range=[10,30], window=[0,1000]) + #uicontrol invlerp intensity(range=[10,30], window=[0,1000]) void main() { setColor(defaultColor()); setPointMarkerSize(1.0 + 19.0*intensity()); @@ -177,7 +177,7 @@ control. .. code-block:: glsl - #uicontrol float intensity invlerp(range=[10,30], window=[0,1000]) + #uicontrol invlerp intensity(range=[10,30], window=[0,1000]) #uicontrol float maxsize slider(min=1.0, max=50.0, step=1.0) void main() { setColor(defaultColor()); diff --git a/docs/user-guide/index.rst b/docs/user-guide/index.rst index de12484cf3..9469822beb 100644 --- a/docs/user-guide/index.rst +++ b/docs/user-guide/index.rst @@ -12,8 +12,12 @@ Topics to segmentation layers. - :doc:`annotation_shaders` — writing custom GLSL shader code to drive the visual appearance of annotations from their properties. +- :doc:`skeleton_editing` — tracing, navigation, visual previews, saving, + Undo/Redo, failure recovery, and source setup. - :doc:`voxel_annotation` — painting, erasing and flood filling voxels of image and segmentation layers. +- :doc:`segmentation_shaders` — writing custom GLSL shader code to color + segmentation layers from segment ids and segment properties. .. toctree:: :hidden: @@ -21,4 +25,6 @@ Topics navigation annotations annotation_shaders + skeleton_editing voxel_annotation + segmentation_shaders diff --git a/docs/user-guide/segmentation_shaders.rst b/docs/user-guide/segmentation_shaders.rst new file mode 100644 index 0000000000..fa84a8ff4f --- /dev/null +++ b/docs/user-guide/segmentation_shaders.rst @@ -0,0 +1,199 @@ +Segmentation Shaders +-------------------- + +Segmentation layers can use custom GLSL code to change how segments are colored. +The technical reference for the shader API is in +`the segmentation rendering guide `_. +This page is a gentler introduction to the same ideas. + +The Segment Color Function +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A segmentation shader defines a ``segmentColor`` function. The default shader +keeps Neuroglancer's existing segment color unchanged: + +.. code-block:: text + + vec3 segmentColor(vec3 color, bool hasProperties, bool isStated) { + return color; + } + +The ``color`` argument is the color Neuroglancer would normally use for the +segment. It may come from the segment color hash, the layer's default segment +color, or an explicit color assigned to that segment. The ``isStated`` argument +is ``true`` when ``color`` came from an explicit segment color. The +``hasProperties`` argument is ``true`` when Neuroglancer found segment property +data for the current segment. + +To make every visible segment red, return a red ``vec3``: + +.. code-block:: text + + vec3 segmentColor(vec3 color, bool hasProperties, bool isStated) { + return vec3(1.0, 0.0, 0.0); + } + +If you want to preserve explicit per-segment colors but recolor everything +else, use ``isStated``: + +.. code-block:: text + + vec3 segmentColor(vec3 color, bool hasProperties, bool isStated) { + if (isStated) { + return color; + } + return vec3(0.0, 0.6, 1.0); + } + +Opacity +~~~~~~~ + +Use a ``vec4`` return type to adjust opacity. The alpha channel is the fourth +component. It is multiplied by **Opacity (on)** or **Opacity (off)** in slice +views. For meshes and skeletons, it is multiplied by **Opacity (3d)**. + +.. code-block:: text + + vec4 segmentColor(vec4 color, bool hasProperties, bool isStated) { + if (isStated) { + return color; + } + return vec4(color.rgb, 0.35); + } + +Segment Properties +~~~~~~~~~~~~~~~~~~ + +Segment properties can drive color choices. If a segment property map is +available, a shader can read tags and properties directly by name: + +.. code-block:: text + + vec3 segmentColor(vec3 color, bool hasProperties, bool isStated) { + if (!hasProperties) { + return vec3(0.5, 0.5, 0.5); + } + if (tag("axon")) { + return vec3(1.0, 0.4, 0.0); + } + if (prop("size") > 100u) { + return vec3(1.0, 1.0, 0.0); + } + return color; + } + +``tag("axon")`` returns ``true`` when the current segment has that tag. +``prop("size")`` reads a numerical property named ``size``. For string +properties, compare the value with a string literal: + +.. code-block:: text + + vec3 segmentColor(vec3 color, bool hasProperties, bool isStated) { + if (!hasProperties) { + return vec3(0.5, 0.5, 0.5); + } + if (prop("class") == "interneuron") { + return vec3(0.0, 1.0, 0.6); + } + return color; + } + +Property Controls +~~~~~~~~~~~~~~~~~ + +A ``property`` UI control lets the user choose which segment property a shader +uses. The control can be filtered to tags, numerical properties, or string +properties. + +.. code-block:: text + + #uicontrol property selectedTag(type="tag") + #uicontrol property selectedSize(type="number") + #uicontrol property selectedClass(type="string") + + vec3 segmentColor(vec3 color, bool hasProperties, bool isStated) { + if (!hasProperties) { + return vec3(0.5, 0.5, 0.5); + } + if (selectedTag) { + return vec3(1.0, 0.0, 0.0); + } + if (selectedSize > 100u) { + return vec3(1.0, 1.0, 0.0); + } + if (selectedClass == "interneuron") { + return vec3(0.0, 1.0, 0.6); + } + return color; + } + +A ``type="tag"`` control lets the user choose an individual tag and evaluates +to a ``bool`` indicating whether the current segment has that tag. A +``type="string"`` control lets the user choose a string property and evaluates +to that property's value, which can be compared with a string literal. +``type="number"`` and ``type="numerical"`` both select numerical properties; +the control's GLSL type matches the selected property's data type. + +Data Mapping +~~~~~~~~~~~~ + +For continuous numerical properties, an ``invlerp`` control maps a property +range to ``0-1``. The user can adjust the selected property and range from the +shader UI. + +.. code-block:: glsl + + #uicontrol invlerp intensity(property="size", range=[0, 1000]) + + vec3 segmentColor(vec3 color, bool hasProperties, bool isStated) { + if (!hasProperties) { + return vec3(0.5, 0.5, 0.5); + } + return intensity() * vec3(1.0, 0.2, 0.0); + } + +If ``property`` is omitted, Neuroglancer selects the first available numerical +segment property as the default. ``range`` controls the data values mapped to +``0`` and ``1``. ``window`` can be added to control the range shown by the UI +widget. + +Colormaps +~~~~~~~~~ + +The remapped value from an ``invlerp`` control can be passed to a colormap: + +.. code-block:: glsl + + #uicontrol invlerp intensity(property="size", range=[0, 1000]) + + vec3 segmentColor(vec3 color, bool hasProperties, bool isStated) { + if (!hasProperties) { + return vec3(0.5, 0.5, 0.5); + } + if (isStated) { + return color; + } + return colormapJet(intensity()); + } + +This pattern is useful when a numerical segment property should control color +continuously while still respecting explicitly assigned segment colors. + +Relationship to the Skeleton Shader +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A segmentation layer may have both a segment color shader and a skeleton user +shader. The segment color shader determines the per-segment color used by slice +views, meshes, and skeletons. + +The default skeleton shader preserves the result of the segment color shader: + +.. code-block:: glsl + + void main() { + emitDefault(); + } + +Here, ``emitDefault()`` emits the color and alpha returned by the segment color +shader. A custom skeleton shader can also access that result through +``vec4 segmentColor()``, or emit its own color. diff --git a/docs/user-guide/skeleton_editing.rst b/docs/user-guide/skeleton_editing.rst new file mode 100644 index 0000000000..fd59f22af6 --- /dev/null +++ b/docs/user-guide/skeleton_editing.rst @@ -0,0 +1,565 @@ +.. _optimistic-skeleton-edit-queue: + +Skeleton editing +================ + +When you edit a skeleton, Neuroglancer shows a preview of the result and saves +it to CATMAID in the background. This lets you continue tracing while earlier +changes save. It applies to adding, moving, and deleting nodes; changing node +properties; rerooting; splitting and merging skeletons; and Undo and Redo. + +.. _skeleton-queue-edit-gestures: + +Edit a skeleton +--------------- + +1. Open your writable CATMAID layer. Make the skeleton visible in **Seg**, or + double-click one of its nodes in the viewport. +2. **Hover over or select a node** to show that skeleton's node list in + **Skeleton**. Allow its details to finish loading. Making the skeleton + visible alone does not choose which skeleton's nodes the panel shows. +3. Activate **Skeleton editing** and make your edits. The preview appears as + soon as it is ready; you can continue editing while earlier changes save. +4. Open the layer's **Queue** tab to check progress. **Saved** confirms that + CATMAID saved the action and Neuroglancer applied the result locally. + +For example, add a node and then add a child to it before the first save +finishes. Both appear in the preview. Neuroglancer saves them in order and +attaches the child to the correct parent once CATMAID returns its saved ID. + +You can keep selecting, navigating, filtering, pinning, and changing visibility +while edits save. You can also use Undo and Redo when their controls are +available. + +.. _skeleton-editing-tools: + +Activate Skeleton editing +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Activate **Skeleton editing** from the Skeleton tab. To assign it a shortcut, +click its key-binding box and press a free key, such as **E**. **Shift+E** then +activates the tool. Moving, adding, merging, splitting, creating a skeleton, +inserting, and deleting are modes of this one tool. + +Use these gestures with **Skeleton editing** active and the pointer over a +viewport. Click means left-click. Release **M**, **S**, **N**, **D**, or **I** +to leave that mode after completing the gesture. + +.. list-table:: + :header-rows: 1 + :widths: 25 75 + + * - Action + - Gesture + * - Select a node + - Click the node. + * - Move a node + - Drag the node to its new position. + * - Add a child + - Select its parent, then **Shift+click** where the child should go. + * - Merge skeletons + - Hold **M**, click the source node, then click the target node in the + other skeleton. + * - Split a skeleton + - Hold **S**, then click a non-root node that is not marked as a true + end. That node and its descendants become a separate skeleton. + * - Create a new skeleton + - Hold **N**, then click empty space to place its root node. + * - Insert a node + - Hold **I**, then click two directly connected nodes to insert a node + at the midpoint of their edge. + * - Delete a node + - Hold **D**, then click the node to delete. + +.. _skeleton-editing-insert: + +Inserting a Node +~~~~~~~~~~~~~~~~ + +Hold :kbd:`I` and click two directly connected nodes: one must be the parent of +the other. The order of the two clicks does not matter. A new node is inserted +at the midpoint of the edge between them; it becomes a child of the parent node +and the new parent of the child node. + +Because a node can have only one parent, two nodes that are not directly +connected are rejected and nothing is changed. The first node you clicked stays +selected so you can pick one of its neighbours instead. Both nodes must belong +to a visible skeleton. + +Merge and split rules +~~~~~~~~~~~~~~~~~~~~~ + +Merge joins two skeletons through the source and target nodes you choose. +Start with the source skeleton visible and its node details available. +Neuroglancer fetches the target skeleton's details if needed before previewing +the merge. CATMAID decides which skeleton ID survives, and Neuroglancer follows +the saved result. + +Split cuts the connection between the selected node and its parent. The +selected node becomes the root of a new skeleton with all its descendants; +the rest stays in the original skeleton. This produces two skeletons, even +when the selected node is a branch point or a leaf. The selected node must +have a parent and must not be marked as a true end. Its complete skeleton +details must be available before the split can start. + +Rerooting, node properties, Undo, and Redo are also available through the +**Skeleton** controls. + +.. _skeleton-editing-tab: + +Inspect and navigate skeletons +------------------------------ + +The **Skeleton** tab is available for CATMAID layers with the spatially indexed +skeleton subsource active. Hover over or select a node to choose which +skeleton's details appear. Make the skeleton visible in **Seg**, or double-click +one of its nodes, to request its complete details. Making it visible alone +does not choose its node list. Previously fetched details may remain available +after a skeleton is hidden. + +Find nodes by ID or description, or filter the list to show leaves, virtual +ends, true ends, or nodes with descriptions. Pin a selection to keep its +details in the panel while navigating elsewhere. + +Navigate the tree +~~~~~~~~~~~~~~~~~ + +The Skeleton toolbar provides controls to: + +- Go to the root. +- Go to the start or end of the current branch. +- Cycle through nodes at the current level. +- Go to the parent or a child of the current node. +- Go to the nearest leaf that is not marked as a true end. + +In the node list, right-click a node to move to it, or left-click to select it +and move to it. + +.. _skeleton-node-types: + +Node types +~~~~~~~~~~ + +Node symbols indicate their place in the skeleton: + +- **Root:** the root node of the skeleton. +- **Regular node:** an interior node along a branch. +- **Branch point:** a node with more than one child. +- **Virtual end:** a leaf that has not been marked as a true end. +- **True end:** a leaf marked by a reviewer as the end of a branch. + +For a visible skeleton, click a leaf's type icon in the node list to toggle +between virtual end and true end. + +.. _skeleton-node-properties: + +Node properties +~~~~~~~~~~~~~~~ + +Show the skeleton, then select a node in its node list or use **Ctrl+right-click** +in the viewport (**Cmd+right-click** on macOS). The selected node's controls +let you change its radius, confidence, or free-text description. Depending on +the node, you can also delete it, change its end type, or make it the root. + +These changes preview and save through the same queue as edits made in the +viewport. A read-only source still allows inspection, but disables editing. + +Understand the visual cues +-------------------------- + +.. list-table:: + :header-rows: 1 + :widths: 25 75 + + * - Cue + - Meaning + * - **Dashed yellow rings and lines** + - A structural preview is being prepared. Rings mark known affected + nodes; lines indicate the connection or path involved. The previous + complete structure stays visible until the preview is ready. + * - **Preview** in red + - A new node or skeleton has a temporary identity while CATMAID assigns + its saved ID. You can continue editing it. Red here does not indicate + an error. + * - **Updating** beside the skeleton + - The panel retains the last complete shape while the next preview is + being prepared. This shape can already include earlier edits that are + still saving. + +The letters or symbols inside dashed yellow rings identify the requested +change: **S** for split, **M** for merge, **R** for reroot, **×** for delete, +and **+** for restore, such as undoing a deletion. These cues disappear when +the complete preview replaces them, which may happen before the save finishes. +On small skeletons, preparation may finish too quickly to see the cues. + +Here are examples of when they appear: + +- **Split a branch:** while the split preview is being prepared, yellow **S** + rings mark the cut node and its parent, with a dashed line along the + connection being cut. The branch still looks attached during preparation. + **Updating** in Skeleton means the list still describes that earlier shape. + Once the preview is ready, the branch appears as a separate skeleton and + the yellow cues disappear, even if Queue still says Saving. +- **Merge two skeletons:** yellow **M** rings mark the two chosen endpoints, + with a dashed line showing the intended join while its preview is prepared. + Once joined in the preview, the combined skeleton shows **Preview** in red + until CATMAID confirms its saved skeleton ID. You can keep editing it. +- **Delete a node or undo a deletion:** a yellow **×** marks the node being + deleted; **+** marks where a deleted node is being restored while that + preview is prepared. +- **Choose a new root:** yellow **R** markers identify the requested root and + the known path involved in rerooting while the preview is prepared. +- **Create a skeleton or add a child:** the new skeleton or node can show + **Preview** in place of its ID while its save is pending. It is already + available for further editing, such as adding another child. + +A visible preview or a permanent numeric ID alone does not confirm that all +pending edits have saved. Use **Queue** to check completion. + +Check progress in Queue +----------------------- + +**Pending edits** shows unfinished actions in the order you requested them. +Completed actions move to **Recent activity**. + +.. list-table:: + :header-rows: 1 + :widths: 30 35 35 + + * - Status + - Where it appears + - What it means + * - **Preparing** + - Pending edits + - Neuroglancer is building the preview. Some controls may briefly be + unavailable. + * - **Queued** + - Pending edits + - Your preview is ready and waiting for its turn to save. + * - **Saving** + - Pending edits + - CATMAID is processing the action. + * - **Reconciling** + - Pending edits + - CATMAID has replied and Neuroglancer is applying the saved result + locally. This is usually brief. + * - **Saved** + - Recent activity + - CATMAID saved the action and Neuroglancer applied the result locally. + * - **Reverted** + - Recent activity + - Pending actions canceled each other locally, such as an edit followed + by Undo, without saving those actions. + * - **Not saved** + - Recent activity + - The action failed or was canceled. See the failure guidance below + before trying again. + * - **Reload required** + - Pending edits and a persistent alert + - Neuroglancer cannot reliably match its local skeleton to CATMAID. + Editing, Undo, and Redo are blocked until you reload and inspect the + saved result. + +Recent activity keeps **64 completed actions by default**, ordered newest +requested action first. Once there are more than 64, the oldest rows leave +the list; rows do not expire after a set amount of time. Removing a row does +not remove a saved change or decide whether it can still be undone. + +**Undo and Redo each add their own activity row.** For example, moving a node +and then undoing the move produces a Move row and an Undo row. Undo does not +delete the Move row. Both count toward the 64-row limit, even if they cancel +locally and show Reverted. + +.. _skeleton-editing-undo: + +.. _skeleton-queue-undo-redo: + +Undo and Redo +------------- + +Use **Undo** and **Redo** in the Skeleton toolbar. Undo works backwards through +your latest edits, including changes that are still waiting to save. +The page retains the edit information they need, so you do not have to show +a hidden skeleton again before using Undo or Redo. + +- **Before saving starts:** Undo can remove the preview without sending the + edit to CATMAID. Recent activity may show Reverted. Redo can reapply it. +- **While saving is in progress:** Undo can restore the earlier appearance + immediately. The original save finishes first, then Neuroglancer saves the + undo. Wait for both to finish before treating the result as saved. +- **After an edit is saved:** Undo and Redo create their own previews and save + in turn, just like other actions. + +For example, create a new skeleton, then click Undo and Redo while its first +save is still in progress. The node disappears and reappears immediately. +It stays visible while the original creation, Undo, and Redo save in order. +Wait for the queue to finish before leaving the page. + +Undo/Redo retains **64 original edits by default**, shared between what you +can undo and what you can redo. Undo and Redo move an existing edit between +those two groups; they do not use another history slot. New edits enter this +history as soon as they are accepted, before saving finishes. + +**History controls what the Undo and Redo buttons can do. Recent activity is +a log of what happened.** Both default to 64, but they count different things: + +.. list-table:: + :header-rows: 1 + :widths: 30 35 35 + + * - What you do, starting with empty history + - Undo/Redo choices + - Recent activity after the actions finish + * - Move one node, then Undo it + - One original edit is retained: nothing to Undo, one move to Redo. + - Two rows: Move and Undo. + * - Move one node, then repeat Undo followed by Redo 32 times + - Still one original edit: one move to Undo, nothing to Redo. + - 65 actions have completed. Only the latest 64 rows are shown; the + original Move row has left the log, but the move is still available to + Undo. + * - Make 65 consecutive new edits, allowing them to save + - Only the latest 64 edits can be undone. The first edit has left + history. + - Only the latest 64 actions are shown. + +Making a new edit after Undo clears the Redo choices immediately. If the new edit is rejected without changing CATMAID and recovery +succeeds, those Redo choices return. Reloading the page or replacing the +skeleton layer clears history. A disabled button's tooltip explains why the +action is currently unavailable. + +Undoing a split or merge restores the structure, but CATMAID may assign new +skeleton or node IDs. One Undo can require several saving steps. All those +steps must succeed before the Undo is marked Saved. + +When the queue is full +---------------------- + +The queue accepts **64 unfinished actions by default**. Actions count while +preparing, waiting to save, saving, or applying the saved result locally. +Undo and Redo normally each count as an action; an action with several server +steps still counts as one. + +At that limit, a new edit is not accepted. Wait until a pending action finishes +or is canceled, then try again. Saved actions and Recent activity rows do not +occupy queue space. +Undo may still be available at the limit if it can cancel an unsent action +locally and free space. + +If something needs attention +---------------------------- + +An action asks you to inspect the skeleton +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Make the skeleton visible in **Seg**, or double-click one of its nodes. Hover +over or select a node so its node list appears in **Skeleton**, wait for the +details to finish loading, then repeat the action. A few points in the viewport +can be shown before the full skeleton details needed for editing are available. + +An action rejected with this inspection message has not added anything to +Queue or history. When a merge needs to fetch the second skeleton's details, +it waits up to two minutes. If that fetch fails, no merge is queued; you can +show the second skeleton's details and try again. + +A save is taking a long time +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A warning appears if a save request takes more than **30 seconds**. The +warning does not cancel the request or mean it failed. Check your connection +and Queue, and let the pending request finish before repeating that action. + +What happens when an action fails +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The status depends on what happened to the saved data and whether Neuroglancer +can restore a reliable local view: + +.. list-table:: + :header-rows: 1 + :widths: 30 35 35 + + * - Status + - When it appears + - Can I make a new edit? + * - **Not saved** + - The action was rejected without changing CATMAID, and Neuroglancer + successfully removed its preview and canceled later pending actions. + Those canceled actions also show Not saved. + - **Yes.** Read the error and correct the cause first. The queue accepts + new actions after recovery finishes. + * - **Reload required** + - The save outcome is uncertain, an action only partly saved, or + Neuroglancer cannot reliably apply or roll back the result locally. + - **No.** The queue rejects new edits, Undo, and Redo until the page is + reloaded. Waiting for queue space does not clear this state. + +If a Reload required alert appears alongside a Not saved row, follow the +alert: editing stays blocked until reload. + +When an edit fails without changing CATMAID and recovery succeeds, +Neuroglancer removes its preview and every later pending preview. This includes +later edits to other skeletons in the layer. **Earlier changes and their +Undo/Redo choices remain available.** An earlier edit that is still saving +continues normally. + +For example: + +1. You change a node's description from “unreviewed” to “checked” and wait for Saved. +2. You move that node from position A to position B, then add a child before + the move finishes saving. +3. CATMAID rejects the move. Neuroglancer removes the move preview and cancels + the pending child. The node returns to A, the child disappears, and both + actions show Not saved. The saved description is still “checked”. +4. After correcting the cause of the error, you can use Undo to restore the + description to “unreviewed”, or continue with a new edit. + +.. list-table:: + :header-rows: 1 + :widths: 25 75 + + * - Action that was rejected + - What happens to Undo/Redo after successful recovery + * - A new edit + - That edit and later actions leave history. Earlier Undo choices remain, + and any Redo choices cleared by the rejected edit return. Redo does not + retry the failed new edit. + * - Undo + - The original edit returns to Undo. After correcting the cause, you can + try Undo again. + * - Redo + - The original edit returns to Redo. After correcting the cause, you can + try Redo again. + +Read the error, inspect the remaining skeleton, and correct the problem before +continuing. Canceled actions are not retried automatically. Recent activity +keeps its record of completed actions; it does not determine which edits can +be undone or redone. If recovery requires a reload, the entire Undo/Redo history +is cleared instead. + +**If Reload required is present**, use **Reload page** in the alert. Show the +affected skeletons in **Seg**, then hover over or select their nodes to check +what CATMAID saved before repeating an action. Selection, navigation, and +inspection remain available while editing is blocked. Replacing the layer +does not clear the alert; Neuroglancer does not automatically retry or undo +an uncertain result. + +Before you leave +---------------- + +Wait until Pending edits is empty and check Recent activity for failures +before closing the page, reloading, or removing the layer. An empty pending +list alone does not mean every action succeeded. + +Closing or replacing the layer discards actions that have not started saving. +Requests already sent may still change CATMAID. Removing the layer is therefore +not a way to undo an edit. After an unexpected interruption, show the affected +skeletons and check the saved result before continuing. + +.. _skeleton-editing-sources: + +Source setup +------------ + +If your writable CATMAID layer is already configured, use it as described above. +This section covers connecting a source and configuring its display. + +CATMAID requirements +~~~~~~~~~~~~~~~~~~~~ + +Skeleton editing currently supports CATMAID sources. The server needs: + +- CATMAID ``2026.05.06.dev11+g...`` or later by git-describe version ordering. +- A CATMAID project and a linked project stack. +- CATMAID read permissions for anonymous access or a personal API token. +- CATMAID edit permissions for the token account when editing is enabled. +- Cross-origin access for the Neuroglancer origin and authorization headers. +- Skeletons initialized for that project. + +CATMAID coordinates are in nanometers. Neuroglancer uses the linked stack's +dimensions multiplied by its resolution to determine the project bounds. + +The linked stack can define spatial skeleton metadata, with one entry in +``spatial`` for each index level: + +.. code-block:: json + + { + "spatial": [ + { + "chunk_size": [11168145, 11168145, 11168145], + "limit": 500 + }, + { + "chunk_size": [3939000, 3939000, 3939000], + "limit": 7000 + } + ], + "cache_provider": "cached_msgpack_grid", + "read_only": false + } + +``chunk_size`` uses CATMAID project-space nanometers. Each level requires a +``limit``, the maximum expected node count. A limit of ``0`` means complete, +unlimited results and is allowed only on the finest level. The optional +``cache_provider`` is passed to CATMAID's node-list requests. + +Set ``read_only`` to ``false`` to allow editing. Otherwise the source supports +inspection only. If ``spatial`` is absent or empty, Neuroglancer derives a +default chunk size from the project bounds and uses ``limit: 0``. + +After setting this up, enter +``catmaid:/`` as a data +source in Neuroglancer. Public projects use CATMAID's anonymous API token. +Private projects prompt for a personal API token, which is retained for the +current browser tab. Python-hosted viewers can configure the token with +``neuroglancer.set_catmaid_token`` or ``CATMAID_CREDENTIALS``. See +:ref:`catmaid-datasource` for authentication and CORS details. + +.. _skeleton-editing-subsources: + +Layer subsources and display +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The data source exposes a single spatially indexed skeleton subsource, which is +required for editing. +The **Seg** tab controls skeleton visibility by ID or by an assigned label. + +Showing a skeleton requests its complete nodes and details. Allow that request +to finish. Otherwise, the viewport may show only the points supplied by the +spatial index for the current view. **Spacing (cross section)** and +**Spacing (projection)** control the selected index level. + +In **Render**, **Opacity (3d)** controls fully loaded visible skeletons. +**Hidden Opacity (3d)** controls the spatially indexed indicators for hidden +skeletons. + +.. _skeleton-editing-find-path: + +Find Path +--------- + +Click **Find Path** in the skeleton tab, then left-click the source node followed +by the target node. You may also hold :kbd:`Shift` while selecting. Both +endpoints must be distinct, exact nodes in the same skeleton segment; points on +edges are not accepted. A third selection is ignored until an endpoint is +removed or the tool is cleared. The endpoint rows show each node's derived +topology type and coordinates; hover a row to see its node ID. + +The route is computed automatically after the target is selected and displayed +as a white annotation polyline. **Find Path** uses complete skeleton data already +cached in the client and does not initiate a download. A cached skeleton can be +used even if it is no longer visible. If the skeleton is not cached, make it +visible and wait for the normal visibility pipeline to load it; the route is +computed automatically when loading completes. Click **Clear** to remove the +endpoints and route. Deleting the route annotation has the same effect as +**Clear**. If a generic skeleton contains cycles, **Find Path** selects a +deterministic route with the fewest edges. + +While Find Path is active, use the middle mouse button to navigate. Control plus +left mouse provides the same trackpad-friendly navigation alternative as the +Edit tool. + +The spatial skeleton tool supports one active spatial skeleton datasource per +segmentation layer. Switching Find Path to another datasource while the layer +is loaded is not supported. Find Path state is saved with its datasource. diff --git a/eslint.config.js b/eslint.config.js index 16969c4d7d..93a3959817 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -115,6 +115,28 @@ export default tseslint.config( ], }, }, + { + files: ["src/skeleton/edit_queue/**/*.ts"], + + rules: { + "no-restricted-imports": [ + "error", + { + patterns: [ + { + group: ["./", "../"], + message: "Relative imports are not allowed.", + }, + { + regex: "^(?:#src/|src/)datasource(?:/|$)", + message: + "Generic optimistic edit modules must not depend on datasource implementations.", + }, + ], + }, + ], + }, + }, { files: ["build_tools/**/*.cjs"], languageOptions: { diff --git a/package.json b/package.json index 9a2b273664..dbddbdbe6e 100644 --- a/package.json +++ b/package.json @@ -29,7 +29,10 @@ "build-python:watch": "node ./build_tools/cli.ts --python build --watch", "test": "vitest --run", "test:watch": "vitest watch", - "example-project-test": "playwright test", + "test:skeleton:browser": "playwright test --project=skeleton-browser-integration --workers=1", + "test:skeleton:e2e": "playwright test --project=skeleton-e2e --workers=1", + "example-mock-catmaid": "vite-node tests/skeleton_edit/harness/serve_mock_catmaid.ts", + "example-project-test": "playwright test tests/example_project_test", "benchmark": "vitest bench --run", "benchmark:watch": "vitest bench", "lint:check": "oxlint && eslint . --cache --format codeframe", @@ -185,6 +188,25 @@ "neuroglancer/datasource/brainmaps:disabled": "./src/util/false.ts", "default": "./src/datasource/brainmaps/register_credentials_provider.ts" }, + "#datasource/catmaid/backend": { + "neuroglancer/datasource/catmaid:enabled": "./src/datasource/catmaid/backend.ts", + "neuroglancer/datasource:none_by_default": "./src/util/false.ts", + "neuroglancer/datasource/catmaid:disabled": "./src/util/false.ts", + "default": "./src/datasource/catmaid/backend.ts" + }, + "#datasource/catmaid/register_default": { + "neuroglancer/datasource/catmaid:enabled": "./src/datasource/catmaid/register_default.ts", + "neuroglancer/datasource:none_by_default": "./src/util/false.ts", + "neuroglancer/datasource/catmaid:disabled": "./src/util/false.ts", + "default": "./src/datasource/catmaid/register_default.ts" + }, + "#datasource/catmaid/register_credentials_provider": { + "neuroglancer/python": "./src/util/false.ts", + "neuroglancer/datasource/catmaid:enabled": "./src/datasource/catmaid/register_credentials_provider.ts", + "neuroglancer/datasource:none_by_default": "./src/util/false.ts", + "neuroglancer/datasource/catmaid:disabled": "./src/util/false.ts", + "default": "./src/datasource/catmaid/register_credentials_provider.ts" + }, "#datasource/deepzoom/backend": { "neuroglancer/datasource/deepzoom:enabled": "./src/datasource/deepzoom/backend.ts", "neuroglancer/datasource:none_by_default": "./src/util/false.ts", diff --git a/playwright.config.ts b/playwright.config.ts index fd598f38ae..ccea6c8fff 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -16,7 +16,11 @@ import { defineConfig } from "@playwright/test"; import exampleProjectTestConfig from "#tests/example_project_test/config.js"; +import skeletonEditTestConfig from "#tests/skeleton_edit/config.js"; export default defineConfig({ - projects: exampleProjectTestConfig.projects, + projects: [ + ...exampleProjectTestConfig.projects!, + ...skeletonEditTestConfig.projects!, + ], }); diff --git a/pyproject.toml b/pyproject.toml index 3a2258f514..fbb2362e91 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -67,6 +67,10 @@ ignore = [ "E501", # Line length regulated by ruff format ] +[tool.ruff.lint.per-file-ignores] +# These scripts run inside the CATMAID container and import Django after configuring it. +"tests/skeleton_edit/harness/docker/*.py" = ["E402"] + [tool.mypy] show_error_codes = true pretty = true @@ -95,6 +99,11 @@ module = [ "scipy.*", "cloudvolume", "trio", + "django", + "django.*", + "rest_framework.*", + "guardian.*", + "catmaid.*", ] ignore_missing_imports = true diff --git a/python/examples/example_spatial_skeletons.py b/python/examples/example_spatial_skeletons.py new file mode 100644 index 0000000000..df5b8a5f1d --- /dev/null +++ b/python/examples/example_spatial_skeletons.py @@ -0,0 +1,61 @@ +import argparse + +import neuroglancer +import neuroglancer.cli +import numpy as np + +voxel_size = np.array([10, 10, 10]) + +shape = (100, 100, 100) + +segmentation = np.arange(np.prod(shape), dtype=np.uint32).reshape(shape) + +viewer = neuroglancer.Viewer() +dimensions = neuroglancer.CoordinateSpace( + names=["x", "y", "z"], + units="nm", + scales=[10, 10, 10], +) +with viewer.txn() as s: + s.layers.append( + name="a", + layer=neuroglancer.SegmentationLayer( + source=[ + neuroglancer.LocalVolume( + data=segmentation, + dimensions=dimensions, + ), # example of segmentation that could accompany the skeleton + "catmaid://http://localhost:8000/4", # replace with your catmaid URL/project ID + ], + tab="skeleton", + ), + ) + # Can adjust the skeleton rendering options + s.layers[0].skeleton_rendering.mode2d = "lines" + s.layers[0].skeleton_rendering.line_width2d = 3 + s.layers[0].skeleton_rendering.mode3d = "lines_and_points" + s.layers[0].skeleton_rendering.line_width3d = 10 + + # Can adjust visibility of layer side panel + s.selected_layer.layer = "a" + s.selected_layer.visible = True + + # Can set the new spatial related options + layer = s.layers[0] + layer.skeleton_browse.node_query = "1" + layer.skeleton_browse.node_filter = neuroglancer.SkeletonNodeFilterType.LEAF + layer.hidden_object_alpha = 0.8 + layer.skeleton_cross_section_spacing = 4.0 + layer.skeleton_projection_spacing = 4.0 + layer.visible_segments = [649] + + # Can pick a specific segment and node to select + selection_for_layers = s.selection.layers + selection_for_layers["a"] = {"value": "649", "nodeId": "131"} + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + neuroglancer.cli.add_server_arguments(ap) + args = ap.parse_args() + neuroglancer.cli.handle_server_arguments(args) + print(viewer) diff --git a/python/neuroglancer/__init__.py b/python/neuroglancer/__init__.py index c216904838..a7a9998c0d 100644 --- a/python/neuroglancer/__init__.py +++ b/python/neuroglancer/__init__.py @@ -18,7 +18,10 @@ server, # noqa: F401 skeleton, # noqa: F401 ) -from .default_credentials_manager import set_boss_token # noqa: F401 +from .default_credentials_manager import ( # noqa: F401 + set_boss_token, + set_catmaid_token, +) from .equivalence_map import EquivalenceMap # noqa: F401 from .local_volume import LocalVolume # noqa: F401 from .screenshot import ScreenshotSaver # noqa: F401 @@ -91,6 +94,7 @@ InvlerpParameters, # noqa: F401 TransferFunctionParameters, # noqa: F401 ImageLayer, # noqa: F401 + SkeletonNodeFilterType, # noqa: F401 SkeletonRenderingOptions, # noqa: F401 StarredSegments, # noqa: F401 VisibleSegments, # noqa: F401 diff --git a/python/neuroglancer/catmaid_credentials.py b/python/neuroglancer/catmaid_credentials.py new file mode 100644 index 0000000000..92b20e47eb --- /dev/null +++ b/python/neuroglancer/catmaid_credentials.py @@ -0,0 +1,127 @@ +# @license +# Copyright 2026 Google Inc. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +import os +import threading +import urllib.request + +from . import credentials_provider +from .futures import run_on_new_thread + +_configured_tokens: dict[str, str] = {} +_providers: dict[str, "CatmaidCredentialsProvider"] = {} +_providers_lock = threading.Lock() + + +def canonicalize_server_url(server_url): + if not isinstance(server_url, str) or not server_url: + raise ValueError("CATMAID server URL must be a non-empty string") + return server_url.rstrip("/") + + +def set_token(server_url, token): + """Configure or remove a personal API token for one CATMAID server.""" + server_url = canonicalize_server_url(server_url) + with _providers_lock: + if token is None: + _configured_tokens.pop(server_url, None) + return + if not isinstance(token, str) or not token.strip(): + raise ValueError("CATMAID API token must be a non-empty string or None") + _configured_tokens[server_url] = token.strip() + + +def _get_environment_tokens(): + value = os.environ.get("CATMAID_CREDENTIALS") + if not value: + return {} + try: + parsed = json.loads(value) + except json.JSONDecodeError as error: + raise RuntimeError( + "CATMAID_CREDENTIALS must be a JSON object mapping server URLs to tokens" + ) from error + if not isinstance(parsed, dict) or any( + not isinstance(server_url, str) + or not isinstance(token, str) + or not token.strip() + for server_url, token in parsed.items() + ): + raise RuntimeError( + "CATMAID_CREDENTIALS must be a JSON object mapping server URLs to " + "non-empty string tokens" + ) + return { + canonicalize_server_url(server_url): token.strip() + for server_url, token in parsed.items() + } + + +def _get_configured_token(server_url): + with _providers_lock: + token = _configured_tokens.get(server_url) + if token is not None: + return token + return _get_environment_tokens().get(server_url) + + +class CatmaidCredentialsProvider(credentials_provider.CredentialsProvider): + def __init__(self, parameters): + super().__init__() + self.server_url = canonicalize_server_url( + (parameters or {}).get("serverUrl", "") + ) + self._last_personal_token = None + self._anonymous_token_was_returned = False + + def get_new(self): + server_url = self.server_url + + def func(): + personal_token = _get_configured_token(server_url) + if personal_token is not None: + if personal_token == self._last_personal_token: + raise RuntimeError( + f"The configured CATMAID API token for {server_url} was rejected" + ) + self._last_personal_token = personal_token + return {"token": personal_token, "kind": "personal"} + + if self._anonymous_token_was_returned: + raise RuntimeError( + f"CATMAID server {server_url} requires a personal API token; " + "call neuroglancer.set_catmaid_token or configure " + "CATMAID_CREDENTIALS" + ) + + token_url = f"{server_url}/accounts/anonymous-api-token" + with urllib.request.urlopen(token_url) as response: + data = json.loads(response.read().decode()) + if not isinstance(data, dict) or not isinstance(data.get("token"), str): + raise RuntimeError(f"Unexpected response from {token_url}: {data!r}") + self._anonymous_token_was_returned = True + return {"token": data["token"], "kind": "anonymous"} + + return run_on_new_thread(func) + + +def get_credentials_provider(parameters): + server_url = canonicalize_server_url((parameters or {}).get("serverUrl", "")) + with _providers_lock: + provider = _providers.get(server_url) + if provider is None: + provider = CatmaidCredentialsProvider({"serverUrl": server_url}) + _providers[server_url] = provider + return provider diff --git a/python/neuroglancer/default_credentials_manager.py b/python/neuroglancer/default_credentials_manager.py index 96139788d7..2056e43ef2 100644 --- a/python/neuroglancer/default_credentials_manager.py +++ b/python/neuroglancer/default_credentials_manager.py @@ -14,6 +14,7 @@ from . import ( boss_credentials, + catmaid_credentials, credentials_provider, dvid_credentials, google_credentials, @@ -46,6 +47,11 @@ ), ) +default_credentials_manager.register( + "CATMAID", + lambda parameters: catmaid_credentials.get_credentials_provider(parameters), +) + def set_boss_token(token): """Sets the authentication token for connecting to bossDB. @@ -54,3 +60,15 @@ def set_boss_token(token): credentials """ boss_credentials_provider.set_token(token) + + +def set_catmaid_token(server_url, token): + """Sets or removes a personal API token for a CATMAID server. + + Pass None as the token to remove a previously configured value. Tokens + should be configured before adding CATMAID layers. + + Group: + credentials + """ + catmaid_credentials.set_token(server_url, token) diff --git a/python/neuroglancer/read_precomputed_annotations.py b/python/neuroglancer/read_precomputed_annotations.py index 6f53f687a6..e4dfdd91ba 100644 --- a/python/neuroglancer/read_precomputed_annotations.py +++ b/python/neuroglancer/read_precomputed_annotations.py @@ -177,7 +177,7 @@ def _point_check_bounds(annotation, lower_bound, upper_bound): def _bbox_check_bounds(min_pt, max_pt, lower_bound, upper_bound): - return np.all(min_pt <= upper_bound) and np.all(max_pt <= lower_bound) + return np.all(min_pt <= upper_bound) and np.all(max_pt >= lower_bound) def _line_check_bounds(annotation, lower_bound, upper_bound): @@ -199,7 +199,7 @@ def _axis_aligned_bounding_box_check_bounds(annotation, lower_bound, upper_bound def _ellipsoid_check_bounds(annotation, lower_bound, upper_bound): - center = annotation.point_a + center = annotation.center radii = annotation.radii return _bbox_check_bounds(center - radii, center + radii, lower_bound, upper_bound) @@ -397,9 +397,20 @@ def __init__( viewer_state.AnnotationPropertySpec(prop) for prop in self.metadata.get("properties", []) ] + # Properties are encoded in order of decreasing alignment, which may + # differ from the order in which they are listed in the metadata. + alignments = [ + write_annotations._PROPERTY_DTYPES[p.type][1] for p in self.properties + ] + encoded_order = sorted( + range(len(self.properties)), key=lambda i: -alignments[i] + ) self._property_dtype = write_annotations._get_dtype_for_properties( - self.properties + [self.properties[i] for i in encoded_order] ) + self._property_field_names = [""] * len(self.properties) + for encoded_index, i in enumerate(encoded_order): + self._property_field_names[i] = f"property{encoded_index}" self._dtype = ( write_annotations._get_dtype_for_geometry( self.annotation_type, self.coordinate_space.rank @@ -430,7 +441,7 @@ def _decode_single_annotation( dtype = self._get_dtype(encoded) decoded = np.frombuffer(encoded, dtype=dtype, count=1)[0] geom = decoded["geometry"] - props = [decoded[f"property{i}"] for i in range(len(self.properties))] + props = [decoded[name] for name in self._property_field_names] offset = decoded.nbytes segments = [] for i in range(len(self.relationships)): @@ -473,12 +484,12 @@ def _decode_multiple_annotations( ) constructor = _ANNOTATION_TYPE_CONSTRUCTORS[self.annotation_type] rank = self.coordinate_space.rank - num_properties = len(self.properties) + property_field_names = self._property_field_names return [ constructor( decoded[annotation_i]["geometry"], rank, - [decoded[annotation_i][f"property{i}"] for i in range(num_properties)], + [decoded[annotation_i][name] for name in property_field_names], None, str(ids[annotation_i]), ) diff --git a/python/neuroglancer/viewer_state.py b/python/neuroglancer/viewer_state.py index 126334ed72..7e5946d151 100644 --- a/python/neuroglancer/viewer_state.py +++ b/python/neuroglancer/viewer_state.py @@ -18,6 +18,7 @@ import collections import collections.abc import copy +import enum import math import numbers import os @@ -745,6 +746,26 @@ def _linked_segmentation_color_group_value(x): raise ValueError(f"Expected str or False, but received: {x!r}") +@export +class SkeletonNodeFilterType(enum.StrEnum): + DEFAULT = "default" + NONE = "none" + LEAF = "leaf" + VIRTUAL_END = "virtual_end" + TRUE_END = "true_end" + HAS_DESCRIPTION = "has_description" + + +@export +class SkeletonBrowseState(JsonObjectWrapper): + __slots__ = () + + node_query = nodeQuery = wrapped_property("nodeQuery", optional(str, "")) + node_filter = nodeFilter = wrapped_property( + "nodeFilter", optional(SkeletonNodeFilterType) + ) + + @export class SkeletonRenderingOptions(JsonObjectWrapper): __slots__ = () @@ -1081,12 +1102,27 @@ def skeleton_shader(self, shader): "meshSilhouetteRendering", optional(float, 0) ) segment_query = segmentQuery = wrapped_property("segmentQuery", optional(str)) + skeleton_browse = skeletonBrowse = wrapped_property( + "skeletonBrowse", SkeletonBrowseState + ) + hidden_object_alpha = hiddenObjectAlpha = wrapped_property( + "hiddenObjectAlpha", optional(float, 0.5) + ) + skeleton_cross_section_spacing = skeletonCrossSectionSpacing = wrapped_property( + "skeletonCrossSectionSpacing", optional(float, 8) + ) + skeleton_projection_spacing = skeletonProjectionSpacing = wrapped_property( + "skeletonProjectionSpacing", optional(float, 8) + ) segment_colors = segmentColors = wrapped_property( "segmentColors", typed_map(key_type=np.uint64, value_type=str) ) segment_default_color = segmentDefaultColor = wrapped_property( "segmentDefaultColor", optional(str) ) + segment_color_shader = segmentColorShader = wrapped_property( + "segmentColorShader", optional(str) + ) @property def segment_html_color_dict(self): @@ -1959,6 +1995,7 @@ class LayerSelectionState(JsonObjectWrapper): annotation_subsource = annotationSubsource = wrapped_property( "annotationSubsource", optional(str) ) + node_id = nodeId = wrapped_property("nodeId", optional(str)) if typing.TYPE_CHECKING or _BUILDING_DOCS: diff --git a/python/tests/catmaid_credentials_test.py b/python/tests/catmaid_credentials_test.py new file mode 100644 index 0000000000..64db540da1 --- /dev/null +++ b/python/tests/catmaid_credentials_test.py @@ -0,0 +1,119 @@ +# @license +# Copyright 2026 Google Inc. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import io +import json +from unittest import mock + +import pytest +from neuroglancer import catmaid_credentials + + +def get_credentials(provider, invalid_generation=None): + return provider.get(invalid_generation).result(timeout=2) + + +def test_runtime_token_precedes_environment(monkeypatch): + server_url = "https://runtime-token.catmaid.example" + monkeypatch.setenv( + "CATMAID_CREDENTIALS", json.dumps({server_url: "environment-token"}) + ) + catmaid_credentials.set_token(server_url + "/", " runtime-token ") + try: + provider = catmaid_credentials.CatmaidCredentialsProvider( + {"serverUrl": server_url} + ) + assert get_credentials(provider)["credentials"] == { + "token": "runtime-token", + "kind": "personal", + } + finally: + catmaid_credentials.set_token(server_url, None) + + +def test_environment_token_is_normalized(monkeypatch): + server_url = "https://environment-token.catmaid.example" + monkeypatch.setenv( + "CATMAID_CREDENTIALS", + json.dumps({server_url + "/": " environment-token "}), + ) + provider = catmaid_credentials.CatmaidCredentialsProvider( + {"serverUrl": server_url + "/"} + ) + + assert get_credentials(provider)["credentials"] == { + "token": "environment-token", + "kind": "personal", + } + + +def test_anonymous_token_is_used_without_configuration(monkeypatch): + server_url = "https://anonymous.catmaid.example" + monkeypatch.delenv("CATMAID_CREDENTIALS", raising=False) + provider = catmaid_credentials.CatmaidCredentialsProvider( + {"serverUrl": server_url + "/"} + ) + response = io.BytesIO(json.dumps({"token": "anonymous-token"}).encode()) + + with mock.patch( + "neuroglancer.catmaid_credentials.urllib.request.urlopen", + return_value=response, + ) as urlopen: + credentials = get_credentials(provider) + + assert credentials["credentials"] == { + "token": "anonymous-token", + "kind": "anonymous", + } + urlopen.assert_called_once_with(server_url + "/accounts/anonymous-api-token") + + with pytest.raises(RuntimeError, match="requires a personal API token"): + get_credentials(provider, credentials["generation"]) + + +def test_rejected_personal_token_requires_reconfiguration(monkeypatch): + server_url = "https://rejected-token.catmaid.example" + monkeypatch.setenv( + "CATMAID_CREDENTIALS", json.dumps({server_url: "rejected-token"}) + ) + provider = catmaid_credentials.CatmaidCredentialsProvider({"serverUrl": server_url}) + credentials = get_credentials(provider) + + with pytest.raises(RuntimeError, match="was rejected"): + get_credentials(provider, credentials["generation"]) + + +def test_malformed_environment_configuration_is_rejected(monkeypatch): + monkeypatch.setenv("CATMAID_CREDENTIALS", "[]") + provider = catmaid_credentials.CatmaidCredentialsProvider( + {"serverUrl": "https://invalid-config.catmaid.example"} + ) + + with pytest.raises(RuntimeError, match="must be a JSON object"): + get_credentials(provider) + + +def test_provider_cache_is_scoped_by_canonical_server_url(): + first = catmaid_credentials.get_credentials_provider( + {"serverUrl": "https://cached.catmaid.example/"} + ) + second = catmaid_credentials.get_credentials_provider( + {"serverUrl": "https://cached.catmaid.example"} + ) + other = catmaid_credentials.get_credentials_provider( + {"serverUrl": "https://other.catmaid.example"} + ) + + assert first is second + assert first is not other diff --git a/python/tests/read_precomputed_annotations_test.py b/python/tests/read_precomputed_annotations_test.py new file mode 100644 index 0000000000..c67c358dfe --- /dev/null +++ b/python/tests/read_precomputed_annotations_test.py @@ -0,0 +1,141 @@ +# @license +# Copyright 2026 Google Inc. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pathlib + +import neuroglancer +import numpy as np +import pytest +from neuroglancer import write_annotations + +pytest.importorskip("tensorstore") + +from neuroglancer import read_precomputed_annotations # noqa: E402 + + +def _coordinate_space(rank: int = 3): + return neuroglancer.CoordinateSpace( + names=["x", "y", "z"][:rank], units="nm", scales=[1] * rank + ) + + +def _open_reader(path: pathlib.Path): + return read_precomputed_annotations.AnnotationReader( + {"driver": "file", "path": str(path)} + ) + + +def _props_by_id(reader, annotation): + return { + p.id: np.asarray(v).tolist() + for p, v in zip(reader.properties, annotation.props) + } + + +def test_properties_not_sorted_by_alignment(tmp_path: pathlib.Path): + # Properties are listed in an order that differs from the encoded order + # (decreasing alignment). + properties = [ + neuroglancer.AnnotationPropertySpec(id="color", type="rgb"), + neuroglancer.AnnotationPropertySpec(id="flag", type="uint8"), + neuroglancer.AnnotationPropertySpec(id="size", type="float32"), + neuroglancer.AnnotationPropertySpec(id="cell_type", type="uint16"), + ] + writer = write_annotations.AnnotationWriter( + coordinate_space=_coordinate_space(), + annotation_type="point", + properties=properties, + ) + writer.add_point( + [1, 2, 3], id=5, color=(10, 20, 30), flag=7, size=2.5, cell_type=16 + ) + writer.add_point( + [4, 5, 6], id=6, color=(40, 50, 60), flag=8, size=0.5, cell_type=17 + ) + writer.write(tmp_path) + + reader = _open_reader(tmp_path) + expected = { + "5": {"color": [10, 20, 30], "flag": 7, "size": 2.5, "cell_type": 16}, + "6": {"color": [40, 50, 60], "flag": 8, "size": 0.5, "cell_type": 17}, + } + assert [p.id for p in reader.properties] == [p.id for p in properties] + assert _props_by_id(reader, reader.by_id[5]) == expected["5"] + assert _props_by_id(reader, reader.by_id[6]) == expected["6"] + assert { + a.id: _props_by_id(reader, a) for a in reader.get_within_spatial_bounds() + } == expected + + +def test_polyline_properties_not_sorted_by_alignment(tmp_path: pathlib.Path): + properties = [ + neuroglancer.AnnotationPropertySpec(id="color", type="rgba"), + neuroglancer.AnnotationPropertySpec(id="cell_type", type="uint16"), + neuroglancer.AnnotationPropertySpec(id="size", type="float32"), + ] + writer = write_annotations.AnnotationWriter( + coordinate_space=_coordinate_space(), + annotation_type="polyline", + properties=properties, + ) + writer.add_polyline( + [[0, 0, 0], [1, 2, 3], [4, 5, 6]], + id=1, + color=(1, 2, 3, 4), + cell_type=12, + size=6, + ) + writer.write(tmp_path) + + reader = _open_reader(tmp_path) + expected = {"color": [1, 2, 3, 4], "cell_type": 12, "size": 6.0} + assert _props_by_id(reader, reader.by_id[1]) == expected + (annotation,) = reader.get_within_spatial_bounds() + assert _props_by_id(reader, annotation) == expected + + +def test_get_within_spatial_bounds_line(tmp_path: pathlib.Path): + lines = { + 0: ([0, 0, 0], [10, 10, 10]), # Passes through the query box. + 1: ([40, 40, 40], [50, 50, 50]), # Entirely above the query box. + 2: ([0, 0, 0], [1, 1, 1]), # Entirely below the query box. + } + writer = write_annotations.AnnotationWriter( + coordinate_space=_coordinate_space(), annotation_type="line" + ) + for annotation_id, (point_a, point_b) in lines.items(): + writer.add_line(point_a, point_b, id=annotation_id) + writer.write(tmp_path) + + reader = _open_reader(tmp_path) + assert sorted(a.id for a in reader.get_within_spatial_bounds()) == ["0", "1", "2"] + result = reader.get_within_spatial_bounds( + lower_bound=[4, 4, 4], upper_bound=[6, 6, 6] + ) + assert [a.id for a in result] == ["0"] + + +def test_get_within_spatial_bounds_ellipsoid(tmp_path: pathlib.Path): + writer = write_annotations.AnnotationWriter( + coordinate_space=_coordinate_space(), annotation_type="ellipsoid" + ) + writer.add_ellipsoid([5, 5, 5], [20, 20, 20], id=0) + writer.write(tmp_path) + + reader = _open_reader(tmp_path) + # The query box lies within `[center - radii, center + radii]`. + result = reader.get_within_spatial_bounds( + lower_bound=[6, 6, 6], upper_bound=[8, 8, 8] + ) + assert [a.id for a in result] == ["0"] diff --git a/python/tests/skeleton_options_test.py b/python/tests/skeleton_options_test.py index 2d01eae19d..29e2245b7e 100644 --- a/python/tests/skeleton_options_test.py +++ b/python/tests/skeleton_options_test.py @@ -62,20 +62,52 @@ def test_skeleton_options(webdriver): s.layers[0].skeleton_rendering.shader_controls["color"] = "#f00" s.show_axis_lines = False screenshot = webdriver.viewer.screenshot(size=[10, 10]).screenshot + opaque_pixels_2d = screenshot.image_pixels.copy() np.testing.assert_array_equal( - screenshot.image_pixels, + opaque_pixels_2d, np.tile(np.array([255, 0, 0, 255], dtype=np.uint8), (10, 10, 1)), ) + with webdriver.viewer.txn() as s: + s.layers[0].source[0].subsources["default"] = False + background_pixels_2d = webdriver.viewer.screenshot( + size=[10, 10] + ).screenshot.image_pixels.copy() + + with webdriver.viewer.txn() as s: + s.layers[0].source[0].subsources["default"] = True + s.layers[0].object_alpha = 0.5 + screenshot = webdriver.viewer.screenshot(size=[10, 10]).screenshot + pixels = screenshot.image_pixels + np.testing.assert_allclose( + pixels[..., :3], + opaque_pixels_2d[..., :3] * 0.5 + background_pixels_2d[..., :3] * 0.5, + atol=2, + ) + np.testing.assert_array_equal(pixels[..., 3], 255) + with webdriver.viewer.txn() as s: s.layout = "3d" + s.layers[0].object_alpha = 1.0 s.layers[0].skeleton_rendering.line_width3d = 100 screenshot = webdriver.viewer.screenshot(size=[10, 10]).screenshot + opaque_pixels = screenshot.image_pixels.copy() np.testing.assert_array_equal( - screenshot.image_pixels, + opaque_pixels, np.tile(np.array([255, 0, 0, 255], dtype=np.uint8), (10, 10, 1)), ) + # Perspective OIT requires premultiplied RGB, so reducing opacity must + # reduce the red intensity rather than leave it saturated or brighten it. + with webdriver.viewer.txn() as s: + s.layers[0].object_alpha = 0.5 + screenshot = webdriver.viewer.screenshot(size=[10, 10]).screenshot + pixels = screenshot.image_pixels + np.testing.assert_allclose(pixels[..., 0], opaque_pixels[..., 0] * 0.5, atol=2) + np.testing.assert_array_equal(pixels[..., 1], 0) + np.testing.assert_array_equal(pixels[..., 2], 0) + np.testing.assert_array_equal(pixels[..., 3], 255) + with webdriver.viewer.txn() as s: s.layers[0].source[0].subsources["default"] = False @@ -89,9 +121,20 @@ def test_skeleton_options(webdriver): @pytest.mark.parametrize("layout", ["xy", "3d"]) @pytest.mark.parametrize("primitive", ["edge", "node"]) @pytest.mark.parametrize( - "shader_alpha,layer_alpha", [(1, 1), (0.5, 1), (1, 0.5), (0.5, 0.5)] + "shader_output,shader_alpha", + [ + ("rgba", 1), + ("rgba", 0.5), + ("rgb", 1), + ("default", 1), + ("segment-rgb", 1), + ("segment-rgba", 1), + ], ) -def test_skeleton_rgba_opacity(webdriver, layout, primitive, shader_alpha, layer_alpha): +@pytest.mark.parametrize("layer_alpha", [1, 0.5]) +def test_skeleton_opacity( + webdriver, layout, primitive, shader_output, shader_alpha, layer_alpha +): if primitive == "edge": source = SkeletonSource( vertex_positions=[[-100, 0, 0], [100, 0, 0]], @@ -117,6 +160,7 @@ def test_skeleton_rgba_opacity(webdriver, layout, primitive, shader_alpha, layer source=source, segments=[1], object_alpha=layer_alpha, + segment_colors={1: "#ff8040"}, ), ) rendering = s.layers[0].skeleton_rendering @@ -124,13 +168,75 @@ def test_skeleton_rgba_opacity(webdriver, layout, primitive, shader_alpha, layer rendering.mode3d = "lines" rendering.line_width2d = 16 rendering.line_width3d = 16 - rendering.shader = f""" + if shader_output == "rgba": + rendering.shader = f""" void main() {{ emitRGBA(vec4(1.0, 0.5, 0.25, {shader_alpha:.1f})); }} """ + elif shader_output == "rgb": + rendering.shader = "void main() { emitRGB(vec3(1.0, 0.5, 0.25)); }" + elif shader_output == "default": + rendering.shader = "void main() { emitDefault(); }" + elif shader_output == "segment-rgb": + rendering.shader = "void main() { emitRGB(segmentColor().rgb); }" + else: + rendering.shader = "void main() { emitRGBA(segmentColor()); }" pixels = webdriver.viewer.screenshot(size=[32, 32]).screenshot.image_pixels - expected_rgb = np.array([1.0, 0.5, 0.25]) * shader_alpha * layer_alpha * 255 + color = ( + np.array([255, 128, 64]) + if shader_output in ("default", "segment-rgb", "segment-rgba") + else np.array([255, 127.5, 63.75]) + ) + expected_rgb = color * shader_alpha * layer_alpha expected = np.tile(np.append(expected_rgb, 255), (4, 4, 1)) np.testing.assert_allclose(pixels[14:18, 14:18], expected, atol=2, rtol=0) + + +def test_segment_color_shader_alpha_makes_skeleton_transparent(webdriver): + image_data = np.zeros((20, 20, 20), dtype=np.uint8) + image_data[1:19, 1:19, 11:20] = 255 + + with webdriver.viewer.txn() as s: + s.dimensions = dimensions + s.layers.append( + name="image", + layer=neuroglancer.ImageLayer( + source=neuroglancer.LocalVolume(data=image_data, dimensions=dimensions), + volume_rendering_mode="Max", + shader=""" +#uicontrol invlerp normalized +void main() { + emitRGBA(vec4(0.0, 0.0, normalized(), 1.0)); +} +""", + ), + ) + s.layers.append( + name="skeleton", + layer=neuroglancer.SegmentationLayer( + source=SkeletonSource(vertex_positions=[(10, 10, 5)]), + segments=[1], + segment_color_shader=""" +vec4 segmentColor(vec4 color, bool hasProperties, bool isStated) { + return vec4(color.rgb, 0.5); +} +""", + skeleton_shader=""" +void main() { + emitRGB(vec3(1.0, 0.0, 0.0)); +} +""", + ), + ) + s.layers["skeleton"].skeleton_rendering.line_width3d = 100 + s.layout = "3d" + s.show_axis_lines = False + s.position = [10, 10, 10] + s.projection_scale = 15 + + webdriver.sync() + pixels = webdriver.viewer.screenshot(size=[10, 10]).screenshot.image_pixels + assert np.all(pixels[..., 0] > 0) + assert np.all(pixels[..., 2] > 0) diff --git a/python/tests/volume_rendering_test.py b/python/tests/volume_rendering_test.py index edc89cd0b7..4b4eaacbb2 100644 --- a/python/tests/volume_rendering_test.py +++ b/python/tests/volume_rendering_test.py @@ -126,6 +126,41 @@ def test_volume_rendering_occlusion(webdriver, orthographic): np.testing.assert_array_equal(pixels, volume_pixels) +@pytest.mark.parametrize("orthographic", [False, True]) +def test_transparent_mesh_color_is_premultiplied(webdriver, orthographic): + _setup_viewer_with_volume_and_mesh(webdriver, orthographic=orthographic) + + webdriver.sync() + opaque_pixels = webdriver.viewer.screenshot(size=[10, 10]).screenshot.image_pixels + + with webdriver.viewer.txn() as s: + s.layers["seg"].object_alpha = 0.5 + + webdriver.sync() + transparent_pixels = webdriver.viewer.screenshot( + size=[10, 10] + ).screenshot.image_pixels + assert np.all(transparent_pixels[..., 0] > 0) + assert np.all(transparent_pixels[..., 0] < opaque_pixels[..., 0]) + + +@pytest.mark.parametrize("orthographic", [False, True]) +def test_segment_color_shader_alpha_makes_mesh_transparent(webdriver, orthographic): + _setup_viewer_with_volume_and_mesh(webdriver, orthographic=orthographic) + + with webdriver.viewer.txn() as s: + s.layers["seg"].segment_color_shader = """ +vec4 segmentColor(vec4 color, bool hasProperties, bool isStated) { + return vec4(color.rgb, 0.5); +} +""" + + webdriver.sync() + pixels = webdriver.viewer.screenshot(size=[10, 10]).screenshot.image_pixels + assert np.all(pixels[..., 0] > 0) + assert np.all(pixels[..., 2] > 0) + + @pytest.mark.parametrize("orthographic", [False, True]) def test_volume_rendering_picking_does_not_occlude_mesh(webdriver, orthographic): """Volume rendering must not steal pick buffer entries from a transparent entry in front of it. diff --git a/src/annotation/type_handler.browser_test.ts b/src/annotation/type_handler.browser_test.ts new file mode 100644 index 0000000000..126e97b8e6 --- /dev/null +++ b/src/annotation/type_handler.browser_test.ts @@ -0,0 +1,107 @@ +/** + * @license + * Copyright 2026 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import "#src/annotation/bounding_box.js"; +import "#src/annotation/ellipsoid.js"; +import "#src/annotation/line.js"; +import "#src/annotation/point.js"; +import "#src/annotation/polyline.js"; + +import { describe, expect, it } from "vitest"; +import type { AnnotationPropertySpec } from "#src/annotation/index.js"; +import { AnnotationType } from "#src/annotation/index.js"; +import { + type AnnotationShaderGetter, + getAnnotationTypeRenderHandler, +} from "#src/annotation/type_handler.js"; +import { WatchableValue } from "#src/trackable_value.js"; +import { initializeWebGL } from "#src/webgl/context.js"; +import { + makeTrackableFragmentMain, + makeWatchableShaderError, +} from "#src/webgl/dynamic_shader.js"; +import { + getFallbackBuilderState, + parseShaderUiControls, + ShaderControlState, +} from "#src/webgl/shader_ui_controls.js"; + +describe("annotation property shaders", () => { + it("compiles a shader that colors by boolean property", () => { + const canvas = document.createElement("canvas"); + const gl = initializeWebGL(canvas); + const fragmentMain = makeTrackableFragmentMain(` +void main() { + if (prop_highlight() != 0u) { + setColor(vec3(1.0, 0.0, 0.0)); + } else { + setColor(vec3(0.0, 0.0, 1.0)); + } +} +`); + const shaderControlState = new ShaderControlState(fragmentMain); + const fallbackShaderParameters = new WatchableValue( + getFallbackBuilderState(parseShaderUiControls(fragmentMain.value)), + ); + const shaderError = makeWatchableShaderError(); + const properties: AnnotationPropertySpec[] = [ + { + identifier: "highlight", + description: undefined, + type: "bool", + default: 0, + }, + ]; + const renderHandler = getAnnotationTypeRenderHandler(AnnotationType.POINT); + const renderHelper = new renderHandler.perspectiveViewRenderHelper( + gl, + AnnotationType.POINT, + /*rank=*/ 3, + properties, + shaderControlState, + fallbackShaderParameters, + shaderError, + ); + renderHelper.targetIsSliceView = false; + renderHelper.pickIdsPerInstance = renderHandler.pickIdsPerInstance; + + const shaderGetter = ( + renderHelper as typeof renderHelper & { + shaderGetter3d: AnnotationShaderGetter; + } + ).shaderGetter3d; + const shaderResult = shaderGetter((builder) => { + builder.addOutputBuffer("vec4", "out_color", 0); + builder.addFragmentCode(` +void emit(vec4 color, highp uint pickId) { + out_color = color; +} +`); + }); + + expect(shaderError.value).toBeNull(); + expect(shaderResult.shader).not.toBeNull(); + expect(shaderResult.shader!.vertexSource).toContain( + "highp uint prop_highlight()", + ); + expect(shaderResult.shader!.vertexSource).toContain( + "if (prop_highlight() != 0u)", + ); + + renderHelper.dispose(); + shaderControlState.dispose(); + }); +}); diff --git a/src/annotation/type_handler.ts b/src/annotation/type_handler.ts index 58a8872690..5f1454fd17 100644 --- a/src/annotation/type_handler.ts +++ b/src/annotation/type_handler.ts @@ -42,6 +42,7 @@ import { parameterizedEmitterDependentShaderGetter, shaderCodeWithLineDirective, } from "#src/webgl/dynamic_shader.js"; +import { copyHistogramToCPU } from "#src/webgl/empirical_cdf.js"; import { defineInvlerpShaderFunction, enableLerpShaderFunction, @@ -269,10 +270,10 @@ class AnnotationRenderHelperBase extends RefCounted { protected defineProperties( builder: ShaderBuilder, - referencedProperties: number[], + annotationPropertyIndices: number[], ) { const { properties, rank } = this; - for (const i of referencedProperties) { + for (const i of annotationPropertyIndices) { const property = properties[i]; const handler = annotationPropertyTypeRenderHandlers[property.type]; handler.defineShader(builder, property.identifier, rank); @@ -280,7 +281,7 @@ class AnnotationRenderHelperBase extends RefCounted { const { propertyOffsets } = this; const { propertyGroupBytes, propertyGroupCumulativeBytes } = this; builder.addInitializer((shader) => { - const binders = referencedProperties.map( + const binders = annotationPropertyIndices.map( (i) => shader.vertexShaderInputBinders[`prop_${properties[i].identifier}`], ); @@ -294,7 +295,7 @@ class AnnotationRenderHelperBase extends RefCounted { bind(stride: number, offset: number) { for (let i = 0; i < numProperties; ++i) { const { group, offset: propertyOffset } = - propertyOffsets[referencedProperties[i]]; + propertyOffsets[annotationPropertyIndices[i]]; binders[i].bind( /*stride=*/ propertyGroupBytes[group], /*offset=*/ offset + @@ -350,8 +351,11 @@ export abstract class AnnotationRenderHelper extends AnnotationRenderHelperBase parameters: ShaderControlsBuilderState, ) => { const { rank, properties } = this; - const referencedProperties: number[] = []; - const controlsReferencedProperties = parameters.referencedProperties; + const annotationPropertyIndices: number[] = []; + const controlAnnotationProperties = + parameters.propertyReferences.source === "annotation" + ? parameters.propertyReferences.references + : []; const processedCode = parameters.parseResult.code; for ( let i = 0, numProperties = properties.length; @@ -361,14 +365,14 @@ export abstract class AnnotationRenderHelper extends AnnotationRenderHelperBase const property = properties[i]; const functionName = `prop_${property.identifier}`; if ( - !controlsReferencedProperties.includes(property.identifier) && + !controlAnnotationProperties.includes(property.identifier) && !processedCode.match(new RegExp(`\\b${functionName}\\b`)) ) { continue; } - referencedProperties.push(i); + annotationPropertyIndices.push(i); } - this.defineProperties(builder, referencedProperties); + this.defineProperties(builder, annotationPropertyIndices); builder.addUniform("highp vec3", "uColor"); builder.addUniform("highp uint", "uSelectedIndex"); builder.addVarying("highp vec4", "vColor"); @@ -445,7 +449,7 @@ float getMaxSubspaceClipCoefficient(float modelPointA[${this.rank}], float mode } `); - addControlsToBuilder(parameters, builder); + addControlsToBuilder(parameters, builder, /*fragment=*/ false); builder.addVertexCode(` const bool PROJECTION_VIEW = ${!this.targetIsSliceView}; bool ng_discardValue; @@ -782,21 +786,12 @@ gl_PointSize = 1.0; } gl.drawArrays(WebGL2RenderingContext.POINTS, 0, context.count); if (DEBUG_HISTOGRAMS) { - const tempBuffer = new Float32Array(256 * 4); - gl.readPixels( - 0, - 0, - 256, - 1, - WebGL2RenderingContext.RGBA, - WebGL2RenderingContext.FLOAT, - tempBuffer, + const histogram = copyHistogramToCPU(gl); + console.log( + "histogram property:", + propertyIdentifier, + histogram.join(" "), ); - const tempBuffer2 = new Float32Array(256); - for (let j = 0; j < 256; ++j) { - tempBuffer2[j] = tempBuffer[j * 4]; - } - console.log("histogram", tempBuffer2.join(" ")); } binder.disable(); break; diff --git a/src/datasource/catmaid/api.spec.ts b/src/datasource/catmaid/api.spec.ts new file mode 100644 index 0000000000..3c23d0c02f --- /dev/null +++ b/src/datasource/catmaid/api.spec.ts @@ -0,0 +1,1360 @@ +/** + * @license + * Copyright 2026 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { pack } from "msgpackr"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { + CredentialsProvider, + type CredentialsWithGeneration, +} from "#src/credentials_provider/index.js"; +import { + CatmaidClient, + getDefaultCatmaidChunkSize, + type CatmaidToken, +} from "#src/datasource/catmaid/api.js"; +import { HttpError } from "#src/util/http_request.js"; + +type FetchMock = ReturnType; + +function getFetchCall(fetchMock: FetchMock, callIndex = 0) { + const call = fetchMock.mock.calls[callIndex]; + if (call === undefined) { + throw new Error(`Expected fetch call ${callIndex + 1} to exist.`); + } + return call; +} + +function getFetchPath(fetchMock: FetchMock, callIndex = 0) { + return getFetchCall(fetchMock, callIndex)[0]; +} + +function getFetchBody(fetchMock: FetchMock, callIndex = 0) { + const [, requestInit] = getFetchCall(fetchMock, callIndex); + if (requestInit === undefined || typeof requestInit !== "object") { + throw new Error( + `Expected fetch call ${callIndex + 1} to include request options.`, + ); + } + const body = (requestInit as { body?: unknown }).body; + if (!(body instanceof URLSearchParams)) { + throw new Error( + `Expected fetch call ${callIndex + 1} to include a URLSearchParams body.`, + ); + } + return body; +} + +function getFetchInit(fetchMock: FetchMock, callIndex = 0) { + const [, requestInit] = getFetchCall(fetchMock, callIndex); + if (requestInit === undefined || typeof requestInit !== "object") { + throw new Error( + `Expected fetch call ${callIndex + 1} to include request options.`, + ); + } + return requestInit as RequestInit & { priority?: unknown }; +} + +class SequenceCredentialsProvider extends CredentialsProvider { + calls: Array | undefined> = []; + + constructor(private credentials: CatmaidToken[]) { + super(); + } + + get: CredentialsProvider["get"] = async ( + invalidCredentials, + ) => { + this.calls.push(invalidCredentials); + const index = Math.min(this.calls.length - 1, this.credentials.length - 1); + return { + generation: this.calls.length, + credentials: this.credentials[index], + }; + }; +} + +function jsonResponse(value: unknown, status = 200) { + return new Response(JSON.stringify(value), { + status, + statusText: status === 200 ? "OK" : "Forbidden", + headers: { "Content-Type": "application/json" }, + }); +} + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe("CatmaidClient", () => { + it("does not cache transient metadata discovery failures as null", async () => { + const client = new CatmaidClient("https://example.invalid", 1); + const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); + (client as any).listStacks = vi + .fn() + .mockRejectedValueOnce(new Error("temporary stack lookup failure")) + .mockResolvedValueOnce([{ id: 7, title: "stack" }]); + (client as any).getStackInfo = vi.fn().mockResolvedValue({ + dimension: { x: 10, y: 20, z: 30 }, + resolution: { x: 2, y: 3, z: 4 }, + translation: { x: 5, y: 6, z: 7 }, + metadata: { + spatial: [{ chunk_size: [15, 15, 15], limit: 1 }], + }, + }); + + await expect(client.getSpatialIndexMetadata()).resolves.toBeNull(); + await expect(client.getSpatialIndexMetadata()).resolves.toEqual({ + bounds: { + lowerBounds: Float64Array.of(5, 6, 7), + upperBounds: Float64Array.of(25, 66, 127), + }, + readonly: true, + spatial: [ + { + chunkSize: [15, 15, 15], + limit: 1, + }, + ], + }); + + expect((client as any).listStacks).toHaveBeenCalledTimes(2); + expect((client as any).getStackInfo).toHaveBeenCalledTimes(1); + warnSpy.mockRestore(); + }); + + it("reports a stack as editable when its metadata says it is not read-only", async () => { + const client = new CatmaidClient("https://example.invalid", 1); + (client as any).listStacks = vi.fn().mockResolvedValue([{ id: 7 }]); + (client as any).getStackInfo = vi.fn().mockResolvedValue({ + dimension: { x: 10, y: 20, z: 30 }, + resolution: { x: 2, y: 3, z: 4 }, + translation: { x: 5, y: 6, z: 7 }, + metadata: { + read_only: false, + spatial: [{ chunk_size: [15, 15, 15], limit: 1 }], + }, + }); + + await expect(client.getSpatialIndexMetadata()).resolves.toMatchObject({ + readonly: false, + }); + }); + + it.each([ + ["missing", {}], + ["empty", { spatial: [] }], + ])( + "falls back to one default level when the stack lists no spatial levels (%s)", + async (_case, metadata) => { + const client = new CatmaidClient("https://example.invalid", 1); + (client as any).listStacks = vi.fn().mockResolvedValue([{ id: 7 }]); + (client as any).getStackInfo = vi.fn().mockResolvedValue({ + dimension: { x: 10, y: 20, z: 30 }, + resolution: { x: 2, y: 3, z: 4 }, + translation: { x: 5, y: 6, z: 7 }, + metadata, + }); + + await expect(client.getSpatialIndexMetadata()).resolves.toEqual({ + bounds: { + lowerBounds: Float64Array.of(5, 6, 7), + upperBounds: Float64Array.of(25, 66, 127), + }, + readonly: true, + spatial: [ + { + chunkSize: [15, 15, 15], + limit: 0, + }, + ], + }); + }, + ); + + it("reads the spatial index levels and cache provider from stack metadata", async () => { + const client = new CatmaidClient("https://example.invalid", 1); + (client as any).listStacks = vi.fn().mockResolvedValue([{ id: 7 }]); + (client as any).getStackInfo = vi.fn().mockResolvedValue({ + dimension: { x: 10, y: 20, z: 30 }, + resolution: { x: 2, y: 3, z: 4 }, + translation: { x: 5, y: 6, z: 7 }, + metadata: { + cache_provider: "cached_msgpack_grid", + read_only: true, + spatial: [ + { + chunk_size: [11168145, 11168145, 11168145], + limit: 500, + }, + { + chunk_size: [6632497, 6632497, 6632497], + limit: 500, + }, + { + chunk_size: [3939000, 3939000, 3939000], + limit: 7000, + }, + { + chunk_size: [2339000, 2339000, 2339000], + limit: 27500, + }, + { + chunk_size: [1500000, 1500000, 1500000], + limit: 70000, + }, + ], + }, + }); + + await expect(client.getSpatialIndexMetadata()).resolves.toEqual({ + bounds: { + lowerBounds: Float64Array.of(5, 6, 7), + upperBounds: Float64Array.of(25, 66, 127), + }, + readonly: true, + spatial: [ + { + chunkSize: [11168145, 11168145, 11168145], + limit: 500, + }, + { + chunkSize: [6632497, 6632497, 6632497], + limit: 500, + }, + { + chunkSize: [3939000, 3939000, 3939000], + limit: 7000, + }, + { + chunkSize: [2339000, 2339000, 2339000], + limit: 27500, + }, + { + chunkSize: [1500000, 1500000, 1500000], + limit: 70000, + }, + ], + }); + await expect(client.getCacheProvider()).resolves.toBe( + "cached_msgpack_grid", + ); + }); + + it("lists anisotropic levels from coarsest to finest whatever order the stack metadata gives", async () => { + const client = new CatmaidClient("https://example.invalid", 1); + (client as any).listStacks = vi.fn().mockResolvedValue([{ id: 7 }]); + (client as any).getStackInfo = vi.fn().mockResolvedValue({ + dimension: { x: 10, y: 20, z: 30 }, + resolution: { x: 2, y: 3, z: 4 }, + translation: { x: 5, y: 6, z: 7 }, + metadata: { + spatial: [ + { chunk_size: [2000, 2000, 40], limit: 0 }, + { chunk_size: [4000, 4000, 40], limit: 500 }, + ], + }, + }); + + const metadata = await client.getSpatialIndexMetadata(); + + expect(metadata?.spatial).toEqual([ + { chunkSize: [4000, 4000, 40], limit: 500 }, + { chunkSize: [2000, 2000, 40], limit: 0 }, + ]); + }); + + it("accepts a zero node limit on the finest level", async () => { + const client = new CatmaidClient("https://example.invalid", 1); + (client as any).listStacks = vi.fn().mockResolvedValue([{ id: 7 }]); + (client as any).getStackInfo = vi.fn().mockResolvedValue({ + dimension: { x: 10, y: 20, z: 30 }, + resolution: { x: 2, y: 3, z: 4 }, + translation: { x: 5, y: 6, z: 7 }, + metadata: { + spatial: [ + { chunk_size: [30, 30, 30], limit: 10 }, + { chunk_size: [15, 15, 15], limit: 0 }, + ], + }, + }); + + await expect(client.getSpatialIndexMetadata()).resolves.toMatchObject({ + spatial: [{ limit: 10 }, { limit: 0 }], + }); + }); + + it("loads a skeleton's nodes, descriptions and true ends in one request", async () => { + const client = new CatmaidClient("https://example.invalid", 1); + const fetchMock = vi.fn().mockResolvedValue([ + [ + [ + 22107946, + null, + 2, + 23697030.0, + 15055839.0, + 16651262.0, + 2000.0, + 5, + "2026-03-29T10:15:00Z", + ], + [ + 22107955, + 22107954, + 2, + 23705874.0, + 15093672.0, + 16682375.0, + 2000.0, + 5, + "2026-03-29T10:16:00Z", + ], + [ + 22107959, + 22107958, + 2, + 23704520.0, + 15085237.0, + 16708998.0, + 2000.0, + 5, + "2026-03-29T10:17:00Z", + ], + ], + [], + { + "afonso reviewed it": [22107946], + "test 123 4": [ + [22107955, "2026-03-29 10:16:00.000000+00:00"], + [22107955, "2026-03-29 10:15:30.000000+00:00"], + ], + "stale description": [[22107955, "2026-03-29 10:15:45.000000+00:00"]], + ends: [[22107959, "2026-03-29 10:17:00.000000+00:00"]], + }, + [], + [], + ]); + (client as any).fetchProjectEndpoint = fetchMock; + + await expect(client.getSkeleton(2n)).resolves.toEqual([ + { + nodeId: 22107946n, + parentNodeId: undefined, + position: new Float32Array([23697030, 15055839, 16651262]), + segmentId: 2n, + description: "afonso reviewed it", + attributes: { radius: [2000], confidence: [100] }, + }, + { + nodeId: 22107955n, + parentNodeId: 22107954n, + position: new Float32Array([23705874, 15093672, 16682375]), + segmentId: 2n, + description: "test 123 4", + attributes: { radius: [2000], confidence: [100] }, + }, + { + nodeId: 22107959n, + parentNodeId: 22107958n, + position: new Float32Array([23704520, 15085237, 16708998]), + segmentId: 2n, + description: undefined, + attributes: { radius: [2000], confidence: [100], true_end: [1] }, + }, + ]); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(getFetchPath(fetchMock)).toBe( + "skeletons/2/compact-detail?with_tags=true", + ); + }); + + it("treats every compact-detail 404 payload as an absent skeleton", async () => { + for (const body of [ + "", + JSON.stringify({ error: "Unknown skeleton" }), + JSON.stringify({ detail: "Skeleton was removed" }), + ]) { + const client = new CatmaidClient("https://example.invalid", 1); + const response = new Response(body, { + status: 404, + statusText: "Not Found", + }); + (client as any).fetchProjectEndpoint = vi + .fn() + .mockRejectedValue(HttpError.fromResponse(response)); + + await expect(client.getSkeleton(17n)).resolves.toEqual([]); + } + }); + + it("parses raw comma labels from compact-detail as descriptions", async () => { + const client = new CatmaidClient("https://example.invalid", 1); + const fetchMock = vi.fn().mockResolvedValue([ + [ + [ + 22107946, + null, + 2, + 23697030.0, + 15055839.0, + 16651262.0, + 2000.0, + 5, + "2026-03-29T10:15:00Z", + ], + ], + [], + { + "left, branch": [[22107946, "2026-03-29 10:15:00.000000+00:00"]], + }, + [], + [], + ]); + (client as any).fetchProjectEndpoint = fetchMock; + + await expect(client.getSkeleton(2n)).resolves.toEqual([ + { + nodeId: 22107946n, + parentNodeId: undefined, + position: new Float32Array([23697030, 15055839, 16651262]), + segmentId: 2n, + description: "left, branch", + attributes: { radius: [2000], confidence: [100] }, + }, + ]); + }); + + it("loads a skeleton and warns when one tag names an invalid node", async () => { + const client = new CatmaidClient("https://example.invalid", 1); + (client as any).fetchProjectEndpoint = vi.fn().mockResolvedValue([ + [[22107946, null, 2, 1, 2, 3, 2000, 5, "2026-03-29T10:15:00Z"]], + [], + { + reviewed: [ + [22107946, "2026-03-29 10:15:00.000000+00:00"], + [2 ** 53 + 2, "2026-03-29 10:16:00.000000+00:00"], + ], + }, + [], + [], + ]); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + await expect(client.getSkeleton(2n)).resolves.toMatchObject([ + { nodeId: 22107946n, description: "reviewed" }, + ]); + expect(warn).toHaveBeenCalledOnce(); + } finally { + warn.mockRestore(); + } + }); + + it("decodes compact-detail sentinel labels without treating them as true ends", async () => { + const client = new CatmaidClient("https://example.invalid", 1); + const fetchMock = vi.fn().mockResolvedValue([ + [ + [ + 22107946, + null, + 2, + 23697030.0, + 15055839.0, + 16651262.0, + 2000.0, + 5, + "2026-03-29T10:15:00Z", + ], + [ + 22107955, + 22107946, + 2, + 23705874.0, + 15093672.0, + 16682375.0, + 2000.0, + 5, + "2026-03-29T10:16:00Z", + ], + ], + [], + { + "plain stale description": [ + [22107946, "2026-03-29 10:14:00.000000+00:00"], + ], + "plain duplicate": [[22107955, "2026-03-29 10:16:00.000000+00:00"]], + "neuroglancer-description:v1:left%2C%20branch": [ + [22107946, "2026-03-29 10:15:00.000000+00:00"], + [22107955, "2026-03-29 10:16:00.000000+00:00"], + ], + ends: [[22107955, "2026-03-29 10:16:00.000000+00:00"]], + }, + [], + [], + ]); + (client as any).fetchProjectEndpoint = fetchMock; + + await expect(client.getSkeleton(2n)).resolves.toEqual([ + { + nodeId: 22107946n, + parentNodeId: undefined, + position: new Float32Array([23697030, 15055839, 16651262]), + segmentId: 2n, + description: "left, branch", + attributes: { radius: [2000], confidence: [100] }, + }, + { + nodeId: 22107955n, + parentNodeId: 22107946n, + position: new Float32Array([23705874, 15093672, 16682375]), + segmentId: 2n, + description: "left, branch", + attributes: { radius: [2000], confidence: [100], true_end: [1] }, + }, + ]); + }); + + it("loads skeleton rows that have no edition time column", async () => { + const client = new CatmaidClient("https://example.invalid", 1); + const fetchMock = vi + .fn() + .mockResolvedValue([ + [[22107946, null, 2, 23697030.0, 15055839.0, 16651262.0, 2000.0, 5]], + [], + {}, + [], + [], + ]); + (client as any).fetchProjectEndpoint = fetchMock; + + await expect(client.getSkeleton(2n)).resolves.toEqual([ + { + nodeId: 22107946n, + parentNodeId: undefined, + position: new Float32Array([23697030, 15055839, 16651262]), + segmentId: 2n, + description: undefined, + attributes: { radius: [2000], confidence: [100] }, + }, + ]); + }); + + const editRows: readonly { + name: string; + call: (client: CatmaidClient) => Promise; + response: object; + result?: object; + path: string; + fields: Record; + }[] = [ + { + name: "merge", + call: (client) => client.mergeSkeletons(101n, 202n), + response: { + result_skeleton_id: 17, + deleted_skeleton_id: 21, + stable_annotation_swap: true, + }, + result: { + resultSegmentId: 17n, + deletedSegmentId: 21n, + directionAdjusted: true, + }, + path: "skeleton/join", + fields: { from_id: "101", to_id: "202" }, + }, + { + name: "add node", + call: (client) => client.addNode(1, 2, 3, 7n), + response: { treenode_id: 88, skeleton_id: 13 }, + result: { nodeId: 88n, segmentId: 13n }, + path: "treenode/create", + fields: { parent_id: "7", skeleton_id: null }, + }, + { + name: "insert node", + call: (client) => client.insertNode(1, 2, 3, 7n, [11n, 12n]), + response: { treenode_id: 89, skeleton_id: 13 }, + result: { nodeId: 89n, segmentId: 13n }, + path: "treenode/insert", + fields: { + parent_id: "7", + child_id: "11", + "takeover_child_ids[0]": "12", + skeleton_id: null, + }, + }, + { + name: "reroot", + call: (client) => client.rerootSkeleton(202n), + response: { newroot: 202, skeleton_id: 17 }, + path: "skeleton/reroot", + fields: { treenode_id: "202" }, + }, + { + name: "split", + call: (client) => client.splitSkeleton(202n), + response: { existing_skeleton_id: 17, new_skeleton_id: 21 }, + result: { existingSegmentId: 17n, newSegmentId: 21n }, + path: "skeleton/split", + fields: { treenode_id: "202", downstream_annotation_map: "{}" }, + }, + { + name: "move", + call: (client) => client.moveNode(42n, 10, 11, 12), + response: { updated: 1 }, + path: "node/update", + fields: {}, + }, + { + name: "delete", + call: (client) => client.deleteNode(11n), + response: { success: "Removed treenode successfully." }, + path: "treenode/delete", + fields: { treenode_id: "11" }, + }, + { + name: "radius", + call: (client) => client.updateRadius(11n, 25), + response: {}, + path: "treenode/11/radius", + fields: { radius: "25" }, + }, + { + name: "confidence", + call: (client) => client.updateConfidence(11n, 75), + response: {}, + path: "treenodes/11/confidence", + fields: {}, + }, + ]; + + it.each(editRows.map((row) => [row.name, row] as const))( + "sends the %s request with CATMAID's edition check turned off", + async (_name, { call, response, path, fields }) => { + const client = new CatmaidClient("https://example.invalid", 1); + const fetchMock = vi.fn().mockResolvedValue(response); + (client as any).fetchProjectEndpoint = fetchMock; + + await call(client); + + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(getFetchPath(fetchMock)).toBe(path); + const requestBody = getFetchBody(fetchMock); + for (const [field, value] of Object.entries(fields)) { + expect(requestBody.get(field)).toBe(value); + } + expect(requestBody.get("nocheck")).toBeNull(); + expect(requestBody.get("state")).toBe(JSON.stringify({ nocheck: true })); + }, + ); + + it.each( + editRows + .filter((row) => row.result !== undefined) + .map((row) => [row.name, row] as const), + )( + "reads CATMAID's reply to the %s request", + async (_name, { call, response, result }) => { + const client = new CatmaidClient("https://example.invalid", 1); + (client as any).fetchProjectEndpoint = vi + .fn() + .mockResolvedValue(response); + + await expect(call(client)).resolves.toEqual(result); + }, + ); + + it("lists the nodes in a region at low fetch priority", async () => { + const client = new CatmaidClient("https://example.invalid", 1); + const fetchMock = vi.fn().mockResolvedValue([ + [ + [101, null, 1, 2, 3, 5, 2000, 11, "2026-03-29T11:50:00Z", 2], + [102, 101, 4, 5, 6, 5, 2000, 17, "2026-03-29T11:51:00Z", 2], + ], + [], + {}, + false, + [], + [], + ]); + (client as any).fetchProjectEndpoint = fetchMock; + + await expect( + client.fetchNodes({ + lowerBounds: Float64Array.of(0, 0, 0), + upperBounds: Float64Array.of(10, 10, 10), + }), + ).resolves.toEqual([ + { + nodeId: 101n, + parentNodeId: undefined, + position: new Float32Array([1, 2, 3]), + segmentId: 11n, + }, + { + nodeId: 102n, + parentNodeId: 101n, + position: new Float32Array([4, 5, 6]), + segmentId: 17n, + }, + ]); + + expect(getFetchPath(fetchMock)).toMatch(/^node\/list\?/); + expect( + new URLSearchParams(getFetchPath(fetchMock).split("?")[1]).get("lod"), + ).toBe("0"); + expect(getFetchInit(fetchMock).priority).toBe("low"); + }); + + it("requests node/list at the level of detail the source asks for", async () => { + const client = new CatmaidClient("https://example.invalid", 1); + const fetchMock = vi.fn().mockResolvedValue([[], [], {}, false, [], []]); + (client as any).fetchProjectEndpoint = fetchMock; + + await client.fetchNodes( + { + lowerBounds: Float64Array.of(0, 0, 0), + upperBounds: Float64Array.of(10, 10, 10), + }, + 0.5, + ); + + expect( + new URLSearchParams(getFetchPath(fetchMock).split("?")[1]).get("lod"), + ).toBe("0.5"); + }); + + it("rejects CATMAID node-list bounds with fewer than three coordinates", async () => { + const client = new CatmaidClient("https://example.invalid", 1); + const fetchMock = vi.fn(); + (client as any).fetchProjectEndpoint = fetchMock; + + await expect( + client.fetchNodes({ + lowerBounds: Float64Array.of(0, 0), + upperBounds: Float64Array.of(10, 10), + }), + ).rejects.toThrow(/requires at least 3 coordinates/i); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it.each([ + "move", + "delete", + "reroot", + "true-end", + "radius", + "confidence", + ] as const)( + "accepts a %s acknowledgement without edition metadata", + async (operation) => { + const client = new CatmaidClient("https://example.invalid", 1); + const fetchMock = vi + .fn() + .mockResolvedValue({ success: true, newroot: 11 }); + (client as any).fetchProjectEndpoint = fetchMock; + const mutations = { + move: () => client.moveNode(11n, 1, 2, 3), + delete: () => client.deleteNode(11n), + reroot: () => client.rerootSkeleton(11n), + "true-end": () => client.toggleTrueEnd(11n, true), + radius: () => client.updateRadius(11n, 25), + confidence: () => client.updateConfidence(11n, 75), + }; + + await expect(mutations[operation]()).resolves.toBeUndefined(); + expect(fetchMock).toHaveBeenCalledTimes(1); + }, + ); + + it("rejects reroot when CATMAID reports a different new root", async () => { + const client = new CatmaidClient("https://example.invalid", 1); + const fetchMock = vi.fn().mockResolvedValue({ + newroot: 203, + skeleton_id: 17, + edition_time: "2026-03-29T12:08:00Z", + }); + (client as any).fetchProjectEndpoint = fetchMock; + + await expect(client.rerootSkeleton(202n)).rejects.toThrow( + "CATMAID skeleton/reroot did not return the requested new root.", + ); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it("updates a description without CATMAID's edition check state", async () => { + const client = new CatmaidClient("https://example.invalid", 1); + const fetchMock = vi + .fn() + .mockResolvedValue({ edition_time: "2026-03-29T13:00:00Z" }); + (client as any).fetchProjectEndpoint = fetchMock; + + await expect( + client.updateDescription(11n, "updated description"), + ).resolves.toEqual({ + description: "updated description", + }); + + const requestBody = getFetchBody(fetchMock); + expect(requestBody.get("state")).toBeNull(); + expect(requestBody.get("tags")).toBe("updated description"); + expect(requestBody.get("delete_existing")).toBe("true"); + }); + + it("encodes comma descriptions as one comma-free CATMAID label", async () => { + const client = new CatmaidClient("https://example.invalid", 1); + const fetchMock = vi + .fn() + .mockResolvedValue({ edition_time: "2026-03-29T13:01:00Z" }); + (client as any).fetchProjectEndpoint = fetchMock; + + await expect( + client.updateDescription(11n, " left, branch \n LEFT, BRANCH \n ends "), + ).resolves.toEqual({ + description: "left, branch", + }); + + const requestBody = getFetchBody(fetchMock); + expect(requestBody.get("tags")).toBe( + "neuroglancer-description:v1:left%2C%20branch", + ); + expect(requestBody.get("tags")).not.toContain(","); + expect(requestBody.get("delete_existing")).toBe("true"); + }); + + it("encodes sentinel-prefixed descriptions even without commas", async () => { + const client = new CatmaidClient("https://example.invalid", 1); + const fetchMock = vi + .fn() + .mockResolvedValue({ edition_time: "2026-03-29T13:02:00Z" }); + (client as any).fetchProjectEndpoint = fetchMock; + + await expect( + client.updateDescription(11n, "neuroglancer-description:v1:left"), + ).resolves.toEqual({ + description: "neuroglancer-description:v1:left", + }); + + const requestBody = getFetchBody(fetchMock); + expect(requestBody.get("tags")).toBe( + "neuroglancer-description:v1:neuroglancer-description%3Av1%3Aleft", + ); + }); + + it("preserves true-end labels while replacing description labels", async () => { + const client = new CatmaidClient("https://example.invalid", 1); + const fetchMock = vi + .fn() + .mockResolvedValue({ edition_time: "2026-03-29T13:05:00Z" }); + (client as any).fetchProjectEndpoint = fetchMock; + + await expect( + client.updateDescription(11n, "updated description\nends", { + isTrueEnd: true, + }), + ).resolves.toEqual({ + description: "updated description", + }); + + const requestBody = getFetchBody(fetchMock); + expect(requestBody.get("tags")).toBe("updated description,ends"); + expect(requestBody.get("delete_existing")).toBe("true"); + }); + + it("preserves true-end labels while replacing comma descriptions", async () => { + const client = new CatmaidClient("https://example.invalid", 1); + const fetchMock = vi + .fn() + .mockResolvedValue({ edition_time: "2026-03-29T13:06:00Z" }); + (client as any).fetchProjectEndpoint = fetchMock; + + await expect( + client.updateDescription(11n, "left, branch\nends", { + isTrueEnd: true, + }), + ).resolves.toEqual({ + description: "left, branch", + }); + + const requestBody = getFetchBody(fetchMock); + expect(requestBody.get("tags")).toBe( + "neuroglancer-description:v1:left%2C%20branch,ends", + ); + expect(requestBody.get("delete_existing")).toBe("true"); + }); + + it("toggles a true end without CATMAID's edition check state", async () => { + const client = new CatmaidClient("https://example.invalid", 1); + const fetchMock = vi + .fn() + .mockResolvedValueOnce({ edition_time: "2026-03-29T13:10:00Z" }) + .mockResolvedValueOnce({ edition_time: "2026-03-29T13:11:00Z" }); + (client as any).fetchProjectEndpoint = fetchMock; + + await expect(client.toggleTrueEnd(11n, true)).resolves.toBeUndefined(); + await expect(client.toggleTrueEnd(11n, false)).resolves.toBeUndefined(); + + const addTagRequestBody = getFetchBody(fetchMock, 0); + const removeTagRequestBody = getFetchBody(fetchMock, 1); + expect(addTagRequestBody.get("state")).toBeNull(); + expect(removeTagRequestBody.get("state")).toBeNull(); + expect(addTagRequestBody.get("tags")).toBe("ends"); + expect(addTagRequestBody.get("delete_existing")).toBe("false"); + expect(removeTagRequestBody.get("tag")).toBe("ends"); + }); + + it("maps generic confidence percentages to CATMAID confidence levels", async () => { + const client = new CatmaidClient("https://example.invalid", 1); + const fetchMock = vi.fn().mockResolvedValue({ + updated_partners: { "11": { edition_time: "2026-03-29T13:20:00Z" } }, + }); + (client as any).fetchProjectEndpoint = fetchMock; + + await expect(client.updateConfidence(11n, 75)).resolves.toBeUndefined(); + + expect(getFetchPath(fetchMock)).toBe("treenodes/11/confidence"); + expect(getFetchBody(fetchMock).get("new_confidence")).toBe("4"); + expect(getFetchBody(fetchMock).get("state")).toBe( + JSON.stringify({ nocheck: true }), + ); + }); + + it("asks the user to refresh when CATMAID says the skeleton is out of date", async () => { + const client = new CatmaidClient("https://example.invalid", 1); + const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue( + new Response( + JSON.stringify({ + type: "StateMatchingError", + error: + "The provided state differs from the database state: {'edition_time': '2026-03-29T13:12:00Z'}", + }), + { + status: 400, + headers: { + "Content-Type": "application/json", + }, + }, + ), + ); + + await expect(client.moveNode(11n, 1, 2, 3)).rejects.toThrow( + "CATMAID rejected the edit because the inspected skeleton is out of date. Refresh the skeleton and try again.", + ); + + fetchMock.mockRestore(); + }); + + // Provider rejections must reach the existing edit feedback without replacing + // HTTP metadata used by other callers or consuming the original response body. + it("surfaces deletion rejection instructions while preserving HTTP metadata", async () => { + const client = new CatmaidClient("https://example.invalid", 1); + const message = + "This skeleton is associated with a task and cannot be deleted. Link the task to a different skeleton first."; + const payload = { + error: message, + meta: { code: "task_skeleton_final_node" }, + }; + const response = new Response(JSON.stringify(payload), { + status: 409, + statusText: "Conflict", + headers: { "Content-Type": "application/json" }, + }); + Object.defineProperty(response, "url", { + value: "https://example.invalid/1/treenode/delete", + }); + const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(response); + + await expect(client.deleteNode(7n)).rejects.toMatchObject({ + name: "HttpError", + status: 409, + response, + message: `Fetching "https://example.invalid/1/treenode/delete" resulted in HTTP error 409: Conflict. ${message}`, + }); + await expect(response.json()).resolves.toEqual(payload); + + fetchMock.mockRestore(); + }); + + it("surfaces a non-empty detail only when the provider error field is absent", async () => { + const client = new CatmaidClient("https://example.invalid", 1); + const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue( + new Response( + JSON.stringify({ + detail: " This edit is not permitted. ", + }), + { + status: 403, + headers: { "Content-Type": "application/json" }, + }, + ), + ); + + await expect(client.deleteNode(7n)).rejects.toMatchObject({ + name: "HttpError", + status: 403, + message: + 'Fetching "" resulted in HTTP error 403. This edit is not permitted.', + }); + + fetchMock.mockRestore(); + }); + + it.each([ + ["malformed JSON", "{"], + ["non-string fields", JSON.stringify({ error: 1, detail: {} })], + ["empty fields", JSON.stringify({ error: " ", detail: "" })], + ["non-object payload", JSON.stringify(["Invalid edit"])], + [ + "blank error with traceback", + JSON.stringify({ + error: " ", + detail: "Traceback (most recent call last): private server paths", + }), + ], + [ + "null error with traceback", + JSON.stringify({ + error: null, + detail: "Traceback (most recent call last): private server paths", + }), + ], + ])("retains the HTTP fallback for %s", async (_name, body) => { + const client = new CatmaidClient("https://example.invalid", 1); + const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue( + new Response(body, { + status: 409, + headers: { "Content-Type": "application/json" }, + }), + ); + + await expect(client.deleteNode(7n)).rejects.toMatchObject({ + name: "HttpError", + status: 409, + message: 'Fetching "" resulted in HTTP error 409.', + }); + + fetchMock.mockRestore(); + }); + + it("keeps a CATMAID 400 that is not a stale-skeleton error as an HTTP error", async () => { + const client = new CatmaidClient("https://example.invalid", 1); + const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue( + new Response( + JSON.stringify({ + type: "ValueError", + error: "No valid state provided, missing edition time", + }), + { + status: 400, + headers: { + "Content-Type": "application/json", + }, + }, + ), + ); + + await expect(client.moveNode(11n, 1, 2, 3)).rejects.toMatchObject({ + name: "HttpError", + status: 400, + }); + + fetchMock.mockRestore(); + }); + + it.each([ + ["readable error", "Treenode 7 doesn't exist", "Treenode 7 doesn't exist"], + ["blank error", " ", "CATMAID resource not found."], + ["null error", null, "CATMAID resource not found."], + ])( + "uses a safe message for a middleware 404 with %s", + async (_kind, error, message) => { + const client = new CatmaidClient("https://example.invalid", 1); + const payload = { + error, + detail: + "Traceback (most recent call last): private server paths; Treenode 7 doesn't exist", + type: "Http404", + }; + const response = new Response(JSON.stringify(payload), { status: 404 }); + const fetchMock = vi + .spyOn(globalThis, "fetch") + .mockResolvedValue(response); + try { + await expect(client.deleteNode(7n)).rejects.toMatchObject({ + name: "CatmaidNotFoundError", + message, + }); + expect(response.bodyUsed).toBe(false); + await expect(response.json()).resolves.toEqual(payload); + } finally { + fetchMock.mockRestore(); + } + }, + ); + + it("shows the detail of a detail-only 404 when an edit fails", async () => { + const client = new CatmaidClient("https://example.invalid", 1); + const message = "Skeleton 456 doesn't exist"; + const fetchMock = vi + .spyOn(globalThis, "fetch") + .mockImplementation( + async () => + new Response(JSON.stringify({ detail: message }), { status: 404 }), + ); + try { + await expect(client.deleteNode(7n)).rejects.toMatchObject({ + name: "CatmaidNotFoundError", + message, + }); + } finally { + fetchMock.mockRestore(); + } + }); + + // Transport failures must retain useful diagnostics and never display raw proxy pages. + it.each(["read", "edit"] as const)( + "retains HTTP diagnostics for a %s rejected by an HTML proxy page", + async (operation) => { + const client = new CatmaidClient("https://example.invalid", 1); + const response = new Response( + "502 Bad Gateway", + { + status: 502, + statusText: "Bad Gateway", + headers: { "Content-Type": "text/html" }, + }, + ); + Object.defineProperty(response, "url", { + value: "https://example.invalid/1/endpoint", + }); + const fetchMock = vi + .spyOn(globalThis, "fetch") + .mockResolvedValue(response); + try { + const result = + operation === "read" + ? client.getSkeleton(456n) + : client.deleteNode(7n); + await expect(result).rejects.toMatchObject({ + name: "HttpError", + status: 502, + response, + message: + 'Fetching "https://example.invalid/1/endpoint" resulted in HTTP error 502: Bad Gateway.', + }); + expect(response.bodyUsed).toBe(false); + } finally { + fetchMock.mockRestore(); + } + }, + ); + + it("keeps URL and status when appending a structured read failure", async () => { + const client = new CatmaidClient("https://example.invalid", 1); + const response = new Response(JSON.stringify({ error: "Read denied" }), { + status: 403, + }); + Object.defineProperty(response, "url", { + value: "https://example.invalid/1/skeletons/456/compact-detail", + }); + const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(response); + try { + await expect(client.getSkeleton(456n)).rejects.toMatchObject({ + name: "HttpError", + status: 403, + message: + 'Fetching "https://example.invalid/1/skeletons/456/compact-detail" resulted in HTTP error 403. Read denied', + }); + } finally { + fetchMock.mockRestore(); + } + }); + + it("does not append a traceback to a state-validation error when error is blank", async () => { + const client = new CatmaidClient("https://example.invalid", 1); + const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue( + new Response( + JSON.stringify({ + type: "StateMatchingError", + error: "", + detail: "Traceback (most recent call last): private server paths", + }), + { status: 400 }, + ), + ); + try { + await expect(client.deleteNode(7n)).rejects.toMatchObject({ + name: "CatmaidStateValidationError", + message: + "CATMAID rejected the edit because the inspected skeleton is out of date. Refresh the skeleton and try again.", + }); + } finally { + fetchMock.mockRestore(); + } + }); + + it("reads skeleton and node IDs above 2^53 exactly from a node list", async () => { + const client = new CatmaidClient("https://example.invalid", 1); + const row = [ + 2n ** 53n + 1n, + 2n ** 53n + 3n, + 1.5, + 2.5, + 3.5, + 0, + 5, + 2n ** 63n + 5n, + ]; + const fetchMock = vi + .spyOn(globalThis, "fetch") + .mockResolvedValue( + new Response(new Uint8Array(pack([[row], [], {}, false]))), + ); + try { + await expect( + client.fetchNodes({ + lowerBounds: Float64Array.of(0, 0, 0), + upperBounds: Float64Array.of(10, 10, 10), + }), + ).resolves.toEqual([ + { + nodeId: 2n ** 53n + 1n, + parentNodeId: 2n ** 53n + 3n, + position: new Float32Array([1.5, 2.5, 3.5]), + segmentId: 2n ** 63n + 5n, + }, + ]); + } finally { + fetchMock.mockRestore(); + } + }); + + it("rejects a created node ID above 2^53 instead of rounding it", async () => { + const client = new CatmaidClient("https://example.invalid", 1); + (client as any).fetchProjectEndpoint = vi.fn().mockResolvedValue({ + treenode_id: 2 ** 53 + 2, + skeleton_id: 13, + }); + + await expect(client.addNode(1, 2, 3)).rejects.toThrow( + /too large to read exactly/, + ); + }); +}); + +describe("CatmaidClient authenticated requests", () => { + it("retries anonymous 403 responses with refreshed credentials", async () => { + const provider = new SequenceCredentialsProvider([ + { token: "anonymous-token", kind: "anonymous" }, + { token: "personal-token", kind: "personal" }, + ]); + const fetchMock = vi + .fn() + .mockResolvedValueOnce(jsonResponse({ detail: "forbidden" }, 403)) + .mockResolvedValueOnce(jsonResponse([17])); + vi.stubGlobal("fetch", fetchMock); + const client = new CatmaidClient("https://catmaid.example", 1, provider); + + await expect(client.listSkeletons()).resolves.toEqual([17n]); + expect(provider.calls).toHaveLength(2); + expect(provider.calls[1]).toMatchObject({ + credentials: { kind: "anonymous" }, + }); + expect( + (fetchMock.mock.calls[0][1].headers as Headers).get("Authorization"), + ).toBe("Token anonymous-token"); + expect( + (fetchMock.mock.calls[1][1].headers as Headers).get("Authorization"), + ).toBe("Token personal-token"); + }); + + it("does not retry personal-token 403 responses", async () => { + const provider = new SequenceCredentialsProvider([ + { token: "personal-token", kind: "personal" }, + ]); + const fetchMock = vi + .fn() + .mockResolvedValue(jsonResponse({ detail: "forbidden" }, 403)); + vi.stubGlobal("fetch", fetchMock); + const client = new CatmaidClient("https://catmaid.example", 1, provider); + + await expect(client.listSkeletons()).rejects.toThrow("HTTP error 403"); + expect(provider.calls).toHaveLength(1); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it("replaces personal credentials after a 401 response", async () => { + const provider = new SequenceCredentialsProvider([ + { token: "expired-token", kind: "personal" }, + { token: "replacement-token", kind: "personal" }, + ]); + const fetchMock = vi + .fn() + .mockResolvedValueOnce(jsonResponse({ detail: "invalid" }, 401)) + .mockResolvedValueOnce(jsonResponse([23])); + vi.stubGlobal("fetch", fetchMock); + const client = new CatmaidClient("https://catmaid.example", 1, provider); + + await expect(client.listSkeletons()).resolves.toEqual([23n]); + expect(provider.calls).toHaveLength(2); + expect(provider.calls[1]).toMatchObject({ + credentials: { token: "expired-token", kind: "personal" }, + }); + }); + + it("preserves caller and form headers while adding authorization", async () => { + const provider = new SequenceCredentialsProvider([ + { token: "personal-token", kind: "personal" }, + ]); + const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ ok: true })); + vi.stubGlobal("fetch", fetchMock); + const client = new CatmaidClient("https://catmaid.example", 1, provider); + + await (client as any).fetchProjectEndpoint("test", { + method: "POST", + body: new URLSearchParams({ value: "1" }), + headers: { "X-Test": "present" }, + }); + + const headers = fetchMock.mock.calls[0][1].headers as Headers; + expect(headers.get("Authorization")).toBe("Token personal-token"); + expect(headers.get("Content-Type")).toBe( + "application/x-www-form-urlencoded", + ); + expect(headers.get("X-Test")).toBe("present"); + }); +}); + +describe("getDefaultCatmaidChunkSize", () => { + it("keeps the chunk size isotropic for elongated bounds", () => { + expect( + getDefaultCatmaidChunkSize({ + lowerBounds: Float64Array.of(0, 0, 0), + upperBounds: Float64Array.of(1000, 10, 10), + }), + ).toEqual([16, 16, 16]); + }); + + it("returns the minimum chunk size for tiny bounds", () => { + expect( + getDefaultCatmaidChunkSize({ + lowerBounds: Float64Array.of(0, 0, 0), + upperBounds: Float64Array.of(2, 2, 2), + }), + ).toEqual([1, 1, 1]); + }); +}); diff --git a/src/datasource/catmaid/api.ts b/src/datasource/catmaid/api.ts new file mode 100644 index 0000000000..24a3f89160 --- /dev/null +++ b/src/datasource/catmaid/api.ts @@ -0,0 +1,1393 @@ +/** + * @license + * Copyright 2026 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file Reads skeletons and spatial index metadata from a CATMAID project + * through its HTTP API. Sends skeleton edits to it. + */ + +import { Unpackr } from "msgpackr"; +import type { BoundingBox } from "#src/coordinate_transform.js"; +import { fetchOkWithCredentials } from "#src/credentials_provider/http_request.js"; +import type { CredentialsProvider } from "#src/credentials_provider/index.js"; +import type { + SkeletonSpatialIndexLevel, + SkeletonVector, + SkeletonNode, +} from "#src/skeleton/api.js"; +import { SpatialSkeletonEditConflictError } from "#src/skeleton/edit_queue/edit_errors.js"; +import { setSkeletonNodeAttributes } from "#src/skeleton/node_attributes.js"; +import { bigintCompare } from "#src/util/bigint.js"; +import { HttpError } from "#src/util/http_request.js"; +import { parseUint64 } from "#src/util/json.js"; + +const MAX_DEFAULT_CHUNK_COUNT = 64; +const MIN_DEFAULT_CHUNK_SIZE = 1; + +function getChunkCoverageForChunkSize( + extents: readonly number[], + chunkSize: number, +) { + return extents.reduce((product, extent) => { + const axisChunks = extent <= 0 ? 1 : Math.ceil(extent / chunkSize); + return product * axisChunks; + }, 1); +} + +// For a stack whose metadata lists no spatial levels: the smallest isotropic +// chunk size that covers the bounds with at most MAX_DEFAULT_CHUNK_COUNT chunks. +export function getDefaultCatmaidChunkSize(bounds: BoundingBox): number[] { + const extents = Array.from(bounds.lowerBounds, (lowerBound, index) => + Math.max(0, bounds.upperBounds[index] - lowerBound), + ); + const maxExtent = Math.max(...extents); + if (!(maxExtent > 0)) { + return extents.map(() => MIN_DEFAULT_CHUNK_SIZE); + } + let low = MIN_DEFAULT_CHUNK_SIZE; + let high = Math.max(MIN_DEFAULT_CHUNK_SIZE, Math.ceil(maxExtent)); + while (low < high) { + const mid = Math.floor((low + high) / 2); + if (getChunkCoverageForChunkSize(extents, mid) <= MAX_DEFAULT_CHUNK_COUNT) { + high = mid; + } else { + low = mid + 1; + } + } + return extents.map(() => low); +} + +export interface CatmaidSpatialIndexInfo { + readonly bounds: BoundingBox; + readonly spatial: readonly SkeletonSpatialIndexLevel[]; + readonly readonly: boolean; +} + +interface CatmaidStackInfo { + dimension: { x: number; y: number; z: number }; + resolution: { x: number; y: number; z: number }; + translation: { x: number; y: number; z: number }; + metadata?: { + cache_provider?: string; + read_only?: boolean; + spatial?: Array<{ + chunk_size: SkeletonVector; + limit: number; + }>; + }; +} + +export interface CatmaidToken { + token: string; + kind: "anonymous" | "personal"; +} + +export const credentialsKey = "CATMAID"; +const CATMAID_NO_MATCHING_NODE_PROVIDER_ERROR = + "Could not find matching node provider for request"; +const CATMAID_STATE_MATCHING_ERROR_TYPE = "StateMatchingError"; + +type CatmaidFetchPriority = "high" | "low" | "auto"; +type CatmaidRequestInit = RequestInit & { priority?: CatmaidFetchPriority }; +export type CatmaidRank3Vector = readonly [number, number, number]; + +export interface CatmaidAddNodeResult { + nodeId: bigint; + segmentId: bigint; +} + +export type CatmaidInsertNodeResult = CatmaidAddNodeResult; + +export interface CatmaidDescriptionUpdateResult { + description?: string; +} + +export interface CatmaidDescriptionUpdateOptions { + isTrueEnd?: boolean; +} + +export interface CatmaidMergeResult { + resultSegmentId: bigint | undefined; + deletedSegmentId: bigint | undefined; + directionAdjusted: boolean; +} + +export interface CatmaidSplitResult { + existingSegmentId: bigint | undefined; + newSegmentId: bigint | undefined; +} + +export interface CatmaidSpatialSkeletonEditApi { + addNode( + x: number, + y: number, + z: number, + parentId?: bigint, + ): Promise; + deleteNode(nodeId: bigint): Promise; + moveNode(nodeId: bigint, x: number, y: number, z: number): Promise; + splitSkeleton(nodeId: bigint): Promise; + mergeSkeletons( + fromNodeId: bigint, + toNodeId: bigint, + ): Promise; + toggleTrueEnd(nodeId: bigint, nextIsTrueEnd: boolean): Promise; + insertNode( + x: number, + y: number, + z: number, + parentId: bigint, + childNodeIds: readonly bigint[], + ): Promise; + rerootSkeleton(nodeId: bigint): Promise; + updateDescription( + nodeId: bigint, + description: string, + options?: CatmaidDescriptionUpdateOptions, + ): Promise; + updateRadius(nodeId: bigint, radius: number): Promise; + updateConfidence(nodeId: bigint, confidence: number): Promise; +} + +class CatmaidNotFoundError extends Error { + constructor(detail?: string) { + super(detail ?? "CATMAID resource not found."); + this.name = "CatmaidNotFoundError"; + } +} + +export class CatmaidStateValidationError extends SpatialSkeletonEditConflictError { + constructor(detail?: string) { + super( + detail === undefined + ? "CATMAID rejected the edit because the inspected skeleton is out of date. Refresh the skeleton and try again." + : `CATMAID rejected the edit because the inspected skeleton is out of date. Refresh the skeleton and try again. ${detail}`, + ); + this.name = "CatmaidStateValidationError"; + } +} + +export const CATMAID_SPATIAL_SKELETON_CONFIDENCE_VALUES = [ + 0, 25, 50, 75, 100, +] as const; + +const CATMAID_TRUE_END_LABEL = "ends"; +const CATMAID_ENCODED_DESCRIPTION_LABEL_PREFIX = "neuroglancer-description:v1:"; +const CATMAID_CLOSED_END_LABEL_PATTERNS = [ + /^uncertain continuation$/i, + /^not a branch$/i, + /^soma$/i, + /^(really|uncertain|anterior|posterior)?\s?ends?$/i, +]; + +function isCatmaidClosedEndLabel(label: string) { + const normalized = label.trim(); + return ( + normalized.length > 0 && + CATMAID_CLOSED_END_LABEL_PATTERNS.some((pattern) => + pattern.test(normalized), + ) + ); +} + +function includesNoMatchingNodeProviderError(value: unknown): boolean { + return ( + typeof value === "string" && + value.includes(CATMAID_NO_MATCHING_NODE_PROVIDER_ERROR) + ); +} + +function isNoMatchingNodeProviderErrorPayload(payload: unknown): boolean { + if (payload === null || typeof payload !== "object") return false; + const value = payload as { error?: unknown; detail?: unknown }; + return ( + includesNoMatchingNodeProviderError(value.error) || + includesNoMatchingNodeProviderError(value.detail) + ); +} + +function getCatmaidErrorMessage(payload: unknown): string | undefined { + if ( + payload === null || + typeof payload !== "object" || + Array.isArray(payload) + ) { + return undefined; + } + const value = payload as { error?: unknown; detail?: unknown }; + // CATMAID's exception middleware uses detail for a traceback, even when error is blank. + const message = Object.hasOwn(value, "error") ? value.error : value.detail; + return typeof message === "string" && message.trim().length > 0 + ? message.trim() + : undefined; +} + +function isCatmaidNotFoundPayload(payload: unknown): boolean { + if (payload === null || typeof payload !== "object" || Array.isArray(payload)) + return false; + const value = payload as { detail?: unknown }; + return ( + typeof value.detail === "string" && value.detail.includes("doesn't exist") + ); +} + +function isCatmaidStateMatchingErrorPayload(payload: unknown): boolean { + if ( + payload === null || + typeof payload !== "object" || + Array.isArray(payload) + ) { + return false; + } + const value = payload as { type?: unknown }; + return value.type === CATMAID_STATE_MATCHING_ERROR_TYPE; +} + +interface ParsedCatmaidNodeLabel { + label: string; + time?: number; +} + +function decodeCatmaidDescriptionLabel(label: string): string | undefined { + const trimmed = label.trim(); + if (!trimmed.startsWith(CATMAID_ENCODED_DESCRIPTION_LABEL_PREFIX)) { + return undefined; + } + try { + const decoded = decodeURIComponent( + trimmed.substring(CATMAID_ENCODED_DESCRIPTION_LABEL_PREFIX.length), + ).trim(); + return decoded.length === 0 ? undefined : decoded; + } catch { + return undefined; + } +} + +function makeCatmaidEncodedDescriptionLabel(description: string) { + return `${CATMAID_ENCODED_DESCRIPTION_LABEL_PREFIX}${encodeURIComponent( + description, + )}`; +} + +function normalizeCatmaidDescription( + labels: readonly ParsedCatmaidNodeLabel[] | undefined, +): string | undefined { + if (labels === undefined || labels.length === 0) { + return undefined; + } + const descriptionLabels = labels.filter( + ({ label }) => + label.trim().length > 0 && + label.trim().toLowerCase() !== CATMAID_TRUE_END_LABEL && + !isCatmaidClosedEndLabel(label), + ); + const timedDescriptionLabels = descriptionLabels.filter( + ({ time }) => time !== undefined, + ); + const currentDescriptionLabels = + timedDescriptionLabels.length === 0 + ? descriptionLabels + : (() => { + const latestTime = Math.max( + ...timedDescriptionLabels.map(({ time }) => time!), + ); + return timedDescriptionLabels.filter( + ({ time }) => time === latestTime, + ); + })(); + if (currentDescriptionLabels.length === 0) { + return undefined; + } + const decodedDescriptionLabels = currentDescriptionLabels + .map(({ label }) => decodeCatmaidDescriptionLabel(label)) + .filter((label): label is string => label !== undefined); + const visibleDescriptionLabels = + decodedDescriptionLabels.length === 0 + ? currentDescriptionLabels.map(({ label }) => label) + : decodedDescriptionLabels; + return visibleDescriptionLabels.length === 0 + ? undefined + : visibleDescriptionLabels.join("\n"); +} + +function parseCatmaidLabelNodeId(value: unknown, label: string) { + try { + return parseCatmaidId(value); + } catch (error) { + console.warn(`Ignoring CATMAID tag "${label}" on an invalid node:`, error); + return undefined; + } +} + +function parseCatmaidLabelNodeReference(entry: unknown, label: string) { + const nodeId = parseCatmaidLabelNodeId( + Array.isArray(entry) ? entry[0] : entry, + label, + ); + if (nodeId === undefined) return undefined; + const time = Array.isArray(entry) + ? getCatmaidLabelTimestamp(entry[1]) + : undefined; + return { nodeId, time }; +} + +function addParsedCatmaidNodeLabel( + labelsByNodeId: Map, + nodeId: bigint, + label: ParsedCatmaidNodeLabel, +) { + const existingLabels = labelsByNodeId.get(nodeId); + if (existingLabels === undefined) { + labelsByNodeId.set(nodeId, [label]); + return; + } + if ( + !existingLabels.some( + (existingLabel) => + existingLabel.label === label.label && + existingLabel.time === label.time, + ) + ) { + existingLabels.push(label); + } +} + +function parseCatmaidNodeLabels( + rawLabels: unknown, +): Map { + const labelsByNodeId = new Map(); + if (rawLabels === null || typeof rawLabels !== "object") { + return labelsByNodeId; + } + for (const [key, value] of Object.entries( + rawLabels as Record, + )) { + if (!Array.isArray(value) || value.length === 0) continue; + const stringValues = value.filter( + (entry): entry is string => typeof entry === "string", + ); + if (stringValues.length === value.length) { + const labels = stringValues + .map((label) => label.trim()) + .filter((label) => label.length > 0); + if (labels.length === 0) continue; + const nodeId = parseCatmaidLabelNodeId(key, labels.join(", ")); + if (nodeId === undefined) continue; + labelsByNodeId.set( + nodeId, + labels.map((label) => ({ label })), + ); + continue; + } + const label = key.trim(); + if (label.length === 0) continue; + for (const entry of value) { + const nodeReference = parseCatmaidLabelNodeReference(entry, label); + if (nodeReference === undefined) continue; + addParsedCatmaidNodeLabel(labelsByNodeId, nodeReference.nodeId, { + label, + time: nodeReference.time, + }); + } + } + return labelsByNodeId; +} + +function getCatmaidNodeDescriptions( + labelsByNodeId: ReadonlyMap, +) { + const descriptionsByNodeId = new Map(); + for (const [nodeId, labels] of labelsByNodeId) { + const description = normalizeCatmaidDescription(labels); + if (description !== undefined) { + descriptionsByNodeId.set(nodeId, description); + } + } + return descriptionsByNodeId; +} + +function getCatmaidTrueEndNodes( + labelsByNodeId: ReadonlyMap, +) { + const trueEndByNodeId = new Map(); + for (const [nodeId, labels] of labelsByNodeId) { + const isTrueEnd = labels.some( + ({ label }) => label.trim().toLowerCase() === CATMAID_TRUE_END_LABEL, + ); + if (isTrueEnd) { + trueEndByNodeId.set(nodeId, true); + } + } + return trueEndByNodeId; +} + +async function tryReadJsonPayload( + response: Response, +): Promise { + try { + return await response.json(); + } catch { + return undefined; + } +} + +async function tryReadErrorPayload( + response: Response, +): Promise { + const contentType = response.headers.get("content-type") ?? ""; + if (contentType.includes("application/json")) { + return tryReadJsonPayload(response); + } + try { + const text = await response.text(); + if (!text) return undefined; + try { + return JSON.parse(text); + } catch { + return { error: text }; + } + } catch { + return undefined; + } +} + +function mapCatmaidConfidenceToPercent(confidence: number | undefined) { + if (confidence === undefined) return undefined; + const normalized = Math.max( + 1, + Math.min( + CATMAID_SPATIAL_SKELETON_CONFIDENCE_VALUES.length, + Math.round(confidence), + ), + ); + return CATMAID_SPATIAL_SKELETON_CONFIDENCE_VALUES[normalized - 1]; +} + +function mapPercentConfidenceToCatmaid(confidence: number) { + const normalized = Math.max( + CATMAID_SPATIAL_SKELETON_CONFIDENCE_VALUES[0], + Math.min( + CATMAID_SPATIAL_SKELETON_CONFIDENCE_VALUES[ + CATMAID_SPATIAL_SKELETON_CONFIDENCE_VALUES.length - 1 + ], + confidence, + ), + ); + let bestIndex = 0; + let bestDistance = Math.abs( + CATMAID_SPATIAL_SKELETON_CONFIDENCE_VALUES[0] - normalized, + ); + for (let i = 1; i < CATMAID_SPATIAL_SKELETON_CONFIDENCE_VALUES.length; ++i) { + const candidate = CATMAID_SPATIAL_SKELETON_CONFIDENCE_VALUES[i]; + const distance = Math.abs(candidate - normalized); + if ( + distance < bestDistance || + (distance === bestDistance && + candidate > CATMAID_SPATIAL_SKELETON_CONFIDENCE_VALUES[bestIndex]) + ) { + bestDistance = distance; + bestIndex = i; + } + } + return bestIndex + 1; +} + +function getCatmaidProjectSpaceBounds(info: CatmaidStackInfo): BoundingBox { + const { dimension, resolution, translation } = info; + const offsetX = translation?.x ?? 0; + const offsetY = translation?.y ?? 0; + const offsetZ = translation?.z ?? 0; + + // CATMAID treenode coordinates and grid cache cell sizes are in project-space nanometers. + return { + lowerBounds: Float64Array.of(offsetX, offsetY, offsetZ), + upperBounds: Float64Array.of( + offsetX + dimension.x * resolution.x, + offsetY + dimension.y * resolution.y, + offsetZ + dimension.z * resolution.z, + ), + }; +} + +function getDefaultCatmaidSpatialIndexLevel( + bounds: BoundingBox, +): SkeletonSpatialIndexLevel { + const chunkSize = requireCatmaidPositiveRank3Vector( + getDefaultCatmaidChunkSize(bounds), + "default spatial skeleton chunk_size", + ); + return { chunkSize, limit: 0 }; +} + +export function requireCatmaidRank3Vector( + vector: SkeletonVector, + label: string, +): CatmaidRank3Vector { + if (vector.length < 3) { + throw new Error(`CATMAID ${label} requires at least 3 coordinates.`); + } + const values = [ + Number(vector[0]), + Number(vector[1]), + Number(vector[2]), + ] as const; + if (values.some((value) => !Number.isFinite(value))) { + throw new Error(`CATMAID ${label} coordinates must be finite.`); + } + return values; +} + +export function requireCatmaidPositiveRank3Vector( + value: unknown, + label: string, +): CatmaidRank3Vector { + if (!Array.isArray(value) || value.length !== 3) { + throw new Error(`CATMAID ${label} must be a rank-3 array.`); + } + const values = [ + Number(value[0]), + Number(value[1]), + Number(value[2]), + ] as const; + if (values.some((x) => !Number.isFinite(x) || x <= 0)) { + throw new Error( + `CATMAID ${label} coordinates must be finite and positive.`, + ); + } + return values; +} + +export function toCatmaidPositionInModelSpace( + position: SkeletonVector, + label: string, +) { + return new Float32Array(requireCatmaidRank3Vector(position, label)); +} + +function requireCatmaidNonNegativeInt(value: unknown, label: string): number { + const numberValue = Number(value); + if (!Number.isInteger(numberValue) || numberValue < 0) { + throw new Error(`CATMAID ${label} must be a non-negative integer.`); + } + return numberValue; +} + +function parseOptionalCatmaidBoolean( + value: unknown, + label: string, +): boolean | undefined { + if (value === undefined) { + return undefined; + } + if (typeof value !== "boolean") { + throw new Error(`CATMAID ${label} must be a boolean.`); + } + return value; +} + +function normalizeBoundingBoxForNodeList(bounds: BoundingBox) { + const [minX, minY, minZ] = requireCatmaidRank3Vector( + bounds.lowerBounds, + "node-list lower bound", + ); + const [maxX, maxY, maxZ] = requireCatmaidRank3Vector( + bounds.upperBounds, + "node-list upper bound", + ); + const left = Math.floor(minX); + const top = Math.floor(minY); + const z1 = Math.floor(minZ); + + // CATMAID node-list bounds are half-open: [left,right) x [top,bottom) x [z1,z2). + // Use ceil for exclusive upper bounds and ensure a positive extent on each axis. + const right = Math.max(left + 1, Math.ceil(maxX)); + const bottom = Math.max(top + 1, Math.ceil(maxY)); + const z2 = Math.max(z1 + 1, Math.ceil(maxZ)); + + return { left, top, z1, right, bottom, z2 }; +} + +export function getCatmaidSpatialSkeletonGridCellBounds( + cellIndex: SkeletonVector, + chunkSize: SkeletonVector, +): BoundingBox { + const [cellX, cellY, cellZ] = requireCatmaidRank3Vector( + cellIndex, + "spatial skeleton grid cell index", + ); + const [sizeX, sizeY, sizeZ] = requireCatmaidRank3Vector( + chunkSize, + "spatial skeleton grid cell size", + ); + return { + lowerBounds: Float64Array.of(cellX * sizeX, cellY * sizeY, cellZ * sizeZ), + upperBounds: Float64Array.of( + (cellX + 1) * sizeX, + (cellY + 1) * sizeY, + (cellZ + 1) * sizeZ, + ), + }; +} + +function appendNodeUpdateRows( + body: URLSearchParams, + key: string, + rows: Array<[bigint, number, number, number]>, +) { + // CATMAID get_request_list parses nested lists from bracketed keys + // (e.g. t[0][0]=id, t[0][1]=x, ...), not from a JSON string. + for (let rowIndex = 0; rowIndex < rows.length; ++rowIndex) { + const row = rows[rowIndex]; + for (let colIndex = 0; colIndex < row.length; ++colIndex) { + body.append(`${key}[${rowIndex}][${colIndex}]`, row[colIndex].toString()); + } + } +} + +function appendScalarList( + body: URLSearchParams, + key: string, + values: readonly bigint[], +) { + for (let index = 0; index < values.length; ++index) { + body.append(`${key}[${index}]`, values[index].toString()); + } +} + +function appendUncheckedCatmaidState(body: URLSearchParams) { + // CATMAID requires an explicit state policy. Queue ordering and local cache + // revisions do not depend on server edition timestamps. + body.append("state", JSON.stringify({ nocheck: true })); +} + +const CATMAID_LABEL_TIMESTAMP_WITH_SPACE_PATTERN = + /^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}(?:\.\d+)?)(Z|[+-]\d{2}:\d{2})$/; + +function getCatmaidLabelTimestamp(value: unknown) { + if (typeof value === "number" && Number.isFinite(value)) { + return value; + } + if (typeof value !== "string") { + return undefined; + } + const normalizedValue = value.trim(); + if (normalizedValue.length === 0) { + return undefined; + } + const parsedValue = Date.parse( + normalizedValue.replace( + CATMAID_LABEL_TIMESTAMP_WITH_SPACE_PATTERN, + "$1T$2$3", + ), + ); + return Number.isFinite(parsedValue) ? parsedValue : undefined; +} + +function fetchWithCatmaidCredentials( + credentialsProvider: CredentialsProvider, + input: string, + init: CatmaidRequestInit, +): Promise { + return fetchOkWithCredentials( + credentialsProvider, + input, + init, + (credentials: CatmaidToken, init: RequestInit) => { + const headers = new Headers(init.headers); + headers.set("Authorization", `Token ${credentials.token}`); + return { ...init, headers }; + }, + (error, credentials) => { + const { status } = error; + if ( + status === 401 || + (status === 403 && credentials.kind === "anonymous") + ) { + // Anonymous credentials may not have access to private projects. A + // 401 also indicates that a personal token must be replaced. + return "refresh"; + } + throw error; + }, + ); +} + +function parseCatmaidId(value: unknown): bigint { + // JSON.parse has already rounded a number above 2^53. + if (typeof value === "number" && !Number.isSafeInteger(value)) { + throw new Error(`CATMAID ID ${value} is too large to read exactly.`); + } + const id = parseUint64(value); + if (id === 0n) { + throw new Error("CATMAID returned an ID of 0."); + } + return id; +} + +function parseCatmaidNodeListRow(row: readonly any[]): SkeletonNode { + return { + nodeId: parseCatmaidId(row[0]), + parentNodeId: parseOptionalCatmaidId(row[1]), + position: new Float32Array([row[2], row[3], row[4]]), + segmentId: parseCatmaidId(row[7]), + }; +} + +function parseOptionalCatmaidId(value: unknown): bigint | undefined { + return value === null || value === undefined + ? undefined + : parseCatmaidId(value); +} + +export class CatmaidClient implements CatmaidSpatialSkeletonEditApi { + private metadataInfoPromise: Promise | undefined; + private readonly msgpackUnpackr = new Unpackr({ + mapsAsObjects: false, + int64AsType: "bigint", + }); + + constructor( + public baseUrl: string, + public projectId: number, + public credentialsProvider?: CredentialsProvider, + ) {} + + private async normalizeFetchError(error: unknown): Promise { + if (!(error instanceof HttpError) || error.response === undefined) { + return error; + } + let payload: unknown; + try { + payload = await tryReadJsonPayload(error.response.clone()); + } catch { + // Optional message enrichment must preserve the original HTTP diagnostics. + return error; + } + if (isCatmaidStateMatchingErrorPayload(payload)) { + return new CatmaidStateValidationError(getCatmaidErrorMessage(payload)); + } + if (error.status === 404 && isCatmaidNotFoundPayload(payload)) { + return new CatmaidNotFoundError(getCatmaidErrorMessage(payload)); + } + const message = getCatmaidErrorMessage(payload); + if (message !== undefined) { + error.message = `${error.message} ${message}`; + } + return error; + } + + private async fetchProjectEndpoint( + endpoint: string, + options: CatmaidRequestInit = {}, + expectMsgpack: boolean = false, + ): Promise { + // Ensure baseUrl doesn't have trailing slash and endpoint doesn't have leading slash + const baseUrl = this.baseUrl.replace(/\/$/, ""); + const url = `${baseUrl}/${this.projectId}/${endpoint}`; + const headers = new Headers(options.headers); + // CATMAID API often expects form-encoded data for POST + if (options.method === "POST" && options.body instanceof URLSearchParams) { + headers.append("Content-Type", "application/x-www-form-urlencoded"); + } + + let response: Response; + try { + if (this.credentialsProvider) { + response = await fetchWithCatmaidCredentials( + this.credentialsProvider, + url, + { ...options, headers }, + ); + } else { + response = await fetch(url, { ...options, headers }); + if (!response.ok) { + throw HttpError.fromResponse(response); + } + } + } catch (error) { + throw await this.normalizeFetchError(error); + } + + if (expectMsgpack) { + const contentType = response.headers.get("content-type") ?? ""; + if (contentType.includes("application/json")) { + return response.json(); + } + const buffer = await response.arrayBuffer(); + try { + return this.msgpackUnpackr.unpack(new Uint8Array(buffer)); + } catch (error) { + // Some CATMAID deployments return a JSON error body with a msgpack request. + try { + return JSON.parse(new TextDecoder().decode(buffer)); + } catch { + throw error; + } + } + } + + return response.json(); + } + + private async isNoMatchingNodeProviderHttpError( + error: unknown, + ): Promise { + if (!(error instanceof HttpError) || error.response === undefined) { + return false; + } + const payload = await tryReadErrorPayload(error.response.clone()); + return isNoMatchingNodeProviderErrorPayload(payload); + } + + async listSkeletons(): Promise { + const skeletonIds: unknown[] = + await this.fetchProjectEndpoint("skeletons/"); + return skeletonIds.map(parseCatmaidId); + } + + private async listStacks(): Promise<{ id: number }[]> { + return this.fetchProjectEndpoint("stacks"); + } + + private async getStackInfo(stackId: number): Promise { + return this.fetchProjectEndpoint(`stack/${stackId}/info`); + } + + private async loadMetadataInfo(): Promise { + const stacks = await this.listStacks(); + if (!stacks || stacks.length === 0) return null; + return this.getStackInfo(stacks[0].id); + } + + private getMetadataInfo(): Promise { + let promise = this.metadataInfoPromise; + if (promise === undefined) { + promise = this.loadMetadataInfo(); + this.metadataInfoPromise = promise; + promise.catch(() => { + if (this.metadataInfoPromise === promise) { + this.metadataInfoPromise = undefined; + } + }); + } + return promise; + } + + private async tryGetMetadataInfo(): Promise { + try { + return await this.getMetadataInfo(); + } catch (e) { + console.warn("Failed to fetch stack info:", e); + return null; + } + } + + private getSpatialIndexLevelsFromSpatialMetadata( + metadata: CatmaidStackInfo["metadata"], + bounds: BoundingBox, + ): SkeletonSpatialIndexLevel[] { + const spatial = metadata?.spatial; + if (spatial == null) { + return [getDefaultCatmaidSpatialIndexLevel(bounds)]; + } + if (!Array.isArray(spatial)) { + throw new Error( + "CATMAID stack metadata.spatial must be a spatial skeleton metadata array.", + ); + } + if (spatial.length === 0) { + return [getDefaultCatmaidSpatialIndexLevel(bounds)]; + } + const levels = spatial.map((level, index) => ({ + chunkSize: requireCatmaidPositiveRank3Vector( + level?.chunk_size, + `spatial skeleton metadata spatial[${index}].chunk_size`, + ), + limit: requireCatmaidNonNegativeInt( + level?.limit, + `spatial skeleton metadata spatial[${index}].limit`, + ), + })); + // CATMAID lists levels in any order. + const cellVolume = ({ chunkSize }: SkeletonSpatialIndexLevel) => + chunkSize[0] * chunkSize[1] * chunkSize[2]; + return levels.sort((a, b) => cellVolume(b) - cellVolume(a)); + } + + private getSpatialSkeletonReadonlyFromMetadataInfo( + info: CatmaidStackInfo, + ): boolean { + const { metadata } = info; + return ( + parseOptionalCatmaidBoolean( + metadata?.read_only, + "spatial skeleton metadata read_only", + ) ?? true + ); + } + + async getSpatialIndexMetadata(): Promise { + const info = await this.tryGetMetadataInfo(); + if (info === null) { + return null; + } + const bounds = getCatmaidProjectSpaceBounds(info); + return { + bounds, + spatial: this.getSpatialIndexLevelsFromSpatialMetadata( + info.metadata, + bounds, + ), + readonly: this.getSpatialSkeletonReadonlyFromMetadataInfo(info), + }; + } + + async getCacheProvider(): Promise { + const info = await this.tryGetMetadataInfo(); + return info?.metadata?.cache_provider; + } + + async getSkeleton( + skeletonId: bigint, + options: { signal?: AbortSignal } = {}, + ): Promise { + const { signal } = options; + let data: any; + try { + data = await this.fetchProjectEndpoint( + `skeletons/${skeletonId}/compact-detail?with_tags=true`, + { + signal, + }, + ); + } catch (error) { + if ( + error instanceof CatmaidNotFoundError || + (error instanceof HttpError && error.status === 404) + ) { + // A compact-detail 404 is authoritative absence regardless of which + // CATMAID error payload (or empty body) accompanied it. Keep this + // endpoint-specific instead of treating every CATMAID 404 as an + // empty resource. + return []; + } else { + throw error; + } + } + const rawNodes = Array.isArray(data?.[0]) ? data[0] : []; + const labelsByNodeId = parseCatmaidNodeLabels(data?.[2]); + const descriptionByNodeId = getCatmaidNodeDescriptions(labelsByNodeId); + const trueEndByNodeId = getCatmaidTrueEndNodes(labelsByNodeId); + const currentNodes = rawNodes.filter( + (node): node is any[] => Array.isArray(node) && node.length >= 8, + ); + return currentNodes.map((n) => { + const nodeId = parseCatmaidId(n[0]); + return { + nodeId, + parentNodeId: parseOptionalCatmaidId(n[1]), + position: new Float32Array([n[3], n[4], n[5]]), + segmentId: skeletonId, + attributes: setSkeletonNodeAttributes(undefined, { + radius: Number.isFinite(n[6]) ? n[6] : undefined, + confidence: Number.isFinite(n[7]) + ? mapCatmaidConfidenceToPercent(n[7]) + : undefined, + isTrueEnd: trueEndByNodeId.has(nodeId), + }), + description: descriptionByNodeId.get(nodeId), + }; + }); + } + + async fetchNodes( + bounds: BoundingBox, + lod: number = 0, + options: { + cacheProvider?: string; + signal?: AbortSignal; + } = {}, + ): Promise { + const { cacheProvider, signal } = options; + const normalizedBoundingBox = normalizeBoundingBoxForNodeList(bounds); + const params = new URLSearchParams({ + left: normalizedBoundingBox.left.toString(), + top: normalizedBoundingBox.top.toString(), + z1: normalizedBoundingBox.z1.toString(), + right: normalizedBoundingBox.right.toString(), + bottom: normalizedBoundingBox.bottom.toString(), + z2: normalizedBoundingBox.z2.toString(), + lod_type: "percent", + lod: lod.toString(), + format: "msgpack", + }); + + // Add cache provider if available + if (cacheProvider) { + params.append("src", cacheProvider); + } + + let data: any; + try { + data = await this.fetchProjectEndpoint( + `node/list?${params.toString()}`, + { signal, priority: "low" }, + true, + ); + } catch (error) { + if (await this.isNoMatchingNodeProviderHttpError(error)) { + return []; + } + throw error; + } + + if (isNoMatchingNodeProviderErrorPayload(data)) { + return []; + } + + if (!Array.isArray(data) || !Array.isArray(data[0])) { + throw new Error( + "CATMAID node/list endpoint returned an unexpected response format.", + ); + } + + // Check if limit was reached for the first LOD level + if (data[3]) { + console.warn( + "CATMAID node/list endpoint returned limit_reached=true. Some nodes may be missing.", + ); + } + + // Process first LOD level (data[0]) + const nodes: SkeletonNode[] = data[0].map((n: any[]) => + parseCatmaidNodeListRow(n), + ); + + // Process additional LOD levels. + const extraNodes = data[5]; + if (Array.isArray(extraNodes)) { + for (const lodLevel of extraNodes) { + if (lodLevel[3]) { + console.warn( + "CATMAID node/list endpoint returned limit_reached=true for an extra LOD level. Some nodes may be missing.", + ); + } + const treenodes = lodLevel[0]; + if (Array.isArray(treenodes)) { + for (const n of treenodes) { + nodes.push(parseCatmaidNodeListRow(n)); + } + } + } + } + + return nodes; + } + + async moveNode( + nodeId: bigint, + x: number, + y: number, + z: number, + ): Promise { + const body = new URLSearchParams(); + appendNodeUpdateRows(body, "t", [[nodeId, x, y, z]]); + appendUncheckedCatmaidState(body); + + await this.fetchProjectEndpoint(`node/update`, { + method: "POST", + body: body, + }); + } + + async rerootSkeleton(nodeId: bigint): Promise { + const body = new URLSearchParams({ + treenode_id: nodeId.toString(), + }); + appendUncheckedCatmaidState(body); + const response = await this.fetchProjectEndpoint(`skeleton/reroot`, { + method: "POST", + body, + }); + if (parseOptionalCatmaidId(response?.newroot) !== nodeId) { + throw new Error( + "CATMAID skeleton/reroot did not return the requested new root.", + ); + } + } + + async deleteNode(nodeId: bigint): Promise { + const body = new URLSearchParams({ + treenode_id: nodeId.toString(), + }); + appendUncheckedCatmaidState(body); + const response = await this.fetchProjectEndpoint(`treenode/delete`, { + method: "POST", + body: body, + }); + if (response?.success === undefined) { + throw new Error("Delete endpoint returned an unexpected response."); + } + } + + async addNode( + x: number, + y: number, + z: number, + parentId?: bigint, + ): Promise { + const body = new URLSearchParams({ + x: x.toString(), + y: y.toString(), + z: z.toString(), + parent_id: (parentId ?? -1).toString(), + }); + appendUncheckedCatmaidState(body); + + const res = await this.fetchProjectEndpoint(`treenode/create`, { + method: "POST", + body: body, + }); + return { + nodeId: parseCatmaidId(res?.treenode_id), + segmentId: parseCatmaidId(res?.skeleton_id), + }; + } + + async insertNode( + x: number, + y: number, + z: number, + parentId: bigint, + childNodeIds: readonly bigint[], + ): Promise { + const normalizedChildIds = [...new Set(childNodeIds)].sort(bigintCompare); + if (normalizedChildIds.length === 0) { + throw new Error( + "CATMAID insert-node requires at least one child node to reattach.", + ); + } + const body = new URLSearchParams({ + x: x.toString(), + y: y.toString(), + z: z.toString(), + parent_id: parentId.toString(), + child_id: normalizedChildIds[0].toString(), + }); + appendScalarList(body, "takeover_child_ids", normalizedChildIds.slice(1)); + appendUncheckedCatmaidState(body); + + const response = await this.fetchProjectEndpoint(`treenode/insert`, { + method: "POST", + body, + }); + return { + nodeId: parseCatmaidId(response?.treenode_id), + segmentId: parseCatmaidId(response?.skeleton_id), + }; + } + + private async updateNodeLabel( + nodeId: bigint, + endpoint: "update" | "remove", + body: URLSearchParams, + ) { + return this.fetchProjectEndpoint(`label/treenode/${nodeId}/${endpoint}`, { + method: "POST", + body, + }); + } + + private normalizeNodeLabels(labels: readonly string[]) { + const normalizedLabels: string[] = []; + const seen = new Set(); + for (const label of labels) { + const trimmed = label.trim(); + if (trimmed.length === 0) continue; + if (trimmed.includes(",")) { + throw new Error( + "Node labels containing commas are not supported by the CATMAID label update endpoint.", + ); + } + const key = trimmed.toLowerCase(); + if (seen.has(key)) continue; + seen.add(key); + normalizedLabels.push(trimmed); + } + return normalizedLabels; + } + + private normalizeDescriptionLabels(description: string) { + const normalizedLabels: string[] = []; + const seen = new Set(); + for (const label of description.split(/\r?\n/)) { + const trimmed = label.trim(); + if (trimmed.length === 0 || isCatmaidClosedEndLabel(trimmed)) continue; + const key = trimmed.toLowerCase(); + if (seen.has(key)) continue; + seen.add(key); + normalizedLabels.push(trimmed); + } + return normalizedLabels; + } + + private buildDescriptionUpdate(description: string) { + const normalizedDescriptionLabels = + this.normalizeDescriptionLabels(description); + if (normalizedDescriptionLabels.length === 0) { + return { labels: [], description: undefined }; + } + const normalizedDescription = normalizedDescriptionLabels.join("\n"); + const requiresEncodedDescription = + normalizedDescription.includes(",") || + normalizedDescriptionLabels.some((label) => + label.startsWith(CATMAID_ENCODED_DESCRIPTION_LABEL_PREFIX), + ); + return { + labels: requiresEncodedDescription + ? [makeCatmaidEncodedDescriptionLabel(normalizedDescription)] + : normalizedDescriptionLabels, + description: normalizedDescription, + }; + } + + private async replaceNodeLabels(nodeId: bigint, labels: readonly string[]) { + const normalizedLabels = this.normalizeNodeLabels(labels); + return this.updateNodeLabel( + nodeId, + "update", + new URLSearchParams({ + tags: normalizedLabels.join(","), + delete_existing: "true", + }), + ); + } + + private async addNodeLabel(nodeId: bigint, label: string) { + const normalizedLabel = label.trim(); + if (normalizedLabel.length === 0) { + throw new Error("Node label must not be empty."); + } + return this.updateNodeLabel( + nodeId, + "update", + new URLSearchParams({ + tags: normalizedLabel, + delete_existing: "false", + }), + ); + } + + private async removeNodeLabel(nodeId: bigint, label: string) { + const normalizedLabel = label.trim(); + if (normalizedLabel.length === 0) { + throw new Error("Node label must not be empty."); + } + return this.updateNodeLabel( + nodeId, + "remove", + new URLSearchParams({ tag: normalizedLabel }), + ); + } + + async updateDescription( + nodeId: bigint, + description: string, + options: CatmaidDescriptionUpdateOptions = {}, + ): Promise { + const descriptionUpdate = this.buildDescriptionUpdate(description); + const labels = + options.isTrueEnd === true + ? [...descriptionUpdate.labels, CATMAID_TRUE_END_LABEL] + : descriptionUpdate.labels; + await this.replaceNodeLabels(nodeId, labels); + return { + description: descriptionUpdate.description, + }; + } + + async toggleTrueEnd(nodeId: bigint, nextIsTrueEnd: boolean): Promise { + if (nextIsTrueEnd) { + await this.addNodeLabel(nodeId, CATMAID_TRUE_END_LABEL); + } else { + await this.removeNodeLabel(nodeId, CATMAID_TRUE_END_LABEL); + } + } + + async updateRadius(nodeId: bigint, radius: number): Promise { + if (!Number.isFinite(radius)) { + throw new Error("Radius must be a finite number."); + } + const body = new URLSearchParams({ + radius: radius.toString(), + }); + appendUncheckedCatmaidState(body); + await this.fetchProjectEndpoint(`treenode/${nodeId}/radius`, { + method: "POST", + body, + }); + } + + async updateConfidence(nodeId: bigint, confidence: number): Promise { + if (!Number.isFinite(confidence) || confidence < 0 || confidence > 100) { + throw new Error("Confidence must be between 0 and 100."); + } + const body = new URLSearchParams({ + new_confidence: mapPercentConfidenceToCatmaid(confidence).toString(), + }); + appendUncheckedCatmaidState(body); + await this.fetchProjectEndpoint(`treenodes/${nodeId}/confidence`, { + method: "POST", + body, + }); + } + + async mergeSkeletons( + fromNodeId: bigint, + toNodeId: bigint, + ): Promise { + const body = new URLSearchParams({ + from_id: fromNodeId.toString(), + to_id: toNodeId.toString(), + }); + appendUncheckedCatmaidState(body); + const response = await this.fetchProjectEndpoint(`skeleton/join`, { + method: "POST", + body, + }); + return { + resultSegmentId: parseOptionalCatmaidId(response?.result_skeleton_id), + deletedSegmentId: parseOptionalCatmaidId(response?.deleted_skeleton_id), + directionAdjusted: Boolean(response?.stable_annotation_swap), + }; + } + + async splitSkeleton(nodeId: bigint): Promise { + const body = new URLSearchParams({ + treenode_id: nodeId.toString(), + downstream_annotation_map: JSON.stringify({}), + }); + appendUncheckedCatmaidState(body); + const response = await this.fetchProjectEndpoint(`skeleton/split`, { + method: "POST", + body, + }); + return { + existingSegmentId: parseOptionalCatmaidId(response?.existing_skeleton_id), + newSegmentId: parseOptionalCatmaidId(response?.new_skeleton_id), + }; + } +} diff --git a/src/datasource/catmaid/backend.spec.ts b/src/datasource/catmaid/backend.spec.ts new file mode 100644 index 0000000000..ba31c59abc --- /dev/null +++ b/src/datasource/catmaid/backend.spec.ts @@ -0,0 +1,60 @@ +/** + * @license + * Copyright 2026 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { describe, expect, it, vi } from "vitest"; + +import { CatmaidSpatiallyIndexedSkeletonSourceBackend } from "#src/datasource/catmaid/backend.js"; + +describe("CatmaidSpatiallyIndexedSkeletonSourceBackend", () => { + it("downloads a chunk's region at the source's level of detail", async () => { + const signal = new AbortController().signal; + const fetchNodes = vi.fn().mockResolvedValue([]); + const source = Object.create( + CatmaidSpatiallyIndexedSkeletonSourceBackend.prototype, + ); + Object.defineProperties(source, { + client: { value: { fetchNodes } }, + parameters: { + value: { + catmaidLod: 0.5, + catmaidParameters: { cacheProvider: "cached_msgpack_grid" }, + }, + }, + spec: { + value: { + chunkDataSize: Float32Array.of(10, 20, 30), + }, + }, + }); + await CatmaidSpatiallyIndexedSkeletonSourceBackend.prototype.downloadChunk.call( + source, + Float32Array.of(2, 3, 4), + signal, + ); + + expect(fetchNodes).toHaveBeenCalledWith( + { + lowerBounds: Float64Array.of(20, 60, 120), + upperBounds: Float64Array.of(30, 80, 150), + }, + 0.5, + { + cacheProvider: "cached_msgpack_grid", + signal, + }, + ); + }); +}); diff --git a/src/datasource/catmaid/backend.ts b/src/datasource/catmaid/backend.ts new file mode 100644 index 0000000000..02c0e90abc --- /dev/null +++ b/src/datasource/catmaid/backend.ts @@ -0,0 +1,66 @@ +/** + * @license + * Copyright 2026 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file Downloads the CATMAID nodes of one spatial index chunk. It runs on the + * chunk worker. + */ + +import { WithParameters } from "#src/chunk_manager/backend.js"; +import { WithSharedCredentialsProviderCounterpart } from "#src/credentials_provider/shared_counterpart.js"; +import type { + CatmaidClient, + CatmaidToken, +} from "#src/datasource/catmaid/api.js"; +import { getCatmaidSpatialSkeletonGridCellBounds } from "#src/datasource/catmaid/api.js"; +import { + CatmaidSkeletonSourceParameters, + makeCatmaidClient, +} from "#src/datasource/catmaid/base.js"; +import { SpatiallyIndexedSkeletonSourceBackend } from "#src/skeleton/spatial/backend.js"; +import { registerSharedObject } from "#src/worker_rpc.js"; + +@registerSharedObject() +export class CatmaidSpatiallyIndexedSkeletonSourceBackend extends WithParameters( + WithSharedCredentialsProviderCounterpart()( + SpatiallyIndexedSkeletonSourceBackend, + ), + CatmaidSkeletonSourceParameters, +) { + private clientInstance: CatmaidClient | undefined; + + get client(): CatmaidClient { + return (this.clientInstance ??= makeCatmaidClient( + this.parameters.catmaidParameters, + this.credentialsProvider, + )); + } + + constructor(...args: any[]) { + super(args[0], args[1]); + } + + downloadChunk(chunkGridPosition: Float32Array, signal: AbortSignal) { + const bounds = getCatmaidSpatialSkeletonGridCellBounds( + chunkGridPosition, + this.spec.chunkDataSize, + ); + return this.client.fetchNodes(bounds, this.parameters.catmaidLod ?? 0, { + cacheProvider: this.parameters.catmaidParameters.cacheProvider, + signal, + }); + } +} diff --git a/src/datasource/catmaid/base.spec.ts b/src/datasource/catmaid/base.spec.ts new file mode 100644 index 0000000000..83a890c000 --- /dev/null +++ b/src/datasource/catmaid/base.spec.ts @@ -0,0 +1,53 @@ +/** + * @license + * Copyright 2026 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { describe, expect, it } from "vitest"; + +import { + getCatmaidLodForSpatialIndexLevel, + parseCatmaidUrl, +} from "#src/datasource/catmaid/base.js"; + +describe("CATMAID level of detail for each spatial index level", () => { + it("maps a single spatial index level to full CATMAID LOD", () => { + expect(getCatmaidLodForSpatialIndexLevel(0, 1)).toBe(1); + }); + + it("maps multiple spatial index levels from coarse to fine", () => { + expect(getCatmaidLodForSpatialIndexLevel(0, 3)).toBe(0); + expect(getCatmaidLodForSpatialIndexLevel(1, 3)).toBe(0.5); + expect(getCatmaidLodForSpatialIndexLevel(2, 3)).toBe(1); + }); +}); + +describe("CATMAID data source URL", () => { + it.each([ + "catmaid://catmaid.example.org/4", + "catmaid://catmaid.example.org", + "catmaid://localhost:8000/4", + ])("rejects %s because the protocol is missing", (url) => { + expect(() => parseCatmaidUrl(url)).toThrow( + `Invalid CATMAID URL "${url}": expected catmaid://:///`, + ); + }); + + it("reads the base URL and project ID when the protocol is present", () => { + expect(parseCatmaidUrl("catmaid://http://localhost:8000/4")).toEqual({ + baseUrl: "http://localhost:8000", + projectId: 4, + }); + }); +}); diff --git a/src/datasource/catmaid/base.ts b/src/datasource/catmaid/base.ts new file mode 100644 index 0000000000..e403899052 --- /dev/null +++ b/src/datasource/catmaid/base.ts @@ -0,0 +1,83 @@ +/** + * @license + * Copyright 2026 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file Defines the CATMAID source parameters and builds a CATMAID client from + * them on either thread. Parses a catmaid:// URL and maps a spatial index level + * to a CATMAID level of detail. + */ + +import type { CredentialsProvider } from "#src/credentials_provider/index.js"; +import type { CatmaidToken } from "#src/datasource/catmaid/api.js"; +import { CatmaidClient } from "#src/datasource/catmaid/api.js"; + +export class CatmaidDataSourceParameters { + url!: string; + projectId!: number; + cacheProvider?: string; +} + +export class CatmaidSkeletonSourceParameters { + catmaidParameters!: CatmaidDataSourceParameters; + gridIndex?: number; + catmaidLod?: number; + static RPC_ID = "catmaid/SkeletonSource"; +} + +export function getCatmaidLodForSpatialIndexLevel( + gridIndex: number, + gridLevelCount: number, +) { + const lastGridIndex = gridLevelCount - 1; + return lastGridIndex === 0 ? 1 : gridIndex / lastGridIndex; +} + +export function parseCatmaidUrl(providerUrl: string): { + baseUrl: string; + projectId: number; +} { + const schemePrefix = "catmaid://"; + const urlWithoutScheme = providerUrl.startsWith(schemePrefix) + ? providerUrl.substring(schemePrefix.length) + : providerUrl; + + const lastSlash = urlWithoutScheme.lastIndexOf("/"); + if (lastSlash === -1 || !/^[a-z]+:\/\//.test(urlWithoutScheme)) { + throw new Error( + `Invalid CATMAID URL ${JSON.stringify(providerUrl)}: expected catmaid://:///`, + ); + } + + const projectIdText = urlWithoutScheme.substring(lastSlash + 1); + const projectId = parseInt(projectIdText); + if (isNaN(projectId)) { + throw new Error(`Invalid project ID: ${projectIdText}`); + } + + const baseUrl = urlWithoutScheme.substring(0, lastSlash).replace(/\/+$/, ""); + return { baseUrl, projectId }; +} + +export function makeCatmaidClient( + parameters: CatmaidDataSourceParameters, + credentialsProvider?: CredentialsProvider, +) { + return new CatmaidClient( + parameters.url, + parameters.projectId, + credentialsProvider, + ); +} diff --git a/src/datasource/catmaid/credentials_provider.spec.ts b/src/datasource/catmaid/credentials_provider.spec.ts new file mode 100644 index 0000000000..ec4be18367 --- /dev/null +++ b/src/datasource/catmaid/credentials_provider.spec.ts @@ -0,0 +1,173 @@ +/** + * @license + * Copyright 2026 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { + CatmaidCredentialsProvider, + type CatmaidTokenStorage, + getCatmaidTokenStorageKey, +} from "#src/datasource/catmaid/credentials_provider.js"; +import { statusMessages } from "#src/status.js"; + +class MemoryTokenStorage implements CatmaidTokenStorage { + values = new Map(); + + getItem(key: string) { + return this.values.get(key) ?? null; + } + + setItem(key: string, value: string) { + this.values.set(key, value); + } + + removeItem(key: string) { + this.values.delete(key); + } +} + +function mockAnonymousToken(token = "anonymous-token") { + const fetchMock = vi.fn().mockResolvedValue( + new Response(JSON.stringify({ token }), { + status: 200, + headers: { "Content-Type": "application/json" }, + }), + ); + vi.stubGlobal("fetch", fetchMock); + return fetchMock; +} + +async function submitPersonalToken(token: string) { + await vi.waitFor(() => { + expect( + document.querySelector('input[aria-label="CATMAID API token"]'), + ).not.toBeNull(); + }); + const input = document.querySelector( + 'input[aria-label="CATMAID API token"]', + )!; + input.value = token; + input.form!.dispatchEvent( + new Event("submit", { bubbles: true, cancelable: true }), + ); +} + +afterEach(() => { + vi.unstubAllGlobals(); + for (const status of statusMessages) { + status.dispose(); + } +}); + +describe("CatmaidCredentialsProvider", () => { + it("uses anonymous credentials first when no personal token is stored", async () => { + const fetchMock = mockAnonymousToken(); + const provider = new CatmaidCredentialsProvider( + "https://catmaid.example/", + new MemoryTokenStorage(), + ); + + await expect(provider.get()).resolves.toMatchObject({ + credentials: { token: "anonymous-token", kind: "anonymous" }, + }); + expect(fetchMock).toHaveBeenCalledWith( + "https://catmaid.example/accounts/anonymous-api-token", + expect.objectContaining({ method: "GET" }), + ); + }); + + it("prompts after anonymous rejection and persists the personal token", async () => { + const fetchMock = mockAnonymousToken(); + const storage = new MemoryTokenStorage(); + const provider = new CatmaidCredentialsProvider( + "https://catmaid.example", + storage, + ); + const anonymous = await provider.get(); + + const personalPromise = provider.get(anonymous); + await submitPersonalToken(" personal-token "); + + await expect(personalPromise).resolves.toMatchObject({ + credentials: { token: "personal-token", kind: "personal" }, + }); + expect( + storage.getItem(getCatmaidTokenStorageKey("https://catmaid.example")), + ).toBe("personal-token"); + + const reloadedProvider = new CatmaidCredentialsProvider( + "https://catmaid.example///", + storage, + ); + await expect(reloadedProvider.get()).resolves.toMatchObject({ + credentials: { token: "personal-token", kind: "personal" }, + }); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it("clears a rejected personal token and validates its replacement", async () => { + const storage = new MemoryTokenStorage(); + storage.setItem( + getCatmaidTokenStorageKey("https://catmaid.example"), + "rejected-token", + ); + const provider = new CatmaidCredentialsProvider( + "https://catmaid.example", + storage, + ); + const rejected = await provider.get(); + + const replacementPromise = provider.get(rejected); + await submitPersonalToken(" "); + expect(document.querySelector('[role="alert"]')?.textContent).toContain( + "non-empty", + ); + await submitPersonalToken("replacement-token"); + + await expect(replacementPromise).resolves.toMatchObject({ + credentials: { token: "replacement-token", kind: "personal" }, + }); + expect( + storage.getItem(getCatmaidTokenStorageKey("https://catmaid.example")), + ).toBe("replacement-token"); + }); + + it("aborts and removes an outstanding token prompt", async () => { + mockAnonymousToken(); + const provider = new CatmaidCredentialsProvider( + "https://catmaid.example", + new MemoryTokenStorage(), + ); + const anonymous = await provider.get(); + const abortController = new AbortController(); + const reason = new Error("cancelled"); + + const personalPromise = provider.get(anonymous, { + signal: abortController.signal, + }); + await vi.waitFor(() => { + expect( + document.querySelector('input[aria-label="CATMAID API token"]'), + ).not.toBeNull(); + }); + abortController.abort(reason); + + await expect(personalPromise).rejects.toBe(reason); + expect( + document.querySelector('input[aria-label="CATMAID API token"]'), + ).toBeNull(); + }); +}); diff --git a/src/datasource/catmaid/credentials_provider.ts b/src/datasource/catmaid/credentials_provider.ts new file mode 100644 index 0000000000..b58cbdf943 --- /dev/null +++ b/src/datasource/catmaid/credentials_provider.ts @@ -0,0 +1,232 @@ +/** + * @license + * Copyright 2026 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file Uses the personal CATMAID API token kept in session storage, otherwise + * an anonymous token. Asks the user for a personal token when the server + * rejects the current one. + */ + +import { + CredentialsProvider, + makeCachedCredentialsGetter, +} from "#src/credentials_provider/index.js"; +import type { CatmaidToken } from "#src/datasource/catmaid/api.js"; +import { StatusMessage } from "#src/status.js"; +import { scopedAbortCallback } from "#src/util/abort.js"; +import { fetchOk } from "#src/util/http_request.js"; +import { ProgressSpan } from "#src/util/progress_listener.js"; + +const CATMAID_TOKEN_STORAGE_PREFIX = "neuroglancer:catmaid:api-token:v1:"; + +export interface CatmaidTokenStorage { + getItem(key: string): string | null; + setItem(key: string, value: string): void; + removeItem(key: string): void; +} + +export function canonicalizeCatmaidServerUrl(serverUrl: string) { + return serverUrl.replace(/\/+$/, ""); +} + +export function getCatmaidTokenStorageKey(serverUrl: string) { + return `${CATMAID_TOKEN_STORAGE_PREFIX}${canonicalizeCatmaidServerUrl( + serverUrl, + )}`; +} + +function getSessionTokenStorage(): CatmaidTokenStorage | undefined { + try { + return sessionStorage; + } catch { + return undefined; + } +} + +async function getAnonymousToken( + serverUrl: string, + signal: AbortSignal, +): Promise { + // serverUrl passed here is the base URL. + + const tokenUrl = `${serverUrl}/accounts/anonymous-api-token`; + + const response = await fetchOk(tokenUrl, { + method: "GET", + signal: signal, + }); + + const json = await response.json(); + if ( + typeof json === "object" && + json !== null && + typeof json.token === "string" + ) { + return { token: json.token, kind: "anonymous" }; + } + throw new Error( + `Unexpected response from ${tokenUrl}: ${JSON.stringify(json)}`, + ); +} + +function requestPersonalToken( + serverUrl: string, + signal: AbortSignal, +): Promise { + signal.throwIfAborted(); + const status = new StatusMessage(/*delay=*/ false, /*modal=*/ true); + status.setPreventFocusChangeOnMouseDown(false); + + const form = document.createElement("form"); + const instructions = document.createElement("p"); + instructions.append( + `A personal CATMAID API token is required for ${serverUrl}. `, + ); + const serverLink = document.createElement("a"); + serverLink.href = serverUrl; + serverLink.target = "_blank"; + serverLink.rel = "noopener noreferrer"; + serverLink.textContent = "Open CATMAID"; + instructions.append( + serverLink, + " and use the account menu to obtain an API token.", + ); + form.appendChild(instructions); + + const label = document.createElement("label"); + label.textContent = "API token: "; + const input = document.createElement("input"); + input.type = "password"; + input.autocomplete = "off"; + input.spellcheck = false; + input.setAttribute("aria-label", "CATMAID API token"); + label.appendChild(input); + form.appendChild(label); + + const submit = document.createElement("button"); + submit.type = "submit"; + submit.textContent = "Use token"; + form.appendChild(submit); + + const error = document.createElement("span"); + error.setAttribute("role", "alert"); + form.appendChild(error); + status.element.replaceChildren(form); + status.setVisible(true); + + const { promise, resolve, reject } = Promise.withResolvers(); + const abortCleanup = scopedAbortCallback(signal, (reason) => { + status.dispose(); + reject(reason); + }); + form.addEventListener("submit", (event) => { + event.preventDefault(); + const token = input.value.trim(); + if (token.length === 0) { + error.textContent = " Enter a non-empty API token."; + input.focus(); + return; + } + abortCleanup?.[Symbol.dispose](); + status.dispose(); + resolve(token); + }); + queueMicrotask(() => input.focus()); + return promise; +} + +export class CatmaidCredentialsProvider extends CredentialsProvider { + public readonly serverUrl: string; + private generation = 0; + private personalToken: string | undefined; + private readonly storageKey: string; + + constructor( + serverUrl: string, + private tokenStorage: + | CatmaidTokenStorage + | undefined = getSessionTokenStorage(), + ) { + super(); + this.serverUrl = canonicalizeCatmaidServerUrl(serverUrl); + this.storageKey = getCatmaidTokenStorageKey(this.serverUrl); + } + + private getStoredPersonalToken() { + if (this.personalToken !== undefined) return this.personalToken; + try { + const token = this.tokenStorage?.getItem(this.storageKey)?.trim(); + if (token) { + this.personalToken = token; + return token; + } + } catch { + // Browser storage can be disabled. In-memory credentials still work. + } + return undefined; + } + + private storePersonalToken(token: string) { + this.personalToken = token; + try { + this.tokenStorage?.setItem(this.storageKey, token); + } catch { + // Fall back to the in-memory copy. + } + } + + private clearPersonalToken(token: string) { + if (this.personalToken === token) { + this.personalToken = undefined; + } + try { + if (this.tokenStorage?.getItem(this.storageKey) === token) { + this.tokenStorage.removeItem(this.storageKey); + } + } catch { + // Ignore unavailable browser storage. + } + } + + get = makeCachedCredentialsGetter( + async (invalidCredentials, options) => { + using _span = new ProgressSpan(options.progressListener, { + message: `Requesting CATMAID access token from ${this.serverUrl}`, + }); + + let credentials: CatmaidToken; + if (invalidCredentials === undefined) { + const storedToken = this.getStoredPersonalToken(); + credentials = + storedToken === undefined + ? await getAnonymousToken(this.serverUrl, options.signal) + : { token: storedToken, kind: "personal" }; + } else { + if (invalidCredentials.credentials.kind === "personal") { + this.clearPersonalToken(invalidCredentials.credentials.token); + } + const token = await requestPersonalToken( + this.serverUrl, + options.signal, + ); + this.storePersonalToken(token); + credentials = { token, kind: "personal" }; + } + + return { generation: ++this.generation, credentials }; + }, + ); +} diff --git a/src/datasource/catmaid/frontend.ts b/src/datasource/catmaid/frontend.ts new file mode 100644 index 0000000000..a0cb51e054 --- /dev/null +++ b/src/datasource/catmaid/frontend.ts @@ -0,0 +1,276 @@ +/** + * @license + * Copyright 2026 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file Opens a catmaid:// data source with its spatially indexed skeletons, + * editable unless the project is read-only, its segment property map and its + * bounds. It runs on the main thread. + */ + +import { makeDataBoundsBoundingBoxAnnotationSet } from "#src/annotation/index.js"; +import type { ChunkManager } from "#src/chunk_manager/frontend.js"; +import { WithParameters } from "#src/chunk_manager/frontend.js"; +import { + makeCoordinateSpace, + makeIdentityTransform, +} from "#src/coordinate_transform.js"; +import { WithCredentialsProvider } from "#src/credentials_provider/chunk_source_frontend.js"; +import type { CredentialsProvider } from "#src/credentials_provider/index.js"; +import type { + CatmaidClient, + CatmaidToken, +} from "#src/datasource/catmaid/api.js"; +import { + CATMAID_SPATIAL_SKELETON_CONFIDENCE_VALUES, + credentialsKey, +} from "#src/datasource/catmaid/api.js"; +import { + CatmaidSkeletonSourceParameters, + CatmaidDataSourceParameters, + getCatmaidLodForSpatialIndexLevel, + makeCatmaidClient, + parseCatmaidUrl, +} from "#src/datasource/catmaid/base.js"; +import { CatmaidSpatialSkeletonEditCommands } from "#src/datasource/catmaid/spatial_skeleton_edit/command_factories.js"; +import type { + DataSource, + DataSourceProvider, + GetDataSourceOptions, +} from "#src/datasource/index.js"; +import { + SegmentPropertyMap, + normalizeInlineSegmentPropertyMap, +} from "#src/segmentation_display_state/property_map.js"; +import { + SkeletonEdgeDirection, + type EditableSkeletonSource, + type SkeletonEdge, + type SkeletonFragment, + type SkeletonFragmentNode, + type SkeletonManifest, + type SkeletonSpatialIndexMetadata, +} from "#src/skeleton/api.js"; +import { SkeletonDataSourceState } from "#src/skeleton/find_path/find_path.js"; +import { + SpatiallyIndexedSkeletonSource, + MultiscaleSpatiallyIndexedSkeletonSource, +} from "#src/skeleton/spatial/frontend.js"; +import { mat4 } from "#src/util/geom.js"; +import "#src/datasource/catmaid/register_credentials_provider.js"; + +export class CatmaidSpatiallyIndexedSkeletonSource extends WithParameters( + WithCredentialsProvider()(SpatiallyIndexedSkeletonSource), + CatmaidSkeletonSourceParameters, +) {} + +class CatmaidSkeletonSource + extends CatmaidSpatialSkeletonEditCommands + implements EditableSkeletonSource +{ + readonly confidenceValues = CATMAID_SPATIAL_SKELETON_CONFIDENCE_VALUES; + readonly edgeDirection = SkeletonEdgeDirection.CHILD_TO_PARENT; + + constructor(private readonly catmaidClient: CatmaidClient) { + super({ getClient: () => catmaidClient }); + } + + // One compact-detail request returns a whole skeleton. + async getSkeletonManifest(): Promise { + return { fragmentKeys: ["skeleton"] }; + } + + async getSkeletonFragment( + skeletonId: bigint, + _fragmentKey: string, + signal: AbortSignal, + ): Promise { + const skeletonNodes = await this.catmaidClient.getSkeleton(skeletonId, { + signal, + }); + const nodes: SkeletonFragmentNode[] = []; + const edges: SkeletonEdge[] = []; + for (const { parentNodeId, ...node } of skeletonNodes) { + nodes.push(node); + if (parentNodeId !== undefined) { + edges.push({ firstNodeId: node.nodeId, secondNodeId: parentNodeId }); + } + } + return { nodes, edges }; + } +} + +interface CatmaidLevelSourceOptions { + readonly baseUrl: string; + readonly projectId: number; + readonly cacheProvider: string | undefined; + readonly credentialsProvider: CredentialsProvider; +} + +class CatmaidMultiscaleSpatiallyIndexedSkeletonSource extends MultiscaleSpatiallyIndexedSkeletonSource { + readonly fragmentSource: CatmaidSkeletonSource; + readonly editableSource: CatmaidSkeletonSource | undefined; + + constructor( + chunkManager: ChunkManager, + metadata: SkeletonSpatialIndexMetadata, + client: CatmaidClient, + readonly: boolean, + private readonly levelSourceOptions: CatmaidLevelSourceOptions, + ) { + super(chunkManager, metadata); + this.fragmentSource = new CatmaidSkeletonSource(client); + this.editableSource = readonly ? undefined : this.fragmentSource; + } + + getSources() { + const { baseUrl, projectId, cacheProvider, credentialsProvider } = + this.levelSourceOptions; + const specs = this.getLevelSpecs(); + return [ + specs.map((spec, coarseToFineIndex) => { + const parameters = new CatmaidSkeletonSourceParameters(); + parameters.catmaidParameters = new CatmaidDataSourceParameters(); + parameters.catmaidParameters.url = baseUrl; + parameters.catmaidParameters.projectId = projectId; + parameters.catmaidParameters.cacheProvider = cacheProvider; + parameters.gridIndex = coarseToFineIndex; + parameters.catmaidLod = getCatmaidLodForSpatialIndexLevel( + coarseToFineIndex, + specs.length, + ); + return { + chunkSource: this.chunkManager.getChunkSource( + CatmaidSpatiallyIndexedSkeletonSource, + { parameters, spec, credentialsProvider }, + ), + chunkToMultiscaleTransform: mat4.create(), + }; + }), + ]; + } +} + +export class CatmaidDataSourceProvider implements DataSourceProvider { + get scheme() { + return "catmaid"; + } + + get description() { + return "CATMAID"; + } + + async get(options: GetDataSourceOptions): Promise { + const { providerUrl } = options; + const state = new SkeletonDataSourceState(options.state); + + const { baseUrl, projectId } = parseCatmaidUrl(providerUrl); + + const credentialsProvider = + options.registry.credentialsManager.getCredentialsProvider( + credentialsKey, + { serverUrl: baseUrl }, + ) as CredentialsProvider; + + const client = makeCatmaidClient( + { url: baseUrl, projectId }, + credentialsProvider, + ); + + // Fetch project metadata, cache-provider configuration, and skeleton IDs concurrently. + const [spatialIndexMetadata, cacheProvider, skeletonIds] = + await Promise.all([ + options.registry.chunkManager.memoize.getAsync( + { type: "catmaid:spatial-index-metadata", baseUrl, projectId }, + options, + () => client.getSpatialIndexMetadata(), + ), + options.registry.chunkManager.memoize.getAsync( + { type: "catmaid:cache-provider", baseUrl, projectId }, + options, + () => client.getCacheProvider(), + ), + options.registry.chunkManager.memoize.getAsync( + { type: "catmaid:skeletons", baseUrl, projectId }, + options, + () => client.listSkeletons(), + ), + ]); + + if (spatialIndexMetadata === null) { + throw new Error("Failed to fetch CATMAID spatial index metadata"); + } + + const { bounds, spatial, readonly: sourceReadonly } = spatialIndexMetadata; + // The model-space coordinates we emit are in nanometers, converted to meters for Neuroglancer. + const modelSpace = makeCoordinateSpace({ + names: ["x", "y", "z"], + units: ["m", "m", "m"], + scales: Float64Array.from([1e-9, 1e-9, 1e-9]), + boundingBoxes: [ + { + box: bounds, + transform: Float64Array.from([1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]), + }, + ], + }); + + const multiscaleSource = + new CatmaidMultiscaleSpatiallyIndexedSkeletonSource( + options.registry.chunkManager, + { modelSpace, levels: spatial }, + client, + sourceReadonly, + { baseUrl, projectId, cacheProvider, credentialsProvider }, + ); + // Create SegmentPropertyMap + const ids = BigUint64Array.from(skeletonIds); + + const propertyMap = new SegmentPropertyMap({ + inlineProperties: normalizeInlineSegmentPropertyMap({ + ids, + properties: [], + }), + }); + + const subsources = [ + { + id: "skeletons", + default: true, + subsource: { spatialSkeleton: multiscaleSource }, + }, + { + id: "properties", + default: true, + subsource: { segmentPropertyMap: propertyMap }, + }, + { + id: "bounds", + default: true, + subsource: { + staticAnnotations: makeDataBoundsBoundingBoxAnnotationSet( + modelSpace.bounds, + ), + }, + }, + ]; + + return { + modelTransform: makeIdentityTransform(modelSpace), + subsources, + state, + }; + } +} diff --git a/src/datasource/catmaid/register_credentials_provider.ts b/src/datasource/catmaid/register_credentials_provider.ts new file mode 100644 index 0000000000..9e72699704 --- /dev/null +++ b/src/datasource/catmaid/register_credentials_provider.ts @@ -0,0 +1,30 @@ +/** + * @license + * Copyright 2026 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file Registers the CATMAID credentials provider as the default for CATMAID + * servers. + */ + +import { registerDefaultCredentialsProvider } from "#src/credentials_provider/default_manager.js"; +import { credentialsKey } from "#src/datasource/catmaid/api.js"; +import { CatmaidCredentialsProvider } from "#src/datasource/catmaid/credentials_provider.js"; + +registerDefaultCredentialsProvider( + credentialsKey, + (params: { serverUrl: string }) => + new CatmaidCredentialsProvider(params.serverUrl), +); diff --git a/src/datasource/catmaid/register_default.ts b/src/datasource/catmaid/register_default.ts new file mode 100644 index 0000000000..1578c0546d --- /dev/null +++ b/src/datasource/catmaid/register_default.ts @@ -0,0 +1,24 @@ +/** + * @license + * Copyright 2026 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file Registers the catmaid:// data source provider. + */ + +import { CatmaidDataSourceProvider } from "#src/datasource/catmaid/frontend.js"; +import { registerProvider } from "#src/datasource/default_provider.js"; + +registerProvider(new CatmaidDataSourceProvider()); diff --git a/src/datasource/catmaid/spatial_skeleton_edit/command_factories.spec.ts b/src/datasource/catmaid/spatial_skeleton_edit/command_factories.spec.ts new file mode 100644 index 0000000000..bf74984b0b --- /dev/null +++ b/src/datasource/catmaid/spatial_skeleton_edit/command_factories.spec.ts @@ -0,0 +1,92 @@ +/** + * @license + * Copyright 2026 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { describe, expect, it } from "vitest"; + +import type { CatmaidClient } from "#src/datasource/catmaid/api.js"; +import { + CatmaidSpatialSkeletonEditCommands, + getCatmaidMergeQueueInputRequirements, + getCatmaidQueueInputRequirements, +} from "#src/datasource/catmaid/spatial_skeleton_edit/command_factories.js"; + +function makeCommands() { + return new CatmaidSpatialSkeletonEditCommands({ + getClient: () => ({}) as CatmaidClient, + }); +} + +describe("CATMAID edit commands", () => { + it("keeps the children an insert was created with when the caller's array changes later", () => { + const childNodeIds = [2n]; + const command = makeCommands().insertNodesCommand.createCommand({ + skeletonId: 23n, + parentNodeId: 1n, + childNodeIds, + positionInModelSpace: [1, 2, 3], + }); + childNodeIds.push(3n); + expect((command as any).payload.options.childNodeIds).toEqual([2n]); + }); + + it("rejects an insert with no children, a repeated child, or a child that is not an ID", () => { + const commands = makeCommands(); + for (const children of [[], [2n, 2n], [NaN]]) { + expect(() => + commands.insertNodesCommand.createCommand({ + skeletonId: 23n, + parentNodeId: 1n, + childNodeIds: children, + positionInModelSpace: [1, 2, 3], + }), + ).toThrow(/invalid payload/); + } + }); + + it("refuses a move whose node is malformed, naming the command", () => { + expect(() => + makeCommands().moveNodesCommand.createCommand({ + node: {}, + nextPositionInModelSpace: new Float32Array([7, 8, 9]), + }), + ).toThrow("CATMAID move-node command received an invalid payload."); + }); +}); + +describe("CATMAID queue input requirements", () => { + it("deduplicates required endpoints", () => { + const endpoint = { segmentId: 7n, nodeId: 11n }; + expect(getCatmaidQueueInputRequirements(endpoint, endpoint)).toEqual({ + required: [endpoint], + }); + }); + + it("declares the Merge destination as loadable", () => { + const source = { segmentId: 7n, nodeId: 11n }; + const target = { segmentId: 8n, nodeId: 12n }; + expect(getCatmaidMergeQueueInputRequirements(source, target)).toEqual({ + required: [source], + loadable: [target], + }); + }); + + it("does not expose a duplicate required endpoint as loadable", () => { + const endpoint = { segmentId: 7n, nodeId: 11n }; + expect(getCatmaidMergeQueueInputRequirements(endpoint, endpoint)).toEqual({ + required: [endpoint], + }); + }); +}); diff --git a/src/datasource/catmaid/spatial_skeleton_edit/command_factories.ts b/src/datasource/catmaid/spatial_skeleton_edit/command_factories.ts new file mode 100644 index 0000000000..501b5326af --- /dev/null +++ b/src/datasource/catmaid/spatial_skeleton_edit/command_factories.ts @@ -0,0 +1,581 @@ +/** + * @license + * Copyright 2026 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file Turns spatial skeleton edit actions into CATMAID commands. Sends their + * requests to a CATMAID client. + */ + +import type { CatmaidClient } from "#src/datasource/catmaid/api.js"; +import { + requireCatmaidAddNodeCommandOptions, + requireCatmaidDeleteNodeCommandPayload, + requireCatmaidInsertNodeCommandOptions, + requireCatmaidMergeCommandPayload, + requireCatmaidMoveNodeCommandOptions, + requireCatmaidNodeConfidenceCommandOptions, + requireCatmaidNodeDescriptionCommandOptions, + requireCatmaidNodeRadiusCommandOptions, + requireCatmaidNodeTrueEndCommandOptions, + requireCatmaidRerootCommandPayload, + requireCatmaidSplitCommandPayload, + type CatmaidSpatialSkeletonCommandPayload, +} from "#src/datasource/catmaid/spatial_skeleton_edit/command_payloads.js"; +import type { + CatmaidSpatialSkeletonAddNodeRequest, + CatmaidSpatialSkeletonAddNodeResult, + CatmaidSpatialSkeletonConfidenceUpdateRequest, + CatmaidSpatialSkeletonDeleteNodeRequest, + CatmaidSpatialSkeletonDescriptionUpdateRequest, + CatmaidSpatialSkeletonDescriptionUpdateResult, + CatmaidSpatialSkeletonInsertNodeRequest, + CatmaidSpatialSkeletonInsertNodeResult, + CatmaidSpatialSkeletonMergeRequest, + CatmaidSpatialSkeletonMergeResult, + CatmaidSpatialSkeletonMoveNodeRequest, + CatmaidSpatialSkeletonRadiusUpdateRequest, + CatmaidSpatialSkeletonRerootRequest, + CatmaidSpatialSkeletonSplitRequest, + CatmaidSpatialSkeletonSplitResult, + CatmaidSpatialSkeletonTrueEndUpdateRequest, + CatmaidSpatialSkeletonEditOperations, +} from "#src/datasource/catmaid/spatial_skeleton_edit/edit_operations.js"; +import type { CatmaidSpatialSkeletonCommandDescriptor } from "#src/datasource/catmaid/spatial_skeleton_edit/edit_planner.js"; +import { + CATMAID_PROVISIONAL_NUMERIC_ID_POLICY, + CatmaidEditPlanner, +} from "#src/datasource/catmaid/spatial_skeleton_edit/edit_planner.js"; +import { + CatmaidEditRequests, + getCatmaidEditRequestScope, +} from "#src/datasource/catmaid/spatial_skeleton_edit/edit_requests.js"; +import type { SkeletonNode, SkeletonVector } from "#src/skeleton/api.js"; +import type { + SpatialSkeletonAction, + SpatialSkeletonCommandContext, + SpatialSkeletonEditCommand, + SpatialSkeletonEditCommandFactory, +} from "#src/skeleton/edit/edit_commands.js"; +import { SpatialSkeletonActions } from "#src/skeleton/edit/edit_commands.js"; +import type { + SpatialSkeletonEditPlannerRegistration, + SpatialSkeletonEditPlannerProvider, +} from "#src/skeleton/edit_queue/api.js"; +import type { + SpatialSkeletonQueueInputRequirement, + SpatialSkeletonQueueInputRequirements, +} from "#src/skeleton/edit_queue/queue_input.js"; + +/** Resolve the current skeleton/node IDs required by a CATMAID queue input. */ +function getCatmaidQueueInputRequirement( + context: SpatialSkeletonCommandContext, + stableSegmentId: bigint | undefined, + stableNodeId: bigint | undefined, +): SpatialSkeletonQueueInputRequirement | undefined { + const segmentId = + stableSegmentId === undefined + ? undefined + : (context.identities.resolveSegment( + context.identities.getOrCreateSegmentHandle(stableSegmentId), + ) ?? stableSegmentId); + if (segmentId === undefined || segmentId === 0n) { + return undefined; + } + const nodeId = + stableNodeId === undefined + ? undefined + : (context.identities.resolveNode( + context.identities.getOrCreateNodeHandle(stableNodeId), + ) ?? stableNodeId); + return { + segmentId, + nodeId: nodeId === 0n ? undefined : nodeId, + }; +} + +export function getCatmaidQueueInputRequirements( + ...requirements: readonly (SpatialSkeletonQueueInputRequirement | undefined)[] +): SpatialSkeletonQueueInputRequirements { + const unique = new Map(); + for (const requirement of requirements) { + if (requirement === undefined) continue; + const key = `${requirement.segmentId}:${requirement.nodeId ?? ""}`; + if (!unique.has(key)) unique.set(key, Object.freeze({ ...requirement })); + } + return Object.freeze({ required: Object.freeze([...unique.values()]) }); +} + +export function getCatmaidMergeQueueInputRequirements( + required: SpatialSkeletonQueueInputRequirement | undefined, + mergeTarget: SpatialSkeletonQueueInputRequirement | undefined, +): SpatialSkeletonQueueInputRequirements { + if ( + required !== undefined && + mergeTarget !== undefined && + required.segmentId === mergeTarget.segmentId && + required.nodeId === mergeTarget.nodeId + ) { + return getCatmaidQueueInputRequirements(required); + } + return Object.freeze({ + required: getCatmaidQueueInputRequirements(required).required, + ...(mergeTarget === undefined + ? {} + : { loadable: Object.freeze([Object.freeze({ ...mergeTarget })]) }), + }); +} + +export interface CatmaidSpatialSkeletonEditCommandContext { + getClient(): CatmaidClient; +} + +function getCatmaidEditPosition( + position: SkeletonVector, +): readonly [number, number, number] { + const value = Array.from(position, Number); + return Object.freeze([value[0]!, value[1]!, value[2]!] as const); +} + +function cloneNode(node: SkeletonNode) { + return Object.freeze({ + ...node, + position: getCatmaidEditPosition(node.position), + }); +} + +function freezePayload( + payload: CatmaidSpatialSkeletonCommandPayload, +): CatmaidSpatialSkeletonCommandPayload { + switch (payload.kind) { + case "add-node": + return Object.freeze({ + kind: payload.kind, + options: Object.freeze({ + ...payload.options, + ...(payload.options.childNodeIds === undefined + ? {} + : { + childNodeIds: Object.freeze([...payload.options.childNodeIds]), + }), + positionInModelSpace: getCatmaidEditPosition( + payload.options.positionInModelSpace, + ), + }), + }); + case "move-node": + return Object.freeze({ + kind: payload.kind, + options: Object.freeze({ + node: cloneNode(payload.options.node), + nextPositionInModelSpace: getCatmaidEditPosition( + payload.options.nextPositionInModelSpace, + ), + }), + }); + case "delete-node": + return Object.freeze({ + kind: payload.kind, + node: cloneNode(payload.node), + }); + case "reroot": + case "split": + return Object.freeze({ + kind: payload.kind, + node: Object.freeze({ + ...payload.node, + ...(payload.node.position === undefined + ? {} + : { + position: getCatmaidEditPosition(payload.node.position), + }), + }), + }); + case "description": + case "true-end": + case "radius": + case "confidence": + return Object.freeze({ + kind: payload.kind, + options: Object.freeze({ + ...payload.options, + node: cloneNode(payload.options.node), + }), + }) as CatmaidSpatialSkeletonCommandPayload; + case "merge": + return Object.freeze({ + kind: payload.kind, + options: Object.freeze({ + firstNode: Object.freeze({ + ...payload.options.firstNode, + ...(payload.options.firstNode.position === undefined + ? {} + : { + position: getCatmaidEditPosition( + payload.options.firstNode.position, + ), + }), + }), + secondNode: Object.freeze({ + ...payload.options.secondNode, + ...(payload.options.secondNode.position === undefined + ? {} + : { + position: getCatmaidEditPosition( + payload.options.secondNode.position, + ), + }), + }), + }), + }); + } +} + +function getQueueInputRequirements( + payload: CatmaidSpatialSkeletonCommandPayload, + context: SpatialSkeletonCommandContext, +): SpatialSkeletonQueueInputRequirements { + switch (payload.kind) { + case "add-node": + if (payload.options.parentNodeId === undefined) { + return getCatmaidQueueInputRequirements(); + } + return getCatmaidQueueInputRequirements( + getCatmaidQueueInputRequirement( + context, + payload.options.skeletonId, + payload.options.parentNodeId, + ), + ...(payload.options.childNodeIds ?? []).map((nodeId) => + getCatmaidQueueInputRequirement( + context, + payload.options.skeletonId, + nodeId, + ), + ), + ); + case "move-node": + case "description": + case "true-end": + case "radius": + case "confidence": + return getCatmaidQueueInputRequirements( + getCatmaidQueueInputRequirement( + context, + payload.options.node.segmentId, + payload.options.node.nodeId, + ), + ); + case "delete-node": + return getCatmaidQueueInputRequirements( + getCatmaidQueueInputRequirement( + context, + payload.node.segmentId, + payload.node.nodeId, + ), + ); + case "reroot": + case "split": + return getCatmaidQueueInputRequirements( + getCatmaidQueueInputRequirement( + context, + payload.node.segmentId, + payload.node.nodeId, + ), + ); + case "merge": + return getCatmaidMergeQueueInputRequirements( + getCatmaidQueueInputRequirement( + context, + payload.options.firstNode.segmentId, + payload.options.firstNode.nodeId, + ), + getCatmaidQueueInputRequirement( + context, + payload.options.secondNode.segmentId, + payload.options.secondNode.nodeId, + ), + ); + } +} + +function makeCommandDescriptor( + action: SpatialSkeletonAction, + label: string, + payload: CatmaidSpatialSkeletonCommandPayload, +): CatmaidSpatialSkeletonCommandDescriptor { + const retainedPayload = freezePayload(payload); + return Object.freeze({ + action, + label, + payload: retainedPayload, + getQueueInputRequirements(context: SpatialSkeletonCommandContext) { + return getQueueInputRequirements(retainedPayload, context); + }, + }); +} + +function makeCatmaidCommandFactory( + action: TAction, + createCommand: (payload: object) => SpatialSkeletonEditCommand, +): SpatialSkeletonEditCommandFactory { + return { + action, + createCommand, + }; +} + +export class CatmaidSpatialSkeletonEditCommands { + private readonly editOperations: CatmaidSpatialSkeletonEditOperations; + + constructor( + private readonly context: CatmaidSpatialSkeletonEditCommandContext, + ) { + let editRequestScope: object | undefined; + this.editOperations = Object.freeze({ + get editRequestScope() { + return (editRequestScope ??= getCatmaidEditRequestScope( + context.getClient(), + )); + }, + commitAddNode: (request) => this.commitAddNode(request), + commitInsertNode: (request) => this.commitInsertNode(request), + commitMoveNode: (request) => this.commitMoveNode(request), + commitDeleteNode: (request) => this.commitDeleteNode(request), + commitReroot: (request) => this.commitReroot(request), + commitDescription: (request) => this.commitDescription(request), + commitTrueEnd: (request) => this.commitTrueEnd(request), + commitRadius: (request) => this.commitRadius(request), + commitConfidence: (request) => this.commitConfidence(request), + commitMerge: (request) => this.commitMerge(request), + commitSplit: (request) => this.commitSplit(request), + }); + } + + readonly editPlannerProvider: SpatialSkeletonEditPlannerProvider = { + createPlanner: ({ identities, provisionalIds }) => { + const registration: SpatialSkeletonEditPlannerRegistration = { + planner: new CatmaidEditPlanner(identities, provisionalIds), + editRequestAdapter: new CatmaidEditRequests(this.editOperations), + provisionalNumericIdPolicy: CATMAID_PROVISIONAL_NUMERIC_ID_POLICY, + }; + return registration; + }, + }; + + readonly addNodesCommand = makeCatmaidCommandFactory( + SpatialSkeletonActions.addNodes, + (payload) => + makeCommandDescriptor(SpatialSkeletonActions.addNodes, "Add node", { + kind: "add-node", + options: requireCatmaidAddNodeCommandOptions(payload), + }), + ); + + readonly insertNodesCommand = makeCatmaidCommandFactory( + SpatialSkeletonActions.insertNodes, + (payload) => + makeCommandDescriptor(SpatialSkeletonActions.insertNodes, "Insert node", { + kind: "add-node", + options: requireCatmaidInsertNodeCommandOptions(payload), + }), + ); + + readonly moveNodesCommand = makeCatmaidCommandFactory( + SpatialSkeletonActions.moveNodes, + (payload) => + makeCommandDescriptor(SpatialSkeletonActions.moveNodes, "Move node", { + kind: "move-node", + options: requireCatmaidMoveNodeCommandOptions(payload), + }), + ); + + readonly deleteNodesCommand = makeCatmaidCommandFactory( + SpatialSkeletonActions.deleteNodes, + (payload) => + makeCommandDescriptor(SpatialSkeletonActions.deleteNodes, "Delete node", { + kind: "delete-node", + node: requireCatmaidDeleteNodeCommandPayload(payload), + }), + ); + + readonly rerootCommand = makeCatmaidCommandFactory( + SpatialSkeletonActions.reroot, + (payload) => + makeCommandDescriptor(SpatialSkeletonActions.reroot, "Reroot skeleton", { + kind: "reroot", + node: requireCatmaidRerootCommandPayload(payload), + }), + ); + + readonly editNodeDescriptionCommand = makeCatmaidCommandFactory( + SpatialSkeletonActions.editNodeDescription, + (payload) => + makeCommandDescriptor( + SpatialSkeletonActions.editNodeDescription, + "Edit node description", + { + kind: "description", + options: requireCatmaidNodeDescriptionCommandOptions(payload), + }, + ), + ); + + readonly editNodeTrueEndCommand = makeCatmaidCommandFactory( + SpatialSkeletonActions.editNodeTrueEnd, + (payload) => + makeCommandDescriptor( + SpatialSkeletonActions.editNodeTrueEnd, + "Edit node true end state", + { + kind: "true-end", + options: requireCatmaidNodeTrueEndCommandOptions(payload), + }, + ), + ); + + readonly editNodeRadiusCommand = makeCatmaidCommandFactory( + SpatialSkeletonActions.editNodeRadius, + (payload) => + makeCommandDescriptor( + SpatialSkeletonActions.editNodeRadius, + "Edit node radius", + { + kind: "radius", + options: requireCatmaidNodeRadiusCommandOptions(payload), + }, + ), + ); + + readonly editNodeConfidenceCommand = makeCatmaidCommandFactory( + SpatialSkeletonActions.editNodeConfidence, + (payload) => + makeCommandDescriptor( + SpatialSkeletonActions.editNodeConfidence, + "Edit node confidence", + { + kind: "confidence", + options: requireCatmaidNodeConfidenceCommandOptions(payload), + }, + ), + ); + + readonly mergeSkeletonsCommand = makeCatmaidCommandFactory( + SpatialSkeletonActions.mergeSkeletons, + (payload) => + makeCommandDescriptor( + SpatialSkeletonActions.mergeSkeletons, + "Merge skeletons", + { + kind: "merge", + options: requireCatmaidMergeCommandPayload(payload), + }, + ), + ); + + readonly splitSkeletonsCommand = makeCatmaidCommandFactory( + SpatialSkeletonActions.splitSkeletons, + (payload) => + makeCommandDescriptor( + SpatialSkeletonActions.splitSkeletons, + "Split skeleton", + { + kind: "split", + node: requireCatmaidSplitCommandPayload(payload), + }, + ), + ); + + private get client() { + return this.context.getClient(); + } + + private commitAddNode( + request: CatmaidSpatialSkeletonAddNodeRequest, + ): Promise { + const [x, y, z] = getCatmaidEditPosition(request.position); + return this.client.addNode(x, y, z, request.parentNodeId); + } + + private commitInsertNode( + request: CatmaidSpatialSkeletonInsertNodeRequest, + ): Promise { + const [x, y, z] = getCatmaidEditPosition(request.position); + return this.client.insertNode( + x, + y, + z, + request.parentNodeId, + request.childNodeIds, + ); + } + + private commitMoveNode( + request: CatmaidSpatialSkeletonMoveNodeRequest, + ): Promise { + const [x, y, z] = getCatmaidEditPosition(request.position); + return this.client.moveNode(request.nodeId, x, y, z); + } + + private commitDeleteNode( + request: CatmaidSpatialSkeletonDeleteNodeRequest, + ): Promise { + return this.client.deleteNode(request.nodeId); + } + + private commitReroot( + request: CatmaidSpatialSkeletonRerootRequest, + ): Promise { + return this.client.rerootSkeleton(request.nodeId); + } + + private commitDescription( + request: CatmaidSpatialSkeletonDescriptionUpdateRequest, + ): Promise { + return this.client.updateDescription(request.nodeId, request.description, { + isTrueEnd: request.isTrueEnd, + }); + } + + private commitTrueEnd( + request: CatmaidSpatialSkeletonTrueEndUpdateRequest, + ): Promise { + return this.client.toggleTrueEnd(request.nodeId, request.isTrueEnd); + } + + private commitRadius( + request: CatmaidSpatialSkeletonRadiusUpdateRequest, + ): Promise { + return this.client.updateRadius(request.nodeId, request.radius); + } + + private commitConfidence( + request: CatmaidSpatialSkeletonConfidenceUpdateRequest, + ): Promise { + return this.client.updateConfidence(request.nodeId, request.confidence); + } + + private commitMerge( + request: CatmaidSpatialSkeletonMergeRequest, + ): Promise { + return this.client.mergeSkeletons(request.fromNodeId, request.toNodeId); + } + + private commitSplit( + request: CatmaidSpatialSkeletonSplitRequest, + ): Promise { + return this.client.splitSkeleton(request.nodeId); + } +} diff --git a/src/datasource/catmaid/spatial_skeleton_edit/command_payloads.ts b/src/datasource/catmaid/spatial_skeleton_edit/command_payloads.ts new file mode 100644 index 0000000000..1bb545e849 --- /dev/null +++ b/src/datasource/catmaid/spatial_skeleton_edit/command_payloads.ts @@ -0,0 +1,386 @@ +/** + * @license + * Copyright 2026 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file Defines the payload of each CATMAID edit command and rejects a payload + * that does not match it. + */ + +import type { SkeletonNode, SkeletonVector } from "#src/skeleton/api.js"; + +export interface CatmaidSpatialSkeletonAddNodeCommandOptions { + skeletonId: bigint; + parentNodeId: bigint | undefined; + positionInModelSpace: SkeletonVector; + childNodeIds?: readonly bigint[]; +} + +export interface CatmaidSpatialSkeletonMoveNodeCommandOptions { + node: SkeletonNode; + nextPositionInModelSpace: SkeletonVector; +} + +export interface CatmaidSpatialSkeletonNodeDescriptionCommandOptions { + node: SkeletonNode; + nextDescription?: string; +} + +export interface CatmaidSpatialSkeletonNodeTrueEndCommandOptions { + node: SkeletonNode; + nextIsTrueEnd: boolean; +} + +export interface CatmaidSpatialSkeletonNodeRadiusCommandOptions { + node: SkeletonNode; + nextRadius: number; +} + +export interface CatmaidSpatialSkeletonNodeConfidenceCommandOptions { + node: SkeletonNode; + nextConfidence: number; +} + +export interface CatmaidSpatialSkeletonMergeEndpoint { + nodeId: bigint; + segmentId: bigint; + position?: SkeletonVector; +} + +export interface CatmaidSpatialSkeletonMergeCommandPayload { + firstNode: CatmaidSpatialSkeletonMergeEndpoint; + secondNode: CatmaidSpatialSkeletonMergeEndpoint; +} + +/** Payloads accepted by CATMAID skeleton command factories and plans. */ +export type CatmaidSpatialSkeletonCommandPayload = + | { + readonly kind: "add-node"; + readonly options: CatmaidSpatialSkeletonAddNodeCommandOptions; + } + | { + readonly kind: "move-node"; + readonly options: CatmaidSpatialSkeletonMoveNodeCommandOptions; + } + | { + readonly kind: "delete-node"; + readonly node: SkeletonNode; + } + | { + readonly kind: "reroot"; + readonly node: Pick< + SkeletonNode, + "nodeId" | "segmentId" | "parentNodeId" + > & + Partial>; + } + | { + readonly kind: "description"; + readonly options: CatmaidSpatialSkeletonNodeDescriptionCommandOptions; + } + | { + readonly kind: "true-end"; + readonly options: CatmaidSpatialSkeletonNodeTrueEndCommandOptions; + } + | { + readonly kind: "radius"; + readonly options: CatmaidSpatialSkeletonNodeRadiusCommandOptions; + } + | { + readonly kind: "confidence"; + readonly options: CatmaidSpatialSkeletonNodeConfidenceCommandOptions; + } + | { + readonly kind: "split"; + readonly node: Pick & + Partial>; + } + | { + readonly kind: "merge"; + readonly options: CatmaidSpatialSkeletonMergeCommandPayload; + }; + +function isFiniteNumber(value: number | undefined) { + return typeof value === "number" && Number.isFinite(value); +} + +function isId(value: bigint | undefined) { + return typeof value === "bigint"; +} + +function isOptionalId(value: bigint | undefined) { + return value === undefined || isId(value); +} + +function isSkeletonVector(value: object | undefined): value is SkeletonVector { + // Coordinate contents are consumed by the generic reducer or CATMAID + // transport. Admission only requires the user-facing value to be present. + return value !== undefined; +} + +function isSkeletonNodePayload( + value: object | undefined, +): value is SkeletonNode { + if (value === undefined) return false; + const candidate = value as { + nodeId?: bigint; + segmentId?: bigint; + position?: object; + parentNodeId?: bigint; + attributes?: object; + description?: string; + }; + return ( + isId(candidate.nodeId) && + isId(candidate.segmentId) && + isSkeletonVector(candidate.position) && + isOptionalId(candidate.parentNodeId) && + (candidate.attributes === undefined || + (typeof candidate.attributes === "object" && + candidate.attributes !== null)) && + (candidate.description === undefined || + typeof candidate.description === "string") + ); +} + +function isCatmaidMergeEndpoint( + value: object | undefined, +): value is CatmaidSpatialSkeletonMergeEndpoint { + if (value === undefined) return false; + const candidate = value as { + nodeId?: bigint; + segmentId?: bigint; + position?: object; + }; + return ( + isId(candidate.nodeId) && + isId(candidate.segmentId) && + (candidate.position === undefined || isSkeletonVector(candidate.position)) + ); +} + +function requireCatmaidCommandPayload( + payload: object, + label: string, + isValid: (payload: object) => payload is T, +) { + if (!isValid(payload)) { + throw new Error(`CATMAID ${label} command received an invalid payload.`); + } + return payload; +} + +export function requireCatmaidAddNodeCommandOptions(payload: object) { + return requireCatmaidCommandPayload( + payload, + "add-node", + (candidate): candidate is CatmaidSpatialSkeletonAddNodeCommandOptions => { + const options = candidate as { + skeletonId?: bigint; + parentNodeId?: bigint; + positionInModelSpace?: object; + }; + return ( + isId(options.skeletonId) && + isOptionalId(options.parentNodeId) && + isSkeletonVector(options.positionInModelSpace) + ); + }, + ); +} + +export function requireCatmaidInsertNodeCommandOptions(payload: object) { + const options = requireCatmaidAddNodeCommandOptions(payload); + if ( + options.parentNodeId === undefined || + !Array.isArray(options.childNodeIds) || + options.childNodeIds.length === 0 || + !options.childNodeIds.every(isId) || + new Set(options.childNodeIds).size !== options.childNodeIds.length + ) { + throw new Error("CATMAID insert-node command received an invalid payload."); + } + return options; +} + +export function requireCatmaidMoveNodeCommandOptions(payload: object) { + return requireCatmaidCommandPayload( + payload, + "move-node", + (candidate): candidate is CatmaidSpatialSkeletonMoveNodeCommandOptions => { + const options = candidate as { + node?: object; + nextPositionInModelSpace?: object; + }; + return ( + isSkeletonNodePayload(options.node) && + isSkeletonVector(options.nextPositionInModelSpace) + ); + }, + ); +} + +export function requireCatmaidDeleteNodeCommandPayload(payload: object) { + return requireCatmaidCommandPayload( + payload, + "delete-node", + isSkeletonNodePayload, + ); +} + +export function requireCatmaidNodeDescriptionCommandOptions(payload: object) { + return requireCatmaidCommandPayload( + payload, + "node-description", + ( + candidate, + ): candidate is CatmaidSpatialSkeletonNodeDescriptionCommandOptions => { + const options = candidate as { + node?: object; + nextDescription?: string; + }; + return ( + isSkeletonNodePayload(options.node) && + (options.nextDescription === undefined || + typeof options.nextDescription === "string") + ); + }, + ); +} + +export function requireCatmaidNodeTrueEndCommandOptions(payload: object) { + return requireCatmaidCommandPayload( + payload, + "node-true-end", + ( + candidate, + ): candidate is CatmaidSpatialSkeletonNodeTrueEndCommandOptions => { + const options = candidate as { + node?: object; + nextIsTrueEnd?: boolean; + }; + return ( + isSkeletonNodePayload(options.node) && + typeof options.nextIsTrueEnd === "boolean" + ); + }, + ); +} + +export function requireCatmaidNodeRadiusCommandOptions(payload: object) { + return requireCatmaidCommandPayload( + payload, + "node-radius", + ( + candidate, + ): candidate is CatmaidSpatialSkeletonNodeRadiusCommandOptions => { + const options = candidate as { + node?: object; + nextRadius?: number; + }; + return ( + isSkeletonNodePayload(options.node) && + isFiniteNumber(options.nextRadius) + ); + }, + ); +} + +export function requireCatmaidNodeConfidenceCommandOptions(payload: object) { + return requireCatmaidCommandPayload( + payload, + "node-confidence", + ( + candidate, + ): candidate is CatmaidSpatialSkeletonNodeConfidenceCommandOptions => { + const options = candidate as { + node?: object; + nextConfidence?: number; + }; + return ( + isSkeletonNodePayload(options.node) && + isFiniteNumber(options.nextConfidence) + ); + }, + ); +} + +export function requireCatmaidRerootCommandPayload(payload: object) { + return requireCatmaidCommandPayload( + payload, + "reroot", + ( + candidate, + ): candidate is Pick< + SkeletonNode, + "nodeId" | "segmentId" | "parentNodeId" + > & + Partial> => { + const node = candidate as { + nodeId?: bigint; + segmentId?: bigint; + parentNodeId?: bigint; + position?: object; + }; + return ( + isId(node.nodeId) && + isId(node.segmentId) && + isOptionalId(node.parentNodeId) && + (node.position === undefined || isSkeletonVector(node.position)) + ); + }, + ); +} + +export function requireCatmaidSplitCommandPayload(payload: object) { + return requireCatmaidCommandPayload( + payload, + "split", + ( + candidate, + ): candidate is Pick & + Partial> => { + const node = candidate as { + nodeId?: bigint; + segmentId?: bigint; + parentNodeId?: bigint; + position?: object; + }; + return ( + isId(node.nodeId) && + isId(node.segmentId) && + isOptionalId(node.parentNodeId) && + (node.position === undefined || isSkeletonVector(node.position)) + ); + }, + ); +} + +export function requireCatmaidMergeCommandPayload(payload: object) { + return requireCatmaidCommandPayload( + payload, + "merge", + (candidate): candidate is CatmaidSpatialSkeletonMergeCommandPayload => { + const options = candidate as { + firstNode?: object; + secondNode?: object; + }; + return ( + isCatmaidMergeEndpoint(options.firstNode) && + isCatmaidMergeEndpoint(options.secondNode) + ); + }, + ); +} diff --git a/src/datasource/catmaid/spatial_skeleton_edit/edit_operations.ts b/src/datasource/catmaid/spatial_skeleton_edit/edit_operations.ts new file mode 100644 index 0000000000..81f7cd1f4f --- /dev/null +++ b/src/datasource/catmaid/spatial_skeleton_edit/edit_operations.ts @@ -0,0 +1,128 @@ +/** + * @license + * Copyright 2026 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file Defines the request and result of each CATMAID edit operation. + */ + +import type { + CatmaidAddNodeResult, + CatmaidDescriptionUpdateResult, + CatmaidInsertNodeResult, + CatmaidMergeResult, + CatmaidSplitResult, +} from "#src/datasource/catmaid/api.js"; +import type { SkeletonVector } from "#src/skeleton/api.js"; + +export interface CatmaidSpatialSkeletonEditOperations { + /** Stable identity of the physical CATMAID edit request target. */ + readonly editRequestScope: object; + commitAddNode( + request: CatmaidSpatialSkeletonAddNodeRequest, + ): Promise; + commitInsertNode( + request: CatmaidSpatialSkeletonInsertNodeRequest, + ): Promise; + commitMoveNode(request: CatmaidSpatialSkeletonMoveNodeRequest): Promise; + commitDeleteNode( + request: CatmaidSpatialSkeletonDeleteNodeRequest, + ): Promise; + commitReroot(request: CatmaidSpatialSkeletonRerootRequest): Promise; + commitDescription( + request: CatmaidSpatialSkeletonDescriptionUpdateRequest, + ): Promise; + commitTrueEnd( + request: CatmaidSpatialSkeletonTrueEndUpdateRequest, + ): Promise; + commitRadius( + request: CatmaidSpatialSkeletonRadiusUpdateRequest, + ): Promise; + commitConfidence( + request: CatmaidSpatialSkeletonConfidenceUpdateRequest, + ): Promise; + commitMerge( + request: CatmaidSpatialSkeletonMergeRequest, + ): Promise; + commitSplit( + request: CatmaidSpatialSkeletonSplitRequest, + ): Promise; +} + +// CATMAID owns these payloads; the generic skeleton API only promises named edit operations. +export interface CatmaidSpatialSkeletonAddNodeRequest { + position: SkeletonVector; + parentNodeId?: bigint; +} + +export type CatmaidSpatialSkeletonAddNodeResult = CatmaidAddNodeResult; + +export interface CatmaidSpatialSkeletonInsertNodeRequest { + position: SkeletonVector; + parentNodeId: bigint; + childNodeIds: readonly bigint[]; +} + +export type CatmaidSpatialSkeletonInsertNodeResult = CatmaidInsertNodeResult; + +export interface CatmaidSpatialSkeletonMoveNodeRequest { + nodeId: bigint; + position: SkeletonVector; +} + +export interface CatmaidSpatialSkeletonDeleteNodeRequest { + nodeId: bigint; +} + +export interface CatmaidSpatialSkeletonSplitRequest { + nodeId: bigint; +} + +export type CatmaidSpatialSkeletonSplitResult = CatmaidSplitResult; + +export interface CatmaidSpatialSkeletonMergeRequest { + fromNodeId: bigint; + toNodeId: bigint; +} + +export type CatmaidSpatialSkeletonMergeResult = CatmaidMergeResult; + +export interface CatmaidSpatialSkeletonRerootRequest { + nodeId: bigint; +} + +export interface CatmaidSpatialSkeletonDescriptionUpdateRequest { + nodeId: bigint; + description: string; + isTrueEnd: boolean; +} + +export type CatmaidSpatialSkeletonDescriptionUpdateResult = + CatmaidDescriptionUpdateResult; + +export interface CatmaidSpatialSkeletonTrueEndUpdateRequest { + nodeId: bigint; + isTrueEnd: boolean; +} + +export interface CatmaidSpatialSkeletonRadiusUpdateRequest { + nodeId: bigint; + radius: number; +} + +export interface CatmaidSpatialSkeletonConfidenceUpdateRequest { + nodeId: bigint; + confidence: number; +} diff --git a/src/datasource/catmaid/spatial_skeleton_edit/edit_plan.ts b/src/datasource/catmaid/spatial_skeleton_edit/edit_plan.ts new file mode 100644 index 0000000000..17d5db51cf --- /dev/null +++ b/src/datasource/catmaid/spatial_skeleton_edit/edit_plan.ts @@ -0,0 +1,281 @@ +/** + * @license + * Copyright 2026 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + */ + +/** + * @file Defines the captured edit that a CATMAID plan stores and derives the + * plan's server steps in either direction. + */ + +import type { SkeletonNode, SkeletonVector } from "#src/skeleton/api.js"; +import type { CompleteSkeleton } from "#src/skeleton/edit_queue/complete_skeleton.js"; +import type { SpatialSkeletonEditNodeAttributes } from "#src/skeleton/edit_queue/complete_skeleton_edits.js"; +import type { + SpatialSkeletonStableNodeHandle, + SpatialSkeletonStableSegmentHandle, +} from "#src/skeleton/edit_queue/stable_id_handles.js"; +import { + getSkeletonNodeConfidence, + getSkeletonNodeRadius, + isSkeletonNodeTrueEnd, +} from "#src/skeleton/node_attributes.js"; + +export interface CatmaidCapturedSegment { + readonly segment: SpatialSkeletonStableSegmentHandle; + readonly physicalId: bigint; + readonly snapshot: CompleteSkeleton; + readonly cacheRevision: number; +} + +/** A logical node together with the physical ID captured for its recipe. */ +export interface CatmaidRetainedNode extends SpatialSkeletonStableNodeHandle { + readonly capturedNodeId: bigint; + readonly handle: SpatialSkeletonStableNodeHandle; +} + +export interface CatmaidSemanticBase { + readonly capturedSegments: readonly CatmaidCapturedSegment[]; + readonly retainedNodes: ReadonlyMap; +} + +export interface CatmaidCreatedNodeSemantic extends CatmaidSemanticBase { + readonly kind: "add-node"; + readonly node: SpatialSkeletonStableNodeHandle; + readonly segment: SpatialSkeletonStableSegmentHandle; + readonly parent: CatmaidRetainedNode | undefined; + readonly position: SkeletonVector; + readonly attributes: SpatialSkeletonEditNodeAttributes; + readonly createsSegment: boolean; + readonly children?: readonly CatmaidRetainedNode[]; +} + +export interface CatmaidDeleteNodeSemantic extends CatmaidSemanticBase { + readonly kind: "delete-node"; + readonly node: CatmaidRetainedNode; + readonly segment: SpatialSkeletonStableSegmentHandle; + readonly parent: CatmaidRetainedNode | undefined; + readonly children: readonly CatmaidRetainedNode[]; + readonly deletedSnapshot: SkeletonNode; + readonly wasSoleRoot: boolean; +} + +export interface CatmaidMoveNodeSemantic extends CatmaidSemanticBase { + readonly kind: "move-node"; + readonly node: CatmaidRetainedNode; + readonly segment: SpatialSkeletonStableSegmentHandle; + readonly before: SkeletonVector; + readonly after: SkeletonVector; +} + +export interface CatmaidAttributeSemantic extends CatmaidSemanticBase { + readonly kind: "description" | "true-end" | "radius" | "confidence"; + readonly node: CatmaidRetainedNode; + readonly segment: SpatialSkeletonStableSegmentHandle; + readonly nodeSnapshot: SkeletonNode; + readonly before: string | boolean | number | undefined; + readonly after: string | boolean | number | undefined; +} + +export interface CatmaidRerootSemantic extends CatmaidSemanticBase { + readonly kind: "reroot"; + readonly node: CatmaidRetainedNode; + readonly originalRoot: CatmaidRetainedNode; + readonly originalRootConfidence: number | undefined; + readonly segment: SpatialSkeletonStableSegmentHandle; +} + +export interface CatmaidSplitSemantic extends CatmaidSemanticBase { + readonly kind: "split"; + readonly sourceSegment: SpatialSkeletonStableSegmentHandle; + readonly downstreamSegment: SpatialSkeletonStableSegmentHandle; + readonly node: CatmaidRetainedNode; + readonly formerParent: CatmaidRetainedNode; +} + +export interface CatmaidMergeSemantic extends CatmaidSemanticBase { + readonly kind: "merge"; + readonly firstSegment: SpatialSkeletonStableSegmentHandle; + readonly secondSegment: SpatialSkeletonStableSegmentHandle; + /** + * The merged workspace output is a distinct logical resource. In + * particular, Undo must be able to use this as the merged input while + * restoring both original segment handles as outputs. + */ + readonly mergedSegment: SpatialSkeletonStableSegmentHandle; + readonly firstNode: CatmaidRetainedNode; + readonly secondNode: CatmaidRetainedNode; + readonly originalRoot: CatmaidRetainedNode; + readonly originalRootConfidence: number | undefined; + readonly inverseOrientation: "second-from-first" | "first-from-second"; +} + +export type CatmaidCapturedEdit = + | CatmaidCreatedNodeSemantic + | CatmaidDeleteNodeSemantic + | CatmaidMoveNodeSemantic + | CatmaidAttributeSemantic + | CatmaidRerootSemantic + | CatmaidSplitSemantic + | CatmaidMergeSemantic; + +export type CatmaidEditPlanStep = + | { + readonly kind: "restore-confidence"; + readonly node: SpatialSkeletonStableNodeHandle; + readonly confidence: number; + } + | { + readonly kind: "add-node"; + readonly semantic: CatmaidCreatedNodeSemantic | CatmaidDeleteNodeSemantic; + } + | { + readonly kind: "insert-node"; + readonly semantic: CatmaidCreatedNodeSemantic | CatmaidDeleteNodeSemantic; + } + | { readonly kind: "move-node"; readonly semantic: CatmaidMoveNodeSemantic } + | { + readonly kind: "delete-node"; + readonly semantic: CatmaidCreatedNodeSemantic | CatmaidDeleteNodeSemantic; + } + | { + readonly kind: "reroot"; + readonly semantic: CatmaidRerootSemantic | CatmaidMergeSemantic; + } + | { + readonly kind: "description"; + readonly semantic: CatmaidAttributeSemantic | CatmaidDeleteNodeSemantic; + } + | { + readonly kind: "true-end"; + readonly semantic: CatmaidAttributeSemantic | CatmaidDeleteNodeSemantic; + } + | { + readonly kind: "radius"; + readonly semantic: CatmaidAttributeSemantic | CatmaidDeleteNodeSemantic; + } + | { + readonly kind: "confidence"; + readonly semantic: CatmaidAttributeSemantic | CatmaidDeleteNodeSemantic; + } + | { + readonly kind: "split"; + readonly semantic: CatmaidSplitSemantic | CatmaidMergeSemantic; + } + | { + readonly kind: "merge"; + readonly semantic: CatmaidSplitSemantic | CatmaidMergeSemantic; + }; + +/** + * Immutable CATMAID recipe retained by the generic engine. Physical attempts, + * results, cursors, leases, and lifecycle are all canonical engine state. + */ +type CatmaidEditPlanFor = + TSemantic extends CatmaidCapturedEdit + ? Readonly<{ + kind: TSemantic["kind"]; + direction: "forward" | "inverse"; + semantic: TSemantic; + }> + : never; + +/** Discriminated immutable CATMAID plan recipe. */ +export type CatmaidEditPlan = CatmaidEditPlanFor; + +export function requirePositiveId(value: bigint | undefined, label: string) { + if (value === undefined || value === 0n) { + throw new Error(`CATMAID ${label} has no authoritative numeric id.`); + } + return value; +} + +function getRestoreSteps(semantic: CatmaidDeleteNodeSemantic) { + const result: CatmaidEditPlanStep[] = [ + { + kind: semantic.children.length === 0 ? "add-node" : "insert-node", + semantic, + }, + ]; + if (semantic.deletedSnapshot.description !== undefined) { + result.push({ kind: "description", semantic }); + } + if ( + semantic.deletedSnapshot.description === undefined && + isSkeletonNodeTrueEnd(semantic.deletedSnapshot) + ) { + result.push({ kind: "true-end", semantic }); + } + if (getSkeletonNodeRadius(semantic.deletedSnapshot) !== undefined) { + result.push({ kind: "radius", semantic }); + } + if (getSkeletonNodeConfidence(semantic.deletedSnapshot) !== undefined) { + result.push({ kind: "confidence", semantic }); + } + return Object.freeze(result); +} + +/** CATMAID resets a newly rerooted root to full confidence. */ +function getRerootSteps( + semantic: CatmaidRerootSemantic | CatmaidMergeSemantic, + direction: "forward" | "inverse", +): readonly CatmaidEditPlanStep[] { + const steps: CatmaidEditPlanStep[] = [{ kind: "reroot", semantic }]; + if (direction === "inverse") { + const root = semantic.originalRoot; + const confidence = semantic.originalRootConfidence; + if (confidence !== undefined && confidence !== 100) { + steps.push({ kind: "restore-confidence", node: root, confidence }); + } + } + return Object.freeze(steps); +} + +export function makeSteps( + semantic: CatmaidCapturedEdit, + direction: "forward" | "inverse", +): readonly CatmaidEditPlanStep[] { + switch (semantic.kind) { + case "add-node": + return Object.freeze([ + direction === "forward" + ? { + kind: semantic.children?.length ? "insert-node" : "add-node", + semantic, + } + : { kind: "delete-node", semantic }, + ]); + case "delete-node": + return direction === "forward" + ? Object.freeze([{ kind: "delete-node", semantic }]) + : getRestoreSteps(semantic); + case "move-node": + return Object.freeze([{ kind: "move-node", semantic }]); + case "description": + case "true-end": + case "radius": + case "confidence": + return Object.freeze([{ kind: semantic.kind, semantic }]); + case "reroot": + return getRerootSteps(semantic, direction); + case "split": + return Object.freeze([ + direction === "forward" + ? { kind: "split", semantic } + : { kind: "merge", semantic }, + ]); + case "merge": + return direction === "forward" + ? Object.freeze([{ kind: "merge", semantic }]) + : Object.freeze([ + { kind: "split", semantic }, + ...(semantic.originalRoot.stableId === + (semantic.inverseOrientation === "second-from-first" + ? semantic.secondNode.stableId + : semantic.firstNode.stableId) + ? [] + : getRerootSteps(semantic, direction)), + ]); + } +} diff --git a/src/datasource/catmaid/spatial_skeleton_edit/edit_planner.spec.ts b/src/datasource/catmaid/spatial_skeleton_edit/edit_planner.spec.ts new file mode 100644 index 0000000000..9a90dd123b --- /dev/null +++ b/src/datasource/catmaid/spatial_skeleton_edit/edit_planner.spec.ts @@ -0,0 +1,1483 @@ +/** + * @license + * Copyright 2026 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { describe, expect, it, vi } from "vitest"; + +import type { + CatmaidSpatialSkeletonCommandDescriptor, + CatmaidEditPlan, +} from "#src/datasource/catmaid/spatial_skeleton_edit/edit_planner.js"; +import { CatmaidEditPlanner } from "#src/datasource/catmaid/spatial_skeleton_edit/edit_planner.js"; +import type { + CatmaidEditRequest, + CatmaidEditRequestResult, +} from "#src/datasource/catmaid/spatial_skeleton_edit/edit_requests.js"; +import type { SkeletonNode } from "#src/skeleton/api.js"; +import { SpatialSkeletonActions } from "#src/skeleton/edit/edit_commands.js"; +import { createCompleteSkeleton } from "#src/skeleton/edit_queue/complete_skeleton.js"; +import type { SpatialSkeletonEditInverseDelta } from "#src/skeleton/edit_queue/complete_skeleton_edits.js"; +import type { + SpatialSkeletonAuthoritativeReconciliation, + SpatialSkeletonPreviewIntentDelta, +} from "#src/skeleton/edit_queue/preview.js"; +import type { SpatialSkeletonQueueInput } from "#src/skeleton/edit_queue/queue_input.js"; +import type { + SpatialSkeletonStableNodeHandle, + SpatialSkeletonStableSegmentHandle, +} from "#src/skeleton/edit_queue/stable_id_handles.js"; +import { + spatialSkeletonStableNode, + spatialSkeletonStableSegment, +} from "#src/skeleton/edit_queue/stable_id_handles.js"; +import { bigintCompare } from "#src/util/bigint.js"; + +class TestIdentities { + private readonly nodeHandles = new Map< + bigint, + SpatialSkeletonStableNodeHandle + >(); + private readonly segmentHandles = new Map< + bigint, + SpatialSkeletonStableSegmentHandle + >(); + private readonly nodeBindings = new Map(); + private readonly segmentBindings = new Map(); + + getOrCreateNodeHandle(nodeId: bigint) { + let handle = this.nodeHandles.get(nodeId); + if (handle === undefined) { + handle = spatialSkeletonStableNode(`authority:${nodeId}`); + this.nodeHandles.set(nodeId, handle); + this.nodeBindings.set(handle.stableId, nodeId); + } + return handle; + } + + getOrCreateNodeHandles(nodeIds: readonly bigint[]) { + return new Map( + [...new Set(nodeIds)].map((nodeId) => [ + nodeId, + this.getOrCreateNodeHandle(nodeId), + ]), + ); + } + + getOrCreateSegmentHandle(segmentId: bigint) { + let handle = this.segmentHandles.get(segmentId); + if (handle === undefined) { + handle = spatialSkeletonStableSegment(`authority:${segmentId}`); + this.segmentHandles.set(segmentId, handle); + this.segmentBindings.set(handle.stableId, segmentId); + } + return handle; + } + + resolveNode(handle: SpatialSkeletonStableNodeHandle) { + return this.nodeBindings.get(handle.stableId); + } + + resolveSegment(handle: SpatialSkeletonStableSegmentHandle) { + return this.segmentBindings.get(handle.stableId); + } + + resolveAuthoritativeNode = this.resolveNode; + resolveAuthoritativeSegment = this.resolveSegment; + + resolveNodeTarget(handle: SpatialSkeletonStableNodeHandle) { + const physicalId = this.resolveNode(handle); + return physicalId === undefined + ? ({ state: "unbound" } as const) + : ({ state: "authoritative", physicalId } as const); + } + + resolveSegmentTarget(handle: SpatialSkeletonStableSegmentHandle) { + const physicalId = this.resolveSegment(handle); + return physicalId === undefined + ? ({ state: "unbound" } as const) + : ({ state: "authoritative", physicalId } as const); + } + + apply(reconciliation: SpatialSkeletonAuthoritativeReconciliation) { + for (const [handle, physicalId] of reconciliation.bindings?.nodes ?? []) { + this.nodeBindings.set(handle.stableId, physicalId); + this.nodeHandles.set(physicalId, handle); + } + for (const [handle, physicalId] of reconciliation.bindings?.segments ?? + []) { + this.segmentBindings.set(handle.stableId, physicalId); + this.segmentHandles.set(physicalId, handle); + } + } +} + +function node( + nodeId: number, + segmentId: number, + parentNodeId?: number, + attributes?: SkeletonNode["attributes"], +): SkeletonNode { + return { + nodeId: BigInt(nodeId), + segmentId: BigInt(segmentId), + parentNodeId: parentNodeId === undefined ? undefined : BigInt(parentNodeId), + position: Object.freeze([nodeId, nodeId + 1, nodeId + 2]), + attributes, + }; +} + +function makePlanner( + nodesBySegment: ReadonlyMap, +) { + currentQueueInput = Object.freeze({ + segments: Object.freeze( + [...nodesBySegment].map(([segmentId, nodes]) => + Object.freeze({ + segmentId, + snapshot: createCompleteSkeleton(nodes), + cacheRevision: Number(segmentId) + 100, + }), + ), + ), + }); + const identities = new TestIdentities(); + const planner = new CatmaidEditPlanner(identities, { + allocateNodeId: (intentId) => BigInt(1_000_000 - intentId), + allocateSegmentId: (intentId) => BigInt(2_000_000 - intentId), + }); + return { planner, identities }; +} + +let currentQueueInput: SpatialSkeletonQueueInput = Object.freeze({ + segments: Object.freeze([]), +}); + +function command( + action: CatmaidSpatialSkeletonCommandDescriptor["action"], + label: string, + payload: CatmaidSpatialSkeletonCommandDescriptor["payload"], +): CatmaidSpatialSkeletonCommandDescriptor { + return Object.freeze({ + action, + label, + payload, + getQueueInputRequirements: () => + Object.freeze({ required: Object.freeze([]) }), + }); +} + +function context( + intentId: number, + intent: "execute" | "undo" | "redo", + recipe?: { + readonly plan: ReturnType["plan"]; + readonly preview: SpatialSkeletonPreviewIntentDelta; + readonly inversePreview?: SpatialSkeletonEditInverseDelta; + }, +) { + if (intent === "execute") { + return { intentId, intent, queueInput: currentQueueInput } as any; + } + if (recipe === undefined) throw new Error(`${intent} requires a recipe.`); + return { intentId, intent, recipe } as any; +} + +type CommittedAttempt = Readonly<{ + editRequest: CatmaidEditRequest; + result: CatmaidEditRequestResult; +}>; + +function planContext( + intentId: number, + intent: "execute" | "undo" | "redo", + committedAttempts: readonly CommittedAttempt[], +) { + return { + intentId, + intent, + committedAttempts: Object.freeze([...committedAttempts]), + } as any; +} + +function commitNextAttempt( + planner: CatmaidEditPlanner, + plan: CatmaidEditPlan, + result: CatmaidEditRequestResult, + attempts: CommittedAttempt[], + intent: "execute" | "undo" | "redo" = "execute", +) { + const before = planContext(1, intent, attempts); + const next = planner.nextAttempt(plan, before); + if (next === undefined) throw new Error("Expected a CATMAID attempt."); + const editRequest = next.materializeEditRequest(); + if (editRequest instanceof Promise) { + throw new Error("CATMAID test materialization must be synchronous."); + } + attempts.push(Object.freeze({ editRequest, result })); + return editRequest; +} + +describe("CatmaidEditPlanner", () => { + it("a move adds no new node or skeleton IDs", () => { + const original = node(2, 23, 1); + const { planner } = makePlanner(new Map([[23n, [node(1, 23), original]]])); + const logical = planner.planIntent( + command(SpatialSkeletonActions.moveNodes, "Move node", { + kind: "move-node", + options: { + node: original, + nextPositionInModelSpace: Object.freeze([10, 11, 12]), + }, + }), + context(1, "execute"), + ); + + expect(logical.kind).toBe("moveNode"); + expect(logical.preview.delta).toMatchObject({ + kind: "move", + position: [10, 11, 12], + }); + + const attempts: CommittedAttempt[] = []; + commitNextAttempt(planner, logical.plan, {} as any, attempts); + const reconciliation = planner.createReconciliation( + logical.plan, + planContext(1, "execute", attempts), + ); + expect(reconciliation).toEqual({ + bindings: { nodes: [], segments: [] }, + retiredResources: [], + }); + }); + + it("refuses an edit whose skeleton has not been loaded", () => { + const original = node(2, 23, 1); + const { planner } = makePlanner(new Map([[23n, [node(1, 23), original]]])); + const descriptor = command(SpatialSkeletonActions.moveNodes, "Move node", { + kind: "move-node", + options: { + node: original, + nextPositionInModelSpace: Object.freeze([10, 11, 12]), + }, + }); + + expect(() => + planner.planIntent(descriptor, { + intentId: 1, + intent: "execute", + queueInput: Object.freeze({ segments: Object.freeze([]) }), + }), + ).toThrow(/requires admitted complete skeleton 23/); + }); + + it("orders CATMAID edits by the skeletons they touch", () => { + const { planner } = makePlanner( + new Map([ + [11n, [node(101, 11)]], + [17n, [node(201, 17)]], + [23n, [node(1, 23), node(2, 23, 1)]], + ]), + ); + const intents = [ + planner.planIntent( + command(SpatialSkeletonActions.addNodes, "Add node", { + kind: "add-node", + options: { + skeletonId: 23n, + parentNodeId: 1n, + positionInModelSpace: [1, 2, 3], + }, + }), + context(1, "execute"), + ), + planner.planIntent( + command(SpatialSkeletonActions.moveNodes, "Move node", { + kind: "move-node", + options: { + node: node(2, 23, 1), + nextPositionInModelSpace: [4, 5, 6], + }, + }), + context(2, "execute"), + ), + planner.planIntent( + command(SpatialSkeletonActions.splitSkeletons, "Split skeleton", { + kind: "split", + node: node(2, 23, 1), + }), + context(3, "execute"), + ), + planner.planIntent( + command(SpatialSkeletonActions.mergeSkeletons, "Merge skeletons", { + kind: "merge", + options: { + firstNode: { nodeId: 101n, segmentId: 11n }, + secondNode: { nodeId: 201n, segmentId: 17n }, + }, + }), + context(4, "execute"), + ), + ]; + + expect( + intents.map((intent) => + intent.stableResources.map(({ handle }) => handle.kind), + ), + ).toEqual([ + ["segment"], + ["segment"], + ["segment", "segment"], + ["segment", "segment", "segment"], + ]); + }); + + it("remembers only the nodes each edit needs, without copying whole skeletons", () => { + const main = [ + node(1, 23), + node(2, 23, 1), + node(3, 23, 2), + node(4, 23, 1), + node(5, 23, 3), + ]; + const first = [node(100, 11), node(101, 11, 100), node(102, 11, 100)]; + const second = [node(200, 17), node(201, 17, 200), node(202, 17, 201)]; + const { planner } = makePlanner( + new Map([ + [23n, main], + [11n, first], + [17n, second], + ]), + ); + const materializeSpies = currentQueueInput.segments.map(({ snapshot }) => + vi.spyOn(snapshot, "materialize"), + ); + const retainedIds = ( + descriptor: CatmaidSpatialSkeletonCommandDescriptor, + intentId: number, + ) => { + const intent = planner.planIntent( + descriptor, + context(intentId, "execute"), + ); + const retainedNodes = intent.plan.semantic.retainedNodes; + expect( + [...retainedNodes].every( + ([nodeId, retained]) => nodeId === retained.capturedNodeId, + ), + ).toBe(true); + return { + intent, + ids: [...retainedNodes.keys()].sort(bigintCompare), + }; + }; + + expect( + retainedIds( + command(SpatialSkeletonActions.addNodes, "Add", { + kind: "add-node", + options: { + skeletonId: 23n, + parentNodeId: 2n, + positionInModelSpace: [1, 2, 3], + }, + }), + 1, + ).ids, + ).toEqual([2n]); + expect( + retainedIds( + command(SpatialSkeletonActions.moveNodes, "Move", { + kind: "move-node", + options: { node: main[2], nextPositionInModelSpace: [4, 5, 6] }, + }), + 2, + ).ids, + ).toEqual([3n]); + expect( + retainedIds( + command(SpatialSkeletonActions.editNodeDescription, "Description", { + kind: "description", + options: { node: main[2], nextDescription: "next" }, + }), + 3, + ).ids, + ).toEqual([3n]); + expect( + retainedIds( + command(SpatialSkeletonActions.addNodes, "Root Add", { + kind: "add-node", + options: { + skeletonId: 0n, + parentNodeId: undefined, + positionInModelSpace: [1, 2, 3], + }, + }), + 4, + ).ids, + ).toEqual([]); + + expect( + retainedIds( + command(SpatialSkeletonActions.deleteNodes, "Delete", { + kind: "delete-node", + node: main[1], + }), + 6, + ).ids, + ).toEqual([1n, 2n, 3n]); + expect( + retainedIds( + command(SpatialSkeletonActions.reroot, "Reroot", { + kind: "reroot", + node: main[2], + }), + 7, + ).ids, + ).toEqual([1n, 2n, 3n]); + expect( + retainedIds( + command(SpatialSkeletonActions.splitSkeletons, "Split", { + kind: "split", + node: main[2], + }), + 8, + ).ids, + ).toEqual([2n, 3n]); + const merge = retainedIds( + command(SpatialSkeletonActions.mergeSkeletons, "Merge", { + kind: "merge", + options: { + firstNode: first[1], + secondNode: second[1], + }, + }), + 9, + ); + expect(merge.ids).toEqual([100n, 101n, 200n, 201n]); + expect(materializeSpies.every((spy) => spy.mock.calls.length === 0)).toBe( + true, + ); + }); + + it.each([ + { input: " normalized ", normalized: "normalized" }, + { input: "ends", normalized: undefined }, + { input: " \n\t", normalized: undefined }, + { input: "", normalized: undefined }, + ])( + "Undo restores the old description and Redo re-sends the one CATMAID stored: $input", + ({ input, normalized }) => { + const original = Object.freeze({ + ...node(2, 23, 1), + description: "before", + }); + const { planner } = makePlanner( + new Map([[23n, [node(1, 23), original]]]), + ); + const descriptor = command( + SpatialSkeletonActions.editNodeDescription, + "Edit description", + { + kind: "description", + options: { + node: original, + nextDescription: input, + }, + }, + ); + const execute = planner.planIntent(descriptor, context(1, "execute")); + const executeAttempts: CommittedAttempt[] = []; + expect( + commitNextAttempt( + planner, + execute.plan, + { description: normalized } as any, + executeAttempts, + ), + ).toMatchObject({ + kind: "description", + request: { description: input }, + }); + const reconciliation = planner.createReconciliation( + execute.plan, + planContext(1, "execute", executeAttempts), + ); + expect(reconciliation.finalizedPreviewDelta).toMatchObject({ + kind: "node-attributes", + changes: { description: normalized }, + }); + const executeDelta = execute.preview.delta; + if (executeDelta.kind !== "node-attributes") { + throw new Error("Expected a description preview."); + } + const canonicalPreview = Object.freeze({ + ...execute.preview, + delta: reconciliation.finalizedPreviewDelta!, + }); + const inversePreview = Object.freeze({ + kind: "node-attributes" as const, + segment: executeDelta.segment, + node: executeDelta.node, + changes: Object.freeze({ description: "before" }), + }); + const recipe = { + plan: execute.plan, + preview: canonicalPreview, + inversePreview, + }; + + const undo = planner.planIntent(descriptor, context(2, "undo", recipe)); + expect(undo.preview.delta).toBe(inversePreview); + const undoAttempts: CommittedAttempt[] = []; + expect( + commitNextAttempt( + planner, + undo.plan, + { description: "before" } as any, + undoAttempts, + "undo", + ), + ).toMatchObject({ + kind: "description", + request: { description: "before" }, + }); + + const redo = planner.planIntent(descriptor, context(3, "redo", recipe)); + expect(redo.preview.delta).toMatchObject({ + kind: "node-attributes", + changes: { description: normalized }, + }); + const redoAttempts: CommittedAttempt[] = []; + expect( + commitNextAttempt( + planner, + redo.plan, + { description: normalized } as any, + redoAttempts, + "redo", + ), + ).toMatchObject({ + kind: "description", + request: { description: normalized ?? "" }, + }); + }, + ); + + it.each([ + ["reroot", 0], + ["reroot", 25], + ["reroot", 100], + ["merge", 0], + ["merge", 25], + ["merge", 100], + ["reversed merge", 0], + ["reversed merge", 25], + ["reversed merge", 100], + ] as const)( + "restores %s root confidence %s using the current node ID", + (kind, confidence) => { + const rootAttributes = { confidence: [confidence] }; + const first = [ + node(101, 11, undefined, rootAttributes), + node(102, 11, 101), + ]; + const second = [ + node(201, 17, undefined, rootAttributes), + node(202, 17, 201), + ]; + const { planner, identities } = makePlanner( + new Map([ + [11n, first], + [17n, second], + ]), + ); + const descriptor = + kind === "reroot" + ? command(SpatialSkeletonActions.reroot, "Reroot", { + kind: "reroot", + node: first[1], + }) + : command(SpatialSkeletonActions.mergeSkeletons, "Merge", { + kind: "merge", + options: { firstNode: first[1], secondNode: second[1] }, + }); + const execute = planner.planIntent(descriptor, context(1, "execute")); + let semantic = execute.plan.semantic; + const rootId = kind === "merge" ? 201n : 101n; + const rootHandle = identities.getOrCreateNodeHandle(rootId); + if (kind === "reversed merge" && semantic.kind === "merge") { + semantic = { + ...semantic, + inverseOrientation: "first-from-second", + originalRoot: { + ...rootHandle, + capturedNodeId: rootId, + handle: rootHandle, + }, + originalRootConfidence: confidence, + }; + } + const inverse = { + ...execute.plan, + semantic, + direction: "inverse", + } as CatmaidEditPlan; + // A later deletion/restoration can replace the physical root before Undo. + identities.apply({ bindings: { nodes: [[rootHandle, 901n]] } }); + const attempts: CommittedAttempt[] = []; + const undo = (result?: object) => + commitNextAttempt(planner, inverse, result as any, attempts, "undo"); + if (kind !== "reroot") { + expect( + undo({ + existingSegmentId: kind === "merge" ? 11n : 17n, + newSegmentId: 700n, + }), + ).toMatchObject({ kind: "split" }); + } + expect(undo()).toMatchObject({ + kind: "reroot", + request: { nodeId: 901n }, + }); + if (confidence !== 100) { + expect(undo()).toEqual({ + kind: "confidence", + request: { nodeId: 901n, confidence }, + }); + } + expect( + planner.nextAttempt(inverse, planContext(2, "undo", attempts)), + ).toBeUndefined(); + }, + ); + + it("sends each edit to CATMAID with only the fields its endpoint needs", () => { + const richLeaf = Object.freeze({ + ...node(3, 23, 2, { true_end: [1], radius: [4], confidence: [80] }), + description: "leaf", + }); + const first = [node(100, 11), node(101, 11, 100)]; + const second = [node(200, 17), node(201, 17, 200)]; + const { planner } = makePlanner( + new Map([ + [23n, [node(1, 23), node(2, 23, 1), richLeaf]], + [11n, first], + [17n, second], + ]), + ); + const editRequest = ( + descriptor: CatmaidSpatialSkeletonCommandDescriptor, + intentId: number, + ) => { + const logical = planner.planIntent( + descriptor, + context(intentId, "execute"), + ); + return planner + .nextAttempt(logical.plan, planContext(intentId, "execute", []))! + .materializeEditRequest(); + }; + + const cases: readonly [ + CatmaidSpatialSkeletonCommandDescriptor["action"], + CatmaidSpatialSkeletonCommandDescriptor["payload"], + object, + ][] = [ + [ + SpatialSkeletonActions.addNodes, + { + kind: "add-node", + options: { + skeletonId: 23n, + parentNodeId: 2n, + positionInModelSpace: [1, 2, 3], + }, + }, + { + kind: "add-node", + request: { position: [1, 2, 3], parentNodeId: 2n }, + }, + ], + [ + SpatialSkeletonActions.moveNodes, + { + kind: "move-node", + options: { node: richLeaf, nextPositionInModelSpace: [7, 8, 9] }, + }, + { kind: "move-node", request: { nodeId: 3n, position: [7, 8, 9] } }, + ], + [ + SpatialSkeletonActions.deleteNodes, + { kind: "delete-node", node: richLeaf }, + { kind: "delete-node", request: { nodeId: 3n } }, + ], + [ + SpatialSkeletonActions.reroot, + { kind: "reroot", node: richLeaf }, + { kind: "reroot", request: { nodeId: 3n } }, + ], + [ + SpatialSkeletonActions.editNodeDescription, + { + kind: "description", + options: { node: richLeaf, nextDescription: "next" }, + }, + { + kind: "description", + request: { nodeId: 3n, description: "next", isTrueEnd: true }, + }, + ], + [ + SpatialSkeletonActions.editNodeTrueEnd, + { kind: "true-end", options: { node: richLeaf, nextIsTrueEnd: false } }, + { kind: "true-end", request: { nodeId: 3n, isTrueEnd: false } }, + ], + [ + SpatialSkeletonActions.editNodeRadius, + { kind: "radius", options: { node: richLeaf, nextRadius: 12 } }, + { kind: "radius", request: { nodeId: 3n, radius: 12 } }, + ], + [ + SpatialSkeletonActions.editNodeConfidence, + { kind: "confidence", options: { node: richLeaf, nextConfidence: 90 } }, + { kind: "confidence", request: { nodeId: 3n, confidence: 90 } }, + ], + [ + SpatialSkeletonActions.splitSkeletons, + { kind: "split", node: richLeaf }, + { kind: "split", request: { nodeId: 3n } }, + ], + [ + SpatialSkeletonActions.mergeSkeletons, + { + kind: "merge", + options: { firstNode: first[1], secondNode: second[1] }, + }, + { + kind: "merge", + request: { fromNodeId: 101n, toNodeId: 201n }, + inputSegmentIds: [11n, 17n], + }, + ], + ]; + cases.forEach(([action, payload, expected], index) => { + const actual = editRequest(command(action, "Edit", payload), index + 1); + expect(actual.kind).toBe((expected as { kind: string }).kind); + expect(actual.request).toEqual((expected as { request: object }).request); + if (actual.kind === "merge") { + expect(actual.inputSegmentIds).toEqual( + (expected as { inputSegmentIds: readonly bigint[] }).inputSegmentIds, + ); + } + }); + }); + + it("sends a move to the node's current ID when the ID changed after planning", () => { + const original = node(2, 23, 1); + const { planner, identities } = makePlanner( + new Map([[23n, [node(1, 23), original]]]), + ); + const logical = planner.planIntent( + command(SpatialSkeletonActions.moveNodes, "Move", { + kind: "move-node", + options: { + node: original, + nextPositionInModelSpace: [10, 11, 12], + }, + }), + context(1, "execute"), + ); + const delta = logical.preview.delta; + if (delta.kind !== "move") throw new Error("Expected move preview."); + identities.apply({ bindings: { nodes: [[delta.node, 900n]] } }); + + expect( + planner + .nextAttempt(logical.plan, planContext(1, "execute", []))! + .materializeEditRequest(), + ).toEqual({ + kind: "move-node", + request: { nodeId: 900n, position: [10, 11, 12] }, + }); + }); + + it("restores a deleted description and true-end label in one CATMAID request", () => { + const deleted = Object.freeze({ + ...node(2, 23, 1, { true_end: [1] }), + description: "terminal", + }); + const { planner, identities } = makePlanner( + new Map([[23n, [node(1, 23), deleted]]]), + ); + const descriptor = command(SpatialSkeletonActions.deleteNodes, "Delete", { + kind: "delete-node", + node: deleted, + }); + const execute = planner.planIntent(descriptor, context(1, "execute")); + const undo = planner.planIntent( + descriptor, + context(2, "undo", { + plan: execute.plan, + preview: execute.preview, + inversePreview: { + kind: "restore-delete", + segment: identities.getOrCreateSegmentHandle(23n), + snapshot: { + node: identities.getOrCreateNodeHandle(2n), + parent: identities.getOrCreateNodeHandle(1n), + position: deleted.position, + attributes: { description: "terminal", isTrueEnd: true }, + }, + children: [], + }, + }), + ); + const attempts: CommittedAttempt[] = []; + expect( + commitNextAttempt( + planner, + undo.plan, + { nodeId: 20n, segmentId: 23n } as any, + attempts, + "undo", + ), + ).toMatchObject({ + kind: "add-node", + request: { position: new Float32Array([2, 3, 4]), parentNodeId: 1n }, + }); + expect( + commitNextAttempt( + planner, + undo.plan, + { description: "terminal" } as any, + attempts, + "undo", + ), + ).toEqual({ + kind: "description", + request: { nodeId: 20n, description: "terminal", isTrueEnd: true }, + }); + expect( + planner.nextAttempt(undo.plan, planContext(2, "undo", attempts)), + ).toBeUndefined(); + }); + + it("Redo of an added node creates it again under a new ID that the same handle follows", () => { + const { planner, identities } = makePlanner( + new Map([[23n, [node(1, 23)]]]), + ); + const descriptor = command(SpatialSkeletonActions.addNodes, "Add node", { + kind: "add-node", + options: { + skeletonId: 23n, + parentNodeId: 1n, + positionInModelSpace: Object.freeze([4, 5, 6]), + }, + }); + const execute = planner.planIntent(descriptor, context(1, "execute")); + expect(execute.kind).toBe("addNode"); + expect(execute.preview.provisionalBindings?.nodes?.[0]?.[1]).toBe(999_999n); + expect(execute.preview.uiHints).toMatchObject({ + segmentVisibility: [{ visible: true, select: "pin" }], + selectedNode: { + kind: "select", + position: [4, 5, 6], + moveView: true, + }, + }); + + const executeAttempts: CommittedAttempt[] = []; + expect( + commitNextAttempt( + planner, + execute.plan, + { nodeId: 2n, segmentId: 23n } as any, + executeAttempts, + ), + ).toMatchObject({ + kind: "add-node", + request: { parentNodeId: 1n }, + }); + const executeReconciliation = planner.createReconciliation( + execute.plan, + planContext(1, "execute", executeAttempts), + ); + identities.apply(executeReconciliation); + const createdHandle = (execute.preview.delta as any).node; + expect(identities.resolveNode(createdHandle)).toBe(2n); + + const inversePreview = { + kind: "delete", + segment: (execute.preview.delta as any).segment, + node: createdHandle, + } as SpatialSkeletonEditInverseDelta; + const recipe = { + plan: execute.plan, + preview: execute.preview, + inversePreview, + }; + const undo = planner.planIntent(descriptor, context(2, "undo", recipe)); + expect(undo.preview.delta).toBe(inversePreview); + expect(undo.plan).not.toBe(execute.plan); + expect(undo.preview.uiHints).toMatchObject({ + selectedNode: { kind: "select", node: { stableId: "authority:1" } }, + }); + const undoAttempts: CommittedAttempt[] = []; + const undoEditRequest = commitNextAttempt( + planner, + undo.plan, + {} as any, + undoAttempts, + "undo", + ); + expect(undoEditRequest).toEqual({ + kind: "delete-node", + request: { nodeId: 2n }, + }); + expect(executeAttempts).toHaveLength(1); + + const redo = planner.planIntent(descriptor, context(3, "redo", recipe)); + expect(redo.preview.delta).toStrictEqual(execute.preview.delta); + expect(redo.preview.provisionalBindings?.nodes?.[0]?.[1]).toBe(999_997n); + expect(redo.preview.uiHints).toMatchObject({ + segmentVisibility: [{ visible: true, select: "preserve" }], + selectedNode: { kind: "select", moveView: false }, + }); + const redoAttempts: CommittedAttempt[] = []; + expect( + commitNextAttempt( + planner, + redo.plan, + { nodeId: 3n, segmentId: 23n } as any, + redoAttempts, + "redo", + ), + ).toMatchObject({ + kind: "add-node", + request: { parentNodeId: 1n }, + }); + identities.apply( + planner.createReconciliation( + redo.plan, + planContext(3, "redo", redoAttempts), + ), + ); + expect(identities.resolveNode(createdHandle)).toBe(3n); + }); + + it("reroots at the chosen node on Execute and Redo, and at the original root on Undo", () => { + const nodes = [node(1, 23), node(2, 23, 1), node(3, 23, 2), node(4, 23, 1)]; + const { planner } = makePlanner(new Map([[23n, nodes]])); + const descriptor = command(SpatialSkeletonActions.reroot, "Reroot", { + kind: "reroot", + node: nodes[2], + }); + const execute = planner.planIntent(descriptor, context(1, "execute")); + const semantic = execute.plan.semantic; + if (semantic.kind !== "reroot") + throw new Error("Expected reroot semantic."); + expect(semantic.node.stableId).toBe("authority:3"); + expect(semantic.originalRoot.stableId).toBe("authority:1"); + const recipe = { + plan: execute.plan, + preview: execute.preview, + inversePreview: { + kind: "restore-topology", + segment: semantic.segment, + patches: nodes.slice(0, 3).map((node) => ({ + node: semantic.retainedNodes.get(node.nodeId)!, + parent: + node.parentNodeId === undefined + ? null + : semantic.retainedNodes.get(node.parentNodeId)!, + confidence: node.attributes?.confidence?.[0], + })), + } as SpatialSkeletonEditInverseDelta, + }; + + for (const [intent, intentId] of [ + ["execute", 1], + ["undo", 2], + ["redo", 3], + ] as const) { + const logical = + intent === "execute" + ? execute + : planner.planIntent(descriptor, context(intentId, intent, recipe)); + const attempts: CommittedAttempt[] = []; + const editRequest = commitNextAttempt( + planner, + logical.plan, + undefined, + attempts, + intent, + ); + expect(editRequest).toEqual({ + kind: "reroot", + request: { nodeId: intent === "undo" ? 1n : 3n }, + }); + expect( + planner.nextAttempt( + logical.plan, + planContext(intentId, intent, attempts), + ), + ).toBeUndefined(); + const reconciliation = planner.createReconciliation( + logical.plan, + planContext(intentId, intent, attempts), + ); + expect(reconciliation).toEqual({ + bindings: { nodes: [], segments: [] }, + retiredResources: [], + }); + } + }); + + it("after a delete, selects the parent, or clears the selection when the skeleton is gone", () => { + const { planner } = makePlanner( + new Map([[23n, [node(1, 23), node(2, 23, 1)]]]), + ); + const childDelete = planner.planIntent( + command(SpatialSkeletonActions.deleteNodes, "Delete node", { + kind: "delete-node", + node: node(2, 23, 1), + }), + context(1, "execute"), + ); + expect(childDelete.preview.uiHints).toMatchObject({ + selectedNode: { + kind: "select", + node: { stableId: "authority:1" }, + segment: { stableId: "authority:23" }, + moveView: true, + }, + }); + + const { planner: soleRootPlanner } = makePlanner( + new Map([[31n, [node(7, 31)]]]), + ); + const rootDelete = soleRootPlanner.planIntent( + command(SpatialSkeletonActions.deleteNodes, "Delete node", { + kind: "delete-node", + node: node(7, 31), + }), + context(2, "execute"), + ); + expect(rootDelete.preview.uiHints).toMatchObject({ + segmentVisibility: [ + { + segment: { stableId: "authority:31" }, + visible: false, + deselect: true, + }, + ], + selectedNode: { kind: "clear" }, + }); + }); + + describe("merge", () => { + it("when CATMAID keeps the second skeleton, both merged skeletons resolve to it", () => { + const { planner, identities } = makePlanner( + new Map([ + [11n, [node(101, 11)]], + [17n, [node(201, 17)]], + ]), + ); + const logical = planner.planIntent( + command(SpatialSkeletonActions.mergeSkeletons, "Merge skeletons", { + kind: "merge", + options: { + firstNode: { nodeId: 101n, segmentId: 11n }, + secondNode: { nodeId: 201n, segmentId: 17n }, + }, + }), + context(1, "execute"), + ); + identities.apply({ + bindings: logical.preview.inspectionSeed?.authoritativeBindings, + }); + const attempts: CommittedAttempt[] = []; + expect( + commitNextAttempt( + planner, + logical.plan, + { + resultSegmentId: 17n, + deletedSegmentId: 11n, + directionAdjusted: true, + } as any, + attempts, + ), + ).toMatchObject({ + kind: "merge", + request: { + fromNodeId: 101n, + toNodeId: 201n, + }, + }); + const reconciliation = planner.createReconciliation( + logical.plan, + planContext(1, "execute", attempts), + ); + identities.apply(reconciliation); + const merge = logical.preview.delta as any; + + expect(identities.resolveSegment(merge.firstSegment)).toBe(17n); + expect(identities.resolveSegment(merge.secondSegment)).toBe(17n); + expect(identities.resolveSegment(merge.resultSegment)).toBe(17n); + expect(merge.resultSegment.stableId).not.toBe( + merge.firstSegment.stableId, + ); + expect(merge.resultSegment.stableId).not.toBe( + merge.secondSegment.stableId, + ); + expect(reconciliation.retiredResources).toEqual([]); + expect(reconciliation.finalizedPreviewDelta).toMatchObject({ + kind: "merge", + firstSegment: merge.secondSegment, + secondSegment: merge.firstSegment, + resultSegment: merge.resultSegment, + firstNode: merge.secondNode, + secondNode: merge.firstNode, + }); + expect(logical.preview.uiHints).toMatchObject({ + segmentVisibilityStateRemaps: [ + { + from: { stableId: "authority:11" }, + to: { stableId: "intent:1:merge-output" }, + }, + { + from: { stableId: "authority:17" }, + to: { stableId: "intent:1:merge-output" }, + }, + ], + segmentVisibility: [ + { segment: { stableId: "intent:1:merge-output" }, visible: true }, + { segment: { stableId: "authority:17" }, visible: false }, + ], + selectedNode: { + kind: "select", + node: { stableId: "authority:201" }, + segment: { stableId: "intent:1:merge-output" }, + }, + }); + }); + + it("retires whichever skeleton CATMAID deleted, on Merge and on Redo", () => { + const makeMerge = () => { + const setup = makePlanner( + new Map([ + [11n, [node(100, 11), node(101, 11, 100)]], + [17n, [node(200, 17), node(201, 17, 200)]], + ]), + ); + const descriptor = command( + SpatialSkeletonActions.mergeSkeletons, + "Merge", + { + kind: "merge", + options: { + firstNode: { nodeId: 101n, segmentId: 11n }, + secondNode: { nodeId: 201n, segmentId: 17n }, + }, + }, + ); + const execute = setup.planner.planIntent( + descriptor, + context(1, "execute"), + ); + return { ...setup, descriptor, execute }; + }; + + for (const directionAdjusted of [false, true]) { + const { planner, execute } = makeMerge(); + const attempts: CommittedAttempt[] = []; + const resultSegmentId = directionAdjusted ? 17n : 11n; + const deletedSegmentId = directionAdjusted ? 11n : 17n; + commitNextAttempt( + planner, + execute.plan, + { resultSegmentId, deletedSegmentId, directionAdjusted } as any, + attempts, + ); + const reconciliation = planner.createReconciliation( + execute.plan, + planContext(1, "execute", attempts), + ); + expect(reconciliation.retiredSegmentIds).toEqual([deletedSegmentId]); + expect(reconciliation.finalizedPreviewDelta === undefined).toBe( + !directionAdjusted, + ); + } + + for (const directionAdjusted of [false, true]) { + const { planner, descriptor, execute } = makeMerge(); + const semantic = execute.plan.semantic; + if (semantic.kind !== "merge") + throw new Error("Expected merge semantic."); + const inversePreview = { + kind: "unmerge", + mergedSegment: semantic.mergedSegment, + firstSegment: semantic.secondSegment, + secondSegment: semantic.firstSegment, + firstNode: semantic.secondNode, + secondNode: semantic.firstNode, + formerSecondTopology: [ + { node: semantic.firstNode, parent: null, confidence: undefined }, + ], + } as SpatialSkeletonEditInverseDelta; + const redo = planner.planIntent( + descriptor, + context(3, "redo", { + plan: execute.plan, + preview: execute.preview, + inversePreview, + }), + ); + const attempts: CommittedAttempt[] = []; + commitNextAttempt( + planner, + redo.plan, + { + resultSegmentId: directionAdjusted ? 11n : 17n, + deletedSegmentId: directionAdjusted ? 17n : 11n, + directionAdjusted, + } as any, + attempts, + "redo", + ); + const reconciliation = planner.createReconciliation( + redo.plan, + planContext(3, "redo", attempts), + ); + expect(reconciliation.retiredSegmentIds).toEqual([ + directionAdjusted ? 17n : 11n, + ]); + expect(reconciliation.finalizedPreviewDelta === undefined).toBe( + !directionAdjusted, + ); + } + }); + + it.each([false, true])( + "Undo of a split keeps the original skeleton, or asks for a reload when CATMAID keeps the split-off one (CATMAID kept the split-off one: %s)", + (directionAdjusted) => { + const nodes = [node(1, 23), node(2, 23, 1)]; + const { planner, identities } = makePlanner(new Map([[23n, nodes]])); + const descriptor = command( + SpatialSkeletonActions.splitSkeletons, + "Split", + { + kind: "split", + node: nodes[1], + }, + ); + const execute = planner.planIntent(descriptor, context(1, "execute")); + const semantic = execute.plan.semantic; + if (semantic.kind !== "split") + throw new Error("Expected split semantic."); + identities.apply({ + bindings: { + segments: [ + [semantic.sourceSegment, 23n], + [semantic.downstreamSegment, 24n], + ], + }, + }); + const undo = planner.planIntent( + descriptor, + context(2, "undo", { + plan: execute.plan, + preview: execute.preview, + inversePreview: { + kind: "join-split", + sourceSegment: semantic.sourceSegment, + downstreamSegment: semantic.downstreamSegment, + resultSegment: semantic.sourceSegment, + formerParent: semantic.formerParent, + node: semantic.node, + }, + }), + ); + const attempts: CommittedAttempt[] = []; + commitNextAttempt( + planner, + undo.plan, + { + resultSegmentId: directionAdjusted ? 24n : 23n, + deletedSegmentId: directionAdjusted ? 23n : 24n, + directionAdjusted, + } as any, + attempts, + "undo", + ); + const reconcile = () => + planner.createReconciliation( + undo.plan, + planContext(2, "undo", attempts), + ); + if (directionAdjusted) { + expect(reconcile).toThrow( + /reversed the merge used to undo a split.*reload is required/i, + ); + } else { + expect(reconcile()).toMatchObject({ + bindings: { + segments: [ + [semantic.sourceSegment, 23n], + [semantic.downstreamSegment, 23n], + ], + }, + retiredResources: [], + retiredSegmentIds: [24n], + }); + } + }, + ); + + it("after CATMAID reversed a merge, Undo splits at the original node and Redo merges in CATMAID's direction", () => { + const { planner, identities } = makePlanner( + new Map([ + [11n, [node(101, 11)]], + [17n, [node(201, 17)]], + ]), + ); + const descriptor = command( + SpatialSkeletonActions.mergeSkeletons, + "Merge skeletons", + { + kind: "merge", + options: { + firstNode: { nodeId: 101n, segmentId: 11n }, + secondNode: { nodeId: 201n, segmentId: 17n }, + }, + }, + ); + const execute = planner.planIntent(descriptor, context(1, "execute")); + const semantic = execute.plan.semantic; + if (semantic.kind !== "merge") + throw new Error("Expected merge semantic."); + identities.apply({ + bindings: { + segments: [ + [semantic.firstSegment, 99n], + [semantic.secondSegment, 99n], + [semantic.mergedSegment, 99n], + ], + }, + }); + const inversePreview = { + kind: "unmerge", + mergedSegment: semantic.mergedSegment, + firstSegment: semantic.secondSegment, + secondSegment: semantic.firstSegment, + firstNode: semantic.secondNode, + secondNode: semantic.firstNode, + formerSecondTopology: [ + { node: semantic.firstNode, parent: null, confidence: undefined }, + ], + } as SpatialSkeletonEditInverseDelta; + const undo = planner.planIntent( + descriptor, + context(2, "undo", { + plan: execute.plan, + preview: execute.preview, + inversePreview, + }), + ); + + expect(undo.plan.semantic).toMatchObject({ + kind: "merge", + inverseOrientation: "first-from-second", + originalRoot: semantic.firstNode, + originalRootConfidence: undefined, + }); + expect(undo.preview.delta).toBe(inversePreview); + const splitBack = planner.nextAttempt( + undo.plan, + planContext(2, "undo", []), + ); + expect(splitBack?.materializeEditRequest()).toMatchObject({ + kind: "split", + request: { nodeId: 101n }, + }); + + const redo = planner.planIntent( + descriptor, + context(3, "redo", { + plan: execute.plan, + preview: execute.preview, + inversePreview, + }), + ); + expect(redo.plan.semantic).toMatchObject({ + kind: "merge", + inverseOrientation: "first-from-second", + }); + expect(redo.preview.delta).toMatchObject({ + kind: "merge", + firstSegment: semantic.secondSegment, + secondSegment: semantic.firstSegment, + firstNode: semantic.secondNode, + secondNode: semantic.firstNode, + }); + const redoAttempt = planner.nextAttempt( + redo.plan, + planContext(3, "redo", []), + ); + expect(redoAttempt?.materializeEditRequest()).toMatchObject({ + kind: "merge", + request: { + fromNodeId: 201n, + toNodeId: 101n, + }, + }); + }); + + it("Redo of a Merge with no recorded inverse merges in the original direction", () => { + const { planner } = makePlanner( + new Map([ + [11n, [node(101, 11)]], + [17n, [node(201, 17)]], + ]), + ); + const descriptor = command( + SpatialSkeletonActions.mergeSkeletons, + "Merge skeletons", + { + kind: "merge", + options: { + firstNode: { nodeId: 101n, segmentId: 11n }, + secondNode: { nodeId: 201n, segmentId: 17n }, + }, + }, + ); + const execute = planner.planIntent(descriptor, context(1, "execute")); + const redo = planner.planIntent( + descriptor, + context(3, "redo", { + plan: execute.plan, + preview: execute.preview, + }), + ); + + expect(redo.plan.semantic).toMatchObject({ + kind: "merge", + inverseOrientation: "second-from-first", + }); + expect(redo.preview.delta).toStrictEqual(execute.preview.delta); + }); + }); +}); diff --git a/src/datasource/catmaid/spatial_skeleton_edit/edit_planner.ts b/src/datasource/catmaid/spatial_skeleton_edit/edit_planner.ts new file mode 100644 index 0000000000..5b018ff117 --- /dev/null +++ b/src/datasource/catmaid/spatial_skeleton_edit/edit_planner.ts @@ -0,0 +1,2216 @@ +/** + * @license + * Copyright 2026 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file Turns each CATMAID Execute, Undo or Redo intent into a preview and a + * plan, builds the edit request for each step, and reads CATMAID's results into + * confirmed IDs. + */ + +import { toCatmaidPositionInModelSpace } from "#src/datasource/catmaid/api.js"; +import type { CatmaidSpatialSkeletonCommandPayload } from "#src/datasource/catmaid/spatial_skeleton_edit/command_payloads.js"; +import type { + CatmaidAttributeSemantic, + CatmaidCapturedSegment, + CatmaidCreatedNodeSemantic, + CatmaidDeleteNodeSemantic, + CatmaidMergeSemantic, + CatmaidMoveNodeSemantic, + CatmaidRerootSemantic, + CatmaidRetainedNode, + CatmaidCapturedEdit, + CatmaidSplitSemantic, + CatmaidEditPlan, + CatmaidEditPlanStep, +} from "#src/datasource/catmaid/spatial_skeleton_edit/edit_plan.js"; +import { + makeSteps, + requirePositiveId, +} from "#src/datasource/catmaid/spatial_skeleton_edit/edit_plan.js"; +import type { + CatmaidEditRequest, + CatmaidEditRequestResult, +} from "#src/datasource/catmaid/spatial_skeleton_edit/edit_requests.js"; +import type { SkeletonNode, SkeletonVector } from "#src/skeleton/api.js"; +import type { + SpatialSkeletonAction, + SpatialSkeletonEditCommand, +} from "#src/skeleton/edit/edit_commands.js"; +import type { + SpatialSkeletonIntentCreationContext, + SpatialSkeletonEditPlanner, + SpatialSkeletonIntentPlan, + SpatialSkeletonEditPlanContext, + SpatialSkeletonIdentityService, + SpatialSkeletonPendingEditDescriptor, + SpatialSkeletonProvisionalNumericIdPolicy, + SpatialSkeletonProvisionalNumericIdService, +} from "#src/skeleton/edit_queue/api.js"; +import type { CompleteSkeleton } from "#src/skeleton/edit_queue/complete_skeleton.js"; +import type { + SpatialSkeletonEditDelta, + SpatialSkeletonEditInverseDelta, +} from "#src/skeleton/edit_queue/complete_skeleton_edits.js"; +import { getSkeletonNodeChanges } from "#src/skeleton/edit_queue/complete_skeleton_edits.js"; +import type { SpatialSkeletonIntentResource } from "#src/skeleton/edit_queue/edit_intent_journal.js"; +import type { + SpatialSkeletonAuthoritativeReconciliation, + SpatialSkeletonPreviewInspectionSeed, + SpatialSkeletonPreviewIntentDelta, +} from "#src/skeleton/edit_queue/preview.js"; +import type { SpatialSkeletonPreviewUiHints } from "#src/skeleton/edit_queue/preview_ui_hints.js"; +import type { SpatialSkeletonQueueInput } from "#src/skeleton/edit_queue/queue_input.js"; +import type { + SpatialSkeletonStableNodeHandle, + SpatialSkeletonStableResourceHandle, + SpatialSkeletonStableSegmentHandle, +} from "#src/skeleton/edit_queue/stable_id_handles.js"; +import { + getSpatialSkeletonStableResourceKey, + spatialSkeletonStableNode, + spatialSkeletonStableSegment, +} from "#src/skeleton/edit_queue/stable_id_handles.js"; +import type { SpatialSkeletonAuthorityLabels } from "#src/skeleton/edit_queue/types.js"; +import { + getSkeletonNodeConfidence, + getSkeletonNodeRadius, + isSkeletonNodeTrueEnd, +} from "#src/skeleton/node_attributes.js"; + +export type { CatmaidEditPlan } from "#src/datasource/catmaid/spatial_skeleton_edit/edit_plan.js"; + +/** Immutable queue input returned by CATMAID command factories. */ +export interface CatmaidSpatialSkeletonCommandDescriptor + extends SpatialSkeletonEditCommand { + readonly action: SpatialSkeletonAction; + readonly payload: CatmaidSpatialSkeletonCommandPayload; +} + +interface CatmaidMaterializationContext { + readonly direction: "forward" | "inverse"; + readonly localNodeBindings: ReadonlyMap; + readonly localSegmentBindings: ReadonlyMap; +} + +type CatmaidEditPlanContext = SpatialSkeletonEditPlanContext< + CatmaidEditRequest, + CatmaidEditRequestResult +>; + +/** CATMAID authority half of the generic edit planner. */ +abstract class CatmaidEditPlanCommitBase { + constructor(protected readonly identity: SpatialSkeletonIdentityService) {} + + protected segmentHandle(segmentId: bigint) { + return this.identity.getOrCreateSegmentHandle(segmentId); + } + + nextAttempt(plan: CatmaidEditPlan, context: CatmaidEditPlanContext) { + const steps = makeSteps(plan.semantic, plan.direction); + const step = steps[context.committedAttempts.length]; + if (step === undefined) return undefined; + const { committedAttempts } = context; + return Object.freeze({ + materializeEditRequest: () => + this.makeEditRequest( + this.createMaterializationContext(plan, committedAttempts), + step, + ), + }); + } + + createReconciliation(plan: CatmaidEditPlan, context: CatmaidEditPlanContext) { + return this.reconcile(plan, context); + } + + private createMaterializationContext( + plan: CatmaidEditPlan, + attempts: CatmaidEditPlanContext["committedAttempts"], + ): CatmaidMaterializationContext { + const localNodeBindings = new Map(); + const localSegmentBindings = new Map(); + const steps = makeSteps(plan.semantic, plan.direction); + for (let index = 0; index < attempts.length; ++index) { + const attempt = attempts[index]; + const step = steps[index]!; + if (step.kind === "add-node" || step.kind === "insert-node") { + const result = attempt.result as { + readonly nodeId?: bigint; + readonly segmentId?: bigint; + }; + localNodeBindings.set( + step.semantic.node.stableId, + requirePositiveId(result.nodeId, "created node result"), + ); + localSegmentBindings.set( + step.semantic.segment.stableId, + requirePositiveId(result.segmentId, "created skeleton result"), + ); + } else if (step.kind === "split") { + const result = attempt.result as { + readonly existingSegmentId?: bigint; + readonly newSegmentId?: bigint; + }; + const existingId = requirePositiveId( + result.existingSegmentId, + "split existing skeleton", + ); + const newId = requirePositiveId( + result.newSegmentId, + "split result skeleton", + ); + if (step.semantic.kind === "split") { + localSegmentBindings.set( + step.semantic.sourceSegment.stableId, + existingId, + ); + localSegmentBindings.set( + step.semantic.downstreamSegment.stableId, + newId, + ); + } else { + const existingSegment = + step.semantic.inverseOrientation === "second-from-first" + ? step.semantic.firstSegment + : step.semantic.secondSegment; + const restoredSegment = + step.semantic.inverseOrientation === "second-from-first" + ? step.semantic.secondSegment + : step.semantic.firstSegment; + localSegmentBindings.set(existingSegment.stableId, existingId); + localSegmentBindings.set(restoredSegment.stableId, newId); + } + } else if (step.kind === "merge") { + const resultId = requirePositiveId( + (attempt.result as { readonly resultSegmentId?: bigint }) + .resultSegmentId, + "merge result skeleton", + ); + if (step.semantic.kind === "split") { + localSegmentBindings.set( + step.semantic.sourceSegment.stableId, + resultId, + ); + localSegmentBindings.set( + step.semantic.downstreamSegment.stableId, + resultId, + ); + } else { + localSegmentBindings.set( + step.semantic.firstSegment.stableId, + resultId, + ); + localSegmentBindings.set( + step.semantic.secondSegment.stableId, + resultId, + ); + localSegmentBindings.set( + step.semantic.mergedSegment.stableId, + resultId, + ); + } + } + } + return Object.freeze({ + direction: plan.direction, + localNodeBindings, + localSegmentBindings, + }); + } + + private resolveNode( + context: CatmaidMaterializationContext, + handle: SpatialSkeletonStableNodeHandle, + ) { + const local = context.localNodeBindings.get(handle.stableId); + if (local !== undefined) return local; + const physicalId = this.identity.resolveAuthoritativeNode(handle); + if (physicalId === undefined) { + const target = this.identity.resolveNodeTarget(handle); + throw new Error( + `CATMAID plan requires authoritative node ${handle.stableId}; it is ${target.state}.`, + ); + } + return physicalId; + } + + private resolveSegment( + context: CatmaidMaterializationContext, + handle: SpatialSkeletonStableSegmentHandle, + ) { + const local = context.localSegmentBindings.get(handle.stableId); + if (local !== undefined) return local; + const physicalId = this.identity.resolveAuthoritativeSegment(handle); + if (physicalId === undefined) { + const target = this.identity.resolveSegmentTarget(handle); + throw new Error( + `CATMAID plan requires authoritative skeleton ${handle.stableId}; it is ${target.state}.`, + ); + } + return physicalId; + } + + private makeEditRequest( + context: CatmaidMaterializationContext, + step: CatmaidEditPlanStep, + ): CatmaidEditRequest { + switch (step.kind) { + case "add-node": { + const semantic = step.semantic as + | CatmaidCreatedNodeSemantic + | CatmaidDeleteNodeSemantic; + const { parent } = semantic; + return { + kind: "add-node", + request: { + position: + semantic.kind === "delete-node" + ? semantic.deletedSnapshot.position + : semantic.position, + parentNodeId: + parent === undefined + ? undefined + : this.resolveNode(context, parent), + }, + }; + } + case "insert-node": { + const { semantic } = step; + if (semantic.parent === undefined) { + throw new Error("CATMAID insert plan is missing its parent."); + } + return { + kind: "insert-node", + request: { + position: + semantic.kind === "delete-node" + ? semantic.deletedSnapshot.position + : semantic.position, + parentNodeId: this.resolveNode(context, semantic.parent), + childNodeIds: (semantic.children ?? []).map((handle) => + this.resolveNode(context, handle), + ), + }, + }; + } + case "delete-node": { + const semantic = step.semantic as + | CatmaidCreatedNodeSemantic + | CatmaidDeleteNodeSemantic; + return { + kind: "delete-node", + request: { nodeId: this.resolveNode(context, semantic.node) }, + }; + } + case "move-node": { + const semantic = step.semantic as CatmaidMoveNodeSemantic; + return { + kind: "move-node", + request: { + nodeId: this.resolveNode(context, semantic.node), + position: + context.direction === "forward" + ? semantic.after + : semantic.before, + }, + }; + } + case "description": { + const semantic = step.semantic as + | CatmaidAttributeSemantic + | CatmaidDeleteNodeSemantic; + const value = this.getAttributeValue(context, semantic, "description"); + return { + kind: "description", + request: { + nodeId: this.resolveNode(context, semantic.node), + description: typeof value === "string" ? value : "", + isTrueEnd: + semantic.kind === "delete-node" + ? isSkeletonNodeTrueEnd(semantic.deletedSnapshot) + : isSkeletonNodeTrueEnd(semantic.nodeSnapshot), + }, + }; + } + case "true-end": { + const semantic = step.semantic as + | CatmaidAttributeSemantic + | CatmaidDeleteNodeSemantic; + return { + kind: "true-end", + request: { + nodeId: this.resolveNode(context, semantic.node), + isTrueEnd: Boolean( + this.getAttributeValue(context, semantic, "true-end"), + ), + }, + }; + } + case "radius": { + const semantic = step.semantic as + | CatmaidAttributeSemantic + | CatmaidDeleteNodeSemantic; + return { + kind: "radius", + request: { + nodeId: this.resolveNode(context, semantic.node), + radius: Number(this.getAttributeValue(context, semantic, "radius")), + }, + }; + } + case "restore-confidence": + return { + kind: "confidence", + request: { + nodeId: this.resolveNode(context, step.node), + confidence: step.confidence, + }, + }; + case "confidence": { + const semantic = step.semantic as + | CatmaidAttributeSemantic + | CatmaidDeleteNodeSemantic; + return { + kind: "confidence", + request: { + nodeId: this.resolveNode(context, semantic.node), + confidence: Number( + this.getAttributeValue(context, semantic, "confidence"), + ), + }, + }; + } + case "reroot": { + const semantic = step.semantic as + | CatmaidRerootSemantic + | CatmaidMergeSemantic; + const target = + semantic.kind === "reroot" && context.direction === "forward" + ? semantic.node + : semantic.originalRoot; + return { + kind: "reroot", + request: { nodeId: this.resolveNode(context, target) }, + }; + } + case "split": { + const semantic = step.semantic as + | CatmaidSplitSemantic + | CatmaidMergeSemantic; + const target = + semantic.kind === "split" + ? semantic.node + : semantic.inverseOrientation === "second-from-first" + ? semantic.secondNode + : semantic.firstNode; + return { + kind: "split", + request: { nodeId: this.resolveNode(context, target) }, + }; + } + case "merge": { + const semantic = step.semantic as + | CatmaidSplitSemantic + | CatmaidMergeSemantic; + const firstHandle = + semantic.kind === "split" + ? semantic.formerParent + : semantic.inverseOrientation === "second-from-first" + ? semantic.firstNode + : semantic.secondNode; + const secondHandle = + semantic.kind === "split" + ? semantic.node + : semantic.inverseOrientation === "second-from-first" + ? semantic.secondNode + : semantic.firstNode; + const inputSegmentIds: readonly [bigint, bigint] = Object.freeze( + semantic.kind === "split" + ? [ + this.resolveSegment(context, semantic.sourceSegment), + this.resolveSegment(context, semantic.downstreamSegment), + ] + : [ + this.resolveSegment(context, semantic.firstSegment), + this.resolveSegment(context, semantic.secondSegment), + ], + ); + const editRequest: CatmaidEditRequest<"merge"> = Object.freeze({ + kind: "merge", + request: Object.freeze({ + fromNodeId: this.resolveNode(context, firstHandle), + toNodeId: this.resolveNode(context, secondHandle), + }), + inputSegmentIds, + }); + return editRequest; + } + } + } + + private getAttributeValue( + context: CatmaidMaterializationContext, + semantic: CatmaidAttributeSemantic | CatmaidDeleteNodeSemantic, + kind: "description" | "true-end" | "radius" | "confidence", + ) { + if (semantic.kind === "delete-node") { + switch (kind) { + case "description": + return semantic.deletedSnapshot.description; + case "true-end": + return isSkeletonNodeTrueEnd(semantic.deletedSnapshot); + case "radius": + return getSkeletonNodeRadius(semantic.deletedSnapshot) ?? 0; + case "confidence": + return getSkeletonNodeConfidence(semantic.deletedSnapshot) ?? 0; + } + } + return context.direction === "forward" ? semantic.after : semantic.before; + } + + private reconcile( + plan: CatmaidEditPlan, + context: CatmaidEditPlanContext, + ): SpatialSkeletonAuthoritativeReconciliation { + const materialization = this.createMaterializationContext( + plan, + context.committedAttempts, + ); + const nodeBindings: Array< + readonly [SpatialSkeletonStableNodeHandle, bigint] + > = []; + const segmentBindings: Array< + readonly [SpatialSkeletonStableSegmentHandle, bigint] + > = []; + const retired = new Map(); + const retiredSegmentIds = new Set(); + let finalizedPreviewDelta: SpatialSkeletonEditDelta | undefined; + + const steps = makeSteps(plan.semantic, plan.direction); + const attempts = context.committedAttempts; + for (let index = 0; index < attempts.length; ++index) { + const committed = attempts[index]; + const step = steps[index]!; + switch (step.kind) { + case "add-node": + case "insert-node": { + const result = committed.result as { + nodeId: bigint; + segmentId: bigint; + }; + nodeBindings.push([step.semantic.node, result.nodeId]); + segmentBindings.push([step.semantic.segment, result.segmentId]); + break; + } + case "description": { + const result = committed.result as { + description?: string; + }; + if ( + step.semantic.kind === "description" && + result.description !== + this.getAttributeValue( + materialization, + step.semantic, + "description", + ) + ) { + finalizedPreviewDelta = { + kind: "node-attributes", + segment: step.semantic.segment, + node: step.semantic.node, + changes: { description: result.description }, + }; + } + break; + } + case "delete-node": { + retired.set( + getSpatialSkeletonStableResourceKey(step.semantic.node), + step.semantic.node, + ); + if ( + (step.semantic.kind === "add-node" && + step.semantic.createsSegment) || + (step.semantic.kind === "delete-node" && step.semantic.wasSoleRoot) + ) { + retired.set( + getSpatialSkeletonStableResourceKey(step.semantic.segment), + step.semantic.segment, + ); + } + break; + } + case "split": { + const result = committed.result as { + existingSegmentId?: bigint; + newSegmentId?: bigint; + }; + const existingId = requirePositiveId( + result.existingSegmentId, + "split existing skeleton", + ); + const newId = requirePositiveId( + result.newSegmentId, + "split result skeleton", + ); + if (step.semantic.kind === "split") { + segmentBindings.push([step.semantic.sourceSegment, existingId]); + segmentBindings.push([step.semantic.downstreamSegment, newId]); + } else { + const existingSegment = + step.semantic.inverseOrientation === "second-from-first" + ? step.semantic.firstSegment + : step.semantic.secondSegment; + const restoredSegment = + step.semantic.inverseOrientation === "second-from-first" + ? step.semantic.secondSegment + : step.semantic.firstSegment; + segmentBindings.push([existingSegment, existingId]); + segmentBindings.push([restoredSegment, newId]); + } + break; + } + case "merge": { + const result = committed.result as { + resultSegmentId?: bigint; + deletedSegmentId?: bigint; + directionAdjusted?: boolean; + }; + const resultId = requirePositiveId( + result.resultSegmentId, + "merge result skeleton", + ); + const deletedId = requirePositiveId( + result.deletedSegmentId, + "merge deleted skeleton", + ); + if (step.semantic.kind === "split") { + if (result.directionAdjusted === true) { + throw new Error( + "CATMAID reversed the merge used to undo a split; reload is required to reconcile the committed topology.", + ); + } + const [sourceId, downstreamId] = this.requireMergeInputSegmentIds( + committed.editRequest, + ); + if (resultId !== sourceId || deletedId !== downstreamId) { + throw new Error( + "CATMAID split Undo merge result does not match its retained input skeletons.", + ); + } + segmentBindings.push( + [step.semantic.sourceSegment, resultId], + [step.semantic.downstreamSegment, resultId], + ); + } else { + const mergeSemantic = step.semantic; + const requestedOrientation = mergeSemantic.inverseOrientation; + const [firstId, secondId] = this.requireMergeInputSegmentIds( + committed.editRequest, + ); + if ( + !( + (resultId === firstId && deletedId === secondId) || + (resultId === secondId && deletedId === firstId) + ) + ) { + throw new Error( + "CATMAID merge result does not match either retained input skeleton.", + ); + } + const actualOrientation = result.directionAdjusted + ? requestedOrientation === "second-from-first" + ? ("first-from-second" as const) + : ("second-from-first" as const) + : requestedOrientation; + const expectedResultId = + actualOrientation === "second-from-first" ? firstId : secondId; + const expectedDeletedId = + actualOrientation === "second-from-first" ? secondId : firstId; + if ( + resultId !== expectedResultId || + deletedId !== expectedDeletedId + ) { + throw new Error( + "CATMAID merge result conflicts with its reported orientation.", + ); + } + // Keep both semantic identities bound to the source-wide survivor. + // Later previewed edits and history recipes may refer to either; + // Undo overlays the restored loser with its fresh split id. + segmentBindings.push( + [step.semantic.firstSegment, resultId], + [step.semantic.secondSegment, resultId], + [step.semantic.mergedSegment, resultId], + ); + if (actualOrientation !== requestedOrientation) { + finalizedPreviewDelta = { + kind: "merge", + firstSegment: + actualOrientation === "second-from-first" + ? step.semantic.firstSegment + : step.semantic.secondSegment, + secondSegment: + actualOrientation === "second-from-first" + ? step.semantic.secondSegment + : step.semantic.firstSegment, + resultSegment: step.semantic.mergedSegment, + firstNode: + actualOrientation === "second-from-first" + ? step.semantic.firstNode + : step.semantic.secondNode, + secondNode: + actualOrientation === "second-from-first" + ? step.semantic.secondNode + : step.semantic.firstNode, + }; + } + } + retiredSegmentIds.add(deletedId); + break; + } + } + } + + return Object.freeze({ + bindings: Object.freeze({ + nodes: Object.freeze(nodeBindings), + segments: Object.freeze(segmentBindings), + }), + retiredResources: Object.freeze([...retired.values()]), + ...(retiredSegmentIds.size === 0 + ? {} + : { retiredSegmentIds: Object.freeze([...retiredSegmentIds]) }), + ...(finalizedPreviewDelta === undefined ? {} : { finalizedPreviewDelta }), + }); + } + + private requireMergeInputSegmentIds( + editRequest: CatmaidEditRequest, + ): readonly [bigint, bigint] { + if (editRequest.kind !== "merge") { + throw new Error("CATMAID merge reconciliation lost its edit request."); + } + return editRequest.inputSegmentIds; + } +} + +/** Resolve a queued user intent against the complete, ordered input bundle. */ +function resolveCatmaidPreparedCommand( + command: CatmaidSpatialSkeletonCommandDescriptor, + queueInput: SpatialSkeletonQueueInput, + identity: SpatialSkeletonIdentityService, +): CatmaidSpatialSkeletonCommandDescriptor { + const resolveNode = ( + node: T, + ): T => { + const nodeId = + identity.resolveNode(identity.getOrCreateNodeHandle(node.nodeId)) ?? + node.nodeId; + const current = queueInput.segments + .map(({ snapshot }) => snapshot.getNode(nodeId)) + .find((node) => node !== undefined); + const segmentId = + current?.segmentId ?? + identity.resolveSegment( + identity.getOrCreateSegmentHandle(node.segmentId), + ) ?? + node.segmentId; + return Object.freeze({ ...node, nodeId, segmentId }); + }; + const { payload } = command; + let resolved: CatmaidSpatialSkeletonCommandPayload; + switch (payload.kind) { + case "merge": + resolved = { + ...payload, + options: { + ...payload.options, + firstNode: resolveNode(payload.options.firstNode), + secondNode: resolveNode(payload.options.secondNode), + }, + }; + break; + case "add-node": { + const { options } = payload; + if (options.parentNodeId === undefined) return command; + const parent = resolveNode({ + nodeId: options.parentNodeId, + segmentId: options.skeletonId, + }); + resolved = { + ...payload, + options: { + ...options, + parentNodeId: parent.nodeId, + skeletonId: parent.segmentId, + }, + }; + break; + } + case "delete-node": + resolved = { ...payload, node: resolveNode(payload.node) }; + break; + case "reroot": + resolved = { ...payload, node: resolveNode(payload.node) }; + break; + case "split": + resolved = { ...payload, node: resolveNode(payload.node) }; + break; + case "move-node": + resolved = { + ...payload, + options: { + ...payload.options, + node: resolveNode(payload.options.node), + }, + }; + break; + case "description": + resolved = { + ...payload, + options: { + ...payload.options, + node: resolveNode(payload.options.node), + }, + }; + break; + case "true-end": + resolved = { + ...payload, + options: { + ...payload.options, + node: resolveNode(payload.options.node), + }, + }; + break; + case "radius": + resolved = { + ...payload, + options: { + ...payload.options, + node: resolveNode(payload.options.node), + }, + }; + break; + case "confidence": + resolved = { + ...payload, + options: { + ...payload.options, + node: resolveNode(payload.options.node), + }, + }; + break; + } + return Object.freeze({ ...command, payload: Object.freeze(resolved) }); +} + +// Match CATMAID creation defaults so later history captures complete values. +const CATMAID_CREATED_NODE_ATTRIBUTES = Object.freeze({ + radius: 0, + confidence: 0, + isTrueEnd: false, +}); + +const CATMAID_OPTIMISTIC_STALLED_WARNING = Object.freeze({ + delayMs: 30_000, + message: + "CATMAID has not confirmed the optimistic skeleton edit yet. The server edit request lane is stalled, but you may continue previewing independent edits while the request remains in order.", +}); + +const CATMAID_OPTIMISTIC_OPERATION_NOUNS = Object.freeze({ + "add-node": "node creation", + "move-node": "node movement", + "delete-node": "node deletion", + reroot: "skeleton rerooting", + split: "skeleton splitting", + merge: "skeleton merging", + description: "node description editing", + "true-end": "node true-end editing", + radius: "node radius editing", + confidence: "node confidence editing", +}) satisfies Readonly< + Record +>; + +function getCatmaidAuthorityLabels( + kind: CatmaidSpatialSkeletonCommandPayload["kind"], +): SpatialSkeletonAuthorityLabels { + return Object.freeze({ + authorityLabel: "CATMAID", + operationNoun: CATMAID_OPTIMISTIC_OPERATION_NOUNS[kind], + stalledWarning: CATMAID_OPTIMISTIC_STALLED_WARNING, + }); +} + +function copyVector(value: ArrayLike): SkeletonVector { + return Object.freeze(Array.from(value)); +} + +function uniqueResources( + handles: readonly SpatialSkeletonStableResourceHandle[], +) { + const resources = new Map(); + for (const handle of handles) { + resources.set(getSpatialSkeletonStableResourceKey(handle), { + handle, + access: "write", + }); + } + return Object.freeze([...resources.values()]); +} + +function freezeNode(node: SkeletonNode) { + return Object.freeze({ + nodeId: node.nodeId, + segmentId: node.segmentId, + position: toCatmaidPositionInModelSpace(node.position, "node position"), + parentNodeId: node.parentNodeId, + attributes: node.attributes, + description: node.description, + }); +} + +function makeRetainedNode( + capturedNodeId: bigint, + handle: SpatialSkeletonStableNodeHandle, +): CatmaidRetainedNode { + return Object.freeze({ + capturedNodeId, + handle, + get kind() { + return handle.kind; + }, + get stableId() { + return handle.stableId; + }, + }); +} + +function getDirection( + intent: "execute" | "undo" | "redo", +): "forward" | "inverse" { + return intent === "undo" ? "inverse" : "forward"; +} + +// CATMAID IDs are Postgres int8, so an ID from 2^63 is never a real one. +const CATMAID_FIRST_PROVISIONAL_ID = 2n ** 63n; + +/** Deterministic, state-free policy; the generic identity service owns use. */ +export const CATMAID_PROVISIONAL_NUMERIC_ID_POLICY: SpatialSkeletonProvisionalNumericIdPolicy = + Object.freeze({ + allocateNodeId(intentId: number) { + return CATMAID_FIRST_PROVISIONAL_ID + BigInt(intentId); + }, + allocateSegmentId(intentId: number) { + return CATMAID_FIRST_PROVISIONAL_ID + BigInt(intentId); + }, + }); + +export class CatmaidEditPlanner + extends CatmaidEditPlanCommitBase + implements + SpatialSkeletonEditPlanner< + CatmaidSpatialSkeletonCommandDescriptor, + CatmaidEditPlan, + SpatialSkeletonPreviewIntentDelta, + CatmaidEditRequest, + CatmaidEditRequestResult, + SpatialSkeletonAuthoritativeReconciliation, + SpatialSkeletonEditInverseDelta + > +{ + constructor( + identity: SpatialSkeletonIdentityService, + private readonly provisionalIds: SpatialSkeletonProvisionalNumericIdService, + ) { + super(identity); + } + + describeIntent(input: CatmaidSpatialSkeletonCommandDescriptor) { + const { payload } = input; + return Object.freeze({ + kind: this.getQueueKind(payload.kind), + commandLabel: input.label, + authorityLabels: getCatmaidAuthorityLabels(payload.kind), + ...(payload.kind === "merge" + ? { + pendingEdit: Object.freeze({ + kind: "merge" as const, + segmentIds: Object.freeze([ + payload.options.firstNode.segmentId, + payload.options.secondNode.segmentId, + ]), + endpointNodeIds: Object.freeze([ + payload.options.firstNode.nodeId, + payload.options.secondNode.nodeId, + ]), + lastKnownPositions: Object.freeze( + [payload.options.firstNode, payload.options.secondNode].flatMap( + (node) => + node.position === undefined + ? [] + : [ + Object.freeze({ + nodeId: node.nodeId, + position: node.position, + }), + ], + ), + ), + }), + } + : {}), + }); + } + + planIntent( + input: CatmaidSpatialSkeletonCommandDescriptor, + context: SpatialSkeletonIntentCreationContext< + CatmaidEditPlan, + SpatialSkeletonPreviewIntentDelta, + SpatialSkeletonEditInverseDelta + >, + ): SpatialSkeletonIntentPlan< + CatmaidEditPlan, + SpatialSkeletonPreviewIntentDelta + > { + const direction = getDirection(context.intent); + let semantic: CatmaidCapturedEdit; + let delta: SpatialSkeletonEditDelta; + if (context.intent === "execute") { + semantic = this.createSemanticRecipe( + input, + context.intentId, + context.queueInput, + ); + delta = this.makeForwardDelta(semantic); + } else { + const prior = context.recipe; + semantic = this.prepareHistorySemantic( + prior.plan.semantic, + prior.preview.delta, + prior.inversePreview, + ); + if (context.intent === "undo") { + if (prior.inversePreview === undefined) { + throw new Error("CATMAID Undo is missing its canonical inverse."); + } + delta = prior.inversePreview; + } else { + delta = this.makeForwardDelta(semantic); + } + } + + const preview = this.makePreview( + semantic, + delta, + context.intent, + context.intentId, + context.intent === "execute", + ); + const plan = Object.freeze({ + kind: semantic.kind, + direction, + semantic, + }) as CatmaidEditPlan; + return { + kind: this.getQueueKind(semantic.kind), + commandLabel: input.label, + authorityLabels: getCatmaidAuthorityLabels(semantic.kind), + stableResources: this.getStableResources(semantic), + pendingEdit: this.makePendingEditDescriptor(semantic), + preview, + plan, + }; + } + + private createSemanticRecipe( + command: CatmaidSpatialSkeletonCommandDescriptor, + intentId: number, + queueInput: SpatialSkeletonQueueInput, + ): CatmaidCapturedEdit { + command = resolveCatmaidPreparedCommand(command, queueInput, this.identity); + switch (command.payload.kind) { + case "add-node": + return this.createAddSemantic(command, intentId, queueInput); + case "move-node": + return this.createMoveSemantic(command, queueInput); + case "delete-node": + return this.createDeleteSemantic(command, queueInput); + case "reroot": + return this.createRerootSemantic(command, queueInput); + case "description": + case "true-end": + case "radius": + case "confidence": + return this.createAttributeSemantic(command, queueInput); + case "split": + return this.createSplitSemantic(command, intentId, queueInput); + case "merge": + return this.createMergeSemantic(command, intentId, queueInput); + } + } + + /** History follows the engine's finalized canonical preview artifacts. */ + private prepareHistorySemantic( + semantic: CatmaidCapturedEdit, + forwardPreview: SpatialSkeletonEditDelta, + inversePreview: SpatialSkeletonEditInverseDelta | undefined, + ): CatmaidCapturedEdit { + if (semantic.kind === "reroot" && inversePreview !== undefined) { + if (inversePreview.kind !== "restore-topology") { + throw new Error( + "CATMAID reroot history has an invalid canonical inverse.", + ); + } + const root = inversePreview.patches.find(({ parent }) => parent === null); + if (root === undefined) { + throw new Error("CATMAID canonical reroot inverse lost its root."); + } + return Object.freeze({ + ...semantic, + originalRoot: this.retainHistoryNode(root.node), + originalRootConfidence: root.confidence, + }); + } + if (semantic.kind === "description") { + if ( + forwardPreview.kind !== "node-attributes" || + forwardPreview.segment.stableId !== semantic.segment.stableId || + forwardPreview.node.stableId !== semantic.node.stableId || + !("description" in forwardPreview.changes) + ) { + throw new Error( + "CATMAID description history has an invalid canonical preview.", + ); + } + const after = forwardPreview.changes.description; + return after === semantic.after + ? semantic + : Object.freeze({ ...semantic, after }); + } + if (semantic.kind === "confidence" && inversePreview !== undefined) { + if ( + inversePreview.kind !== "node-attributes" || + inversePreview.node.stableId !== semantic.node.stableId || + !("confidence" in inversePreview.changes) + ) { + throw new Error( + "CATMAID confidence history has an invalid canonical inverse.", + ); + } + return Object.freeze({ + ...semantic, + before: inversePreview.changes.confidence ?? 0, + }); + } + if (semantic.kind === "split" && inversePreview !== undefined) { + if (inversePreview.kind !== "join-split") { + throw new Error( + "CATMAID split history has an invalid canonical inverse.", + ); + } + return Object.freeze({ + ...semantic, + formerParent: this.retainHistoryNode(inversePreview.formerParent), + }); + } + if (semantic.kind === "delete-node" && inversePreview !== undefined) { + if (inversePreview.kind !== "restore-delete") { + throw new Error( + "CATMAID delete history has an invalid canonical inverse.", + ); + } + const { snapshot, children } = inversePreview; + const parent = + snapshot.parent === null + ? undefined + : this.retainHistoryNode(snapshot.parent); + return Object.freeze({ + ...semantic, + parent, + children: Object.freeze( + children.map((node) => this.retainHistoryNode(node)), + ), + deletedSnapshot: freezeNode({ + ...semantic.deletedSnapshot, + ...getSkeletonNodeChanges( + semantic.deletedSnapshot, + snapshot.attributes, + ), + position: snapshot.position, + parentNodeId: parent?.capturedNodeId, + }), + wasSoleRoot: parent === undefined && children.length === 0, + }); + } + if (semantic.kind !== "merge") return semantic; + if (inversePreview === undefined) return semantic; + if (inversePreview.kind !== "unmerge") { + throw new Error( + "CATMAID merge history has an invalid canonical inverse.", + ); + } + const inverseOrientation = + inversePreview.firstNode.stableId === semantic.firstNode.stableId && + inversePreview.secondNode.stableId === semantic.secondNode.stableId + ? ("second-from-first" as const) + : inversePreview.firstNode.stableId === semantic.secondNode.stableId && + inversePreview.secondNode.stableId === semantic.firstNode.stableId + ? ("first-from-second" as const) + : undefined; + if (inverseOrientation === undefined) + throw new Error("CATMAID canonical merge inverse lost its endpoints."); + const originalRoot = inversePreview.formerSecondTopology.find( + ({ parent }) => parent === null, + ); + if (originalRoot === undefined) + throw new Error("CATMAID canonical merge inverse lost its root."); + return Object.freeze({ + ...semantic, + inverseOrientation, + originalRoot: this.retainHistoryNode(originalRoot.node), + originalRootConfidence: originalRoot.confidence, + }); + } + + private retainHistoryNode(handle: SpatialSkeletonStableNodeHandle) { + const nodeId = this.identity.resolveNode(handle); + if (nodeId === undefined) { + throw new Error( + "CATMAID canonical history node has no numeric identity.", + ); + } + return makeRetainedNode(nodeId, handle); + } + + private makeForwardDelta( + semantic: CatmaidCapturedEdit, + ): SpatialSkeletonEditDelta { + switch (semantic.kind) { + case "add-node": + if (semantic.children?.length) { + return Object.freeze({ + kind: "restore-delete", + segment: semantic.segment, + snapshot: Object.freeze({ + node: semantic.node, + parent: semantic.parent ?? null, + position: semantic.position, + attributes: semantic.attributes, + }), + children: semantic.children, + }); + } + return Object.freeze({ + kind: "add", + segment: semantic.segment, + node: semantic.node, + parent: semantic.parent, + position: semantic.position, + attributes: semantic.attributes, + }); + case "move-node": + return Object.freeze({ + kind: "move", + segment: semantic.segment, + node: semantic.node, + position: semantic.after, + }); + case "delete-node": + return Object.freeze({ + kind: "delete", + segment: semantic.segment, + node: semantic.node, + }); + case "description": + return Object.freeze({ + kind: "node-attributes", + segment: semantic.segment, + node: semantic.node, + changes: Object.freeze({ + description: semantic.after as string | undefined, + }), + }); + case "true-end": + return Object.freeze({ + kind: "node-attributes", + segment: semantic.segment, + node: semantic.node, + changes: Object.freeze({ + isTrueEnd: semantic.after as boolean | undefined, + }), + }); + case "radius": + return Object.freeze({ + kind: "node-attributes", + segment: semantic.segment, + node: semantic.node, + changes: Object.freeze({ + radius: semantic.after as number | undefined, + }), + }); + case "confidence": + return Object.freeze({ + kind: "node-attributes", + segment: semantic.segment, + node: semantic.node, + changes: Object.freeze({ + confidence: semantic.after as number | undefined, + }), + }); + case "reroot": + return Object.freeze({ + kind: "reroot", + segment: semantic.segment, + node: semantic.node, + }); + case "split": + return Object.freeze({ + kind: "split", + sourceSegment: semantic.sourceSegment, + downstreamSegment: semantic.downstreamSegment, + node: semantic.node, + }); + case "merge": + return semantic.inverseOrientation === "second-from-first" + ? Object.freeze({ + kind: "merge" as const, + firstSegment: semantic.firstSegment, + secondSegment: semantic.secondSegment, + resultSegment: semantic.mergedSegment, + firstNode: semantic.firstNode, + secondNode: semantic.secondNode, + }) + : Object.freeze({ + kind: "merge" as const, + firstSegment: semantic.secondSegment, + secondSegment: semantic.firstSegment, + resultSegment: semantic.mergedSegment, + firstNode: semantic.secondNode, + secondNode: semantic.firstNode, + }); + } + } + + private getStableResources( + semantic: CatmaidCapturedEdit, + ): readonly SpatialSkeletonIntentResource[] { + switch (semantic.kind) { + case "add-node": + case "delete-node": + case "move-node": + case "description": + case "true-end": + case "radius": + case "confidence": + case "reroot": + return uniqueResources([semantic.segment]); + case "split": + return uniqueResources([ + semantic.sourceSegment, + semantic.downstreamSegment, + ]); + case "merge": + return uniqueResources([ + semantic.firstSegment, + semantic.secondSegment, + semantic.mergedSegment, + ]); + } + } + + private makePendingEditDescriptor( + semantic: CatmaidCapturedEdit, + ): SpatialSkeletonPendingEditDescriptor | undefined { + switch (semantic.kind) { + case "delete-node": + return Object.freeze({ + kind: "delete", + stableNodeHandles: Object.freeze([semantic.node]), + stableSegmentHandles: Object.freeze([semantic.segment]), + segmentIds: Object.freeze( + semantic.capturedSegments.map(({ physicalId }) => physicalId), + ), + nodeId: semantic.node.capturedNodeId, + lastKnownPositions: Object.freeze([ + { + nodeId: semantic.deletedSnapshot.nodeId, + position: semantic.deletedSnapshot.position, + }, + ]), + }); + case "reroot": + return Object.freeze({ + kind: "reroot", + stableNodeHandles: Object.freeze([ + semantic.node, + semantic.originalRoot, + ]), + stableSegmentHandles: Object.freeze([semantic.segment]), + segmentIds: Object.freeze( + semantic.capturedSegments.map(({ physicalId }) => physicalId), + ), + nodeId: semantic.node.capturedNodeId, + rootNodeId: semantic.originalRoot.capturedNodeId, + }); + case "split": + return Object.freeze({ + kind: "split", + stableNodeHandles: Object.freeze([ + semantic.node, + semantic.formerParent, + ]), + stableSegmentHandles: Object.freeze([ + semantic.sourceSegment, + semantic.downstreamSegment, + ]), + segmentIds: Object.freeze( + semantic.capturedSegments.map(({ physicalId }) => physicalId), + ), + cutNodeId: semantic.node.capturedNodeId, + cutParentNodeId: semantic.formerParent.capturedNodeId, + }); + case "merge": + return Object.freeze({ + kind: "merge", + stableNodeHandles: Object.freeze([ + semantic.firstNode, + semantic.secondNode, + ]), + stableSegmentHandles: Object.freeze([ + semantic.firstSegment, + semantic.secondSegment, + semantic.mergedSegment, + ]), + segmentIds: Object.freeze( + semantic.capturedSegments.map(({ physicalId }) => physicalId), + ), + endpointNodeIds: Object.freeze([ + semantic.firstNode.capturedNodeId, + semantic.secondNode.capturedNodeId, + ]), + }); + default: + return undefined; + } + } + + private captureSegments( + queueInput: SpatialSkeletonQueueInput, + segmentIds: readonly bigint[], + eagerNodeIds: readonly bigint[], + ) { + const captured: CatmaidCapturedSegment[] = []; + for (const segmentId of new Set(segmentIds)) { + const entry = this.requireQueueInputSegment(queueInput, segmentId); + const segment = this.segmentHandle(segmentId); + captured.push( + Object.freeze({ + segment, + physicalId: segmentId, + snapshot: entry.snapshot, + cacheRevision: entry.cacheRevision, + }), + ); + } + const requestedNodeIds = [...new Set(eagerNodeIds)]; + for (const nodeId of requestedNodeIds) { + if ( + !captured.some(({ snapshot }) => snapshot.getNode(nodeId) !== undefined) + ) { + throw new Error(`CATMAID queue input is missing node ${nodeId}.`); + } + } + const handles = this.identity.getOrCreateNodeHandles(requestedNodeIds); + return { + capturedSegments: Object.freeze(captured), + retainedNodes: new Map( + requestedNodeIds.map( + (nodeId) => + [nodeId, makeRetainedNode(nodeId, handles.get(nodeId)!)] as const, + ), + ), + }; + } + + private getRetainedNode( + capture: { + readonly retainedNodes: ReadonlyMap; + }, + nodeId: bigint, + ) { + return capture.retainedNodes.get(nodeId)!; + } + + private requireQueueInputSegment( + queueInput: SpatialSkeletonQueueInput, + segmentId: bigint, + ) { + const entry = queueInput.segments.find( + (candidate) => candidate.segmentId === segmentId, + ); + if (entry === undefined) { + throw new Error( + `CATMAID edit requires admitted complete skeleton ${segmentId}.`, + ); + } + return entry; + } + + private getPathToRoot(snapshot: CompleteSkeleton, targetNodeId: bigint) { + const path: SkeletonNode[] = []; + const seen = new Set(); + let current = snapshot.getNode(targetNodeId); + if (current === undefined) { + throw new Error(`CATMAID queue input is missing node ${targetNodeId}.`); + } + while (current !== undefined) { + if (seen.has(current.nodeId)) { + throw new Error("CATMAID retained path to root is cyclic."); + } + seen.add(current.nodeId); + path.push(current); + if (current.parentNodeId === undefined) break; + const parent = snapshot.getNode(current.parentNodeId); + if (parent === undefined) { + throw new Error( + `CATMAID retained path is missing parent ${current.parentNodeId}.`, + ); + } + current = parent; + } + return Object.freeze(path); + } + + private requireCapturedNode( + capture: ReturnType, + nodeId: bigint, + ) { + for (const { snapshot } of capture.capturedSegments) { + const node = snapshot.getNode(nodeId); + if (node !== undefined) return freezeNode(node); + } + throw new Error(`CATMAID queue input is missing node ${nodeId}.`); + } + + private createAddSemantic( + command: CatmaidSpatialSkeletonCommandDescriptor, + intentId: number, + queueInput: SpatialSkeletonQueueInput, + ): CatmaidCreatedNodeSemantic { + if (command.payload.kind !== "add-node") + throw new Error("Invalid add recipe."); + const { options } = command.payload; + const capture = + options.parentNodeId === undefined + ? { + capturedSegments: Object.freeze([]), + retainedNodes: new Map(), + } + : this.captureSegments( + queueInput, + [options.skeletonId], + [options.parentNodeId, ...(options.childNodeIds ?? [])], + ); + const parent = + options.parentNodeId === undefined + ? undefined + : this.getRetainedNode(capture, options.parentNodeId); + const children = Object.freeze( + (options.childNodeIds ?? []).map((nodeId) => { + const child = this.requireCapturedNode(capture, nodeId); + if ( + child.parentNodeId !== options.parentNodeId || + child.segmentId !== options.skeletonId + ) { + throw new Error( + `Node ${nodeId} is not a child of node ${options.parentNodeId}.`, + ); + } + return this.getRetainedNode(capture, nodeId); + }), + ); + const node = spatialSkeletonStableNode(`intent:${intentId}:created-node`); + const createsSegment = parent === undefined; + const segment = createsSegment + ? spatialSkeletonStableSegment(`intent:${intentId}:created-segment`) + : this.segmentHandle(options.skeletonId); + const position = copyVector(options.positionInModelSpace); + return Object.freeze({ + kind: "add-node", + ...capture, + node, + segment, + parent, + position, + attributes: CATMAID_CREATED_NODE_ATTRIBUTES, + createsSegment, + children, + }); + } + + private createMoveSemantic( + command: CatmaidSpatialSkeletonCommandDescriptor, + queueInput: SpatialSkeletonQueueInput, + ): CatmaidMoveNodeSemantic { + if (command.payload.kind !== "move-node") + throw new Error("Invalid move recipe."); + const { options } = command.payload; + const capture = this.captureSegments( + queueInput, + [options.node.segmentId], + [options.node.nodeId], + ); + const nodeSnapshot = this.requireCapturedNode(capture, options.node.nodeId); + const node = this.getRetainedNode(capture, nodeSnapshot.nodeId)!; + const segment = this.segmentHandle(nodeSnapshot.segmentId); + const before = copyVector(nodeSnapshot.position); + const after = copyVector(options.nextPositionInModelSpace); + return Object.freeze({ + kind: "move-node", + ...capture, + node, + segment, + before, + after, + }); + } + + private createDeleteSemantic( + command: CatmaidSpatialSkeletonCommandDescriptor, + queueInput: SpatialSkeletonQueueInput, + ): CatmaidDeleteNodeSemantic { + if (command.payload.kind !== "delete-node") { + throw new Error("Invalid delete recipe."); + } + const { segmentId } = command.payload.node; + const entry = this.requireQueueInputSegment(queueInput, segmentId); + const rawDeleted = entry.snapshot.getNode(command.payload.node.nodeId); + if (rawDeleted === undefined) { + throw new Error( + `CATMAID queue input is missing node ${command.payload.node.nodeId}.`, + ); + } + const childIds: bigint[] = []; + entry.snapshot.forEachNode((candidate) => { + if (candidate.parentNodeId === rawDeleted.nodeId) { + childIds.push(candidate.nodeId); + } + }); + if (rawDeleted.parentNodeId === undefined && childIds.length !== 0) { + throw new Error( + "Deleting a root node with children is blocked. Reroot the skeleton manually before deleting it.", + ); + } + const eagerNodeIds = [ + rawDeleted.nodeId, + ...(rawDeleted.parentNodeId === undefined + ? [] + : [rawDeleted.parentNodeId]), + ...childIds, + ]; + const capture = this.captureSegments(queueInput, [segmentId], eagerNodeIds); + const deletedSnapshot = freezeNode(rawDeleted); + const children = childIds.map( + (nodeId) => this.getRetainedNode(capture, nodeId)!, + ); + const node = this.getRetainedNode(capture, deletedSnapshot.nodeId)!; + const parent = + deletedSnapshot.parentNodeId === undefined + ? undefined + : this.getRetainedNode(capture, deletedSnapshot.parentNodeId); + const segment = capture.capturedSegments[0].segment; + return Object.freeze({ + kind: "delete-node", + ...capture, + node, + segment, + parent, + children: Object.freeze(children), + deletedSnapshot, + wasSoleRoot: entry.snapshot.nodeCount === 1, + }); + } + + private createAttributeSemantic( + command: CatmaidSpatialSkeletonCommandDescriptor, + queueInput: SpatialSkeletonQueueInput, + ): CatmaidAttributeSemantic { + const { payload } = command; + if ( + payload.kind !== "description" && + payload.kind !== "true-end" && + payload.kind !== "radius" && + payload.kind !== "confidence" + ) { + throw new Error("Invalid CATMAID attribute recipe."); + } + const { options } = payload; + const capture = this.captureSegments( + queueInput, + [options.node.segmentId], + [options.node.nodeId], + ); + const nodeSnapshot = this.requireCapturedNode(capture, options.node.nodeId); + const node = this.getRetainedNode(capture, nodeSnapshot.nodeId)!; + const segment = capture.capturedSegments[0].segment; + let before: string | boolean | number | undefined; + let after: string | boolean | number | undefined; + switch (payload.kind) { + case "description": + before = nodeSnapshot.description; + after = payload.options.nextDescription; + break; + case "true-end": + before = isSkeletonNodeTrueEnd(nodeSnapshot); + after = payload.options.nextIsTrueEnd; + if (after) { + if (nodeSnapshot.parentNodeId === undefined) { + throw new Error("Cannot set the root node as a true end."); + } + let hasChild = false; + capture.capturedSegments[0].snapshot.forEachNode((candidate) => { + if (candidate.parentNodeId === nodeSnapshot.nodeId) hasChild = true; + }); + if (hasChild) { + throw new Error("Only leaf nodes can be marked as true ends."); + } + } + break; + case "radius": + before = getSkeletonNodeRadius(nodeSnapshot) ?? 0; + after = payload.options.nextRadius; + break; + case "confidence": + before = getSkeletonNodeConfidence(nodeSnapshot) ?? 0; + after = payload.options.nextConfidence; + break; + } + return Object.freeze({ + kind: payload.kind, + ...capture, + node, + segment, + nodeSnapshot, + before, + after, + }); + } + + private createRerootSemantic( + command: CatmaidSpatialSkeletonCommandDescriptor, + queueInput: SpatialSkeletonQueueInput, + ): CatmaidRerootSemantic { + if (command.payload.kind !== "reroot") + throw new Error("Invalid reroot recipe."); + const { segmentId } = command.payload.node; + const entry = this.requireQueueInputSegment(queueInput, segmentId); + const path = this.getPathToRoot( + entry.snapshot, + command.payload.node.nodeId, + ); + const capture = this.captureSegments( + queueInput, + [segmentId], + path.map(({ nodeId }) => nodeId), + ); + const target = path[0]; + const root = path.at(-1)!; + const node = this.getRetainedNode(capture, target.nodeId)!; + const originalRoot = this.getRetainedNode(capture, root.nodeId)!; + const segment = capture.capturedSegments[0].segment; + return Object.freeze({ + kind: "reroot", + ...capture, + node, + originalRoot, + originalRootConfidence: getSkeletonNodeConfidence(root), + segment, + }); + } + + private createSplitSemantic( + command: CatmaidSpatialSkeletonCommandDescriptor, + intentId: number, + queueInput: SpatialSkeletonQueueInput, + ): CatmaidSplitSemantic { + if (command.payload.kind !== "split") + throw new Error("Invalid split recipe."); + const { segmentId } = command.payload.node; + const entry = this.requireQueueInputSegment(queueInput, segmentId); + const target = entry.snapshot.getNode(command.payload.node.nodeId); + if (target === undefined) { + throw new Error( + `CATMAID queue input is missing node ${command.payload.node.nodeId}.`, + ); + } + if (target.parentNodeId === undefined) + throw new Error("Cannot split at the root node."); + const capture = this.captureSegments( + queueInput, + [segmentId], + [target.nodeId, target.parentNodeId], + ); + const sourceSegment = capture.capturedSegments[0].segment; + const downstreamSegment = spatialSkeletonStableSegment( + `intent:${intentId}:split-output`, + ); + const node = this.getRetainedNode(capture, target.nodeId)!; + const formerParent = this.getRetainedNode(capture, target.parentNodeId)!; + return Object.freeze({ + kind: "split", + ...capture, + sourceSegment, + downstreamSegment, + node, + formerParent, + }); + } + + private createMergeSemantic( + command: CatmaidSpatialSkeletonCommandDescriptor, + intentId: number, + queueInput: SpatialSkeletonQueueInput, + ): CatmaidMergeSemantic { + if (command.payload.kind !== "merge") + throw new Error("Invalid merge recipe."); + const { firstNode, secondNode } = command.payload.options; + if (firstNode.segmentId === secondNode.segmentId) { + throw new Error("Cannot merge nodes from the same skeleton."); + } + const firstEntry = this.requireQueueInputSegment( + queueInput, + firstNode.segmentId, + ); + const secondEntry = this.requireQueueInputSegment( + queueInput, + secondNode.segmentId, + ); + const firstPath = this.getPathToRoot(firstEntry.snapshot, firstNode.nodeId); + const secondPath = this.getPathToRoot( + secondEntry.snapshot, + secondNode.nodeId, + ); + const capture = this.captureSegments( + queueInput, + [firstNode.segmentId, secondNode.segmentId], + [ + ...firstPath.map(({ nodeId }) => nodeId), + ...secondPath.map(({ nodeId }) => nodeId), + ], + ); + const first = this.requireCapturedNode(capture, firstNode.nodeId); + const second = this.requireCapturedNode(capture, secondNode.nodeId); + const secondRoot = secondPath.at(-1)!; + const firstSegment = this.segmentHandle(first.segmentId); + const secondSegment = this.segmentHandle(second.segmentId); + const mergedSegment = spatialSkeletonStableSegment( + `intent:${intentId}:merge-output`, + ); + const firstHandle = this.getRetainedNode(capture, first.nodeId)!; + const secondHandle = this.getRetainedNode(capture, second.nodeId)!; + return Object.freeze({ + kind: "merge", + ...capture, + firstSegment, + secondSegment, + mergedSegment, + firstNode: firstHandle, + secondNode: secondHandle, + originalRoot: this.getRetainedNode(capture, secondRoot.nodeId)!, + originalRootConfidence: getSkeletonNodeConfidence(secondRoot), + inverseOrientation: "second-from-first", + }); + } + + private getCapturedNodeForHint( + semantic: CatmaidCapturedEdit, + retained: CatmaidRetainedNode, + ) { + for (const { snapshot } of semantic.capturedSegments) { + const node = snapshot.getNode(retained.capturedNodeId); + if (node !== undefined) return node; + } + return undefined; + } + + /** + * CATMAID describes user intent with logical handles; the generic runtime + * resolves and applies these wishes after its model adoption. Nothing here + * owns selection, visibility, or remapping state. + */ + private makeUiHints( + semantic: CatmaidCapturedEdit, + direction: "forward" | "inverse", + intent: "execute" | "undo" | "redo", + rollback?: { readonly provisionalSegmentId?: bigint }, + ): SpatialSkeletonPreviewUiHints { + const segmentVisibility: Array< + NonNullable[number] + > = []; + const segmentVisibilityStateRemaps: Array< + NonNullable< + SpatialSkeletonPreviewUiHints["segmentVisibilityStateRemaps"] + >[number] + > = []; + const retainSegments: SpatialSkeletonStableSegmentHandle[] = []; + let selectedNode: SpatialSkeletonPreviewUiHints["selectedNode"]; + const select = ( + node: SpatialSkeletonStableNodeHandle, + segment: SpatialSkeletonStableSegmentHandle, + position?: ArrayLike, + moveView = false, + ) => { + selectedNode = Object.freeze({ + kind: "select" as const, + node, + segment, + ...(position === undefined + ? {} + : { position: Object.freeze(Array.from(position, Number)) }), + pin: "preserve" as const, + moveView: moveView && rollback === undefined, + }); + }; + const show = ( + segment: SpatialSkeletonStableSegmentHandle, + selection?: "preserve" | "pin" | "unpin", + restoreVisibilityState = false, + ) => { + segmentVisibility.push( + Object.freeze({ + segment, + visible: true, + ...(selection === undefined ? {} : { select: selection }), + ...(restoreVisibilityState + ? { restoreVisibilityState: true as const } + : {}), + }), + ); + }; + const hide = (segment: SpatialSkeletonStableSegmentHandle | bigint) => { + segmentVisibility.push( + Object.freeze({ segment, visible: false, deselect: true }), + ); + }; + + if (rollback?.provisionalSegmentId !== undefined) { + hide(rollback.provisionalSegmentId); + } + + switch (semantic.kind) { + case "add-node": + if (direction === "forward") { + show(semantic.segment, intent === "execute" ? "pin" : "preserve"); + select( + semantic.node, + semantic.segment, + semantic.position, + intent === "execute", + ); + retainSegments.push(semantic.segment); + } else { + if (semantic.createsSegment) hide(semantic.segment); + if (semantic.parent === undefined) { + selectedNode = Object.freeze({ kind: "clear" }); + } else { + const parent = this.getCapturedNodeForHint( + semantic, + semantic.parent, + ); + select(semantic.parent, semantic.segment, parent?.position, false); + retainSegments.push(semantic.segment); + } + } + break; + case "delete-node": + if (direction === "forward") { + if (semantic.wasSoleRoot) hide(semantic.segment); + if (semantic.parent === undefined) { + selectedNode = Object.freeze({ kind: "clear" }); + } else { + const parent = this.getCapturedNodeForHint( + semantic, + semantic.parent, + ); + select( + semantic.parent, + semantic.segment, + parent?.position, + intent === "execute", + ); + retainSegments.push(semantic.segment); + } + } else { + show(semantic.segment, "preserve"); + select( + semantic.node, + semantic.segment, + semantic.deletedSnapshot.position, + ); + retainSegments.push(semantic.segment); + } + break; + case "move-node": + selectedNode = Object.freeze({ + kind: "refresh-if-selected", + node: semantic.node, + segment: semantic.segment, + position: direction === "forward" ? semantic.after : semantic.before, + }); + retainSegments.push(semantic.segment); + break; + case "description": + case "true-end": + case "radius": + case "confidence": + retainSegments.push(semantic.segment); + break; + case "reroot": { + const target = + direction === "forward" ? semantic.node : semantic.originalRoot; + const snapshot = this.getCapturedNodeForHint(semantic, target); + show(semantic.segment); + select(target, semantic.segment, snapshot?.position); + retainSegments.push(semantic.segment); + break; + } + case "split": + if (direction === "forward") { + show(semantic.sourceSegment); + show(semantic.downstreamSegment, "pin"); + select(semantic.node, semantic.downstreamSegment); + retainSegments.push( + semantic.sourceSegment, + semantic.downstreamSegment, + ); + } else { + segmentVisibilityStateRemaps.push( + Object.freeze({ + from: semantic.downstreamSegment, + to: semantic.sourceSegment, + }), + ); + show(semantic.sourceSegment); + hide(semantic.downstreamSegment); + select(semantic.node, semantic.sourceSegment); + retainSegments.push(semantic.sourceSegment); + } + break; + case "merge": { + const forwardFirstSegment = + semantic.inverseOrientation === "second-from-first" + ? semantic.firstSegment + : semantic.secondSegment; + const forwardSecondSegment = + semantic.inverseOrientation === "second-from-first" + ? semantic.secondSegment + : semantic.firstSegment; + const forwardSecondNode = + semantic.inverseOrientation === "second-from-first" + ? semantic.secondNode + : semantic.firstNode; + const restoreVisibilityState = rollback !== undefined; + if (direction === "forward") { + show(semantic.mergedSegment, "preserve", restoreVisibilityState); + if (rollback === undefined) { + segmentVisibilityStateRemaps.push( + Object.freeze({ + from: semantic.firstSegment, + to: semantic.mergedSegment, + }), + Object.freeze({ + from: semantic.secondSegment, + to: semantic.mergedSegment, + }), + ); + hide(forwardSecondSegment); + } + select(forwardSecondNode, semantic.mergedSegment); + retainSegments.push(semantic.mergedSegment); + } else { + show(forwardFirstSegment, undefined, restoreVisibilityState); + show(forwardSecondSegment, undefined, restoreVisibilityState); + select(forwardSecondNode, forwardSecondSegment); + retainSegments.push(forwardFirstSegment, forwardSecondSegment); + } + break; + } + } + + return Object.freeze({ + segmentVisibilityStateRemaps: Object.freeze(segmentVisibilityStateRemaps), + segmentVisibility: Object.freeze(segmentVisibility), + ...(selectedNode === undefined ? {} : { selectedNode }), + retainSegments: Object.freeze(retainSegments), + }); + } + + private makePreview( + semantic: CatmaidCapturedEdit, + delta: SpatialSkeletonEditDelta, + intent: "execute" | "undo" | "redo", + intentId: number, + includeInspectionSeed: boolean, + ): SpatialSkeletonPreviewIntentDelta { + const direction = getDirection(intent); + const seed = includeInspectionSeed + ? this.captureRetainedInspectionSeed(semantic) + : undefined; + const nodeBindings: Array< + readonly [SpatialSkeletonStableNodeHandle, bigint] + > = []; + const segmentBindings: Array< + readonly [SpatialSkeletonStableSegmentHandle, bigint] + > = []; + let provisionalMergeSegmentId: bigint | undefined; + if (semantic.kind === "add-node" && direction === "forward") { + nodeBindings.push([ + semantic.node, + this.provisionalIds.allocateNodeId(intentId), + ]); + if (semantic.createsSegment) { + segmentBindings.push([ + semantic.segment, + this.provisionalIds.allocateSegmentId(intentId), + ]); + } + } else if (semantic.kind === "delete-node" && direction === "inverse") { + nodeBindings.push([ + semantic.node, + this.provisionalIds.allocateNodeId(intentId), + ]); + if (semantic.wasSoleRoot) { + segmentBindings.push([ + semantic.segment, + this.provisionalIds.allocateSegmentId(intentId), + ]); + } + } else if (semantic.kind === "split" && direction === "forward") { + segmentBindings.push([ + semantic.downstreamSegment, + this.provisionalIds.allocateSegmentId(intentId), + ]); + } else if (semantic.kind === "merge") { + const previewSegment = + delta.kind === "unmerge" ? delta.secondSegment : semantic.mergedSegment; + // The handle may resolve to a saved skeleton once this attempt rolls back. + provisionalMergeSegmentId = + this.provisionalIds.allocateSegmentId(intentId); + segmentBindings.push([previewSegment, provisionalMergeSegmentId]); + } + return Object.freeze({ + delta, + ...(seed === undefined ? {} : { inspectionSeed: seed }), + ...(nodeBindings.length === 0 && segmentBindings.length === 0 + ? {} + : { + provisionalBindings: Object.freeze({ + nodes: Object.freeze(nodeBindings), + segments: Object.freeze(segmentBindings), + }), + }), + uiHints: this.makeUiHints(semantic, direction, intent), + rollbackUiHints: this.makeUiHints( + semantic, + direction === "forward" ? "inverse" : "forward", + intent, + { provisionalSegmentId: provisionalMergeSegmentId }, + ), + pendingEditIntentId: intentId, + }); + } + + private captureRetainedInspectionSeed( + semantic: CatmaidCapturedEdit, + ): SpatialSkeletonPreviewInspectionSeed { + const segments: Array<{ + readonly segment: SpatialSkeletonStableSegmentHandle; + readonly snapshot: CompleteSkeleton; + }> = []; + const nodeBindings: Array< + readonly [SpatialSkeletonStableNodeHandle, bigint] + > = []; + const segmentBindings: Array< + readonly [SpatialSkeletonStableSegmentHandle, bigint] + > = []; + const expectedCacheRevisions = new Map(); + const seenNodes = new Set(); + const seenSegments = new Set(); + for (const captured of semantic.capturedSegments) { + const resourceHandle = captured.segment; + const target = this.identity.resolveSegmentTarget(resourceHandle); + const segmentId = captured.physicalId; + if (!seenSegments.has(resourceHandle.stableId)) { + segments.push({ segment: resourceHandle, snapshot: captured.snapshot }); + seenSegments.add(resourceHandle.stableId); + } + expectedCacheRevisions.set(segmentId, captured.cacheRevision); + if (target.state !== "provisional") { + segmentBindings.push([resourceHandle, segmentId]); + } + } + for (const { + capturedNodeId: nodeId, + handle, + } of semantic.retainedNodes.values()) { + if (seenNodes.has(handle.stableId)) continue; + const nodeTarget = this.identity.resolveNodeTarget(handle); + if (nodeTarget.state !== "provisional") { + nodeBindings.push([handle, nodeId]); + } + seenNodes.add(handle.stableId); + } + + return Object.freeze({ + segments: Object.freeze(segments), + authoritativeBindings: Object.freeze({ + nodes: Object.freeze(nodeBindings), + segments: Object.freeze(segmentBindings), + }), + expectedCacheRevisions, + }); + } + + private getQueueKind(kind: CatmaidCapturedEdit["kind"]) { + switch (kind) { + case "add-node": + return "addNode"; + case "move-node": + return "moveNode"; + case "delete-node": + return "deleteNode"; + case "reroot": + return "rerootSkeleton"; + case "description": + return "editDescription"; + case "true-end": + return "editTrueEnd"; + case "radius": + return "editRadius"; + case "confidence": + return "editConfidence"; + case "split": + return "splitSkeleton"; + case "merge": + return "mergeSkeletons"; + } + } +} diff --git a/src/datasource/catmaid/spatial_skeleton_edit/edit_requests.spec.ts b/src/datasource/catmaid/spatial_skeleton_edit/edit_requests.spec.ts new file mode 100644 index 0000000000..20f95e866c --- /dev/null +++ b/src/datasource/catmaid/spatial_skeleton_edit/edit_requests.spec.ts @@ -0,0 +1,151 @@ +/** + * @license + * Copyright 2026 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { describe, expect, it, vi } from "vitest"; + +import type { CatmaidSpatialSkeletonEditOperations } from "#src/datasource/catmaid/spatial_skeleton_edit/edit_operations.js"; +import { CatmaidEditRequests } from "#src/datasource/catmaid/spatial_skeleton_edit/edit_requests.js"; +import type { SpatialSkeletonEditRequestContext } from "#src/skeleton/edit_queue/api.js"; +import { commitSpatialSkeletonEditRequest } from "#src/skeleton/edit_queue/api.js"; +import { SpatialSkeletonEditConflictError } from "#src/skeleton/edit_queue/edit_errors.js"; + +function makeOperations( + overrides: Partial = {}, +): CatmaidSpatialSkeletonEditOperations { + return { + editRequestScope: {}, + commitAddNode: vi.fn(async () => ({ nodeId: 101n, segmentId: 10n })), + commitInsertNode: vi.fn(async () => ({ nodeId: 102n, segmentId: 10n })), + commitMoveNode: vi.fn(async () => undefined), + commitDeleteNode: vi.fn(async () => undefined), + commitReroot: vi.fn(async () => undefined), + commitDescription: vi.fn(async () => ({})), + commitTrueEnd: vi.fn(async () => undefined), + commitRadius: vi.fn(async () => undefined), + commitConfidence: vi.fn(async () => undefined), + commitMerge: vi.fn(async () => ({ + resultSegmentId: 10n, + deletedSegmentId: 20n, + directionAdjusted: false, + })), + commitSplit: vi.fn(async () => ({ + existingSegmentId: 10n, + newSegmentId: 20n, + })), + ...overrides, + }; +} + +const context: SpatialSkeletonEditRequestContext = { + intent: "execute", + operationId: 7, +}; + +describe("CatmaidEditRequests", () => { + it("sends a move to CATMAID with the node and position the edit asked for", async () => { + const result = undefined; + const commitMoveNode = vi.fn(async () => result); + const adapter = new CatmaidEditRequests(makeOperations({ commitMoveNode })); + + await expect( + commitSpatialSkeletonEditRequest( + adapter, + { + kind: "move-node", + request: { + nodeId: 4n, + position: new Float32Array([8, 9, 10]), + }, + }, + context, + ), + ).resolves.toEqual({ status: "committed", result }); + expect(commitMoveNode).toHaveBeenCalledWith({ + nodeId: 4n, + position: new Float32Array([8, 9, 10]), + }); + }); + + it("a sent edit gets no cancellation signal, so it cannot be cancelled", async () => { + const controller = new AbortController(); + const commitAddNode = vi.fn(async () => ({ nodeId: 1n, segmentId: 2n })); + const adapter = new CatmaidEditRequests(makeOperations({ commitAddNode })); + + await commitSpatialSkeletonEditRequest( + adapter, + { + kind: "add-node", + request: { + position: new Float32Array([1, 2, 3]), + }, + }, + { ...context, signal: controller.signal }, + ); + expect(commitAddNode).toHaveBeenCalledWith({ + position: new Float32Array([1, 2, 3]), + }); + }); + + it("reports a CATMAID conflict as rejected and a lost connection as possibly saved", async () => { + const conflict = new SpatialSkeletonEditConflictError("stale"); + const uncertain = new Error("connection disappeared"); + const rejectConflict = new CatmaidEditRequests( + makeOperations({ + commitMoveNode: vi.fn(async () => Promise.reject(conflict)), + }), + ); + const rejectUncertain = new CatmaidEditRequests( + makeOperations({ + commitMoveNode: vi.fn(async () => Promise.reject(uncertain)), + }), + ); + const editRequest = { + kind: "move-node" as const, + request: { + nodeId: 4n, + position: new Float32Array([8, 9, 10]), + }, + }; + + await expect( + commitSpatialSkeletonEditRequest(rejectConflict, editRequest, context), + ).resolves.toEqual({ status: "rejected", error: conflict }); + await expect( + commitSpatialSkeletonEditRequest(rejectUncertain, editRequest, context), + ).resolves.toEqual({ status: "indeterminate", error: uncertain }); + }); + + it("reports cancellation before dispatch as not started", async () => { + const commitMoveNode = vi.fn(async () => undefined); + const adapter = new CatmaidEditRequests(makeOperations({ commitMoveNode })); + const controller = new AbortController(); + controller.abort("disposed"); + + const outcome = await commitSpatialSkeletonEditRequest( + adapter, + { + kind: "move-node", + request: { + nodeId: 4n, + position: new Float32Array([8, 9, 10]), + }, + }, + { ...context, signal: controller.signal }, + ); + expect(outcome.status).toBe("not-started"); + expect(commitMoveNode).not.toHaveBeenCalled(); + }); +}); diff --git a/src/datasource/catmaid/spatial_skeleton_edit/edit_requests.ts b/src/datasource/catmaid/spatial_skeleton_edit/edit_requests.ts new file mode 100644 index 0000000000..89c71af87d --- /dev/null +++ b/src/datasource/catmaid/spatial_skeleton_edit/edit_requests.ts @@ -0,0 +1,227 @@ +/** + * @license + * Copyright 2026 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file Commits each CATMAID edit request through CATMAID's edit operations and + * classifies its failure as not started, rejected or indeterminate. Its edit + * request scope is one CATMAID server and project. + */ + +import type { CatmaidClient } from "#src/datasource/catmaid/api.js"; +import type { + CatmaidSpatialSkeletonAddNodeRequest, + CatmaidSpatialSkeletonAddNodeResult, + CatmaidSpatialSkeletonConfidenceUpdateRequest, + CatmaidSpatialSkeletonDeleteNodeRequest, + CatmaidSpatialSkeletonDescriptionUpdateRequest, + CatmaidSpatialSkeletonDescriptionUpdateResult, + CatmaidSpatialSkeletonInsertNodeRequest, + CatmaidSpatialSkeletonInsertNodeResult, + CatmaidSpatialSkeletonMergeRequest, + CatmaidSpatialSkeletonMergeResult, + CatmaidSpatialSkeletonMoveNodeRequest, + CatmaidSpatialSkeletonRadiusUpdateRequest, + CatmaidSpatialSkeletonRerootRequest, + CatmaidSpatialSkeletonSplitRequest, + CatmaidSpatialSkeletonSplitResult, + CatmaidSpatialSkeletonTrueEndUpdateRequest, + CatmaidSpatialSkeletonEditOperations, +} from "#src/datasource/catmaid/spatial_skeleton_edit/edit_operations.js"; +import type { + SpatialSkeletonEditRequestContext, + SpatialSkeletonEditRequestAdapter, +} from "#src/skeleton/edit_queue/api.js"; +import { SpatialSkeletonEditConflictError } from "#src/skeleton/edit_queue/edit_errors.js"; +import { HttpError } from "#src/util/http_request.js"; + +const catmaidEditRequestScopes = new Map(); + +export function getCatmaidEditRequestScope(client: CatmaidClient) { + if ( + typeof client.baseUrl !== "string" || + !Number.isSafeInteger(client.projectId) + ) { + return client; + } + let normalizedBaseUrl: string; + try { + const url = new URL(client.baseUrl); + url.hash = ""; + url.search = ""; + url.pathname = url.pathname.replace(/\/+$/, ""); + normalizedBaseUrl = url.toString().replace(/\/+$/, ""); + } catch { + normalizedBaseUrl = client.baseUrl.trim().replace(/\/+$/, ""); + } + const key = `${normalizedBaseUrl}/${client.projectId}`; + let scope = catmaidEditRequestScopes.get(key); + if (scope === undefined) { + scope = Object.freeze({ key }); + catmaidEditRequestScopes.set(key, scope); + } + return scope; +} + +/** + * CATMAID edit requests as seen by datasource-neutral optimistic machinery. + * + * Transport controls such as CATMAID's `nocheck` flag deliberately do not + * cross this boundary. The CATMAID client applies its fixed transport policy. + */ +export interface CatmaidEditRequestMap { + "add-node": { + request: CatmaidSpatialSkeletonAddNodeRequest; + result: CatmaidSpatialSkeletonAddNodeResult; + }; + "insert-node": { + request: CatmaidSpatialSkeletonInsertNodeRequest; + result: CatmaidSpatialSkeletonInsertNodeResult; + }; + "move-node": { + request: CatmaidSpatialSkeletonMoveNodeRequest; + result: void; + }; + "delete-node": { + request: CatmaidSpatialSkeletonDeleteNodeRequest; + result: void; + }; + reroot: { + request: CatmaidSpatialSkeletonRerootRequest; + result: void; + }; + description: { + request: CatmaidSpatialSkeletonDescriptionUpdateRequest; + result: CatmaidSpatialSkeletonDescriptionUpdateResult; + }; + "true-end": { + request: CatmaidSpatialSkeletonTrueEndUpdateRequest; + result: void; + }; + radius: { + request: CatmaidSpatialSkeletonRadiusUpdateRequest; + result: void; + }; + confidence: { + request: CatmaidSpatialSkeletonConfidenceUpdateRequest; + result: void; + }; + merge: { + request: CatmaidSpatialSkeletonMergeRequest; + result: CatmaidSpatialSkeletonMergeResult; + }; + split: { + request: CatmaidSpatialSkeletonSplitRequest; + result: CatmaidSpatialSkeletonSplitResult; + }; +} + +export type CatmaidEditRequestKind = keyof CatmaidEditRequestMap; + +export type CatmaidEditRequest< + TKind extends CatmaidEditRequestKind = CatmaidEditRequestKind, +> = { + [K in TKind]: { + readonly kind: K; + readonly request: CatmaidEditRequestMap[K]["request"]; + } & (K extends "merge" + ? { readonly inputSegmentIds: readonly [bigint, bigint] } + : object); +}[TKind]; + +export type CatmaidEditRequestResult< + TKind extends CatmaidEditRequestKind = CatmaidEditRequestKind, +> = CatmaidEditRequestMap[TKind]["result"]; + +/** A generic cancellation was observed before any CATMAID operation began. */ +export class CatmaidEditRequestNotStartedError extends Error { + constructor(readonly reason: unknown) { + super("The CATMAID edit request was cancelled before its request started."); + this.name = "CatmaidEditRequestNotStartedError"; + } +} + +/** Whether an error proves that CATMAID did not commit the edit request. */ +export function isDefinitiveCatmaidEditRequestRejection(error: unknown) { + return ( + error instanceof SpatialSkeletonEditConflictError || + (error instanceof HttpError && error.status >= 400 && error.status < 500) || + (error instanceof Error && error.name === "CatmaidNotFoundError") + ); +} + +export class CatmaidEditRequests + implements + SpatialSkeletonEditRequestAdapter< + CatmaidEditRequest, + CatmaidEditRequestResult + > +{ + constructor( + private readonly editOperations: CatmaidSpatialSkeletonEditOperations, + ) {} + + get editRequestScope() { + return this.editOperations.editRequestScope; + } + + commit( + editRequest: CatmaidEditRequest, + context: SpatialSkeletonEditRequestContext, + ): Promise>; + commit( + editRequest: CatmaidEditRequest, + context: SpatialSkeletonEditRequestContext, + ): Promise { + if (context.signal?.aborted) { + return Promise.reject( + new CatmaidEditRequestNotStartedError(context.signal.reason), + ); + } + switch (editRequest.kind) { + case "add-node": + return this.editOperations.commitAddNode(editRequest.request); + case "insert-node": + return this.editOperations.commitInsertNode(editRequest.request); + case "move-node": + return this.editOperations.commitMoveNode(editRequest.request); + case "delete-node": + return this.editOperations.commitDeleteNode(editRequest.request); + case "reroot": + return this.editOperations.commitReroot(editRequest.request); + case "description": + return this.editOperations.commitDescription(editRequest.request); + case "true-end": + return this.editOperations.commitTrueEnd(editRequest.request); + case "radius": + return this.editOperations.commitRadius(editRequest.request); + case "confidence": + return this.editOperations.commitConfidence(editRequest.request); + case "merge": + return this.editOperations.commitMerge(editRequest.request); + case "split": + return this.editOperations.commitSplit(editRequest.request); + } + } + + classifyFailure(error: unknown) { + if (error instanceof CatmaidEditRequestNotStartedError) { + return "not-started" as const; + } + return isDefinitiveCatmaidEditRequestRejection(error) + ? ("rejected" as const) + : ("indeterminate" as const); + } +} diff --git a/src/datasource/enabled_backend_modules.ts b/src/datasource/enabled_backend_modules.ts index 62f3d8564e..8b00c3af81 100644 --- a/src/datasource/enabled_backend_modules.ts +++ b/src/datasource/enabled_backend_modules.ts @@ -1,6 +1,7 @@ // DO NOT EDIT: Generated by config/update_conditions.ts import "#datasource/boss/backend"; import "#datasource/brainmaps/backend"; +import "#datasource/catmaid/backend"; import "#datasource/deepzoom/backend"; import "#datasource/dvid/backend"; import "#datasource/graphene/backend"; diff --git a/src/datasource/enabled_frontend_modules.ts b/src/datasource/enabled_frontend_modules.ts index 264c63800b..7ba19e4dfc 100644 --- a/src/datasource/enabled_frontend_modules.ts +++ b/src/datasource/enabled_frontend_modules.ts @@ -3,6 +3,8 @@ import "#datasource/boss/register_default"; import "#datasource/boss/register_credentials_provider"; import "#datasource/brainmaps/register_default"; import "#datasource/brainmaps/register_credentials_provider"; +import "#datasource/catmaid/register_default"; +import "#datasource/catmaid/register_credentials_provider"; import "#datasource/deepzoom/register_default"; import "#datasource/dvid/register_default"; import "#datasource/dvid/register_credentials_provider"; diff --git a/src/datasource/index.ts b/src/datasource/index.ts index 31c8a047e6..6dbfa64b52 100644 --- a/src/datasource/index.ts +++ b/src/datasource/index.ts @@ -43,6 +43,7 @@ import type { SegmentPropertyMap } from "#src/segmentation_display_state/propert import type { SegmentationGraphSource } from "#src/segmentation_graph/source.js"; import type { SingleMeshSource } from "#src/single_mesh/frontend.js"; import type { SkeletonSource } from "#src/skeleton/frontend.js"; +import type { MultiscaleSpatiallyIndexedSkeletonSource } from "#src/skeleton/spatial/frontend.js"; import type { MultiscaleVolumeChunkSource } from "#src/sliceview/volume/frontend.js"; import type { WatchableValueInterface } from "#src/trackable_value.js"; import type { @@ -126,6 +127,7 @@ export interface ConvertLegacyUrlOptions extends ConvertLegacyUrlOptionsBase { export interface DataSubsource { volume?: MultiscaleVolumeChunkSource; mesh?: MeshSource | MultiscaleMeshSource | SkeletonSource; + spatialSkeleton?: MultiscaleSpatiallyIndexedSkeletonSource; annotation?: MultiscaleAnnotationSource; staticAnnotations?: AnnotationSource; local?: LocalDataSource; diff --git a/src/datasource/precomputed/skeletons.md b/src/datasource/precomputed/skeletons.md index 68dc31930a..37b8afafc8 100644 --- a/src/datasource/precomputed/skeletons.md +++ b/src/datasource/precomputed/skeletons.md @@ -53,6 +53,16 @@ The skeleton representation for a single segment ID is a binary file with the fo - `attribute_data`: `num_vertices * num_components` elements of the specified `data_type` in little-endian format. +### Parent and child of each vertex + +Neuroglancer treats each edge as undirected. The Skeleton tab shows each vertex index as its node ID. To browse a skeleton as a tree in the viewer, Neuroglancer chooses a parent for each vertex following this strategy: + +- The root of each connected part is its lowest vertex index. Vertex 0 is the root of its part. If the whole skeleton is connected, vertex 0 is the only root. +- The parent of a vertex is the neighbor that is closest to the root. If more than one neighbor is that near, the parent is the one with the lowest index. Two neighbors can be equally near only in a loop. In a skeleton without loops, each edge points away from the root. +- Every other edge closes a loop. Neuroglancer still draws it, and the Skeleton tab lists each end of it as a loop neighbor of the other, but parent and child navigation does not follow it. + +For example, the edges `0-5`, `5-9`, `9-2`, `2-5` and `2-10` give `5` the parent `0`, both `9` and `2` the parent `5`, and `10` the parent `2`. Vertices `9` and `2` are both two edges from the root, so the edge `9-2` closes the loop and is tracked separately from the parent and child relationship. + ### Unsharded storage of encoded skeleton data If the unsharded format is used, the encoded skeleton data is stored as a separate file within the diff --git a/src/gpu_hash/shader.ts b/src/gpu_hash/shader.ts index af44a0b97b..9140bdf899 100644 --- a/src/gpu_hash/shader.ts +++ b/src/gpu_hash/shader.ts @@ -119,7 +119,10 @@ export class HashSetShaderManager { this.readTable = prefix + "_readTable"; } - defineShader(builder: ShaderBuilder) { + defineShader(builder: ShaderBuilder, fragment = true) { + const addCode = fragment + ? builder.addFragmentCode.bind(builder) + : builder.addVertexCode.bind(builder); const { hashSeedsName, samplerName, numAlternatives, hashKeyMask } = this; builder.addUniform("highp uint", hashSeedsName, numAlternatives); builder.addUniform("highp uint", hashKeyMask); @@ -128,11 +131,11 @@ export class HashSetShaderManager { samplerName, this.textureUnitSymbol, ); - builder.addFragmentCode(glsl_hashCombine); - builder.addFragmentCode(glsl_uint64); - builder.addFragmentCode(glsl_equalUint64); + addCode(glsl_hashCombine); + addCode(glsl_uint64); + addCode(glsl_equalUint64); this.accessHelper.defineShader(builder); - builder.addFragmentCode( + addCode( this.accessHelper.getAccessor( this.readTable, this.samplerName, @@ -159,7 +162,7 @@ bool ${this.hasFunctionName}(uint64_t x) { return false; } `; - builder.addFragmentCode(s); + addCode(s); } get hasFunctionName() { @@ -172,7 +175,7 @@ bool ${this.hasFunctionName}(uint64_t x) { hashTable: GPUHashTable, ) { hashTable.copyToGPU(); - const textureUnit = shader.textureUnit(this.textureUnitSymbol); + const textureUnit = shader.textureUnit(this.textureUnitSymbol)!; gl.activeTexture(WebGL2RenderingContext.TEXTURE0 + textureUnit); gl.bindTexture(WebGL2RenderingContext.TEXTURE_2D, hashTable.texture); gl.uniform1ui( @@ -186,15 +189,18 @@ bool ${this.hasFunctionName}(uint64_t x) { } disable(gl: GL, shader: ShaderProgram) { - const textureUnit = shader.textureUnit(this.textureUnitSymbol); + const textureUnit = shader.textureUnit(this.textureUnitSymbol)!; gl.activeTexture(WebGL2RenderingContext.TEXTURE0 + textureUnit); gl.bindTexture(WebGL2RenderingContext.TEXTURE_2D, null); } } export class HashMapShaderManager extends HashSetShaderManager { - defineShader(builder: ShaderBuilder) { - super.defineShader(builder); + defineShader(builder: ShaderBuilder, fragment = true) { + const addCode = fragment + ? builder.addFragmentCode.bind(builder) + : builder.addVertexCode.bind(builder); + super.defineShader(builder, fragment); const { numAlternatives, hashSeedsName, hashKeyMask } = this; let s = ` bool ${this.getFunctionName}(uint64_t x, out uint64_t value) { @@ -215,7 +221,7 @@ bool ${this.getFunctionName}(uint64_t x, out uint64_t value) { return false; } `; - builder.addFragmentCode(s); + addCode(s); } get getFunctionName() { diff --git a/src/layer/annotation/index.ts b/src/layer/annotation/index.ts index 55c1a33463..ee119452f2 100644 --- a/src/layer/annotation/index.ts +++ b/src/layer/annotation/index.ts @@ -849,7 +849,7 @@ export class AnnotationUserLayer extends Base { function makeShaderCodeWidget(layer: AnnotationUserLayer) { return new ShaderCodeWidget({ shaderError: layer.annotationDisplayState.shaderError, - fragmentMain: layer.annotationDisplayState.shader, + fragment: layer.annotationDisplayState.shader, shaderControlState: layer.annotationDisplayState.shaderControls, }); } diff --git a/src/layer/annotation/property_tools.ts b/src/layer/annotation/property_tools.ts index 3c1907a874..e75fe04cac 100644 --- a/src/layer/annotation/property_tools.ts +++ b/src/layer/annotation/property_tools.ts @@ -37,6 +37,7 @@ import type { ToolActivation } from "#src/ui/tool.js"; import { LayerTool, makeToolActivationStatusMessageWithHeader, + makeToolStatusChip, registerTool, } from "#src/ui/tool.js"; import { animationFrameDebounce } from "#src/util/animation_frame_debounce.js"; @@ -450,28 +451,6 @@ export abstract class AnnotationPropertyEntryTool extends LayerTool { - this.appendChip( - valueContainer, - useNumberEntry - ? String(index + 1) - : (keyForEnumOptionIndex(index) ?? String(index + 1)), - enumLabels[index] ?? String(value), - value === currentValue, + valueContainer.appendChild( + makeToolStatusChip( + useNumberEntry + ? String(index + 1) + : (keyForEnumOptionIndex(index) ?? String(index + 1)), + enumLabels[index] ?? String(value), + value === currentValue, + ), ); }); if (useNumberEntry) this.entry.render(entrySlot); diff --git a/src/layer/image/index.ts b/src/layer/image/index.ts index 5b93089ff7..9911668859 100644 --- a/src/layer/image/index.ts +++ b/src/layer/image/index.ts @@ -542,7 +542,7 @@ void main() { function makeShaderCodeWidget(layer: ImageUserLayer) { return new ShaderCodeWidget({ shaderError: layer.shaderError, - fragmentMain: layer.fragmentMain, + fragment: layer.fragmentMain, shaderControlState: layer.shaderControlState, }); } diff --git a/src/layer/index.spec.ts b/src/layer/index.spec.ts new file mode 100644 index 0000000000..b71cb5d85b --- /dev/null +++ b/src/layer/index.spec.ts @@ -0,0 +1,117 @@ +/** + * @license + * Copyright 2026 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { + CoordinateSpaceCombiner, + TrackableCoordinateSpace, +} from "#src/coordinate_transform.js"; +import type { LayerListSpecification } from "#src/layer/index.js"; +import { + LayerManager, + LayerSelectedValues, + ManagedUserLayer, + MouseSelectionState, + TrackableDataSelectionState, + UserLayer, +} from "#src/layer/index.js"; +import { GlobalToolBinder } from "#src/ui/tool.js"; +import type { MultiToolPaletteState } from "#src/ui/tool_palette.js"; +import { RefCounted } from "#src/util/disposable.js"; +import { NullarySignal } from "#src/util/signal.js"; + +function makeSelectionFixture() { + const scope = new RefCounted(); + const toolBinder = scope.registerDisposer( + new GlobalToolBinder(() => {}, {} as MultiToolPaletteState), + ); + const manager = scope.registerDisposer(new LayerManager()); + scope.registerDisposer(manager.useDirectly()); + const coordinateSpace = new TrackableCoordinateSpace(); + const specification = { + rootLayers: manager, + root: { + coordinateSpaceCombiner: new CoordinateSpaceCombiner( + coordinateSpace, + () => true, + ), + display: { updateStarted: new NullarySignal(), scheduleRedraw: vi.fn() }, + toolBinder, + }, + } as unknown as LayerListSpecification; + const mouse = new MouseSelectionState(); + mouse.setActive(true); + const selected = scope.registerDisposer( + new LayerSelectedValues(manager, mouse), + ); + const persistent = scope.registerDisposer( + new TrackableDataSelectionState(coordinateSpace, selected), + ); + + function createLayer(name: string) { + const managed = new ManagedUserLayer(name, specification); + const layer = new UserLayer(managed); + managed.layer = layer; + manager.addManagedLayer(managed); + return layer; + } + + return { scope, selected, persistent, createLayer }; +} + +describe("selection of layers added before initialization", () => { + let fixture: ReturnType; + + beforeEach(() => { + vi.useFakeTimers(); + fixture = makeSelectionFixture(); + }); + + afterEach(() => { + fixture.scope.dispose(); + vi.clearAllTimers(); + vi.useRealTimers(); + }); + + it("omits an uninitialized layer from selection reads and serialization", () => { + const layer = fixture.createLayer("layer"); + + expect(fixture.selected.get(layer)).toBeUndefined(); + expect(fixture.selected.toJSON()).toEqual({}); + + layer.initializationDone(); + + expect(fixture.selected.get(layer)?.localPositionValid).toBe(true); + expect(fixture.selected.toJSON()).toEqual({ layer: {} }); + }); + + it("resamples live selection after initialization without mouse movement", () => { + fixture.persistent.unpin(); + vi.runAllTimers(); + + const layer = fixture.createLayer("layer"); + vi.runAllTimers(); + + expect(fixture.persistent.value?.layers).toEqual([]); + layer.initializationDone(); + vi.runAllTimers(); + + expect( + fixture.persistent.value?.layers.map((entry) => entry.layer), + ).toEqual([layer]); + }); +}); diff --git a/src/layer/index.ts b/src/layer/index.ts index fad0e1400e..fc75e7e998 100644 --- a/src/layer/index.ts +++ b/src/layer/index.ts @@ -364,6 +364,9 @@ export class UserLayer extends RefCounted { get isReady() { return this.loadingCounter === 0; } + isReadyWatchable: WatchableValueInterface = new WatchableValue( + false, + ); tabs = this.registerDisposer(new TabSpecification()); panels = new UserLayerSidePanelsState(this); @@ -379,6 +382,11 @@ export class UserLayer extends RefCounted { constructor(public managedLayer: Borrowed) { super(); + this.registerDisposer( + this.readyStateChanged.add(() => { + this.isReadyWatchable.value = this.isReady; + }), + ); this.toolBinder = this.registerDisposer( new LayerToolBinder(this, this.manager.root.toolBinder), ); @@ -481,6 +489,8 @@ export class UserLayer extends RefCounted { const selectionState = (this.selectionState = {} as any); this.initializeSelectionState(selectionState); this.decrementLoadingCounter(); + // Layers can be published before initialization, including while sources load. + this.layersChanged.dispatch(); } getLegacyDataSourceSpecifications( @@ -608,6 +618,12 @@ export class UserLayer extends RefCounted { return value; } + getMissingAnnotationToolMessage(): string { + return `The selected layer (${JSON.stringify( + this.managedLayer.name, + )}) does not have an active annotation tool.`; + } + toJSON(): any { return { type: this.type, @@ -1115,10 +1131,17 @@ export class LayerManager extends RefCounted { } } +export interface PickedSpatialSkeletonState { + nodeId?: bigint; + segmentId?: bigint; + position?: Float32Array; +} + export interface PickState { pickedRenderLayer: RenderLayer | null; pickedValue: bigint; pickedOffset: number; + pickedSpatialSkeleton: PickedSpatialSkeletonState | undefined; pickedAnnotationLayer: AnnotationLayerState | undefined; pickedAnnotationId: string | undefined; pickedAnnotationBuffer: ArrayBuffer | undefined; @@ -1140,6 +1163,7 @@ export class MouseSelectionState implements PickState { pickedRenderLayer: RenderLayer | null = null; pickedValue = 0n; pickedOffset = 0; + pickedSpatialSkeleton: PickedSpatialSkeletonState | undefined = undefined; pickedAnnotationLayer: AnnotationLayerState | undefined = undefined; pickedAnnotationId: string | undefined = undefined; pickedAnnotationBuffer: ArrayBuffer | undefined = undefined; @@ -1236,6 +1260,7 @@ export class LayerSelectedValues extends RefCounted { const userLayer = layer.layer; if (layer.visible && userLayer !== null) { const { selectionState } = userLayer; + if (selectionState === undefined) continue; userLayer.resetSelectionState(selectionState); selectionState.generation = generation; userLayer.captureSelectionState(selectionState, mouseState); @@ -1247,7 +1272,7 @@ export class LayerSelectedValues extends RefCounted { get(userLayer: T): T["selectionState"] | undefined { this.update(); const { selectionState } = userLayer; - if (selectionState.generation !== this.changed.count) return undefined; + if (selectionState?.generation !== this.changed.count) return undefined; return selectionState; } diff --git a/src/layer/segmentation/index.browser_test.ts b/src/layer/segmentation/index.browser_test.ts new file mode 100644 index 0000000000..b6dc525364 --- /dev/null +++ b/src/layer/segmentation/index.browser_test.ts @@ -0,0 +1,827 @@ +/** + * @license + * Copyright 2026 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { emptyInvalidCoordinateSpace } from "#src/coordinate_transform.js"; +import { CatmaidSpatialSkeletonEditCommands } from "#src/datasource/catmaid/spatial_skeleton_edit/command_factories.js"; +import { LocalDataSource } from "#src/datasource/local.js"; +import { TrackableDataSelectionState } from "#src/layer/index.js"; +import { SegmentationUserLayer } from "#src/layer/segmentation/index.js"; +import { SkeletonNodeSelection } from "#src/layer/segmentation/skeleton_node_selection.js"; +import { SkeletonSourceConnection } from "#src/layer/segmentation/skeleton_source_connection.js"; +import { LocalSegmentationGraphSource } from "#src/segmentation_graph/local.js"; +import { SharedDisjointUint64Sets } from "#src/shared_disjoint_sets.js"; +import { SkeletonEdgeDirection } from "#src/skeleton/api.js"; +import { SpatialSkeletonActions } from "#src/skeleton/edit/edit_commands.js"; +import { SpatialSkeletonEditSession } from "#src/skeleton/edit/spatial_skeleton_edit_session.js"; +import { executeSpatialSkeletonAddNode } from "#src/skeleton/edit/submit_edits.js"; +import { MultiscaleSpatiallyIndexedSkeletonSource } from "#src/skeleton/spatial/frontend.js"; +import { SkeletonOverlaySegments } from "#src/skeleton/spatial/overlay_segments.js"; +import { StatusMessage } from "#src/status.js"; +import { WatchableValue } from "#src/trackable_value.js"; +import { SelectionDetailsPanel } from "#src/ui/selection_details.js"; +import { Uint64OrderedSet } from "#src/uint64_ordered_set.js"; +import { Uint64Set } from "#src/uint64_set.js"; +import { RefCounted } from "#src/util/disposable.js"; +import { NullarySignal } from "#src/util/signal.js"; +import { DependentViewWidget } from "#src/widget/dependent_view_widget.js"; + +const segmentationDisplayStateCallbacks = vi.hoisted( + () => new Set<() => void>(), +); + +vi.mock( + "#src/segmentation_display_state/frontend.js", + async (importOriginal) => { + const original = await importOriginal>(); + return { + ...original, + makeSegmentWidget: (_displayState: unknown, id: { key: bigint }) => { + const row = document.createElement("div"); + row.textContent = `segment ${id.key}`; + return row; + }, + bindSegmentListWidth: () => () => {}, + getBaseObjectColor: () => new Float32Array([0.2, 0.4, 0.6, 1]), + registerCallbackWhenSegmentationDisplayStateChanged: ( + _displayState: unknown, + context: { registerDisposer(disposer: () => void): void }, + callback: () => void, + ) => { + segmentationDisplayStateCallbacks.add(callback); + context.registerDisposer(() => + segmentationDisplayStateCallbacks.delete(callback), + ); + }, + }; + }, +); + +function makeSkeletonSourceConnection( + spatialSkeletonEditSession: SpatialSkeletonEditSession, +) { + return new SkeletonSourceConnection({ + spatialSkeletonEditSession, + selection: {} as any, + overlaySegments: new SkeletonOverlaySegments({ + segmentationGroupState: new WatchableValue({} as any), + editSession: spatialSkeletonEditSession, + }), + segmentationGroupState: new WatchableValue({} as any), + skeletonNodeAccess: new WatchableValue(undefined), + spatiallyIndexedSkeletonLayer: new WatchableValue(undefined), + }); +} + +function makeSelectionHookLayer() { + const renderLayer = {}; + const layer = Object.create(SegmentationUserLayer.prototype); + const layerSelectedValues = { + changed: new NullarySignal(), + mouseState: { active: false }, + }; + const selectionState = new TrackableDataSelectionState( + new WatchableValue(emptyInvalidCoordinateSpace), + layerSelectedValues as any, + ); + Object.defineProperties(layer, { + localCoordinateSpace: { value: { value: { rank: 0 } } }, + localPosition: { value: { value: new Float32Array(0) } }, + renderLayers: { value: [renderLayer] }, + getValueAt: { value: () => 7n }, + manager: { value: { layerSelectedValues, root: { selectionState } } }, + }); + layer.skeletonNodeSelection = new SkeletonNodeSelection({ + layer, + skeletonNodeAccess: new WatchableValue(undefined), + spatiallyIndexedSkeletonLayer: new WatchableValue(undefined), + spatialSkeletonEditSession: new SpatialSkeletonEditSession(), + }); + return { layer, renderLayer }; +} + +function makeEditableSpatialSkeletonSource( + options: { + rerootCommand?: boolean; + } = {}, +) { + const createCommand = () => ({ + label: "test command", + execute: vi.fn(), + undo: vi.fn(), + redo: vi.fn(), + }); + const makeCommand = (action: string) => ({ + action, + createCommand, + }); + return { + editPlannerProvider: { + createPlanner: vi.fn(), + }, + addNodesCommand: makeCommand(SpatialSkeletonActions.addNodes), + moveNodesCommand: makeCommand(SpatialSkeletonActions.moveNodes), + deleteNodesCommand: makeCommand(SpatialSkeletonActions.deleteNodes), + editNodeDescriptionCommand: makeCommand( + SpatialSkeletonActions.editNodeDescription, + ), + editNodeTrueEndCommand: makeCommand(SpatialSkeletonActions.editNodeTrueEnd), + editNodeRadiusCommand: makeCommand(SpatialSkeletonActions.editNodeRadius), + editNodeConfidenceCommand: makeCommand( + SpatialSkeletonActions.editNodeConfidence, + ), + mergeSkeletonsCommand: makeCommand(SpatialSkeletonActions.mergeSkeletons), + splitSkeletonsCommand: makeCommand(SpatialSkeletonActions.splitSkeletons), + edgeDirection: SkeletonEdgeDirection.CHILD_TO_PARENT, + getSkeletonManifest: async () => ({ fragmentKeys: [] }), + getSkeletonFragment: async () => ({ nodes: [], edges: [] }), + ...(options.rerootCommand !== true + ? {} + : { + rerootCommand: makeCommand(SpatialSkeletonActions.reroot), + }), + }; +} + +describe("layer/segmentation spatial skeleton source teardown", () => { + function makeActivatingSegmentationLayer() { + const spatialSkeletonEditSession = new SpatialSkeletonEditSession(); + const layer = Object.assign( + Object.create(SegmentationUserLayer.prototype), + { + spatialSkeletonEditSession, + displayState: { + linkedSegmentationGroup: { root: { value: undefined } }, + segmentationGroupState: { value: {} }, + originalSegmentationGroupState: { + segmentPropertyMap: new WatchableValue(undefined), + graph: new WatchableValue(undefined), + }, + hasVolume: new WatchableValue(false), + }, + }, + ); + layer.skeletonSourceConnection = makeSkeletonSourceConnection( + spatialSkeletonEditSession, + ); + Object.defineProperty(layer, "manager", { + value: { chunkManager: { memoize: { getUncounted: () => undefined } } }, + }); + return { layer, spatialSkeletonEditSession }; + } + + function makeSpatialSkeletonSubsource() { + return { + subsourceEntry: { + subsource: { + spatialSkeleton: Object.create( + MultiscaleSpatiallyIndexedSkeletonSource.prototype, + ), + }, + }, + loadedDataSource: { dataSource: { state: undefined } }, + activate: vi.fn(), + deactivate: vi.fn(), + }; + } + + it("clears edit state when the skeleton source is replaced or removed", () => { + const { layer, spatialSkeletonEditSession } = + makeActivatingSegmentationLayer(); + const original = makeSpatialSkeletonSubsource(); + const replacement = makeSpatialSkeletonSubsource(); + layer.activateDataSubsources([original]); + spatialSkeletonEditSession.editMode.value = true; + spatialSkeletonEditSession.setMergeAnchor(5n); + + const { commandHistory } = spatialSkeletonEditSession; + commandHistory.confirm(commandHistory.stageExecute("add node")); + + layer.activateDataSubsources([replacement]); + expect(spatialSkeletonEditSession.editMode.value).toBe(false); + expect(spatialSkeletonEditSession.mergeAnchorNodeId.value).toBeUndefined(); + expect(commandHistory.canUndo.value).toBe(false); + + spatialSkeletonEditSession.editMode.value = true; + spatialSkeletonEditSession.setMergeAnchor(6n); + layer.activateDataSubsources([]); + expect(spatialSkeletonEditSession.editMode.value).toBe(false); + expect(spatialSkeletonEditSession.mergeAnchorNodeId.value).toBeUndefined(); + }); + + it("keeps edit mode, merge anchor, edit queue and undo history when the same skeleton source is activated again", () => { + const { layer, spatialSkeletonEditSession } = + makeActivatingSegmentationLayer(); + const subsource = makeSpatialSkeletonSubsource(); + layer.activateDataSubsources([subsource]); + spatialSkeletonEditSession.editMode.value = true; + spatialSkeletonEditSession.setMergeAnchor(5n); + (spatialSkeletonEditSession as any).editQueue = { + hasUnconfirmedActions: () => true, + dispose: async () => {}, + }; + const { commandHistory } = spatialSkeletonEditSession; + commandHistory.confirm(commandHistory.stageExecute("add node")); + + layer.activateDataSubsources([subsource]); + + expect(spatialSkeletonEditSession.editMode.value).toBe(true); + expect(spatialSkeletonEditSession.mergeAnchorNodeId.value).toBe(5n); + expect(spatialSkeletonEditSession.hasUnconfirmedEdits()).toBe(true); + expect(commandHistory.undoLabel.value).toBe("add node"); + }); +}); + +describe("layer/segmentation spatial skeleton selection state", () => { + it("a saved node selection keeps both the node and its skeleton", () => { + const { layer } = makeSelectionHookLayer(); + const state: any = {}; + layer.initializeSelectionState(state); + + layer.selectionStateFromJson(state, { nodeId: "23", value: "7" }); + + expect(state.nodeId).toBe(23n); + expect(state.value).toBe(7n); + expect(layer.selectionStateToJson(state, false)).toEqual({ + nodeId: "23", + value: "7", + }); + const copiedState: any = {}; + layer.initializeSelectionState(copiedState); + layer.copySelectionState(copiedState, state); + expect(copiedState.nodeId).toBe(23n); + expect(copiedState.value).toBe(7n); + }); + + it("clicking a skeleton node selects the node and its skeleton, not the voxel below it", () => { + const { layer, renderLayer } = makeSelectionHookLayer(); + const state: any = {}; + layer.initializeSelectionState(state); + + layer.captureSelectionState(state, { + active: true, + position: new Float32Array(0), + pickedRenderLayer: renderLayer, + pickedSpatialSkeleton: { nodeId: 31n, segmentId: 9n }, + } as any); + + expect(state.nodeId).toBe(31n); + expect(state.value).toBe(9n); + }); + + it("a node picked in another layer's skeleton leaves the voxel selection", () => { + const { layer } = makeSelectionHookLayer(); + const state: any = {}; + layer.initializeSelectionState(state); + + layer.captureSelectionState(state, { + active: true, + position: new Float32Array(0), + pickedRenderLayer: {}, + pickedSpatialSkeleton: { nodeId: 31n, segmentId: 9n }, + } as any); + + expect(state.nodeId).toBeUndefined(); + expect(state.value).toBe(7n); + }); +}); + +function makeEquivalencesLayer(savedEquivalences: string[][]) { + const layer = Object.create(SegmentationUserLayer.prototype); + const localGraph = new LocalSegmentationGraphSource(); + localGraph.restoreState(savedEquivalences); + const groupState = { + localGraph, + graph: new WatchableValue(undefined), + segmentPropertyMap: new WatchableValue(undefined), + segmentEquivalences: new SharedDisjointUint64Sets(), + visibleSegments: new Uint64Set(), + }; + Object.defineProperty(layer, "manager", { + value: { chunkManager: { memoize: { getUncounted: () => undefined } } }, + }); + Object.assign(layer, { + displayState: { + linkedSegmentationGroup: { root: { value: layer } }, + originalSegmentationGroupState: groupState, + segmentationGroupState: { value: groupState }, + hasVolume: new WatchableValue(false), + }, + graphConnection: new WatchableValue(undefined), + skeletonSourceConnection: makeSkeletonSourceConnection( + new SpatialSkeletonEditSession(), + ), + }); + return { layer, groupState }; +} + +function makeLinkedLayer(rootEquivalences: [bigint, bigint][]) { + const { layer, groupState } = makeEquivalencesLayer([]); + const { groupState: rootGroupState } = makeEquivalencesLayer([]); + for (const [firstSegment, secondSegment] of rootEquivalences) { + rootGroupState.segmentEquivalences.link(firstSegment, secondSegment); + } + const root = { value: { managedLayer: { name: "merged" } } as unknown }; + layer.managedLayer = { name: "catmaid" }; + layer.displayState.segmentationGroupState.value = rootGroupState; + layer.displayState.linkedSegmentationGroup = { + root, + isolate: () => { + root.value = layer; + layer.displayState.segmentationGroupState.value = groupState; + }, + }; + return { layer, root }; +} + +function makeLoadedSubsource(subsource: object) { + return { + subsourceEntry: { subsource }, + loadedDataSource: { dataSource: { state: undefined } }, + activated: undefined as RefCounted | undefined, + errorMessage: undefined as string | undefined, + activate(callback: (refCounted: RefCounted) => void) { + this.errorMessage = undefined; + if (this.activated !== undefined) return; + this.activated = new RefCounted(); + callback(this.activated); + }, + deactivate(message: string) { + this.errorMessage = message; + this.activated?.dispose(); + this.activated = undefined; + }, + }; +} + +function makeEquivalencesSubsource() { + return makeLoadedSubsource({ local: LocalDataSource.equivalences }); +} + +function makeSkeletonSubsource(editableSource: unknown) { + const spatialSkeleton = Object.create( + MultiscaleSpatiallyIndexedSkeletonSource.prototype, + ); + Object.defineProperty(spatialSkeleton, "editableSource", { + value: editableSource, + }); + return { ...makeLoadedSubsource({ spatialSkeleton }), activate: vi.fn() }; +} + +describe("layer/segmentation equivalences with editable skeletons", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("turns off equivalences when the layer has an editable skeleton source", () => { + const { layer, groupState } = makeEquivalencesLayer([["3", "7"]]); + const equivalences = makeEquivalencesSubsource(); + + layer.activateDataSubsources([ + equivalences, + makeSkeletonSubsource(makeEditableSpatialSkeletonSource()), + ]); + + expect(groupState.segmentEquivalences.get(7n)).toBe(7n); + expect(groupState.graph.value).toBeUndefined(); + expect(equivalences.errorMessage).toBe( + "Not supported with editable skeletons", + ); + }); + + it("removes merges that were applied before the editable skeleton source loaded", () => { + const { layer, groupState } = makeEquivalencesLayer([["3", "7"]]); + const equivalences = makeEquivalencesSubsource(); + layer.activateDataSubsources([equivalences]); + expect(groupState.segmentEquivalences.get(7n)).toBe(3n); + + layer.activateDataSubsources([ + equivalences, + makeSkeletonSubsource(makeEditableSpatialSkeletonSource()), + ]); + + expect(groupState.segmentEquivalences.get(7n)).toBe(7n); + }); + + it("removes merges that a linked layer left behind", () => { + const { layer, groupState } = makeEquivalencesLayer([]); + groupState.segmentEquivalences.link(3n, 7n); + + layer.activateDataSubsources([ + makeSkeletonSubsource(makeEditableSpatialSkeletonSource()), + ]); + + expect(groupState.segmentEquivalences.get(7n)).toBe(7n); + }); + + it("keeps equivalences for a skeleton source that cannot be edited", () => { + const { layer, groupState } = makeEquivalencesLayer([["3", "7"]]); + + layer.activateDataSubsources([ + makeEquivalencesSubsource(), + makeSkeletonSubsource(undefined), + ]); + + expect(groupState.segmentEquivalences.get(7n)).toBe(3n); + }); + + it("keeps the saved equivalences while they are turned off", () => { + const { layer, groupState } = makeEquivalencesLayer([["3", "7"]]); + const equivalences = makeEquivalencesSubsource(); + layer.activateDataSubsources([equivalences]); + + layer.activateDataSubsources([ + equivalences, + makeSkeletonSubsource(makeEditableSpatialSkeletonSource()), + ]); + + expect(groupState.localGraph.toJSON()).toEqual([["3", "7"]]); + }); + + it("unlinks a layer with editable skeletons from a layer that has equivalences", () => { + const showMessage = vi + .spyOn(StatusMessage, "showTemporaryMessage") + .mockImplementation(() => ({}) as any); + const { layer, root } = makeLinkedLayer([[3n, 7n]]); + + layer.activateDataSubsources([ + makeSkeletonSubsource(makeEditableSpatialSkeletonSource()), + ]); + + expect(root.value).toBe(layer); + expect(showMessage).toHaveBeenCalledWith( + "Unlinked catmaid from merged: layers with editable skeletons do not support equivalences.", + ); + }); + + it("keeps a layer with editable skeletons linked to a layer without equivalences", () => { + const { layer, root } = makeLinkedLayer([]); + const linkedRoot = root.value; + + layer.activateDataSubsources([ + makeSkeletonSubsource(makeEditableSpatialSkeletonSource()), + ]); + + expect(root.value).toBe(linkedRoot); + }); + + it("keeps a layer without editable skeletons linked to a layer with equivalences", () => { + const { layer, root } = makeLinkedLayer([[3n, 7n]]); + const linkedRoot = root.value; + + layer.activateDataSubsources([makeSkeletonSubsource(undefined)]); + + expect(root.value).toBe(linkedRoot); + }); +}); + +describe("layer/segmentation spatial skeleton sources", () => { + it("shows only the first spatial skeleton source and reports the second as unsupported", () => { + const { layer } = makeEquivalencesLayer([]); + const firstSkeleton = makeSkeletonSubsource(undefined); + const secondSkeleton = makeSkeletonSubsource(undefined); + + layer.activateDataSubsources([firstSkeleton, secondSkeleton]); + + expect(firstSkeleton.activate).toHaveBeenCalled(); + expect(firstSkeleton.errorMessage).toBeUndefined(); + expect(secondSkeleton.activate).not.toHaveBeenCalled(); + expect(secondSkeleton.errorMessage).toBe( + "Only one spatially indexed skeleton source is supported", + ); + }); +}); + +describe("layer/segmentation selection details", () => { + function makeDetailsHostLayer() { + const layer = Object.create(SegmentationUserLayer.prototype); + const layerSelectedValues = { + changed: new NullarySignal(), + mouseState: { active: false }, + }; + const selectionState = new TrackableDataSelectionState( + new WatchableValue(emptyInvalidCoordinateSpace), + layerSelectedValues as any, + ); + const spatialSkeletonEditSession = new SpatialSkeletonEditSession(); + const commands = new CatmaidSpatialSkeletonEditCommands({ + getClient: () => ({}) as any, + }); + const skeletonNodeAccess = new WatchableValue({ + getSegmentNodes: () => [], + parentsInferred: false, + nodesChanged: new NullarySignal(), + hasPickableNodes: false, + displayState: { transform: new WatchableValue(undefined) }, + }); + const spatiallyIndexedSkeletonLayer = new WatchableValue({ + editableSource: { + editPlannerProvider: commands.editPlannerProvider, + editNodeRadiusCommand: commands.editNodeRadiusCommand, + }, + getNode: () => undefined, + }); + Object.defineProperties(layer, { + manager: { + value: { + layerSelectedValues, + root: { + selectionState, + globalPosition: new WatchableValue(new Float32Array(3)), + }, + }, + }, + renderLayers: { value: [] }, + displayState: { + value: { + segmentationGroupState: { + value: { + segmentEquivalences: { get: (id: bigint) => id }, + segmentPropertyMap: { value: undefined }, + }, + }, + }, + }, + }); + const skeletonNodeSelection = new SkeletonNodeSelection({ + layer, + skeletonNodeAccess, + spatiallyIndexedSkeletonLayer, + spatialSkeletonEditSession, + }); + Object.assign(layer, { + spatialSkeletonEditSession, + skeletonNodeAccess, + skeletonNodeSelection, + skeletonSourceConnection: new SkeletonSourceConnection({ + spatialSkeletonEditSession, + selection: skeletonNodeSelection, + overlaySegments: new SkeletonOverlaySegments({ + segmentationGroupState: new WatchableValue({} as any), + editSession: spatialSkeletonEditSession, + }), + segmentationGroupState: new WatchableValue({} as any), + skeletonNodeAccess, + spatiallyIndexedSkeletonLayer, + }), + }); + return { layer, spatialSkeletonEditSession }; + } + + it("keeps a radius being typed while the hovered segment changes", async () => { + const { layer, spatialSkeletonEditSession } = makeDetailsHostLayer(); + spatialSkeletonEditSession.replaceCachedSegmentSnapshots([ + [ + 5n, + [ + { + nodeId: 1n, + segmentId: 5n, + position: new Float32Array([1, 2, 3]), + attributes: { radius: [2] }, + }, + ], + ], + ]); + const state: any = {}; + layer.initializeSelectionState(state); + state.nodeId = 1n; + state.value = 5n; + const panel = new DependentViewWidget( + { value: undefined, changed: new NullarySignal() }, + (_, parent, context) => { + layer.displaySelectionState(state, parent, context); + }, + ); + document.body.appendChild(panel.element); + const radius = [ + ...panel.element.querySelectorAll(".neuroglancer-annotation-property"), + ].find((row) => row.firstElementChild?.textContent === "Radius")! + .lastElementChild!.firstElementChild as HTMLInputElement; + radius.focus(); + radius.value = "7"; + radius.dispatchEvent(new Event("input")); + + for (const callback of segmentationDisplayStateCallbacks) callback(); + await new Promise((resolve) => requestAnimationFrame(resolve)); + + expect(radius.isConnected).toBe(true); + expect(radius.value).toBe("7"); + expect(document.activeElement).toBe(radius); + panel.dispose(); + panel.element.remove(); + }); + + function makeCreatingHostLayer() { + const layer = Object.create(SegmentationUserLayer.prototype); + const layerSelectedValues = { + changed: new NullarySignal(), + mouseState: { active: false }, + }; + const selectionState = new TrackableDataSelectionState( + new WatchableValue(emptyInvalidCoordinateSpace), + layerSelectedValues as any, + ); + selectionState.location.visible = true; + const spatialSkeletonEditSession = new SpatialSkeletonEditSession(); + let confirmCreation: + | ((created: { nodeId: bigint; segmentId: bigint }) => void) + | undefined; + const client = { + baseUrl: "https://catmaid.example.test", + projectId: 1, + addNode: vi.fn( + () => + new Promise<{ nodeId: bigint; segmentId: bigint }>((resolve) => { + confirmCreation = resolve; + }), + ), + updateDescription: vi.fn(), + }; + const commands = new CatmaidSpatialSkeletonEditCommands({ + getClient: () => client as any, + }); + const source = { + editPlannerProvider: commands.editPlannerProvider, + addNodesCommand: commands.addNodesCommand, + editNodeDescriptionCommand: commands.editNodeDescriptionCommand, + edgeDirection: SkeletonEdgeDirection.CHILD_TO_PARENT, + getSkeletonManifest: async () => ({ fragmentKeys: [] }), + getSkeletonFragment: async () => ({ nodes: [], edges: [] }), + }; + const skeletonNodeAccess = new WatchableValue({ + getSegmentNodes: () => [], + parentsInferred: false, + nodesChanged: new NullarySignal(), + hasPickableNodes: false, + displayState: { transform: new WatchableValue(undefined) }, + }); + const spatiallyIndexedSkeletonLayer = new WatchableValue({ + fragmentSource: source, + editableSource: source, + getNode: (nodeId: bigint) => + spatialSkeletonEditSession.getCachedNode(nodeId), + remapOverlaySegments: vi.fn(), + retainOverlaySegment: vi.fn(), + }); + const segmentationGroupState = new WatchableValue({ + visibleSegments: new Uint64Set(), + temporaryVisibleSegments: new Uint64Set(), + selectedSegments: new Uint64OrderedSet(), + segmentEquivalences: { get: (id: bigint) => id }, + segmentPropertyMap: { value: undefined }, + }); + Object.defineProperties(layer, { + manager: { + value: { + layerSelectedValues, + root: { + selectionState, + globalPosition: new WatchableValue(new Float32Array(3)), + }, + }, + }, + managedLayer: { + value: { layerChanged: new NullarySignal(), name: "skeletons" }, + }, + isReady: { value: true }, + wasDisposed: { value: false }, + renderLayers: { value: [] }, + displayState: { value: { segmentationGroupState } }, + }); + const skeletonNodeSelection = new SkeletonNodeSelection({ + layer, + skeletonNodeAccess, + spatiallyIndexedSkeletonLayer, + spatialSkeletonEditSession, + }); + Object.assign(layer, { + spatialSkeletonEditSession, + skeletonNodeAccess, + skeletonNodeSelection, + skeletonSourceConnection: new SkeletonSourceConnection({ + spatialSkeletonEditSession, + selection: skeletonNodeSelection, + overlaySegments: new SkeletonOverlaySegments({ + segmentationGroupState: segmentationGroupState, + editSession: spatialSkeletonEditSession, + }), + segmentationGroupState, + skeletonNodeAccess, + spatiallyIndexedSkeletonLayer, + }), + }); + const panel = new SelectionDetailsPanel( + {} as any, + selectionState, + { globalPosition: new WatchableValue(new Float32Array(3)) } as any, + {} as any, + ); + document.body.appendChild(panel.element); + return { + layer, + panel, + client, + spatialSkeletonEditSession, + confirmCreation: (created: { nodeId: bigint; segmentId: bigint }) => + confirmCreation!(created), + }; + } + + function nextFrame() { + return new Promise((resolve) => requestAnimationFrame(resolve)); + } + + it("labels a selected new skeleton as Preview, without its provisional ID, until the server confirms it", async () => { + const { layer, panel, spatialSkeletonEditSession, confirmCreation } = + makeCreatingHostLayer(); + await executeSpatialSkeletonAddNode(layer.skeletonSourceConnection, { + skeletonId: 0n, + parentNodeId: undefined, + positionInModelSpace: new Float32Array([1, 2, 3]), + }); + const [provisionalNodeId] = + spatialSkeletonEditSession.spatialSkeletonDisplay.value + .provisionalNodeIds; + const provisionalSegmentId = + spatialSkeletonEditSession.getCachedNode(provisionalNodeId)!.segmentId; + layer.manager.root.selectionState.captureSingleLayerState( + layer, + (state: { value?: bigint }) => { + state.value = provisionalSegmentId; + return true; + }, + true, + ); + await nextFrame(); + await nextFrame(); + + expect(panel.element.textContent).toContain("Segment IDPreview"); + expect(panel.element.textContent).not.toContain(`${provisionalSegmentId}`); + + confirmCreation({ nodeId: 501n, segmentId: 77n }); + await vi.waitFor(() => + expect(panel.element.textContent).toContain("segment 77"), + ); + expect(panel.element.textContent).not.toContain("Preview"); + panel.dispose(); + panel.element.remove(); + spatialSkeletonEditSession.dispose(); + }); + + it("keeps a description being typed when the server gives its new node a permanent ID", async () => { + const { + layer, + panel, + client, + spatialSkeletonEditSession, + confirmCreation, + } = makeCreatingHostLayer(); + await executeSpatialSkeletonAddNode(layer.skeletonSourceConnection, { + skeletonId: 0n, + parentNodeId: undefined, + positionInModelSpace: new Float32Array([1, 2, 3]), + }); + const [provisionalNodeId] = + spatialSkeletonEditSession.spatialSkeletonDisplay.value + .provisionalNodeIds; + layer.skeletonNodeSelection.select(provisionalNodeId, true); + await nextFrame(); + const description = panel.element.querySelector("textarea")!; + description.focus(); + description.value = "unfinished draft"; + description.dispatchEvent(new Event("input")); + description.setSelectionRange(3, 3); + + confirmCreation({ nodeId: 501n, segmentId: 77n }); + await vi.waitFor(() => + expect(layer.skeletonNodeSelection.selected.value?.nodeId).toBe(501n), + ); + await nextFrame(); + + expect(description.isConnected).toBe(true); + expect(document.activeElement).toBe(description); + expect(description.value).toBe("unfinished draft"); + expect(description.selectionStart).toBe(3); + expect(client.updateDescription).not.toHaveBeenCalled(); + expect(panel.element.textContent).toContain("Node ID501"); + description.blur(); + panel.dispose(); + panel.element.remove(); + spatialSkeletonEditSession.dispose(); + }); +}); diff --git a/src/layer/segmentation/index.ts b/src/layer/segmentation/index.ts index 340f1c6800..8d66e5d064 100644 --- a/src/layer/segmentation/index.ts +++ b/src/layer/segmentation/index.ts @@ -23,7 +23,12 @@ import { LocalDataSource, localEquivalencesUrl, } from "#src/datasource/local.js"; -import type { LayerActionContext, ManagedUserLayer } from "#src/layer/index.js"; +import type { + LayerActionContext, + ManagedUserLayer, + MouseSelectionState, + UserLayerSelectionState, +} from "#src/layer/index.js"; import { LinkedLayerGroup, registerLayerType, @@ -35,6 +40,8 @@ import type { LoadedDataSubsource } from "#src/layer/layer_data_source.js"; import { layerDataSourceSpecificationFromJson } from "#src/layer/layer_data_source.js"; import * as json_keys from "#src/layer/segmentation/json_keys.js"; import { registerLayerControls } from "#src/layer/segmentation/layer_controls.js"; +import { SkeletonNodeSelection } from "#src/layer/segmentation/skeleton_node_selection.js"; +import { SkeletonSourceConnection } from "#src/layer/segmentation/skeleton_source_connection.js"; import { registerVoxelEditingLayerControls } from "#src/layer/voxel_editing/controls.js"; import { UserLayerWithVoxelEditingMixin } from "#src/layer/voxel_editing/index.js"; import { @@ -48,7 +55,15 @@ import { RenderScaleHistogram, trackableRenderScaleTarget, } from "#src/render_scale_statistics.js"; -import { getCssColor, SegmentColorHash } from "#src/segment_color.js"; +import type { RenderLayer } from "#src/renderlayer.js"; +import { + DEFAULT_USER_MAIN_SEGMENT_COLOR, + encodeSegmentPropertyShaderDefinition, + getCssColor, + SegmentColorHash, + SegmentColorUserShaderManager, +} from "#src/segment_color.js"; +import { getSegmentEquivalences } from "#src/segmentation_display_state/base.js"; import type { SegmentationColorGroupState, SegmentationDisplayState, @@ -57,7 +72,7 @@ import type { import { augmentSegmentId, bindSegmentListWidth, - getBaseObjectColor, + getBaseObjectColors, makeSegmentWidget, maybeAugmentSegmentId, registerCallbackWhenSegmentationDisplayStateChanged, @@ -78,12 +93,26 @@ import type { import { SegmentationGraphSourceTab } from "#src/segmentation_graph/source.js"; import { SharedDisjointUint64Sets } from "#src/shared_disjoint_sets.js"; import { SharedWatchableValue } from "#src/shared_watchable_value.js"; +import type { EditableSkeletonSource } from "#src/skeleton/api.js"; +import { SpatialSkeletonEditSession } from "#src/skeleton/edit/spatial_skeleton_edit_session.js"; +import { SkeletonDataSourceState } from "#src/skeleton/find_path/find_path.js"; +import { attachFindPath } from "#src/skeleton/find_path/find_path_attachment.js"; import { PerspectiveViewSkeletonLayer, SkeletonLayer, SkeletonRenderingOptions, SliceViewPanelSkeletonLayer, } from "#src/skeleton/frontend.js"; +import type { SkeletonNodeAccess } from "#src/skeleton/navigation.js"; +import { SkeletonBrowseState } from "#src/skeleton/node_attributes.js"; +import type { MultiscaleSpatiallyIndexedSkeletonSource } from "#src/skeleton/spatial/frontend.js"; +import { SkeletonOverlaySegments } from "#src/skeleton/spatial/overlay_segments.js"; +import { + PerspectiveViewSpatiallyIndexedSkeletonLayer, + SliceViewPanelSpatiallyIndexedSkeletonLayer, + SpatiallyIndexedSkeletonLayer, + type SpatiallyIndexedSkeletonLayerDisplayState, +} from "#src/skeleton/spatial/skeleton_render_layer.js"; import { DataType, VolumeType } from "#src/sliceview/volume/base.js"; import { MultiscaleVolumeChunkSource } from "#src/sliceview/volume/frontend.js"; import { SegmentationRenderLayer } from "#src/sliceview/volume/segmentation_renderlayer.js"; @@ -95,12 +124,13 @@ import type { WatchableValueInterface, } from "#src/trackable_value.js"; import { - registerNested, + AggregateWatchableValue, IndirectTrackableValue, IndirectWatchableValue, makeCachedDerivedWatchableValue, makeCachedLazyDerivedWatchableValue, observeWatchable, + registerNested, registerNestedSync, TrackableValue, WatchableValue, @@ -110,10 +140,18 @@ import { SegmentDisplayTab } from "#src/ui/segment_list.js"; import { registerSegmentSelectTools } from "#src/ui/segment_select_tools.js"; import { registerSegmentSplitMergeTools } from "#src/ui/segment_split_merge_tools.js"; import { DisplayOptionsTab } from "#src/ui/segmentation_display_options_tab.js"; +import { registerSpatialSkeletonEditTool } from "#src/ui/skeleton_edit_tools.js"; +import { registerSpatialSkeletonFindPathTool } from "#src/ui/skeleton_find_path_tool.js"; +import { + displayProvisionalSkeletonSegment, + displaySkeletonNodeSelection, +} from "#src/ui/skeleton_selection_details.js"; +import { registerSkeletonTabs } from "#src/ui/skeleton_tab.js"; import { registerVoxelEditingTools } from "#src/ui/voxel_editing.js"; import { Uint64Map } from "#src/uint64_map.js"; import { Uint64OrderedSet } from "#src/uint64_ordered_set.js"; import { Uint64Set } from "#src/uint64_set.js"; +import type { TypedArray } from "#src/util/array.js"; import { gatherUpdate } from "#src/util/array.js"; import { packColor, @@ -124,7 +162,8 @@ import { } from "#src/util/color.js"; import type { Borrowed, Owned } from "#src/util/disposable.js"; import { RefCounted } from "#src/util/disposable.js"; -import type { vec3, vec4 } from "#src/util/geom.js"; +import type { vec3 } from "#src/util/geom.js"; +import { vec4 } from "#src/util/geom.js"; import { parseArray, parseUint64, @@ -133,18 +172,71 @@ import { verifyOptionalObjectProperty, verifyString, } from "#src/util/json.js"; -import { Signal } from "#src/util/signal.js"; +import { NullarySignal, Signal } from "#src/util/signal.js"; import { SEGMENTATION_ERASE_SENTINEL, EMPTY_VOXEL_VALUE, type PaintValueGetter, } from "#src/voxel_editing/base.js"; import { VoxelEditingPreviewRenderLayerMixin } from "#src/voxel_editing/preview_render_layer.js"; -import { makeWatchableShaderError } from "#src/webgl/dynamic_shader.js"; +import { GLBuffer } from "#src/webgl/buffer.js"; +import type { WatchableShaderError } from "#src/webgl/dynamic_shader.js"; +import { + makeAggregateWatchableShaderError, + makeTrackableFragmentMain, + makeWatchableShaderError, + parameterizedEmitterDependentShaderGetter, +} from "#src/webgl/dynamic_shader.js"; +import { + FramebufferConfiguration, + makeTextureBuffers, +} from "#src/webgl/offscreen.js"; +import type { ShaderModule } from "#src/webgl/shader.js"; +import { + getFallbackBuilderState, + parseShaderUiControls, + ShaderControlState, + type ShaderDataContext, +} from "#src/webgl/shader_ui_controls.js"; import type { DependentViewContext } from "#src/widget/dependent_view_widget.js"; +import { DependentViewWidget } from "#src/widget/dependent_view_widget.js"; import { registerLayerShaderControlsTool } from "#src/widget/shader_controls.js"; const MAX_LAYER_BAR_UI_INDICATOR_COLORS = 6; +const MAX_LAYER_BAR_SEGMENTS_TO_CHECK = 10_000; +const emptySegmentColorShaderModule: ShaderModule = () => {}; + +export function getSegmentColorShaderDataContext( + segmentPropertyMap: PreprocessedSegmentPropertyMap | undefined, + isReady: boolean, +): ShaderDataContext | null { + if (!isReady) return null; + if (segmentPropertyMap === undefined) return {}; + const properties = new Map(); + const values = new Map>(); + for (const property of segmentPropertyMap.numericalProperties) { + properties.set(property.id, property.dataType); + values.set(property.id, property.values); + } + const getPropertyValueExpression = (property: string) => { + const identifier = + SegmentColorUserShaderManager.getNumericalPropertyShaderIdentifier( + segmentPropertyMap, + property, + ); + if (identifier === undefined) { + throw new Error(`Unknown numerical property: ${property}`); + } + return identifier; + }; + return { + properties, + values, + propertySource: "segment", + getPropertyValueExpression, + segmentPropertyMap, + }; +} export class SegmentationUserLayerGroupState extends RefCounted @@ -422,11 +514,22 @@ class LinkedSegmentationGroupState< } class SegmentationUserLayerDisplayState implements SegmentationDisplayState { + private getSegmentColorShader; + + segmentColorShaderControlState: ShaderControlState; + segmentationColorUserShader: SegmentColorUserShaderManager; + constructor(public layer: SegmentationUserLayer) { // Even though `SegmentationUserLayer` assigns this to its `displayState` property, redundantly // assign it here first in order to allow it to be accessed by `segmentationGroupState`. layer.displayState = this; + this.shaderError = makeAggregateWatchableShaderError(this.layer, [ + this.volumeShaderError, + this.meshShaderError, + this.offscreenShaderError, + ]); + this.linkedSegmentationGroup = layer.registerDisposer( new LinkedLayerGroup( layer.manager.rootLayers, @@ -531,8 +634,42 @@ class SegmentationUserLayerDisplayState implements SegmentationDisplayState { (group) => group.segmentPropertyMap, ), ); + + this.segmentColorShaderControlState = this.layer.registerDisposer( + new ShaderControlState( + this.fragmentSegmentColor, + makeCachedLazyDerivedWatchableValue( + getSegmentColorShaderDataContext, + this.segmentPropertyMap, + this.layer.isReadyWatchable, + ), + undefined, + {}, + DEFAULT_USER_MAIN_SEGMENT_COLOR, + ), + ); + + const gl = this.layer.manager.chunkManager.chunkQueueManager.gl; + this.segmentationColorUserShader = this.layer.registerDisposer( + new SegmentColorUserShaderManager(this, gl), + ); + this.segmentColorFramebuffer = this.layer.registerDisposer( + new FramebufferConfiguration(gl, { + colorBuffers: makeTextureBuffers(gl, 1), + }), + ); + this.segmentColorVertexArray = gl.createVertexArray(); + this.layer.registerDisposer(() => { + gl.deleteVertexArray(this.segmentColorVertexArray); + }); + this.segmentColorIdBuffer = this.layer.registerDisposer(new GLBuffer(gl)); + this.getSegmentColorShader = this.makeSegmentColorShaderGetter(); } + private segmentColorFramebuffer; + private segmentColorVertexArray; + private segmentColorIdBuffer; + segmentSelectionState = new SegmentSelectionState(); selectedAlpha = trackableAlphaValue(0.5); saturation = trackableAlphaValue(1.0); @@ -544,12 +681,25 @@ class SegmentationUserLayerDisplayState implements SegmentationDisplayState { 0, ); objectAlpha = trackableAlphaValue(1.0); + hiddenObjectAlpha = trackableAlphaValue(0.5); + spatialSkeletonSpacingTarget2d = trackableRenderScaleTarget(8); + spatialSkeletonSpacingTarget3d = trackableRenderScaleTarget(8); + spatialSkeletonSpacingHistogram2d = new RenderScaleHistogram(); + spatialSkeletonSpacingHistogram3d = new RenderScaleHistogram(); + skeletonBrowse = new SkeletonBrowseState(); ignoreNullVisibleSet = new TrackableBoolean(true, true); skeletonRenderingOptions = new SkeletonRenderingOptions(); - shaderError = makeWatchableShaderError(); + volumeShaderError = makeWatchableShaderError(); + meshShaderError = makeWatchableShaderError(); + offscreenShaderError = makeWatchableShaderError(); + shaderError: WatchableShaderError; + fragmentSegmentColor = makeTrackableFragmentMain( + DEFAULT_USER_MAIN_SEGMENT_COLOR, + ); + renderScaleHistogram = new RenderScaleHistogram(); renderScaleTarget = trackableRenderScaleTarget(1); - selectSegment: (id: bigint, pin: boolean | "toggle") => void; + selectSegment: SegmentationDisplayState["selectSegment"]; transparentPickEnabled: TrackableBoolean; baseSegmentColoring = new TrackableBoolean(false, false); baseSegmentHighlighting = new TrackableBoolean(false, false); @@ -562,6 +712,164 @@ class SegmentationUserLayerDisplayState implements SegmentationDisplayState { this.layer.moveToSegment(id); }; + makeSegmentColorShaderGetter = () => { + const parameters = this.layer.registerDisposer( + new AggregateWatchableValue(() => ({ + segmentColorParameters: + this.segmentationColorUserShader.shaderParameters, + segmentColorProperties: this.segmentationColorUserShader.usedProperties, + shaderBuilderState: this.segmentColorShaderControlState.builderState, + })), + ); + const fallbackParameters = new WatchableValue({ + segmentColorParameters: + this.segmentationColorUserShader.shaderParameters.value, + segmentColorProperties: [], + shaderBuilderState: getFallbackBuilderState( + parseShaderUiControls(DEFAULT_USER_MAIN_SEGMENT_COLOR), + ), + }); + return parameterizedEmitterDependentShaderGetter( + this.layer, + this.layer.manager.chunkManager.chunkQueueManager.gl, + { + memoizeKey: `segmentation/ColorShader`, + parameters, + fallbackParameters, + encodeParameters: (p) => { + return `${p.shaderBuilderState.key}/${JSON.stringify(p.segmentColorParameters)}/${JSON.stringify(p.segmentColorProperties.map(encodeSegmentPropertyShaderDefinition))}`; + }, + shaderError: this.layer.displayState.offscreenShaderError, + defineShader: ( + builder, + { segmentColorParameters, shaderBuilderState }, + ) => { + this.segmentationColorUserShader.defineShader( + builder, + /*fragment=*/ false, + shaderBuilderState, + segmentColorParameters, + ); + builder.addAttribute("highp uvec2", "aID"); + builder.addUniform("highp float", "uFramebufferWidth"); + builder.addVarying("highp vec4", "vColor"); + const vertexMain = ` +float x = 2.0 * (float(gl_VertexID) + 0.5) / uFramebufferWidth - 1.0; +gl_Position = vec4(x, 0.0, 0.0, 1.0); +gl_PointSize = 1.0; +vColor = segmentColorUserShader(uint64_t(aID)); +`; + builder.addVertexMain(vertexMain); + builder.addOutputBuffer("vec4", "out_fragColor", 0); + builder.setFragmentMain("out_fragColor = vColor;"); + }, + }, + ); + }; + + private tempColor = vec4.create(); + + getShaderBaseSegmentColors = ( + ids: readonly bigint[], + colors: Float32Array = new Float32Array(ids.length * 4), + ) => { + const numIds = ids.length; + if (colors.length < numIds * 4) { + throw new RangeError("Output color buffer is too small"); + } + if (numIds === 0) return colors; + const gl = this.layer.manager.chunkManager.chunkQueueManager.gl; + // The scissor or blend state of a panel that is drawing would return the previous lookup. + const scissorTestEnabled = gl.isEnabled(gl.SCISSOR_TEST); + const blendEnabled = gl.isEnabled(gl.BLEND); + gl.disable(gl.SCISSOR_TEST); + gl.disable(gl.BLEND); + try { + const { shader, parameters, fallback } = this.getSegmentColorShader( + emptySegmentColorShaderModule, + ); + if (shader === null) return; + const maxBatchSize = Math.min(numIds, gl.maxTextureSize); + this.segmentColorFramebuffer.bind(maxBatchSize, 1); + gl.bindVertexArray(this.segmentColorVertexArray); + shader.bind(); + gl.uniform1f(shader.uniform("uFramebufferWidth"), maxBatchSize); + + const idsData = new Uint32Array(maxBatchSize * 2); + this.segmentColorIdBuffer.bindToVertexAttribI(shader.attribute("aID"), 2); + try { + this.segmentationColorUserShader.enable( + gl, + shader, + parameters.shaderBuilderState, + { fallback, binding: this.layer }, + parameters.segmentColorParameters, + { + segmentDefaultColor: this.segmentDefaultColor.value, + segmentStatedColors: this.segmentStatedColors.value, + hoverHighlight: false, + }, + ); + const segmentEquivalences = getSegmentEquivalences( + this.segmentationGroupState.value, + ); + const baseSegmentColoring = this.baseSegmentColoring.value; + const data = new Uint8Array(4 * maxBatchSize); + for (let batchStart = 0; batchStart < numIds; ) { + const batchSize = Math.min(maxBatchSize, numIds - batchStart); + for (let i = 0; i < batchSize; ++i) { + const inputId = ids[batchStart + i]; + const id = baseSegmentColoring + ? inputId + : segmentEquivalences.get(inputId); + idsData[2 * i] = Number(id & 0xffffffffn); + idsData[2 * i + 1] = Number(id >> 32n); + } + this.segmentColorIdBuffer.setData( + idsData.subarray(0, batchSize * 2), + WebGL2RenderingContext.STREAM_DRAW, + ); + gl.drawArrays(gl.POINTS, 0, batchSize); + gl.readPixels( + 0, + 0, + batchSize, + 1, + WebGL2RenderingContext.RGBA, + WebGL2RenderingContext.UNSIGNED_BYTE, + data, + ); + const outputOffset = batchStart * 4; + for (let i = 0; i < batchSize * 4; ++i) { + colors[outputOffset + i] = data[i] / 255.0; + } + batchStart += batchSize; + } + } finally { + this.segmentationColorUserShader.disable( + gl, + shader, + parameters.segmentColorParameters, + ); + } + return colors; + } finally { + // UI color lookups run between render stages; release the bindings + // changed by this lookup before the next stage starts. + this.segmentColorFramebuffer.unbind(); + gl.useProgram(null); + gl.bindVertexArray(null); + gl.bindBuffer(gl.ARRAY_BUFFER, null); + if (scissorTestEnabled) gl.enable(gl.SCISSOR_TEST); + if (blendEnabled) gl.enable(gl.BLEND); + } + }; + + getShaderBaseSegmentColor = (id: bigint) => { + const colors = this.getShaderBaseSegmentColors([id], this.tempColor); + return colors === undefined ? undefined : this.tempColor; + }; + linkedSegmentationGroup: LinkedLayerGroup; linkedSegmentationColorGroup: LinkedLayerGroup; originalSegmentationGroupState: SegmentationUserLayerGroupState; @@ -590,6 +898,11 @@ interface SegmentationActionContext extends LayerActionContext { segmentationToggleSegmentState?: boolean | undefined; } +export interface SegmentationLayerSelectionState + extends UserLayerSelectionState { + nodeId: bigint | undefined; +} + class SegmentationPreviewRenderLayer extends VoxelEditingPreviewRenderLayerMixin( SegmentationRenderLayer, ) { @@ -599,10 +912,18 @@ const Base = UserLayerWithVoxelEditingMixin( UserLayerWithAnnotationsMixin(UserLayer), ); export class SegmentationUserLayer extends Base { + declare selectionState: SegmentationLayerSelectionState; + sliceViewRenderScaleHistogram = new RenderScaleHistogram(); voxelEditingPreviewRenderScaleHistogram = new RenderScaleHistogram(); sliceViewRenderScaleTarget = trackableRenderScaleTarget(1); codeVisible = new TrackableBoolean(true); + readonly spatialSkeletonEditSession = this.registerDisposer( + new SpatialSkeletonEditSession(), + ); + readonly skeletonNodeSelection: SkeletonNodeSelection; + readonly skeletonOverlaySegments: SkeletonOverlaySegments; + readonly skeletonSourceConnection: SkeletonSourceConnection; graphConnection = new WatchableValue< SegmentationGraphSourceConnection | undefined @@ -661,6 +982,12 @@ export class SegmentationUserLayer extends Base { }; displayState = new SegmentationUserLayerDisplayState(this); + readonly skeletonNodeAccess: WatchableValueInterface< + SkeletonNodeAccess | undefined + >; + readonly editableSkeletonSource: WatchableValueInterface< + EditableSkeletonSource | undefined + >; anchorSegment = new TrackableValue(undefined, (x) => x === undefined ? undefined : parseUint64(x), @@ -701,6 +1028,18 @@ export class SegmentationUserLayer extends Base { this.displayState.objectAlpha.changed.add( this.specificationChanged.dispatch, ); + this.displayState.hiddenObjectAlpha.changed.add( + this.specificationChanged.dispatch, + ); + this.displayState.skeletonBrowse.changed.add( + this.specificationChanged.dispatch, + ); + this.displayState.spatialSkeletonSpacingTarget2d.changed.add( + this.specificationChanged.dispatch, + ); + this.displayState.spatialSkeletonSpacingTarget3d.changed.add( + this.specificationChanged.dispatch, + ); this.displayState.hoverHighlight.changed.add( this.specificationChanged.dispatch, ); @@ -729,6 +1068,26 @@ export class SegmentationUserLayer extends Base { this.displayState.linkedSegmentationGroup.changed.add(() => this.updateDataSubsourceActivations(), ); + this.registerDisposer( + registerNestedSync((context, group) => { + context.registerDisposer( + group.segmentEquivalences.changed.add(() => { + if ( + this.editableSkeletonSource.value !== undefined && + this.displayState.linkedSegmentationGroup.root.value !== this + ) { + this.updateDataSubsourceActivations(); + } + }), + ); + }, this.displayState.segmentationGroupState), + ); + this.displayState.fragmentSegmentColor.changed.add( + this.specificationChanged.dispatch, + ); + this.displayState.segmentColorShaderControlState.changed.add( + this.specificationChanged.dispatch, + ); this.tabs.add("rendering", { label: "Render", order: -100, @@ -739,6 +1098,44 @@ export class SegmentationUserLayer extends Base { order: -50, getter: () => new SegmentDisplayTab(this), }); + this.skeletonNodeAccess = this.registerDisposer( + makeCachedLazyDerivedWatchableValue( + (_renderLayers: RenderLayer[]): SkeletonNodeAccess | undefined => + this.spatiallyIndexedSkeletonLayer.value ?? this.getSkeletonLayer(), + { changed: this.layersChanged, value: this.renderLayers }, + ), + ); + this.editableSkeletonSource = this.registerDisposer( + makeCachedDerivedWatchableValue( + (skeletonLayer) => skeletonLayer?.editableSource, + [this.spatiallyIndexedSkeletonLayer], + ), + ); + this.skeletonNodeSelection = this.registerDisposer( + new SkeletonNodeSelection({ + layer: this, + skeletonNodeAccess: this.skeletonNodeAccess, + spatiallyIndexedSkeletonLayer: this.spatiallyIndexedSkeletonLayer, + spatialSkeletonEditSession: this.spatialSkeletonEditSession, + }), + ); + this.skeletonOverlaySegments = this.registerDisposer( + new SkeletonOverlaySegments({ + segmentationGroupState: this.displayState.segmentationGroupState, + editSession: this.spatialSkeletonEditSession, + }), + ); + this.skeletonSourceConnection = this.registerDisposer( + new SkeletonSourceConnection({ + spatialSkeletonEditSession: this.spatialSkeletonEditSession, + selection: this.skeletonNodeSelection, + overlaySegments: this.skeletonOverlaySegments, + segmentationGroupState: this.displayState.segmentationGroupState, + skeletonNodeAccess: this.skeletonNodeAccess, + spatiallyIndexedSkeletonLayer: this.spatiallyIndexedSkeletonLayer, + }), + ); + registerSkeletonTabs(this); const hideGraphTab = this.registerDisposer( makeCachedDerivedWatchableValue( (x) => x === undefined, @@ -773,7 +1170,7 @@ export class SegmentationUserLayer extends Base { x instanceof MeshLayer || x instanceof MultiscaleMeshLayer || x instanceof PerspectiveViewSkeletonLayer || - x instanceof SliceViewPanelSkeletonLayer, + x instanceof PerspectiveViewSpatiallyIndexedSkeletonLayer, ), { changed: this.layersChanged, value: this.renderLayers }, ), @@ -781,30 +1178,123 @@ export class SegmentationUserLayer extends Base { readonly hasSkeletonsLayer = this.registerDisposer( makeCachedLazyDerivedWatchableValue( - (layers) => layers.some((x) => x instanceof PerspectiveViewSkeletonLayer), + (layers) => + layers.some( + (x) => + x instanceof PerspectiveViewSkeletonLayer || + x instanceof SliceViewPanelSkeletonLayer || + x instanceof PerspectiveViewSpatiallyIndexedSkeletonLayer || + x instanceof SliceViewPanelSpatiallyIndexedSkeletonLayer, + ), { changed: this.layersChanged, value: this.renderLayers }, ), ); + readonly spatiallyIndexedSkeletonLayer = this.registerDisposer( + makeCachedLazyDerivedWatchableValue( + (layers): SpatiallyIndexedSkeletonLayer | undefined => { + for (const layer of layers) { + if (layer instanceof PerspectiveViewSpatiallyIndexedSkeletonLayer) { + return layer.base; + } + } + return undefined; + }, + { changed: this.layersChanged, value: this.renderLayers }, + ), + ); + + readonly hasSpatiallyIndexedSkeletonsLayer = this.registerDisposer( + makeCachedDerivedWatchableValue( + (skeletonLayer) => skeletonLayer !== undefined, + [this.spatiallyIndexedSkeletonLayer], + ), + ); + readonly getSkeletonLayer = () => { for (const layer of this.renderLayers) { - if (layer instanceof PerspectiveViewSkeletonLayer) { + if ( + layer instanceof PerspectiveViewSkeletonLayer || + layer instanceof PerspectiveViewSpatiallyIndexedSkeletonLayer + ) { return layer.base; } } return undefined; }; + private makeSpatiallyIndexedSkeletonLayers( + loadedSubsource: LoadedDataSubsource, + source: MultiscaleSpatiallyIndexedSkeletonSource, + displayState: SpatiallyIndexedSkeletonLayerDisplayState & { + localPosition: WatchableValueInterface; + }, + options: { attachFindPath: boolean }, + ): void { + if (source.getLevelSpecs().length === 0) { + return; + } + // One base serves 2D and 3D panels so their edit state stays consistent. + const base = new SpatiallyIndexedSkeletonLayer({ + multiscaleSource: source, + displayState, + editSession: this.spatialSkeletonEditSession, + nodeSelection: this.skeletonNodeSelection, + overlaySegments: this.skeletonOverlaySegments, + }); + if (options.attachFindPath) { + attachFindPath(this, loadedSubsource, base); + } + loadedSubsource.addRenderLayer( + new PerspectiveViewSpatiallyIndexedSkeletonLayer(base.addRef()), + ); + loadedSubsource.addRenderLayer( + new SliceViewPanelSpatiallyIndexedSkeletonLayer( + /* transfer ownership */ base, + ), + ); + } + activateDataSubsources(subsources: Iterable) { + const loadedSubsources = [...subsources]; + const spatialSkeletonSubsource = loadedSubsources.find( + ({ subsourceEntry }) => + subsourceEntry.subsource.spatialSkeleton !== undefined, + ); + this.skeletonSourceConnection.sourceChanged( + spatialSkeletonSubsource?.subsourceEntry.subsource.spatialSkeleton, + ); + const hasEditableSpatialSkeletonSource = + spatialSkeletonSubsource?.subsourceEntry.subsource.spatialSkeleton + ?.editableSource !== undefined; + const { linkedSegmentationGroup } = this.displayState; + const linkedRoot = linkedSegmentationGroup.root.value; + if ( + hasEditableSpatialSkeletonSource && + linkedRoot !== this && + this.displayState.segmentationGroupState.value.segmentEquivalences.size > + 0 + ) { + StatusMessage.showTemporaryMessage( + `Unlinked ${this.managedLayer.name} from ${linkedRoot.managedLayer.name}: layers with editable skeletons do not support equivalences.`, + ); + linkedSegmentationGroup.isolate(); + return; + } const updatedSegmentPropertyMaps: SegmentPropertyMap[] = []; - const isGroupRoot = - this.displayState.linkedSegmentationGroup.root.value === this; + const isGroupRoot = linkedRoot === this; let updatedGraph: SegmentationGraphSource | undefined; let hasVolume = false; - for (const loadedSubsource of subsources) { + for (const loadedSubsource of loadedSubsources) { if (this.addStaticAnnotations(loadedSubsource)) continue; - const { volume, mesh, segmentPropertyMap, segmentationGraph, local } = - loadedSubsource.subsourceEntry.subsource; + const { + volume, + mesh, + spatialSkeleton, + segmentPropertyMap, + segmentationGraph, + local, + } = loadedSubsource.subsourceEntry.subsource; if (volume instanceof MultiscaleVolumeChunkSource) { switch (volume.dataType) { case DataType.FLOAT32: @@ -868,6 +1358,30 @@ export class SegmentationUserLayer extends Base { ); } }, this.displayState.segmentationGroupState.value); + } else if (spatialSkeleton !== undefined) { + if (loadedSubsource !== spatialSkeletonSubsource) { + loadedSubsource.deactivate( + "Only one spatially indexed skeleton source is supported", + ); + continue; + } + loadedSubsource.activate(() => { + const displayState = { + ...this.displayState, + transform: loadedSubsource.getRenderLayerTransform(), + localPosition: this.localPosition, + }; + this.makeSpatiallyIndexedSkeletonLayers( + loadedSubsource, + spatialSkeleton, + displayState, + { + attachFindPath: + loadedSubsource.loadedDataSource.dataSource.state instanceof + SkeletonDataSourceState, + }, + ); + }, this.displayState.segmentationGroupState.value); } else if (segmentPropertyMap !== undefined) { if (!isGroupRoot) { loadedSubsource.deactivate( @@ -917,6 +1431,8 @@ export class SegmentationUserLayer extends Base { loadedSubsource.deactivate( "Not supported on non-root linked segmentation layers", ); + } else if (hasEditableSpatialSkeletonSource) { + loadedSubsource.deactivate("Not supported with editable skeletons"); } else { if (updatedGraph !== undefined) { loadedSubsource.deactivate( @@ -939,6 +1455,9 @@ export class SegmentationUserLayer extends Base { loadedSubsource.deactivate("Not compatible with segmentation layer"); } } + if (hasEditableSpatialSkeletonSource && isGroupRoot) { + this.displayState.segmentationGroupState.value.segmentEquivalences.clear(); + } this.displayState.originalSegmentationGroupState.segmentPropertyMap.value = getPreprocessedSegmentPropertyMap( this.manager.chunkManager, @@ -1036,6 +1555,18 @@ export class SegmentationUserLayer extends Base { this.displayState.objectAlpha.restoreState( specification[json_keys.OBJECT_ALPHA_JSON_KEY], ); + this.displayState.hiddenObjectAlpha.restoreState( + specification[json_keys.HIDDEN_OPACITY_3D_JSON_KEY], + ); + this.displayState.skeletonBrowse.restoreState( + specification[json_keys.SKELETON_BROWSE_JSON_KEY], + ); + this.displayState.spatialSkeletonSpacingTarget2d.restoreState( + specification[json_keys.SKELETON_CROSS_SECTION_SPACING_JSON_KEY], + ); + this.displayState.spatialSkeletonSpacingTarget3d.restoreState( + specification[json_keys.SKELETON_PROJECTION_SPACING_JSON_KEY], + ); this.displayState.baseSegmentColoring.restoreState( specification[json_keys.BASE_SEGMENT_COLORING_JSON_KEY], ); @@ -1045,6 +1576,9 @@ export class SegmentationUserLayer extends Base { this.displayState.ignoreNullVisibleSet.restoreState( specification[json_keys.IGNORE_NULL_VISIBLE_SET_JSON_KEY], ); + this.displayState.fragmentSegmentColor.restoreState( + specification[json_keys.SEGMENT_COLOR_SHADER_JSON_KEY], + ); const { skeletonRenderingOptions } = this.displayState; skeletonRenderingOptions.restoreState( @@ -1054,7 +1588,9 @@ export class SegmentationUserLayer extends Base { if (skeletonShader !== undefined) { skeletonRenderingOptions.shader.restoreState(skeletonShader); } - this.codeVisible.restoreState(json_keys.SKELETON_CODE_VISIBLE_KEY); + this.codeVisible.restoreState( + specification[json_keys.SKELETON_CODE_VISIBLE_KEY], + ); this.displayState.renderScaleTarget.restoreState( specification[json_keys.MESH_RENDER_SCALE_JSON_KEY], ); @@ -1089,6 +1625,9 @@ export class SegmentationUserLayer extends Base { this.displayState.segmentationColorGroupState.value.restoreState( specification, ); + this.displayState.segmentColorShaderControlState.restoreState( + specification[json_keys.SHADER_CONTROLS_JSON_KEY], + ); } toJSON() { @@ -1099,6 +1638,14 @@ export class SegmentationUserLayer extends Base { this.displayState.notSelectedAlpha.toJSON(); x[json_keys.SATURATION_JSON_KEY] = this.displayState.saturation.toJSON(); x[json_keys.OBJECT_ALPHA_JSON_KEY] = this.displayState.objectAlpha.toJSON(); + x[json_keys.SKELETON_BROWSE_JSON_KEY] = + this.displayState.skeletonBrowse.toJSON(); + x[json_keys.HIDDEN_OPACITY_3D_JSON_KEY] = + this.displayState.hiddenObjectAlpha.toJSON(); + x[json_keys.SKELETON_CROSS_SECTION_SPACING_JSON_KEY] = + this.displayState.spatialSkeletonSpacingTarget2d.toJSON(); + x[json_keys.SKELETON_PROJECTION_SPACING_JSON_KEY] = + this.displayState.spatialSkeletonSpacingTarget3d.toJSON(); x[json_keys.HOVER_HIGHLIGHT_JSON_KEY] = this.displayState.hoverHighlight.toJSON(); x[json_keys.BASE_SEGMENT_COLORING_JSON_KEY] = @@ -1117,6 +1664,8 @@ export class SegmentationUserLayer extends Base { this.displayState.renderScaleTarget.toJSON(); x[json_keys.CROSS_SECTION_RENDER_SCALE_JSON_KEY] = this.sliceViewRenderScaleTarget.toJSON(); + x[json_keys.SEGMENT_COLOR_SHADER_JSON_KEY] = + this.displayState.fragmentSegmentColor.toJSON(); const { linkedSegmentationGroup, linkedSegmentationColorGroup } = this.displayState; @@ -1140,6 +1689,8 @@ export class SegmentationUserLayer extends Base { this.displayState.segmentationColorGroupState.value.toJSON(), ); } + x[json_keys.SHADER_CONTROLS_JSON_KEY] = + this.displayState.segmentColorShaderControlState.toJSON(); return x; } @@ -1150,6 +1701,16 @@ export class SegmentationUserLayer extends Base { return maybeAugmentSegmentId(this.displayState, value); } + getMissingAnnotationToolMessage() { + const editDisabledReason = + this.skeletonSourceConnection.getActionsDisabledReason(); + const layerName = JSON.stringify(this.managedLayer.name); + if (editDisabledReason === undefined) { + return `Activate the edit mode tool to place skeletons in layer ${layerName}`; + } + return `The selected layer (${layerName}) does not have an active annotation tool or support editable skeletons (${editDisabledReason}).`; + } + handleAction(action: string, context: SegmentationActionContext) { switch (action) { case "recolor": { @@ -1189,8 +1750,28 @@ export class SegmentationUserLayer extends Base { } } } + + initializeSelectionState(state: this["selectionState"]) { + super.initializeSelectionState(state); + this.skeletonNodeSelection.initializeSelectionState(state); + } + + resetSelectionState(state: this["selectionState"]) { + super.resetSelectionState(state); + this.skeletonNodeSelection.resetSelectionState(state); + } + + copySelectionState( + dest: this["selectionState"], + source: this["selectionState"], + ) { + super.copySelectionState(dest, source); + this.skeletonNodeSelection.copySelectionState(dest, source); + } + selectionStateFromJson(state: this["selectionState"], json: any) { super.selectionStateFromJson(state, json); + this.skeletonNodeSelection.restoreSelectionState(state, json); let { value } = state; if (typeof value === "number") value = value.toString(); try { @@ -1199,8 +1780,18 @@ export class SegmentationUserLayer extends Base { state.value = undefined; } } + + captureSelectionState( + state: this["selectionState"], + mouseState: MouseSelectionState, + ) { + super.captureSelectionState(state, mouseState); + this.skeletonNodeSelection.captureSelectionState(state, mouseState); + } + selectionStateToJson(state: this["selectionState"], forPython: boolean): any { const json = super.selectionStateToJson(state, forPython); + this.skeletonNodeSelection.writeSelectionState(state, json); const { value } = state; if (value instanceof Uint64MapEntry) { if (forPython) { @@ -1239,6 +1830,28 @@ export class SegmentationUserLayer extends Base { } else { return false; } + const segmentDisplayChanged = new NullarySignal(); + registerCallbackWhenSegmentationDisplayStateChanged( + this.displayState, + context, + () => segmentDisplayChanged.dispatch(), + ); + parent.appendChild( + context.registerDisposer( + new DependentViewWidget( + { value: id, changed: segmentDisplayChanged }, + (id, parent, context) => this.displaySegment(id, parent, context), + ), + ).element, + ); + return true; + } + + private displaySegment( + id: bigint, + parent: HTMLElement, + context: DependentViewContext, + ) { const { displayState } = this; const normalizedId = augmentSegmentId(displayState, id); const { @@ -1247,11 +1860,6 @@ export class SegmentationUserLayer extends Base { } = this.displayState.segmentationGroupState.value; const mapped = segmentEquivalences.get(id); const row = makeSegmentWidget(this.displayState, normalizedId); - registerCallbackWhenSegmentationDisplayStateChanged( - displayState, - context, - context.redraw, - ); context.registerDisposer(bindSegmentListWidth(displayState, row)); row.classList.add("neuroglancer-selection-details-segment"); parent.appendChild(row); @@ -1308,7 +1916,6 @@ export class SegmentationUserLayer extends Base { } } } - return true; } displaySelectionState( @@ -1316,7 +1923,12 @@ export class SegmentationUserLayer extends Base { parent: HTMLElement, context: DependentViewContext, ): boolean { - let displayed = this.displaySegmentationSelection(state, parent, context); + let displayed = + displayProvisionalSkeletonSegment(this, state, parent) || + this.displaySegmentationSelection(state, parent, context); + if (displaySkeletonNodeSelection(this, state, parent, context)) { + displayed = true; + } if (super.displaySelectionState(state, parent, context)) displayed = true; return displayed; } @@ -1333,7 +1945,7 @@ export class SegmentationUserLayer extends Base { const { rank, globalToRenderLayerDimensions } = transform; const { globalPosition } = this.manager.root; const globalLayerPosition = new Float32Array(rank); - const renderToGlobalLayerDimensions = []; + const renderToGlobalLayerDimensions: number[] = []; for (let i = 0; i < rank; i++) { renderToGlobalLayerDimensions[globalToRenderLayerDimensions[i]] = i; } @@ -1361,6 +1973,10 @@ export class SegmentationUserLayer extends Base { callback, this.displayState.segmentDefaultColor, ); + const shaderDisposer = observeWatchable( + callback, + this.displayState.fragmentSegmentColor, + ); const visibleSegmentDisposer = this.displayState.segmentationGroupState.value.visibleSegments.changed.add( callback, @@ -1375,6 +1991,7 @@ export class SegmentationUserLayer extends Base { return () => { disposer(); defaultColorDisposer(); + shaderDisposer(); visibleSegmentDisposer(); colorHashChangeDisposer(); showAllByDefaultDisposer(); @@ -1386,53 +2003,44 @@ export class SegmentationUserLayer extends Base { const { displayState } = this; const visibleSegmentsSet = displayState.segmentationGroupState.value.visibleSegments; - const fixedColor = displayState.segmentDefaultColor.value; - - const noVisibleSegments = visibleSegmentsSet.size === 0; - const tooManyVisibleSegments = - visibleSegmentsSet.size > MAX_LAYER_BAR_UI_INDICATOR_COLORS; - const hasMappedColors = - displayState.segmentationColorGroupState.value.segmentStatedColors.size > - 0; - const isFixedColorOnly = fixedColor !== undefined && !hasMappedColors; - const showAllByDefault = displayState.ignoreNullVisibleSet.value; - const hasVolume = displayState.hasVolume.value; - - if (noVisibleSegments) { - if (!showAllByDefault || !hasVolume) return []; // No segments visible - if (isFixedColorOnly) return [getCssColor(fixedColor)]; - return undefined; // Rainbow colors - } - if (isFixedColorOnly) { - return [getCssColor(fixedColor)]; // All segments show as one color + + if ( + visibleSegmentsSet.size === 0 && + (!displayState.ignoreNullVisibleSet.value || + !displayState.hasVolume.value) + ) { + return []; // No segments visible } - // Because manually mapped colors are not guaranteed to be unique, - // we need to actually check all the visible segments if - // manually mapped colors are used - if (!hasMappedColors && tooManyVisibleSegments) { - return undefined; // Too many segments to show + const defaultColor = displayState.segmentDefaultColor.value; + if ( + defaultColor !== undefined && + displayState.fragmentSegmentColor.value === + DEFAULT_USER_MAIN_SEGMENT_COLOR + ) { + return [getCssColor(defaultColor)]; } - const visibleSegments = [...visibleSegmentsSet]; - const colors = visibleSegments.map((id) => { - const color = getCssColor(getBaseObjectColor(displayState, id)); - return { color, id }; - }); + if (visibleSegmentsSet.size === 0) { + return undefined; // Rainbow colors + } - // Sort the colors by their segment ID - // Otherwise, the order is random which is a bit confusing in the UI - colors.sort((a, b) => { - const aId = a.id; - const bId = b.id; - return aId < bId ? -1 : aId > bId ? 1 : 0; - }); + const visibleSegments: bigint[] = []; + for (const id of visibleSegmentsSet) { + visibleSegments.push(id); + if (visibleSegments.length === MAX_LAYER_BAR_SEGMENTS_TO_CHECK) break; + } + visibleSegments.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)); - const uniqueColors = [...new Set(colors.map((color) => color.color))]; - if (uniqueColors.length > MAX_LAYER_BAR_UI_INDICATOR_COLORS) { + const baseColors = getBaseObjectColors(displayState, visibleSegments); + const uniqueColors = new Set(); + for (let i = 0; i < visibleSegments.length; ++i) { + uniqueColors.add(getCssColor(baseColors.subarray(4 * i, 4 * i + 4))); + } + if (uniqueColors.size > MAX_LAYER_BAR_UI_INDICATOR_COLORS) { return undefined; // Too many colors to show } - return uniqueColors; + return [...uniqueColors]; } static type = "segmentation"; @@ -1447,12 +2055,16 @@ registerVoxelEditingLayerControls(SegmentationUserLayer); registerLayerType(SegmentationUserLayer); registerVolumeLayerType(VolumeType.SEGMENTATION, SegmentationUserLayer); registerLayerTypeDetector((subsource) => { - if (subsource.mesh !== undefined) { + if (subsource.mesh !== undefined || subsource.spatialSkeleton !== undefined) { return { layerConstructor: SegmentationUserLayer, priority: 1 }; } return undefined; }); +registerLayerShaderControlsTool(SegmentationUserLayer, (layer) => ({ + shaderControlState: layer.displayState.segmentColorShaderControlState, +})); + registerLayerShaderControlsTool( SegmentationUserLayer, (layer) => ({ @@ -1462,5 +2074,7 @@ registerLayerShaderControlsTool( json_keys.SKELETON_RENDERING_SHADER_CONTROL_TOOL_ID, ); +registerSpatialSkeletonEditTool(SegmentationUserLayer); +registerSpatialSkeletonFindPathTool(SegmentationUserLayer); registerSegmentSplitMergeTools(SegmentationUserLayer); registerSegmentSelectTools(SegmentationUserLayer); diff --git a/src/layer/segmentation/json_keys.ts b/src/layer/segmentation/json_keys.ts index 47d603dab4..feb09bb70d 100644 --- a/src/layer/segmentation/json_keys.ts +++ b/src/layer/segmentation/json_keys.ts @@ -1,6 +1,10 @@ export const SELECTED_ALPHA_JSON_KEY = "selectedAlpha"; export const NOT_SELECTED_ALPHA_JSON_KEY = "notSelectedAlpha"; export const OBJECT_ALPHA_JSON_KEY = "objectAlpha"; +export const HIDDEN_OPACITY_3D_JSON_KEY = "hiddenObjectAlpha"; +export const SKELETON_CROSS_SECTION_SPACING_JSON_KEY = + "skeletonCrossSectionSpacing"; +export const SKELETON_PROJECTION_SPACING_JSON_KEY = "skeletonProjectionSpacing"; export const SATURATION_JSON_KEY = "saturation"; export const HOVER_HIGHLIGHT_JSON_KEY = "hoverHighlight"; export const HIDE_SEGMENT_ZERO_JSON_KEY = "hideSegmentZero"; @@ -14,10 +18,12 @@ export const COLOR_SEED_JSON_KEY = "colorSeed"; export const SEGMENT_STATED_COLORS_JSON_KEY = "segmentColors"; export const MESH_RENDER_SCALE_JSON_KEY = "meshRenderScale"; export const CROSS_SECTION_RENDER_SCALE_JSON_KEY = "crossSectionRenderScale"; +export const SEGMENT_COLOR_SHADER_JSON_KEY = "segmentColorShader"; export const SKELETON_RENDERING_JSON_KEY = "skeletonRendering"; export const SKELETON_SHADER_JSON_KEY = "skeletonShader"; export const SKELETON_CODE_VISIBLE_KEY = "codeVisible"; export const SEGMENT_QUERY_JSON_KEY = "segmentQuery"; +export const SKELETON_BROWSE_JSON_KEY = "skeletonBrowse"; export const MESH_SILHOUETTE_RENDERING_JSON_KEY = "meshSilhouetteRendering"; export const LINKED_SEGMENTATION_GROUP_JSON_KEY = "linkedSegmentationGroup"; export const LINKED_SEGMENTATION_COLOR_GROUP_JSON_KEY = @@ -26,3 +32,4 @@ export const SEGMENT_DEFAULT_COLOR_JSON_KEY = "segmentDefaultColor"; export const ANCHOR_SEGMENT_JSON_KEY = "anchorSegment"; export const SKELETON_RENDERING_SHADER_CONTROL_TOOL_ID = "skeletonShaderControl"; +export const SHADER_CONTROLS_JSON_KEY = "shaderControls"; diff --git a/src/layer/segmentation/layer_controls.ts b/src/layer/segmentation/layer_controls.ts index 8bcc268fa2..60448ef4de 100644 --- a/src/layer/segmentation/layer_controls.ts +++ b/src/layer/segmentation/layer_controls.ts @@ -5,12 +5,23 @@ import { registerLayerControl } from "#src/widget/layer_control.js"; import { checkboxLayerControl } from "#src/widget/layer_control_checkbox.js"; import { enumLayerControl } from "#src/widget/layer_control_enum.js"; import { rangeLayerControl } from "#src/widget/layer_control_range.js"; -import { renderScaleLayerControl } from "#src/widget/render_scale_widget.js"; +import { + RenderScaleWidget, + renderScaleLayerControl, +} from "#src/widget/render_scale_widget.js"; import { colorSeedLayerControl, fixedColorLayerControl, } from "#src/widget/segmentation_color_mode.js"; +class SkeletonSpacingRenderScaleWidget extends RenderScaleWidget { + protected formatSpatialScale(spatialScale: number) { + return spatialScale === 0 + ? "all nodes" + : super.formatSpatialScale(spatialScale); + } +} + export const LAYER_CONTROLS: LayerControlDefinition[] = [ { label: "Color seed", @@ -67,6 +78,34 @@ export const LAYER_CONTROLS: LayerControlDefinition[] = [ target: layer.displayState.renderScaleTarget, })), }, + { + label: "Spacing (cross section)", + toolJson: json_keys.SKELETON_CROSS_SECTION_SPACING_JSON_KEY, + isValid: (layer) => layer.hasSpatiallyIndexedSkeletonsLayer, + title: + "Select the node spacing for spatially indexed skeletons in cross-section views", + ...renderScaleLayerControl( + (layer) => ({ + histogram: layer.displayState.spatialSkeletonSpacingHistogram2d, + target: layer.displayState.spatialSkeletonSpacingTarget2d, + }), + SkeletonSpacingRenderScaleWidget, + ), + }, + { + label: "Spacing (projection)", + toolJson: json_keys.SKELETON_PROJECTION_SPACING_JSON_KEY, + isValid: (layer) => layer.hasSpatiallyIndexedSkeletonsLayer, + title: + "Select the node spacing for spatially indexed skeletons in projection views", + ...renderScaleLayerControl( + (layer) => ({ + histogram: layer.displayState.spatialSkeletonSpacingHistogram3d, + target: layer.displayState.spatialSkeletonSpacingTarget3d, + }), + SkeletonSpacingRenderScaleWidget, + ), + }, { label: "Opacity (3d)", toolJson: json_keys.OBJECT_ALPHA_JSON_KEY, @@ -76,6 +115,15 @@ export const LAYER_CONTROLS: LayerControlDefinition[] = [ value: layer.displayState.objectAlpha, })), }, + { + label: "Hidden Opacity (3d)", + toolJson: json_keys.HIDDEN_OPACITY_3D_JSON_KEY, + isValid: (layer) => layer.hasSpatiallyIndexedSkeletonsLayer, + title: "Opacity of hidden (non-visible) skeleton nodes in 3D views", + ...rangeLayerControl((layer) => ({ + value: layer.displayState.hiddenObjectAlpha, + })), + }, { label: "Silhouette (3d)", toolJson: json_keys.MESH_SILHOUETTE_RENDERING_JSON_KEY, diff --git a/src/layer/segmentation/rendering.md b/src/layer/segmentation/rendering.md new file mode 100644 index 0000000000..1631166170 --- /dev/null +++ b/src/layer/segmentation/rendering.md @@ -0,0 +1,141 @@ +# Segmentation rendering + +Segmentation rendering can be customized using GLSL shader code. The shader is +applied after Neuroglancer has determined the base segment color, including +explicit per-segment colors and the default segment color. + +## Shader language + +The shader code must conform to the OpenGL ES Shading Language (GLSL) version 3.0, specified at . + +You may find the WebGL reference card helpful: . + +## UI Controls + +[UI control directives](../sliceview/image_layer_rendering.md#ui-controls) are +supported. Segmentation shaders also support segment property controls: + +```glsl +#uicontrol property selectedTag(type="tag") +#uicontrol property selectedNumber(type="number") +#uicontrol property selectedString(type="string") +``` + +The `type` parameter filters the property picker. Valid values are `tag`, +`number`, `numerical`, and `string`. In shader code, a tag property control is a +`bool`; numerical property controls have the GLSL type corresponding to the +selected property data type; string property controls are string values and may +be compared with string literals. + +Numerical segment properties can also be used with `invlerp` controls: + +```glsl +#uicontrol invlerp intensity(property="size", range=[0, 100]) +``` + +If `property` is omitted, the control defaults to the first available numerical +segment property and the selected property may be changed from the UI. + +## API + +### Format of user shader + +The basic user shader is in the form of: + +```glsl +vec3 segmentColor(vec3 color, bool hasProperties, bool isStated) { + return color; +} +``` + +- `color` is the color that would be displayed if you chose not to override it. + It includes the segment color hash, the default segment color, or a stated + per-segment color. + +- `hasProperties` indicates that segment property data was found for the target + segment. Check this before relying on property values if your shader needs a + fallback for segments without property rows. + +- `isStated` indicates that `color` came from an explicit stated segment color. + +A `vec4` version of `segmentColor` can also be used to adjust opacity. The alpha +is multiplied by **Opacity (on)** or **Opacity (off)** in slice views. For +meshes and skeletons, it is multiplied by **Opacity (3d)**. + +```glsl +vec4 segmentColor(vec4 color, bool hasProperties, bool isStated) { + return color; +} +``` + +### Accessing segmentation properties + +To retrieve a numerical or string property named `myProperty`, use the syntax +`prop("myProperty")`. + +To check if a tag named `myTag` is enabled for a segment, use the syntax + +```glsl +if (tag("myTag")) { + // do something +} +``` + +The helper functions require a segment property map. If the named tag or +property does not exist, shader compilation reports an error. + +### Examples + +```glsl +#uicontrol invlerp property1(property="myNumericalProperty", window=[1, 10]) +vec4 segmentColor(vec4 color, bool hasProperties, bool isStated) { + if (!hasProperties) { + return vec4(0.5, 0.5, 0.5, 1.0); + } + if (isStated) { + return color; + } + vec4 newColor = vec4(0.0, 0.0, 0.0, 1.0); + newColor.rgb = colormapJet(property1()); + + if (tag("lot-of-axon")) { + return vec4(1.0, 1.0, 1.0, 1.0); + } + + newColor.a = 1.0; + + return newColor; +} +``` + +```glsl +#uicontrol property redTag(type="tag") +#uicontrol property size(type="number") +vec3 segmentColor(vec3 color, bool hasProperties, bool isStated) { + if (!hasProperties) { + return vec3(0.5); + } + if (redTag) { + return vec3(1.0, 0.0, 0.0); + } + if (size > 50u) { + return vec3(1.0, 1.0, 0.0); + } + return color.rgb; +} +``` + +```glsl +vec4 segmentColor(vec4 color, bool hasProperties, bool isStated) { + if (!hasProperties) { + return vec4(0.5, 0.5, 0.5, 1.0); + } + if (isStated) { + return color; + } + if (prop("NAis") > 10u) { + return vec4(1.0, 1.0, 1.0, 1.0); + } + return color; +} +``` diff --git a/src/layer/segmentation/segment_color_shader.browser_test.ts b/src/layer/segmentation/segment_color_shader.browser_test.ts new file mode 100644 index 0000000000..f9ba130986 --- /dev/null +++ b/src/layer/segmentation/segment_color_shader.browser_test.ts @@ -0,0 +1,1271 @@ +/** + * @license + * Copyright 2026 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { describe, it, expect, vi } from "vitest"; +import { DisplayContext } from "#src/display_context.js"; +import { makeLayer } from "#src/layer/index.js"; +import { + getSegmentColorShaderDataContext, + type SegmentationUserLayer, +} from "#src/layer/segmentation/index.js"; +import "#layer/segmentation"; +import { + type InlineSegmentPropertyMap, + PreprocessedSegmentPropertyMap, + SegmentPropertyMap, +} from "#src/segmentation_display_state/property_map.js"; +import type { SliceView } from "#src/sliceview/frontend.js"; +import { SegmentationRenderLayer } from "#src/sliceview/volume/segmentation_renderlayer.js"; +import { WatchableValue } from "#src/trackable_value.js"; +import { packColor } from "#src/util/color.js"; +import { DataType } from "#src/util/data_type.js"; +import { type Disposer, invokeDisposers } from "#src/util/disposable.js"; +import { vec3, vec4 } from "#src/util/geom.js"; +import { Viewer } from "#src/viewer.js"; +import { ShaderCompilationError } from "#src/webgl/shader.js"; +import { FragmentShaderTester } from "#src/webgl/shader_testing.js"; +import { + ShaderControlState, + type SegmentPropertyReference, + type ShaderDataContext, +} from "#src/webgl/shader_ui_controls.js"; +import { trivialColorShader } from "#src/webgl/trivial_shaders.js"; + +const setupSegmentationLayer = () => { + const target = document.createElement("div"); + const display = new DisplayContext(target); + const viewer = new Viewer(display); + return makeLayer(viewer.layerSpecification, "test", { type: "segmentation" }) + .layer! as SegmentationUserLayer; +}; + +const setSegmentPropertyMap = ( + segmentationUserLayer: SegmentationUserLayer, + inlineProperties: InlineSegmentPropertyMap, +) => { + segmentationUserLayer.displayState.segmentPropertyMap.value = + new PreprocessedSegmentPropertyMap( + new SegmentPropertyMap({ inlineProperties }), + ); +}; + +const setSegmentPropertyControl = ( + segmentationUserLayer: SegmentationUserLayer, + controlName: string, + value: SegmentPropertyReference, +) => { + const controlState = + segmentationUserLayer.displayState.segmentColorShaderControlState.state.get( + controlName, + ); + expect(controlState).toBeDefined(); + controlState!.trackable.value = value; +}; + +const compareWithCPUHash = ( + segmentationUserLayer: SegmentationUserLayer, + objectId: bigint, +) => { + const outColor = + segmentationUserLayer.displayState.getShaderBaseSegmentColor(objectId); + const colorGroupState = + segmentationUserLayer.displayState.segmentationColorGroupState.value; + const outColorCPU = vec4.create(); + colorGroupState.segmentColorHash.compute(outColorCPU, objectId); + outColorCPU[3] = 1.0; + expect(outColor).toBeDefined(); + expect(outColor!.length).toBe(4); + for (let i = 0; i < 4; ++i) { + expect(outColor![i]).toBeCloseTo(outColorCPU[i]); + } +}; + +expect.extend({ + toBeCloseToFoo(received: number[] | Float32Array, expected: number[]) { + if (received.length !== expected.length) { + return { + pass: false, + message: () => + `Expected array length ${expected.length} but received ${received.length}`, + }; + } + for (let i = 0; i < received.length; ++i) { + if (Math.abs(received[i] - expected[i]) > 1e-6) { + return { + pass: false, + message: () => + `Expected element ${i} to be close to ${expected[i]} but received ${received[i]}`, + }; + } + } + return { + pass: true, + message: () => "Arrays are close", + }; + }, +}); + +const expectColor = ( + color: vec4, + expected: [number, number, number, number], +) => { + expect(color).toBeDefined(); + expect(color!.length).toBe(4); + expect([...color]).toEqual(expected.map((x) => expect.closeTo(x))); +}; + +describe("segment-color active controls", () => { + const shaderWithControls = ` +#uicontrol bool useTint checkbox(default=false) +#uicontrol vec3 tint color +#uicontrol float gain slider(min=0, max=2, default=1) +vec3 segmentColor(vec3 color, bool hasProperties, bool isStated) { + return (useTint ? tint : color) * gain; +}`; + + it.each([false, true])( + "tracks slice shaders with fallback=%s", + (fallback) => { + const segmentationUserLayer = setupSegmentationLayer(); + const { displayState } = segmentationUserLayer; + displayState.fragmentSegmentColor.value = shaderWithControls; + const { segmentColorShaderControlState, segmentationColorUserShader } = + displayState; + const sourceControls = new Set(["useTint", "tint", "gain"]); + expect(segmentColorShaderControlState.activeControls.hint.value).toEqual( + sourceControls, + ); + const binding = { disposers: [] as Disposer[] }; + const gl = + segmentationUserLayer.manager.chunkManager.chunkQueueManager.gl; + const tester = new FragmentShaderTester(gl, {}, { outputValue: "float" }); + try { + const parameters = { + segmentColorParameters: + segmentationColorUserShader.shaderParameters.value, + segmentColorProperties: [], + shaderBuilderState: segmentColorShaderControlState.builderState.value, + hasEquivalences: false, + baseSegmentColoring: false, + baseSegmentHighlighting: false, + hideSegmentZero: false, + hasHighlightColor: false, + }; + segmentationColorUserShader.defineShader( + tester.builder, + true, + parameters.shaderBuilderState, + parameters.segmentColorParameters, + ); + tester.builder.addUniform("highp float", "uSelectedAlpha"); + tester.builder.addUniform("highp float", "uNotSelectedAlpha"); + tester.builder.addUniform("bool", "uShowAllSegments"); + tester.builder.setFragmentMain( + "outputValue = segmentColorUserShader(uint64_t(uvec2(1u, 0u))).r;", + ); + tester.build(); + tester.shader.bind(); + const layer = { + gl: tester.gl, + displayState, + segmentationGroupState: displayState.segmentationGroupState.value, + hashTableManager: { enable: vi.fn() }, + } as unknown as SegmentationRenderLayer; + const sliceView = { + visibleLayers: new Map([[layer, binding]]), + } as unknown as SliceView; + SegmentationRenderLayer.prototype.initializeShader.call( + layer, + sliceView, + tester.shader, + parameters, + fallback, + ); + expect( + segmentColorShaderControlState.activeControls.hint.value, + ).toEqual(fallback ? sourceControls : new Set(["useTint", "gain"])); + expect(binding.disposers).toHaveLength(fallback ? 0 : 1); + } finally { + invokeDisposers(binding.disposers); + tester.dispose(); + } + }, + ); + + it("tracks offscreen colors with the layer lifetime", () => { + const layer = setupSegmentationLayer(); + const { displayState } = layer; + displayState.fragmentSegmentColor.value = shaderWithControls; + const state = displayState.segmentColorShaderControlState; + const trackShader = vi.spyOn(state.activeControls, "trackShader"); + try { + expect(displayState.getShaderBaseSegmentColor(1n)).toBeDefined(); + expect(state.activeControls.hint.value).toEqual( + new Set(["useTint", "gain"]), + ); + expect(trackShader).toHaveBeenLastCalledWith( + { + shader: expect.anything(), + parameters: state.builderState.value, + fallback: false, + uniformPrefix: "u_segmentColorShaderControl_", + }, + layer, + ); + + state.state.get("useTint")!.trackable.value = true; + expect(displayState.getShaderBaseSegmentColor(1n)).toBeDefined(); + expect(state.activeControls.hint.value).toEqual( + new Set(["useTint", "tint", "gain"]), + ); + } finally { + trackShader.mockRestore(); + } + }); + + it("does not replace control hints with an offscreen fallback shader", () => { + const layer = setupSegmentationLayer(); + const { displayState } = layer; + displayState.fragmentSegmentColor.value = `${shaderWithControls}\n#error test fallback\n`; + const state = displayState.segmentColorShaderControlState; + const trackShader = vi.spyOn(state.activeControls, "trackShader"); + try { + expect(displayState.getShaderBaseSegmentColor(1n)).toBeDefined(); + expect(state.activeControls.hint.value).toEqual( + new Set(["useTint", "tint", "gain"]), + ); + expect(trackShader).toHaveBeenLastCalledWith( + expect.objectContaining({ fallback: true }), + layer, + ); + } finally { + trackShader.mockRestore(); + } + }); +}); + +describe("getShaderBaseSegmentColor", () => { + it.each(["property", "helper", "invlerp"])( + "updates %s shader dependencies when linking to another segmentation group", + (controlType) => { + const layer = setupSegmentationLayer(); + const otherLayer = makeLayer(layer.manager, "other", { + type: "segmentation", + }).layer! as SegmentationUserLayer; + const { displayState } = layer; + setSegmentPropertyMap(layer, { + ids: new BigUint64Array([1n]), + properties: [ + { + id: "foo", + type: "number", + dataType: DataType.FLOAT32, + values: new Float32Array([25]), + description: undefined, + bounds: [0, 100], + }, + ], + }); + setSegmentPropertyMap(otherLayer, { + ids: new BigUint64Array([1n]), + properties: [ + { + id: "bar", + type: "number", + dataType: DataType.FLOAT32, + values: new Float32Array([50]), + description: undefined, + bounds: [0, 100], + }, + { + id: "foo", + type: "number", + dataType: DataType.UINT8, + values: new Uint8Array([75]), + description: undefined, + bounds: [0, 100], + }, + ], + }); + const directive = + controlType === "property" + ? '#uicontrol property fooProperty(type="number")' + : controlType === "invlerp" + ? '#uicontrol invlerp normalized(property="foo", range=[0, 100])' + : ""; + const expression = + controlType === "property" + ? "float(fooProperty) / 100.0" + : controlType === "invlerp" + ? "normalized()" + : 'float(prop("foo")) / 100.0'; + displayState.fragmentSegmentColor.value = ` +${directive} +vec3 segmentColor(vec3 color, bool hasProperties, bool isStated) { + return vec3(${expression}, 0.0, 0.0); +}`; + if (controlType === "property") { + setSegmentPropertyControl(layer, "fooProperty", { + type: "numerical", + id: "foo", + }); + } + const { segmentationColorUserShader, segmentColorShaderControlState } = + displayState; + expect(segmentationColorUserShader.usedProperties.value).toEqual([ + { identifier: "numerical0", dataType: DataType.FLOAT32 }, + ]); + expectColor(displayState.getShaderBaseSegmentColor(1n)!, [0.25, 0, 0, 1]); + const previousBuilderState = + segmentColorShaderControlState.builderState.value; + + displayState.linkedSegmentationGroup.linkToLayer(otherLayer); + + expect(displayState.segmentationGroupState.value).toBe( + otherLayer.displayState.segmentationGroupState.value, + ); + expect(segmentationColorUserShader.usedProperties.value).toEqual([ + { identifier: "numerical1", dataType: DataType.UINT8 }, + ]); + if (controlType !== "helper") { + expect(segmentColorShaderControlState.builderState.value).not.toBe( + previousBuilderState, + ); + } + expectColor(displayState.getShaderBaseSegmentColor(1n)!, [0.75, 0, 0, 1]); + }, + ); + + it("restores property invlerp state after all property maps load", () => { + const makePropertyMap = (propertyIds: string[]) => + new PreprocessedSegmentPropertyMap( + new SegmentPropertyMap({ + inlineProperties: { + ids: new BigUint64Array([1n]), + properties: propertyIds.map((id) => ({ + id, + type: "number" as const, + dataType: DataType.FLOAT32, + values: new Float32Array([1]), + description: undefined, + bounds: [0, 10], + })), + }, + }), + ); + const partialPropertyMap = makePropertyMap(["first"]); + const completePropertyMap = makePropertyMap(["first", "second"]); + const dataContext = new WatchableValue( + getSegmentColorShaderDataContext(partialPropertyMap, false), + ); + const shaderControlState = new ShaderControlState( + new WatchableValue(` +#uicontrol invlerp normalized +vec3 segmentColor(vec3 color, bool hasProperties, bool isStated) { + return color; +}`), + dataContext, + ); + expect(dataContext.value).toBeNull(); + expect(shaderControlState.state.size).toBe(0); + const savedState = { + normalized: { + property: "second", + range: [2, 8], + window: [1, 9], + }, + }; + try { + shaderControlState.restoreState(savedState); + expect(shaderControlState.toJSON()).toEqual(savedState); + + dataContext.value = getSegmentColorShaderDataContext( + completePropertyMap, + true, + ); + + expect( + shaderControlState.state.get("normalized")!.trackable.value, + ).toEqual({ + property: "second", + dataType: DataType.FLOAT32, + range: [2, 8], + window: [1, 9], + }); + } finally { + shaderControlState.dispose(); + } + }); + + it("default shader, return hash", () => { + const segmentationUserLayer = setupSegmentationLayer(); + const objectId = 1n; + compareWithCPUHash(segmentationUserLayer, objectId); + }); + it("default shader, random segment id", () => { + const segmentationUserLayer = setupSegmentationLayer(); + const objectId = BigInt(Math.floor(Math.random() * 100000)); + compareWithCPUHash(segmentationUserLayer, objectId); + }); + it("red shader", () => { + const segmentationUserLayer = setupSegmentationLayer(); + segmentationUserLayer.displayState.fragmentSegmentColor.value = ` + vec3 segmentColor(vec3 color, bool hasProperties, bool isStated) { + return vec3(1.0, 0.0, 0.0); + }`; + const outColor = + segmentationUserLayer.displayState.getShaderBaseSegmentColor(1n); + expectColor(outColor!, [1.0, 0.0, 0.0, 1.0]); + }); + + it.each([ + "highp vec3 segmentColor", + "vec3 segmentColor ", + "vec3\nsegmentColor\n", + ])("supports %s declarations", (declaration) => { + const segmentationUserLayer = setupSegmentationLayer(); + segmentationUserLayer.displayState.fragmentSegmentColor.value = ` +${declaration}(vec3 color, bool hasProperties, bool isStated) { + return vec3(1.0, 0.0, 0.0); +}`; + + const outColor = + segmentationUserLayer.displayState.getShaderBaseSegmentColor(1n); + + expectColor(outColor!, [1.0, 0.0, 0.0, 1.0]); + }); + + it("alpha shader", () => { + const segmentationUserLayer = setupSegmentationLayer(); + segmentationUserLayer.displayState.fragmentSegmentColor.value = ` + vec4 segmentColor(vec4 color, bool hasProperties, bool isStated) { + return vec4(0.0, 0.0, 0.0, 0.5); + }`; + const outColor = + segmentationUserLayer.displayState.getShaderBaseSegmentColor(1n); + expectColor(outColor!, [0.0, 0.0, 0.0, 0.5]); + }); + + it("preserves alpha from mapped segment colors", () => { + const segmentationUserLayer = setupSegmentationLayer(); + segmentationUserLayer.displayState.segmentStatedColors.value.set( + 1n, + BigInt(packColor(vec4.fromValues(0.25, 0.5, 0.75, 0.5))), + ); + + expectColor( + segmentationUserLayer.displayState.getShaderBaseSegmentColor(1n)!, + [0.25, 0.5, 0.75, 128 / 255], + ); + }); + + it("uses the representative color for equivalent segments", () => { + const segmentationUserLayer = setupSegmentationLayer(); + const { displayState } = segmentationUserLayer; + displayState.segmentationGroupState.value.segmentEquivalences.link(1n, 2n); + displayState.segmentStatedColors.value.set( + 1n, + BigInt(packColor(vec3.fromValues(1.0, 0.0, 0.0))), + ); + displayState.segmentStatedColors.value.set( + 2n, + BigInt(packColor(vec3.fromValues(0.0, 1.0, 0.0))), + ); + + expectColor( + displayState.getShaderBaseSegmentColor(2n)!, + [1.0, 0.0, 0.0, 1.0], + ); + + displayState.baseSegmentColoring.value = true; + expectColor( + displayState.getShaderBaseSegmentColor(2n)!, + [0.0, 1.0, 0.0, 1.0], + ); + }); + + it("uses the identity alpha for rgb mapped segment colors", () => { + const segmentationUserLayer = setupSegmentationLayer(); + segmentationUserLayer.displayState.segmentStatedColors.value.set( + 1n, + BigInt(packColor(vec3.fromValues(1.0, 0.0, 0.0))), + ); + segmentationUserLayer.displayState.fragmentSegmentColor.value = ` + vec4 segmentColor(vec4 color, bool hasProperties, bool isStated) { + return color; + }`; + + expectColor( + segmentationUserLayer.displayState.getShaderBaseSegmentColor(1n)!, + [1.0, 0.0, 0.0, 1.0], + ); + }); + + it("gets multiple colors with a single framebuffer lookup", () => { + const segmentationUserLayer = setupSegmentationLayer(); + const { displayState } = segmentationUserLayer; + displayState.segmentStatedColors.value.set( + 1n, + BigInt(packColor(vec3.fromValues(1.0, 0.0, 0.0))), + ); + displayState.segmentStatedColors.value.set( + 2n, + BigInt(packColor(vec3.fromValues(0.0, 1.0, 0.0))), + ); + displayState.segmentDefaultColor.value = vec3.fromValues(0.0, 0.0, 1.0); + + const colors = displayState.getShaderBaseSegmentColors([1n, 2n, 3n])!; + expectColor(colors.subarray(0, 4) as vec4, [1.0, 0.0, 0.0, 1.0]); + expectColor(colors.subarray(4, 8) as vec4, [0.0, 1.0, 0.0, 1.0]); + expectColor(colors.subarray(8, 12) as vec4, [0.0, 0.0, 1.0, 1.0]); + }); + + it("rejects an undersized output color buffer", () => { + const segmentationUserLayer = setupSegmentationLayer(); + expect(() => + segmentationUserLayer.displayState.getShaderBaseSegmentColors( + [1n, 2n], + new Float32Array(7), + ), + ).toThrow(RangeError); + }); + + it("batches lookups that exceed the maximum framebuffer width", () => { + const segmentationUserLayer = setupSegmentationLayer(); + const { displayState } = segmentationUserLayer; + displayState.segmentStatedColors.value.set( + 1n, + BigInt(packColor(vec3.fromValues(1.0, 0.0, 0.0))), + ); + const gl = segmentationUserLayer.manager.chunkManager.chunkQueueManager.gl; + const ids = new Array(gl.maxTextureSize + 1).fill(1n); + + const colors = displayState.getShaderBaseSegmentColors(ids)!; + expectColor(colors.subarray(0, 4) as vec4, [1.0, 0.0, 0.0, 1.0]); + expectColor( + colors.subarray(colors.length - 4) as vec4, + [1.0, 0.0, 0.0, 1.0], + ); + }); + + it("returns the colour of the requested segment while a panel is drawing", () => { + const segmentationUserLayer = setupSegmentationLayer(); + const { displayState } = segmentationUserLayer; + displayState.segmentStatedColors.value.set( + 1n, + BigInt(packColor(vec3.fromValues(1.0, 0.0, 0.0))), + ); + displayState.segmentStatedColors.value.set( + 2n, + BigInt(packColor(vec3.fromValues(0.0, 0.0, 1.0))), + ); + const gl = segmentationUserLayer.manager.chunkManager.chunkQueueManager.gl; + displayState.getShaderBaseSegmentColor(1n); + gl.enable(gl.SCISSOR_TEST); + gl.scissor(10, 10, 20, 20); + gl.enable(gl.BLEND); + try { + expectColor( + displayState.getShaderBaseSegmentColor(2n)! as vec4, + [0.0, 0.0, 1.0, 1.0], + ); + expect(gl.isEnabled(gl.SCISSOR_TEST)).toBe(true); + expect(gl.isEnabled(gl.BLEND)).toBe(true); + } finally { + gl.disable(gl.SCISSOR_TEST); + gl.disable(gl.BLEND); + } + }); + + it("cleans up WebGL state owned by a framebuffer lookup", () => { + const segmentationUserLayer = setupSegmentationLayer(); + const { displayState } = segmentationUserLayer; + displayState.fragmentSegmentColor.value = ` +vec3 segmentColor(vec3 color, bool hasProperties, bool isStated) { + return vec3(1.0, 0.0, 0.0); +}`; + const gl = segmentationUserLayer.manager.chunkManager.chunkQueueManager.gl; + const initialDrawFramebuffer = gl.getParameter( + gl.DRAW_FRAMEBUFFER_BINDING, + ) as WebGLFramebuffer | null; + const initialReadFramebuffer = gl.getParameter( + gl.READ_FRAMEBUFFER_BINDING, + ) as WebGLFramebuffer | null; + const initialViewport = gl.getParameter(gl.VIEWPORT) as Int32Array; + const initialProgram = gl.getParameter( + gl.CURRENT_PROGRAM, + ) as WebGLProgram | null; + const initialVertexArray = gl.getParameter( + gl.VERTEX_ARRAY_BINDING, + ) as WebGLVertexArrayObject | null; + const initialArrayBuffer = gl.getParameter( + gl.ARRAY_BUFFER_BINDING, + ) as WebGLBuffer | null; + const initialActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE) as number; + const initialTextureBindings = new Array( + gl.maxTextureImageUnits, + ); + for (let i = 0; i < initialTextureBindings.length; ++i) { + gl.activeTexture(gl.TEXTURE0 + i); + initialTextureBindings[i] = gl.getParameter( + gl.TEXTURE_BINDING_2D, + ) as WebGLTexture | null; + } + + const drawFramebuffer = gl.createFramebuffer(); + const readFramebuffer = gl.createFramebuffer(); + const vertexArray = gl.createVertexArray(); + const arrayBuffer = gl.createBuffer(); + const textures = Array.from({ length: gl.maxTextureImageUnits }, () => + gl.createTexture(), + ); + const activeTexture = gl.TEXTURE0 + gl.maxTextureImageUnits - 1; + const markerShader = trivialColorShader(gl); + + try { + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, drawFramebuffer); + gl.bindFramebuffer(gl.READ_FRAMEBUFFER, readFramebuffer); + gl.viewport(7, 11, 13, 17); + markerShader.bind(); + gl.bindVertexArray(vertexArray); + gl.bindBuffer(gl.ARRAY_BUFFER, arrayBuffer); + for (let i = 0; i < textures.length; ++i) { + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, textures[i]); + } + gl.activeTexture(activeTexture); + + expectColor(displayState.getShaderBaseSegmentColor(1n)!, [1, 0, 0, 1]); + expect(gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING)).toBe(null); + expect(gl.getParameter(gl.READ_FRAMEBUFFER_BINDING)).toBe(null); + expect(gl.getParameter(gl.CURRENT_PROGRAM)).toBe(null); + expect(gl.getParameter(gl.VERTEX_ARRAY_BINDING)).toBe(null); + expect(gl.getParameter(gl.ARRAY_BUFFER_BINDING)).toBe(null); + expect(gl.getParameter(gl.ACTIVE_TEXTURE)).toBe(gl.TEXTURE0); + expect(gl.getParameter(gl.TEXTURE_BINDING_2D)).toBe(null); + gl.activeTexture(gl.TEXTURE1); + expect(gl.getParameter(gl.TEXTURE_BINDING_2D)).toBe(textures[1]); + gl.activeTexture(gl.TEXTURE0 + gl.tempTextureUnit); + expect(gl.getParameter(gl.TEXTURE_BINDING_2D)).toBe(null); + } finally { + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, initialDrawFramebuffer); + gl.bindFramebuffer(gl.READ_FRAMEBUFFER, initialReadFramebuffer); + gl.viewport( + initialViewport[0], + initialViewport[1], + initialViewport[2], + initialViewport[3], + ); + gl.useProgram(initialProgram); + gl.bindVertexArray(initialVertexArray); + gl.bindBuffer(gl.ARRAY_BUFFER, initialArrayBuffer); + for (let i = 0; i < initialTextureBindings.length; ++i) { + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, initialTextureBindings[i]); + } + gl.activeTexture(initialActiveTexture); + gl.deleteFramebuffer(drawFramebuffer); + gl.deleteFramebuffer(readFramebuffer); + gl.deleteVertexArray(vertexArray); + gl.deleteBuffer(arrayBuffer); + for (const texture of textures) gl.deleteTexture(texture); + } + }); + + it("does not apply hover highlighting to offscreen color lookups", () => { + const segmentationUserLayer = setupSegmentationLayer(); + segmentationUserLayer.displayState.segmentStatedColors.value.set( + 1n, + BigInt(packColor(vec3.fromValues(1.0, 0.0, 0.0))), + ); + segmentationUserLayer.displayState.segmentSelectionState.set(1n); + + expectColor( + segmentationUserLayer.displayState.getShaderBaseSegmentColor(1n)!, + [1.0, 0.0, 0.0, 1.0], + ); + }); + + it("uses the fallback shader if segment properties have not been loaded", () => { + const segmentationUserLayer = setupSegmentationLayer(); + segmentationUserLayer.displayState.fragmentSegmentColor.value = ` +#uicontrol property redTag(type="tag") + vec3 segmentColor(vec3 color, bool hasProperties, bool isStated) { + if (redTag) { + return vec3(1.0, 0.0, 0.0); + } + return vec3(0.0, 0.0, 0.0); + }`; + + expect( + segmentationUserLayer.displayState.getShaderBaseSegmentColor(1n), + ).toBeDefined(); + }); + + it("colors by string properties", () => { + const segmentationUserLayer = setupSegmentationLayer(); + setSegmentPropertyMap(segmentationUserLayer, { + ids: new BigUint64Array([1n, 2n]), + properties: [ + { + id: "color", + type: "string", + values: ["red", "green"], + }, + ], + }); + segmentationUserLayer.displayState.fragmentSegmentColor.value = ` +#uicontrol property colorProperty(type="string") + vec3 segmentColor(vec3 color, bool hasProperties, bool isStated) { + if (!hasProperties) { + return vec3(0.0, 0.0, 1.0); + } + if (colorProperty == "red") { + return vec3(1.0, 0.0, 0.0); + } + if (colorProperty == "green") { + return vec3(0.0, 1.0, 0.0); + } + return vec3(0.5, 0.5, 0.5); + }`; + setSegmentPropertyControl(segmentationUserLayer, "colorProperty", { + type: "string", + id: "color", + }); + expectColor( + segmentationUserLayer.displayState.getShaderBaseSegmentColor(1n)!, + [1.0, 0.0, 0.0, 1.0], + ); + expectColor( + segmentationUserLayer.displayState.getShaderBaseSegmentColor(2n)!, + [0.0, 1.0, 0.0, 1.0], + ); + expectColor( + segmentationUserLayer.displayState.getShaderBaseSegmentColor(3n)!, + [0.0, 0.0, 1.0, 1.0], + ); + }); + + it("colors by string literals with ids greater than 255", () => { + const segmentationUserLayer = setupSegmentationLayer(); + setSegmentPropertyMap(segmentationUserLayer, { + ids: new BigUint64Array([1n]), + properties: [ + { + id: "color", + type: "string", + values: ["target"], + }, + ], + }); + const precedingLiterals = Array.from( + { length: 256 }, + (_, index) => `"unused${index}"`, + ).join(" "); + segmentationUserLayer.displayState.fragmentSegmentColor.value = ` +#uicontrol property colorProperty(type="string") + /* ${precedingLiterals} */ + vec3 segmentColor(vec3 color, bool hasProperties, bool isStated) { + if (colorProperty == "target") { + return vec3(1.0, 0.0, 0.0); + } + return vec3(0.0, 0.0, 1.0); + }`; + setSegmentPropertyControl(segmentationUserLayer, "colorProperty", { + type: "string", + id: "color", + }); + expectColor( + segmentationUserLayer.displayState.getShaderBaseSegmentColor(1n)!, + [1.0, 0.0, 0.0, 1.0], + ); + }); + + it("defaults invalid string property control state", () => { + const segmentationUserLayer = setupSegmentationLayer(); + setSegmentPropertyMap(segmentationUserLayer, { + ids: new BigUint64Array([1n]), + properties: [ + { + id: "color", + type: "string", + values: ["red"], + }, + ], + }); + segmentationUserLayer.displayState.fragmentSegmentColor.value = ` +#uicontrol property colorProperty(type="string") + vec3 segmentColor(vec3 color, bool hasProperties, bool isStated) { + if (colorProperty == "red") { + return vec3(0.0, 1.0, 0.0); + } + return vec3(0.5, 0.5, 0.5); + }`; + const controlState = + segmentationUserLayer.displayState.segmentColorShaderControlState.state.get( + "colorProperty", + ); + expect(controlState).toBeDefined(); + controlState!.trackable.restoreState({ type: "string", id: "foo" }); + expect(controlState!.trackable.value).toEqual({ + type: "string", + id: "color", + }); + expectColor( + segmentationUserLayer.displayState.getShaderBaseSegmentColor(1n)!, + [0.0, 1.0, 0.0, 1.0], + ); + }); + + it("handles unmatched string property value", () => { + const segmentationUserLayer = setupSegmentationLayer(); + setSegmentPropertyMap(segmentationUserLayer, { + ids: new BigUint64Array([1n]), + properties: [ + { + id: "color", + type: "string", + values: ["foo"], + }, + ], + }); + segmentationUserLayer.displayState.fragmentSegmentColor.value = ` +#uicontrol property colorProperty(type="string") + vec3 segmentColor(vec3 color, bool hasProperties, bool isStated) { + if (colorProperty != "red") { + return vec3(0.0, 1.0, 0.0); + } + return vec3(0.5, 0.5, 0.5); + }`; + setSegmentPropertyControl(segmentationUserLayer, "colorProperty", { + type: "string", + id: "color", + }); + expectColor( + segmentationUserLayer.displayState.getShaderBaseSegmentColor(1n)!, + [0.0, 1.0, 0.0, 1.0], + ); + }); + + it("colors by tag", () => { + const segmentationUserLayer = setupSegmentationLayer(); + setSegmentPropertyMap(segmentationUserLayer, { + ids: new BigUint64Array([1n, 2n]), + properties: [ + { + id: "tag1", + type: "tags", + tags: ["red", "blue"], + tagDescriptions: ["red", "blue"], + values: ["\u0000", "\u0001"], + }, + ], + }); + segmentationUserLayer.displayState.fragmentSegmentColor.value = ` +#uicontrol property redTag(type="tag") +#uicontrol property blueTag(type="tag") +vec3 segmentColor(vec3 color, bool hasProperties, bool isStated) { + if (!hasProperties) { + return vec3(0.0, 1.0, 0.0); + } + if (redTag) { + return vec3(1.0, 0.0, 0.0); + } + if (blueTag) { + return vec3(0.0, 0.0, 1.0); + } + return vec3(0.3, 0.6, 0.9); +}`; + setSegmentPropertyControl(segmentationUserLayer, "redTag", { + type: "tag", + id: "red", + }); + setSegmentPropertyControl(segmentationUserLayer, "blueTag", { + type: "tag", + id: "blue", + }); + expectColor( + segmentationUserLayer.displayState.getShaderBaseSegmentColor(1n)!, + [1.0, 0.0, 0.0, 1.0], + ); + expectColor( + segmentationUserLayer.displayState.getShaderBaseSegmentColor(2n)!, + [0.0, 0.0, 1.0, 1.0], + ); + expectColor( + segmentationUserLayer.displayState.getShaderBaseSegmentColor(3n)!, + [0.0, 1.0, 0.0, 1.0], + ); + expectColor( + segmentationUserLayer.displayState.getShaderBaseSegmentColor(0n)!, + [0.0, 1.0, 0.0, 1.0], + ); + }); + + it("colors by tag helper", () => { + const segmentationUserLayer = setupSegmentationLayer(); + setSegmentPropertyMap(segmentationUserLayer, { + ids: new BigUint64Array([1n, 2n]), + properties: [ + { + id: "tag1", + type: "tags", + tags: ["red", "blue"], + tagDescriptions: ["red", "blue"], + values: ["\u0000", "\u0001"], + }, + ], + }); + segmentationUserLayer.displayState.fragmentSegmentColor.value = ` +vec3 segmentColor(vec3 color, bool hasProperties, bool isStated) { + if (!hasProperties) { + return vec3(0.0, 1.0, 0.0); + } + if (tag("red")) { + return vec3(1.0, 0.0, 0.0); + } + if (tag("blue")) { + return vec3(0.0, 0.0, 1.0); + } + return vec3(0.3, 0.6, 0.9); +}`; + expectColor( + segmentationUserLayer.displayState.getShaderBaseSegmentColor(1n)!, + [1.0, 0.0, 0.0, 1.0], + ); + expectColor( + segmentationUserLayer.displayState.getShaderBaseSegmentColor(2n)!, + [0.0, 0.0, 1.0, 1.0], + ); + expectColor( + segmentationUserLayer.displayState.getShaderBaseSegmentColor(3n)!, + [0.0, 1.0, 0.0, 1.0], + ); + }); + + it("reports shader error for missing tag helper", () => { + const segmentationUserLayer = setupSegmentationLayer(); + setSegmentPropertyMap(segmentationUserLayer, { + ids: new BigUint64Array([1n]), + properties: [ + { + id: "tag1", + type: "tags", + tags: ["red"], + tagDescriptions: ["red"], + values: ["\u0000"], + }, + ], + }); + segmentationUserLayer.displayState.fragmentSegmentColor.value = ` +vec3 segmentColor(vec3 color, bool hasProperties, bool isStated) { + if (tag("blue")) { + return vec3(0.0, 0.0, 1.0); + } + float otherError = missingValue; + return vec3(0.0, 0.0, 0.0); +}`; + expect( + segmentationUserLayer.displayState.getShaderBaseSegmentColor(1n), + ).toBeDefined(); + const shaderError = segmentationUserLayer.displayState.shaderError.value; + expect(shaderError).toBeInstanceOf(ShaderCompilationError); + expect(shaderError!.message).toContain( + `'tag("blue")' : tag does not exist`, + ); + expect(shaderError!.message).not.toContain( + `'' : 'tag("blue")' : tag does not exist`, + ); + expect(shaderError!.message).not.toContain( + "no matching overloaded function found", + ); + expect(shaderError!.message).toContain("missingValue"); + expect( + (shaderError as ShaderCompilationError).errorMessages.find((x) => + x.message.includes(`'tag("blue")' : tag does not exist`), + )?.line, + ).toBe(2); + expect( + (shaderError as ShaderCompilationError).errorMessages.find((x) => + x.message.includes("missingValue"), + )?.line, + ).toBe(5); + }); + + it("colors by numerical property uint8", () => { + const segmentationUserLayer = setupSegmentationLayer(); + setSegmentPropertyMap(segmentationUserLayer, { + ids: new BigUint64Array([1n, 2n]), + properties: [ + { + id: "prop1", + type: "number", + dataType: DataType.UINT8, + values: new Uint8Array([0, 50]), + description: "prop1", + bounds: [0, 100], + }, + ], + }); + + segmentationUserLayer.displayState.fragmentSegmentColor.value = ` +#uicontrol property prop1Property(type="number") +vec3 segmentColor(vec3 color, bool hasProperties, bool isStated) { + if (prop1Property == 50u) { + return vec3(1.0, 0.0, 0.0); + } + return vec3(0.0, 0.0, 0.0); +}`; + setSegmentPropertyControl(segmentationUserLayer, "prop1Property", { + type: "numerical", + id: "prop1", + }); + expectColor( + segmentationUserLayer.displayState.getShaderBaseSegmentColor(1n)!, + [0.0, 0.0, 0.0, 1.0], + ); + expectColor( + segmentationUserLayer.displayState.getShaderBaseSegmentColor(2n)!, + [1.0, 0.0, 0.0, 1.0], + ); + }); + + it("preserves integer and zero numerical property values", () => { + const segmentationUserLayer = setupSegmentationLayer(); + setSegmentPropertyMap(segmentationUserLayer, { + ids: new BigUint64Array([1n, 2n]), + properties: [ + { + id: "score", + type: "number", + dataType: DataType.UINT32, + description: undefined, + values: Uint32Array.of(4_000_000_001, 0), + bounds: [0, 4_000_000_001], + }, + ], + }); + segmentationUserLayer.displayState.fragmentSegmentColor.value = ` +#uicontrol property scoreProperty(type="number") +vec3 segmentColor(vec3 color, bool hasProperties, bool isStated) { + if (!hasProperties) return vec3(0.0, 0.0, 1.0); + if (scoreProperty == 4000000001u) return vec3(1.0, 0.0, 0.0); + if (scoreProperty == 0u) return vec3(0.0, 1.0, 0.0); + return vec3(0.0, 0.0, 0.0); +}`; + setSegmentPropertyControl(segmentationUserLayer, "scoreProperty", { + type: "numerical", + id: "score", + }); + + expectColor( + segmentationUserLayer.displayState.getShaderBaseSegmentColor(1n)!, + [1.0, 0.0, 0.0, 1.0], + ); + expectColor( + segmentationUserLayer.displayState.getShaderBaseSegmentColor(2n)!, + [0.0, 1.0, 0.0, 1.0], + ); + }); + + it("colors by numerical property helper", () => { + const segmentationUserLayer = setupSegmentationLayer(); + setSegmentPropertyMap(segmentationUserLayer, { + ids: new BigUint64Array([1n, 2n]), + properties: [ + { + id: "prop1", + type: "number", + dataType: DataType.UINT8, + values: new Uint8Array([0, 50]), + description: "prop1", + bounds: [0, 100], + }, + ], + }); + + segmentationUserLayer.displayState.fragmentSegmentColor.value = ` +vec3 segmentColor(vec3 color, bool hasProperties, bool isStated) { + if (prop("prop1") == 50u) { + return vec3(1.0, 0.0, 0.0); + } + return vec3(0.0, 0.0, 0.0); +}`; + expectColor( + segmentationUserLayer.displayState.getShaderBaseSegmentColor(1n)!, + [0.0, 0.0, 0.0, 1.0], + ); + expectColor( + segmentationUserLayer.displayState.getShaderBaseSegmentColor(2n)!, + [1.0, 0.0, 0.0, 1.0], + ); + }); + + it("reports shader error for missing property helper", () => { + const segmentationUserLayer = setupSegmentationLayer(); + setSegmentPropertyMap(segmentationUserLayer, { + ids: new BigUint64Array([1n]), + properties: [ + { + id: "prop1", + type: "number", + dataType: DataType.UINT8, + values: new Uint8Array([0]), + description: "prop1", + bounds: [0, 100], + }, + ], + }); + segmentationUserLayer.displayState.fragmentSegmentColor.value = ` +vec3 segmentColor(vec3 color, bool hasProperties, bool isStated) { + if (prop("prop2") == 50u) { + return vec3(1.0, 0.0, 0.0); + } + float otherError = missingValue; + return vec3(0.0, 0.0, 0.0); +}`; + expect( + segmentationUserLayer.displayState.getShaderBaseSegmentColor(1n), + ).toBeDefined(); + const shaderError = segmentationUserLayer.displayState.shaderError.value; + expect(shaderError).toBeInstanceOf(ShaderCompilationError); + expect(shaderError!.message).toContain( + `'prop("prop2")' : property does not exist`, + ); + expect(shaderError!.message).not.toContain( + `'' : 'prop("prop2")' : property does not exist`, + ); + expect(shaderError!.message).not.toContain( + "no matching overloaded function found", + ); + expect(shaderError!.message).toContain("missingValue"); + expect( + (shaderError as ShaderCompilationError).errorMessages.find((x) => + x.message.includes(`'prop("prop2")' : property does not exist`), + )?.line, + ).toBe(2); + expect( + (shaderError as ShaderCompilationError).errorMessages.find((x) => + x.message.includes("missingValue"), + )?.line, + ).toBe(5); + }); + + it("colors by string property helper", () => { + const segmentationUserLayer = setupSegmentationLayer(); + setSegmentPropertyMap(segmentationUserLayer, { + ids: new BigUint64Array([1n, 2n]), + properties: [ + { + id: "color", + type: "string", + values: ["red", "green"], + }, + ], + }); + segmentationUserLayer.displayState.fragmentSegmentColor.value = ` + vec3 segmentColor(vec3 color, bool hasProperties, bool isStated) { + if (!hasProperties) { + return vec3(0.0, 0.0, 1.0); + } + if (prop("color") == "red") { + return vec3(1.0, 0.0, 0.0); + } + if (prop("color") == "green") { + return vec3(0.0, 1.0, 0.0); + } + return vec3(0.5, 0.5, 0.5); + }`; + expectColor( + segmentationUserLayer.displayState.getShaderBaseSegmentColor(1n)!, + [1.0, 0.0, 0.0, 1.0], + ); + expectColor( + segmentationUserLayer.displayState.getShaderBaseSegmentColor(2n)!, + [0.0, 1.0, 0.0, 1.0], + ); + expectColor( + segmentationUserLayer.displayState.getShaderBaseSegmentColor(3n)!, + [0.0, 0.0, 1.0, 1.0], + ); + }); + + it("colors by numerical property invlerp", () => { + const segmentationUserLayer = setupSegmentationLayer(); + setSegmentPropertyMap(segmentationUserLayer, { + ids: new BigUint64Array([1n, 2n]), + properties: [ + { + id: "prop1", + type: "number", + dataType: DataType.UINT8, + values: new Uint8Array([0, 50]), + description: "prop1", + bounds: [0, 100], + }, + ], + }); + + segmentationUserLayer.displayState.fragmentSegmentColor.value = ` +#uicontrol invlerp normalized(property="prop1", range=[0, 100]) +vec3 segmentColor(vec3 color, bool hasProperties, bool isStated) { + return vec3(normalized(), 0.0, 0.0); +}`; + expectColor( + segmentationUserLayer.displayState.getShaderBaseSegmentColor(1n)!, + [0.0, 0.0, 0.0, 1.0], + ); + expectColor( + segmentationUserLayer.displayState.getShaderBaseSegmentColor(2n)!, + [0.5, 0.0, 0.0, 1.0], + ); + }); + + it("colors by numerical property float", () => { + const segmentationUserLayer = setupSegmentationLayer(); + setSegmentPropertyMap(segmentationUserLayer, { + ids: new BigUint64Array([1n, 2n]), + properties: [ + { + id: "prop1", + type: "number", + dataType: DataType.FLOAT32, + values: new Float32Array([0, 0.75]), + description: "prop1", + bounds: [0, 100], + }, + ], + }); + + segmentationUserLayer.displayState.fragmentSegmentColor.value = ` +#uicontrol property prop1Property(type="number") +vec3 segmentColor(vec3 color, bool hasProperties, bool isStated) { + return vec3(prop1Property, 0.0, 0.0); +}`; + setSegmentPropertyControl(segmentationUserLayer, "prop1Property", { + type: "numerical", + id: "prop1", + }); + expectColor( + segmentationUserLayer.displayState.getShaderBaseSegmentColor(1n)!, + [0.0, 0.0, 0.0, 1.0], + ); + expectColor( + segmentationUserLayer.displayState.getShaderBaseSegmentColor(2n)!, + [0.75, 0.0, 0.0, 1.0], + ); + }); +}); diff --git a/src/layer/segmentation/skeleton_node_selection.spec.ts b/src/layer/segmentation/skeleton_node_selection.spec.ts new file mode 100644 index 0000000000..fef3bc774a --- /dev/null +++ b/src/layer/segmentation/skeleton_node_selection.spec.ts @@ -0,0 +1,388 @@ +/** + * @license + * Copyright 2026 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { emptyInvalidCoordinateSpace } from "#src/coordinate_transform.js"; +import type { + LayerSelectedValues, + MouseSelectionState, + UserLayer, + UserLayerSelectionState, +} from "#src/layer/index.js"; +import { TrackableDataSelectionState } from "#src/layer/index.js"; +import type { SegmentationUserLayer } from "#src/layer/segmentation/index.js"; +import { + getSegmentIdFromLayerSelectionValue, + SkeletonHoverState, + SkeletonNodeSelection, +} from "#src/layer/segmentation/skeleton_node_selection.js"; +import type { RenderLayerTransform } from "#src/render_coordinate_transform.js"; +import { Uint64MapEntry } from "#src/segmentation_display_state/base.js"; +import type { SkeletonNode } from "#src/skeleton/api.js"; +import { SpatialSkeletonEditSession } from "#src/skeleton/edit/spatial_skeleton_edit_session.js"; +import { + SkeletonNavigation, + type SkeletonNodeAccess, +} from "#src/skeleton/navigation.js"; +import type { SpatiallyIndexedSkeletonLayer } from "#src/skeleton/spatial/skeleton_render_layer.js"; +import { StatusMessage } from "#src/status.js"; +import { WatchableValue } from "#src/trackable_value.js"; +import { NullarySignal } from "#src/util/signal.js"; + +describe("segment selection", () => { + it("reads the segment of a clicked segment that has a label", () => { + expect( + getSegmentIdFromLayerSelectionValue({ + value: new Uint64MapEntry(7n, undefined, "axon"), + }), + ).toBe(7n); + }); + + it("looks up the skeleton of the clicked segment, not its merged representative", () => { + expect( + getSegmentIdFromLayerSelectionValue({ + value: new Uint64MapEntry(7n, 3n), + }), + ).toBe(7n); + }); + + it("extracts the hovered node id only for matching render layers", () => { + // Create mock state, layers, and signal handlers + const renderLayerA = {}; + const renderLayerB = {}; + const layer = { renderLayers: [renderLayerA] }; + let mouseState: { + active: boolean; + pickedRenderLayer: unknown; + pickedSpatialSkeleton?: { nodeId?: unknown; segmentId?: unknown }; + } = { + active: false, + pickedRenderLayer: null, + pickedSpatialSkeleton: undefined, + }; + const handlers: Array<() => void> = []; + const layerSelectedValues = { + changed: { + add: (cb: () => void) => { + handlers.push(cb); + return () => true as boolean; + }, + }, + get mouseState() { + return mouseState; + }, + }; + const hoverState = new SkeletonHoverState(); + hoverState.bindTo( + layerSelectedValues as LayerSelectedValues, + layer as SegmentationUserLayer, + ); + const trigger = () => handlers.forEach((h) => h()); + + // A node id alone is not a usable hover: consumers derive the outline colour from the hovered + // segment, so both ids have to resolve before a hover is reported. + mouseState = { + active: true, + pickedRenderLayer: renderLayerA, + pickedSpatialSkeleton: { nodeId: 31n }, + }; + trigger(); + expect(hoverState.value).toBeUndefined(); + + mouseState = { + active: true, + pickedRenderLayer: renderLayerA, + pickedSpatialSkeleton: { nodeId: 31n, segmentId: 7n }, + }; + trigger(); + expect(hoverState.value).toEqual({ nodeId: 31n, segmentId: 7n }); + + mouseState = { + active: true, + pickedRenderLayer: renderLayerB, + pickedSpatialSkeleton: { nodeId: 31n }, + }; + trigger(); + expect(hoverState.value).toBeUndefined(); + + mouseState = { + active: false, + pickedRenderLayer: renderLayerA, + pickedSpatialSkeleton: { nodeId: 31n }, + }; + trigger(); + expect(hoverState.value).toBeUndefined(); + + mouseState = { + active: true, + pickedRenderLayer: renderLayerA, + pickedSpatialSkeleton: { nodeId: 0n }, + }; + trigger(); + expect(hoverState.value).toBeUndefined(); + + hoverState.dispose(); + }); +}); + +function makeIdentityTransform() { + return { + rank: 3, + modelToRenderLayerTransform: new Float32Array([ + 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, + ]), + globalToRenderLayerDimensions: [0, 1, 2], + error: undefined, + } as unknown as RenderLayerTransform; +} + +function makeSelectionHarness( + options: { loadedNodes?: readonly SkeletonNode[] } = {}, +) { + const loadedNodes = options.loadedNodes ?? []; + const layerSelectedValues = { + changed: new NullarySignal(), + mouseState: { active: false }, + } as unknown as LayerSelectedValues; + const selectionState = new TrackableDataSelectionState( + new WatchableValue(emptyInvalidCoordinateSpace), + layerSelectedValues, + ); + selectionState.location.visible = true; + const setLayerPosition = vi.fn(); + const renderLayer = {}; + const layer = { + manager: { + layerSelectedValues, + root: { + selectionState, + globalPosition: new WatchableValue(new Float32Array(3)), + }, + }, + renderLayers: [renderLayer], + initializeSelectionState(state: UserLayerSelectionState) { + state.value = undefined; + (state as { nodeId?: bigint }).nodeId = undefined; + }, + setLayerPosition, + } as unknown as UserLayer; + const skeletonNodeAccess = new WatchableValue( + { + getSegmentNodes: (segmentId) => + loadedNodes.filter((node) => node.segmentId === segmentId), + parentsInferred: false, + nodesChanged: new NullarySignal(), + hasPickableNodes: false, + displayState: { + transform: new WatchableValue(makeIdentityTransform()), + }, + }, + ); + const spatiallyIndexedSkeletonLayer = new WatchableValue({ + getNode: (nodeId: bigint) => + loadedNodes.find((node) => node.nodeId === nodeId), + } as unknown as SpatiallyIndexedSkeletonLayer); + const selection = new SkeletonNodeSelection({ + layer, + skeletonNodeAccess, + spatiallyIndexedSkeletonLayer, + spatialSkeletonEditSession: new SpatialSkeletonEditSession(), + }); + const readLayerEntry = () => + selectionState.value?.layers.find((entry) => entry.layer === layer) + ?.state as (UserLayerSelectionState & { nodeId?: bigint }) | undefined; + return { + selection, + selectionState, + setLayerPosition, + readLayerEntry, + }; +} + +function makeHints( + hints: { + nodeIdRemappings?: [bigint, bigint][]; + segmentIdRemappings?: [bigint, bigint][]; + } = {}, +) { + return { + nodeIdRemappings: new Map(hints.nodeIdRemappings), + segmentIdRemappings: new Map(hints.segmentIdRemappings), + segmentVisibility: [], + selectedNode: undefined, + }; +} + +describe("SkeletonNodeSelection", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("selecting a node shows it in the Selection panel with its skeleton and position", () => { + const { selection, selectionState, readLayerEntry } = makeSelectionHarness({ + loadedNodes: [ + { nodeId: 5n, segmentId: 1n, position: new Float32Array([4, 5, 6]) }, + ], + }); + + selection.select(5n, true); + + expect(readLayerEntry()).toMatchObject({ nodeId: 5n, value: 1n }); + expect(selectionState.pin.value).toBe(true); + expect(selectionState.value?.position).toEqual(new Float32Array([4, 5, 6])); + expect(selection.selected.value).toEqual({ + nodeId: 5n, + segmentId: 1n, + position: new Float32Array([4, 5, 6]), + }); + }); + + it("selecting a node that is not loaded keeps the last known position for the same node", () => { + const { selection } = makeSelectionHarness(); + + selection.select(5n, true, { segmentId: 1n, position: [1, 2, 3] }); + selection.select(5n, true, { segmentId: 1n }); + + expect(selection.selected.value?.position).toEqual( + new Float32Array([1, 2, 3]), + ); + }); + + it("clearing the selection removes the node from the Selection panel", () => { + const { selection, readLayerEntry } = makeSelectionHarness(); + selection.select(5n, true, { segmentId: 1n }); + + selection.clear(true); + + expect(readLayerEntry()?.nodeId).toBeUndefined(); + expect(selection.selected.value).toBeUndefined(); + }); + + it("a pinned node selection follows the node when the server renumbers it", () => { + const { selection, selectionState, readLayerEntry } = + makeSelectionHarness(); + selection.select(5n, true, { segmentId: 1n, position: [1, 2, 3] }); + + selection.applyPreviewUiHints(makeHints({ nodeIdRemappings: [[5n, 9n]] })); + + expect(readLayerEntry()?.nodeId).toBe(9n); + expect(selectionState.pin.value).toBe(true); + expect(selection.selected.value).toEqual({ + nodeId: 9n, + segmentId: 1n, + position: new Float32Array([1, 2, 3]), + }); + }); + + it("a pinned node selection moves to the surviving skeleton after a merge", () => { + const { selection, readLayerEntry } = makeSelectionHarness(); + selection.select(5n, true, { segmentId: 1n }); + + selection.applyPreviewUiHints( + makeHints({ segmentIdRemappings: [[1n, 2n]] }), + ); + + expect(readLayerEntry()?.value).toBe(2n); + expect(selection.selected.value?.segmentId).toBe(2n); + }); + + it("choosing a node in the Selection panel history restores that node as selected", () => { + const { selection, selectionState } = makeSelectionHarness(); + selection.select(5n, true, { segmentId: 1n }); + selection.select(6n, true, { segmentId: 1n }); + + selectionState.goBack(); + + expect(selection.selected.value?.nodeId).toBe(5n); + }); + + it("navigating to a parent selects it and moves the view to it", () => { + const { selection, setLayerPosition } = makeSelectionHarness({ + loadedNodes: [ + { nodeId: 1n, segmentId: 1n, position: new Float32Array([0, 0, 0]) }, + { + nodeId: 2n, + segmentId: 1n, + parentNodeId: 1n, + position: new Float32Array([10, 0, 0]), + }, + ], + }); + selection.select(2n, true); + + selection.navigate(SkeletonNavigation.PARENT); + + expect(selection.selected.value?.nodeId).toBe(1n); + expect(setLayerPosition).toHaveBeenCalledWith( + expect.anything(), + new Float32Array([0, 0, 0]), + ); + }); + + it("navigating when no node is selected reports why instead of moving the view", () => { + const { selection, setLayerPosition } = makeSelectionHarness(); + const showMessage = vi + .spyOn(StatusMessage, "showTemporaryMessage") + .mockReturnValue(undefined as unknown as StatusMessage); + + selection.navigate(SkeletonNavigation.PARENT); + + expect(showMessage).toHaveBeenCalledWith( + "No segment/skeleton is selected.", + ); + expect(setLayerPosition).not.toHaveBeenCalled(); + }); + + it("a saved state with a node selection restores the same node", () => { + const { selection } = makeSelectionHarness(); + const nodeIdAboveDoublePrecision = 2n ** 60n + 1n; + const savedJson: Record = {}; + selection.writeSelectionState( + { nodeId: nodeIdAboveDoublePrecision, value: 1n }, + savedJson, + ); + + const restoredState = { nodeId: undefined, value: undefined }; + selection.restoreSelectionState( + restoredState, + JSON.parse(JSON.stringify(savedJson)), + ); + + expect(restoredState.nodeId).toBe(nodeIdAboveDoublePrecision); + }); + + it("a saved state with an unreadable node id restores no node", () => { + const { selection } = makeSelectionHarness(); + const restoredState = { nodeId: 3n as bigint | undefined, value: "7" }; + + selection.restoreSelectionState(restoredState, { nodeId: "not-a-node" }); + + expect(restoredState.nodeId).toBeUndefined(); + }); + + it("picking a node in another layer leaves this layer's selection alone", () => { + const { selection } = makeSelectionHarness(); + const state = { nodeId: undefined, value: undefined }; + + selection.captureSelectionState(state, { + pickedRenderLayer: {}, + pickedSpatialSkeleton: { nodeId: 5n, segmentId: 1n }, + } as unknown as MouseSelectionState); + + expect(state).toEqual({ nodeId: undefined, value: undefined }); + }); +}); diff --git a/src/layer/segmentation/skeleton_node_selection.ts b/src/layer/segmentation/skeleton_node_selection.ts new file mode 100644 index 0000000000..5ab025d1ab --- /dev/null +++ b/src/layer/segmentation/skeleton_node_selection.ts @@ -0,0 +1,611 @@ +/** + * @license + * Copyright 2026 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file Tracks the hovered and selected skeleton node of a segmentation layer + * through the viewer's selection state. + */ + +import type { + LayerSelectedValues, + MouseSelectionState, + PickedSpatialSkeletonState, + UserLayer, + UserLayerSelectionState, +} from "#src/layer/index.js"; +import type { SegmentationLayerSelectionState } from "#src/layer/segmentation/index.js"; +import type { RenderLayerTransform } from "#src/render_coordinate_transform.js"; +import { Uint64MapEntry } from "#src/segmentation_display_state/base.js"; +import type { SkeletonNode } from "#src/skeleton/api.js"; +import type { SpatialSkeletonEditSession } from "#src/skeleton/edit/spatial_skeleton_edit_session.js"; +import type { + SpatialSkeletonPreviewSelectionPin, + SpatialSkeletonResolvedPreviewUiHints, +} from "#src/skeleton/edit_queue/preview_ui_hints.js"; +import { + type SkeletonNavigation, + SkeletonNavigator, + type SkeletonNodeAccess, +} from "#src/skeleton/navigation.js"; +import type { SpatiallyIndexedSkeletonLayer } from "#src/skeleton/spatial/skeleton_render_layer.js"; +import { StatusMessage } from "#src/status.js"; +import { + WatchableValue, + type WatchableValueInterface, +} from "#src/trackable_value.js"; +import { gatherUpdate } from "#src/util/array.js"; +import { RefCounted } from "#src/util/disposable.js"; +import { parseUint64, verifyOptionalObjectProperty } from "#src/util/json.js"; +import * as matrix from "#src/util/matrix.js"; +import { NullarySignal } from "#src/util/signal.js"; + +interface SkeletonViewerHoverMouseStateLike { + active: boolean; + pickedRenderLayer: TRenderLayer | null | undefined; + pickedSpatialSkeleton?: PickedSpatialSkeletonState; +} + +export interface SkeletonHoverInfo { + readonly nodeId: bigint; + // A hover is only reported once both ids resolve, so consumers (e.g. outline colouring, which + // derives from the hovered segment) can rely on the segment being known. + readonly segmentId: bigint; + // Model-space position of the picked node, carried so the highlight overlay can + // still be placed when the node's skeleton is not currently loaded/cached. + readonly position?: Float32Array; +} + +interface SkeletonViewerHoverLayerLike { + renderLayers: readonly TRenderLayer[]; +} + +function parseSelectionStateId(value: unknown) { + try { + return parseUint64(value); + } catch { + return undefined; + } +} + +// Node 0 is a valid node. +export function getNodeIdFromLayerSelectionState( + state: { nodeId?: unknown; value?: unknown } | undefined, +) { + const nodeId = state?.nodeId; + return typeof nodeId === "bigint" ? nodeId : undefined; +} + +// Segment 0 means no segment. +export function getSegmentIdFromLayerSelectionValue( + state: { nodeId?: unknown; value?: unknown } | undefined, +) { + const value = state?.value; + // A merged segment's members keep their own skeletons, so the picked id is the lookup key. + const segmentId = + value instanceof Uint64MapEntry ? value.key : parseSelectionStateId(value); + return segmentId === 0n ? undefined : segmentId; +} + +export function hasSkeletonNodeSelection( + state: { nodeId?: unknown; value?: unknown } | undefined, +) { + return getNodeIdFromLayerSelectionState(state) !== undefined; +} + +function getSkeletonHoverInfoFromViewerHover( + mouseState: SkeletonViewerHoverMouseStateLike, + layer: SkeletonViewerHoverLayerLike, +): SkeletonHoverInfo | undefined { + if (!mouseState.active) return undefined; + const { pickedRenderLayer } = mouseState; + if (pickedRenderLayer !== null) { + if ( + pickedRenderLayer === undefined || + !layer.renderLayers.includes(pickedRenderLayer) + ) { + return undefined; + } + } + const { pickedSpatialSkeleton } = mouseState; + const nodeId = pickedSpatialSkeleton?.nodeId; + if (nodeId === undefined) return undefined; + const segmentId = pickedSpatialSkeleton?.segmentId; + if (segmentId === undefined) return undefined; + return { nodeId, segmentId, position: pickedSpatialSkeleton?.position }; +} + +function positionsEqual( + a: Float32Array | undefined, + b: Float32Array | undefined, +) { + if (a === b) return true; + if (a === undefined || b === undefined || a.length !== b.length) return false; + for (let i = 0; i < a.length; ++i) if (a[i] !== b[i]) return false; + return true; +} + +function skeletonHoverInfoEqual( + a: SkeletonHoverInfo | undefined, + b: SkeletonHoverInfo | undefined, +) { + if (a === b) return true; + if (a === undefined || b === undefined) return false; + return ( + a.nodeId === b.nodeId && + a.segmentId === b.segmentId && + positionsEqual(a.position, b.position) + ); +} + +export class SkeletonHoverState extends RefCounted { + value: SkeletonHoverInfo | undefined = undefined; + readonly changed = new NullarySignal(); + + setValue(value: SkeletonHoverInfo | undefined) { + if (!skeletonHoverInfoEqual(this.value, value)) { + this.value = value; + this.changed.dispatch(); + } + } + + bindTo(layerSelectedValues: LayerSelectedValues, layer: UserLayer) { + this.registerDisposer( + layerSelectedValues.changed.add(() => { + this.setValue( + getSkeletonHoverInfoFromViewerHover( + layerSelectedValues.mouseState, + layer, + ), + ); + }), + ); + } +} + +export type SkeletonSelectionPin = boolean | "toggle" | "force-unpin"; + +export interface SelectedSkeletonNodeInfo { + readonly nodeId: bigint; + readonly segmentId?: bigint; + readonly position?: Float32Array; +} + +type SkeletonNodeSelectionState = Pick< + SegmentationLayerSelectionState, + "nodeId" | "value" +>; + +export interface SkeletonNodeSelectionOptions { + readonly layer: UserLayer; + readonly skeletonNodeAccess: WatchableValueInterface< + SkeletonNodeAccess | undefined + >; + readonly spatiallyIndexedSkeletonLayer: WatchableValueInterface< + SpatiallyIndexedSkeletonLayer | undefined + >; + readonly spatialSkeletonEditSession: SpatialSkeletonEditSession; +} + +export class SkeletonNodeSelection extends RefCounted { + readonly hovered = this.registerDisposer(new SkeletonHoverState()); + readonly navigator: SkeletonNavigator; + private readonly selectedValue = new WatchableValue< + SelectedSkeletonNodeInfo | undefined + >(undefined); + readonly selected: Readonly< + WatchableValueInterface + > = this.selectedValue; + private knownPosition: + | { readonly nodeId: bigint; readonly position: Float32Array } + | undefined; + + constructor(private readonly options: SkeletonNodeSelectionOptions) { + super(); + const { layer, spatialSkeletonEditSession } = options; + this.navigator = new SkeletonNavigator(options.skeletonNodeAccess); + this.hovered.bindTo(layer.manager.layerSelectedValues, layer); + const updateSelected = () => { + this.reconcileSegmentOwnership(); + this.updateSelected(); + }; + this.registerDisposer( + layer.manager.root.selectionState.changed.add(updateSelected), + ); + this.registerDisposer( + spatialSkeletonEditSession.nodeDataVersion.changed.add(updateSelected), + ); + updateSelected(); + } + + select( + nodeId: bigint, + pin: SkeletonSelectionPin = false, + node: { segmentId?: bigint; position?: ArrayLike } = {}, + ): void { + const loadedNode = this.findNode(nodeId); + const segmentId = undefinedIfZero(node.segmentId ?? loadedNode?.segmentId); + const position = + node.position ?? loadedNode?.position ?? this.getKnownPosition(nodeId); + if (position !== undefined) { + this.knownPosition = { nodeId, position: new Float32Array(position) }; + } + this.captureState( + (state) => { + state.nodeId = nodeId; + state.value = segmentId; + return true; + }, + pin, + this.toGlobalPosition(position), + ); + } + + clear(pin: SkeletonSelectionPin = false): void { + this.captureState((state) => { + state.nodeId = undefined; + state.value = undefined; + return true; + }, pin); + } + + navigate(navigation: SkeletonNavigation): void { + const selected = this.selected.value; + const result = this.navigator.navigate(navigation, { + segmentId: + getSegmentIdFromLayerSelectionValue(this.getLayerEntryState()) ?? + selected?.segmentId, + nodeId: selected?.nodeId, + }); + if (typeof result === "number") { + StatusMessage.showTemporaryMessage( + this.navigator.describeFailure(navigation, result), + ); + return; + } + this.selectAndMoveTo(result, true); + } + + moveViewTo(modelPosition: ArrayLike): void { + const transform = this.getRenderLayerTransform(); + if (transform === undefined) return; + this.options.layer.setLayerPosition( + transform, + transformModelPosition(transform, modelPosition), + ); + } + + toGlobalPosition( + modelPosition: ArrayLike | undefined, + ): Float32Array | undefined { + if (modelPosition === undefined) return undefined; + const transform = this.getRenderLayerTransform(); + if (transform === undefined) return undefined; + const globalPosition = + this.options.layer.manager.root.globalPosition.value.slice(); + gatherUpdate( + globalPosition, + transformModelPosition(transform, modelPosition), + transform.globalToRenderLayerDimensions, + ); + return globalPosition; + } + + applyPreviewUiHints( + hints: Pick< + SpatialSkeletonResolvedPreviewUiHints, + | "nodeIdRemappings" + | "segmentIdRemappings" + | "selectedNode" + | "segmentVisibility" + >, + ): void { + this.remapSelectionEntry(hints.nodeIdRemappings, hints.segmentIdRemappings); + const { selectionState } = this.options.layer.manager.root; + for (const visibility of hints.segmentVisibility) { + if (visibility.select === undefined) continue; + this.selectSegment( + visibility.segmentId, + resolveHintPin(visibility.select, selectionState.pin.value), + ); + } + const selectedNode = hints.selectedNode; + if (selectedNode === undefined) return; + if (selectedNode.kind === "clear") { + this.clear(selectionState.pin.value); + return; + } + if ( + selectedNode.kind === "refresh-if-selected" && + this.selected.value?.nodeId !== selectedNode.nodeId + ) { + return; + } + const cachedNode = this.options.spatialSkeletonEditSession.getCachedNode( + selectedNode.nodeId, + ); + const position = selectedNode.position ?? cachedNode?.position; + this.select( + selectedNode.nodeId, + resolveHintPin(selectedNode.pin, selectionState.pin.value), + { + segmentId: selectedNode.segmentId ?? cachedNode?.segmentId, + position, + }, + ); + if (selectedNode.moveView && position !== undefined) { + this.moveViewTo(position); + } + } + + initializeSelectionState(state: SkeletonNodeSelectionState): void { + state.nodeId = undefined; + } + + resetSelectionState(state: SkeletonNodeSelectionState): void { + state.nodeId = undefined; + } + + copySelectionState( + dest: SkeletonNodeSelectionState, + source: SkeletonNodeSelectionState, + ): void { + dest.nodeId = source.nodeId; + } + + restoreSelectionState(state: SkeletonNodeSelectionState, json: unknown) { + try { + state.nodeId = verifyOptionalObjectProperty(json, "nodeId", parseUint64); + } catch { + state.nodeId = undefined; + } + } + + writeSelectionState( + state: SkeletonNodeSelectionState, + json: Record, + ) { + if (state.nodeId !== undefined) { + json.nodeId = state.nodeId.toString(); + } + } + + captureSelectionState( + state: SkeletonNodeSelectionState, + mouseState: MouseSelectionState, + ): void { + const { pickedSpatialSkeleton, pickedRenderLayer } = mouseState; + if (pickedSpatialSkeleton === undefined) return; + if ( + pickedRenderLayer !== null && + !this.options.layer.renderLayers.includes(pickedRenderLayer) + ) { + return; + } + state.nodeId = undefinedIfZero(pickedSpatialSkeleton.nodeId); + const segmentId = undefinedIfZero(pickedSpatialSkeleton.segmentId); + if (segmentId !== undefined) { + state.value = segmentId; + } + } + + private selectAndMoveTo( + node: Pick | undefined, + pin: boolean | "toggle" = this.options.layer.manager.root.selectionState.pin + .value, + ): boolean { + if (node === undefined) { + this.clear(pin); + return false; + } + this.select(node.nodeId, pin, node); + this.moveViewTo(node.position); + return true; + } + + private selectSegment(segmentId: bigint, pin: SkeletonSelectionPin) { + this.options.layer.manager.root.selectionState.captureSingleLayerState( + this.options.layer, + (state) => { + state.value = segmentId; + return true; + }, + pin, + ); + } + + private captureState( + capture: (state: UserLayerSelectionState & { nodeId?: bigint }) => boolean, + pin: SkeletonSelectionPin, + globalPosition?: Float32Array, + ) { + const { layer } = this.options; + const { selectionState } = layer.manager.root; + if (pin === false && selectionState.pin.value) return; + const state = {} as UserLayerSelectionState; + layer.initializeSelectionState(state); + if (!capture(state)) return; + if (pin !== false) { + selectionState.location.visible = true; + if (pin === true) { + selectionState.pin.value = true; + } else if (pin === "toggle") { + selectionState.pin.value = !selectionState.pin.value; + } else { + selectionState.pin.value = false; + } + } + selectionState.value = { + layers: [{ layer, state }], + coordinateSpace: selectionState.coordinateSpace.value, + position: globalPosition, + }; + } + + private getLayerEntry() { + const { layer } = this.options; + return layer.manager.root.selectionState.value?.layers.find( + (entry) => entry.layer === layer, + ); + } + + private getLayerEntryState(): SkeletonNodeSelectionState | undefined { + return this.getLayerEntry()?.state as + | SkeletonNodeSelectionState + | undefined; + } + + private findNode(nodeId: bigint) { + return ( + this.options.spatiallyIndexedSkeletonLayer.value?.getNode(nodeId) ?? + this.options.spatialSkeletonEditSession.getCachedNode(nodeId) + ); + } + + private getKnownPosition(nodeId: bigint) { + const { knownPosition } = this; + return knownPosition?.nodeId === nodeId + ? knownPosition.position + : undefined; + } + + private getRenderLayerTransform() { + const transform = + this.options.skeletonNodeAccess.value?.displayState.transform.value; + if (transform === undefined || transform.error !== undefined) { + return undefined; + } + return transform; + } + + private updateSelected() { + const entryState = this.getLayerEntryState(); + const nodeId = getNodeIdFromLayerSelectionState(entryState); + if (nodeId === undefined) { + this.selectedValue.value = undefined; + return; + } + const segmentId = getSegmentIdFromLayerSelectionValue(entryState); + const loadedPosition = toFloat32Position(this.findNode(nodeId)?.position); + if (loadedPosition !== undefined) { + this.knownPosition = { nodeId, position: loadedPosition }; + } + const position = loadedPosition ?? this.getKnownPosition(nodeId); + const previous = this.selectedValue.value; + if ( + previous?.nodeId === nodeId && + previous.segmentId === segmentId && + positionsEqual(previous.position, position) + ) { + return; + } + this.selectedValue.value = { nodeId, segmentId, position }; + } + + // Merge, split and rollback can change a node's skeleton without an id remap. + private reconcileSegmentOwnership() { + const entry = this.getLayerEntry(); + const nodeId = getNodeIdFromLayerSelectionState(entry?.state); + if (entry === undefined || nodeId === undefined) return; + const node = + this.options.spatiallyIndexedSkeletonLayer.value === undefined + ? undefined + : this.findNode(nodeId); + if ( + node === undefined || + node.segmentId === getSegmentIdFromLayerSelectionValue(entry.state) + ) { + return; + } + this.replaceLayerEntryState({ value: node.segmentId }); + } + + private remapSelectionEntry( + nodeIdRemappings: ReadonlyMap, + segmentIdRemappings: ReadonlyMap, + ) { + const entryState = this.getLayerEntryState(); + const nodeId = getNodeIdFromLayerSelectionState(entryState); + const segmentId = getSegmentIdFromLayerSelectionValue(entryState); + const nextNodeId = + nodeId === undefined ? undefined : nodeIdRemappings.get(nodeId); + const nextSegmentId = + segmentId === undefined ? undefined : segmentIdRemappings.get(segmentId); + if (nextNodeId === undefined && nextSegmentId === undefined) return; + if (nextNodeId !== undefined) { + const position = this.getKnownPosition(nodeId!); + if (position !== undefined) { + this.knownPosition = { nodeId: nextNodeId, position }; + } + } + this.replaceLayerEntryState({ + ...(nextNodeId === undefined ? {} : { nodeId: nextNodeId }), + ...(nextSegmentId === undefined ? {} : { value: nextSegmentId }), + }); + } + + private replaceLayerEntryState(changes: Partial) { + const { layer } = this.options; + const { selectionState } = layer.manager.root; + const selection = selectionState.value; + if (selection === undefined) return; + selectionState.value = { + ...selection, + layers: selection.layers.map((entry) => + entry.layer === layer + ? { ...entry, state: { ...entry.state, ...changes } } + : entry, + ), + }; + } +} + +function toFloat32Position(position: ArrayLike | undefined) { + if (position === undefined || position instanceof Float32Array) { + return position; + } + return new Float32Array(position); +} + +function undefinedIfZero(value: bigint | undefined) { + return value === 0n ? undefined : value; +} + +function resolveHintPin( + pin: SpatialSkeletonPreviewSelectionPin, + currentPin: boolean, +): boolean | "force-unpin" { + return pin === "pin" ? true : pin === "unpin" ? "force-unpin" : currentPin; +} + +function transformModelPosition( + transform: RenderLayerTransform, + modelPosition: ArrayLike, +) { + const { rank } = transform; + const paddedModelPosition = new Float32Array(rank); + for (let i = 0; i < Math.min(modelPosition.length, rank); ++i) { + paddedModelPosition[i] = Number(modelPosition[i]); + } + const layerPosition = new Float32Array(rank); + matrix.transformPoint( + layerPosition, + transform.modelToRenderLayerTransform, + rank + 1, + paddedModelPosition, + rank, + ); + return layerPosition; +} diff --git a/src/layer/segmentation/skeleton_source_connection.spec.ts b/src/layer/segmentation/skeleton_source_connection.spec.ts new file mode 100644 index 0000000000..eb25e7e32d --- /dev/null +++ b/src/layer/segmentation/skeleton_source_connection.spec.ts @@ -0,0 +1,398 @@ +/** + * @license + * Copyright 2026 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { describe, expect, it, vi } from "vitest"; + +import { emptyInvalidCoordinateSpace } from "#src/coordinate_transform.js"; +import { CatmaidSpatialSkeletonEditCommands } from "#src/datasource/catmaid/spatial_skeleton_edit/command_factories.js"; +import type { + LayerSelectedValues, + UserLayer, + UserLayerSelectionState, +} from "#src/layer/index.js"; +import { TrackableDataSelectionState } from "#src/layer/index.js"; +import { SkeletonNodeSelection } from "#src/layer/segmentation/skeleton_node_selection.js"; +import { SkeletonSourceConnection } from "#src/layer/segmentation/skeleton_source_connection.js"; +import type { SegmentationGroupState } from "#src/segmentation_display_state/frontend.js"; +import { SkeletonEdgeDirection, type SkeletonNode } from "#src/skeleton/api.js"; +import { SpatialSkeletonActions } from "#src/skeleton/edit/edit_commands.js"; +import { SpatialSkeletonEditSession } from "#src/skeleton/edit/spatial_skeleton_edit_session.js"; +import { executeSpatialSkeletonDeleteNode } from "#src/skeleton/edit/submit_edits.js"; +import type { SpatialSkeletonResolvedPreviewUiHints } from "#src/skeleton/edit_queue/preview_ui_hints.js"; +import { SkeletonFindPathState } from "#src/skeleton/find_path/find_path.js"; +import type { SkeletonNodeAccess } from "#src/skeleton/navigation.js"; +import type { MultiscaleSpatiallyIndexedSkeletonSource } from "#src/skeleton/spatial/frontend.js"; +import type { SkeletonOverlaySegments } from "#src/skeleton/spatial/overlay_segments.js"; +import type { SpatiallyIndexedSkeletonLayer } from "#src/skeleton/spatial/skeleton_render_layer.js"; +import { WatchableValue } from "#src/trackable_value.js"; +import { Uint64OrderedSet } from "#src/uint64_ordered_set.js"; +import { Uint64Set } from "#src/uint64_set.js"; +import { RefCounted } from "#src/util/disposable.js"; +import { HttpError } from "#src/util/http_request.js"; +import { NullarySignal } from "#src/util/signal.js"; + +function makeEditableSource( + options: { omitReroot?: boolean } = {}, +): Record { + const commands = new CatmaidSpatialSkeletonEditCommands({ + getClient: () => ({}) as any, + }); + return { + editPlannerProvider: commands.editPlannerProvider, + addNodesCommand: commands.addNodesCommand, + deleteNodesCommand: commands.deleteNodesCommand, + ...(options.omitReroot ? {} : { rerootCommand: commands.rerootCommand }), + }; +} + +function makeSkeletonLayer(editableSource: unknown) { + return { + editableSource, + getNode: () => undefined, + } as unknown as SpatiallyIndexedSkeletonLayer; +} + +function makeDeletingSkeletonLayer( + getCachedNode: (nodeId: bigint) => SkeletonNode | undefined, +) { + const client = { + baseUrl: "https://catmaid.example.test", + projectId: 1, + deleteNode: vi.fn(), + }; + const commands = new CatmaidSpatialSkeletonEditCommands({ + getClient: () => client as any, + }); + const source = { + editPlannerProvider: commands.editPlannerProvider, + deleteNodesCommand: commands.deleteNodesCommand, + edgeDirection: SkeletonEdgeDirection.CHILD_TO_PARENT, + getSkeletonManifest: async () => ({ fragmentKeys: [] }), + getSkeletonFragment: async () => ({ nodes: [], edges: [] }), + }; + const skeletonLayer = { + fragmentSource: source, + editableSource: source, + getNode: (nodeId: bigint) => getCachedNode(nodeId), + } as unknown as SpatiallyIndexedSkeletonLayer; + return { skeletonLayer, client }; +} + +function makeConnection( + options: { + skeletonLayer?: SpatiallyIndexedSkeletonLayer; + spatialSkeletonEditSession?: SpatialSkeletonEditSession; + } = {}, +) { + const spatialSkeletonEditSession = + options.spatialSkeletonEditSession ?? new SpatialSkeletonEditSession(); + const layerSelectedValues = { + changed: new NullarySignal(), + mouseState: { active: false }, + } as unknown as LayerSelectedValues; + const selectionState = new TrackableDataSelectionState( + new WatchableValue(emptyInvalidCoordinateSpace), + layerSelectedValues, + ); + selectionState.location.visible = true; + const layer = { + manager: { + layerSelectedValues, + root: { + selectionState, + globalPosition: new WatchableValue(new Float32Array(3)), + }, + }, + renderLayers: [], + initializeSelectionState(state: UserLayerSelectionState) { + state.value = undefined; + (state as { nodeId?: bigint }).nodeId = undefined; + }, + setLayerPosition: vi.fn(), + } as unknown as UserLayer; + const skeletonNodeAccess = new WatchableValue( + { + getSegmentNodes: () => [], + parentsInferred: false, + nodesChanged: new NullarySignal(), + hasPickableNodes: false, + displayState: { transform: new WatchableValue(undefined as any) }, + }, + ); + const spatiallyIndexedSkeletonLayer = new WatchableValue< + SpatiallyIndexedSkeletonLayer | undefined + >(options.skeletonLayer); + const selection = new SkeletonNodeSelection({ + layer, + skeletonNodeAccess, + spatiallyIndexedSkeletonLayer, + spatialSkeletonEditSession, + }); + const group = { + visibleSegments: new Uint64Set(), + temporaryVisibleSegments: new Uint64Set(), + selectedSegments: new Uint64OrderedSet(), + }; + const overlaySegments = { + remap: vi.fn(), + retain: vi.fn(), + clear: vi.fn(), + } as unknown as SkeletonOverlaySegments; + const connection = new SkeletonSourceConnection({ + spatialSkeletonEditSession, + selection, + overlaySegments, + segmentationGroupState: new WatchableValue( + group as unknown as SegmentationGroupState, + ), + skeletonNodeAccess, + spatiallyIndexedSkeletonLayer, + }); + return { + connection, + overlaySegments, + spatialSkeletonEditSession, + selection, + selectionState, + layer, + group, + }; +} + +function makeHints( + hints: Partial, +): SpatialSkeletonResolvedPreviewUiHints { + return { + nodeIdRemappings: new Map(), + segmentIdRemappings: new Map(), + segmentVisibility: [], + retainSegmentIds: [], + selectedNode: undefined, + ...hints, + } as SpatialSkeletonResolvedPreviewUiHints; +} + +describe("SkeletonSourceConnection", () => { + it("edit actions are unavailable while the page needs a reload", () => { + const { connection, spatialSkeletonEditSession } = makeConnection({ + skeletonLayer: makeSkeletonLayer(makeEditableSource()), + }); + const deleteNodes = SpatialSkeletonActions.deleteNodes; + expect(connection.getActionsDisabledReason(deleteNodes)).toBeUndefined(); + spatialSkeletonEditSession.latchReloadRequired({ + reason: "authority-indeterminate", + authority: "indeterminate", + intentId: 1, + cause: new Error("lost response"), + }); + expect(connection.getActionsDisabledReason(deleteNodes)).toMatch(/reload/i); + expect( + connection.getActionsDisabledReason(SpatialSkeletonActions.inspect), + ).toBeUndefined(); + }); + + it("a read-only skeleton source explains that editing is not possible", () => { + const { connection } = makeConnection({ + skeletonLayer: makeSkeletonLayer(undefined), + }); + expect( + connection.getActionsDisabledReason(SpatialSkeletonActions.addNodes), + ).toBe("The active spatial skeleton source is read-only."); + expect( + connection.getActionsDisabledReason(SpatialSkeletonActions.inspect), + ).toBeUndefined(); + }); + + it("a source without an action names the missing action in the disabled reason", () => { + const { connection } = makeConnection({ + skeletonLayer: makeSkeletonLayer( + makeEditableSource({ omitReroot: true }), + ), + }); + expect( + connection.getActionsDisabledReason([ + SpatialSkeletonActions.addNodes, + SpatialSkeletonActions.reroot, + ]), + ).toBe( + "The active spatial skeleton source does not support skeleton rerooting.", + ); + expect( + connection.getActionsDisabledReason(SpatialSkeletonActions.addNodes), + ).toBeUndefined(); + }); + + it("only a change to a different skeleton source ends editing and clears pending edits, undo history and edited skeletons", () => { + const { connection, spatialSkeletonEditSession, overlaySegments } = + makeConnection(); + const firstSource = {} as MultiscaleSpatiallyIndexedSkeletonSource; + const secondSource = {} as MultiscaleSpatiallyIndexedSkeletonSource; + const { commandHistory } = spatialSkeletonEditSession; + const startEditing = () => { + spatialSkeletonEditSession.editMode.value = true; + spatialSkeletonEditSession.setMergeAnchor(5n); + spatialSkeletonEditSession.setPendingNodePosition(7n, [1, 2, 3]); + commandHistory.confirm(commandHistory.stageExecute("add node")); + }; + + connection.sourceChanged(firstSource); + startEditing(); + connection.sourceChanged(firstSource); + expect(spatialSkeletonEditSession.editMode.value).toBe(true); + expect(spatialSkeletonEditSession.mergeAnchorNodeId.value).toBe(5n); + expect(spatialSkeletonEditSession.getPendingNodePosition(7n)).toBeDefined(); + expect(commandHistory.undoLabel.value).toBe("add node"); + expect(overlaySegments.clear).not.toHaveBeenCalled(); + + connection.sourceChanged(secondSource); + expect(spatialSkeletonEditSession.editMode.value).toBe(false); + expect(spatialSkeletonEditSession.mergeAnchorNodeId.value).toBeUndefined(); + expect( + spatialSkeletonEditSession.getPendingNodePosition(7n), + ).toBeUndefined(); + expect(commandHistory.canUndo.value).toBe(false); + expect(overlaySegments.clear).toHaveBeenCalledOnce(); + + startEditing(); + connection.sourceChanged(undefined); + expect(spatialSkeletonEditSession.editMode.value).toBe(false); + expect(spatialSkeletonEditSession.mergeAnchorNodeId.value).toBeUndefined(); + expect(commandHistory.canUndo.value).toBe(false); + }); + + it("an edit shown before it is saved clears the shown Find Path result", () => { + const { connection, spatialSkeletonEditSession } = makeConnection(); + const findPathState = new SkeletonFindPathState(); + const lifetime = new RefCounted(); + connection.attachFindPath( + { + skeletonLayer: makeSkeletonLayer(undefined), + state: findPathState, + annotationController: {} as any, + }, + lifetime, + ); + const result = [{ nodeId: 1n, segmentId: 5n, position: [0, 0, 0] }]; + + findPathState.setResult(result as any); + spatialSkeletonEditSession.nodeDataVersion.value += 1; + expect(findPathState.result).toBe(result); + + vi.spyOn(spatialSkeletonEditSession, "hasUnconfirmedEdits").mockReturnValue( + true, + ); + spatialSkeletonEditSession.nodeDataVersion.value += 1; + expect(findPathState.result).toBeUndefined(); + + lifetime.dispose(); + expect(connection.getFindPathContext()).toBeUndefined(); + }); + + it("a renumbered skeleton stays visible and selected after the server confirms an edit", () => { + const skeletonLayer = makeSkeletonLayer(undefined); + const { connection, group, overlaySegments } = makeConnection({ + skeletonLayer, + }); + group.visibleSegments.add(5n); + group.temporaryVisibleSegments.add(5n); + group.selectedSegments.add(5n); + + connection.applySpatialSkeletonPreviewUiHints( + makeHints({ segmentIdRemappings: new Map([[5n, 9n]]) }), + ); + + expect(group.visibleSegments.has(9n)).toBe(true); + expect(group.visibleSegments.has(5n)).toBe(false); + expect(group.selectedSegments.has(9n)).toBe(true); + expect(group.selectedSegments.has(5n)).toBe(false); + expect(overlaySegments.remap).toHaveBeenCalledWith(new Map([[5n, 9n]])); + }); + + it("deleting the last node of a skeleton hides and deselects it", () => { + const { connection, group, selection } = makeConnection({ + skeletonLayer: makeSkeletonLayer(undefined), + }); + group.visibleSegments.add(5n); + group.temporaryVisibleSegments.add(5n); + group.selectedSegments.add(5n); + selection.select(3n, true, { + segmentId: 5n, + position: new Float32Array([1, 2, 3]), + }); + + connection.applySpatialSkeletonPreviewUiHints( + makeHints({ + segmentVisibility: [{ segmentId: 5n, visible: false, deselect: true }], + selectedNode: { kind: "clear" }, + } as Partial), + ); + + expect(group.visibleSegments.has(5n)).toBe(false); + expect(group.temporaryVisibleSegments.has(5n)).toBe(false); + expect(group.selectedSegments.has(5n)).toBe(false); + expect(selection.selected.value).toBeUndefined(); + }); + + it("a rejected delete restores the skeleton's visibility and the pinned node", async () => { + const spatialSkeletonEditSession = new SpatialSkeletonEditSession(); + const { skeletonLayer, client } = makeDeletingSkeletonLayer((nodeId) => + spatialSkeletonEditSession.getCachedNode(nodeId), + ); + const { connection, group, selection, selectionState, layer } = + makeConnection({ skeletonLayer, spatialSkeletonEditSession }); + const node = { + nodeId: 725n, + segmentId: 87n, + position: new Float32Array([4, 5, 6]), + }; + spatialSkeletonEditSession.replaceCachedSegmentSnapshots([[87n, [node]]]); + group.visibleSegments.add(87n); + selection.select(node.nodeId, true, node); + let rejectDelete: ((error: Error) => void) | undefined; + client.deleteNode.mockImplementation( + () => + new Promise((_, reject) => { + rejectDelete = reject; + }), + ); + const readLayerEntry = () => + selectionState.value?.layers.find((entry) => entry.layer === layer) + ?.state as (UserLayerSelectionState & { nodeId?: bigint }) | undefined; + + const execution = executeSpatialSkeletonDeleteNode(connection, node); + await execution; + await vi.waitFor(() => expect(rejectDelete).toBeDefined()); + expect(readLayerEntry()?.nodeId).toBeUndefined(); + expect(group.visibleSegments.has(87n)).toBe(false); + + rejectDelete!( + new HttpError( + "https://catmaid.example.test/1/treenode/delete", + 409, + "Conflict", + ), + ); + + expect(await execution.settled).toMatchObject({ + outcome: "unchanged", + reason: "rejected", + }); + expect(readLayerEntry()).toMatchObject({ nodeId: 725n, value: 87n }); + expect(group.visibleSegments.has(87n)).toBe(true); + expect(spatialSkeletonEditSession.getCachedNode(725n)).toMatchObject(node); + spatialSkeletonEditSession.dispose(); + }); +}); diff --git a/src/layer/segmentation/skeleton_source_connection.ts b/src/layer/segmentation/skeleton_source_connection.ts new file mode 100644 index 0000000000..b9404d08f0 --- /dev/null +++ b/src/layer/segmentation/skeleton_source_connection.ts @@ -0,0 +1,232 @@ +/** + * @license + * Copyright 2026 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file Reports which spatial skeleton edit actions the active source of a + * segmentation layer allows. Applies the hints of an adopted preview to the + * segments and the selection of the layer. + */ + +import type { SkeletonNodeSelection } from "#src/layer/segmentation/skeleton_node_selection.js"; +import type { SegmentationGroupState } from "#src/segmentation_display_state/frontend.js"; +import type { SpatialSkeletonAction } from "#src/skeleton/edit/edit_commands.js"; +import { + DEFAULT_SPATIAL_SKELETON_EDIT_ACTIONS, + getSpatialSkeletonActionSupportLabel, + isSpatialSkeletonEditAction, + SpatialSkeletonActions, +} from "#src/skeleton/edit/edit_commands.js"; +import type { + SpatialSkeletonLayerContext, + SpatialSkeletonEditSession, +} from "#src/skeleton/edit/spatial_skeleton_edit_session.js"; +import { + ensureSpatialSkeletonEditQueue, + editableSpatiallyIndexedSkeletonSourceSupportsAction, +} from "#src/skeleton/edit/spatial_skeleton_edit_session.js"; +import type { SpatialSkeletonResolvedPreviewUiHints } from "#src/skeleton/edit_queue/preview_ui_hints.js"; +import { SPATIAL_SKELETON_RELOAD_REQUIRED_EDIT_REASON } from "#src/skeleton/edit_queue/types.js"; +import type { SkeletonFindPathState } from "#src/skeleton/find_path/find_path.js"; +import type { SpatialSkeletonFindPathAnnotationController } from "#src/skeleton/find_path/find_path_attachment.js"; +import type { SkeletonNodeAccess } from "#src/skeleton/navigation.js"; +import type { MultiscaleSpatiallyIndexedSkeletonSource } from "#src/skeleton/spatial/frontend.js"; +import type { SkeletonOverlaySegments } from "#src/skeleton/spatial/overlay_segments.js"; +import type { SpatiallyIndexedSkeletonLayer } from "#src/skeleton/spatial/skeleton_render_layer.js"; +import type { WatchableValueInterface } from "#src/trackable_value.js"; +import type { Uint64Set } from "#src/uint64_set.js"; +import { RefCounted } from "#src/util/disposable.js"; + +function remapSegmentSet( + set: Pick, + remappings: ReadonlyMap, +) { + const presentTargets = new Set(); + for (const [from, to] of remappings) { + if (from !== to && set.has(from)) presentTargets.add(to); + } + for (const [from, to] of remappings) { + if (from !== to) set.delete(from); + } + for (const target of presentTargets) set.add(target); +} + +export interface SpatialSkeletonFindPathContext { + readonly skeletonLayer: SpatiallyIndexedSkeletonLayer; + readonly state: SkeletonFindPathState; + readonly annotationController: SpatialSkeletonFindPathAnnotationController; +} + +export interface SkeletonSourceConnectionOptions { + readonly spatialSkeletonEditSession: SpatialSkeletonEditSession; + readonly selection: SkeletonNodeSelection; + readonly overlaySegments: SkeletonOverlaySegments; + readonly segmentationGroupState: WatchableValueInterface; + readonly skeletonNodeAccess: WatchableValueInterface< + SkeletonNodeAccess | undefined + >; + readonly spatiallyIndexedSkeletonLayer: WatchableValueInterface< + SpatiallyIndexedSkeletonLayer | undefined + >; +} + +export class SkeletonSourceConnection + extends RefCounted + implements SpatialSkeletonLayerContext +{ + private activeSource: MultiscaleSpatiallyIndexedSkeletonSource | undefined; + private findPathContext: SpatialSkeletonFindPathContext | undefined; + + constructor(private readonly options: SkeletonSourceConnectionOptions) { + super(); + } + + get spatialSkeletonEditSession() { + return this.options.spatialSkeletonEditSession; + } + + getSpatiallyIndexedSkeletonLayer() { + return this.options.spatiallyIndexedSkeletonLayer.value; + } + + getActionsDisabledReason( + requiredActions: + | SpatialSkeletonAction + | readonly SpatialSkeletonAction[] = DEFAULT_SPATIAL_SKELETON_EDIT_ACTIONS, + ): string | undefined { + const requirements: readonly SpatialSkeletonAction[] = Array.isArray( + requiredActions, + ) + ? requiredActions + : [requiredActions as SpatialSkeletonAction]; + if ( + requirements.some((action) => isSpatialSkeletonEditAction(action)) && + this.spatialSkeletonEditSession.getReloadRequired() !== undefined + ) { + return SPATIAL_SKELETON_RELOAD_REQUIRED_EDIT_REASON; + } + const skeletonLayer = this.getSpatiallyIndexedSkeletonLayer(); + if ( + skeletonLayer !== undefined && + skeletonLayer.editableSource === undefined && + requirements.some((action) => action !== SpatialSkeletonActions.inspect) + ) { + return "The active spatial skeleton source is read-only."; + } + const missingRequirements = requirements.filter( + (action) => !this.supportsAction(action), + ); + if (missingRequirements.length === 0) return undefined; + const names = missingRequirements.map(getSpatialSkeletonActionSupportLabel); + return `The active spatial skeleton source does not support ${names.join(", ")}.`; + } + + sourceChanged( + source: MultiscaleSpatiallyIndexedSkeletonSource | undefined, + ): void { + const previousSource = this.activeSource; + this.activeSource = source; + if (previousSource !== undefined && previousSource !== source) { + this.spatialSkeletonEditSession.clearRuntimeState(); + this.options.overlaySegments.clear(); + } + } + + attachFindPath( + context: SpatialSkeletonFindPathContext, + lifetime: RefCounted, + ): void { + this.findPathContext = context; + lifetime.registerDisposer( + this.spatialSkeletonEditSession.nodeDataVersion.changed.add(() => { + // Invalidate before the active tool recomputes the path. + if (this.spatialSkeletonEditSession.hasUnconfirmedEdits()) { + context.state.invalidateResult(); + } + }), + ); + lifetime.registerDisposer(() => { + if (this.findPathContext === context) { + this.findPathContext = undefined; + } + }); + } + + getFindPathContext(): SpatialSkeletonFindPathContext | undefined { + return this.findPathContext; + } + + readSpatialSkeletonSegmentVisibilityState(segmentId: bigint) { + const group = this.options.segmentationGroupState.value; + return { + visible: group.visibleSegments.has(segmentId), + temporaryVisible: group.temporaryVisibleSegments.has(segmentId), + starred: group.selectedSegments.has(segmentId), + }; + } + + applySpatialSkeletonPreviewUiHints( + hints: SpatialSkeletonResolvedPreviewUiHints, + ): void { + this.spatialSkeletonEditSession.remapPendingNodePositions( + hints.nodeIdRemappings, + ); + const group = this.options.segmentationGroupState.value; + for (const set of [ + group.visibleSegments, + group.temporaryVisibleSegments, + group.selectedSegments, + ]) { + remapSegmentSet(set, hints.segmentIdRemappings); + } + for (const visibility of hints.segmentVisibility) { + const { segmentId } = visibility; + group.visibleSegments.set(segmentId, visibility.visible); + group.temporaryVisibleSegments.set( + segmentId, + visibility.temporaryVisible ?? visibility.visible, + ); + if (visibility.starred !== undefined) { + group.selectedSegments.set(segmentId, visibility.starred); + } else if (!visibility.visible && visibility.deselect) { + group.selectedSegments.delete(segmentId); + } + } + this.options.selection.applyPreviewUiHints(hints); + const { overlaySegments } = this.options; + if (hints.segmentIdRemappings.size !== 0) { + // Copied so that the layer cannot change the preview's publication. + overlaySegments.remap(new Map(hints.segmentIdRemappings)); + } + for (const segmentId of hints.retainSegmentIds) { + overlaySegments.retain(segmentId); + } + } + + private supportsAction(action: SpatialSkeletonAction) { + if (action === SpatialSkeletonActions.inspect) { + return this.options.skeletonNodeAccess.value !== undefined; + } + const source = this.getSpatiallyIndexedSkeletonLayer()?.editableSource; + if (source === undefined) return false; + try { + ensureSpatialSkeletonEditQueue(this, source); + } catch { + // A writable source with an invalid driver contract is inspect-only. + return false; + } + return editableSpatiallyIndexedSkeletonSourceSupportsAction(source, action); + } +} diff --git a/src/layer/segmentation/style.css b/src/layer/segmentation/style.css index 3d379ba8de..9c2407d694 100644 --- a/src/layer/segmentation/style.css +++ b/src/layer/segmentation/style.css @@ -21,15 +21,19 @@ } .neuroglancer-segmentation-rendering-tab .neuroglancer-shader-code-widget { - height: 6em; + flex-shrink: 0; + height: 8em; + resize: vertical; } -.neuroglancer-segmentation-dropdown-skeleton-shader-header { +.neuroglancer-segmentation-dropdown-shader-header { display: flex; flex-direction: row; align-items: center; } +.neuroglancer-segmentation-layer-segment-color-shader-overlay + .neuroglancer-shader-code-widget, .neuroglancer-segmentation-layer-skeleton-shader-overlay .neuroglancer-shader-code-widget { width: 80vw; diff --git a/src/layer/single_mesh/index.ts b/src/layer/single_mesh/index.ts index cbd65286a4..1279851b7f 100644 --- a/src/layer/single_mesh/index.ts +++ b/src/layer/single_mesh/index.ts @@ -143,7 +143,7 @@ export class SingleMeshUserLayer extends UserLayer { function makeShaderCodeWidget(layer: SingleMeshUserLayer) { return new ShaderCodeWidget({ - fragmentMain: layer.displayState.fragmentMain, + fragment: layer.displayState.fragmentMain, shaderError: layer.displayState.shaderError, shaderControlState: layer.displayState.shaderControlState, }); diff --git a/src/main_python.ts b/src/main_python.ts index 9b4256d331..0f8cd2abd1 100644 --- a/src/main_python.ts +++ b/src/main_python.ts @@ -44,6 +44,7 @@ import { registerDefaultCommands } from "#src/ui/default_commands.js"; import { setDefaultInputEventBindings } from "#src/ui/default_input_event_bindings.js"; import { makeDefaultViewer } from "#src/ui/default_viewer.js"; import { bindScreenshotDialog } from "#src/ui/screenshot_menu.js"; +import { bindSkeletonNodeCommands } from "#src/ui/skeleton_node_commands.js"; import { bindStateEditor } from "#src/ui/state_editor.js"; import { bindTitle } from "#src/ui/title.js"; import { UrlHashBinding } from "#src/ui/url_hash_binding.js"; @@ -233,6 +234,7 @@ volumeHandler.sendVolumeChunkResponseRequested.add((requestId, info) => bindDefaultCopyHandler(viewer); bindDefaultPasteHandler(viewer); registerDefaultCommands(viewer.commandRegistry); +bindSkeletonNodeCommands(viewer); bindCommandPalette(viewer); bindStateEditor(viewer); bindScreenshotDialog(viewer); diff --git a/src/mesh/frontend.ts b/src/mesh/frontend.ts index bd6ded8562..a934369c34 100644 --- a/src/mesh/frontend.ts +++ b/src/mesh/frontend.ts @@ -43,6 +43,12 @@ import type { import { PerspectiveViewRenderLayer } from "#src/perspective_view/render_layer.js"; import type { ThreeDimensionalRenderLayerAttachmentState } from "#src/renderlayer.js"; import { update3dRenderLayerAttachment } from "#src/renderlayer.js"; +import type { SegmentationColorUserShaderManagerParameters } from "#src/segment_color.js"; +import { + DEFAULT_USER_MAIN_SEGMENT_COLOR, + encodeSegmentPropertyShaderDefinition, + SegmentColorShaderManager, +} from "#src/segment_color.js"; import { forEachVisibleSegment, getObjectKey, @@ -54,9 +60,12 @@ import { SegmentationLayerSharedObject, } from "#src/segmentation_display_state/frontend.js"; import type { WatchableValueInterface } from "#src/trackable_value.js"; -import { makeCachedDerivedWatchableValue } from "#src/trackable_value.js"; +import { + AggregateWatchableValue, + makeCachedDerivedWatchableValue, + WatchableValue, +} from "#src/trackable_value.js"; import type { Borrowed, RefCounted } from "#src/util/disposable.js"; -import type { vec4 } from "#src/util/geom.js"; import { getFrustumPlanes, mat3, @@ -68,8 +77,14 @@ import { import * as matrix from "#src/util/matrix.js"; import { GLBuffer } from "#src/webgl/buffer.js"; import type { GL } from "#src/webgl/context.js"; +import type { WatchableShaderError } from "#src/webgl/dynamic_shader.js"; import { parameterizedEmitterDependentShaderGetter } from "#src/webgl/dynamic_shader.js"; import type { ShaderBuilder, ShaderProgram } from "#src/webgl/shader.js"; +import { glsl_uint64 } from "#src/webgl/shader_lib.js"; +import { + getFallbackBuilderState, + parseShaderUiControls, +} from "#src/webgl/shader_ui_controls.js"; import type { RPC } from "#src/worker_rpc.js"; import { registerSharedObjectOwner } from "#src/worker_rpc.js"; @@ -179,7 +194,7 @@ function getFloatPositionHandler( defineShader: (builder: ShaderBuilder) => { builder.addAttribute("highp vec3", "aVertexPosition"); builder.addVertexCode( - "highp vec3 getVertexPosition() { return aVertexPosition; }", + "highp vec3 getVertexPosition() { return aVertexPosition; }\n", ); }, bind( @@ -265,14 +280,18 @@ export class MeshShaderManager { } } - setColor(gl: GL, shader: ShaderProgram, color: vec4) { - gl.uniform4fv(shader.uniform("uColor"), color); - } - setPickID(gl: GL, shader: ShaderProgram, pickID: number) { gl.uniform1ui(shader.uniform("uPickID"), pickID); } + setID(gl: GL, shader: ShaderProgram, id: bigint) { + gl.uniform2ui( + shader.uniform(`uID`), + Number(id & 0xffffffffn), + Number(id >> 32n), + ); + } + beginModel( gl: GL, shader: ShaderProgram, @@ -343,30 +362,81 @@ export class MeshShaderManager { this.drawFragmentHelper(gl, shader, fragmentChunk, indexBegin, indexEnd); } - endLayer(gl: GL, shader: ShaderProgram) { + endLayer( + gl: GL, + shader: ShaderProgram, + displayState: MeshDisplayState, + segmentColorParameters: SegmentationColorUserShaderManagerParameters, + ) { + displayState.segmentationColorUserShader.disable( + gl, + shader, + segmentColorParameters, + ); this.vertexPositionHandler.endLayer(gl, shader); gl.disableVertexAttribArray(shader.attribute("aVertexNormal")); } makeGetter(layer: RefCounted & { gl: GL; displayState: MeshDisplayState }) { - const silhouetteRenderingEnabled = layer.registerDisposer( - makeCachedDerivedWatchableValue( - (x) => x > 0, - [layer.displayState.silhouetteRendering], - ), + const parameters = layer.registerDisposer( + new AggregateWatchableValue((refCounted) => ({ + segmentColorParameters: + layer.displayState.segmentationColorUserShader.shaderParameters, + segmentColorProperties: + layer.displayState.segmentationColorUserShader.usedProperties, + shaderBuilderState: + layer.displayState.segmentColorShaderControlState.builderState, + silhouetteRenderingEnabled: refCounted.registerDisposer( + makeCachedDerivedWatchableValue( + (x) => x > 0, + [layer.displayState.silhouetteRendering], + ), + ), + })), ); + const fallbackParameters = new WatchableValue({ + segmentColorParameters: + layer.displayState.segmentationColorUserShader.shaderParameters.value, + segmentColorProperties: [], + shaderBuilderState: getFallbackBuilderState( + parseShaderUiControls(DEFAULT_USER_MAIN_SEGMENT_COLOR), + ), + silhouetteRenderingEnabled: + layer.displayState.silhouetteRendering.value > 0, + }); + return parameterizedEmitterDependentShaderGetter(layer, layer.gl, { memoizeKey: `mesh/MeshShaderManager/${this.fragmentRelativeVertices}/${this.vertexPositionFormat}`, - parameters: silhouetteRenderingEnabled, - defineShader: (builder, silhouetteRenderingEnabled) => { + parameters, + encodeParameters: (p) => { + return `${p.shaderBuilderState.key}/${JSON.stringify(p.segmentColorParameters)}/${JSON.stringify(p.segmentColorProperties.map(encodeSegmentPropertyShaderDefinition))}/${p.silhouetteRenderingEnabled}`; + }, + fallbackParameters, + shaderError: layer.displayState.meshShaderError, + defineShader: ( + builder, + { + segmentColorParameters, + shaderBuilderState, + silhouetteRenderingEnabled, + }, + ) => { this.vertexPositionHandler.defineShader(builder); + layer.displayState.segmentationColorUserShader.defineShader( + builder, + /*fragment=*/ false, + shaderBuilderState, + segmentColorParameters, + ); builder.addAttribute("highp vec2", "aVertexNormal"); builder.addVarying("highp vec4", "vColor"); builder.addUniform("highp vec4", "uLightDirection"); - builder.addUniform("highp vec4", "uColor"); builder.addUniform("highp mat3", "uNormalMatrix"); builder.addUniform("highp mat4", "uModelViewProjection"); builder.addUniform("highp uint", "uPickID"); + builder.addUniform("highp uvec2", "uID"); + builder.addUniform("highp float", "uAlpha"); + if (silhouetteRenderingEnabled) { builder.addUniform("highp float", "uSilhouettePower"); } @@ -375,6 +445,7 @@ export class MeshShaderManager { builder.addUniform("highp vec3", "uFragmentShape"); } builder.addVertexCode(glsl_decodeNormalOctahedronSnorm8); + builder.addVertexCode(glsl_uint64); let vertexMain = ""; if (this.fragmentRelativeVertices) { vertexMain += ` @@ -393,7 +464,9 @@ vec3 origNormal = decodeNormalOctahedronSnorm8(aVertexNormal); vec3 normal = normalize(uNormalMatrix * (normalMultiplier * origNormal)); float absCosAngle = abs(dot(normal, uLightDirection.xyz)); float lightingFactor = absCosAngle + uLightDirection.w; -vColor = vec4(lightingFactor * uColor.rgb, uColor.a); +vColor = segmentColorUserShader(uint64_t(uID)); +float alpha = uAlpha * vColor.a; +vColor = vec4(lightingFactor * vColor.rgb * alpha, alpha); `; if (silhouetteRenderingEnabled) { vertexMain += ` @@ -401,6 +474,8 @@ vColor *= pow(1.0 - absCosAngle, uSilhouettePower); `; } builder.setVertexMain(vertexMain); + const shaderManager = new SegmentColorShaderManager("getColor"); + shaderManager.defineShader(builder); builder.setFragmentMain("emit(vColor, uPickID);"); }, }); @@ -409,6 +484,7 @@ vColor *= pow(1.0 - absCosAngle, uSilhouettePower); export interface MeshDisplayState extends SegmentationDisplayState3D { silhouetteRendering: WatchableValueInterface; + shaderError: WatchableShaderError; } export class MeshLayer extends PerspectiveViewRenderLayer { @@ -454,6 +530,7 @@ export class MeshLayer extends PerspectiveViewRenderLayer 0 ); } @@ -490,11 +567,20 @@ export class MeshLayer extends PerspectiveViewRenderLayer { + (objectId, pickIndex, colorObjectId) => { const key = getObjectKey(objectId); const manifestChunk = manifestChunks.get(key); ++totalChunks; if (manifestChunk === undefined) return; ++presentChunks; if (renderContext.emitColor) { - meshShaderManager.setColor(gl, shader, color!); + gl.uniform1f( + shader.uniform("uAlpha"), + displayState.objectAlpha.value, + ); } if (renderContext.emitPickID) { meshShaderManager.setPickID(gl, shader, pickIndex!); } + meshShaderManager.setID(gl, shader, colorObjectId); totalChunks += manifestChunk.fragmentIds.length; for (const fragmentId of manifestChunk.fragmentIds) { @@ -550,7 +639,12 @@ export class MeshLayer extends PerspectiveViewRenderLayer 0 ); } @@ -829,10 +924,19 @@ export class MultiscaleMeshLayer extends PerspectiveViewRenderLayer { + (objectId, pickIndex, colorObjectId) => { const key = getObjectKey(objectId); const manifestChunk = chunks.get(key); ++totalManifestChunks; @@ -895,11 +998,16 @@ export class MultiscaleMeshLayer extends PerspectiveViewRenderLayer