118 Commits

Author SHA1 Message Date
Nan
1ced263441 5.0 (#63)
* feat: Add Bioxel asset catalog and layer management functionality

- Introduced a new asset catalog definition file for Blender to manage Bioxel assets.
- Implemented layer caching and snapshot functionality in `layer.py`, allowing for VDB file generation and low-resolution snapshots.
- Created node management functions in `node.py` for handling Bioxel nodes within Blender's Geometry Node Editor.
- Added an operator to extract mesh data from selected nodes in `structure.py`.
- Developed UI panels in `panels.py` for layer management, including import options and layer library display.

* Add unit tests for bioxel module and documentation

- Created README.md for test instructions and categories.
- Implemented comprehensive unit tests for the Data, Layer, and utility functions in the bioxel module.
- Added tests for reading NRRD and DICOM formats, data properties, and edge cases.
- Included tests for real data files to ensure functionality with actual datasets.

* feat: Update .gitattributes and .gitignore for improved asset management and ignore patterns

chore: Add app.json and omoolab.css for Obsidian integration

refactor: Clean up AGENTS.md and remove outdated test files

* feat: Update .gitignore to include scipy_ndimage directory

* feat: Update release workflow and manifest for improved dependency management and layer handling

* feat: Update .gitignore and add binary files for scipy_ndimage across multiple platforms

* feat: Add OPSX commands for archiving, exploring, and proposing changes

* feat: Refactor asset library management and update manifest for improved organization

* feat: Downgrade h5py version to 3.14.0 in requirements and manifest

* feat: Update Help operator and panel labels to use English terminology

* Translate documentation to Chinese, add support format details, and enhance styling with new fonts. Update mkdocs configuration for multilingual support and improve package dependencies.

* feat: Remove default version setting from extra configuration in mkdocs.yml

* fix: Update documentation links to point to the correct URLs for Chinese and English versions

* Add documentation for basic usage, supported formats, and performance tips

- Created English and Chinese documentation for basic usage of the add-on, including data download, import, extraction, and rendering steps.
- Added support format documentation listing compatible file types for the add-on.
- Included links to open databases for volumetric data.
- Provided performance improvement tips for voxel reconstruction and rendering, including settings for low-resolution previews and balanced rendering configurations.

* Add OpenSpec skills for change management and exploration

- Implement openspec-apply-change skill for applying tasks from OpenSpec changes.
- Create openspec-archive-change skill for archiving completed changes.
- Introduce openspec-explore skill for exploring ideas and clarifying requirements.
- Add openspec-propose skill for proposing new changes with generated artifacts.
- Migrate source command skills: source-command-opsx-apply, source-command-opsx-archive, source-command-opsx-explore, and source-command-opsx-propose for improved command handling.

* feat: Update version to 2.0.1, refactor asset library handling, and enhance layer import process

* fix: downgrade scipy version to 1.16.3 in build.py and pyproject.toml

* Remove deprecated modules and functions from bioxel package

- Deleted _ni_support.py, _utils.py, and dtype.py as they contained unused or redundant functions.
- Removed the resize function and related utilities from _warps.py to streamline image processing.
- Cleaned up the skimage module by removing unnecessary imports and functions.

* feat: Add SKIP_MODULE_NAMES to exclude specific modules during import and refactor io_worker import logic

* refactor: Remove known limitations section from documentation for EEVEE NEXT support

* feat: Implement CLI command registration for bioxelnodes_import_worker and refactor io_worker for improved module handling

* chore: Update version to 2.0.2 in project files and dependencies

* feat: Enhance volumetric data parsing by adding progress updates and refactoring worker processes
2026-07-09 00:50:34 +08:00
Nan
e9ea4c5248 5.0 (#62)
* feat: Add Bioxel asset catalog and layer management functionality

- Introduced a new asset catalog definition file for Blender to manage Bioxel assets.
- Implemented layer caching and snapshot functionality in `layer.py`, allowing for VDB file generation and low-resolution snapshots.
- Created node management functions in `node.py` for handling Bioxel nodes within Blender's Geometry Node Editor.
- Added an operator to extract mesh data from selected nodes in `structure.py`.
- Developed UI panels in `panels.py` for layer management, including import options and layer library display.

* Add unit tests for bioxel module and documentation

- Created README.md for test instructions and categories.
- Implemented comprehensive unit tests for the Data, Layer, and utility functions in the bioxel module.
- Added tests for reading NRRD and DICOM formats, data properties, and edge cases.
- Included tests for real data files to ensure functionality with actual datasets.

* feat: Update .gitattributes and .gitignore for improved asset management and ignore patterns

chore: Add app.json and omoolab.css for Obsidian integration

refactor: Clean up AGENTS.md and remove outdated test files

* feat: Update .gitignore to include scipy_ndimage directory

* feat: Update release workflow and manifest for improved dependency management and layer handling

* feat: Update .gitignore and add binary files for scipy_ndimage across multiple platforms

* feat: Add OPSX commands for archiving, exploring, and proposing changes

* feat: Refactor asset library management and update manifest for improved organization

* feat: Downgrade h5py version to 3.14.0 in requirements and manifest

* feat: Update Help operator and panel labels to use English terminology

* Translate documentation to Chinese, add support format details, and enhance styling with new fonts. Update mkdocs configuration for multilingual support and improve package dependencies.

* feat: Remove default version setting from extra configuration in mkdocs.yml

* fix: Update documentation links to point to the correct URLs for Chinese and English versions

* Add documentation for basic usage, supported formats, and performance tips

- Created English and Chinese documentation for basic usage of the add-on, including data download, import, extraction, and rendering steps.
- Added support format documentation listing compatible file types for the add-on.
- Included links to open databases for volumetric data.
- Provided performance improvement tips for voxel reconstruction and rendering, including settings for low-resolution previews and balanced rendering configurations.

* Add OpenSpec skills for change management and exploration

- Implement openspec-apply-change skill for applying tasks from OpenSpec changes.
- Create openspec-archive-change skill for archiving completed changes.
- Introduce openspec-explore skill for exploring ideas and clarifying requirements.
- Add openspec-propose skill for proposing new changes with generated artifacts.
- Migrate source command skills: source-command-opsx-apply, source-command-opsx-archive, source-command-opsx-explore, and source-command-opsx-propose for improved command handling.

* feat: Update version to 2.0.1, refactor asset library handling, and enhance layer import process

* fix: downgrade scipy version to 1.16.3 in build.py and pyproject.toml

* Remove deprecated modules and functions from bioxel package

- Deleted _ni_support.py, _utils.py, and dtype.py as they contained unused or redundant functions.
- Removed the resize function and related utilities from _warps.py to streamline image processing.
- Cleaned up the skimage module by removing unnecessary imports and functions.

* feat: Add SKIP_MODULE_NAMES to exclude specific modules during import and refactor io_worker import logic

* refactor: Remove known limitations section from documentation for EEVEE NEXT support
2026-07-08 13:48:52 +08:00
Nan
ae7868d410 5.0 (#60)
* feat: Add Bioxel asset catalog and layer management functionality

- Introduced a new asset catalog definition file for Blender to manage Bioxel assets.
- Implemented layer caching and snapshot functionality in `layer.py`, allowing for VDB file generation and low-resolution snapshots.
- Created node management functions in `node.py` for handling Bioxel nodes within Blender's Geometry Node Editor.
- Added an operator to extract mesh data from selected nodes in `structure.py`.
- Developed UI panels in `panels.py` for layer management, including import options and layer library display.

* Add unit tests for bioxel module and documentation

- Created README.md for test instructions and categories.
- Implemented comprehensive unit tests for the Data, Layer, and utility functions in the bioxel module.
- Added tests for reading NRRD and DICOM formats, data properties, and edge cases.
- Included tests for real data files to ensure functionality with actual datasets.

* feat: Update .gitattributes and .gitignore for improved asset management and ignore patterns

chore: Add app.json and omoolab.css for Obsidian integration

refactor: Clean up AGENTS.md and remove outdated test files

* feat: Update .gitignore to include scipy_ndimage directory

* feat: Update release workflow and manifest for improved dependency management and layer handling

* feat: Update .gitignore and add binary files for scipy_ndimage across multiple platforms

* feat: Add OPSX commands for archiving, exploring, and proposing changes

* feat: Refactor asset library management and update manifest for improved organization

* feat: Downgrade h5py version to 3.14.0 in requirements and manifest

* feat: Update Help operator and panel labels to use English terminology

* Translate documentation to Chinese, add support format details, and enhance styling with new fonts. Update mkdocs configuration for multilingual support and improve package dependencies.

* feat: Remove default version setting from extra configuration in mkdocs.yml

* fix: Update documentation links to point to the correct URLs for Chinese and English versions

* Add documentation for basic usage, supported formats, and performance tips

- Created English and Chinese documentation for basic usage of the add-on, including data download, import, extraction, and rendering steps.
- Added support format documentation listing compatible file types for the add-on.
- Included links to open databases for volumetric data.
- Provided performance improvement tips for voxel reconstruction and rendering, including settings for low-resolution previews and balanced rendering configurations.
2026-05-26 16:01:29 +08:00
afae532a2c Update license to GNU General Public License v3 and add citation section in README 2025-04-14 14:12:57 +08:00
Ma Nan
508e6858d7 Add slicer to layer when container is new (#57) 2025-04-11 16:38:56 +08:00
1c49fbb813 Add slicer to layer when first import 2025-04-11 16:10:13 +08:00
35e405acd8 update version 2025-04-11 10:22:36 +08:00
Ma Nan
68748f509a Remove OSL scripts to improve render (#56)
* Remove OSL scripts to improve render

* Remove slice viewer

* Locator will be added next to selected node

* Improve specular in eevee
2025-04-11 10:14:40 +08:00
436296652b fix zip package in build extension step 2025-04-09 22:09:54 +08:00
c265777313 fix zip package in build extension step 2025-04-09 22:01:05 +08:00
e80a2b6683 fix zip package in build extension step 2025-04-09 21:11:11 +08:00
a6586b7304 bump version to 1.0.8 in pyproject.toml and blender_manifest.toml 2025-04-09 20:48:17 +08:00
Ma Nan
59bf9bff2d Fix compatibility with blender 4.4 (#55)
* migrate from poetry to uv

* fix No module named 'pyopenvdb' in blender 4.4

* update auto_load.py

* add vscode workspace

* update relase workflow
2025-04-09 17:47:06 +08:00
Ma Nan
d4bc355d94 Merge pull request #51 from OmooLab/feature/dev
Feature/dev
2024-11-01 11:58:31 +08:00
4e9dc1ce67 Merge branch 'main' of https://github.com/OmooLab/BioxelNodes into feature/dev 2024-11-01 11:57:41 +08:00
dc7d9382d6 fix: slice viewer change all 3d viewports
fix: eevee env light effect cycles render
feat: add gamma prop to correct color from non-linear image
feat: add "copy transform" node
2024-11-01 11:57:29 +08:00
Ma Nan
66aafb41bd Merge pull request #50 from OmooLab/feature/dev
Feature/dev
2024-10-30 13:32:19 +08:00
2c844c01ec Merge branch 'main' of https://github.com/OmooLab/BioxelNodes into feature/dev 2024-10-30 13:30:50 +08:00
e5be3ad5db feat: better shader in eevee
feat: add more control to transform node
feat: add env light to reduse volume shadow in eevee
2024-10-30 13:29:53 +08:00
Ma Nan
29b302531b Merge pull request #49 from OmooLab/feature/dev
feat: improve eevee render
2024-10-29 15:15:14 +08:00
3ca7c2ac5a feat: improve eevee render 2024-10-29 15:14:31 +08:00
Ma Nan
32138c1da6 Merge pull request #48 from OmooLab/feature/dev
feat: add help menu
2024-10-10 12:56:44 +08:00
86fc18ab69 feat: add help menu
feat: better surface topo
fix: cutter node invert not work
2024-10-10 12:54:51 +08:00
Ma Nan
928b15c722 Merge pull request #46 from OmooLab/feature/dev
fix: the as color button's text is incorrectly written as "as label"
2024-09-27 14:55:27 +08:00
487cea4662 fix: the as color button's text is incorrectly written as "as label"
feat: speed up convertion when as label
feat: add new "Extrude Transform" node
2024-09-27 14:53:47 +08:00
Ma Nan
92f85ff1f3 Merge pull request #45 from OmooLab/feature/dev
fix: relocate cannot work on missing layer
2024-09-19 12:28:35 +08:00
63c593f09a fix: relocate cannot work on missing layer
fix: import fail if label are all zero
fix: add cutter name to node
fix: cannot append node lib file on NAS (UNC path)
fix: join component cause disappear
feat: smooth label
feat: better topo on cutout by range
2024-09-19 12:27:39 +08:00
Ma Nan
3c5ff64afd Merge pull request #44 from OmooLab/feature/dev
Feature/dev
2024-09-13 17:12:41 +08:00
0ebc6dafbd fix cannot extract wire 2024-09-13 17:00:00 +08:00
c22ab2c85b Merge branch 'main' into feature/dev 2024-09-13 16:43:51 +08:00
133702619e fix: join component cause missing
feat: extract mesh from node
2024-09-13 16:42:18 +08:00
Ma Nan
e384798184 Merge pull request #43 from OmooLab/feature/dev
fix: cannot decode utf-8 issue
2024-09-11 15:36:19 +08:00
80da400891 fix: cannot decode utf-8 issue 2024-09-11 15:17:00 +08:00
Ma Nan
48700b3001 Merge pull request #42 from OmooLab/feature/dev
Feature/dev
2024-09-11 13:16:51 +08:00
b865d9d78d docs: fix image lost 2024-09-11 13:15:44 +08:00
20c6393344 docs: v1.0.0 2024-09-11 13:10:50 +08:00
Ma Nan
7c71417e5d Merge pull request #41 from OmooLab/feature/dev
Feature/dev
2024-09-04 12:42:33 +08:00
655b19bc7c feat: improving the user experience 2024-09-03 17:53:26 +08:00
051df670a5 feat: boost render speed 2024-08-16 13:56:14 +08:00
9e885865f7 feat: layer list system 2024-08-14 14:16:40 +08:00
Ma Nan
21e0b85662 Merge pull request #38 from OmooLab/fix-import
fix: color ramp not fit
2024-08-07 09:50:54 +08:00
38fb888f00 fix: color ramp not fit
fix: skip DICOM series option not reset.
fix: combine label only combine 2 layers
2024-08-07 09:42:25 +08:00
Ma Nan
2429eef5e0 Merge pull request #36 from OmooLab/feature/dev
Feature/dev
2024-08-05 15:54:19 +08:00
2563f398da chore: update version 2024-08-05 15:53:03 +08:00
0cad35e2da fix: fail to read all sequence in folder with same name prefix 2024-08-05 14:13:48 +08:00
65edf40164 feat: better drag and drop 2024-08-05 13:48:24 +08:00
c3f88b7846 fix: layer cache cannot be saved via save stage data 2024-08-05 11:27:50 +08:00
Ma Nan
088d9c1edb Merge pull request #35 from OmooLab/feature/dev
fix: macos-arm64 cannot install
2024-08-02 11:35:18 +08:00
a6ec769a9b fix: macos-arm64 cannot install
fix: better layer fill smooth filter
2024-08-02 11:34:35 +08:00
Ma Nan
7430fbf3ef Merge pull request #34 from OmooLab/feature/dev
BREAKING CHANGE: not support 4.1 any more
2024-08-01 15:51:48 +08:00
ce397b35aa feat: more time sequence choice
fix: contrast formulation cause leak of high value
fix: empty series_id cause fail to read
chore: restructure folder
chore!: change layer vars
BREAKING CHANGE: not support 4.1 any more
2024-08-01 15:50:41 +08:00
Ma Nan
caf184c327 Merge pull request #33 from OmooLab/feature/dev
chore: update version
2024-07-23 12:32:06 +08:00
488b05f062 chore: update version 2024-07-23 12:31:33 +08:00
Ma Nan
2447a47269 Merge pull request #32 from OmooLab/feature/dev
docs: update discord link
2024-07-23 12:29:36 +08:00
9380342b4f docs: update discord link 2024-07-23 12:27:52 +08:00
Ma Nan
9b36e9d911 Merge pull request #31 from OmooLab/feature/dev
Feature/dev
2024-07-23 12:05:18 +08:00
c9a961d5e8 fix some import issue 2024-07-23 12:04:30 +08:00
77878888ca fix: missing add .ima to DICOM_EXTS 2024-07-22 09:56:20 +08:00
Ma Nan
50e8564027 Merge pull request #30 from OmooLab/feature/dev
docs: update README
2024-07-22 09:06:50 +08:00
f07ac1c70c docs: update README 2024-07-22 09:05:52 +08:00
Ma Nan
b6e7ae0c8b Merge pull request #29 from OmooLab/feature/dev
feat: support more format
2024-07-22 08:51:59 +08:00
854af4c3bc feat: support more format
feat: support .mrc .map
feat: support .ome.tif
feat: improved user experience for importing
feat: better contrast algorithm
2024-07-22 08:51:12 +08:00
Ma Nan
0eaba42f27 Merge pull request #28 from OmooLab/feature/dev
feat: support 4d time data
2024-07-15 14:26:54 +08:00
b2791e3aae fix: eevee specular too high
feat: add pie cutter
feat: support 4d time data
chora: change operators name
docs: update README.md
2024-07-15 14:25:51 +08:00
Ma Nan
2eb2358589 Merge pull request #27 from OmooLab/feature/dev
feat: add primitive cutter
2024-07-10 12:45:43 +08:00
8b862b3fe0 feat: add primitive cutter
fix: eevee shadow
fix: save node toggle not work
fix: color over 1.0 fail to render
2024-07-10 12:45:04 +08:00
Ma Nan
5922269f7e Merge pull request #26 from OmooLab/feature/dev
feat: dramatic reduction in rendering time 🚀
2024-07-09 15:22:20 +08:00
99ce5c28d0 feat: dramatic reduction in rendering time 🚀
feat: add more support to  eevee render
fix: fail to add utils node inflate
fix: file import button missing
chore: change operator names
BREAKING CHANGE: remove support to blender 4.0
BREAKING CHANGE: remove support to gpu render with cuda
2024-07-09 15:20:26 +08:00
Ma Nan
637fc758a7 Merge pull request #25 from OmooLab/feature/dev
chore: change version
2024-07-04 15:06:10 +08:00
f90bf5c532 chore: change version 2024-07-04 15:05:22 +08:00
Ma Nan
f2d1d02c48 Merge pull request #24 from OmooLab/feature/dev
fix: misspell of "scalar"
2024-07-04 15:03:58 +08:00
d04f100dfd fix: misspell of "scalar"
fix: not change raw value of data
2024-07-04 15:02:17 +08:00
Ma Nan
734c4d1cd9 Merge pull request #23 from OmooLab/feature/dev
fix: fail to import membrane shader
2024-07-04 13:50:11 +08:00
78aba5394f fix: fail to import membrane shader 2024-07-04 13:49:18 +08:00
Ma Nan
4fc89beaa0 Merge pull request #22 from OmooLab/feature/dev
fix: fail to import nd_image
2024-07-04 13:43:17 +08:00
fb2a3c9c23 fix: fail to import nd_image
fix: membrane shader
2024-07-04 13:41:52 +08:00
Ma Nan
bc6f88996c Merge pull request #21 from OmooLab/feature/dev
feat: rewrite resize
2024-07-04 13:06:24 +08:00
1db63dd3db feat: rewrite resize
add more nodes
2024-07-04 13:05:46 +08:00
Ma Nan
467d368a76 Merge pull request #19 from OmooLab/feature/dev
feat: support eevee
2024-06-12 15:24:06 +08:00
134d8e382b feat: support eevee 2024-06-12 15:23:09 +08:00
Ma Nan
fefc9285e1 Merge pull request #18 from OmooLab/feature/dev
Feature/dev
2024-06-05 09:40:33 +08:00
322b84cc70 docs: update cover img
add extension description
2024-06-05 09:39:15 +08:00
f3be5d8660 feat: support blender 4.2 extension 2024-06-05 09:11:22 +08:00
470cdab4f6 fix: logging utf-8 cannot decode 2024-06-03 12:36:23 +08:00
Ma Nan
b35c816c25 Merge pull request #17 from OmooLab/feature/dev
fix: cannot convert to mesh in chinese language blender
2024-05-31 13:38:08 +08:00
0e2d6fe1a2 fix: cannot convert to mesh in chinese language blender 2024-05-31 13:36:47 +08:00
Ma Nan
e0c46e95f8 Merge pull request #16 from OmooLab/feature/dev
fix: label join scalar cannot get scalar offset
2024-05-31 10:10:55 +08:00
2528d984ad fix: label join scalar cannot get scalar offset 2024-05-31 10:10:16 +08:00
Ma Nan
56606fd721 Merge pull request #15 from OmooLab/feature/dev
Feature/dev
2024-05-30 09:54:57 +08:00
f21f7d6357 docs: v0.2.0 docs 2024-05-30 09:53:07 +08:00
fa031e63f8 feat: redesign nodes 2024-05-29 11:00:38 +08:00
Ma Nan
e929013183 Merge pull request #13 from OmooLab/feature/dev
Feature/dev
2024-05-14 14:41:01 +08:00
d380cf7036 docs: update docs 2024-05-14 14:39:34 +08:00
05a61527e7 fix: vector as label 2024-05-14 10:57:43 +08:00
Ma Nan
2c80c9ed81 Update README.md 2024-05-14 09:41:30 +08:00
Ma Nan
8e8b176e11 Merge pull request #12 from OmooLab/feature/dev
Feature/dev
2024-05-14 09:40:16 +08:00
c1886f95f8 docs: mkdocs 2024-05-14 09:39:43 +08:00
5e8d12c564 fix: io 2024-05-13 12:09:11 +08:00
1990a16972 feat: add more format support 2024-05-11 10:43:00 +08:00
eeca79e681 chore: change import path 2024-04-26 18:14:34 +08:00
Ma Nan
8b45de4a4d Merge pull request #9 from OmooLab/feature/dev
fix: save all node path not right
2024-04-25 12:13:04 +08:00
2c3d9e5791 fix: save all node path not right 2024-04-25 12:12:43 +08:00
Ma Nan
32b69575b1 Merge pull request #8 from OmooLab/feature/dev
feat: save bioxels, save nodes
2024-04-24 22:48:43 +08:00
d663bfd290 feat: save bioxels, save nodes 2024-04-24 22:48:09 +08:00
Ma Nan
a1aa776725 Merge pull request #7 from OmooLab/feature/dev
Feature/dev
2024-04-24 15:07:16 +08:00
6b18b4e9fa Merge branch 'main' into feature/dev 2024-04-24 15:06:30 +08:00
a579b24f9a feat: add save bioxels function 2024-04-24 14:54:22 +08:00
Ma Nan
8b3ab61467 Update README.md 2024-04-23 15:22:51 +08:00
Ma Nan
084031c496 Merge pull request #5 from OmooLab/feature/dev
fix: get no group input node
2024-04-23 15:12:38 +08:00
15b24b61b5 fix: get no group input node 2024-04-23 15:11:44 +08:00
Ma Nan
81dae0631a Update README.md 2024-04-22 22:48:44 +08:00
Ma Nan
38d2e52c93 Merge pull request #4 from OmooLab/feature/dev
Feature/dev
2024-04-22 22:39:16 +08:00
cf6ccb1743 docs: README add badges 2024-04-22 22:35:57 +08:00
f889b61494 chore: rename packages 2024-04-22 22:35:56 +08:00
Ma Nan
436288df7c Create LICENSE 2024-04-22 17:24:30 +08:00
Ma Nan
7967f144f1 Update README.md 2024-04-22 15:06:46 +08:00
Ma Nan
ba4c6c1dee Merge pull request #3 from OmooLab/feature/dev
docs: README.md
2024-04-22 14:52:30 +08:00
ca9df9065e docs: README.md 2024-04-22 14:51:51 +08:00
114 changed files with 9660 additions and 1693 deletions

View File

@@ -0,0 +1,156 @@
---
name: openspec-apply-change
description: Implement tasks from an OpenSpec change. Use when the user wants to start implementing, continue implementation, or work through tasks.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.3.1"
---
Implement tasks from an OpenSpec change.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and use the **AskUserQuestion tool** to let the user select
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <other>`).
2. **Check status to understand the schema**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand:
- `schemaName`: The workflow being used (e.g., "spec-driven")
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
3. **Get apply instructions**
```bash
openspec instructions apply --change "<name>" --json
```
This returns:
- `contextFiles`: artifact ID -> array of concrete file paths (varies by schema - could be proposal/specs/design/tasks or spec/tests/implementation/docs)
- Progress (total, complete, remaining)
- Task list with status
- Dynamic instruction based on current state
**Handle states:**
- If `state: "blocked"` (missing artifacts): show message, suggest using openspec-continue-change
- If `state: "all_done"`: congratulate, suggest archive
- Otherwise: proceed to implementation
4. **Read context files**
Read every file path listed under `contextFiles` from the apply instructions output.
The files depend on the schema being used:
- **spec-driven**: proposal, specs, design, tasks
- Other schemas: follow the contextFiles from CLI output
5. **Show current progress**
Display:
- Schema being used
- Progress: "N/M tasks complete"
- Remaining tasks overview
- Dynamic instruction from CLI
6. **Implement tasks (loop until done or blocked)**
For each pending task:
- Show which task is being worked on
- Make the code changes required
- Keep changes minimal and focused
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
- Continue to next task
**Pause if:**
- Task is unclear → ask for clarification
- Implementation reveals a design issue → suggest updating artifacts
- Error or blocker encountered → report and wait for guidance
- User interrupts
7. **On completion or pause, show status**
Display:
- Tasks completed this session
- Overall progress: "N/M tasks complete"
- If all done: suggest archive
- If paused: explain why and wait for guidance
**Output During Implementation**
```
## Implementing: <change-name> (schema: <schema-name>)
Working on task 3/7: <task description>
[...implementation happening...]
✓ Task complete
Working on task 4/7: <task description>
[...implementation happening...]
✓ Task complete
```
**Output On Completion**
```
## Implementation Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 7/7 tasks complete ✓
### Completed This Session
- [x] Task 1
- [x] Task 2
...
All tasks complete! Ready to archive this change.
```
**Output On Pause (Issue Encountered)**
```
## Implementation Paused
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 4/7 tasks complete
### Issue Encountered
<description of the issue>
**Options:**
1. <option 1>
2. <option 2>
3. Other approach
What would you like to do?
```
**Guardrails**
- Keep going through tasks until done or blocked
- Always read context files before starting (from the apply instructions output)
- If task is ambiguous, pause and ask before implementing
- If implementation reveals issues, pause and suggest artifact updates
- Keep code changes minimal and scoped to each task
- Update task checkbox immediately after completing each task
- Pause on errors, blockers, or unclear requirements - don't guess
- Use contextFiles from CLI output, don't assume specific file names
**Fluid Workflow Integration**
This skill supports the "actions on a change" model:
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly

View File

@@ -0,0 +1,114 @@
---
name: openspec-archive-change
description: Archive a completed change in the experimental workflow. Use when the user wants to finalize and archive a change after implementation is complete.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.3.1"
---
Archive a completed change in the experimental workflow.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **If no change name provided, prompt for selection**
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
Show only active changes (not already archived).
Include the schema used for each change if available.
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
2. **Check artifact completion status**
Run `openspec status --change "<name>" --json` to check artifact completion.
Parse the JSON to understand:
- `schemaName`: The workflow being used
- `artifacts`: List of artifacts with their status (`done` or other)
**If any artifacts are not `done`:**
- Display warning listing incomplete artifacts
- Use **AskUserQuestion tool** to confirm user wants to proceed
- Proceed if user confirms
3. **Check task completion status**
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
**If incomplete tasks found:**
- Display warning showing count of incomplete tasks
- Use **AskUserQuestion tool** to confirm user wants to proceed
- Proceed if user confirms
**If no tasks file exists:** Proceed without task-related warning.
4. **Assess delta spec sync state**
Check for delta specs at `openspec/changes/<name>/specs/`. If none exist, proceed without sync prompt.
**If delta specs exist:**
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
- Determine what changes would be applied (adds, modifications, removals, renames)
- Show a combined summary before prompting
**Prompt options:**
- If changes needed: "Sync now (recommended)", "Archive without syncing"
- If already synced: "Archive now", "Sync anyway", "Cancel"
If user chooses sync, use Task tool (subagent_type: "general-purpose", prompt: "Use Skill tool to invoke openspec-sync-specs for change '<name>'. Delta spec analysis: <include the analyzed delta spec summary>"). Proceed to archive regardless of choice.
5. **Perform the archive**
Create the archive directory if it doesn't exist:
```bash
mkdir -p openspec/changes/archive
```
Generate target name using current date: `YYYY-MM-DD-<change-name>`
**Check if target already exists:**
- If yes: Fail with error, suggest renaming existing archive or using different date
- If no: Move the change directory to archive
```bash
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
```
6. **Display summary**
Show archive completion summary including:
- Change name
- Schema that was used
- Archive location
- Whether specs were synced (if applicable)
- Note about any warnings (incomplete artifacts/tasks)
**Output On Success**
```
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** ✓ Synced to main specs (or "No delta specs" or "Sync skipped")
All artifacts complete. All tasks complete.
```
**Guardrails**
- Always prompt for change selection if not provided
- Use artifact graph (openspec status --json) for completion checking
- Don't block archive on warnings - just inform and confirm
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
- Show clear summary of what happened
- If sync is requested, use openspec-sync-specs approach (agent-driven)
- If delta specs exist, always run the sync assessment and show the combined summary before prompting

View File

@@ -0,0 +1,288 @@
---
name: openspec-explore
description: Enter explore mode - a thinking partner for exploring ideas, investigating problems, and clarifying requirements. Use when the user wants to think through something before or during a change.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.3.1"
---
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
---
## The Stance
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
- **Adaptive** - Follow interesting threads, pivot when new information emerges
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
---
## What You Might Do
Depending on what the user brings, you might:
**Explore the problem space**
- Ask clarifying questions that emerge from what they said
- Challenge assumptions
- Reframe the problem
- Find analogies
**Investigate the codebase**
- Map existing architecture relevant to the discussion
- Find integration points
- Identify patterns already in use
- Surface hidden complexity
**Compare options**
- Brainstorm multiple approaches
- Build comparison tables
- Sketch tradeoffs
- Recommend a path (if asked)
**Visualize**
```
┌─────────────────────────────────────────┐
│ Use ASCII diagrams liberally │
├─────────────────────────────────────────┤
│ │
│ ┌────────┐ ┌────────┐ │
│ │ State │────────▶│ State │ │
│ │ A │ │ B │ │
│ └────────┘ └────────┘ │
│ │
│ System diagrams, state machines, │
│ data flows, architecture sketches, │
│ dependency graphs, comparison tables │
│ │
└─────────────────────────────────────────┘
```
**Surface risks and unknowns**
- Identify what could go wrong
- Find gaps in understanding
- Suggest spikes or investigations
---
## OpenSpec Awareness
You have full context of the OpenSpec system. Use it naturally, don't force it.
### Check for context
At the start, quickly check what exists:
```bash
openspec list --json
```
This tells you:
- If there are active changes
- Their names, schemas, and status
- What the user might be working on
### When no change exists
Think freely. When insights crystallize, you might offer:
- "This feels solid enough to start a change. Want me to create a proposal?"
- Or keep exploring - no pressure to formalize
### When a change exists
If the user mentions a change or you detect one is relevant:
1. **Read existing artifacts for context**
- `openspec/changes/<name>/proposal.md`
- `openspec/changes/<name>/design.md`
- `openspec/changes/<name>/tasks.md`
- etc.
2. **Reference them naturally in conversation**
- "Your design mentions using Redis, but we just realized SQLite fits better..."
- "The proposal scopes this to premium users, but we're now thinking everyone..."
3. **Offer to capture when decisions are made**
| Insight Type | Where to Capture |
|----------------------------|--------------------------------|
| New requirement discovered | `specs/<capability>/spec.md` |
| Requirement changed | `specs/<capability>/spec.md` |
| Design decision made | `design.md` |
| Scope changed | `proposal.md` |
| New work identified | `tasks.md` |
| Assumption invalidated | Relevant artifact |
Example offers:
- "That's a design decision. Capture it in design.md?"
- "This is a new requirement. Add it to specs?"
- "This changes scope. Update the proposal?"
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
---
## What You Don't Have To Do
- Follow a script
- Ask the same questions every time
- Produce a specific artifact
- Reach a conclusion
- Stay on topic if a tangent is valuable
- Be brief (this is thinking time)
---
## Handling Different Entry Points
**User brings a vague idea:**
```
User: I'm thinking about adding real-time collaboration
You: Real-time collab is a big space. Let me think about this...
COLLABORATION SPECTRUM
════════════════════════════════════════════
Awareness Coordination Sync
│ │ │
▼ ▼ ▼
┌────────┐ ┌────────┐ ┌────────┐
│Presence│ │Cursors │ │ CRDT │
│ "3 │ │ Multi │ │Conflict│
│online" │ │ select │ │ free │
└────────┘ └────────┘ └────────┘
│ │ │
trivial moderate complex
Where's your head at?
```
**User brings a specific problem:**
```
User: The auth system is a mess
You: [reads codebase]
┌─────────────────────────────────────────────┐
│ CURRENT AUTH FLOW │
└─────────────────────────────────────────────┘
│
┌─────────────┼─────────────┐
▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌─────────┐
│ Google │ │ GitHub │ │ Email │
│ OAuth │ │ OAuth │ │ Magic │
└────┬────┘ └────┬────┘ └────┬────┘
│ │ │
└─────────────┼─────────────┘
▼
┌───────────┐
│ Session │
└─────┬─────┘
│
▼
┌───────────┐
│ Perms │
└───────────┘
I see three tangles. Which one's burning?
```
**User is stuck mid-implementation:**
```
User: /opsx:explore add-auth-system
The OAuth integration is more complex than expected
You: [reads change artifacts]
You're on task 4: "Implement OAuth flow"
Let me trace what's involved...
[draws diagram, explores options, suggests paths]
Want to update the design to reflect this?
Or add a spike task to investigate?
```
**User wants to compare options:**
```
User: Should we use Postgres or SQLite?
You: Generic answer is boring. What's the context?
User: A CLI tool that tracks local dev environments
You: That changes everything.
┌─────────────────────────────────────────────────┐
│ CLI TOOL DATA STORAGE │
└─────────────────────────────────────────────────┘
Key constraints:
• No daemon running
• Must work offline
• Single user
SQLite Postgres
Deployment embedded ✓ needs server ✗
Offline yes ✓ no ✗
Single file yes ✓ no ✗
SQLite. Not even close.
Unless... is there a sync component?
```
---
## Ending Discovery
There's no required ending. Discovery might:
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
- **Result in artifact updates**: "Updated design.md with these decisions"
- **Just provide clarity**: User has what they need, moves on
- **Continue later**: "We can pick this up anytime"
When it feels like things are crystallizing, you might summarize:
```
## What We Figured Out
**The problem**: [crystallized understanding]
**The approach**: [if one emerged]
**Open questions**: [if any remain]
**Next steps** (if ready):
- Create a change proposal
- Keep exploring: just keep talking
```
But this summary is optional. Sometimes the thinking IS the value.
---
## Guardrails
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
- **Don't fake understanding** - If something is unclear, dig deeper
- **Don't rush** - Discovery is thinking time, not task time
- **Don't force structure** - Let patterns emerge naturally
- **Don't auto-capture** - Offer to save insights, don't just do it
- **Do visualize** - A good diagram is worth many paragraphs
- **Do explore the codebase** - Ground discussions in reality
- **Do question assumptions** - Including the user's and your own

View File

@@ -0,0 +1,110 @@
---
name: openspec-propose
description: Propose a new change with all artifacts generated in one step. Use when the user wants to quickly describe what they want to build and get a complete proposal with design, specs, and tasks ready for implementation.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.3.1"
---
Propose a new change - create the change and generate all artifacts in one step.
I'll create a change with artifacts:
- proposal.md (what & why)
- design.md (how)
- tasks.md (implementation steps)
When ready to implement, run /opsx:apply
---
**Input**: The user's request should include a change name (kebab-case) OR a description of what they want to build.
**Steps**
1. **If no clear input provided, ask what they want to build**
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
> "What change do you want to work on? Describe what you want to build or fix."
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
2. **Create the change directory**
```bash
openspec new change "<name>"
```
This creates a scaffolded change at `openspec/changes/<name>/` with `.openspec.yaml`.
3. **Get the artifact build order**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to get:
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
- `artifacts`: list of all artifacts with their status and dependencies
4. **Create artifacts in sequence until apply-ready**
Use the **TodoWrite tool** to track progress through the artifacts.
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
a. **For each artifact that is `ready` (dependencies satisfied)**:
- Get instructions:
```bash
openspec instructions <artifact-id> --change "<name>" --json
```
- The instructions JSON includes:
- `context`: Project background (constraints for you - do NOT include in output)
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
- `template`: The structure to use for your output file
- `instruction`: Schema-specific guidance for this artifact type
- `outputPath`: Where to write the artifact
- `dependencies`: Completed artifacts to read for context
- Read any completed dependency files for context
- Create the artifact file using `template` as the structure
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>"
b. **Continue until all `applyRequires` artifacts are complete**
- After creating each artifact, re-run `openspec status --change "<name>" --json`
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
- Stop when all `applyRequires` artifacts are done
c. **If an artifact requires user input** (unclear context):
- Use **AskUserQuestion tool** to clarify
- Then continue with creation
5. **Show final status**
```bash
openspec status --change "<name>"
```
**Output**
After completing all artifacts, summarize:
- Change name and location
- List of artifacts created with brief descriptions
- What's ready: "All artifacts created! Ready for implementation."
- Prompt: "Run `/opsx:apply` or ask me to implement to start working on the tasks."
**Artifact Creation Guidelines**
- Follow the `instruction` field from `openspec instructions` for each artifact type
- The schema defines what each artifact should contain - follow it
- Read dependency artifacts for context before creating new ones
- Use `template` as the structure for your output file - fill in its sections
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
- These guide what you write, but should never appear in the output
**Guardrails**
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
- Always read dependency artifacts before creating a new one
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
- If a change with that name already exists, ask if user wants to continue it or create a new one
- Verify each artifact file exists after writing before proceeding to next

View File

@@ -0,0 +1,156 @@
---
name: "source-command-opsx-apply"
description: "Implement tasks from an OpenSpec change (Experimental)"
---
# source-command-opsx-apply
Use this skill when the user asks to run the migrated source command `opsx-apply`.
## Command Template
Implement tasks from an OpenSpec change.
**Input**: Optionally specify a change name (e.g., `/opsx:apply add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and use the **AskUserQuestion tool** to let the user select
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <other>`).
2. **Check status to understand the schema**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand:
- `schemaName`: The workflow being used (e.g., "spec-driven")
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
3. **Get apply instructions**
```bash
openspec instructions apply --change "<name>" --json
```
This returns:
- `contextFiles`: artifact ID -> array of concrete file paths (varies by schema)
- Progress (total, complete, remaining)
- Task list with status
- Dynamic instruction based on current state
**Handle states:**
- If `state: "blocked"` (missing artifacts): show message, suggest using `/opsx:continue`
- If `state: "all_done"`: congratulate, suggest archive
- Otherwise: proceed to implementation
4. **Read context files**
Read every file path listed under `contextFiles` from the apply instructions output.
The files depend on the schema being used:
- **spec-driven**: proposal, specs, design, tasks
- Other schemas: follow the contextFiles from CLI output
5. **Show current progress**
Display:
- Schema being used
- Progress: "N/M tasks complete"
- Remaining tasks overview
- Dynamic instruction from CLI
6. **Implement tasks (loop until done or blocked)**
For each pending task:
- Show which task is being worked on
- Make the code changes required
- Keep changes minimal and focused
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
- Continue to next task
**Pause if:**
- Task is unclear → ask for clarification
- Implementation reveals a design issue → suggest updating artifacts
- Error or blocker encountered → report and wait for guidance
- User interrupts
7. **On completion or pause, show status**
Display:
- Tasks completed this session
- Overall progress: "N/M tasks complete"
- If all done: suggest archive
- If paused: explain why and wait for guidance
**Output During Implementation**
```
## Implementing: <change-name> (schema: <schema-name>)
Working on task 3/7: <task description>
[...implementation happening...]
✓ Task complete
Working on task 4/7: <task description>
[...implementation happening...]
✓ Task complete
```
**Output On Completion**
```
## Implementation Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 7/7 tasks complete ✓
### Completed This Session
- [x] Task 1
- [x] Task 2
...
All tasks complete! You can archive this change with `/opsx:archive`.
```
**Output On Pause (Issue Encountered)**
```
## Implementation Paused
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 4/7 tasks complete
### Issue Encountered
<description of the issue>
**Options:**
1. <option 1>
2. <option 2>
3. Other approach
What would you like to do?
```
**Guardrails**
- Keep going through tasks until done or blocked
- Always read context files before starting (from the apply instructions output)
- If task is ambiguous, pause and ask before implementing
- If implementation reveals issues, pause and suggest artifact updates
- Keep code changes minimal and scoped to each task
- Update task checkbox immediately after completing each task
- Pause on errors, blockers, or unclear requirements - don't guess
- Use contextFiles from CLI output, don't assume specific file names
**Fluid Workflow Integration**
This skill supports the "actions on a change" model:
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly

View File

@@ -0,0 +1,161 @@
---
name: "source-command-opsx-archive"
description: "Archive a completed change in the experimental workflow"
---
# source-command-opsx-archive
Use this skill when the user asks to run the migrated source command `opsx-archive`.
## Command Template
Archive a completed change in the experimental workflow.
**Input**: Optionally specify a change name after `/opsx:archive` (e.g., `/opsx:archive add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **If no change name provided, prompt for selection**
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
Show only active changes (not already archived).
Include the schema used for each change if available.
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
2. **Check artifact completion status**
Run `openspec status --change "<name>" --json` to check artifact completion.
Parse the JSON to understand:
- `schemaName`: The workflow being used
- `artifacts`: List of artifacts with their status (`done` or other)
**If any artifacts are not `done`:**
- Display warning listing incomplete artifacts
- Prompt user for confirmation to continue
- Proceed if user confirms
3. **Check task completion status**
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
**If incomplete tasks found:**
- Display warning showing count of incomplete tasks
- Prompt user for confirmation to continue
- Proceed if user confirms
**If no tasks file exists:** Proceed without task-related warning.
4. **Assess delta spec sync state**
Check for delta specs at `openspec/changes/<name>/specs/`. If none exist, proceed without sync prompt.
**If delta specs exist:**
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
- Determine what changes would be applied (adds, modifications, removals, renames)
- Show a combined summary before prompting
**Prompt options:**
- If changes needed: "Sync now (recommended)", "Archive without syncing"
- If already synced: "Archive now", "Sync anyway", "Cancel"
If user chooses sync, use Task tool (subagent_type: "general-purpose", prompt: "Use Skill tool to invoke openspec-sync-specs for change '<name>'. Delta spec analysis: <include the analyzed delta spec summary>"). Proceed to archive regardless of choice.
5. **Perform the archive**
Create the archive directory if it doesn't exist:
```bash
mkdir -p openspec/changes/archive
```
Generate target name using current date: `YYYY-MM-DD-<change-name>`
**Check if target already exists:**
- If yes: Fail with error, suggest renaming existing archive or using different date
- If no: Move the change directory to archive
```bash
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
```
6. **Display summary**
Show archive completion summary including:
- Change name
- Schema that was used
- Archive location
- Spec sync status (synced / sync skipped / no delta specs)
- Note about any warnings (incomplete artifacts/tasks)
**Output On Success**
```
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** ✓ Synced to main specs
All artifacts complete. All tasks complete.
```
**Output On Success (No Delta Specs)**
```
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** No delta specs
All artifacts complete. All tasks complete.
```
**Output On Success With Warnings**
```
## Archive Complete (with warnings)
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** Sync skipped (user chose to skip)
**Warnings:**
- Archived with 2 incomplete artifacts
- Archived with 3 incomplete tasks
- Delta spec sync was skipped (user chose to skip)
Review the archive if this was not intentional.
```
**Output On Error (Archive Exists)**
```
## Archive Failed
**Change:** <change-name>
**Target:** openspec/changes/archive/YYYY-MM-DD-<name>/
Target archive directory already exists.
**Options:**
1. Rename the existing archive
2. Delete the existing archive if it's a duplicate
3. Wait until a different date to archive
```
**Guardrails**
- Always prompt for change selection if not provided
- Use artifact graph (openspec status --json) for completion checking
- Don't block archive on warnings - just inform and confirm
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
- Show clear summary of what happened
- If sync is requested, use the Skill tool to invoke `openspec-sync-specs` (agent-driven)
- If delta specs exist, always run the sync assessment and show the combined summary before prompting

View File

@@ -0,0 +1,177 @@
---
name: "source-command-opsx-explore"
description: "Enter explore mode - think through ideas, investigate problems, clarify requirements"
---
# source-command-opsx-explore
Use this skill when the user asks to run the migrated source command `opsx-explore`.
## Command Template
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
**Input**: The argument after `/opsx:explore` is whatever the user wants to think about. Could be:
- A vague idea: "real-time collaboration"
- A specific problem: "the auth system is getting unwieldy"
- A change name: "add-dark-mode" (to explore in context of that change)
- A comparison: "postgres vs sqlite for this"
- Nothing (just enter explore mode)
---
## The Stance
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
- **Adaptive** - Follow interesting threads, pivot when new information emerges
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
---
## What You Might Do
Depending on what the user brings, you might:
**Explore the problem space**
- Ask clarifying questions that emerge from what they said
- Challenge assumptions
- Reframe the problem
- Find analogies
**Investigate the codebase**
- Map existing architecture relevant to the discussion
- Find integration points
- Identify patterns already in use
- Surface hidden complexity
**Compare options**
- Brainstorm multiple approaches
- Build comparison tables
- Sketch tradeoffs
- Recommend a path (if asked)
**Visualize**
```
┌─────────────────────────────────────────┐
│ Use ASCII diagrams liberally │
├─────────────────────────────────────────┤
│ │
│ ┌────────┐ ┌────────┐ │
│ │ State │────────▶│ State │ │
│ │ A │ │ B │ │
│ └────────┘ └────────┘ │
│ │
│ System diagrams, state machines, │
│ data flows, architecture sketches, │
│ dependency graphs, comparison tables │
│ │
└─────────────────────────────────────────┘
```
**Surface risks and unknowns**
- Identify what could go wrong
- Find gaps in understanding
- Suggest spikes or investigations
---
## OpenSpec Awareness
You have full context of the OpenSpec system. Use it naturally, don't force it.
### Check for context
At the start, quickly check what exists:
```bash
openspec list --json
```
This tells you:
- If there are active changes
- Their names, schemas, and status
- What the user might be working on
If the user mentioned a specific change name, read its artifacts for context.
### When no change exists
Think freely. When insights crystallize, you might offer:
- "This feels solid enough to start a change. Want me to create a proposal?"
- Or keep exploring - no pressure to formalize
### When a change exists
If the user mentions a change or you detect one is relevant:
1. **Read existing artifacts for context**
- `openspec/changes/<name>/proposal.md`
- `openspec/changes/<name>/design.md`
- `openspec/changes/<name>/tasks.md`
- etc.
2. **Reference them naturally in conversation**
- "Your design mentions using Redis, but we just realized SQLite fits better..."
- "The proposal scopes this to premium users, but we're now thinking everyone..."
3. **Offer to capture when decisions are made**
| Insight Type | Where to Capture |
|----------------------------|--------------------------------|
| New requirement discovered | `specs/<capability>/spec.md` |
| Requirement changed | `specs/<capability>/spec.md` |
| Design decision made | `design.md` |
| Scope changed | `proposal.md` |
| New work identified | `tasks.md` |
| Assumption invalidated | Relevant artifact |
Example offers:
- "That's a design decision. Capture it in design.md?"
- "This is a new requirement. Add it to specs?"
- "This changes scope. Update the proposal?"
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
---
## What You Don't Have To Do
- Follow a script
- Ask the same questions every time
- Produce a specific artifact
- Reach a conclusion
- Stay on topic if a tangent is valuable
- Be brief (this is thinking time)
---
## Ending Discovery
There's no required ending. Discovery might:
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
- **Result in artifact updates**: "Updated design.md with these decisions"
- **Just provide clarity**: User has what they need, moves on
- **Continue later**: "We can pick this up anytime"
When things crystallize, you might offer a summary - but it's optional. Sometimes the thinking IS the value.
---
## Guardrails
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
- **Don't fake understanding** - If something is unclear, dig deeper
- **Don't rush** - Discovery is thinking time, not task time
- **Don't force structure** - Let patterns emerge naturally
- **Don't auto-capture** - Offer to save insights, don't just do it
- **Do visualize** - A good diagram is worth many paragraphs
- **Do explore the codebase** - Ground discussions in reality
- **Do question assumptions** - Including the user's and your own

View File

@@ -0,0 +1,110 @@
---
name: "source-command-opsx-propose"
description: "Propose a new change - create it and generate all artifacts in one step"
---
# source-command-opsx-propose
Use this skill when the user asks to run the migrated source command `opsx-propose`.
## Command Template
Propose a new change - create the change and generate all artifacts in one step.
I'll create a change with artifacts:
- proposal.md (what & why)
- design.md (how)
- tasks.md (implementation steps)
When ready to implement, run /opsx:apply
---
**Input**: The argument after `/opsx:propose` is the change name (kebab-case), OR a description of what the user wants to build.
**Steps**
1. **If no input provided, ask what they want to build**
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
> "What change do you want to work on? Describe what you want to build or fix."
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
2. **Create the change directory**
```bash
openspec new change "<name>"
```
This creates a scaffolded change at `openspec/changes/<name>/` with `.openspec.yaml`.
3. **Get the artifact build order**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to get:
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
- `artifacts`: list of all artifacts with their status and dependencies
4. **Create artifacts in sequence until apply-ready**
Use the **TodoWrite tool** to track progress through the artifacts.
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
a. **For each artifact that is `ready` (dependencies satisfied)**:
- Get instructions:
```bash
openspec instructions <artifact-id> --change "<name>" --json
```
- The instructions JSON includes:
- `context`: Project background (constraints for you - do NOT include in output)
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
- `template`: The structure to use for your output file
- `instruction`: Schema-specific guidance for this artifact type
- `outputPath`: Where to write the artifact
- `dependencies`: Completed artifacts to read for context
- Read any completed dependency files for context
- Create the artifact file using `template` as the structure
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>"
b. **Continue until all `applyRequires` artifacts are complete**
- After creating each artifact, re-run `openspec status --change "<name>" --json`
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
- Stop when all `applyRequires` artifacts are done
c. **If an artifact requires user input** (unclear context):
- Use **AskUserQuestion tool** to clarify
- Then continue with creation
5. **Show final status**
```bash
openspec status --change "<name>"
```
**Output**
After completing all artifacts, summarize:
- Change name and location
- List of artifacts created with brief descriptions
- What's ready: "All artifacts created! Ready for implementation."
- Prompt: "Run `/opsx:apply` to start implementing."
**Artifact Creation Guidelines**
- Follow the `instruction` field from `openspec instructions` for each artifact type
- The schema defines what each artifact should contain - follow it
- Read dependency artifacts for context before creating new ones
- Use `template` as the structure for your output file - fill in its sections
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
- These guide what you write, but should never appear in the output
**Guardrails**
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
- Always read dependency artifacts before creating a new one
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
- If a change with that name already exists, ask if user wants to continue it or create a new one
- Verify each artifact file exists after writing before proceeding to next

132
.gitattributes vendored
View File

@@ -1 +1,131 @@
*.blend filter=lfs diff=lfs merge=lfs -text # Define macros (only works in top-level gitattributes files)
[attr]lfs filter=lfs diff=lfs merge=lfs -text
# 3D models
*.collada lfs
*.dae lfs
*.dxf lfs
*.FBX lfs
*.fbx lfs
*.jas lfs
*.lws lfs
*.lxo lfs
*.obj lfs
*.ply lfs
*.skp lfs
*.stl lfs
*.stp lfs
*.usd lfs
*.usda lfs
*.usdc lfs
*.usdz lfs
*.glb lfs
*.gltf lfs
# Audio
*.aif lfs
*.aiff lfs
*.it lfs
*.mod lfs
*.mp3 lfs
*.ogg lfs
*.s3m lfs
*.wav lfs
*.xm lfs
# Video
*.asf lfs
*.avi lfs
*.flv lfs
*.mov lfs
*.mp4 lfs
*.mpeg lfs
*.mpg lfs
*.ogv lfs
*.wmv lfs
*.mkv lfs
# Images
*.bmp lfs
*.exr lfs
*.gif lfs
*.hdr lfs
*.iff lfs
*.jpeg lfs
*.jpg lfs
*.pict lfs
*.png lfs
*.psd lfs
*.tga lfs
*.tif lfs
*.tiff lfs
*.webp lfs
# Compressed Archive
*.7z lfs
*.bz2 lfs
*.gz lfs
*.rar lfs
*.tar lfs
*.zip lfs
# Compiled Dynamic Library
*.dll lfs
*.pdb lfs
*.so lfs
# Fonts
*.otf lfs
*.ttf lfs
*.woff lfs
*.woff2 lfs
# Executable/Installer
*.apk lfs
*.exe lfs
# Documents
*.pdf lfs
*.doc lfs
*.xls lfs
*.ppt lfs
*.docx lfs
*.xlsx lfs
*.pptx lfs
# Adobe
*.psd lfs
*.ai lfs
*.aep lfs
*.prproj lfs
*.spp lfs
# Zbrush
*.zbr lfs
*.zpr lfs
*.ztl lfs
*.c4d lfs
# Autodesk
*.max lfs
*.ma lfs
*.mb lfs
*.3dm lfs
*.3ds lfs
# Blender
*.blend lfs
*.blend1 lfs
*.c4d lfs
# Imaging
*.dicom lfs
*.dcm lfs
*.nii lfs
*.ome lfs
*.map lfs
*.mrc lfs
# Others
*.abr lfs
*.tpl lfs

View File

@@ -1,31 +1,12 @@
name: Upload Assets to Release name: Release Version
on: on:
push: push:
branches: tags:
- "release/*" # Publish on any tag starting with a `v`, e.g., v0.1.0
- 'v*'
jobs: jobs:
# draft_release:
# name: Draft Release
# runs-on: ubuntu-latest
# outputs:
# upload_url: ${{ steps.draft_release.outputs.upload_url }}
# version: ${{ steps.set_env.outputs.version }}
# steps:
# - name: Set Version Env
# id: set_env
# run: |
# ref_name=${{ github.ref_name }}
# echo "version=${ref_name#release/}" >> "$GITHUB_OUTPUT"
# - name: Get release
# id: draft_release
# uses: cardinalby/git-get-release-action@1.2.4
# with:
# releaseName: Draft
# env:
# GITHUB_TOKEN: ${{ github.token }}
draft_release: draft_release:
name: Draft Release name: Draft Release
permissions: permissions:
@@ -50,19 +31,32 @@ jobs:
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
upload_blender_addon: build_extension:
name: Upload Blender Add-on name: Build Blender Extension
needs: draft_release needs: draft_release
runs-on: ubuntu-latest runs-on: ubuntu-latest
strategy:
matrix:
platform: ["windows-x64", "linux-x64", "macos-arm64", "macos-x64"]
steps: steps:
- name: Checkout Code - name: Checkout Code
uses: actions/checkout@v4 uses: actions/checkout@v4
with: with:
lfs: 'true' lfs: "true"
- name: Zip Add-on - name: Install uv
uses: astral-sh/setup-uv@v7
- name: Install Dependencies
run: | run: |
zip -r package.zip bioxelnodes uv python install 3.11
- name: Upload Release Asset uv python pin 3.11
uv sync
- name: Build Extension
run: | # build.py need tomlkit to edit blender_manifest.toml
uv run build.py ${{ matrix.platform }} 3.11
uv run build.py ${{ matrix.platform }} 3.13
cd src/bioxelnodes
zip -r ../../package.zip .
- name: Upload Extension
id: upload-release-asset id: upload-release-asset
uses: actions/upload-release-asset@v1 uses: actions/upload-release-asset@v1
env: env:
@@ -70,5 +64,5 @@ jobs:
with: with:
upload_url: ${{ needs.draft_release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps upload_url: ${{ needs.draft_release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps
asset_path: ./package.zip asset_path: ./package.zip
asset_name: BioxelNodes_${{ needs.draft_release.outputs.version }}.zip asset_name: BioxelNodes.${{ needs.draft_release.outputs.version }}.${{ matrix.platform }}.zip
asset_content_type: application/zip asset_content_type: application/zip

294
.gitignore vendored
View File

@@ -1,6 +1,51 @@
# Tempary files
temp
sandbox.*
/notes/
# Environments
.env
.envrc
.venv
.env.*
!.env.example
env/
venv/
ENV/
env.bak/
venv.bak/
.secrets
.secrets.*
!.secrets.example
secrets/
SECRETS/
secrets.bak/
# Claude Code
.claude/settings.local.json
.claudian
# Obsidian
.obsidian/*
!.obsidian/snippets
!.obsidian/app.json
*.canvas
# Keep odox for extract to openwiki
!.obsidian/plugins
.obsidian/plugins/*
!.obsidian/plugins/odox
# Blender
*.blend1
blender_assets.cats.txt~
blendcache_*
# Byte-compiled / optimized / DLL files # Byte-compiled / optimized / DLL files
__pycache__/ __pycache__/
*.py[cod] *.py[codz]
*$py.class *$py.class
# C extensions # C extensions
@@ -20,7 +65,6 @@ parts/
sdist/ sdist/
var/ var/
wheels/ wheels/
pip-wheel-metadata/
share/python-wheels/ share/python-wheels/
*.egg-info/ *.egg-info/
.installed.cfg .installed.cfg
@@ -47,8 +91,10 @@ htmlcov/
nosetests.xml nosetests.xml
coverage.xml coverage.xml
*.cover *.cover
*.py.cover
.hypothesis/ .hypothesis/
.pytest_cache/ .pytest_cache/
cover/
# Translations # Translations
*.mo *.mo
@@ -71,6 +117,7 @@ instance/
docs/_build/ docs/_build/
# PyBuilder # PyBuilder
.pybuilder/
target/ target/
# Jupyter Notebook # Jupyter Notebook
@@ -81,7 +128,9 @@ profile_default/
ipython_config.py ipython_config.py
# pyenv # pyenv
.python-version # For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv # pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
@@ -90,21 +139,59 @@ ipython_config.py
# install all needed dependencies. # install all needed dependencies.
# Pipfile.lock # Pipfile.lock
# celery beat schedule file # UV
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# uv.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
# poetry.lock
# poetry.toml
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
# pdm.lock
# pdm.toml
.pdm-python
.pdm-build/
# pixi
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
# pixi.lock
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
# in the .venv directory. It is recommended not to include this directory in version control.
.pixi
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule celerybeat-schedule
celerybeat.pid
# Redis
*.rdb
*.aof
*.pid
# RabbitMQ
mnesia/
rabbitmq/
rabbitmq-data/
# ActiveMQ
activemq-data/
# SageMath parsed files # SageMath parsed files
*.sage.py *.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings # Spyder project settings
.spyderproject .spyderproject
.spyproject .spyproject
@@ -123,12 +210,183 @@ dmypy.json
# Pyre type checker # Pyre type checker
.pyre/ .pyre/
pythonlib* # pytype static type analyzer
.pytype/
*.blend1 # Cython debug symbols
cython_debug/
blendcache_* # PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
# .idea/
*.ipynb # Abstra
# Abstra is an AI-powered process automation framework.
# Ignore directories containing user credentials, local state, and settings.
# Learn more at https://abstra.io/docs
.abstra/
.secrets # Visual Studio Code
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
# and can be added to the global gitignore or merged into this file. However, if you prefer,
# you could uncomment the following to ignore the entire vscode folder
# .vscode/
# Ruff stuff:
.ruff_cache/
# PyPI configuration file
.pypirc
# Marimo
marimo/_static/
marimo/_lsp/
__marimo__/
# Streamlit
.streamlit/secrets.toml
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
.output
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Sveltekit cache directory
.svelte-kit/
# vitepress build output
**/.vitepress/dist
# vitepress cache directory
**/.vitepress/cache
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# Firebase cache directory
.firebase/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# pnpm
.pnpm-store
# yarn v3
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/sdks
!.yarn/versions
# Vite files
vite.config.js.timestamp-*
vite.config.ts.timestamp-*
.vite/

22
.obsidian/app.json vendored Normal file
View File

@@ -0,0 +1,22 @@
{
"showInlineTitle": false,
"useMarkdownLinks": true,
"pdfExportSettings": {
"pageSize": "Letter",
"landscape": false,
"margin": "0",
"downscalePercent": 100
},
"userIgnoreFilters": [
"notes/assets/"
],
"showUnsupportedFiles": false,
"attachmentFolderPath": "notes/assets",
"livePreview": true,
"showIndentGuide": false,
"alwaysUpdateLinks": true,
"openBehavior": "file:README",
"newFileLocation": "folder",
"newFileFolderPath": "notes",
"newLinkFormat": "relative"
}

30
.obsidian/snippets/omoolab.css vendored Normal file
View File

@@ -0,0 +1,30 @@
/* not show label in canvas */
.canvas-node-label {
display: none;
}
.canvas-node-container:hover + .canvas-node-label {
display: inherit;
}
/* image caption */
.image-embed {
flex-wrap: wrap;
}
.image-embed[alt]:after {
content: attr(alt);
display: block;
padding-bottom: 12px;
line-height: 2.0;
font-style: italic;
color: var(--text-faint);
text-align: center;
width: 100%;
}
/* fix image in canvas */
.image-embed {
padding: 0;
}

11
.prettierrc Normal file
View File

@@ -0,0 +1,11 @@
{
"tabWidth": 2,
"overrides": [
{
"files": "*.md",
"options": {
"tabWidth": 4
}
}
]
}

1
.python-version Normal file
View File

@@ -0,0 +1 @@
3.11

11
.vscode/BioxelNodes.code-workspace vendored Normal file
View File

@@ -0,0 +1,11 @@
{
"folders": [
{
"path": ".."
},
{
"path": "../src/bioxelnodes"
}
],
"settings": {}
}

19
AGENTS.md Normal file
View File

@@ -0,0 +1,19 @@
## 总规范
- 说明性内容(例如提交说明、文档、注释、mermaid),以中文为主,专有名词、约定俗称可用英文
## Markdown 规范
- 不使用`---`分割器
- `# Heading` 一级标题仅用于开头
- mermaid 节点名用英文字符
## 代码规范
- 避免嵌套结构
- 特殊的、非常规的需要写注释
- 变量、函数名、Docstring 用全英文
- 同一事物用统一表达
- 使用的依赖越少越好
- 选用简单直接的方式实现
- 代码、执行方式改变,调整已有的文档、计划,而非新建

674
LICENSE Normal file
View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@@ -1,3 +1,46 @@
# BioxelNodes **v2.0.x has been released, supporting only Blender 5.0+. The usage is completely different from before and is not compatible with old version files. See http://docs.omoolab.xyz/bioxelnodes/2.0.x/en/basics/**
BioxelNodes is a blender add-on for better volume data visualization with cycles.
[中文文档](https://docs.omoolab.xyz/bioxelnodes/latest/)
# Bioxel Nodes
[![For Blender](https://img.shields.io/badge/Blender-orange?style=for-the-badge&logo=blender&logoColor=white&color=black)](https://blender.org/)
![GitHub License](https://img.shields.io/github/license/OmooLab/BioxelNodes?style=for-the-badge&labelColor=black)
![GitHub Release](https://img.shields.io/github/v/release/OmooLab/BioxelNodes?style=for-the-badge&labelColor=black)
![GitHub Repo stars](https://img.shields.io/github/stars/OmooLab/BioxelNodes?style=for-the-badge&labelColor=black)
[![Discord](https://img.shields.io/discord/1265129134397587457?style=for-the-badge&logo=discord&label=Discord&labelColor=white&color=black)](https://discord.gg/pYkNyq2TjE)
Bioxel Nodes is a Blender addon for scientific volumetric data visualization. It using Blender's powerful **Geometry Nodes** and **Cycles** to process and render volumetric data.
![cover](https://omoolab.github.io/BioxelNodes/latest/assets/cover.png)
## Features
- Realistic rendering result, also support EEVEE NEXT.
- Support many formats:.dcm, .jpg, .tif, .nii, .nrrd, .ome, .mrc...
- Support 4D volumetric data.
- Many kinds of cutters.
- Simple and powerful nodes.
- Based on blender natively, can work without addon.
| ![4D](https://omoolab.github.io/BioxelNodes/latest/assets/4d-time.gif) | ![EEVEE](https://omoolab.github.io/BioxelNodes/latest/assets/eevee.gif) |
| :--------------------------------------------------------------------: | :---------------------------------------------------------------------: |
| Support 4D volumetric data | Real-time render with eevee |
**Read the [getting started](https://docs.omoolab.xyz/bioxelnodes/latest/en/installation) to begin your journey into visualizing volumetric data!**
Welcome to our [discord server](https://discord.gg/pYkNyq2TjE), if you have any problems with this add-on.
## Citation
If you want to cite this work, you can cite it from Zenodo:
[![DOI](https://zenodo.org/badge/786623459.svg)](https://zenodo.org/badge/latestdoi/786623459)
## Roadmap
- Better multi-format import experience
- One-click bake model with texture
- AI Segmentation to Generate Labels

View File

@@ -1,34 +0,0 @@
from .nodes import custom_nodes
from . import auto_load
from . import menu
import bpy
bl_info = {
"name": "BiovelNodes",
"author": "Ma Nan",
"description": "",
"blender": (4, 0, 0),
"version": (0, 1, 0),
"location": "File -> Import",
"warning": "",
"category": "Import-Export"
}
auto_load.init()
def register():
auto_load.register()
custom_nodes.register()
menu.create_menu()
def unregister():
try:
menu.remove_menu()
custom_nodes.unregister()
auto_load.unregister()
except RuntimeError:
pass

Binary file not shown.

View File

@@ -1,46 +0,0 @@
import bpy
from .utils import get_bioxels_obj
class ConvertToMesh(bpy.types.Operator):
bl_idname = "bioxelnodes.convert_to_mesh"
bl_label = "Bioxels To Mesh"
bl_description = "Convert Bioxels To Mesh."
bl_options = {'UNDO'}
def execute(self, context):
bioxels_objs = []
for obj in bpy.context.selected_objects:
bioxels_obj = get_bioxels_obj(obj)
if bioxels_obj:
bioxels_objs.append(bioxels_obj)
if len(bioxels_objs)==0:
self.report({"WARNING"}, "Cannot find any bioxels.")
return {'FINISHED'}
for bioxels_obj in bioxels_objs:
bpy.ops.mesh.primitive_cube_add(
size=2, enter_editmode=False, align='WORLD', location=(0, 0, 0), scale=(1, 1, 1))
mesh_obj = bpy.context.active_object
mesh_obj.name = f"{bioxels_obj.parent.name}_Mesh"
bpy.ops.node.new_geometry_nodes_modifier()
modifier = mesh_obj.modifiers[0]
nodes = modifier.node_group.nodes
links = modifier.node_group.links
output_node = nodes.get("Group Output")
object_node = nodes.new("GeometryNodeObjectInfo")
realize_nodes = nodes.new("GeometryNodeRealizeInstances")
object_node.inputs[0].default_value = bioxels_obj
object_node.transform_space = 'RELATIVE'
links.new(object_node.outputs['Geometry'], realize_nodes.inputs[0])
links.new(realize_nodes.outputs[0], output_node.inputs[0])
bpy.ops.object.convert(target='MESH')
bpy.context.object.active_material_index = 1
bpy.ops.object.material_slot_remove()
return {'FINISHED'}

View File

@@ -1 +0,0 @@
from .node_menu import CustomNodes

View File

@@ -1,134 +0,0 @@
import bpy
from pathlib import Path
from .nodes import AddCustomNode
class CustomNodes():
def __init__(
self,
menu_items,
nodes_file,
root_label='CustomNodes',
root_icon='NONE'
) -> None:
if not Path(nodes_file).is_file():
raise FileNotFoundError(Path(nodes_file).resolve().as_posix())
self.menu_items = menu_items
self.nodes_file = Path(nodes_file).resolve().as_posix()
self.root_label = root_label
self.root_icon = root_icon
menu_classes = []
self._create_menu_class(
items=menu_items,
label=root_label,
menu_classes=menu_classes
)
self.menu_classes = menu_classes
idname = f"CUSTOMNODES_MT_NODES__{root_label.replace(' ', '').upper()}"
def add_node_menu(self, context):
if ('GeometryNodeTree' == bpy.context.area.spaces[0].tree_type):
layout = self.layout
layout.separator()
layout.menu(idname, icon=root_icon)
self.add_node_menu = add_node_menu
def _create_menu_class(self, menu_classes, items, label='CustomNodes', icon=0, idname_namespace=None):
nodes_file = self.nodes_file
idname_namespace = idname_namespace or "CUSTOMNODES_MT_NODES_"
idname = f"{idname_namespace}_{label.replace(' ', '').upper()}"
# create submenu class if item is menu.
for item in items:
item_items = item.get('items') if item != 'separator' else None
if item_items:
menu_class = self._create_menu_class(
menu_classes=menu_classes,
items=item_items,
label=item.get('label') or 'CustomNodes',
icon=item.get('icon') or 0,
idname_namespace=idname
)
item['menu_class'] = menu_class
# create menu class
class Menu(bpy.types.Menu):
bl_idname = idname
bl_label = label
def draw(self, context):
layout = self.layout
for item in items:
# print(item)
if item == "separator":
layout.separator()
elif item.get('menu_class'):
layout.menu(
item.get('menu_class').bl_idname,
icon=item.get('icon') or 'NONE'
)
else:
op = layout.operator(
'customnodes.add_custom_node',
text=item.get('label'),
icon=item.get('icon') or 'NONE'
)
op.nodes_file = nodes_file
op.node_type = item['node_type']
op.node_label = item.get('label') or ""
op.node_description = item.get(
'node_description') or "Add Custom Node."
op.node_link = item.get('link') or True
op.node_callback = item.get('node_callback') or ""
menu_classes.append(Menu)
return Menu
def _find_item(self, found_items, menu_items, node_type: str):
for item in menu_items:
if item.get("node_type") == node_type:
found_items.append(item)
item_items = item.get('items') if item != 'separator' else None
if item_items:
self._find_item(found_items, item_items, node_type)
def find_item(self, node_type: str):
found_items = []
self._find_item(found_items, self.menu_items, node_type)
return found_items[0] if len(found_items) > 0 else None
def add_node(self, node_tree, node_type: str):
item = self.find_item(node_type)
if item:
op = AddCustomNode()
op.nodes_file = self.nodes_file
op.node_type = item['node_type']
op.node_label = item.get('label') or ""
op.node_link = item.get('link') or True
op.node_callback = item.get('node_callback') or ""
return op.add_node(node_tree)
else:
raise RuntimeError("No custom node type found.")
def register(self):
for cls in self.menu_classes:
bpy.utils.register_class(cls)
bpy.types.NODE_MT_add.append(self.add_node_menu)
def unregister(self):
try:
for cls in reversed(self.menu_classes):
bpy.utils.unregister_class(cls)
bpy.types.NODE_MT_add.remove(self.add_node_menu)
except RuntimeError:
pass

View File

@@ -1,120 +0,0 @@
import bpy
class AddCustomNode():
nodes_file: bpy.props.StringProperty(
name="nodes_file",
subtype='FILE_PATH',
default=""
) # type: ignore
node_type: bpy.props.StringProperty(
name='node_type',
description='',
default='',
subtype='NONE',
maxlen=0
) # type: ignore
node_label: bpy.props.StringProperty(
name='node_label',
default=''
) # type: ignore
node_description: bpy.props.StringProperty(
name="node_description",
description="",
default="Add custom node group.",
subtype="NONE"
) # type: ignore
node_link: bpy.props.BoolProperty(
name='node_link',
default=True
) # type: ignore
node_callback: bpy.props.StringProperty(
name='node_callback',
default=''
) # type: ignore
@classmethod
def description(cls, context, properties):
return properties.node_description
def assign_node_tree(self, node):
node.node_tree = bpy.data.node_groups[self.node_type]
node.width = 200.0
node.label = self.node_label or self.node_type
node.name = self.node_type
if self.node_callback:
exec(self.node_callback)
return node
def get_node_tree(self, node_type, node_link):
# try to get node from current file if exists
node_tree = bpy.data.node_groups.get(node_type)
# if not exists, get it from asset file.
if not node_tree:
bpy.ops.wm.append(
'EXEC_DEFAULT',
directory=f"{self.nodes_file}/NodeTree",
filename=node_type,
link=node_link,
use_recursive=True
)
node_tree = bpy.data.node_groups.get(node_type)
if node_tree:
# self.recursive_append_material(node_tree)
return node_tree
else:
raise RuntimeError('No custom node found')
def recursive_append_material(self, node_tree):
for child in node_tree.nodes:
material_socket = child.inputs.get('Material')
if material_socket:
print(material_socket.default_value)
try:
self.recursive_append_material(child.node_tree)
except:
...
def add_node(self, node_tree):
self.get_node_tree(self.node_type, self.node_link)
node = node_tree.new("GeometryNodeGroup")
self.assign_node_tree(node)
return node
class CUSTOMNODES_OT_Add_Custom_Node(bpy.types.Operator, AddCustomNode):
bl_idname = "customnodes.add_custom_node"
bl_label = "Add Custom Node"
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
self.get_node_tree(self.node_type, self.node_link)
# intended to be called upon button press in the node tree
prev_context = bpy.context.area.type
bpy.context.area.type = 'NODE_EDITOR'
# actually invoke the operator to add a node to the current node tree
# use_transform=True ensures it appears where the user's mouse is and is currently
# being moved so the user can place it where they wish
bpy.ops.node.add_node(
'INVOKE_DEFAULT',
type='GeometryNodeGroup',
use_transform=True
)
bpy.context.area.type = prev_context
node = bpy.context.active_node
self.assign_node_tree(node)
return {"FINISHED"}

View File

@@ -1 +0,0 @@
from .preferences import ExternalPackagePreferences

View File

@@ -1,389 +0,0 @@
"""
Handling installation of external python packages inside of Blender's bundled python.
"""
import subprocess
import sys
import logging
from importlib.metadata import version as get_version, PackageNotFoundError
import bpy
from pathlib import Path
ADDON_NAME = __package__.split(".")[0]
PYPI_MIRROR = {
# the original.
'Default': '',
# two mirrors in China Mainland to help those poor victims under GFW.
'BFSU (Beijing)': 'https://mirrors.bfsu.edu.cn/pypi/web/simple',
'TUNA (Beijing)': 'https://pypi.tuna.tsinghua.edu.cn/simple',
# append more if necessary.
}
class InstallationError(Exception):
"""
Exception raised when there is an error installing a package.
Attributes
----------
package_name : str
The name of the package that failed to install.
error_message : str
The error message returned by pip.
"""
def __init__(self, package_name, error_message):
self.package_name = package_name
self.error_message = error_message
super().__init__(f"Failed to install {package_name}: {error_message}")
class PackageInstaller():
def __init__(
self,
log_dir: str,
requirements_dir: str,
pypi_mirror_provider='Default',
) -> None:
self.pypi_mirror_provider = pypi_mirror_provider
self.log_path: Path = Path(log_dir)
self.requirements_path: Path = Path(requirements_dir)
def start_logging(self, logfile_name: str = 'side-packages-install') -> logging.Logger:
"""
Configure and start logging to a file.
Parameters
----------
logfile_name : str, optional
The name of the log file. Defaults to 'side-packages-install'.
Returns
-------
logging.Logger
A Logger object that can be used to write log messages.
This function sets up a logging configuration with a specified log file name and logging level.
The log file will be created in the `ADDON_DIR/logs` directory. If the directory
does not exist, it will be created. The function returns a Logger object that can be used to
write log messages.
"""
# Create the logs directory if it doesn't exist
self.log_path.mkdir(parents=True, exist_ok=True)
# Set up logging configuration
logfile_path = Path(self.log_path, f"{logfile_name}.log")
logging.basicConfig(filename=logfile_path, level=logging.INFO)
# Return logger object
return logging.getLogger()
@property
def pypi_mirror_url(self) -> str:
"""
Process a PyPI mirror provider and return the corresponding URL.
Parameters
----------
pypi_mirror_provider : str
The PyPI mirror provider to process.
Returns
-------
str
The URL of the PyPI mirror.
Raises
------
ValueError
If the provided PyPI mirror provider is invalid.
"""
if self.pypi_mirror_provider.startswith('https:'):
return self.pypi_mirror_provider
elif self.pypi_mirror_provider in PYPI_MIRROR.keys():
return PYPI_MIRROR[self.pypi_mirror_provider]
else:
raise ValueError(
f"Invalid PyPI mirror provider: {self.pypi_mirror_provider}")
@property
def packages(self) -> dict:
"""
Read a requirements file and extract package information into a dictionary.
Parameters
----------
requirements : str, optional
The path to the requirements file. If not provided, the function looks for a `requirements.txt`
file in the same directory as the script.
Returns
-------
dict
A dictionary containing package information. Each element of the dictionary is a dictionary containing the package name, version, and description.
Example
-------
Given the following requirements file:
```python
Flask==1.1.2 # A micro web framework for Python
pandas==1.2.3 # A fast, powerful, flexible, and easy-to-use data analysis and manipulation tool
numpy==1.20.1 # Fundamental package for scientific computing
```
The function would return the following dictionary:
```python
[
{
"package": "Flask",
"version": "1.1.2",
"description": "A micro web framework for Python"
},
{
"package": "pandas",
"version": "1.2.3",
"description": "A fast, powerful, flexible, and easy-to-use data analysis and manipulation tool"
},
{
"package": "numpy",
"version": "1.20.1",
"description": "Fundamental package for scientific computing"
}
]
```
"""
requirements_filepath = self.requirements_path / "requirements.txt"
if requirements_filepath.is_file():
with requirements_filepath.open('r') as f:
lines = f.read().splitlines()
packages = {}
for line in lines:
try:
package, description = line.split('#')
package_meta = package.split('==')
name = package_meta[0].strip()
packages[name] = {
"name": name,
"version": package_meta[1].strip(),
"description": description.strip()
}
except ValueError:
# Skip line if it doesn't have the expected format
pass
return packages
else:
raise FileNotFoundError(requirements_filepath)
def is_installed(self, package_name: str) -> bool:
"""
Check if the specified package is installed and the version matches that specified
in the `requirements.txt` file.
Parameters
----------
package : str
The name of the package to check.
Returns
-------
bool
True if the package is the current version, False otherwise.
"""
package = self.packages.get(package_name)
try:
available_version = get_version(package['name'])
return available_version == package['version']
except PackageNotFoundError:
return False
def run_python(self, cmd_list: list = None, timeout: int = 600):
"""
Runs pip command using the specified command list and returns the command output.
Parameters
----------
cmd_list : list, optional
List of pip commands to be executed. Defaults to None.
mirror_url : str, optional
URL of a package repository mirror to be used for the command. Defaults to ''.
timeout : int, optional
Time in seconds to wait for the command to complete. Defaults to 600.
Returns
-------
tuple
A tuple containing the command list, command return code, command standard output,
and command standard error.
Example
-------
Install numpy using pip and print the command output
```python
cmd_list = ["-m", "pip", "install", "numpy"]
mirror_url = 'https://pypi.org/simple/'
cmd_output = run_python(cmd_list, timeout=300)
print(cmd_output)
```
"""
# path to python.exe
python_exe = Path(sys.executable).resolve().as_posix()
# build the command list
cmd_list = [python_exe] + cmd_list
# add mirror to the command list if it's valid
if self.pypi_mirror_url and self.pypi_mirror_url.startswith('https'):
cmd_list += ['-i', self.pypi_mirror_url]
log = self.start_logging()
log.info(f"Running Pip: '{cmd_list}'")
# run the command and capture the output
result = subprocess.run(cmd_list, timeout=timeout,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if result.returncode != 0:
log.error('Command failed: %s', cmd_list)
log.error('stdout: %s', result.stdout.decode())
log.error('stderr: %s', result.stderr.decode())
else:
log.info('Command succeeded: %s', cmd_list)
log.info('stdout: %s', result.stdout.decode())
# return the command list, return code, stdout, and stderr as a tuple
return result
def install_package(self, package: str) -> list:
"""
Install a Python package and its dependencies using pip.
Parameters
----------
package : str
The name of the package to install.
pypi_mirror_provider : str, optional
The name/url of the PyPI mirror provider to use. Default is 'Default'.
Returns
-------
list
A list of tuples containing the command list, return code, stdout, and stderr
for each pip command run.
Raises
------
ValueError
If the package name is not provided.
Example
-------
To install the package 'requests' from the PyPI mirror 'MyMirror', use:
```
install_package('requests', 'MyMirror')
```
"""
if not package:
raise ValueError("Package name must be provided.")
print(f"Installing {package}...")
print(f"Using PyPI mirror: {self.pypi_mirror_provider}")
self.run_python(["-m", "ensurepip"]),
self.run_python(["-m", "pip", "install", "--upgrade", "pip"])
result = self.run_python(["-m", "pip", "install", package, "--user"])
return result
def install_all_packages(self, pypi_mirror_provider: str = 'Default') -> list:
"""
Install all packages listed in the 'requirements.txt' file.
Parameters
----------
pypi_mirror_provider : str, optional
The PyPI mirror to use for package installation. Defaults to 'Default',
which uses the official PyPI repository.
Returns
-------
list
A list of tuples containing the installation results for each package.
Raises
------
InstallationError
If there is an error during package installation.
Example
-------
To install all packages listed in the 'requirements.txt' file, run the following command:
```
install_all_packages(pypi_mirror_provider='https://pypi.org/simple/')
```
"""
results = []
for package in self.packages.items():
try:
result = self.install_package(
package=f"{package.get('name')}=={package.get('version')}"
)
results.append(result)
except InstallationError as e:
raise InstallationError(
f"Error installing package {package.get('name')}: {str(e)}")
return results
class EXTERNALPACKAGE_OT_Install_Package(bpy.types.Operator):
bl_idname = 'externalpackage.install_package'
bl_label = 'Install Given Python Package'
bl_options = {'REGISTER', 'INTERNAL'}
package: bpy.props.StringProperty(
name='Python Package',
description='Python Package to Install'
) # type: ignore
version: bpy.props.StringProperty(
name='Python Package',
description='Python Package to Install'
) # type: ignore
description: bpy.props.StringProperty(
name='Operator description',
default='Install specified python package.'
) # type: ignore
@classmethod
def description(cls, context, properties):
return properties.description
def execute(self, context):
preferences = context.preferences.addons[ADDON_NAME].preferences
installer = PackageInstaller(
pypi_mirror_provider=preferences.pypi_mirror_provider,
log_dir=preferences.log_dir,
requirements_dir=preferences.requirements_dir
)
result = installer.install_package(f"{self.package}=={self.version}")
if result.returncode == 0 and installer.is_installed(self.package):
self.report(
{'INFO'},
f"Successfully installed {self.package} v{self.version}"
)
else:
self.report(
{'ERROR'},
f"""
Error installing package. Please check the log files
in {preferences.log_dir}.
"""
)
return {'FINISHED'}

View File

@@ -1,73 +0,0 @@
import bpy
from pathlib import Path
from .package import PackageInstaller, PYPI_MIRROR
# Defines the preferences panel for the addon, which shows the buttons for
# installing and reinstalling the required python packages defined in 'requirements.txt'
def get_pypi_mirrors(self, context, edit_text):
return PYPI_MIRROR.keys()
class ExternalPackagePreferences():
requirements_dir: bpy.props.StringProperty(
name="requirements.txt Directory",
subtype='DIR_PATH',
default=Path(__file__).parent.as_posix()
) # type: ignore
log_dir: bpy.props.StringProperty(
name="Python Log Directory",
subtype='DIR_PATH',
default=Path(Path.home(), '.externalpackage', 'logs').as_posix()
) # type: ignore
pypi_mirror_provider: bpy.props.StringProperty(
name='pypi_mirror_provider',
description='PyPI Mirror Provider',
options={'TEXTEDIT_UPDATE', 'LIBRARY_EDITABLE'},
default='Default',
subtype='NONE',
search=get_pypi_mirrors,
) # type: ignore
def draw(self, context):
layout = self.layout
layout.label(text="Install the required packages.")
col_main = layout.column(heading='', align=False)
row_import = col_main.row()
row_import.prop(self, 'pypi_mirror_provider', text='Set PyPI Mirror')
installer = PackageInstaller(
pypi_mirror_provider=self.pypi_mirror_provider,
log_dir=self.log_dir,
requirements_dir=self.requirements_dir
)
for package in installer.packages.values():
name = package.get('name')
version = package.get('version')
description = package.get('description')
if installer.is_installed(name):
row = layout.row()
row.label(text=f"{name} version {version} is installed.")
op = row.operator('externalpackage.install_package',
text=f'Reinstall {name}')
op.package = name
op.version = version
op.description = f'Reinstall {name}'
else:
row = layout.row(heading=f"Package: {name}")
col = row.column()
col.label(text=str(description))
col = row.column()
op = col.operator('externalpackage.install_package',
text=f'Install {name}')
op.package = name
op.version = version
op.description = f'Install required python package: {name}'

View File

@@ -1,486 +0,0 @@
import bpy
import shutil
from bpy_extras.io_utils import axis_conversion
import pyopenvdb as vdb
import numpy as np
from pathlib import Path
from uuid import uuid4
import mathutils
from .utils import calc_bbox_verts, extract_last_number, get_bioxels_obj, show_message
from .nodes import custom_nodes
SUPPORT_EXTS = ['.dcm', '.tif', '.tiff', '.png', '.bmp', '', '.jpg']
def get_data_files(filepath: str):
file_path = Path(filepath).resolve()
suffix = file_path.suffix
files = list(file_path.parent.iterdir())
files = [f for f in files if f.is_file() and f.suffix == suffix]
def last_number(file: Path):
return extract_last_number(file.stem)
files.sort(key=last_number)
files = [f.as_posix() for f in files]
return files
def on_orig_spacing_changed(self, context):
if self.auto:
self.auto = False
new_orig_spacing = tuple(self.orig_spacing)
orig_shape = tuple(self.orig_shape)
bioxel_size = float(self.bioxel_size)
self.bioxels_shape = (
int(orig_shape[0] / bioxel_size * new_orig_spacing[0]),
int(orig_shape[1] / bioxel_size * new_orig_spacing[1]),
int(orig_shape[2] / bioxel_size * new_orig_spacing[2]),
)
else:
self.auto = True
def on_bioxel_size_changed(self, context):
if self.auto:
self.auto = False
new_bioxel_size = float(self.bioxel_size)
orig_shape = tuple(self.orig_shape)
orig_spacing = tuple(self.orig_spacing)
self.bioxels_shape = (
int(orig_shape[0] / new_bioxel_size * orig_spacing[0]),
int(orig_shape[1] / new_bioxel_size * orig_spacing[1]),
int(orig_shape[2] / new_bioxel_size * orig_spacing[2]),
)
else:
self.auto = True
def on_info_changed(self, context):
for region in context.area.regions:
if region.type == "UI":
region.tag_redraw()
class ImportDICOMDialog(bpy.types.Operator):
bl_idname = "bioxelnodes.import_dicom_dialog"
bl_label = "Volume Data as Biovels"
bl_description = "Import Volume Data as Biovels (VDB)."
bl_options = {'UNDO'}
filepath: bpy.props.StringProperty(
subtype="FILE_PATH",
options={'HIDDEN'}
) # type: ignore
bioxels_shape: bpy.props.IntVectorProperty(
name="Bioxels Shape",
min=0,
default=(100, 100, 100)
) # type: ignore
bioxel_size: bpy.props.FloatProperty(
name="Bioxel Size",
soft_min=0.1, soft_max=10.0,
min=1e-2, max=1e2,
default=1,
update=on_bioxel_size_changed
) # type: ignore
orig_spacing: bpy.props.FloatVectorProperty(
name="Original Spacing",
default=(1, 1, 1),
update=on_orig_spacing_changed
) # type: ignore
orig_shape: bpy.props.IntVectorProperty(
name="Original Shape",
default=(100, 100, 100),
options={'HIDDEN'}
) # type: ignore
auto: bpy.props.BoolProperty(
name="Auto Setting",
default=False,
options={'HIDDEN'}
) # type: ignore
scene_scale: bpy.props.FloatProperty(
name="Scene Scale",
soft_min=0.001, soft_max=100.0,
min=1e-6, max=1e6,
default=0.01,
) # type: ignore
do_add_segmentnode: bpy.props.BoolProperty(
name="Add Segment Node",
default=True,
) # type: ignore
do_change_render_setting: bpy.props.BoolProperty(
name="Change Render Setting",
default=True,
) # type: ignore
def execute(self, context):
if not self.filepath:
self.report({"WARNING"}, "Get no file path.")
return {'CANCELLED'}
if Path(self.filepath).suffix not in SUPPORT_EXTS:
self.report({"WARNING"}, "Not Supported extension.")
return {'CANCELLED'}
file_path = Path(self.filepath).resolve()
name = file_path.parent.name
files = get_data_files(self.filepath)
import SimpleITK as sitk
image = sitk.ReadImage(files)
bioxel_size = float(self.bioxel_size)
orig_spacing = tuple(self.orig_spacing)
image_spacing = image.GetSpacing()
image_shape = image.GetSize()
bioxels_spacing = (
image_spacing[0] / orig_spacing[0] * bioxel_size,
image_spacing[1] / orig_spacing[1] * bioxel_size,
image_spacing[2] / orig_spacing[2] * bioxel_size
)
bioxels_shape = (
int(image_shape[0] / bioxel_size * orig_spacing[0]),
int(image_shape[1] / bioxel_size * orig_spacing[1]),
int(image_shape[2] / bioxel_size * orig_spacing[2]),
)
print("Bioxel Size:", bioxel_size)
print("Bioxels Shape:", bioxels_shape)
print("Resampling...")
image = sitk.Resample(
image1=image,
size=bioxels_shape,
transform=sitk.Transform(),
interpolator=sitk.sitkLinear,
outputOrigin=image.GetOrigin(),
outputSpacing=bioxels_spacing,
outputDirection=image.GetDirection(),
defaultPixelValue=0,
outputPixelType=image.GetPixelID(),
)
try:
image = sitk.DICOMOrient(image, 'RAS')
except:
...
array = sitk.GetArrayFromImage(image)
orig_dtype = str(array.dtype)
print(f"Coverting Dtype {orig_dtype} -> float")
array = array.astype(float)
# ITK indices, by convention, are [i,j,k] while NumPy indices are [k,j,i]
# https://www.slicer.org/wiki/Coordinate_systems
# ITK Numpy 3D
# R (ight) i -> k -> x
# A (nterior) j -> j -> y
# S (uperior) k -> i -> z
array = np.transpose(array)
bioxels_max = float(np.max(array))
bioxels_min = float(np.min(array))
bioxels_offset = 0.0
if bioxels_min < 0 and orig_dtype[0] != "u":
bioxels_offset = -bioxels_min
array = array + np.full_like(array, bioxels_offset)
bioxels_max = float(np.max(array))
bioxels_min = float(np.min(array))
print("Offseted Max:", bioxels_max)
print("Offseted Min:", bioxels_min)
# Build VDB
grid = vdb.FloatGrid()
grid.copyFromArray(array.copy())
# After sitk.DICOMOrient(), origin and direction will also orient base on LPS
# so we need to convert them into RAS
mat_lps2ras = axis_conversion(
from_forward='-Z',
from_up='-Y',
to_forward='-Z',
to_up='Y'
).to_4x4()
mat_location = mathutils.Matrix.Translation(
mathutils.Vector(image.GetOrigin())
)
mat_rotation = mathutils.Matrix(
np.array(image.GetDirection()).reshape((3, 3))
).to_4x4()
mat_scale = mathutils.Matrix.Scale(
bioxel_size, 4
)
transfrom = mat_lps2ras @ mat_location @ mat_rotation @ mat_scale
grid.transform = vdb.createLinearTransform(transfrom.transposed())
grid.name = "value"
preferences = context.preferences.addons[__package__].preferences
vdb_dirpath = Path(preferences.cache_dir, 'VDBs')
vdb_dirpath.mkdir(parents=True, exist_ok=True)
vdb_path = Path(vdb_dirpath, f"{uuid4()}.vdb")
print(f"Storing the VDB file ({vdb_path.as_posix()})...")
vdb.write(vdb_path.as_posix(), grids=[grid])
# Read VDB
print(f"Importing the VDB file to Blender scene...")
bpy.ops.object.volume_import(
filepath=vdb_path.as_posix(), align='WORLD', location=(0, 0, 0), scale=(1, 1, 1))
bioxels_obj = bpy.context.active_object
# Set props to VDB object
bioxels_obj.name = f"{name}_Bioxels"
bioxels_obj.data.name = f"{name}_Bioxels"
# Make transformation
scene_scale = float(self.scene_scale)
# (S)uperior -Z -> Y
# (A)osterior Y -> Z
mat_ras2blender = axis_conversion(
from_forward='-Z',
from_up='Y',
to_forward='Y',
to_up='Z'
).to_4x4()
mat_scene_scale = mathutils.Matrix.Scale(
scene_scale, 4
)
bioxels_obj.matrix_world = mat_ras2blender @ mat_scene_scale
bioxels_obj.lock_location[0] = True
bioxels_obj.lock_location[1] = True
bioxels_obj.lock_location[2] = True
bioxels_obj.lock_rotation[0] = True
bioxels_obj.lock_rotation[1] = True
bioxels_obj.lock_rotation[2] = True
bioxels_obj.lock_scale[0] = True
bioxels_obj.lock_scale[1] = True
bioxels_obj.lock_scale[2] = True
bioxels_obj.hide_select = True
bioxels_obj['bioxels'] = True
bpy.ops.node.new_geometry_nodes_modifier()
node_tree = bioxels_obj.modifiers[0].node_group
# Wrapper a Container
bpy.ops.mesh.primitive_cube_add(
enter_editmode=False, align='WORLD', location=(0, 0, 0), scale=(1, 1, 1)
)
container_obj = bpy.context.active_object
bbox_verts = calc_bbox_verts((0, 0, 0), bioxels_shape)
for index, vert in enumerate(container_obj.data.vertices):
co = transfrom @ mathutils.Vector(bbox_verts[index])
co = mat_ras2blender @ co
co = mat_scene_scale @ co
vert.co = co
bioxels_obj.parent = container_obj
container_obj.name = name
container_obj.data.name = name
container_obj.visible_camera = False
container_obj.visible_diffuse = False
container_obj.visible_glossy = False
container_obj.visible_transmission = False
container_obj.visible_volume_scatter = False
container_obj.visible_shadow = False
container_obj.display_type = 'WIRE'
container_obj['bioxels_container'] = True
container_obj['scene_scale'] = scene_scale
container_obj['bioxel_size'] = bioxel_size
container_obj['bioxels_max'] = bioxels_max
container_obj['bioxels_min'] = bioxels_min
container_obj['bioxels_offset'] = bioxels_offset
container_obj['bioxels_shape'] = bioxels_shape
bpy.ops.object.modifier_add(type='NODES')
container_obj.modifiers[0].node_group = node_tree
container_obj.modifiers[0].show_in_editmode = False
container_obj.modifiers[0].show_viewport = False
container_obj.modifiers[0].show_render = False
# Create BioxelNodes to VDB object
print(f"Creating BioxelNodes to the VDB...")
if self.do_add_segmentnode:
nodes = node_tree.nodes
links = node_tree.links
input_node = nodes.get("Group Input")
output_node = nodes.get("Group Output")
segment_node = custom_nodes.add_node(nodes, 'BioxelNodes_Segment')
links.new(input_node.outputs[0], segment_node.inputs[0])
links.new(segment_node.outputs[0], output_node.inputs[0])
# Change render setting for better result
if self.do_change_render_setting:
bpy.context.scene.render.engine = 'CYCLES'
bpy.context.scene.cycles.volume_bounces = 12
bpy.context.scene.cycles.transparent_max_bounces = 64
self.report({"INFO"}, "Successfully Imported")
return {'FINISHED'}
def invoke(self, context, event):
# print(tuple(self.orig_shape))
self.auto = True
self.bioxel_size = 1
context.window_manager.invoke_props_dialog(self)
return {'RUNNING_MODAL'}
class ReadDICOM(bpy.types.Operator):
bl_idname = "bioxelnodes.read_dicom"
bl_label = "Volume Data as Biovels"
bl_description = "Import Volume Data as Biovels (VDB)."
bl_options = {'UNDO'}
filepath: bpy.props.StringProperty(
subtype="FILE_PATH"
) # type: ignore
ok: bpy.props.BoolProperty(
default=True
) # type: ignore
def execute(self, context):
files = get_data_files(self.filepath)
import SimpleITK as sitk
image = sitk.ReadImage(files)
print("Collecting Meta Data...")
print("Original Shape:", image.GetSize())
print("Original Spacing:", image.GetSpacing())
print("Original Origin:", image.GetOrigin())
print("Original Direction:", image.GetDirection())
bpy.ops.bioxelnodes.import_dicom_dialog(
'INVOKE_DEFAULT',
filepath=self.filepath,
orig_shape=image.GetSize(),
orig_spacing=image.GetSpacing()
)
self.report({"INFO"}, "Successfully Readed.")
return {'FINISHED'}
def modal(self, context, event):
self.execute(context)
return {'FINISHED'}
def invoke(self, context, event):
if not self.filepath:
return {'CANCELLED'}
if Path(self.filepath).suffix not in SUPPORT_EXTS:
return {'CANCELLED'}
show_message('Reading image data, it may take a while',
'Please be patient...')
context.window_manager.modal_handler_add(self)
return {'RUNNING_MODAL'}
class ImportDICOM(bpy.types.Operator):
bl_idname = "bioxelnodes.import_dicom"
bl_label = "Volume Data as Biovels"
bl_description = "Import Volume Data as Biovels (VDB)."
bl_options = {'UNDO'}
filepath: bpy.props.StringProperty(
subtype="FILE_PATH"
) # type: ignore
def execute(self, context):
bpy.ops.bioxelnodes.read_dicom(
'INVOKE_DEFAULT',
filepath=self.filepath
)
return {'FINISHED'}
def invoke(self, context, event):
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
class BIOXELNODES_FH_ImportDicom(bpy.types.FileHandler):
bl_idname = "BIOXELNODES_FH_ImportDicom"
bl_label = "File handler for dicom import"
bl_import_operator = "bioxelnodes.read_dicom"
bl_file_extensions = ".dcm"
@classmethod
def poll_drop(cls, context):
return (context.area and context.area.type == 'VIEW_3D')
class ExportVDB(bpy.types.Operator):
bl_idname = "bioxelnodes.export_vdb"
bl_label = "Bioxels as VDB"
bl_description = "Export Bioxels original VDB data."
bl_options = {'UNDO'}
filepath: bpy.props.StringProperty(
subtype="FILE_PATH"
) # type: ignore
filename_ext = ".vdb"
def invoke(self, context, event):
bioxels_obj = None
for obj in bpy.context.selected_objects:
bioxels_obj = get_bioxels_obj(obj)
break
if bioxels_obj:
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
else:
self.report({"WARNING"}, "Cannot find any bioxels.")
return {'CANCELLED'}
def execute(self, context):
bioxels_obj = None
for obj in bpy.context.selected_objects:
bioxels_obj = get_bioxels_obj(obj)
break
filepath = f"{self.filepath.split('.')[0]}.vdb"
output_path: Path = Path(filepath).resolve()
source_path: Path = Path(bioxels_obj.data.filepath).resolve()
# print('output_path', output_path)
# print('source_path', source_path)
shutil.copy(source_path, output_path)
return {'FINISHED'}

View File

@@ -1,33 +0,0 @@
import bpy
from .convert import ConvertToMesh
from .io import ExportVDB, ImportDICOM
def TOPBAR_FILE_IMPORT(self, context):
layout = self.layout
layout.separator()
layout.operator(ImportDICOM.bl_idname)
def TOPBAR_FILE_EXPORT(self, context):
layout = self.layout
layout.separator()
layout.operator(ExportVDB.bl_idname)
def VIEW3D_OBJECT(self, context):
layout = self.layout
layout.operator(ConvertToMesh.bl_idname)
layout.separator()
def create_menu():
bpy.types.TOPBAR_MT_file_import.append(TOPBAR_FILE_IMPORT)
bpy.types.TOPBAR_MT_file_export.append(TOPBAR_FILE_EXPORT)
bpy.types.VIEW3D_MT_object_context_menu.prepend(VIEW3D_OBJECT)
def remove_menu():
bpy.types.TOPBAR_MT_file_import.remove(TOPBAR_FILE_IMPORT)
bpy.types.TOPBAR_MT_file_export.remove(TOPBAR_FILE_EXPORT)
bpy.types.VIEW3D_MT_object_context_menu.remove(VIEW3D_OBJECT)

View File

@@ -1,146 +0,0 @@
from pathlib import Path
from .custom_nodes import CustomNodes
import bpy
def add_driver_to_node_factory(source_prop, target_prop):
callback_str = f"""
import bpy
from bioxelnodes.utils import add_direct_driver, get_bioxels_obj
bioxels_obj = get_bioxels_obj(bpy.context.active_object)
container_obj = bioxels_obj.parent
if bioxels_obj:
add_direct_driver(
target=node,
target_prop='{target_prop}',
source=container_obj,
source_prop='{source_prop}'
)
else:
print('Cannot find any bioxels.')
"""
return callback_str
def set_prop_to_node_factory(source_prop, target_prop):
callback_str = f"""
import bpy
from bioxelnodes.utils import get_bioxels_obj
bioxels_obj = get_bioxels_obj(bpy.context.active_object)
container_obj = bioxels_obj.parent
if bioxels_obj:
node.inputs.get('{target_prop}').default_value = container_obj.get('{source_prop}')
else:
print('Cannot find any bioxels.')
"""
return callback_str
MENU_ITEMS = [
{
'label': 'Present',
'icon': 'MESH_MONKEY',
'items': [
{
'label': 'Segment',
'icon': 'OUTLINER_OB_META',
'node_type': 'BioxelNodes_Segment',
'node_description': '',
'node_callback': "\n".join([
set_prop_to_node_factory("bioxel_size", "Detail Size"),
set_prop_to_node_factory("bioxels_offset", "Offset"),
])
},
{
'label': 'Anatomy',
'icon': 'OUTLINER_OB_META',
'node_type': 'BioxelNodes_Anatomy',
'node_description': '',
'node_callback': "\n".join([
set_prop_to_node_factory("bioxel_size", "Detail Size"),
set_prop_to_node_factory("bioxels_offset", "Offset"),
])
}
]
},
{
'label': 'Segment',
'icon': 'OUTLINER_DATA_VOLUME',
'items': [
{
'label': 'Segment by Level',
'icon': 'AREA_JOIN',
'node_type': 'BioxelNodes_SegmentByLevel',
'node_description': '',
'node_callback': "\n".join([
set_prop_to_node_factory("bioxel_size", "Detail Size"),
set_prop_to_node_factory("bioxels_offset", "Offset"),
])
},
{
'label': 'Segment by Range',
'icon': 'AREA_SWAP',
'node_type': 'BioxelNodes_SegmentByRange',
'node_description': '',
'node_callback': "\n".join([
set_prop_to_node_factory("bioxel_size", "Detail Size"),
set_prop_to_node_factory("bioxels_offset", "Offset"),
])
},
{
'label': 'Segment by Layers',
'icon': 'OUTLINER_OB_FORCE_FIELD',
'node_type': 'BioxelNodes_SegmentsByLayers',
'node_description': '',
'node_callback': "\n".join([
set_prop_to_node_factory("bioxel_size", "Detail Size"),
set_prop_to_node_factory("bioxels_offset", "Offset"),
])
}
]
},
{
'label': 'Shader',
'icon': 'SHADING_RENDERED',
'items': [
{
'label': 'Segment Shader',
'icon': 'OUTLINER_OB_VOLUME',
'node_type': 'BioxelNodes_SegmentShader',
'node_description': ''
}
]
},
{
'label': 'Slicer',
'icon': 'CLIPUV_DEHLT',
'items': [
{
'label': 'RAS Slicer',
'icon': 'EMPTY_DATA',
'node_type': 'BioxelNodes_RAS-Slicer',
'node_description': ''
},
{
'label': 'Axis Slicer',
'icon': 'OUTLINER_OB_EMPTY',
'node_type': 'BioxelNodes_AxisSlicer',
'node_description': '',
},
{
'label': 'Box Slicer',
'icon': 'MOD_WIREFRAME',
'node_type': 'BioxelNodes_BoxSlicer',
'node_description': '',
}
]
},
]
custom_nodes = CustomNodes(
menu_items=MENU_ITEMS,
nodes_file=Path(__file__).parent/"assets/Nodes.blend",
root_label='BioxelNodes',
root_icon="FILE_VOLUME",
)

View File

@@ -1,23 +0,0 @@
import bpy
from pathlib import Path
from .external_package import ExternalPackagePreferences
class BioxelNodesPreferences(bpy.types.AddonPreferences, ExternalPackagePreferences):
bl_idname = __package__
cache_dir: bpy.props.StringProperty(
name="Python Log Directory",
subtype='DIR_PATH',
default=Path(Path.home(), '.bioxelnodes').as_posix()
) # type: ignore
def draw(self, context):
layout = self.layout
layout.label(text="Configuration")
layout.prop(self, 'cache_dir', text='Set Cache Directory')
# ExternalPackagePreferences Config
self.requirements_dir = Path(__file__).parent.as_posix()
super().draw(context)

View File

@@ -1 +0,0 @@
SimpleITK==2.3.1 # Insight Segmentation and Registration Toolkit.

View File

@@ -1,135 +0,0 @@
import bpy
import mathutils
def show_message(message="", title="Message Box", icon='INFO'):
def draw(self, context):
self.layout.label(text=message)
bpy.context.window_manager.popup_menu(draw, title=title, icon=icon)
def calc_bbox_verts(origin, size):
bbox_origin = mathutils.Vector(
(origin[0], origin[1], origin[2]))
bbox_size = mathutils.Vector(
(size[0], size[1], size[2]))
bbox_verts = [
(
bbox_origin[0] + 0,
bbox_origin[1] + 0,
bbox_origin[2] + 0
),
(
bbox_origin[0] + 0,
bbox_origin[1] + 0,
bbox_origin[2] + bbox_size[2]
),
(
bbox_origin[0] + 0,
bbox_origin[1] + bbox_size[1],
bbox_origin[2] + 0
),
(
bbox_origin[0] + 0,
bbox_origin[1] + bbox_size[1],
bbox_origin[2] + bbox_size[2]
),
(
bbox_origin[0] + bbox_size[0],
bbox_origin[1] + 0,
bbox_origin[2] + 0
),
(
bbox_origin[0] + bbox_size[0],
bbox_origin[1] + 0,
bbox_origin[2] + bbox_size[2],
),
(
bbox_origin[0] + bbox_size[0],
bbox_origin[1] + bbox_size[1],
bbox_origin[2] + 0,
),
(
bbox_origin[0] + bbox_size[0],
bbox_origin[1] + bbox_size[1],
bbox_origin[2] + bbox_size[2],
),
]
return bbox_verts
def get_bioxels_obj(current_obj):
bioxels_obj = None
if current_obj.get('bioxels_container'):
bioxels_values = []
for obj in bpy.data.objects:
if obj.parent == current_obj and obj.get('bioxels'):
bioxels_values.append(obj)
if len(bioxels_values) > 0:
bioxels_obj = bioxels_values[0]
elif current_obj.get('bioxels') and current_obj.parent:
if current_obj.parent.get('bioxels_container'):
bioxels_obj = current_obj
return bioxels_obj
def extract_last_number(text):
# Initialize an empty string to store the digits
digits = ""
# Iterate through the characters in reverse order
started = False
for char in text[::-1]:
if char.isdigit():
started = True
# If the character is a digit, add it to the digits string
digits += char
else:
if started:
# If a non-digit character is encountered, stop the loop
break
# Reverse the digits string to get the correct order
last_number = digits[::-1]
return int(last_number)
def add_driver(target_prop, var_sources, expression):
driver = target_prop.driver_add("default_value")
is_vector = isinstance(driver, list)
drivers = driver if is_vector else [driver]
for i, driver in enumerate(drivers):
for j, var_source in enumerate(var_sources):
source = var_source['source']
prop = var_source['prop']
var = driver.driver.variables.new()
var.name = f"var{j}"
var.targets[0].id_type = source.id_type
var.targets[0].id = source
var.targets[0].data_path = f'["{prop}"][{i}]'\
if is_vector else f'["{prop}"]'
driver.driver.expression = expression
def add_direct_driver(target, target_prop, source, source_prop):
target_prop = target.inputs.get(target_prop)
drivers = [
{
"source": source,
"prop": source_prop
}
]
expression = "var0"
add_driver(target_prop, drivers, expression)

92
build.py Normal file
View File

@@ -0,0 +1,92 @@
from pathlib import Path
import shutil
import subprocess
import sys
from dataclasses import dataclass
import tomlkit
@dataclass
class Platform:
pypi_suffix: str
blender_tag: str
required_packages = ["SimpleITK==2.5.5",
"pyometiff==1.0.0",
"mrcfile==1.5.1",
"h5py==3.14.0",
"transforms3d==0.4.2",
"tifffile==2024.7.24",
"matplotlib==3.10.7",
"pillow==11.2.1",
"scipy==1.16.3"]
platforms = {"windows-x64": Platform(pypi_suffix="win_amd64",
blender_tag="windows-x64"),
"linux-x64": Platform(pypi_suffix="manylinux2014_x86_64",
blender_tag="linux-x64"),
"macos-arm64": Platform(pypi_suffix="macosx_12_0_arm64",
blender_tag="macos-arm64"),
"macos-x64": Platform(pypi_suffix="macosx_10_16_x86_64",
blender_tag="macos-x64")}
packages_to_remove = {
"imagecodecs",
"numpy",
"packaging"
}
def run_python(args: str):
python = Path(sys.executable).resolve()
subprocess.run([python] + args.split(" "))
def build_extension(platform: Platform, python_version: str) -> None:
wheel_dirpath = Path("./src/bioxelnodes/wheels")
toml_filepath = Path("./src/bioxelnodes/blender_manifest.toml")
# download required_packages
run_python(
f"-m pip download {' '.join(required_packages)} --dest {wheel_dirpath.as_posix()} --only-binary=:all: --python-version={python_version} --platform={platform.pypi_suffix}"
)
for f in wheel_dirpath.glob("*.whl"):
if any([package in f.name for package in packages_to_remove]):
f.unlink(missing_ok=True)
elif (
platform.blender_tag == "macos-arm64"
and "lxml" in f.name
and "universal2" in f.name
):
f.rename(Path(f.parent, f.name.replace("universal2", "arm64")))
# Load the TOML file
with toml_filepath.open("r") as file:
manifest = tomlkit.parse(file.read())
manifest["platforms"] = [platform.blender_tag]
manifest["wheels"] = [
f"./wheels/{f.name}" for f in wheel_dirpath.glob("*.whl")]
# build.append('generated', generated)
# manifest.append('build', build)
# Write the updated TOML file
with toml_filepath.open("w") as file:
text = tomlkit.dumps(manifest)
file.write(text)
def main():
platform_name = sys.argv[1]
python_version = sys.argv[2] or "3.11"
platform = platforms[platform_name]
build_extension(platform, python_version)
if __name__ == "__main__":
main()

99
docs/SARS-Cov-2.en.md Normal file
View File

@@ -0,0 +1,99 @@
# SARS-Cov-2
![alt text](assets/SARS-Cov-2/image.png)
![alt text](assets/SARS-Cov-2/image-1.png)
In this tutorial, we'll make a structural visualzation of the SARS-Cov-2 Virus. Please see [step by step](step_by_step.md) to make sure you have a basic understanding of how to use the addon, and make sure the addon version is v1.0.2 or higher!
Research data is from paper published in September 2020 in Cell Press ([https://www.cell.com/cell/fulltext/S0092-8674(20)31159-4](<https://www.cell.com/cell/fulltext/S0092-8674(20)31159-4>)) by Li Sai team at Tsinghua University. This research revealed the molecular assembly of the authentic SARS-CoV-2 virus using cryoelectron tomography (cryo-ET) and subtomogram averaging (STA). Here is an official video of this study
<iframe width="560" height="315" src="https://www.youtube.com/embed/JSKl5VY4k5w?si=t4LhrCRebxrX_Saf&amp;controls=0" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
"It remains enigmatic how coronaviruses pack the ∼30-kb RNA into the ∼80-nm-diameter viral lumen. Are the RNPs ordered relative to each other to avoid RNA entangling, knotting, or even damage or are they involved in virus assembly?" Three assembly classes were proposed in the paper, we will make a visualzation of the "eggs-in-a-nest"-shaped RNPs assembly, based on real cryo-ET data.
## Download and import data
The data of this research is hosted on EMDB ([https://www.ebi.ac.uk/emdb](https://www.ebi.ac.uk/emdb)), and the website of SARS-Cov-2 virus is [here](https://www.ebi.ac.uk/emdb/EMD-30430). Open the page, find "Download" button and select the first selection "3D Volume (.map.gz)".
In case you can't download data, you can download here.
[SARS-Cov-2.map](https://drive.google.com/file/d/1LMybsmTVbwQ38_eqAx6hbZTc5p2fdcjK/view?usp=sharing)
After downloading, put it into any directory and import the data. In the import options, it is recommended to adjust the Bioxel Size to 5, in order to reduce the shape of the data to increase the speed of calculation and rendering. If you are confident in the performance of your hardware, you can leave the original 2.72 unchanged. After adjusting the Bioxel Size, the shape of the converted data will be calculated below based on the current bioxel size. The amount of data will increase exponentially with larger shape, and may result in OOM (out of memory).
## Cutout the Virus
After importing, you can get the virus by creating and connecting nodes and setting parameters as shown below
![alt text](assets/SARS-Cov-2/image-2.png)
Place the light and the camera in the way as below. The backlight is a area light, color white, intensity 500W, spread 90°, and inside the virus, place a point light, color `FFD08D`, intensity 5W. Camera focal length is 200 mm. the background color is pure black. The Look of the color management is High Contrast.
![alt text](assets/SARS-Cov-2/image-3.png)
Continue editing the node, followed by "Set Properies" and "Set Color by Ramp 4" node, the parameters of these two nodes are set as shown in the figure, where the color part, from top to bottom, is set to `E1D0FC` (1.0), `FFE42D` (0.5), `3793FF` (0.5), `FFFF8EC` (0.1) (alpha value in parentheses). Color alpha also affects density.
![alt text](assets/SARS-Cov-2/image-4.png)
If you feel that rendering is too slow, see [here](improve_performance.md) for suggestions
## Color the RNPs alone
The current rendering is pretty good, but considering that my goal is to make it clear how the RNPs are arranged within the virus, the RNPs should be colored differently than the others. So how to color the RNPs alone?
First of all, we have to separate the RNPs. The value of RNPs is between the membrane and S protein, so it is very difficult to separate. The good thing is that the virus is spherical, we can separate the RNPs part of the virus from the rest by using a sphere cutter. To do so, in the Geometry Nodes panel menu of the container, click **Bioxel Nodes > Add a Cutter > Sphere Cutter**, and adjust the scale and position of the newly created sphere object named "Sphere_Cutter" appropriately, so that it can just separate the internal RNPs and membrane of the virus.
![alt text](assets/SARS-Cov-2/image-5.png)
The process of changing the position of the "Sphere_Cutter" object can be very laggy, then you can turn off "With Surface" and do it in Slice Viewer mode. Once you are happy with it, you can restore the settings.
Then we turn on Invert in the "Sphere Cutter" node and you can see the opposite result. This way we've managed to separate the two, next let's color them separately and finally merge them with Join Component. Create and join the nodes as shown below, where the second Cutter node is copied and the color value in Set Color is `FFDDFE` (0.5). If all is well, the rendering should look like below.
![alt text](assets/SARS-Cov-2/image-6.png)
At this point, the rendering of a SARS-Cov-2 virus is complete!
## Render RNPs and Membranes
Realistic rendering is great, but Non-photorealistic rendering (NPR) is better for presenting structural information. So I will render ultrastructure of the RNPs assembly with toon shader.
![alt text](assets/SARS-Cov-2/image-7.png)
The silhouettes of RNPs uses Blender's Line Art feature, but Line Art must be based on a mesh. Select the nodes that are extruding the RNPs (i.e., the "Cut" nodes that are in charge of cutting out the RNPs), and right-click, click **Bioxel Nodes > Extract Mesh**. This gives you a new mesh object of the RNPs.
Extract the membrane mesh in the same way.
The membrane has a much higher value than the rest of the virus, so let's create a new "Cutout" node, also after the ReCenter, but with the threshold adjusted to 0.13. After the Cutout, connect to the "To Surface" node and parameterize it as shown in the figure, noting that the Remove Island Threshold is set to 1000 so that any fragments smaller than 1000 pts be eliminated. Then select the "To Surface" node, and perform the operation of extracting the mesh.
![alt text](assets/SARS-Cov-2/image-8.png)
The mesh of the membrane needs to be cut in half, this can be done with the Box Trim brush in sculpt mode or with the Boolean modifier. the mesh of the RNPs may also need some repair work, I cleaned up some of the broken surfaces of the RNPs. all the meshes are now ready to be used.
![alt text](assets/SARS-Cov-2/image-9.png)
For Line Art, please see the video tutorial from Blender Secrets.
<iframe width="560" height="315" src="https://www.youtube.com/embed/aIWdBq7-ias?si=CrcStx5VVJBwDpzu&amp;controls=0" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
Finally, an infographic on the ultrastructure of RNPs is done!
![alt text](assets/SARS-Cov-2/image-1.png)
If you have trouble following the docs, you can download the project files.
[SARS-Cov-2.zip](https://drive.google.com/file/d/15GpIoIjVAE-Jr98zWo7oupuk1KfRVPmk/view?usp=sharing)
## Homework
Other data relevant to the study are provided in the paper, you could try visualizing them.
![alt text](assets/SARS-Cov-2/image-10.png)
Go to the official EMDB website https://www.ebi.ac.uk/emdb/ and enter the EMD number in the search box to get them.
The Electron Microscopy Data Bank (EMDB) is a public repository for cryogenic-sample Electron Microscopy (cryoEM) volumes and representative tomograms of macromolecular complexes and subcellular structures. If you want to get data on other virus, just enter their name in the search box. For example, hepatitis B virus, enter it into the search box, then select Virus in the Sample Type on the left side, and download the data you need (it is better to find the corresponding paper to clarify the data information).
**Try to visualize hepatitis B virus.**
![alt text](assets/SARS-Cov-2/image-11.png)

99
docs/SARS-Cov-2.md Normal file
View File

@@ -0,0 +1,99 @@
# SARS-Cov-2
![alt text](assets/SARS-Cov-2/image.png)
![alt text](assets/SARS-Cov-2/image-1.png)
在本教程中,我们将制作 SARS-Cov-2 病毒的结构可视化。请确保您已阅读[分步指南](step_by_step.md)以了解插件的基本使用方法,并确保插件版本为 v1.0.2 或更高!
研究数据来自 2020 年 9 月发表在 Cell Press 的论文([https://www.cell.com/cell/fulltext/S0092-8674(20)31159-4](<https://www.cell.com/cell/fulltext/S0092-8674(20)31159-4>)),作者是清华大学李赛团队。该研究使用冷冻电子断层扫描(cryo-ET)和亚断层图平均(STA)揭示了真实 SARS-CoV-2 病毒的分子组装。以下是该研究的官方视频:
<iframe width="560" height="315" src="https://www.youtube.com/embed/JSKl5VY4k5w?si=t4LhrCRebxrX_Saf&amp;controls=0" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
"冠状病毒如何将约 30kb 的 RNA 包装到约 80nm 直径的病毒腔内仍然是个谜。RNP 彼此之间是否有序以避免 RNA 缠结、打结或损坏,还是它们参与病毒组装?" 论文中提出了三类组装方式,我们将基于真实的冷冻电镜数据,制作"巢中蛋"形 RNP 组装的可视化。
## 下载和导入数据
该研究的数据托管在 EMDB([https://www.ebi.ac.uk/emdb](https://www.ebi.ac.uk/emdb)),SARS-Cov-2 病毒网站是[这里](https://www.ebi.ac.uk/emdb/EMD-30430)。打开页面,找到"Download"按钮,选择第一个选项"3D Volume (.map.gz)"。
如果您无法下载数据,可以从这里下载。
[SARS-Cov-2.map](https://drive.google.com/file/d/1LMybsmTVbwQ38_eqAx6hbZTc5p2fdcjK/view?usp=sharing)
下载后,放到任意目录并导入数据。在导入选项中,建议将 Bioxel Size 调整为 5,以减小数据形状,提高计算和渲染速度。如果您对硬件性能有信心,可以保持原始的 2.72 不变。调整 Bioxel Size 后,下方会根据当前的 bioxel size 计算转换后数据的形状。数据量会随着形状增大呈指数增长,可能会导致内存不足(OOM)。
## 切割病毒
导入后,您可以通过创建和连接节点并设置参数来获取病毒,如下图所示。
![alt text](assets/SARS-Cov-2/image-2.png)
按下图所示放置灯光和相机。背光是区域光,白色,强度 500W,扩散 90°;在病毒内部放置一个点光源,颜色 `FFD08D`,强度 5W。相机焦距为 200mm。背景颜色为纯黑色。颜色管理的 Look 为 High Contrast。
![alt text](assets/SARS-Cov-2/image-3.png)
继续编辑节点,接着是"Set Properties"和"Set Color by Ramp 4"节点,这两个节点的参数设置如下图,其中颜色部分,从上到下设置为 `E1D0FC`(1.0)、`FFE42D`(0.5)、`3793FF`(0.5)、`FFFF8EC`(0.1)(括号中为 alpha 值)。颜色的 alpha 值也会影响密度。
![alt text](assets/SARS-Cov-2/image-4.png)
如果您觉得渲染太慢,请参阅[这里](improve_performance.md)获取建议。
## 单独为 RNP 着色
当前的渲染效果很好,但考虑到我的目标是让您清楚看到 RNP 在病毒内部的排列方式,RNP 应该与其他部分用不同颜色着色。那么如何单独为 RNP 着色呢?
首先,我们必须分离 RNP。RNP 的值介于膜和 S 蛋白之间,因此很难分离。好在病毒是球形的,我们可以使用球形切割器将病毒的 RNP 部分与其余部分分离。为此,在容器的几何节点面板菜单中,点击 **Bioxel Nodes > Add a Cutter > Sphere Cutter**,并适当调整新创建的名为"Sphere_Cutter"的球体对象的大小和位置,使其恰好能将病毒内部的 RNP 和膜分离。
![alt text](assets/SARS-Cov-2/image-5.png)
改变"Sphere_Cutter"对象的位置可能会非常卡顿,此时您可以关闭"With Surface"并在 Slice Viewer 模式下操作。满意后,恢复设置。
然后在"Sphere Cutter"节点中打开 Invert,您可以看到相反的结果。这样我们就成功将两者分离了。接下来让我们分别着色,最后用 Join Component 合并。按如下图所示创建和连接节点,其中第二个 Cutter 节点是复制的,Set Color 中的颜色值设置为 `FFDDFE`(0.5)。如果一切正常,渲染结果应该如下图所示。
![alt text](assets/SARS-Cov-2/image-6.png)
此时,SARS-Cov-2 病毒的渲染完成了!
## 渲染 RNP 和膜
写实渲染很棒,但非写实渲染(NPR)在呈现结构信息方面更好。因此,我将使用卡通着色器来渲染 RNP 组装的首尾结构。
![alt text](assets/SARS-Cov-2/image-7.png)
RNP 的轮廓使用 Blender 的线稿(Line Art)功能,但线稿必须基于网格。选择挤出 RNP 的节点(即负责切割出 RNP 的"Cut"节点),右键点击 **Bioxel Nodes > Extract Mesh**。这将为您创建一个 RNP 的新网格对象。
用同样的方式提取膜网格。
膜的病毒值远高于其他部分,因此让我们创建一个新的"Cutout"节点,同样在 ReCenter 之后,但阈值调整为 0.13。Cutout 后,连接到"To Surface"节点并按如下图所示设置参数,注意 Remove Island Threshold 设置为 1000,以便消除小于 1000 pts 的任何碎片。然后选择"To Surface"节点,执行提取网格的操作。
![alt text](assets/SARS-Cov-2/image-8.png)
膜的网格需要切成两半,这可以通过雕刻模式中的 Box Trim 笔刷或布尔修改器来完成。RNP 的网格也可能需要一些修复工作,我清理了一些 RNP 的破损表面。所有网格现在都可以使用了。
![alt text](assets/SARS-Cov-2/image-9.png)
关于线稿,请参阅 Blender Secrets 的视频教程。
<iframe width="560" height="315" src="https://www.youtube.com/embed/aIWdBq7-ias?si=CrcStx5VVJBwDpzu&amp;controls=0" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
最后,RNP 超微结构的信息图完成了!
![alt text](assets/SARS-Cov-2/image-1.png)
如果您按照文档有困难,可以下载项目文件。
[SARS-Cov-2.zip](https://drive.google.com/file/d/15GpIoIjVAE-Jr98zWo7oupuk1KfRVPmk/view?usp=sharing)
## 作业
论文中提供了其他相关数据,您可以尝试可视化它们。
![alt text](assets/SARS-Cov-2/image-10.png)
前往官方 EMDB 网站 https://www.ebi.ac.uk/emdb/,在搜索框中输入 EMD 编号即可获取。
电子显微镜数据银行(EMDB)是一个公共仓库,用于存放冷冻样品的电子显微镜(cryoEM)体积和代表性断层图。如果您想获取其他病毒的数据,只需在搜索框中输入其名称即可。例如,乙型肝炎病毒,在搜索框中输入,然后选择左侧 Sample Type 中的 Virus,下载您需要的数据(最好找到相应的论文来明确数据信息)。
**尝试可视化乙型肝炎病毒。**
![alt text](assets/SARS-Cov-2/image-11.png)

46
docs/advanced.en.md Normal file
View File

@@ -0,0 +1,46 @@
# Advanced Usage
## Cut "Structure"
"Structure" can be cut to show partial structure, accomplished through the O Cut series nodes. For example, add the **O Cut to Region** node as shown below and connect it. Add any object from the scene as the "Region", and input it into the node:
![](assets/cut-to-region.png)
By properly adjusting the position and rotation of the "Region" object, you can see that the skull structure is confined within the region.
!!! note
The add-on provides a function to quickly make objects phantom. In 3D Viewport mode, right-click the "Region" object and select **Bioxel Nodes > Toggle Phantom** from the menu.
!!! warning
Cutting increases computation and affects real-time performance. Check Resample on O Layer to improve performance.
**O Cut Small Parts** node is a cleanup tool that quickly removes scattered fragments and keeps only clean, continuous large structures. However, the computation is particularly time-consuming, so be aware of performance.
![](assets/cut-small-parts.png)
If you are familiar with geometry nodes, you can also directly define the cutting execution range through **O Cut Structure**. For example, in the image below, select the part where the cutting position X is greater than 0.
![](assets/cut-structure.png)
## Structure Property Settings
Expand the Properties of **O Cutout by Threshold**, where you can directly modify various property values, but they can only be set uniformly. We can use field-type data to assign differences. Take the color property as an example: for instance, connecting a Position node directly produces the effect shown below:
![](assets/set-color-by-pos.png)
We can also map layer values to color gradients, which requires the **O Scalar Layer to Color** node (such conversion function nodes are all under Add > O Bioxel > Utilities in the node menu). Adjust as follows:
- **O Cutout by Threshold**: Set Threshold to 20
- **O Scalar Layer to Color**: Set From Min and From Max to 20 and 90 respectively
![](assets/scalar-to-color.png)
Since soft tissue CT values are lower than bone tissue, when the threshold is lowered, you can see that in addition to the skull, the attached soft tissue is also presented. The From Min and From Max of **O Scalar Layer to Color** define the color mapping range from 0 to 1. Therefore, low-value soft tissue appears black, and high-value bone tissue appears white.
We can also customize the mapping method through the **Closure** node in Blender 5.0+. For example, connect a **Color Ramp** node to change the black area belonging to soft tissue to dark red:
![](assets/scalar-to-color-ramp.png)
Ta-da! The anatomical rendering is done!
Other "Structure" properties can also be adjusted in this way. In addition to **O Scalar Layer to Color**, there is also **O Scalar Layer to Factor** to convert to a single value from 0 to 1.

49
docs/advanced.md Normal file
View File

@@ -0,0 +1,49 @@
# 高级玩法
## 切割「结构体」
「结构体」可以被切割,呈现部分结构,通过 O Cut 系列节点完成。比如按下图添加 **O Cut to Region** 节点并连接,添加任意来自场景的物体作为「区域」,输入到节点:
![](assets/cut-to-region.png)
适当调整作为「区域」物体的位置旋转,可以看到头骨结构被限制在区域范围内。
!!! note
插件提供快速让物体虚化的功能,在 3D 视图模式下,右键「区域」物体,菜单选择 **Bioxel Nodes > Toggle Phantom**
!!! warning
切割会增加计算量,影响实时性能,勾选 O Layer 的 Resample 来提高性能
**O Cut Small Parts** 节点,是清理神器,能快速把零碎的结构删除,只干净连续的大结构。但是计算特别耗时,注意性能。
![](assets/cut-small-parts.png)
如果你对几何节点很了解,你也可以通过 **O Cut Structure** 直接定义切割的执行范围,比如下图中,选择切割位置 X 大于 0 的部分。
![](assets/cut-structure.png)
## 「结构体」属性设置
展开 **O Cutout by Threshold** 的 Properties,你可以直接修改各项属性值,但都只能均一设置,我们可以用场类型数据赋予差异。以颜色属性为例,比如直接接入 Position 节点,效果如下:
![](assets/set-color-by-pos.png)
我们还可以把数据层的值映射为颜色渐变,这里需要用到 **O Scalar Layer to Color** 节点(这类转换功能的节点都在节点菜单,Add > O Bioxel > Utilities 下)。调整如下
- **O Cutout by Threshold**:Threshold 设置为 20
- **O Scalar Layer to Color**:From Min 和 From Max 分别设置为 20 和 90
![](assets/scalar-to-color.png)
由于软组织的 CT 值小于骨质,当阈值降低,可以看到除了头骨外,附着的软组织也被呈现了出来。**O Scalar Layer to Color** 的 From Min 和 From Max,定义了颜色从 0~1 的取值范围。因此低值的软组织呈现黑色,高值的骨质呈现白色
我们还可以通过 Blender 5.0+ 的 **Closure** 节点来自定义映射方式。比如连接 **Color Ramp** 节点,把属于软组织的黑区,改为暗红色
![](assets/scalar-to-color-ramp.png)
哒哒!解剖渲染就做好啦👍
其他「结构体」属性也可以按这样的方式调整,除了 **O Scalar Layer to Color**,还有 **O Scalar Layer to Factor** 来转换为 0~1 的单值

BIN
docs/assets/4d-time.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 246 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 963 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 354 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 278 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 366 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 591 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 184 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 413 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 MiB

BIN
docs/assets/add-o-layer.png LFS Normal file

Binary file not shown.

BIN
docs/assets/adjust-nodes.png LFS Normal file

Binary file not shown.

BIN
docs/assets/connect-nodes.png LFS Normal file

Binary file not shown.

BIN
docs/assets/cover.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 MiB

BIN
docs/assets/cut-small-parts.png LFS Normal file

Binary file not shown.

BIN
docs/assets/cut-structure.png LFS Normal file

Binary file not shown.

BIN
docs/assets/cut-to-region.png LFS Normal file

Binary file not shown.

BIN
docs/assets/eevee.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 MiB

BIN
docs/assets/import-data.png LFS Normal file

Binary file not shown.

BIN
docs/assets/installation.png LFS Normal file

Binary file not shown.

BIN
docs/assets/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Binary file not shown.

BIN
docs/assets/scalar-to-color.png LFS Normal file

Binary file not shown.

BIN
docs/assets/set-color-by-pos.png LFS Normal file

Binary file not shown.

50
docs/basics.en.md Normal file
View File

@@ -0,0 +1,50 @@
# Bacsic Usage
## 1. Download Data
Download and unzip [VHP_M_CT_Head.zip](https://drive.google.com/file/d/1bBGpt5pQ0evr-0-f4KDNRnKPoUYj2bJ-/view?usp=drive_link) to a folder.
The data comes from [Visible Human Project (VHP)](https://www.nlm.nih.gov/research/visible/visible_human.html), which is a CT scan image of a male head.
## 2. Import as "Layer"
Add a geometry node to the cube and open the geometry node interface sidebar. Switch to the Bioxel Nodes tab (1), click the Import Data button (2), and in the file selection dialog, choose any `.dcm` file from the data folder (3), then click the Import Data button (4).
![](assets/import-data.png)
Two dialogs will pop up in sequence, click OK for both. Wait for the data import (you can check the progress bar in the Blender interface status bar at the bottom right). After success, you will see a data preview in the Bioxel Nodes sidebar. Click the Add button at the bottom (1), move the mouse to the node panel, and place the **O Layer** node (2).
![](assets/add-o-layer.png)
The data import is complete!
The data cache is saved as a link in the Blender file in the form of a "Layer", and the "Layer" is loaded into geometry nodes through the **O Layer** node. Their relationship is as follows:
Data Cache -> Layer -> O Layer
## 3. Extract and Render "Structure"
Operations on "Layer" are done through the O Bioxel series geometry nodes.
We need two additional nodes: **O Cutout by Threshold** and **O Realize Structure** nodes (both are in the node menu under Add > O Bioxel > Structure), and connect them as shown below:
![](assets/connect-nodes.png)
If successful, you will see a gray head appear in the viewport. Now let's adjust the node parameters:
- **O Layer**: Check Center, uncheck Resample
- **O Cutout by Threshold**: Set Threshold to 90
- **O Realize Structure**: Set Density to 40, check Surface
Rotate the object, adjust the light position, set the renderer to Cycles, and the final effect is shown below:
![](assets/adjust-nodes.png)
Now we have completed the volumetric rendering of the head CT data!
Let's review the execution logic: First, cutout the "Structure" from the "Layer". As the name suggests, "Structure" is responsible for storing biological tissue structure, but its data type is volumetric and cannot be seen directly. It requires **O Realize Structure** to present the "Structure".
## 4. Save Data Cache (Optional)
Since the data cache is only saved as a link in the Blender file, passing only the Blender file to other devices will cause the "Layer" to lose its cache. Click the Save button in the Bioxel Nodes tab, and select a location to save the data cache to manage the cache resource.
Just like images, when sharing, send both the data cache and the Blender file together.

51
docs/basics.md Normal file
View File

@@ -0,0 +1,51 @@
# 入门
## 1. 下载数据
下载并解压到文件夹中 [VHP_M_CT_Head.zip](https://drive.google.com/file/d/1bBGpt5pQ0evr-0-f4KDNRnKPoUYj2bJ-/view?usp=drive_link)
数据来自 [Visible Human Project (VHP)](https://www.nlm.nih.gov/research/visible/visible_human.html)这是一个男性头部的 CT 扫描图像
## 2. 导入为「数据层」
给立方体添加几何节点,并打开几何节点界面侧边栏。切换到 Bioxel Nodes 分页(1),点击 Import Data 按钮(2),在文件选择对话框中,选择数据文件夹中任意一个`.dcm`文件(3),点击 Import Data 按钮(4)
![](assets/import-data.png)
依次会弹出两个对话框,都点击 OK 按钮,等待数据导入(可查看 Blender 界面右下角状态栏的进度条)成功后可以看到 Bioxel Nodes 侧边栏多了数据预览画面。点击下方的 Add 按钮(1),鼠标移动到节点面板,放置 **O Layer** 节点(2)
![](assets/add-o-layer.png)
数据的导入就完成啦👍
数据缓存在主目录里,以「数据层(Layer)」形式添加在 Blender 文件中,「数据层」通过 **O Layer** 节点装载到几何节点。它们的关系如下:
数据缓存 -> 数据层 -> O Layer
## 3. 提取并渲染「结构体」
对「数据层」的操作通过 O Bioxel 系列几何节点完成。
我们需要额外两个节点,**O Cutout by Threshold** 和 **O Realize Structure** 节点(它们都在节点菜单,Add > O Bioxel > Structure 下),并按下图连接:
![](assets/connect-nodes.png)
如果成功,可以看到视图中出现了灰色的头部。接下来我们调整节点参数:
- **O Layer**:勾选 Center,取消 Resample
- **O Cutout by Threshold**:Threshold 设置为 90
- **O Realize Structure**:Density 设置为 40,勾选 Surface
调整物体转向、灯位置,设置渲染器为 Cycles,最终效果如下图:
![](assets/adjust-nodes.png)
这样我们就完成了头部 CT 数据的体积渲染👍
简单捋一下执行逻辑,「数据层」先被剪出(Cutout)为「结构体」。「结构体」顾名思义就是负责储存生物组织结构的对象,但它本身数据类型是体积,并不能直接被看到。需要 **O Realize Structure** 来呈现「结构体」
## 4. 另存数据缓存(可选)
由于数据缓存只是以链接形式保存在 Blender 文件中,所以只传递 Blender 文件给其他设备,会导致「数据层」遗失缓存。点击 Bioxel Nodes 分页中 Save 按钮,选择数据缓存的另存位置来管理缓存资源。
就像图片一样,传递时把数据缓存和 Blender 文件一起发送。

39
docs/dataset.en.md Normal file
View File

@@ -0,0 +1,39 @@
# Support Format
Can't wait to play with the addon using your own data? Here's a list of the formats currently supported.
| Format | EXT |
| ------ | ---------------------------------------- |
| DICOM | .dcm, .DCM, .DICOM, .ima, .IMA |
| BMP | .bmp, .BMP |
| JPEG | .jpg, .JPG, .jpeg, .JPEG |
| PNG | .png, .PNG |
| TIFF | .tif, .TIF, .tiff, .TIFF |
| Nifti | .nia, .nii, .nii.gz, .hdr, .img, .img.gz |
| Nrrd | .nrrd, .nhdr |
| HDF5 | .hdf, .h4, .hdf4, .he2, .h5, .hdf5, .he5 |
| OME | .ome.tiff, .ome.tif |
| MRC | .mrc, .mrc.gz, .map, .map.gz |
Despite my best efforts, I still can't achieve perfect support for all volumetric data formats, and I will continue to work on this.
## Open Databases
If you don't have volumetric data, then you can download from some open databases.
**Note that just because they are open and available for download does not mean you can use them for anything! Be sure to look at the description of the available scopes from website.**
| Source | Object |
| ------------------------------------------------------------------------------------ | ------------------ |
| [MorphoSource](https://www.morphosource.org/) | Open Research Data |
| [Dryad](https://datadryad.org) | Open Research Data |
| [Cell Image Library](http://cellimagelibrary.org/home) | Cells |
| [OpenOrganelle](https://openorganelle.janelia.org/datasets) | Cells |
| [Allen Cell Explorer](https://www.allencell.org/3d-cell-viewer.html) | Cells |
| [EMDB](https://www.ebi.ac.uk/emdb/) | Protein, Viruses |
| [IDC](https://portal.imaging.datacommons.cancer.gov/explore/) | Medical Images |
| [Embodi3D](https://www.embodi3d.com/files/category/37-medical-scans/) | Medical Images |
| [Github](https://github.com/sfikas/medical-imaging-datasets) | Medical Images |
| [NIHR](https://nhsx.github.io/open-source-imaging-data-sets/) | Medical Images |
| [Medical Segmentation Decathlon](http://medicaldecathlon.com/) | Medical Images |
| [Visible Human Project](https://www.nlm.nih.gov/research/visible/visible_human.html) | Medical Images |

39
docs/dataset.md Normal file
View File

@@ -0,0 +1,39 @@
# 支持的格式
迫不及待想使用自己的数据来体验插件了?以下是当前支持的格式列表。
| 格式 | 扩展名 |
| ------ | ---------------------------------------- |
| DICOM | .dcm, .DCM, .DICOM, .ima, .IMA |
| BMP | .bmp, .BMP |
| JPEG | .jpg, .JPG, .jpeg, .JPEG |
| PNG | .png, .PNG |
| TIFF | .tif, .TIF, .tiff, .TIFF |
| Nifti | .nia, .nii, .nii.gz, .hdr, .img, .img.gz |
| Nrrd | .nrrd, .nhdr |
| HDF5 | .hdf, .h4, .hdf4, .he2, .h5, .hdf5, .he5 |
| OME | .ome.tiff, .ome.tif |
| MRC | .mrc, .mrc.gz, .map, .map.gz |
尽管我尽了最大努力,仍然无法实现对所有体数据格式的完美支持,我将持续努力改进。
## 公开数据库
如果您没有体数据,可以从一些公开数据库下载。
**请注意,虽然它们是公开的且可供下载,但并不意味着您可以将其用于任何目的!请务必查看网站上的可用范围说明。**
| 来源 | 对象 |
| ------------------------------------------------------------------------------------ | ------------------ |
| [MorphoSource](https://www.morphosource.org/) | 开放研究数据 |
| [Dryad](https://datadryad.org) | 开放研究数据 |
| [Cell Image Library](http://cellimagelibrary.org/home) | 细胞 |
| [OpenOrganelle](https://openorganelle.janelia.org/datasets) | 细胞 |
| [Allen Cell Explorer](https://www.allencell.org/3d-cell-viewer.html) | 细胞 |
| [EMDB](https://www.ebi.ac.uk/emdb/) | 蛋白质、病毒 |
| [IDC](https://portal.imaging.datacommons.cancer.gov/explore/) | 医学图像 |
| [Embodi3D](https://www.embodi3d.com/files/category/37-medical-scans/) | 医学图像 |
| [Github](https://github.com/sfikas/medical-imaging-datasets) | 医学图像 |
| [NIHR](https://nhsx.github.io/open-source-imaging-data-sets/) | 医学图像 |
| [Medical Segmentation Decathlon](http://medicaldecathlon.com/) | 医学图像 |
| [Visible Human Project](https://www.nih.gov/research/visible/visible_human.html) | 医学图像 |

15
docs/faq.en.md Normal file
View File

@@ -0,0 +1,15 @@
# FAQ
## Nothing in the scene when rendering?
If you're using the Cycles renderer with GPU, make sure your GPU supports "Optix", as Bioxel Nodes relies on OSL (Open shader language) for volumetric rendering, otherwise you'll have to use the CPU for rendering.
If you're using the EEVEE renderer, this issue is due to EEVEE not loading shaders for some unknown reason, save the file and restart Blender to fix it.
## After updating the addon, the nodes in the file have turned red?
This is because the version of the nodes in the file does not match the current version of the addon after updating.
If you still want to edit the file with Bioxel Nodes, you can only roll back the addon version to the version that corresponds to the nodes.
If you just want the file to work and you won't rely on Bioxel Nodes any more, then you can just click **Bioxel Nodes > Relink Node Library >** in the top menu and select the corresponding version. Check to see if the nodes are working and rendering properly, and when everything is OK, click **Bioxel Nodes > Save Node Library** and select the save location in the dialog box.

15
docs/faq.md Normal file
View File

@@ -0,0 +1,15 @@
# 常见问题
## 渲染时场景什么都没有?
如果您使用 GPU 进行 Cycles 渲染,请确保您的 GPU 支持"Optix",因为 Bioxel Nodes 依赖 OSL(Open Shader Language)进行体渲染,否则您必须使用 CPU 进行渲染。
如果您使用 EEVEE 渲染器,此问题是因为 EEVEE 出于未知原因未加载着色器,保存文件并重启 Blender 即可修复。
## 更新插件后,文件中的节点变红了?
这是因为文件中节点的版本与更新后插件的版本不匹配。
如果您仍想使用 Bioxel Nodes 编辑文件,只能将插件回滚到与节点对应的版本。
如果您只想让文件正常工作,不再依赖 Bioxel Nodes,那么您只需点击顶部菜单 **Bioxel Nodes > Relink Node Library >**,然后选择相应的版本。检查节点是否正常工作并正确渲染,一切正常后,点击 **Bioxel Nodes > Save Node Library**,在对话框中选择保存位置。

0
docs/gallery.md Normal file
View File

59
docs/index.en.md Normal file
View File

@@ -0,0 +1,59 @@
**v2.0.x has been released, supporting only Blender 5.0+. The usage is completely different from before and is not compatible with old version files. See http://docs.omoolab.xyz/bioxelnodes/2.0.x/en/basics/**
# Bioxel Nodes
[![For Blender](https://img.shields.io/badge/Blender-orange?style=for-the-badge&logo=blender&logoColor=white&color=black)](https://blender.org/)
![GitHub License](https://img.shields.io/github/license/OmooLab/BioxelNodes?style=for-the-badge&labelColor=black)
![GitHub Release](https://img.shields.io/github/v/release/OmooLab/BioxelNodes?style=for-the-badge&labelColor=black)
![GitHub Repo stars](https://img.shields.io/github/stars/OmooLab/BioxelNodes?style=for-the-badge&labelColor=black)
[![Discord](https://img.shields.io/discord/1265129134397587457?style=for-the-badge&logo=discord&label=Discord&labelColor=white&color=black)](https://discord.gg/pYkNyq2TjE)
Bioxel Nodes is a Blender addon for scientific volumetric data visualization. It using Blender's powerful **Geometry Nodes** and **Cycles** to process and render volumetric data.
![cover](https://omoolab.github.io/BioxelNodes/latest/assets/cover.png)
- Realistic rendering result, also support EEVEE NEXT.
- Support multiple formats.
- Support 4D volumetric data.
- All kinds of cutters.
- Simple and powerful nodes.
- Based on blender natively, can work without addon.
**Read the [getting started](https://docs.omoolab.xyz/bioxelnodes/latest/en/installation) to begin your journey into visualizing volumetric data!**
Welcome to our [discord server](https://discord.gg/pYkNyq2TjE), if you have any problems with this add-on.
## Support Multiple Formats
| Format | EXT |
| ------ | ---------------------------------------- |
| DICOM | .dcm, .DCM, .DICOM, .ima, .IMA |
| BMP | .bmp, .BMP |
| JPEG | .jpg, .JPG, .jpeg, .JPEG |
| PNG | .png, .PNG |
| TIFF | .tif, .TIF, .tiff, .TIFF |
| Nifti | .nia, .nii, .nii.gz, .hdr, .img, .img.gz |
| Nrrd | .nrrd, .nhdr |
| HDF5 | .hdf, .h4, .hdf4, .he2, .h5, .hdf5, .he5 |
| OME | .ome.tiff, .ome.tif |
| MRC | .mrc, .mrc.gz, .map, .map.gz |
## Support 4D volumetric data
![4d](https://omoolab.github.io/BioxelNodes/latest/assets/4d-time.gif)
🥰 4D volumetric data can also be imported into Blender.
## Support EEVEE NEXT
![eevee](https://omoolab.github.io/BioxelNodes/latest/assets/eevee.gif)
👍 EEVEE NEXT is absolutely AWESOME! Bioxel Nodes is fully support EEVEE NEXT now!
## Roadmap
- Better multi-format import experience
- One-click bake model with texture
- AI Segmentation to Generate Labels

58
docs/index.md Normal file
View File

@@ -0,0 +1,58 @@
**v2.0.X 已发布,仅支持 Blender 5.0+,使用方式和之前截然不同,也无法兼容旧版本文件。使用方式查看 http://docs.omoolab.xyz/bioxelnodes/2.0.x/basics/**
# Bioxel Nodes
[![For Blender](https://img.shields.io/badge/Blender-orange?style=for-the-badge&logo=blender&logoColor=white&color=black)](https://blender.org/)
![GitHub License](https://img.shields.io/github/license/OmooLab/BioxelNodes?style=for-the-badge&labelColor=black)
![GitHub Release](https://img.shields.io/github/v/release/OmooLab/BioxelNodes?style=for-the-badge&labelColor=black)
![GitHub Repo stars](https://img.shields.io/github/stars/OmooLab/BioxelNodes?style=for-the-badge&labelColor=black)
[![Discord](https://img.shields.io/discord/1265129134397587457?style=for-the-badge&logo=discord&label=Discord&labelColor=white&color=black)](https://discord.gg/pYkNyq2TjE)
Bioxel Nodes 是一款用于科学体数据可视化的 Blender 插件。它利用 Blender 强大的 **几何节点 (Geometry Nodes)** 和 **Cycles** 渲染器来处理和渲染体数据。
![cover](https://omoolab.github.io/BioxelNodes/latest/assets/cover.png)
- 逼真的渲染效果,同时也支持 EEVEE NEXT
- 支持多种数据格式
- 支持 4D 体数据
- 多种切割工具
- 简洁而强大的节点系统
- 基于 Blender 原生开发,插件卸载后仍可正常工作
**阅读[安装指南](installation.md)开始您的体数据可视化之旅!**
如果您在使用过程中遇到任何问题,欢迎加入我们的 [Discord 服务器](https://discord.gg/pYkNyq2TjE)。
## 支持多种格式
| 格式 | 扩展名 |
| ----- | ---------------------------------------- |
| DICOM | .dcm, .DCM, .DICOM, .ima, .IMA |
| BMP | .bmp, .BMP |
| JPEG | .jpg, .JPG, .jpeg, .JPEG |
| PNG | .png, .PNG |
| TIFF | .tif, .TIF, .tiff, .TIFF |
| Nifti | .nia, .nii, .nii.gz, .hdr, .img, .img.gz |
| Nrrd | .nrrd, .nhdr |
| HDF5 | .hdf, .h4, .hdf4, .he2, .h5, .hdf5, .he5 |
| OME | .ome.tiff, .ome.tif |
| MRC | .mrc, .mrc.gz, .map, .map.gz |
## 支持 4D 体数据
![4d](https://omoolab.github.io/BioxelNodes/latest/assets/4d-time.gif)
4D 体数据也可以导入到 Blender 中。
## 支持 EEVEE NEXT
![eevee](https://omoolab.github.io/BioxelNodes/latest/assets/eevee.gif)
EEVEE NEXT 太棒了!Bioxel Nodes 现在全面支持 EEVEE NEXT!
## 路线图
- 更完善的多格式导入体验
- 一键烘焙带纹理模型
- AI 分割生成标签

22
docs/installation.en.md Normal file
View File

@@ -0,0 +1,22 @@
# Installation
!!! warning
**v2.0.x only supports Blender 5.0 and above**
The add-on supports multiple installation methods, choose one.
## Blender Preferences (Recommended)
Click the top menu **Edit > Preferences**, search for "biox" in the "Get Extensions" area. Then click Install. Due to the large add-on size (60~100MB), you may need to wait for a while.
![](assets/installation.png)
## Blender Official Extensions Website
Visit [https://extensions.blender.org/add-ons/bioxelnodes/](https://extensions.blender.org/add-ons/bioxelnodes/)
Click Get Add-on, open Blender, drag the add-on into Blender and follow the prompts to install.
## Manual Installation
You can also download `BioxelNodes.{version}.zip` from [here](https://github.com/OmooLab/BioxelNodes/releases/latest) for manual installation.
Click the top menu **Edit > Preferences**, select **Add-ons > Install from Disk**, then choose the Zip file you downloaded.

22
docs/installation.md Normal file
View File

@@ -0,0 +1,22 @@
# 安装
!!! warning
**v2.0.x 仅支持 Blender 5.0 及以上版本**
插件支持多种安装方式,选其中之一即可
## Blender 偏好设置(推荐)
点击顶部菜单 **Edit > Preferences**,在 "Get Extensions" 区域搜索 "biox"。然后点击 Install。由于插件体积较大(60~100MB),可能需要等待一段时间。
![](assets/installation.png)
## Blender 官方扩展网站
访问 [https://extensions.blender.org/add-ons/bioxelnodes/](https://extensions.blender.org/add-ons/bioxelnodes/)
点击 Get Add-on,打开 Blender,将插件拖入并按照提示安装。
## 手动安装
您也可以从 [这里](https://github.com/OmooLab/BioxelNodes/releases/latest) 下载 `BioxelNodes.{version}.zip` 进行手动安装。
点击顶部菜单 **Edit > Preferences**,选择 **Add-ons > Install from Disk**,然后选择您下载的 Zip 文件。

25
docs/performance.en.md Normal file
View File

@@ -0,0 +1,25 @@
# Improve Performance
Voxel reconstruction and voxel rendering are very computation-intensive. Here are some tips to improve the add-on's performance.
## Use Low-Resolution Data as Preview
The resolution of voxels geometrically affects computational efficiency. Enabling Resample on O Layer can greatly improve calculation speed. You can uncheck it when you need to render for real. The Layer Nodes panel in the Bioxel Nodes tab lists all O Layers added in the current geometry nodes. You can uniformly manage whether Resample is enabled and the degree of resampling.
## Balanced Rendering Settings
I list some settings that have the greatest impact on volume rendering, so you can find the most suitable balance for your needs.
- **Light Paths > Max Bounces > Volume** affects the number of bounces for volume data. The higher the value, the more transparent the volume data appears.
- **Light Paths > Max Bounces > Transparent** affects the number of times transparent surfaces are transmitted. The higher the value, the more transparent the transparent surfaces appear.
- **Volumes > Step Rate Render | Viewport** affects the step size of volume rendering. The smaller the value, the more detailed the volume data appears.
Bioxel Nodes provides some render setting presets for quick configuration. Click the top menu **Bioxel Nodes > Render Setting Presets**, including Performance (left), Balance (center), and Quality (right). Here is a comparison:
![alt text](assets/render-performance.png)
## Rendering with EEVEE
EEVEE doesn't render volume as well as Cycles, but it does have the advantage of rendering volumetric data. If you want to get a clear slice view, it is even a better choice. EEVEE's real-time rendering makes it possible to create interactive content in Blender.

25
docs/performance.md Normal file
View File

@@ -0,0 +1,25 @@
# 提升性能
体素重建和体素渲染是非常消耗计算资源的,以下是一些提升插件性能的建议。
## 使用低分辨率数据作为预览
体素的分辨率几何倍地影响计算效率,O Layer 的 Resample 开启可以大大提高计算速度。当你需要正式渲染的时候再关闭即可。在 Bioxel Nodes 分页的 Layer Nodes 面板罗列了当前几何节点中添加的所有 O Layer,你可以统一管理是否开启 Resample,以及程度。
## 平衡的渲染设置
我列出了一些对体渲染影响最大的设置,以便您找到最适合自己的平衡点。
- **Light Paths > Max Bounces > Volume** 影响体数据的反弹次数,值越高,体数据看起来越透明。
- **Light Paths > Max Bounces > Transparent** 影响透明表面透射的次数,值越高,透明表面看起来越透明。
- **Volumes > Step Rate Render | Viewport** 影响体渲染的步长,值越小,体数据看起来越精细。
Bioxel Nodes 提供了一些渲染设置预设以便快速配置。点击顶部菜单 **Bioxel Nodes > Render Setting Presets**,包括 Performance(左侧)、Balance(中间)和 Quality(右侧)。以下是它们的比较。
![alt text](assets/render-performance.png)
## 使用 EEVEE 渲染
EEVEE 渲染体数据不如 Cycles,但它确实有渲染体数据的优势,如果您想获得清晰的切片视图,它甚至是更好的选择。EEVEE 的实时渲染使得在 Blender 中创建交互式内容成为可能。

View File

@@ -0,0 +1,28 @@
@import url("https://fontsapi.zeoseven.com/292/main/result.css");
@import url("https://fontsapi.zeoseven.com/293/main/result.css");
/* [data-md-color-scheme="slate"] {
--md-code-hl-string-color: #8b8b8b;
--md-code-hl-keyword-color: #ffe8a3;
--md-code-hl-number-color: #ffe8a3;
--md-typeset-a-color: #ffe8a3;
}
[data-md-color-scheme="default"] {
--md-code-hl-string-color: #444444;
--md-code-hl-keyword-color: #bd9100;
--md-code-hl-number-color: #bd9100;
}
[data-md-color-scheme=slate][data-md-color-primary=black] {
--md-typeset-a-color: #ffe8a3;
}
[data-md-color-scheme=default][data-md-color-primary=black] {
--md-typeset-a-color: #bd9100;
} */
:root {
--md-text-font: "LXGW WenKai";
--md-code-font: "LXGW WenKai Mono";
}

100
mkdocs.yml Normal file
View File

@@ -0,0 +1,100 @@
site_name: Bioxel Nodes Docs
site_url: https://docs.omoolab.xyz/bioxelnodes/
site_author: OmooLab
site_description: Bioxel Nodes is a Blender add-on for scientific volumetric data visualization.
repo_name: OmooLab/BioxelNodes
repo_url: https://github.com/OmooLab/BioxelNodes
nav:
- 胞素节点:
- index.md
- gallery.md
- 快速开始:
- installation.md
- basics.md
- advanced.md
- dataset.md
- performance.md
theme:
name: material
favicon: assets/logo.png
logo: assets/logo.png
language: zh
font:
text: Open Sans
code: Cascadia Code
palette:
# Palette toggle for automatic mode
- media: "(prefers-color-scheme)"
primary: black
toggle:
icon: fontawesome/solid/circle-half-stroke
name: Switch to light mode
# Palette toggle for light mode
- media: "(prefers-color-scheme: light)"
scheme: default
primary: black
toggle:
icon: fontawesome/regular/moon
name: Switch to dark mode
# Palette toggle for dark mode
- media: "(prefers-color-scheme: dark)"
scheme: slate
primary: black
toggle:
icon: fontawesome/solid/moon
name: Switch to system preference
features:
- header.autohide
- navigation.footer
- navigation.indexes
- navigation.sections
- navigation.tabs
- navigation.tabs.sticky
- content.code.copy
- content.code.select
extra:
version:
provider: mike
extra_css:
- stylesheets/extra.css
copyright: Copyright &copy; 2020 - 2024 Omoolab
plugins:
- search
- mkdocstrings
- i18n:
docs_structure: suffix
languages:
- locale: zh
name: 中文
default: true
- locale: en
name: English
nav_translations:
胞素节点: Bioxel Nodes
快速开始: Getting Started
案例教程: Tutorials
markdown_extensions:
- attr_list
- md_in_html
- mkdocs-click
- admonition
- pymdownx.highlight:
anchor_linenums: true
line_spans: __span
pygments_lang_class: true
- pymdownx.inlinehilite
- pymdownx.snippets
- pymdownx.details
- pymdownx.superfences
- pymdownx.tabbed:
alternate_style: true

20
openspec/config.yaml Normal file
View File

@@ -0,0 +1,20 @@
schema: spec-driven
# Project context (optional)
# This is shown to AI when creating artifacts.
# Add your tech stack, conventions, style guides, domain knowledge, etc.
# Example:
# context: |
# Tech stack: TypeScript, React, Node.js
# We use conventional commits
# Domain: e-commerce platform
# Per-artifact rules (optional)
# Add custom rules for specific artifacts.
# Example:
# rules:
# proposal:
# - Keep proposals under 500 words
# - Always include a "Non-goals" section
# tasks:
# - Break tasks into chunks of max 2 hours

92
pack.py Normal file
View File

@@ -0,0 +1,92 @@
"""
Create a zip archive of the src/bioxelnodes package with a top-level folder
named `bioxelnodes/`. Excludes specified temporary/cache files and folders.
Does not modify any files in the project.
Usage:
python build_package.py <platform_name> [output_zip_path]
Example:
python build_package.py windows-x64
"""
from pathlib import Path
import sys
import zipfile
import fnmatch
from datetime import datetime
platforms = {
"windows-x64": "windows-x64",
"linux-x64": "linux-x64",
"macos-arm64": "macos-arm64",
"macos-x64": "macos-x64",
}
# patterns to exclude (filename matching)
EXCLUDE_FILENAME_PATTERNS = [
"*.blend1",
"blendcache_*",
"*.cats.txt~",
"*.pyc",
"*.pyo",
"*$py.class",
]
# directory names to exclude entirely
EXCLUDE_DIR_NAMES = {
"__pycache__",
}
def should_exclude(path: Path) -> bool:
name = path.name
# exclude directories by name anywhere in the path
if any(part in EXCLUDE_DIR_NAMES for part in path.parts):
return True
# only apply filename patterns to files
if path.is_file():
for pat in EXCLUDE_FILENAME_PATTERNS:
if fnmatch.fnmatch(name, pat):
return True
return False
def build_package(platform_name: str, out_zip: Path):
src_root = Path("src") / "bioxelnodes"
if not src_root.exists():
raise SystemExit(f"Source folder not found: {src_root.resolve()}")
out_zip.parent.mkdir(parents=True, exist_ok=True)
total = 0
with zipfile.ZipFile(out_zip, "w", compression=zipfile.ZIP_DEFLATED) as zf:
for p in src_root.rglob("*"):
if p.is_dir():
continue
if should_exclude(p):
continue
# arcname should place files under top-level 'bioxelnodes/...'
rel = p.relative_to(src_root)
arcname = Path("bioxelnodes") / rel
zf.write(p, arcname.as_posix())
total += 1
print(f"Packaged {total} files into {out_zip}")
def main():
if len(sys.argv) < 2:
print("Usage: python build_package.py <platform_name> [output_zip_path]")
print("Available platforms:", ", ".join(platforms.keys()))
sys.exit(1)
platform_key = sys.argv[1]
if platform_key not in platforms:
print("Unknown platform:", platform_key)
print("Available platforms:", ", ".join(platforms.keys()))
sys.exit(1)
tag = platforms[platform_key]
timestamp = datetime.now().strftime("%Y%m%dT%H%M%S")
default_name = f"bioxelnodes-{tag}-{timestamp}.zip"
out_path = Path(sys.argv[2]) if len(sys.argv) >= 3 else Path(default_name)
build_package(platform_key, out_path)
if __name__ == "__main__":
main()

38
pyproject.toml Normal file
View File

@@ -0,0 +1,38 @@
[project]
name = "bioxelnodes"
version = "2.0.2"
description = ""
authors = [{ name = "MaNan", email = "icrdr2010@outlook.com" }]
requires-python = ">=3.11.0,<3.12.dev0"
readme = "README.md"
license = "MIT"
dependencies = [
"simpleitk==2.3.1",
"pyometiff==1.0.0",
"mrcfile==1.5.1",
"h5py==3.11.0",
"transforms3d==0.4.2",
"matplotlib==3.10.7",
"scipy==1.16.3",
]
[dependency-groups]
dev = [
"bpy>=4.2.0,<5",
"pytest>=8.3.2,<9",
"pytest-dependency>=0.6.0,<0.7",
"pytest-cov>=5.0.0,<6",
"mkdocs>=1.6.0,<2",
"mkdocs-material>=9.5.30,<10",
"autopep8>=2.3.1,<3",
"mike>=2.1.2,<3",
"tomlkit>=0.13.0,<0.14",
"pip>=25.3",
"mkdocstrings[python]>=1.0.4",
"mkdocs-static-i18n[material]>=1.3.1",
"mkdocs-click>=0.9.0",
]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

View File

@@ -0,0 +1,80 @@
import bpy
import bpy.utils.previews as previews
from .constants import PREVIEW_COLLECTIONS
from .props import _bioxel_layer_items, _update_layer_gallery, _update_snapshot_z
from . import auto_load
from . import menus
auto_load.init()
CLI_COMMAND_NAME = "bioxelnodes_import_worker"
def register():
pcoll = previews.new()
pcoll.layer_previews = ()
PREVIEW_COLLECTIONS["layers"] = pcoll
bpy.types.WindowManager.bioxel_progress_factor = bpy.props.FloatProperty(
default=1.0
)
bpy.types.WindowManager.bioxel_progress_text = bpy.props.StringProperty()
bpy.types.WindowManager.bioxel_layer_library = bpy.props.EnumProperty(
name="Bioxel Layer Gallery",
items=_bioxel_layer_items,
update=_update_layer_gallery,
)
bpy.types.WindowManager.bioxel_snapshot_z = bpy.props.FloatProperty(
name="Snapshot Z",
default=0.5,
min=0.0,
max=1.0,
subtype="FACTOR",
update=_update_snapshot_z,
)
bpy.types.WindowManager.bioxel_layer_list_index = bpy.props.IntProperty(
default=0)
auto_load.register()
menus.add()
register_cli_commands()
def unregister():
unregister_cli_commands()
menus.remove()
auto_load.unregister()
del bpy.types.WindowManager.bioxel_progress_factor
del bpy.types.WindowManager.bioxel_progress_text
del bpy.types.WindowManager.bioxel_layer_library
del bpy.types.WindowManager.bioxel_snapshot_z
del bpy.types.WindowManager.bioxel_layer_list_index
for pcoll in PREVIEW_COLLECTIONS.values():
previews.remove(pcoll)
PREVIEW_COLLECTIONS.clear()
def import_worker_cli(args):
from .operators import io_worker
return io_worker.main(args)
def register_cli_commands():
unregister_cli_commands()
bpy.utils.register_cli_command(CLI_COMMAND_NAME, import_worker_cli)
def unregister_cli_commands():
try:
bpy.utils.unregister_cli_command(CLI_COMMAND_NAME)
except Exception:
pass

View File

@@ -0,0 +1,73 @@
import bpy
from pathlib import Path
from .constants import NODE_LIB_DIRPATH
ASSET_LIBRARY_NAME = "O Bioxel"
def _asset_library_path():
return str(NODE_LIB_DIRPATH)
def _normalized_path(path):
return Path(bpy.path.abspath(path)).resolve()
def _asset_libraries():
return bpy.context.preferences.filepaths.asset_libraries
def get_bioxel_asset_library():
lib_path = _normalized_path(_asset_library_path())
for lib in _asset_libraries():
try:
if _normalized_path(lib.path) == lib_path:
return lib
except Exception:
continue
return None
def has_bioxel_asset_library():
return get_bioxel_asset_library() is not None
def add_bioxel_asset_library():
if not NODE_LIB_DIRPATH.exists():
raise FileNotFoundError(f"Node library path does not exist: {NODE_LIB_DIRPATH}")
prefs = _asset_libraries()
lib = get_bioxel_asset_library()
if lib is None:
for item in prefs:
try:
if item.name == ASSET_LIBRARY_NAME:
lib = item
break
except Exception:
continue
if lib is None:
lib = prefs.new()
lib.name = ASSET_LIBRARY_NAME
lib.path = _asset_library_path()
lib.import_method = "PACK"
return lib
def remove_bioxel_asset_library_if_exists():
lib_path = _normalized_path(_asset_library_path())
prefs = _asset_libraries()
for lib in list(prefs):
try:
if "Bioxel" in lib.name or _normalized_path(lib.path) == lib_path:
prefs.remove(lib)
except Exception:
continue

Binary file not shown.

View File

@@ -0,0 +1,12 @@
# This is an Asset Catalog Definition file for Blender.
#
# Empty lines and lines starting with `#` will be ignored.
# The first non-ignored line should be the version indicator.
# Other lines are of the format "UUID:catalog/path/for/assets:simple catalog name"
VERSION 1
c0699a8b-6fd6-4d10-bdde-5ea0fa36724d:O Bioxel:O Bioxel
5ea24e10-5a2b-44d1-b67b-19014c412793:O Bioxel/Layer:O Bioxel-Layer
17383d65-f1a0-4122-b73a-0baaad4b8ecf:O Bioxel/Structure:O Bioxel-Structure
d03fc5b0-465c-45ba-ba8e-524a1c52ae3d:O Bioxel/Utilities:O Bioxel-Utilities

View File

@@ -15,6 +15,10 @@ blender_version = bpy.app.version
modules = None modules = None
ordered_classes = None ordered_classes = None
SKIP_MODULE_NAMES = {
"operators.io_worker",
}
def init(): def init():
global modules global modules
@@ -23,6 +27,7 @@ def init():
modules = get_all_submodules(Path(__file__).parent) modules = get_all_submodules(Path(__file__).parent)
ordered_classes = get_ordered_classes_to_register(modules) ordered_classes = get_ordered_classes_to_register(modules)
def register(): def register():
for cls in ordered_classes: for cls in ordered_classes:
bpy.utils.register_class(cls) bpy.utils.register_class(cls)
@@ -33,6 +38,7 @@ def register():
if hasattr(module, "register"): if hasattr(module, "register"):
module.register() module.register()
def unregister(): def unregister():
for cls in reversed(ordered_classes): for cls in reversed(ordered_classes):
bpy.utils.unregister_class(cls) bpy.utils.unregister_class(cls)
@@ -47,13 +53,18 @@ def unregister():
# Import modules # Import modules
################################################# #################################################
def get_all_submodules(directory): def get_all_submodules(directory):
return list(iter_submodules(directory, directory.name)) return list(iter_submodules(directory, __package__))
def iter_submodules(path, package_name): def iter_submodules(path, package_name):
for name in sorted(iter_submodule_names(path)): for name in sorted(iter_submodule_names(path)):
if name in SKIP_MODULE_NAMES:
continue
yield importlib.import_module("." + name, package_name) yield importlib.import_module("." + name, package_name)
def iter_submodule_names(path, root=""): def iter_submodule_names(path, root=""):
for _, module_name, is_package in pkgutil.iter_modules([str(path)]): for _, module_name, is_package in pkgutil.iter_modules([str(path)]):
if is_package: if is_package:
@@ -67,22 +78,28 @@ def iter_submodule_names(path, root=""):
# Find classes to register # Find classes to register
################################################# #################################################
def get_ordered_classes_to_register(modules): def get_ordered_classes_to_register(modules):
return toposort(get_register_deps_dict(modules)) return toposort(get_register_deps_dict(modules))
def get_register_deps_dict(modules): def get_register_deps_dict(modules):
my_classes = set(iter_my_classes(modules)) my_classes = set(iter_my_classes(modules))
my_classes_by_idname = {cls.bl_idname : cls for cls in my_classes if hasattr(cls, "bl_idname")} my_classes_by_idname = {
cls.bl_idname: cls for cls in my_classes if hasattr(cls, "bl_idname")}
deps_dict = {} deps_dict = {}
for cls in my_classes: for cls in my_classes:
deps_dict[cls] = set(iter_my_register_deps(cls, my_classes, my_classes_by_idname)) deps_dict[cls] = set(iter_my_register_deps(
cls, my_classes, my_classes_by_idname))
return deps_dict return deps_dict
def iter_my_register_deps(cls, my_classes, my_classes_by_idname): def iter_my_register_deps(cls, my_classes, my_classes_by_idname):
yield from iter_my_deps_from_annotations(cls, my_classes) yield from iter_my_deps_from_annotations(cls, my_classes)
yield from iter_my_deps_from_parent_id(cls, my_classes_by_idname) yield from iter_my_deps_from_parent_id(cls, my_classes_by_idname)
def iter_my_deps_from_annotations(cls, my_classes): def iter_my_deps_from_annotations(cls, my_classes):
for value in typing.get_type_hints(cls, {}, {}).values(): for value in typing.get_type_hints(cls, {}, {}).values():
dependency = get_dependency_from_annotation(value) dependency = get_dependency_from_annotation(value)
@@ -90,6 +107,7 @@ def iter_my_deps_from_annotations(cls, my_classes):
if dependency in my_classes: if dependency in my_classes:
yield dependency yield dependency
def get_dependency_from_annotation(value): def get_dependency_from_annotation(value):
if blender_version >= (2, 93): if blender_version >= (2, 93):
if isinstance(value, bpy.props._PropertyDeferred): if isinstance(value, bpy.props._PropertyDeferred):
@@ -100,21 +118,24 @@ def get_dependency_from_annotation(value):
return value[1]["type"] return value[1]["type"]
return None return None
def iter_my_deps_from_parent_id(cls, my_classes_by_idname): def iter_my_deps_from_parent_id(cls, my_classes_by_idname):
if bpy.types.Panel in cls.__bases__: if issubclass(cls, bpy.types.Panel):
parent_idname = getattr(cls, "bl_parent_id", None) parent_idname = getattr(cls, "bl_parent_id", None)
if parent_idname is not None: if parent_idname is not None:
parent_cls = my_classes_by_idname.get(parent_idname) parent_cls = my_classes_by_idname.get(parent_idname)
if parent_cls is not None: if parent_cls is not None:
yield parent_cls yield parent_cls
def iter_my_classes(modules): def iter_my_classes(modules):
base_types = get_register_base_types() base_types = get_register_base_types()
for cls in get_classes_in_modules(modules): for cls in get_classes_in_modules(modules):
if any(base in base_types for base in cls.__bases__): if any(issubclass(cls, base) for base in base_types):
if not getattr(cls, "is_registered", False): if not getattr(cls, "is_registered", False):
yield cls yield cls
def get_classes_in_modules(modules): def get_classes_in_modules(modules):
classes = set() classes = set()
for module in modules: for module in modules:
@@ -122,34 +143,53 @@ def get_classes_in_modules(modules):
classes.add(cls) classes.add(cls)
return classes return classes
def iter_classes_in_module(module): def iter_classes_in_module(module):
for value in module.__dict__.values(): for value in module.__dict__.values():
if inspect.isclass(value): if inspect.isclass(value):
yield value yield value
def get_register_base_types(): def get_register_base_types():
return set(getattr(bpy.types, name) for name in [ return set(
"Panel", "Operator", "PropertyGroup", "FileHandler", getattr(bpy.types, name)
"AddonPreferences", "Header", "Menu", for name in [
"Node", "NodeSocket", "NodeTree", "Panel",
"UIList", "RenderEngine", "Operator",
"Gizmo", "GizmoGroup", "PropertyGroup",
]) "AddonPreferences",
"Header",
"Menu",
"Node",
"NodeSocket",
"NodeTree",
"UIList",
"RenderEngine",
"Gizmo",
"GizmoGroup",
"FileHandler"
]
)
# Find order to register to solve dependencies # Find order to register to solve dependencies
################################################# #################################################
def toposort(deps_dict): def toposort(deps_dict):
sorted_list = [] sorted_list = []
sorted_values = set() sorted_values = set()
while len(deps_dict) > 0: while len(deps_dict) > 0:
unsorted = [] unsorted = []
sorted_list_sub = [] # helper for additional sorting by bl_order - in panels
for value, deps in deps_dict.items(): for value, deps in deps_dict.items():
if len(deps) == 0: if len(deps) == 0:
sorted_list.append(value) sorted_list_sub.append(value)
sorted_values.add(value) sorted_values.add(value)
else: else:
unsorted.append(value) unsorted.append(value)
deps_dict = {value : deps_dict[value] - sorted_values for value in unsorted} deps_dict = {value: deps_dict[value] -
sorted_values for value in unsorted}
sorted_list_sub.sort(key=lambda cls: getattr(cls, "bl_order", 0))
sorted_list.extend(sorted_list_sub)
return sorted_list return sorted_list

View File

@@ -0,0 +1,34 @@
from .layer import Layer
from .container import Container
from .io import load_container, save_container
from .data import (
Data,
read,
read_meta,
calc_layer_shape,
calc_layer_size,
get_ext,
SUPPORT_EXTS,
DICOM_EXTS,
OME_EXTS,
MRC_EXTS,
SEQUENCE_EXTS
)
__all__ = [
'Layer',
'Container',
'load_container',
'save_container',
'Data',
'read',
'read_meta',
'calc_layer_shape',
'calc_layer_size',
'get_ext',
'SUPPORT_EXTS',
'DICOM_EXTS',
'OME_EXTS',
'MRC_EXTS',
'SEQUENCE_EXTS'
]

View File

@@ -0,0 +1,9 @@
from .layer import Layer
class Container():
def __init__(self,
name,
layers: list[Layer] = []) -> None:
self.name = name
self.layers = layers

View File

@@ -0,0 +1,831 @@
from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional, Callable, List
import numpy as np
import SimpleITK as sitk
from pyometiff import OMETIFFReader
import mrcfile
import transforms3d
from .layer import Layer
# 类型定义
ProgressCallback = Optional[Callable[[float, str], None]]
SUPPORT_EXTS = [
"",
".dcm",
".DCM",
".DICOM",
".ima",
".IMA",
".ome.tiff",
".ome.tif",
".tif",
".TIF",
".tiff",
".TIFF",
".mrc",
".mrc.gz",
".map",
".map.gz",
".bmp",
".BMP",
".png",
".PNG",
".jpg",
".JPG",
".jpeg",
".JPEG",
".PIC",
".pic",
".gipl",
".gipl.gz",
".lsm",
".LSM",
".mnc",
".MNC",
".mrc",
".rec",
".mha",
".mhd",
".hdf",
".h4",
".hdf4",
".he2",
".h5",
".hdf5",
".he5",
".nia",
".nii",
".nii.gz",
".hdr",
".img",
".img.gz",
".nrrd",
".nhdr",
".vtk",
".gz",
]
OME_EXTS = [".ome.tiff", ".ome.tif", ".tif", ".TIF", ".tiff", ".TIFF"]
MRC_EXTS = [".mrc", ".mrc.gz", ".map", ".map.gz"]
DICOM_EXTS = ["", ".dcm", ".DCM", ".DICOM", ".ima", ".IMA"]
SEQUENCE_EXTS = [
".bmp",
".BMP",
".jpg",
".JPG",
".jpeg",
".JPEG",
".tif",
".TIF",
".tiff",
".TIFF",
".png",
".PNG",
".mrc",
]
@dataclass
class Data:
filepath: str
series_id: str
_data: Optional[np.ndarray] = field(default=None, repr=False)
_meta: Optional[dict] = field(default=None, repr=False)
@property
def data(self) -> np.ndarray:
if self._data is None:
self.load_data()
return self._data
@property
def meta(self) -> dict:
if self._meta is None:
self.load_meta()
return self._meta
@property
def name(self) -> str:
return self.meta["name"]
@property
def description(self) -> str:
return self.meta["description"]
@property
def shape(self) -> tuple:
return (
self.meta["frame_count"],
*self.meta["xyz_shape"],
self.meta["channel_count"],
)
@property
def xyz_shape(self) -> tuple:
return self.meta["xyz_shape"]
@property
def spacing(self) -> tuple:
return self.meta["spacing"]
@property
def affine(self) -> np.ndarray:
return self.meta["affine"]
@property
def frame_count(self) -> int:
return self.meta["frame_count"]
@property
def channel_count(self) -> int:
return self.meta["channel_count"]
@property
def dtype(self) -> np.dtype:
return self.meta.get("dtype", np.float32)
def load_meta(self, progress_callback: ProgressCallback = None):
data, meta = self._parse_file(progress_callback)
self._meta = meta
del data
def load_data(self, progress_callback: ProgressCallback = None):
if not self.is_loaded():
data, meta = self._parse_file(progress_callback)
self._data = data
self._meta = meta
def is_loaded(self) -> bool:
return self._data is not None
def to_layers(
self,
kind: str = "scalar",
layer_name: str = "",
bioxel_size: float = 1.0,
smooth: int = 0,
remap: bool = False,
split_channel: bool = False,
frame_source: str = "-1",
progress_callback: ProgressCallback = None,
) -> List[Layer]:
from .layer import Layer
data = self.data.copy()
data, layer_shape = self._transform_shape(data, frame_source)
data = self._preprocess(data, kind, remap)
mat_scale = transforms3d.zooms.zfdir2aff(bioxel_size)
affine = np.dot(self.meta["affine"], mat_scale)
base_name = layer_name or kind.capitalize()
if kind == "label":
return self._create_label_layers(
data, base_name, layer_shape, affine, smooth, progress_callback
)
elif kind == "color":
return self._create_color_layers(
data, base_name, layer_shape, affine, progress_callback
)
elif kind == "scalar":
return self._create_scalar_layers(
data,
base_name,
layer_shape,
affine,
smooth,
split_channel,
progress_callback,
)
return []
def _parse_file(self, progress_callback: ProgressCallback = None):
data_path = Path(self.filepath).resolve()
ext = self._get_ext(data_path)
if progress_callback:
progress_callback(0.0, "Reading Data...")
is_sequence = False
sequence = None
if ext in SEQUENCE_EXTS:
sequence = self._collect_sequence(data_path)
if sequence and len(sequence) > 1:
is_sequence = True
data = None
name = ""
description = ""
affine = np.identity(4)
spacing = (1, 1, 1)
origin = (0, 0, 0)
direction = (1, 0, 0, 0, 1, 0, 0, 0, 1)
if data is None and ext in MRC_EXTS and not is_sequence:
data, name, spacing = self._parse_mrc(data_path)
if data is None and ext in OME_EXTS and not is_sequence:
data, name, spacing = self._parse_ome_tiff(data_path, progress_callback)
if data is None:
data, name, description, spacing, origin, direction = self._parse_sitk(
data_path, ext, is_sequence, sequence, progress_callback
)
t = origin
r = np.array(direction).reshape((3, 3))
affine = np.dot(affine, transforms3d.affines.compose(t, r, [1, 1, 1]))
meta = {
"name": name,
"description": description,
"spacing": spacing,
"affine": affine,
"xyz_shape": data.shape[1:4],
"frame_count": data.shape[0],
"channel_count": data.shape[-1],
"dtype": data.dtype,
}
return data, meta
def _parse_mrc(self, data_path: Path):
print("Parsing with mrcfile...")
with mrcfile.open(data_path, "r") as mrc:
mrc_data = mrc.data
if mrc.is_single_image():
data = np.expand_dims(np.asarray(mrc_data), axis=0)
data = np.expand_dims(data, axis=-1)
data = np.expand_dims(data, axis=-1)
elif mrc.is_image_stack():
data = np.expand_dims(np.asarray(mrc_data), axis=-1)
data = np.expand_dims(data, axis=-1)
elif mrc.is_volume():
data = np.expand_dims(np.asarray(mrc_data), axis=0)
data = np.expand_dims(data, axis=-1)
elif mrc.is_volume_stack():
data = np.expand_dims(np.asarray(mrc_data), axis=-1)
name = self._get_file_no_digits_name(data_path)
spacing = (mrc.voxel_size.x, mrc.voxel_size.y, mrc.voxel_size.z)
return data, name, spacing
def _parse_ome_tiff(self, data_path: Path, progress_callback=None):
print("Parsing with OMETIFFReader...")
reader = OMETIFFReader(fpath=data_path)
ome_image, metadata, xml_metadata = reader.read()
if progress_callback:
progress_callback(0.5, "Transpose to 'TXYZC'...")
try:
ome_order = metadata["DimOrder BF Array"]
data = self._transpose_ome_image(ome_image, ome_order)
try:
spacing = (
metadata["PhysicalSizeX"],
metadata["PhysicalSizeY"],
metadata["PhysicalSizeZ"],
)
except:
spacing = (1, 1, 1)
name = self._get_file_no_digits_name(data_path)
except Exception as e:
print(f"Error parsing OME-TIFF: {e}")
data = np.zeros((1, 1, 1, 1, 1), dtype=np.float32)
name = ""
spacing = (1, 1, 1)
return data, name, spacing
def _parse_sitk(
self,
data_path: Path,
ext: str,
is_sequence: bool,
sequence: Optional[list],
progress_callback=None,
):
print("Parsing with SimpleITK...")
if ext in DICOM_EXTS:
data_dirpath = data_path.parent
reader = sitk.ImageSeriesReader()
reader.MetaDataDictionaryArrayUpdateOn()
reader.LoadPrivateTagsOn()
series_files = reader.GetGDCMSeriesFileNames(
str(data_dirpath), self.series_id
)
reader.SetFileNames(series_files)
itk_image = reader.Execute()
name, description = self._extract_dicom_meta(reader, data_dirpath)
elif ext in SEQUENCE_EXTS and is_sequence and sequence:
sequence_list = sequence if sequence else []
itk_image = sitk.ReadImage(sequence_list)
name = self._get_file_no_digits_name(data_path)
description = ""
else:
itk_image = sitk.ReadImage(data_path)
name = self._get_filename(data_path)
description = ""
if progress_callback:
progress_callback(0.5, "Transpose to 'TXYZC'...")
data = self._convert_sitk_to_numpy(itk_image, ext, is_sequence)
if itk_image.GetDimension() >= 3 and ext not in SEQUENCE_EXTS:
spacing = tuple(itk_image.GetSpacing())
origin = tuple(itk_image.GetOrigin())
direction = tuple(itk_image.GetDirection())
else:
spacing = (1, 1, 1)
origin = (0, 0, 0)
direction = (1, 0, 0, 0, 1, 0, 0, 0, 1)
return data, name, description, spacing, origin, direction
def _transpose_ome_image(self, ome_image, ome_order: str):
if ome_image.ndim == 2:
ome_order = ome_order.replace("T", "").replace("C", "").replace("Z", "")
bioxel_order = (ome_order.index("X"), ome_order.index("Y"))
data = np.transpose(ome_image, bioxel_order)
data = np.expand_dims(data, axis=0)
data = np.expand_dims(data, axis=-1)
data = np.expand_dims(data, axis=-1)
elif ome_image.ndim == 3:
ome_order = ome_order.replace("T", "").replace("C", "")
bioxel_order = (
ome_order.index("X"),
ome_order.index("Y"),
ome_order.index("Z"),
)
data = np.transpose(ome_image, bioxel_order)
data = np.expand_dims(data, axis=0)
data = np.expand_dims(data, axis=-1)
elif ome_image.ndim == 4:
ome_order = ome_order.replace("T", "")
bioxel_order = (
ome_order.index("X"),
ome_order.index("Y"),
ome_order.index("Z"),
ome_order.index("C"),
)
data = np.transpose(ome_image, bioxel_order)
data = np.expand_dims(data, axis=0)
elif ome_image.ndim == 5:
bioxel_order = (
ome_order.index("T"),
ome_order.index("X"),
ome_order.index("Y"),
ome_order.index("Z"),
ome_order.index("C"),
)
data = np.transpose(ome_image, bioxel_order)
return data
def _convert_sitk_to_numpy(self, itk_image, ext: str, is_sequence: bool):
if itk_image.GetDimension() == 2:
data = sitk.GetArrayFromImage(itk_image)
if data.ndim == 3:
data = np.transpose(data, (1, 0, 2))
data = np.expand_dims(data, axis=-2)
else:
data = np.transpose(data)
data = np.expand_dims(data, axis=-1)
data = np.expand_dims(data, axis=-1)
data = np.expand_dims(data, axis=0)
elif itk_image.GetDimension() == 3:
if ext not in SEQUENCE_EXTS:
itk_image = sitk.DICOMOrient(itk_image, "RAS")
data = sitk.GetArrayFromImage(itk_image)
if data.ndim == 4:
data = np.transpose(data, (2, 1, 0, 3))
else:
data = np.transpose(data)
data = np.expand_dims(data, axis=-1)
data = np.expand_dims(data, axis=0)
elif itk_image.GetDimension() == 4:
data = sitk.GetArrayFromImage(itk_image)
if data.ndim == 5:
data = np.transpose(data, (0, 3, 2, 1, 4))
else:
data = np.transpose(data, (0, 3, 2, 1))
data = np.expand_dims(data, axis=-1)
return data
def _extract_dicom_meta(self, reader, data_dirpath: Path):
def get_meta(key):
try:
string = reader.GetMetaData(0, key).removesuffix(" ")
string.encode("utf-8")
if string in ["No study description", "No series description", ""]:
return None
else:
return string
except:
return None
study_description = get_meta("0008|1030") or data_dirpath.name
series_description = get_meta("0008|103e")
series_modality = get_meta("0008|0060")
if series_description and series_modality:
description = f"{series_description}-{series_modality}"
elif series_description:
description = series_description
elif series_modality:
description = series_modality
else:
description = ""
name = study_description.replace(" ", "-")
description = description.replace(" ", "-")
return name, description
@staticmethod
def _get_ext(filepath: Path) -> str:
if filepath.name.endswith(".nii.gz"):
return ".nii.gz"
elif filepath.name.endswith(".img.gz"):
return ".img.gz"
elif filepath.name.endswith(".gipl.gz"):
return ".gipl.gz"
elif filepath.name.endswith(".ome.tiff"):
return ".ome.tiff"
elif filepath.name.endswith(".ome.tif"):
return ".ome.tif"
elif filepath.name.endswith(".mrc.gz"):
return ".mrc.gz"
elif filepath.name.endswith(".map.gz"):
return ".map.gz"
else:
suffix = filepath.suffix
return "" if len(suffix) > 5 else suffix
@staticmethod
def _get_filename(filepath: Path) -> str:
ext = Data._get_ext(filepath)
return filepath.name.removesuffix(ext)
@staticmethod
def _get_file_no_digits_name(filepath: Path) -> str:
prefix, digits, suffix = Data._get_filename_parts(filepath)
prefix = Data._remove_end_str(prefix, "_")
prefix = Data._remove_end_str(prefix, ".")
prefix = Data._remove_end_str(prefix, "-")
prefix = Data._remove_end_str(prefix, " ")
return prefix + suffix
@staticmethod
def _get_filename_parts(filepath: Path) -> tuple:
def has_digits(s):
return any(char.isdigit() for char in s)
name = Data._get_filename(filepath)
parts = name.replace(".", " ").replace("_", " ").split(" ")
skip_prefixs = ["CH", "ch", "channel"]
number_part = None
number_part_i = None
for i, part in enumerate(parts[::-1]):
if has_digits(part):
if not any([part.startswith(prefix) for prefix in skip_prefixs]):
number_part = part
number_part_i = len(parts) - i
break
if number_part is None:
return name, "", ""
prefix_parts = parts[: number_part_i - 1]
prefix_parts_count = sum([len(part) + 1 for part in prefix_parts])
digits = ""
suffix = ""
started = False
for char in number_part[::-1]:
if char.isdigit():
started = True
digits += char
else:
if started:
break
else:
suffix += char
digits = digits[::-1]
prefix_parts_count += len(number_part) - len(digits) - len(suffix)
prefix = name[:prefix_parts_count]
suffix = name[prefix_parts_count + len(digits) :]
return prefix, digits, suffix
@staticmethod
def _get_file_index(filepath: Path) -> int:
prefix, digits, suffix = Data._get_filename_parts(filepath)
return int(digits) if digits != "" else 0
@staticmethod
def _collect_sequence(filepath: Path):
file_dict = {}
for f in filepath.parent.iterdir():
if (
f.is_file()
and Data._get_ext(filepath) == Data._get_ext(f)
and Data._get_file_no_digits_name(filepath)
== Data._get_file_no_digits_name(f)
):
index = Data._get_file_index(f)
file_dict[index] = f
for key in list(file_dict.keys()):
if not file_dict.get(key + 1) and not file_dict.get(key - 1):
del file_dict[key]
file_dict = dict(sorted(file_dict.items()))
sequence = [str(f) for f in file_dict.values()]
if len(sequence) == 0:
sequence = [str(filepath)]
return sequence
@staticmethod
def _remove_end_str(string: str, end: str) -> str:
while string.endswith(end) and len(string) > 0:
string = string.removesuffix(end)
return string
def _transform_shape(self, data, frame_source: str) -> tuple:
orig_shape = self.xyz_shape
if frame_source == "-1":
data = data[0:1, :, :, :, :]
new_shape = orig_shape
elif frame_source == "0":
new_shape = orig_shape
elif frame_source == "1":
data = data.transpose(1, 0, 2, 3, 4)
new_shape = (1, orig_shape[1], orig_shape[2])
elif frame_source == "2":
data = data.transpose(2, 1, 0, 3, 4)
new_shape = (orig_shape[0], 1, orig_shape[2])
elif frame_source == "3":
data = data.transpose(3, 1, 2, 0, 4)
new_shape = (orig_shape[0], orig_shape[1], 1)
else:
data = data.transpose(4, 1, 2, 3, 0)
new_shape = orig_shape
return data, new_shape
def _preprocess(self, data, kind: str, remap: bool) -> np.ndarray:
if kind == "color":
if np.issubdtype(data.dtype, np.uint8):
data = np.multiply(data, 1.0 / 256, dtype=np.float32)
elif data.dtype.kind in ["u", "i"]:
data = data.astype(np.float32)
min_val, max_val = data.min(), data.max()
if max_val != min_val:
data = (data - min_val) / (max_val - min_val)
else:
data = np.zeros_like(data, dtype=np.float32)
else:
data = data.astype(np.float32)
if data.shape[4] == 1:
data = np.repeat(data, repeats=3, axis=4)
elif data.shape[4] == 2:
zeros_shape = list(data.shape[:4]) + [1]
zeros = np.zeros(zeros_shape, dtype=np.float32)
data = np.concatenate((data, zeros), axis=-1)
elif data.shape[4] > 3:
data = data[:, :, :, :, :3]
elif kind == "scalar":
if remap:
data = data.astype(np.float32)
min_val, max_val = data.min(), data.max()
if max_val != min_val:
data = (data - min_val) / (max_val - min_val)
else:
data = np.zeros_like(data, dtype=np.float32)
elif kind == "label":
data = data.astype(int)
return data
def _create_progress_cb_factory(self, progress_callback):
def factory(name, progress, progress_step):
def callback(frame, total):
if progress_callback:
sub_progress = progress + frame * (progress_step / total)
progress_callback(
sub_progress, f"Processing {name} Frame {frame+1}..."
)
return callback
return factory
def _create_label_layers(
self,
data,
base_name,
layer_shape,
affine,
smooth,
progress_callback: ProgressCallback,
):
from .layer import Layer
layers = []
label_count = int(np.max(data))
if label_count == 0:
return layers
progress_step = 0.7 / label_count
cb_factory = self._create_progress_cb_factory(progress_callback)
for i in range(label_count):
name_i = f"{base_name}_{i+1}"
progress = 0.2 + i * progress_step
if progress_callback:
progress_callback(progress, f"Processing {name_i}...")
label_data = data == np.full_like(data, i + 1)
progress_cb = cb_factory(name_i, progress, progress_step)
layer = Layer(data=label_data, name=name_i, kind="label")
layer.resize(
shape=layer_shape, smooth=smooth, progress_callback=progress_cb
)
layer.affine = affine
layers.append(layer)
return layers
def _create_color_layers(
self, data, base_name, layer_shape, affine, progress_callback: ProgressCallback
):
from .layer import Layer
if progress_callback:
progress_callback(0.2, f"Processing {base_name}...")
cb_factory = self._create_progress_cb_factory(progress_callback)
progress_cb = cb_factory(base_name, 0.2, 0.7)
layer = Layer(data=data, name=base_name, kind="color")
layer.resize(shape=layer_shape, progress_callback=progress_cb)
layer.affine = affine
return [layer]
def _create_scalar_layers(
self,
data,
base_name,
layer_shape,
affine,
smooth,
split_channel,
progress_callback: ProgressCallback,
):
from .layer import Layer
layers = []
cb_factory = self._create_progress_cb_factory(progress_callback)
if split_channel:
channel_count = data.shape[-1]
progress_step = 0.7 / channel_count
for i in range(channel_count):
name_i = f"{base_name}_{i+1}"
progress = 0.2 + i * progress_step
if progress_callback:
progress_callback(progress, f"Processing {name_i}...")
progress_cb = cb_factory(name_i, progress, progress_step)
layer = Layer(
data=data[:, :, :, :, i : i + 1], name=name_i, kind="scalar"
)
layer.resize(
shape=layer_shape, smooth=smooth, progress_callback=progress_cb
)
layer.affine = affine
layers.append(layer)
else:
if progress_callback:
progress_callback(0.2, f"Processing {base_name}...")
progress_cb = cb_factory(base_name, 0.2, 0.7)
layer = Layer(data=data, name=base_name, kind="scalar")
layer.resize(
shape=layer_shape, smooth=smooth, progress_callback=progress_cb
)
layer.affine = affine
layers.append(layer)
return layers
# 模块级函数签名
def read(
filepath: str, series_id: str = "", progress_callback: ProgressCallback = None
) -> Data:
filepath = Path(filepath).resolve()
if not filepath.exists():
raise FileNotFoundError(f"File not found: {filepath}")
data_obj = Data(filepath=filepath, series_id=series_id)
data_obj.load_data(progress_callback)
return data_obj
def read_meta(filepath: str, series_id: str = "") -> Data:
data_obj = Data(filepath=filepath, series_id=series_id)
data_obj.load_meta()
return data_obj
def calc_layer_shape(
bioxel_size: float, orig_shape: tuple, orig_spacing: tuple
) -> tuple:
shape = (
int(orig_shape[0] / bioxel_size * orig_spacing[0]),
int(orig_shape[1] / bioxel_size * orig_spacing[1]),
int(orig_shape[2] / bioxel_size * orig_spacing[2]),
)
return (
shape[0] if shape[0] > 0 else 1,
shape[1] if shape[1] > 0 else 1,
shape[2] if shape[2] > 0 else 1,
)
def calc_layer_size(shape: tuple, bioxel_size: float, scale: float = 1.0) -> tuple:
size = (
float(shape[0] * bioxel_size * scale),
float(shape[1] * bioxel_size * scale),
float(shape[2] * bioxel_size * scale),
)
return size
def get_ext(filepath: Path) -> str:
if filepath.name.endswith(".nii.gz"):
return ".nii.gz"
elif filepath.name.endswith(".img.gz"):
return ".img.gz"
elif filepath.name.endswith(".gipl.gz"):
return ".gipl.gz"
elif filepath.name.endswith(".ome.tiff"):
return ".ome.tiff"
elif filepath.name.endswith(".ome.tif"):
return ".ome.tif"
elif filepath.name.endswith(".mrc.gz"):
return ".mrc.gz"
elif filepath.name.endswith(".map.gz"):
return ".map.gz"
else:
suffix = filepath.suffix
return "" if len(suffix) > 5 else suffix

View File

@@ -0,0 +1,43 @@
from pathlib import Path
import uuid
# 3rd-party
import h5py
from .container import Container
from .layer import Layer
def load_container(load_file: str):
load_path = Path(load_file).resolve()
with h5py.File(load_path, 'r') as file:
layers = []
for key, layer_dset in file['layers'].items():
layers.append(Layer(data=layer_dset[:],
name=layer_dset.attrs['name'],
kind=layer_dset.attrs['kind'],
affine=layer_dset.attrs['affine']))
container = Container(name=file.attrs['name'],
layers=layers)
return container
def save_container(container: Container, save_file: str, overwrite=False):
save_path = Path(save_file).resolve()
if overwrite:
if save_path.is_file():
save_path.unlink()
with h5py.File(save_path, "w") as file:
file.attrs['name'] = container.name
layer_group = file.create_group("layers")
for layer in container.layers:
layer_key = uuid.uuid4().hex[:8]
layer_dset = layer_group.create_dataset(name=layer_key,
data=layer.data)
layer_dset.attrs['name'] = layer.name
layer_dset.attrs['kind'] = layer.kind
layer_dset.attrs['affine'] = layer.affine

View File

@@ -0,0 +1,182 @@
import copy
import numpy as np
# 条件导入 openvdb(只在 Blender 环境中存在)
try:
import openvdb as vdb
except ImportError:
vdb = None
from scipy import ndimage as ndi
# 3rd-party
import transforms3d
# TODO: turn to dataclasses
class Layer():
def __init__(self,
data: np.ndarray,
name: str,
kind="scalar",
affine=np.identity(4)) -> None:
if data.ndim != 5:
raise Exception("Data shape order should be TXYZC")
affine = np.array(affine)
if affine.shape != (4, 4):
raise Exception("affine shape should be (4,4)")
self.data = data
self.name = name
self.kind = kind
self.affine = affine
@property
def bioxel_size(self):
t, r, z, s = transforms3d.affines.decompose44(self.affine)
return z.tolist()
@property
def shape(self):
return self.data.shape[1:4]
@property
def dtype(self):
return self.data.dtype
@property
def origin(self):
t, r, z, s = transforms3d.affines.decompose44(self.affine)
return t.tolist()
@property
def euler(self):
t, r, z, s = transforms3d.affines.decompose44(self.affine)
return list(transforms3d.euler.mat2euler(r))
@property
def min(self):
return float(np.min(self.data))
@property
def frame_count(self):
return self.data.shape[0]
@property
def channel_count(self):
return self.data.shape[-1]
@property
def max(self):
return float(np.max(self.data))
def copy(self):
return copy.deepcopy(self)
def fill(self, value: float, mask: np.ndarray, smooth: int = 0):
mask_frames = ()
if mask.ndim == 4:
if mask.shape[0] != self.frame_count:
raise Exception("Mask frame count is not same as ")
for f in range(self.frame_count):
mask_frame = mask[f, :, :, :]
if smooth > 0:
mask_frame = ndi.median_filter(mask_frame.astype(np.float32),
mode="nearest",
size=smooth)
mask_frames += (mask_frame,)
elif mask.ndim == 3:
for f in range(self.frame_count):
mask_frame = mask[:, :, :]
if smooth > 0:
mask_frame = ndi.median_filter(mask_frame.astype(np.float32),
mode="nearest",
size=smooth)
mask_frames += (mask_frame,)
else:
raise Exception("Mask shape order should be TXYZ or XYZ")
_mask = np.stack(mask_frames)
_mask = np.expand_dims(_mask, axis=-1)
self.data = _mask * value + (1-_mask) * self.data
def resize(self, shape: tuple, smooth: int = 0, progress_callback=None):
if len(shape) != 3:
raise Exception("Shape must be 3 dim")
data = self.data
# # TXYZC > TXYZ
# if self.kind in ['label', 'scalar']:
# data = np.amax(data, -1)
# if self.kind in ['scalar']:
# dtype = data.dtype
# data = data.astype(np.float32)
data_frames = ()
for f in range(self.frame_count):
if progress_callback:
progress_callback(f, self.frame_count)
frame = data[f, :, :, :, :]
if smooth > 0:
frame = ndi.median_filter(frame.astype(np.float32),
mode="nearest",
size=smooth)
factors = np.divide(self.shape, shape)
zoom_factors = [1 / f for f in factors]
order = 0 if frame.dtype == bool else 1
frame = ndi.zoom(frame,
zoom_factors+[1.0],
mode="nearest",
grid_mode=False,
order=order)
if smooth > 0:
frame = frame.astype(self.dtype)
data_frames += (frame,)
data = np.stack(data_frames)
# if self.kind in ['scalar']:
# data = data.astype(dtype)
# TXYZ > TXYZC
# if self.kind in ['label', 'scalar']:
# data = np.expand_dims(data, axis=-1) # expend channel
self.data = data
mat_scale = transforms3d.zooms.zfdir2aff(factors[0])
self.affine = np.dot(self.affine, mat_scale)
def snapshot(self, shape: tuple, smooth: int = 0):
if len(shape) != 3:
raise Exception("Shape must be 3 dim")
data = self.data
snapshot = data[0, :, :, :, :]
factors = np.divide(self.shape, shape)
zoom_factors = [1 / f for f in factors]
order = 0 if snapshot.dtype == bool else 1
snapshot = ndi.zoom(snapshot,
zoom_factors+[1.0],
mode="nearest",
grid_mode=False,
order=order)
snapshot = snapshot.astype(np.float32)
if self.kind in ['scalar', 'vector', 'color']:
mn = float(np.nanmin(snapshot))
mx = float(np.nanmax(snapshot))
if mx - mn > 1e-8:
snapshot = (snapshot - mn) / (mx - mn)
else:
snapshot = np.clip(snapshot, 0.0, 1.0)
return snapshot

View File

@@ -0,0 +1,436 @@
from pathlib import Path
import numpy as np
# 3rd-party
import SimpleITK as sitk
from pyometiff import OMETIFFReader
import mrcfile
import transforms3d
"""
Convert any volumetric data to 3D numpy array with order TXYZC
"""
SUPPORT_EXTS = ['', '.dcm', '.DCM', '.DICOM', '.ima', '.IMA',
'.ome.tiff', '.ome.tif',
'.tif', '.TIF', '.tiff', '.TIFF',
'.mrc', '.mrc.gz', '.map', '.map.gz',
'.bmp', '.BMP',
'.png', '.PNG',
'.jpg', '.JPG', '.jpeg', '.JPEG',
'.PIC', '.pic',
'.gipl', '.gipl.gz',
'.lsm', '.LSM',
'.mnc', '.MNC',
'.mrc', '.rec',
'.mha', '.mhd',
'.hdf', '.h4', '.hdf4', '.he2', '.h5', '.hdf5', '.he5',
'.nia', '.nii', '.nii.gz', '.hdr', '.img', '.img.gz',
'.nrrd', '.nhdr',
'.vtk',
'.gz']
OME_EXTS = ['.ome.tiff', '.ome.tif',
'.tif', '.TIF', '.tiff', '.TIFF']
MRC_EXTS = ['.mrc', '.mrc.gz', '.map', '.map.gz']
DICOM_EXTS = ['', '.dcm', '.DCM', '.DICOM', '.ima', '.IMA']
SEQUENCE_EXTS = ['.bmp', '.BMP',
'.jpg', '.JPG', '.jpeg', '.JPEG',
'.tif', '.TIF', '.tiff', '.TIFF',
'.png', '.PNG',
'.mrc']
def get_ext(filepath: Path) -> str:
if filepath.name.endswith(".nii.gz"):
return ".nii.gz"
elif filepath.name.endswith(".img.gz"):
return ".img.gz"
elif filepath.name.endswith(".gipl.gz"):
return ".gipl.gz"
elif filepath.name.endswith(".ome.tiff"):
return ".ome.tiff"
elif filepath.name.endswith(".ome.tif"):
return ".ome.tif"
elif filepath.name.endswith(".mrc.gz"):
return ".mrc.gz"
elif filepath.name.endswith(".map.gz"):
return ".map.gz"
else:
suffix = filepath.suffix
return "" if len(suffix) > 5 else suffix
def get_filename(filepath: Path):
ext = get_ext(filepath)
return filepath.name.removesuffix(ext)
def get_filename_parts(filepath: Path) -> str:
def has_digits(s):
return any(char.isdigit() for char in s)
name = get_filename(filepath)
parts = name.replace(".", " ").replace("_", " ").split(" ")
skip_prefixs = ["CH", "ch", "channel"]
number_part = None
number_part_i = None
for i, part in enumerate(parts[::-1]):
if has_digits(part):
if not any([part.startswith(prefix) for prefix in skip_prefixs]):
number_part = part
number_part_i = len(parts)-i
break
if number_part is None:
return name, "", ""
prefix_parts = parts[:number_part_i-1]
prefix_parts_count = sum([len(part)+1 for part in prefix_parts])
digits = ""
suffix = ""
# Iterate through the characters in reverse order
started = False
for char in number_part[::-1]:
if char.isdigit():
started = True
# If the character is a digit, add it to the digits string
digits += char
else:
if started:
# If a non-digit character is encountered, stop the loop
break
else:
suffix += char
digits = digits[::-1]
prefix_parts_count += len(number_part) - \
len(digits) - len(suffix)
# Reverse the digits string to get the correct order
prefix = name[:prefix_parts_count]
suffix = name[prefix_parts_count+len(digits):]
return prefix, digits, suffix
def get_file_no_digits_name(filepath: Path) -> str:
prefix, digits, suffix = get_filename_parts(filepath)
prefix = remove_end_str(prefix, "_")
prefix = remove_end_str(prefix, ".")
prefix = remove_end_str(prefix, "-")
prefix = remove_end_str(prefix, " ")
return prefix + suffix
def get_file_index(filepath: Path) -> int:
prefix, digits, suffix = get_filename_parts(filepath)
return int(digits) if digits != "" else 0
def collect_sequence(filepath: Path):
file_dict = {}
for f in filepath.parent.iterdir():
if f.is_file() \
and get_ext(filepath) == get_ext(f) \
and get_file_no_digits_name(filepath) == get_file_no_digits_name(f):
index = get_file_index(f)
file_dict[index] = f
# reomve isolated seq file
for key in file_dict.copy().keys():
if not file_dict.get(key+1) \
and not file_dict.get(key-1):
del file_dict[key]
file_dict = dict(sorted(file_dict.items()))
sequence = [str(f) for f in file_dict.values()]
if len(sequence) == 0:
sequence = [str(filepath)]
return sequence
def remove_end_str(string: str, end: str):
while string.endswith(end) and len(string) > 0:
string = string.removesuffix(end)
return string
def parse_volumetric_data(data_file: str, series_id="", progress_callback=None):
"""Parse any volumetric data to numpy with shap (T,X,Y,Z,C)
Args:
data_file (str): file path
series_id (str, optional): DICOM series id. Defaults to "".
Returns:
_type_: _description_
"""
data_path = Path(data_file).resolve()
ext = get_ext(data_path)
if progress_callback:
progress_callback(0.0, "Reading the Data...")
is_sequence = False
if ext in SEQUENCE_EXTS:
sequence = collect_sequence(data_path)
if len(sequence) > 1:
is_sequence = True
data = None
name = "",
description = ""
affine = np.identity(4)
spacing = (1, 1, 1)
origin = (0, 0, 0)
direction = (1, 0, 0, 0, 1, 0, 0, 0, 1)
# Parsing with mrcfile
if data is None and ext in MRC_EXTS and not is_sequence:
print("Parsing with mrcfile...")
# TODO: much to do with mrc
with mrcfile.open(data_path, 'r') as mrc:
data = mrc.data
# mrc.print_header()
# print(data.shape)
# print(mrc.voxel_size)
if mrc.is_single_image():
data = np.expand_dims(data, axis=0) # expend frame
data = np.expand_dims(data, axis=-1) # expend Z
data = np.expand_dims(data, axis=-1) # expend channel
elif mrc.is_image_stack():
data = np.expand_dims(data, axis=-1) # expend Z
data = np.expand_dims(data, axis=-1) # expend channel
elif mrc.is_volume():
data = np.expand_dims(data, axis=0) # expend frame
data = np.expand_dims(data, axis=-1) # expend channel
elif mrc.is_volume_stack():
data = np.expand_dims(data, axis=-1) # expend channel
name = get_file_no_digits_name(data_path)
spacing = (mrc.voxel_size.x,
mrc.voxel_size.y,
mrc.voxel_size.z)
# Parsing with OMETIFFReader
if data is None and ext in OME_EXTS and not is_sequence:
print("Parsing with OMETIFFReader...")
reader = OMETIFFReader(fpath=data_path)
ome_image, metadata, xml_metadata = reader.read()
# TODO: some old bio-format tiff the header is not the same.
if progress_callback:
progress_callback(0.5, "Transpose to 'TXYZC'...")
try:
# print(ome_image.shape)
# for key in metadata:
# print(f"{key},{metadata[key]}")
ome_order = metadata['DimOrder BF Array']
if ome_image.ndim == 2:
ome_order = ome_order.replace("T", "")\
.replace("C", "").replace("Z", "")
bioxel_order = (ome_order.index('X'),
ome_order.index('Y'))
data = np.transpose(ome_image, bioxel_order)
data = np.expand_dims(data, axis=0) # expend frame
data = np.expand_dims(data, axis=-1) # expend Z
data = np.expand_dims(data, axis=-1) # expend channel
elif ome_image.ndim == 3:
# -> XYZC
ome_order = ome_order.replace("T", "").replace("C", "")
bioxel_order = (ome_order.index('X'),
ome_order.index('Y'),
ome_order.index('Z'))
data = np.transpose(ome_image, bioxel_order)
data = np.expand_dims(data, axis=0) # expend frame
data = np.expand_dims(data, axis=-1) # expend channel
elif ome_image.ndim == 4:
# -> XYZC
ome_order = ome_order.replace("T", "")
bioxel_order = (ome_order.index('X'),
ome_order.index('Y'),
ome_order.index('Z'),
ome_order.index('C'))
data = np.transpose(ome_image, bioxel_order)
data = np.expand_dims(data, axis=0) # expend frame
elif ome_image.ndim == 5:
# -> TXYZC
bioxel_order = (ome_order.index('T'),
ome_order.index('X'),
ome_order.index('Y'),
ome_order.index('Z'),
ome_order.index('C'))
data = np.transpose(ome_image, bioxel_order)
try:
spacing = (metadata['PhysicalSizeX'],
metadata['PhysicalSizeY'],
metadata['PhysicalSizeZ'])
except:
...
name = get_file_no_digits_name(data_path)
except:
...
# Parsing with SimpleITK
if data is None:
print("Parsing with SimpleITK...")
if ext in DICOM_EXTS:
data_dirpath = data_path.parent
reader = sitk.ImageSeriesReader()
reader.MetaDataDictionaryArrayUpdateOn()
reader.LoadPrivateTagsOn()
series_files = reader.GetGDCMSeriesFileNames(
str(data_dirpath), series_id)
reader.SetFileNames(series_files)
itk_image = reader.Execute()
# for k in reader.GetMetaDataKeys(0):
# v = reader.GetMetaData(0, k)
# print(f'({k}) = = "{v}"')
def get_meta(key):
try:
stirng = reader.GetMetaData(0, key).removesuffix(" ")
stirng.encode('utf-8')
if stirng in ["No study description",
"No series description",
""]:
return None
else:
return stirng
except:
return None
study_description = get_meta("0008|1030")
series_description = get_meta("0008|103e")
series_modality = get_meta("0008|0060")
name = study_description or data_dirpath.name
if series_description and series_modality:
description = f"{series_description}-{series_modality}"
elif series_description:
description = series_description
elif series_modality:
description = series_modality
else:
description = ""
name = name.replace(" ", "-")
description = description.replace(" ", "-")
elif ext in SEQUENCE_EXTS and is_sequence:
itk_image = sitk.ReadImage(sequence)
name = get_file_no_digits_name(data_path)
else:
itk_image = sitk.ReadImage(data_path)
name = get_filename(data_path)
# for key in itk_image.GetMetaDataKeys():
# print(f"{key},{itk_image.GetMetaData(key)}")
if progress_callback:
progress_callback(0.5, "Transpose to 'TXYZC'...")
if itk_image.GetDimension() == 2:
data = sitk.GetArrayFromImage(itk_image)
if data.ndim == 3:
data = np.transpose(data, (1, 0, 2))
data = np.expand_dims(data, axis=-2) # expend Z
else:
data = np.transpose(data)
data = np.expand_dims(data, axis=-1) # expend Z
data = np.expand_dims(data, axis=-1) # expend channel
data = np.expand_dims(data, axis=0) # expend frame
elif itk_image.GetDimension() == 3:
if ext not in SEQUENCE_EXTS:
itk_image = sitk.DICOMOrient(itk_image, 'RAS')
# After sitk.DICOMOrient(), origin and direction will also orient base on LPS
# so we need to convert them into RAS
# affine = axis_conversion(from_forward='-Z',
# from_up='-Y',
# to_forward='-Z',
# to_up='Y').to_4x4()
affine = np.array([[-1.0000, 0.0000, 0.0000, 0.0000],
[0.0000, -1.0000, 0.0000, 0.0000],
[0.0000, 0.0000, 1.0000, 0.0000],
[0.0000, 0.0000, 0.0000, 1.0000]])
spacing = tuple(itk_image.GetSpacing())
origin = tuple(itk_image.GetOrigin())
direction = tuple(itk_image.GetDirection())
data = sitk.GetArrayFromImage(itk_image)
# transpose ijk to kji
if data.ndim == 4:
data = np.transpose(data, (2, 1, 0, 3))
else:
data = np.transpose(data)
data = np.expand_dims(data, axis=-1) # expend channel
data = np.expand_dims(data, axis=0) # expend frame
elif itk_image.GetDimension() == 4:
spacing = tuple(itk_image.GetSpacing()[:3])
origin = tuple(itk_image.GetOrigin()[:3])
# FIXME: not sure...
direction = np.array(itk_image.GetDirection())
direction = direction.reshape(3, 3) if itk_image.GetDimension() == 3 \
else direction.reshape(4, 4)
direction = direction[1:, 1:]
direction = tuple(direction.flatten())
data = sitk.GetArrayFromImage(itk_image)
if data.ndim == 5:
data = np.transpose(data, (0, 3, 2, 1, 4))
else:
data = np.transpose(data, (0, 3, 2, 1))
data = np.expand_dims(data, axis=-1)
if itk_image.GetDimension() > 5:
raise Exception
t = origin
r = np.array(direction).reshape((3, 3))
affine = np.dot(affine,
transforms3d.affines.compose(t, r, [1, 1, 1]))
meta = {
"name": name,
"description": description,
"spacing": spacing,
"affine": affine,
"xyz_shape": data.shape[1:4],
"frame_count": data.shape[0],
"channel_count": data.shape[-1],
}
return data, meta

View File

@@ -0,0 +1,46 @@
schema_version = "1.0.0"
id = "bioxelnodes"
version = "2.0.2"
name = "Bioxel Nodes"
tagline = "For scientific volumetric data visualization in Blender"
maintainer = "Nan <icrdr2010@outlook.com>"
type = "add-on"
website = "https://docs.omoolab.xyz/bioxelnodes/"
tags = ["Geometry Nodes", "Render", "Import-Export"]
blender_version_min = "5.0.0"
license = ['SPDX:GPL-3.0-or-later']
copyright = ["2024 OmooLab"]
platforms = ["windows-x64"]
wheels = [
"./wheels/contourpy-1.3.3-cp311-cp311-win_amd64.whl",
"./wheels/contourpy-1.3.3-cp313-cp313-win_amd64.whl",
"./wheels/cycler-0.12.1-py3-none-any.whl",
"./wheels/fonttools-4.63.0-cp311-cp311-win_amd64.whl",
"./wheels/fonttools-4.63.0-cp313-cp313-win_amd64.whl",
"./wheels/h5py-3.14.0-cp311-cp311-win_amd64.whl",
"./wheels/h5py-3.14.0-cp313-cp313-win_amd64.whl",
"./wheels/kiwisolver-1.5.0-cp311-cp311-win_amd64.whl",
"./wheels/kiwisolver-1.5.0-cp313-cp313-win_amd64.whl",
"./wheels/lxml-6.1.1-cp311-cp311-win_amd64.whl",
"./wheels/lxml-6.1.1-cp313-cp313-win_amd64.whl",
"./wheels/matplotlib-3.10.7-cp311-cp311-win_amd64.whl",
"./wheels/matplotlib-3.10.7-cp313-cp313-win_amd64.whl",
"./wheels/mrcfile-1.5.1-py2.py3-none-any.whl",
"./wheels/pillow-11.2.1-cp311-cp311-win_amd64.whl",
"./wheels/pillow-11.2.1-cp313-cp313-win_amd64.whl",
"./wheels/pyometiff-1.0.0-py3-none-any.whl",
"./wheels/pyparsing-3.3.2-py3-none-any.whl",
"./wheels/python_dateutil-2.9.0.post0-py2.py3-none-any.whl",
"./wheels/scipy-1.17.1-cp311-cp311-win_amd64.whl",
"./wheels/scipy-1.17.1-cp313-cp313-win_amd64.whl",
"./wheels/simpleitk-2.5.5-cp311-abi3-win_amd64.whl",
"./wheels/six-1.17.0-py2.py3-none-any.whl",
"./wheels/tifffile-2024.7.24-py3-none-any.whl",
"./wheels/transforms3d-0.4.2-py3-none-any.whl",
]
[permissions]
files = "Import/export volume data from/to disk"

View File

@@ -0,0 +1,11 @@
from pathlib import Path
NODE_LIB_FILENAME = "O_Bioxel_Nodes.blend"
NODE_LIB_DIRPATH = Path(Path(__file__).parent,
"assets/O_Bioxel").resolve()
LATEST_NODE_LIB_PATH = Path(NODE_LIB_DIRPATH,
NODE_LIB_FILENAME).resolve()
PREVIEW_COLLECTIONS = {}

View File

@@ -0,0 +1,6 @@
# This file is kept for backward compatibility
# Custom exceptions have been replaced with built-in exceptions:
# CancelledByUser -> CancelledError
# NoContent -> ValueError
# NoFound -> LookupError
# Incompatible -> ValueError

290
src/bioxelnodes/layer.py Normal file
View File

@@ -0,0 +1,290 @@
import json
import time
from typing import Any, List, Dict
from pathlib import Path
import matplotlib.pyplot as plt
import bpy
import numpy as np
try:
import openvdb as vdb
except ImportError:
vdb = None
from .bioxel.layer import Layer
from .utils import ndarray_to_png
LAYERS_JSON = "bioxel_layers"
def cache_layer_data(layer: Layer, cache_path: str):
"""
Cache the given Layer's data as one or more VDB files.
- For multi-frame layers, writes per-frame VDB files named data.0001.vdb, data.0002.vdb, ...
- For single-frame layers, writes a single data.vdb file.
- Applies basic type handling:
- label/scalar layers collapse channel dimension via max.
- scalar layers are offset to avoid negative values.
- The VDB grids will have their transform set from layer.affine but no additional metadata is written.
Parameters:
- layer: Layer object containing ndarray data and metadata.
- cache_path: directory path where VDB files will be written (created if missing).
"""
data = layer.data
# 处理标量/标签类型(去除通道维度)
if layer.kind in ["label", "scalar"]:
data = np.amax(data, -1)
# 标量类型偏移处理(避免负值)
offset = 0
if layer.kind in ["scalar"]:
data = data.astype(np.float32)
orig_min = float(np.min(data))
if orig_min < 0:
offset = -orig_min
data = data + np.full_like(data, offset)
# 创建缓存目录
cache_path = Path(cache_path)
cache_path.mkdir(parents=True, exist_ok=True)
# 多帧序列处理
if layer.frame_count > 1:
for f in range(layer.frame_count):
# 根据图层类型创建VDB网格
if layer.kind in ["label", "scalar"]:
grid = vdb.FloatGrid()
grid.copyFromArray(data[f, :, :, :].copy().astype(np.float32))
else: # 颜色类型
grid = vdb.Vec3SGrid()
grid.copyFromArray(data[f, :, :, :, :].copy().astype(np.float32))
# 仅设置transform,不存储metadata
grid.transform = vdb.createLinearTransform(layer.affine.transpose())
grid.name = layer.kind
# 保存序列帧VDB
data_filepath = cache_path / f"data.{str(f+1).zfill(4)}.vdb"
vdb.write(str(data_filepath), grids=[grid])
else:
# 单帧处理
if layer.kind in ["label", "scalar"]:
grid = vdb.FloatGrid()
grid.copyFromArray(data[0, :, :, :].copy().astype(np.float32))
else: # 颜色类型
grid = vdb.Vec3SGrid()
grid.copyFromArray(data[0, :, :, :, :].copy().astype(np.float32))
# 仅设置transform,不存储metadata
grid.transform = vdb.createLinearTransform(layer.affine.transpose())
grid.name = layer.kind
# 保存单帧VDB
data_filepath = cache_path / "data.vdb"
vdb.write(str(data_filepath), grids=[grid])
def cache_layer_snapshot(layer: Layer, cache_path: str):
"""
Create and save a low-resolution snapshot (numpy .npy) of the layer and generate PNG slices.
- Saves a 3D numpy ndarray snapshot to <cache_path>/snapshot.npy.
- Then creates per-Z PNGs in the same directory via snapshot_to_pngs.
Parameters:
- layer: Layer to snapshot (expects Layer.snapshot method).
- cache_path: destination directory where snapshot.npy and PNGs will be created.
"""
cache_path = Path(cache_path)
cache_path.mkdir(parents=True, exist_ok=True)
snapshot_filepath = cache_path / "snapshot.npy"
snapshot = layer.snapshot((64, 64, 32))
np.save(str(snapshot_filepath), snapshot)
snapshot_to_pngs(
snapshot, str(cache_path), normalize=layer.kind in ["scalar", "vector"]
)
if layer.kind in ["scalar", "vector", "color"]:
plt.figure(figsize=(8, 8))
def plot_histogram(plt, data, color="black"):
flattened = data.flatten()
x_min = np.percentile(flattened, 1)
x_max = np.percentile(flattened, 99)
n, bins, _ = plt.hist(
flattened,
bins=50, # 自动根据数据密度调整bins数量(避免空柱)
range=(x_min, x_max), # 只显示核心区域,省略稀疏部分
alpha=0,
edgecolor="none", # 去除边框,使柱形更紧凑
)
bin_centers = 0.5 * (bins[1:] + bins[:-1]) # 计算每个bin的中点
plt.plot(bin_centers, n, color=color, linewidth=4) # 折线
plt.fill_between(bin_centers, n, color=color, alpha=0.1)
if layer.kind == "scalar":
plot_histogram(plt, layer.data[:, :, :, 0], color="black")
elif layer.kind in ["vector", "color"]:
plot_histogram(plt, layer.data[:, :, :, 0], color="tomato")
plot_histogram(plt, layer.data[:, :, :, 1], color="yellowgreen")
plot_histogram(plt, layer.data[:, :, :, 2], color="xkcd:azure")
plt.yscale("log")
plt.gca().get_yaxis().set_visible(False)
plt.xticks(fontsize=32, rotation=45) # 调整字体大小(数值越大字体越大)
ax = plt.gca()
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["left"].set_visible(False) # 隐藏左边框
# 调整布局避免标签被截断
plt.tight_layout()
# 保存图片到指定路径
save_path = cache_path / "histogram.png"
plt.savefig(save_path, bbox_inches="tight", pad_inches=0.1) # 减少边缘留白)
# 关闭图像释放资源
plt.close()
def snapshot_to_pngs(snapshot, cache_path: str, normalize=False):
"""
Convert a 3D/4D snapshot ndarray into per-slice PNG files.
- snapshot is expected with axes order X, Y, Z, (C optional).
- Writes files snapshot_0.png ... snapshot_{Z-1}.png into cache_path.
- Uses ndarray_to_png to perform the per-slice conversion.
Parameters:
- snapshot: numpy ndarray (X, Y, Z[, C])
- cache_path: directory where generated PNGs are stored.
"""
cache_path = Path(cache_path)
cache_path.mkdir(parents=True, exist_ok=True)
if normalize:
mn = float(np.percentile(snapshot, 50))
mx = float(np.percentile(snapshot, 99))
if mx - mn > 1e-8:
snapshot = (snapshot - mn) / (mx - mn)
else:
snapshot = np.clip(snapshot, 0.0, 1.0)
shape = snapshot.shape
for zidx in range(shape[2]):
array = snapshot[:, :, zidx, :]
ndarray_to_png(array, str(cache_path / f"snapshot_{zidx}.png"))
def get_layer_caches() -> List[Dict[str, Any]]:
"""
Read the saved layer metadata list from Blender's internal text datablock.
- Looks for a text datablock named by LAYERS_JSON ("bioxel_layers").
- Returns the parsed list of layer dictionaries if present; otherwise returns an empty list.
Returns:
- list of layer metadata dictionaries (possibly empty)
"""
# 检查文本数据块是否存在
if LAYERS_JSON not in bpy.data.texts:
return []
# 加载并解析数据
layers_text = bpy.data.texts[LAYERS_JSON]
try:
layers_data = json.loads(layers_text.as_string())
# 确保返回格式为列表
return layers_data if isinstance(layers_data, list) else []
except:
return []
def set_layer_caches(layers_data: List[Dict[str, Any]]):
"""
Write the provided list of layer metadata dictionaries into the Blender text datablock.
- Ensures the LAYERS_JSON text datablock exists, then overwrites it with pretty JSON.
Parameters:
- layers_data: list of serializable dictionaries describing the layers
"""
# 获取或创建文本数据块
if LAYERS_JSON not in bpy.data.texts:
bpy.data.texts.new(LAYERS_JSON)
layers_text = bpy.data.texts[LAYERS_JSON]
# 写入数据
layers_text.clear()
layers_text.write(json.dumps(layers_data, indent=4))
def save_layers_to_cache(layers: List[Layer], cache_dir: str) -> List[Dict[str, Any]]:
"""
Save multiple Layer objects into cache folders.
For each layer:
- Generates a unique cache id.
- Writes VDB files and a low-resolution snapshot (.npy) plus PNG slices under cache_dir/<cache_id>/.
Returns:
- List of layer cache metadata dictionaries.
"""
cache_infos = []
cache_dir_path = Path(cache_dir)
cache_dir_path.mkdir(parents=True, exist_ok=True)
for idx, layer in enumerate(layers):
cache_id = str(int(time.time())) + str(idx)
cache_path = cache_dir_path / str(cache_id)
cache_layer_data(layer, cache_path)
cache_layer_snapshot(layer, cache_path)
# build layer_info
cache_info = {
"id": cache_id,
"name": layer.name,
"kind": layer.kind,
"shape": layer.shape,
"affine": layer.affine.tolist(),
"bioxel_size": layer.bioxel_size[0],
"dtype": layer.dtype.str,
"dtype_num": layer.dtype.num,
"frame_count": layer.frame_count,
"channel_count": layer.channel_count,
"offset": max(0, -layer.min),
"min": layer.min,
"max": layer.max,
"path": bpy.path.abspath(str(cache_path)),
"snapshot_z": 0.5,
}
cache_infos.append(cache_info)
return cache_infos
def save_layers_to_json(layers: List[Layer], cache_dir: str) -> List[int]:
"""
Save multiple Layer objects into cache folders and the internal layers text datablock.
"""
existing_data = get_layer_caches()
cache_infos = save_layers_to_cache(layers, cache_dir)
added_ids = []
for cache_info in cache_infos:
existing_data.append(cache_info)
added_ids.append(cache_info["id"])
set_layer_caches(existing_data)
print(f"Successfully added {len(added_ids)} layers to the internal text datablock")
return added_ids

Some files were not shown because too many files have changed in this diff Show More