Compare commits
13 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
467d368a76 | ||
| 134d8e382b | |||
|
|
fefc9285e1 | ||
| 322b84cc70 | |||
| f3be5d8660 | |||
| 470cdab4f6 | |||
|
|
b35c816c25 | ||
| 0e2d6fe1a2 | |||
|
|
e0c46e95f8 | ||
| 2528d984ad | |||
|
|
56606fd721 | ||
| f21f7d6357 | |||
| fa031e63f8 |
37
.github/workflows/upload-assets.yml
vendored
@@ -22,7 +22,7 @@ jobs:
|
||||
# id: draft_release
|
||||
# uses: cardinalby/git-get-release-action@1.2.4
|
||||
# with:
|
||||
# releaseName: Draft
|
||||
# releaseName: Upload
|
||||
# env:
|
||||
# GITHUB_TOKEN: ${{ github.token }}
|
||||
|
||||
@@ -70,5 +70,38 @@ jobs:
|
||||
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
|
||||
asset_path: ./package.zip
|
||||
asset_name: BioxelNodes_${{ needs.draft_release.outputs.version }}.zip
|
||||
asset_name: BioxelNodes_Addon_${{ needs.draft_release.outputs.version }}.zip
|
||||
asset_content_type: application/zip
|
||||
|
||||
upload_blender_extension:
|
||||
name: Upload Blender Extension
|
||||
needs: draft_release
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout Code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
lfs: 'true'
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: 3.11
|
||||
- name: Zip Extension
|
||||
run: |
|
||||
pip download SimpleITK --dest bioxelnodes/wheels --only-binary=:all: --python-version=3.11 --platform=macosx_11_0_arm64
|
||||
pip download SimpleITK --dest bioxelnodes/wheels --only-binary=:all: --python-version=3.11 --platform=win_amd64
|
||||
rm -r bioxelnodes/externalpackage
|
||||
cp extension/__init__.py bioxelnodes/__init__.py
|
||||
cp extension/preferences.py bioxelnodes/preferences.py
|
||||
cp extension/blender_manifest.toml bioxelnodes/blender_manifest.toml
|
||||
zip -r package.zip bioxelnodes
|
||||
- name: Upload Release Asset
|
||||
id: upload-release-asset
|
||||
uses: actions/upload-release-asset@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
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
|
||||
asset_path: ./package.zip
|
||||
asset_name: BioxelNodes_Extension_${{ needs.draft_release.outputs.version }}.zip
|
||||
asset_content_type: application/zip
|
||||
|
||||
39
README.md
@@ -9,17 +9,17 @@
|
||||
|
||||
Bioxel Nodes is a Blender add-on for scientific volumetric data visualization. It using Blender's powerful Geometry Nodes | Cycles to process and render volumetric data.
|
||||
|
||||
# About
|
||||
## About
|
||||
|
||||
Before us, there have been many tutorials and add-ons for importing volumetric data into Blender. However, we found that there were many details that were not addressed in place, some scientific facts were ignored, and the volume rendering was not pretty enough. With Bioxel Nodes, you can easily import the volumetric data into Blender, and more importantly, it can quickly make a beautiful realistic rendering of it.
|
||||
|
||||
Below are some examples with Bioxel Nodes. Thanks to Cycles Render, the volumetric data can be rendered with great detail:
|
||||
|
||||

|
||||

|
||||
|
||||
The "Bioxel" in "BioxelNodes", is a combination of the words "Bio-" and "Voxel". Bioxel is a voxel that stores biological data. The volumetric data made up of Bioxel is called Bioxels. We are developing a toolkit around Bioxels for better biological data visualization. but before its release, we made this Blender version of bioxels toolkit first, in order to let more people to have fun with volumetric data. [Getting Started](https://omoolab.github.io/BioxelNodes/latest/getting-started)
|
||||
The "Bioxel" in "Bioxel Nodes", is a combination of the words "Bio-" and "Voxel". Bioxel is a voxel that stores biological data. We are developing a toolkit around Bioxel for better biological data visualization. but before its release, we made this Blender version of bioxels toolkit first, in order to let more people to have fun with volumetric data. [Getting Started](https://omoolab.github.io/BioxelNodes/latest/getting-started)
|
||||
|
||||
# Supported Format
|
||||
## Supported Format
|
||||
|
||||
| Format | EXT | Test |
|
||||
| ------ | ---------------------------------------- | ------- |
|
||||
@@ -39,7 +39,32 @@ The "Bioxel" in "BioxelNodes", is a combination of the words "Bio-" and "Voxel".
|
||||
| MINC | .mnc, .MNC | yet |
|
||||
| MRC | .mrc, .rec | yet |
|
||||
|
||||
# Known limitations
|
||||
## Known Limitations
|
||||
|
||||
- Sections cannot be generated
|
||||
- Time sequence volume not supported (will be supported soon)
|
||||
- Sections cannot be generated (will be supported soon)
|
||||
- Time sequence volume not supported (will be supported soon)
|
||||
|
||||
## To Upgrade Add-on
|
||||
|
||||
To upgrade from an older version of the add-on to the latest, you need to do the following:
|
||||
|
||||
1. Remove the old version of Bioxel Nodes at Preferences > Add-ons
|
||||
2. Add the new version and restart Blender.
|
||||
|
||||
It is not support editing the same blender file across add-on versions. In order to make sure that the previous file works properly. You need to save the staged data before upgrading ( read the last section of [Getting Started](https://omoolab.github.io/BioxelNodes/latest/getting-started/#share-your-file) ).
|
||||
|
||||
But even then, there is still no guarantee that the new version of the add-on will work on the old blender file. Therefore, it is highly recommended to open a new blender file to start the creating, not based on the old one.
|
||||
|
||||
Alternatively, objects from the old file that have nothing to do with Bioxel Nodes could be append to the new blender file.
|
||||
|
||||
## About EEVEE Render
|
||||
|
||||
Bioxel Nodes is designed for Cycles Render. However, it does support eevee render partially. "Solid Shader" node and "Volume Shader" node have a toggle called "EEVEE Render". If you want to render Bioxel Component in real-time, turn it on.
|
||||
|
||||
Also, there are some limitations:
|
||||
|
||||
1. Only one cutter supported.
|
||||
2. You cannot use "Color Ramp" over 2 colors.
|
||||
3. EEVEE Render result is not that great as Cycles does.
|
||||
|
||||
> "Volume Shader" node is not work properly in EEVEE Next since 4.2. It is because EEVEE Next is not support attributes from instances of volume shader by now. But the Blender 4.2 docs still say attributes reading is ok, so I suppose this feature will eventually be implemented.
|
||||
|
||||
@@ -9,7 +9,7 @@ bl_info = {
|
||||
"author": "Ma Nan",
|
||||
"description": "",
|
||||
"blender": (4, 0, 0),
|
||||
"version": (0, 1, 1),
|
||||
"version": (0, 2, 0),
|
||||
"location": "File -> Import",
|
||||
"warning": "",
|
||||
"category": "Node"
|
||||
@@ -21,8 +21,8 @@ auto_load.init()
|
||||
def register():
|
||||
auto_load.register()
|
||||
menus.add()
|
||||
bpy.types.Scene.bioxels_dir = bpy.props.StringProperty(
|
||||
name="Bioxels Directory",
|
||||
bpy.types.Scene.bioxel_layer_dir = bpy.props.StringProperty(
|
||||
name="Bioxel Layers Directory",
|
||||
subtype='DIR_PATH',
|
||||
default="//"
|
||||
)
|
||||
|
||||
@@ -57,7 +57,7 @@ def unregister():
|
||||
#################################################
|
||||
|
||||
def get_all_submodules(directory):
|
||||
return list(iter_submodules(directory, directory.name))
|
||||
return list(iter_submodules(directory, __package__))
|
||||
|
||||
|
||||
def iter_submodules(path, package_name):
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
import bpy
|
||||
from .utils import get_bioxels_obj, get_node_by_type
|
||||
|
||||
|
||||
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'}
|
||||
|
||||
@classmethod
|
||||
def poll(cls, context):
|
||||
bioxels_obj = None
|
||||
for obj in bpy.context.selected_objects:
|
||||
bioxels_obj = get_bioxels_obj(obj)
|
||||
break
|
||||
|
||||
return True if bioxels_obj else False
|
||||
|
||||
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 = get_node_by_type(nodes, 'NodeGroupOutput')[0]
|
||||
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()
|
||||
|
||||
self.report({"INFO"}, f"Successfully convert to mesh")
|
||||
|
||||
return {'FINISHED'}
|
||||
@@ -146,10 +146,13 @@ class CustomNodes():
|
||||
def _find_item(self, found_items, menu_items, node_type: str):
|
||||
|
||||
for item in menu_items:
|
||||
if item == 'separator':
|
||||
continue
|
||||
|
||||
if item.get("node_type") == node_type:
|
||||
found_items.append(item)
|
||||
|
||||
item_items = item.get('items') if item != 'separator' else None
|
||||
item_items = item.get('items')
|
||||
if item_items:
|
||||
self._find_item(found_items, item_items, node_type)
|
||||
|
||||
@@ -160,16 +163,18 @@ class CustomNodes():
|
||||
|
||||
def add_node(self, node_tree, node_type: str):
|
||||
item = self.find_item(node_type)
|
||||
op = AddCustomNode()
|
||||
op.nodes_file = self.nodes_file
|
||||
op.node_type = 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.")
|
||||
op.node_label = ""
|
||||
op.node_link = True
|
||||
op.node_callback = ""
|
||||
return op.add_node(node_tree)
|
||||
|
||||
def register(self):
|
||||
for cls in self.menu_classes:
|
||||
|
||||
@@ -76,7 +76,8 @@ class PackageInstaller():
|
||||
|
||||
# Set up logging configuration
|
||||
logfile_path = Path(self.log_path, f"{logfile_name}.log")
|
||||
logging.basicConfig(filename=logfile_path, level=logging.INFO)
|
||||
logging.basicConfig(filename=logfile_path,
|
||||
level=logging.INFO, encoding='utf-8')
|
||||
|
||||
# Return logger object
|
||||
return logging.getLogger()
|
||||
@@ -248,13 +249,16 @@ class PackageInstaller():
|
||||
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(errors='ignore'))
|
||||
else:
|
||||
log.info('Command succeeded: %s', cmd_list)
|
||||
log.info('stdout: %s', result.stdout.decode())
|
||||
try:
|
||||
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(errors='ignore'))
|
||||
else:
|
||||
log.info('Command succeeded: %s', cmd_list)
|
||||
log.info('stdout: %s', result.stdout.decode())
|
||||
except:
|
||||
...
|
||||
# return the command list, return code, stdout, and stderr as a tuple
|
||||
return result
|
||||
|
||||
|
||||
@@ -6,16 +6,19 @@ import numpy as np
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
import mathutils
|
||||
import math
|
||||
from .utils import calc_bbox_verts, get_text_index_str, get_bioxels_obj, get_node_by_type, show_message
|
||||
import random
|
||||
|
||||
from .nodes import custom_nodes
|
||||
from .props import BIOXELNODES_Series
|
||||
from .utils import (calc_bbox_verts, get_all_layers, get_container, get_layer, get_text_index_str,
|
||||
get_node_by_type, hide_in_ray, lock_transform, show_message)
|
||||
|
||||
try:
|
||||
import SimpleITK as sitk
|
||||
except:
|
||||
...
|
||||
|
||||
SUPPORT_EXTS = ['.dcm', '.DICOM',
|
||||
SUPPORT_EXTS = ['.dcm', '.DCM', '.DICOM',
|
||||
'.bmp', '.BMP',
|
||||
'.PIC', '.pic',
|
||||
'.gipl', '.gipl.gz',
|
||||
@@ -31,15 +34,15 @@ SUPPORT_EXTS = ['.dcm', '.DICOM',
|
||||
'.png', '.PNG',
|
||||
'.vtk']
|
||||
|
||||
SEQUENCE_EXTS = ['.dcm', '.DICOM',
|
||||
SEQUENCE_EXTS = ['.dcm', '.DCM', '.DICOM',
|
||||
'.bmp', '.BMP',
|
||||
'.jpg', '.JPG', '.jpeg', '.JPEG',
|
||||
'.tif', '.TIF', '.tiff', '.TIFF',
|
||||
'.png', '.PNG']
|
||||
|
||||
DICOM_EXTS = ['.dcm', '.DICOM']
|
||||
DICOM_EXTS = ['.dcm', '.DCM', '.DICOM']
|
||||
|
||||
FH_EXTS = ['.dcm', '.DICOM',
|
||||
FH_EXTS = ['.dcm', '.DCM', '.DICOM',
|
||||
'.gipl', '.gipl.gz',
|
||||
'.mnc', '.MNC',
|
||||
'.mrc', '.rec',
|
||||
@@ -51,7 +54,7 @@ FH_EXTS = ['.dcm', '.DICOM',
|
||||
'.gz']
|
||||
|
||||
|
||||
def get_bioxels_shape(bioxel_size: float, orig_shape: tuple, orig_spacing: tuple):
|
||||
def get_layer_shape(bioxel_size: float, orig_shape: tuple, orig_spacing: 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]))
|
||||
@@ -132,27 +135,36 @@ def read_image(filepath: str, series_id=""):
|
||||
|
||||
def rgb2gray(image):
|
||||
# Convert sRGB image to gray scale and rescale results to [0,255]
|
||||
channels = [sitk.VectorIndexSelectionCast(
|
||||
layers = [sitk.VectorIndexSelectionCast(
|
||||
image, i, sitk.sitkFloat32) for i in range(image.GetNumberOfComponentsPerPixel())]
|
||||
# linear mapping
|
||||
I = (0.2126*channels[0] + 0.7152*channels[1] + 0.0722*channels[2])
|
||||
I = (0.2126*layers[0] + 0.7152*layers[1] + 0.0722*layers[2])
|
||||
|
||||
return sitk.Cast(I, sitk.sitkFloat32)
|
||||
|
||||
|
||||
def x2gray(image):
|
||||
return sitk.VectorIndexSelectionCast(image, 0, sitk.sitkUInt16)
|
||||
|
||||
|
||||
class ImportVolumeDataDialog(bpy.types.Operator):
|
||||
bl_idname = "bioxelnodes.import_volume_data_dialog"
|
||||
bl_label = "Volume Data as Bioxels"
|
||||
bl_description = "Import Volume Data as Bioxels (VDB)"
|
||||
bl_label = "Volume Data as Bioxel Layer"
|
||||
bl_description = "Import Volume Data as Bioxel Layer"
|
||||
bl_options = {'UNDO'}
|
||||
|
||||
filepath: bpy.props.StringProperty(
|
||||
subtype="FILE_PATH",
|
||||
options={'HIDDEN'}
|
||||
subtype="FILE_PATH"
|
||||
) # type: ignore
|
||||
|
||||
container_name: bpy.props.StringProperty(
|
||||
name="Container Name"
|
||||
) # type: ignore
|
||||
|
||||
layer_name: bpy.props.StringProperty(
|
||||
name="Layer Name",
|
||||
) # type: ignore
|
||||
|
||||
series_id: bpy.props.StringProperty() # type: ignore
|
||||
|
||||
resample_method: bpy.props.EnumProperty(
|
||||
@@ -163,6 +175,8 @@ class ImportVolumeDataDialog(bpy.types.Operator):
|
||||
("gaussian", "Gaussian", "")]
|
||||
) # type: ignore
|
||||
|
||||
container: bpy.props.StringProperty() # type: ignore
|
||||
|
||||
read_as: bpy.props.EnumProperty(
|
||||
name="Read as",
|
||||
default="scalar",
|
||||
@@ -170,15 +184,10 @@ class ImportVolumeDataDialog(bpy.types.Operator):
|
||||
("labels", "Labels", "")]
|
||||
) # type: ignore
|
||||
|
||||
label_index: bpy.props.IntProperty(
|
||||
name="Label Index",
|
||||
default=1
|
||||
) # type: ignore
|
||||
|
||||
bioxel_size: bpy.props.FloatProperty(
|
||||
name="Bioxel Size (Larger size means small resolution)",
|
||||
soft_min=0.1, soft_max=10.0,
|
||||
min=1e-2, max=1e2,
|
||||
min=0.1, max=1e2,
|
||||
default=1,
|
||||
) # type: ignore
|
||||
|
||||
@@ -193,7 +202,7 @@ class ImportVolumeDataDialog(bpy.types.Operator):
|
||||
) # type: ignore
|
||||
|
||||
scene_scale: bpy.props.FloatProperty(
|
||||
name="Scene Scale (Bioxels Unit pre Blender Unit)",
|
||||
name="Scene Scale (Bioxel Unit pre Blender Unit)",
|
||||
soft_min=0.001, soft_max=100.0,
|
||||
min=1e-6, max=1e6,
|
||||
default=0.01,
|
||||
@@ -210,32 +219,33 @@ class ImportVolumeDataDialog(bpy.types.Operator):
|
||||
) # type: ignore
|
||||
|
||||
def execute(self, context):
|
||||
image, bioxels_name = read_image(self.filepath, self.series_id)
|
||||
|
||||
is_first_import = len(get_all_layers()) == 0
|
||||
image, name = read_image(self.filepath, self.series_id)
|
||||
container_name = self.container_name or name
|
||||
bioxel_size = self.bioxel_size
|
||||
orig_spacing = self.orig_spacing
|
||||
image_spacing = image.GetSpacing()
|
||||
image_shape = image.GetSize()
|
||||
|
||||
bioxels_spacing = (
|
||||
layer_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 = get_bioxels_shape(
|
||||
layer_shape = get_layer_shape(
|
||||
bioxel_size, image_shape, orig_spacing)
|
||||
|
||||
if self.read_as == "labels":
|
||||
if "vector" in image.GetPixelIDTypeAsString():
|
||||
print("Convet to Grayscale...")
|
||||
print("Conveting to Grayscale...")
|
||||
image = x2gray(image)
|
||||
else:
|
||||
image = sitk.Cast(image, sitk.sitkUInt16)
|
||||
default_value = 0
|
||||
elif self.read_as == "scalar":
|
||||
if "vector" in image.GetPixelIDTypeAsString():
|
||||
print("Convet to Grayscale...")
|
||||
print("Conveting to Grayscale...")
|
||||
image = rgb2gray(image)
|
||||
else:
|
||||
image = sitk.Cast(image, sitk.sitkFloat32)
|
||||
@@ -251,14 +261,17 @@ class ImportVolumeDataDialog(bpy.types.Operator):
|
||||
elif self.resample_method == "gaussian":
|
||||
interpolator = sitk.sitkGaussian
|
||||
|
||||
if self.read_as == "labels":
|
||||
interpolator = sitk.sitkNearestNeighbor
|
||||
|
||||
print(f"Resampling...")
|
||||
image = sitk.Resample(
|
||||
image1=image,
|
||||
size=bioxels_shape,
|
||||
size=layer_shape,
|
||||
transform=sitk.Transform(),
|
||||
interpolator=interpolator,
|
||||
outputOrigin=image.GetOrigin(),
|
||||
outputSpacing=bioxels_spacing,
|
||||
outputSpacing=layer_spacing,
|
||||
outputDirection=image.GetDirection(),
|
||||
defaultPixelValue=default_value,
|
||||
outputPixelType=image.GetPixelID(),
|
||||
@@ -281,63 +294,15 @@ class ImportVolumeDataDialog(bpy.types.Operator):
|
||||
# A (nterior) j -> j -> y
|
||||
# S (uperior) k -> i -> z
|
||||
array = sitk.GetArrayFromImage(image)
|
||||
|
||||
orig_dtype = str(array.dtype)
|
||||
# print(f"Coverting Dtype from {orig_dtype} to float...")
|
||||
# array = array.astype(float)
|
||||
|
||||
if array.ndim == 4:
|
||||
# if array.shape[0] == 3 and self.read_as == "scalar":
|
||||
# # RGB -> Grayscale
|
||||
# array = np.dot(array[..., :3], [0.2989, 0.5870, 0.1140])
|
||||
# else:
|
||||
# array = array[:, :, :, 0]
|
||||
array = array[:, :, :, 0]
|
||||
|
||||
array = np.transpose(array)
|
||||
|
||||
bioxels_shape = array.shape
|
||||
bioxels_offset = 0.0
|
||||
|
||||
if self.read_as == "labels":
|
||||
array = array == np.full_like(array, self.label_index)
|
||||
bioxels_default_threshold = 1.0
|
||||
bioxels_max = 1.0
|
||||
bioxels_min = 0.0
|
||||
bioxels_name = f"{bioxels_name}_{self.label_index}"
|
||||
else:
|
||||
if self.invert_scalar:
|
||||
array = -array
|
||||
|
||||
orig_max = float(np.max(array))
|
||||
orig_min = float(np.min(array))
|
||||
orig_median = float(np.median(array))
|
||||
orig_percentile80 = float(np.percentile(array, 80)) \
|
||||
if self.invert_scalar else float(np.percentile(array, 80))
|
||||
|
||||
# if (orig_dtype[0] != "u" and orig_min < 0) \
|
||||
# or (orig_dtype[0] == "u" and self.invert_scalar):
|
||||
if orig_min < 0:
|
||||
bioxels_offset = -orig_min
|
||||
array = array + np.full_like(array, bioxels_offset)
|
||||
|
||||
bioxels_default_threshold = orig_percentile80
|
||||
bioxels_max = float(np.max(array))
|
||||
bioxels_min = float(np.min(array))
|
||||
|
||||
stats_table = [("Max", orig_max),
|
||||
("Min", orig_min),
|
||||
("Median", orig_median),
|
||||
("80%", orig_percentile80)]
|
||||
|
||||
print("Bioxels Value Stats:")
|
||||
for stats in stats_table:
|
||||
print("| {: >10} | {: >40} |".format(*stats))
|
||||
|
||||
# # Build VDB
|
||||
grid = vdb.BoolGrid() if self.read_as == "labels" else vdb.FloatGrid()
|
||||
grid.copyFromArray(array.copy().astype(float))
|
||||
|
||||
# After sitk.DICOMOrient(), origin and direction will also orient base on LPS
|
||||
# so we need to convert them into RAS
|
||||
mat_lps2ras = axis_conversion(
|
||||
@@ -365,139 +330,239 @@ class ImportVolumeDataDialog(bpy.types.Operator):
|
||||
transfrom = mat_lps2ras @ mat_location @ mat_rotation @ mat_scale \
|
||||
if self.do_orient else mat_location @ mat_rotation @ mat_scale
|
||||
|
||||
grid.transform = vdb.createLinearTransform(transfrom.transposed())
|
||||
grid.name = "scalar"
|
||||
# Wrapper a Container
|
||||
if not self.container:
|
||||
# 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
|
||||
)
|
||||
|
||||
bpy.ops.mesh.primitive_cube_add(
|
||||
enter_editmode=False, align='WORLD', location=(0, 0, 0), scale=(1, 1, 1)
|
||||
)
|
||||
container = bpy.context.active_object
|
||||
|
||||
bbox_verts = calc_bbox_verts((0, 0, 0), array.shape)
|
||||
for index, vert in enumerate(container.data.vertices):
|
||||
bbox_transform = transfrom
|
||||
vert.co = bbox_transform @ mathutils.Vector(bbox_verts[index])
|
||||
|
||||
container.matrix_world = mat_ras2blender @ mat_scene_scale
|
||||
container.name = container_name
|
||||
container.data.name = container_name
|
||||
|
||||
container['bioxel_container'] = True
|
||||
container['scene_scale'] = scene_scale
|
||||
bpy.ops.node.new_geometry_nodes_modifier()
|
||||
container_node_tree = container.modifiers[0].node_group
|
||||
input_node = get_node_by_type(container_node_tree.nodes,
|
||||
'NodeGroupInput')[0]
|
||||
container_node_tree.links.remove(input_node.outputs[0].links[0])
|
||||
|
||||
# bpy.ops.mesh.primitive_cube_add(
|
||||
# enter_editmode=False, align='WORLD', location=(0, 0, 0), scale=(1, 1, 1)
|
||||
# )
|
||||
# frame = bpy.context.active_object
|
||||
# bbox_verts = calc_bbox_verts((0, 0, 0), array.shape)
|
||||
# for index, vert in enumerate(frame.data.vertices):
|
||||
# # bbox_transform = mat_ras2blender @ mat_scene_scale @ transfrom
|
||||
# bbox_transform = transfrom
|
||||
# vert.co = bbox_transform @ mathutils.Vector(bbox_verts[index])
|
||||
|
||||
# frame.name = f"Frame_{container_name}"
|
||||
# frame.data.name = f"Frame_{container_name}"
|
||||
# lock_transform(frame)
|
||||
# hide_in_ray(frame)
|
||||
# frame.hide_select = True
|
||||
# frame.hide_render = True
|
||||
# frame.display_type = 'WIRE'
|
||||
# frame.parent = container
|
||||
|
||||
else:
|
||||
container = bpy.data.objects[self.container]
|
||||
container_node_tree = container.modifiers[0].node_group
|
||||
|
||||
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")
|
||||
cache_dir = Path(preferences.cache_dir, 'VDBs')
|
||||
cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
print(f"Storing the VDB file ({str(vdb_path)})...")
|
||||
vdb.write(str(vdb_path), grids=[grid])
|
||||
loc, rot, sca = transfrom.decompose()
|
||||
|
||||
# Read VDB
|
||||
print(f"Importing the VDB file to Blender scene...")
|
||||
bpy.ops.object.volume_import(
|
||||
filepath=str(vdb_path), align='WORLD', location=(0, 0, 0), scale=(1, 1, 1))
|
||||
layer_origin = tuple(loc)
|
||||
layer_rotation = tuple(rot.to_euler())
|
||||
layer_shape = tuple(array.shape)
|
||||
|
||||
bioxels_obj = bpy.context.active_object
|
||||
def create_layer(array, layer_name, layer_type="scalar"):
|
||||
grid = vdb.FloatGrid()
|
||||
array = array.copy().astype(float)
|
||||
grid.copyFromArray(array)
|
||||
grid.transform = vdb.createLinearTransform(transfrom.transposed())
|
||||
grid.name = layer_type
|
||||
|
||||
# Set props to VDB object
|
||||
bioxels_obj.name = f"{bioxels_name}_Bioxels"
|
||||
bioxels_obj.data.name = f"{bioxels_name}_Bioxels"
|
||||
vdb_path = Path(cache_dir, f"{uuid4()}.vdb")
|
||||
print(f"Storing the cache ({str(vdb_path)})...")
|
||||
vdb.write(str(vdb_path), grids=[grid])
|
||||
|
||||
# Make transformation
|
||||
scene_scale = float(self.scene_scale)
|
||||
# Read VDB
|
||||
print(f"Loading the cache to Blender scene...")
|
||||
bpy.ops.object.volume_import(
|
||||
filepath=str(vdb_path), align='WORLD', location=(0, 0, 0), scale=(1, 1, 1))
|
||||
|
||||
# (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()
|
||||
layer = bpy.context.active_object
|
||||
|
||||
mat_scene_scale = mathutils.Matrix.Scale(
|
||||
scene_scale, 4
|
||||
)
|
||||
# Set props to VDB object
|
||||
layer.name = layer_name
|
||||
layer.data.name = layer_name
|
||||
|
||||
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
|
||||
lock_transform(layer)
|
||||
hide_in_ray(layer)
|
||||
layer.hide_select = True
|
||||
layer.hide_render = True
|
||||
layer.hide_viewport = True
|
||||
layer.data.display.use_slice = True
|
||||
layer.data.display.density = 1e-05
|
||||
|
||||
bpy.ops.node.new_geometry_nodes_modifier()
|
||||
node_tree = bioxels_obj.modifiers[0].node_group
|
||||
layer['bioxel_layer'] = True
|
||||
layer['bioxel_layer_type'] = layer_type
|
||||
layer.parent = container
|
||||
|
||||
# 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):
|
||||
bbox_transform = mat_ras2blender @ mat_scene_scale @ transfrom
|
||||
vert.co = bbox_transform @ mathutils.Vector(bbox_verts[index])
|
||||
for collection in layer.users_collection:
|
||||
collection.objects.unlink(layer)
|
||||
|
||||
bioxels_obj.parent = container_obj
|
||||
container_obj.name = bioxels_name
|
||||
container_obj.data.name = bioxels_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
|
||||
for collection in container.users_collection:
|
||||
collection.objects.link(layer)
|
||||
|
||||
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
|
||||
print(f"Creating layer ...")
|
||||
|
||||
# Create BioxelNodes to VDB object
|
||||
print(f"Creating BioxelNodes to the VDB...")
|
||||
|
||||
if preferences.do_add_segmentnode:
|
||||
bpy.ops.node.new_geometry_nodes_modifier()
|
||||
node_tree = layer.modifiers[0].node_group
|
||||
nodes = node_tree.nodes
|
||||
links = node_tree.links
|
||||
|
||||
input_node = get_node_by_type(nodes, 'NodeGroupInput')[0]
|
||||
output_node = get_node_by_type(nodes, 'NodeGroupOutput')[0]
|
||||
|
||||
segment_node = custom_nodes.add_node(
|
||||
nodes, 'BioxelNodes_Segment')
|
||||
to_layer_node = custom_nodes.add_node(nodes,
|
||||
"BioxelNodes__ConvertToLayer")
|
||||
|
||||
segment_node.inputs['Threshold'].default_value = bioxels_default_threshold
|
||||
links.new(input_node.outputs[0], to_layer_node.inputs[0])
|
||||
links.new(to_layer_node.outputs[0], output_node.inputs[0])
|
||||
|
||||
links.new(input_node.outputs[0], segment_node.inputs[0])
|
||||
links.new(segment_node.outputs[0], output_node.inputs[0])
|
||||
to_layer_node.inputs['Layer ID'].default_value = random.randint(-200000000,
|
||||
200000000)
|
||||
to_layer_node.inputs['Bioxel Size'].default_value = bioxel_size
|
||||
to_layer_node.inputs['Shape'].default_value = layer_shape
|
||||
to_layer_node.inputs['Origin'].default_value = layer_origin
|
||||
to_layer_node.inputs['Rotation'].default_value = layer_rotation
|
||||
|
||||
return layer
|
||||
|
||||
if self.read_as == "labels":
|
||||
orig_max = int(np.max(array))
|
||||
orig_min = int(np.min(array))
|
||||
layer_name = self.layer_name or "Label"
|
||||
|
||||
for i in range(orig_max):
|
||||
label = array == np.full_like(array, i+1)
|
||||
layer = create_layer(array=label,
|
||||
layer_name=f"{container_name}_{layer_name}_{i+1}",
|
||||
layer_type="label")
|
||||
|
||||
output_node = get_node_by_type(container_node_tree.nodes,
|
||||
'NodeGroupOutput')[0]
|
||||
mask_node = custom_nodes.add_node(container_node_tree.nodes,
|
||||
'BioxelNodes_MaskByLabel')
|
||||
mask_node.inputs[0].default_value = layer
|
||||
if len(output_node.inputs[0].links) == 0:
|
||||
container_node_tree.links.new(mask_node.outputs[0],
|
||||
output_node.inputs[0])
|
||||
|
||||
else:
|
||||
if self.invert_scalar:
|
||||
array = -array
|
||||
|
||||
orig_max = float(np.max(array))
|
||||
orig_min = float(np.min(array))
|
||||
orig_median = float(np.median(array))
|
||||
orig_percentile80 = float(np.percentile(array, 80)) \
|
||||
if self.invert_scalar else float(np.percentile(array, 80))
|
||||
|
||||
stats_table = [("Max", orig_max),
|
||||
("Min", orig_min),
|
||||
("Median", orig_median),
|
||||
("80%", orig_percentile80)]
|
||||
|
||||
print("Volume Data Stats:")
|
||||
for stats in stats_table:
|
||||
print("| {: >10} | {: >40} |".format(*stats))
|
||||
|
||||
scalar_offset = 0
|
||||
if orig_min < 0:
|
||||
scalar_offset = -orig_min
|
||||
array = array + np.full_like(array, scalar_offset)
|
||||
|
||||
layer_name = self.layer_name or "Scalar"
|
||||
layer = create_layer(array=array,
|
||||
layer_name=f"{container_name}_{layer_name}",
|
||||
layer_type="scalar")
|
||||
|
||||
layer_node_tree = layer.modifiers[0].node_group
|
||||
to_layer_node = layer_node_tree.nodes['BioxelNodes__ConvertToLayer']
|
||||
to_layer_node.inputs['Scalar Offset'].default_value = scalar_offset
|
||||
to_layer_node.inputs['Scalar Max'].default_value = orig_max
|
||||
to_layer_node.inputs['Scalar Min'].default_value = orig_min
|
||||
|
||||
output_node = get_node_by_type(container_node_tree.nodes,
|
||||
'NodeGroupOutput')[0]
|
||||
mask_node = custom_nodes.add_node(container_node_tree.nodes,
|
||||
'BioxelNodes_MaskByThreshold')
|
||||
mask_node.inputs[0].default_value = layer
|
||||
|
||||
if len(output_node.inputs[0].links) == 0:
|
||||
container_node_tree.links.new(mask_node.outputs[0],
|
||||
output_node.inputs[0])
|
||||
|
||||
bpy.context.view_layer.objects.active = container
|
||||
|
||||
# Change render setting for better result
|
||||
if preferences.do_change_render_setting:
|
||||
if preferences.do_change_render_setting and is_first_import:
|
||||
bpy.context.scene.render.engine = 'CYCLES'
|
||||
bpy.context.scene.cycles.volume_bounces = 12
|
||||
bpy.context.scene.cycles.transparent_max_bounces = 64
|
||||
bpy.context.scene.cycles.transparent_max_bounces = 16
|
||||
bpy.context.scene.cycles.volume_preview_step_rate = 10
|
||||
|
||||
self.report({"INFO"}, "Successfully Imported")
|
||||
|
||||
return {'FINISHED'}
|
||||
|
||||
def invoke(self, context, event):
|
||||
min_size = min(
|
||||
self.orig_spacing[0], self.orig_spacing[1], self.orig_spacing[2])
|
||||
default_size = 1.0
|
||||
self.bioxel_size = min_size if min_size > default_size else default_size
|
||||
context.window_manager.invoke_props_dialog(self, width=400)
|
||||
context.window_manager.invoke_props_dialog(self, width=500)
|
||||
return {'RUNNING_MODAL'}
|
||||
|
||||
def draw(self, context):
|
||||
layout = self.layout
|
||||
bioxels_shape = get_bioxels_shape(
|
||||
layer_shape = get_layer_shape(
|
||||
self.bioxel_size, self.orig_shape, self.orig_spacing)
|
||||
bioxel_count = bioxels_shape[0] * bioxels_shape[1] * bioxels_shape[2]
|
||||
text = f"Shape will be: {str(bioxels_shape)} {bioxel_count:,} "
|
||||
bioxel_count = layer_shape[0] * layer_shape[1] * layer_shape[2]
|
||||
text = f"Shape will be: {str(layer_shape)} {bioxel_count:,} "
|
||||
if bioxel_count > 100000000:
|
||||
text += "**TOO LARGE!**"
|
||||
|
||||
layout = self.layout
|
||||
panel = layout.box()
|
||||
panel.prop(self, "container_name")
|
||||
panel.prop(self, "layer_name")
|
||||
|
||||
panel = layout.box()
|
||||
panel.prop(self, "resample_method")
|
||||
panel.prop(self, "bioxel_size")
|
||||
@@ -505,16 +570,18 @@ class ImportVolumeDataDialog(bpy.types.Operator):
|
||||
row.prop(self, "orig_spacing")
|
||||
panel.label(text=text)
|
||||
|
||||
panel = layout.box()
|
||||
panel.prop(self, "do_orient")
|
||||
|
||||
panel = layout.box()
|
||||
panel.prop(self, "read_as")
|
||||
if self.read_as == "labels":
|
||||
panel.prop(self, "label_index")
|
||||
...
|
||||
else:
|
||||
panel.prop(self, "invert_scalar")
|
||||
|
||||
panel = layout.box()
|
||||
panel.prop(self, "scene_scale")
|
||||
panel.prop(self, "do_orient")
|
||||
|
||||
|
||||
def get_series_ids(self, context):
|
||||
@@ -530,14 +597,15 @@ def get_series_ids(self, context):
|
||||
return items
|
||||
|
||||
|
||||
class ReadDICOM(bpy.types.Operator):
|
||||
bl_idname = "bioxelnodes.read_dicom"
|
||||
bl_label = "Volume Data as Bioxels"
|
||||
bl_description = "Import Volume Data as Bioxels (VDB)"
|
||||
class ParseVolumeData(bpy.types.Operator):
|
||||
bl_idname = "bioxelnodes.parse_volume_data"
|
||||
bl_label = "Volume Data as Bioxel Layer"
|
||||
bl_description = "Import Volume Data as Bioxel Layer"
|
||||
bl_options = {'UNDO'}
|
||||
|
||||
filepath: bpy.props.StringProperty(subtype="FILE_PATH") # type: ignore
|
||||
directory: bpy.props.StringProperty(subtype='DIR_PATH') # type: ignore
|
||||
container: bpy.props.StringProperty() # type: ignore
|
||||
|
||||
series_id: bpy.props.EnumProperty(
|
||||
name="Select Series",
|
||||
@@ -555,25 +623,41 @@ class ReadDICOM(bpy.types.Operator):
|
||||
|
||||
print("Collecting Meta Data...")
|
||||
image, name = read_image(self.filepath, self.series_id)
|
||||
|
||||
stats_table = [("Shape", str(image.GetSize())),
|
||||
("Spacing", str(image.GetSpacing())),
|
||||
("Origin", str(image.GetOrigin())),
|
||||
("Direction", str(image.GetDirection())),
|
||||
("Data Type", image.GetPixelIDTypeAsString())]
|
||||
for k in image.GetMetaDataKeys():
|
||||
stats_table.append((k, str(image.GetMetaData(k))))
|
||||
|
||||
print("Meta Data:")
|
||||
for stats in stats_table:
|
||||
print("| {: >10} | {: >40} |".format(*stats))
|
||||
print("| {: >20} | {: >100} |".format(*stats))
|
||||
|
||||
do_orient = ext not in SEQUENCE_EXTS or ext in DICOM_EXTS
|
||||
|
||||
orig_shape = image.GetSize()
|
||||
orig_spacing = image.GetSpacing()
|
||||
min_size = min(orig_spacing[0], orig_spacing[1], orig_spacing[2])
|
||||
bioxel_size = max(min_size, 1.0)
|
||||
if self.container:
|
||||
container = bpy.data.objects[self.container]
|
||||
container_name = container.name
|
||||
else:
|
||||
container_name = name
|
||||
|
||||
bpy.ops.bioxelnodes.import_volume_data_dialog(
|
||||
'INVOKE_DEFAULT',
|
||||
filepath=self.filepath,
|
||||
orig_shape=image.GetSize(),
|
||||
orig_spacing=image.GetSpacing(),
|
||||
container_name=container_name,
|
||||
orig_shape=orig_shape,
|
||||
orig_spacing=orig_spacing,
|
||||
bioxel_size=bioxel_size,
|
||||
series_id=self.series_id or "",
|
||||
do_orient=do_orient
|
||||
do_orient=do_orient,
|
||||
container=self.container
|
||||
)
|
||||
|
||||
self.report({"INFO"}, "Successfully Readed.")
|
||||
@@ -623,15 +707,15 @@ class ReadDICOM(bpy.types.Operator):
|
||||
|
||||
class ImportVolumeData(bpy.types.Operator):
|
||||
bl_idname = "bioxelnodes.import_volume_data"
|
||||
bl_label = "Volume Data as Bioxels"
|
||||
bl_description = "Import Volume Data as Bioxels (VDB)"
|
||||
bl_label = "Volume Data as Bioxel Layer"
|
||||
bl_description = "Import Volume Data as Bioxel Layer"
|
||||
bl_options = {'UNDO'}
|
||||
|
||||
filepath: bpy.props.StringProperty(subtype="FILE_PATH") # type: ignore
|
||||
directory: bpy.props.StringProperty(subtype='DIR_PATH') # type: ignore
|
||||
|
||||
def execute(self, context):
|
||||
bpy.ops.bioxelnodes.read_dicom(
|
||||
bpy.ops.bioxelnodes.parse_volume_data(
|
||||
'INVOKE_DEFAULT',
|
||||
filepath=self.filepath,
|
||||
directory=self.directory
|
||||
@@ -647,7 +731,7 @@ try:
|
||||
class BIOXELNODES_FH_ImportVolumeData(bpy.types.FileHandler):
|
||||
bl_idname = "BIOXELNODES_FH_ImportVolumeData"
|
||||
bl_label = "File handler for dicom import"
|
||||
bl_import_operator = "bioxelnodes.read_dicom"
|
||||
bl_import_operator = "bioxelnodes.parse_volume_data"
|
||||
bl_file_extensions = ";".join(FH_EXTS)
|
||||
|
||||
@classmethod
|
||||
@@ -657,10 +741,40 @@ except:
|
||||
...
|
||||
|
||||
|
||||
class AddVolumeData(bpy.types.Operator):
|
||||
bl_idname = "bioxelnodes.add_volume_data"
|
||||
bl_label = "Add Volume Data to Container"
|
||||
bl_description = "Add Volume Data to Container"
|
||||
bl_options = {'UNDO'}
|
||||
|
||||
filepath: bpy.props.StringProperty(subtype="FILE_PATH") # type: ignore
|
||||
directory: bpy.props.StringProperty(subtype='DIR_PATH') # type: ignore
|
||||
|
||||
@classmethod
|
||||
def poll(cls, context):
|
||||
container = get_container(bpy.context.active_object)
|
||||
return True if container else False
|
||||
|
||||
def execute(self, context):
|
||||
container = get_container(bpy.context.active_object)
|
||||
|
||||
bpy.ops.bioxelnodes.parse_volume_data(
|
||||
'INVOKE_DEFAULT',
|
||||
filepath=self.filepath,
|
||||
directory=self.directory,
|
||||
container=container.name
|
||||
)
|
||||
return {'FINISHED'}
|
||||
|
||||
def invoke(self, context, event):
|
||||
context.window_manager.fileselect_add(self)
|
||||
return {'RUNNING_MODAL'}
|
||||
|
||||
|
||||
class ExportVDB(bpy.types.Operator):
|
||||
bl_idname = "bioxelnodes.export_vdb"
|
||||
bl_label = "Bioxels as VDB"
|
||||
bl_description = "Export Bioxels original VDB data"
|
||||
bl_label = "Bioxel Layer as VDB"
|
||||
bl_description = "Export Bioxel Layer as VDB"
|
||||
bl_options = {'UNDO'}
|
||||
|
||||
filepath: bpy.props.StringProperty(
|
||||
@@ -671,26 +785,19 @@ class ExportVDB(bpy.types.Operator):
|
||||
|
||||
@classmethod
|
||||
def poll(cls, context):
|
||||
bioxels_obj = None
|
||||
for obj in bpy.context.selected_objects:
|
||||
bioxels_obj = get_bioxels_obj(obj)
|
||||
break
|
||||
|
||||
return True if bioxels_obj else False
|
||||
layer = get_layer(bpy.context.active_object)
|
||||
return True if layer else False
|
||||
|
||||
def invoke(self, context, event):
|
||||
context.window_manager.fileselect_add(self)
|
||||
return {'RUNNING_MODAL'}
|
||||
|
||||
def execute(self, context):
|
||||
bioxels_obj = None
|
||||
for obj in bpy.context.selected_objects:
|
||||
bioxels_obj = get_bioxels_obj(obj)
|
||||
break
|
||||
layer = get_layer(bpy.context.active_object)
|
||||
|
||||
filepath = f"{self.filepath.split('.')[0]}.vdb"
|
||||
# "//"
|
||||
source_dir = bpy.path.abspath(bioxels_obj.data.filepath)
|
||||
source_dir = bpy.path.abspath(layer.data.filepath)
|
||||
|
||||
output_path: Path = Path(filepath).resolve()
|
||||
source_path: Path = Path(source_dir).resolve()
|
||||
|
||||
@@ -22,200 +22,4 @@ def create_points_obj(points, name="points"):
|
||||
# make the bmesh the object's mesh
|
||||
bm.to_mesh(mesh)
|
||||
bm.free() # always do this when finished
|
||||
return obj
|
||||
|
||||
|
||||
# class ImportDICOMPointsDialog(bpy.types.Operator):
|
||||
# bl_idname = "bioxelnodes.import_dicom_points_dialog"
|
||||
# bl_label = "Volume Data as Bioxels"
|
||||
# bl_description = "Import Volume Data as Bioxels (VDB)"
|
||||
# bl_options = {'UNDO'}
|
||||
|
||||
# filepath: bpy.props.StringProperty(
|
||||
# subtype="FILE_PATH",
|
||||
# options={'HIDDEN'}
|
||||
# ) # type: ignore
|
||||
|
||||
# bioxels_shape: bpy.props.IntVectorProperty(
|
||||
# name="Bioxels Shape (ReadOnly)",
|
||||
# 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):
|
||||
# files = get_data_files(self.filepath)
|
||||
# name = Path(self.filepath).parent.name
|
||||
|
||||
# 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("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(),
|
||||
# )
|
||||
|
||||
# print("Orienting to RAS...")
|
||||
# image = sitk.DICOMOrient(image, 'RAS')
|
||||
|
||||
# array = sitk.GetArrayFromImage(image)
|
||||
# orig_dtype = str(array.dtype)
|
||||
# print(f"Coverting Dtype from {orig_dtype} to 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_shape = array.shape
|
||||
|
||||
# print("Bioxel Size:", bioxel_size)
|
||||
# print("Bioxels Shape:", bioxels_shape)
|
||||
|
||||
# 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)
|
||||
|
||||
# points = []
|
||||
# for x in range(array.shape[0]):
|
||||
# for y in range(array.shape[1]):
|
||||
# for z in range(array.shape[2]):
|
||||
# points.append({
|
||||
# "pos": (x, y, z),
|
||||
# "value": array[x, y, z],
|
||||
# })
|
||||
|
||||
# # # 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
|
||||
|
||||
# obj = create_points_obj(points)
|
||||
|
||||
# # 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
|
||||
# )
|
||||
|
||||
# obj.matrix_world = mat_ras2blender @ mat_scene_scale
|
||||
|
||||
# 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'}
|
||||
return obj
|
||||
@@ -1,18 +1,32 @@
|
||||
import bpy
|
||||
from .convert import ConvertToMesh
|
||||
from .io import ExportVDB, ImportVolumeData
|
||||
from .misc import SaveBioxels
|
||||
from .operators import ConvertToMesh, JoinLayers
|
||||
from .io import ExportVDB, ImportVolumeData, AddVolumeData
|
||||
from .misc import SaveBioxelLayers
|
||||
|
||||
|
||||
class ObjectMenu(bpy.types.Menu):
|
||||
bl_idname = "BIOXELNODES_MT_OBJECT"
|
||||
bl_label = "Bioxels"
|
||||
class View3DBioxelsMenu(bpy.types.Menu):
|
||||
bl_idname = "BIOXELNODES_MT_VIEW3D"
|
||||
bl_label = "Bioxel Nodes"
|
||||
|
||||
def draw(self, context):
|
||||
layout = self.layout
|
||||
layout.operator(ConvertToMesh.bl_idname)
|
||||
layout.operator(AddVolumeData.bl_idname)
|
||||
layout.separator()
|
||||
layout.operator(SaveBioxels.bl_idname)
|
||||
layout.operator(SaveBioxelLayers.bl_idname)
|
||||
|
||||
|
||||
class OutlinerBioxelsMenu(bpy.types.Menu):
|
||||
bl_idname = "BIOXELNODES_MT_OUTLINER"
|
||||
bl_label = "Bioxel Nodes"
|
||||
|
||||
def draw(self, context):
|
||||
layout = self.layout
|
||||
layout.operator(JoinLayers.bl_idname)
|
||||
layout.operator(ConvertToMesh.bl_idname)
|
||||
layout.operator(AddVolumeData.bl_idname)
|
||||
layout.separator()
|
||||
layout.operator(SaveBioxelLayers.bl_idname)
|
||||
|
||||
|
||||
def TOPBAR_FILE_IMPORT(self, context):
|
||||
@@ -29,17 +43,25 @@ def TOPBAR_FILE_EXPORT(self, context):
|
||||
|
||||
def VIEW3D_OBJECT(self, context):
|
||||
layout = self.layout
|
||||
layout.menu(ObjectMenu.bl_idname)
|
||||
layout.menu(View3DBioxelsMenu.bl_idname)
|
||||
layout.separator()
|
||||
|
||||
|
||||
def OUTLINER_OBJECT(self, context):
|
||||
layout = self.layout
|
||||
layout.menu(OutlinerBioxelsMenu.bl_idname)
|
||||
layout.separator()
|
||||
|
||||
|
||||
def add():
|
||||
bpy.types.TOPBAR_MT_file_import.append(TOPBAR_FILE_IMPORT)
|
||||
bpy.types.TOPBAR_MT_file_export.append(TOPBAR_FILE_EXPORT)
|
||||
bpy.types.OUTLINER_MT_object.prepend(OUTLINER_OBJECT)
|
||||
bpy.types.VIEW3D_MT_object_context_menu.prepend(VIEW3D_OBJECT)
|
||||
|
||||
|
||||
def remove():
|
||||
bpy.types.TOPBAR_MT_file_import.remove(TOPBAR_FILE_IMPORT)
|
||||
bpy.types.TOPBAR_MT_file_export.remove(TOPBAR_FILE_EXPORT)
|
||||
bpy.types.OUTLINER_MT_object.remove(OUTLINER_OBJECT)
|
||||
bpy.types.VIEW3D_MT_object_context_menu.remove(VIEW3D_OBJECT)
|
||||
|
||||
@@ -1,97 +1,86 @@
|
||||
import bpy
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
from bioxelnodes.utils import get_all_bioxels_objs, get_bioxels_obj
|
||||
from .utils import get_all_layers, get_container, get_container_layers
|
||||
|
||||
|
||||
class SaveBioxels(bpy.types.Operator):
|
||||
bl_idname = "bioxelnodes.save_bioxels"
|
||||
bl_label = "Save Bioxels"
|
||||
bl_description = "Save Bioxels to Directory."
|
||||
def save_layer(layer, output_dir):
|
||||
name = layer.name
|
||||
|
||||
# "//"
|
||||
output_dir = bpy.path.abspath(output_dir)
|
||||
source_dir = bpy.path.abspath(layer.data.filepath)
|
||||
|
||||
output_path: Path = Path(output_dir, f"{name}.vdb").resolve()
|
||||
source_path: Path = Path(source_dir).resolve()
|
||||
|
||||
if output_path != source_path:
|
||||
shutil.copy(source_path, output_path)
|
||||
|
||||
blend_path = Path(bpy.path.abspath("//")).resolve()
|
||||
layer.data.filepath = bpy.path.relpath(
|
||||
str(output_path), start=str(blend_path))
|
||||
|
||||
|
||||
class SaveBioxelLayers(bpy.types.Operator):
|
||||
bl_idname = "bioxelnodes.save_bioxel_layers"
|
||||
bl_label = "Save Bioxel Layers"
|
||||
bl_description = "Save Bioxel Layers to Directory."
|
||||
bl_options = {'UNDO'}
|
||||
|
||||
@classmethod
|
||||
def poll(cls, context):
|
||||
bioxels_obj = None
|
||||
for obj in bpy.context.selected_objects:
|
||||
bioxels_obj = get_bioxels_obj(obj)
|
||||
break
|
||||
|
||||
return True if bioxels_obj else False
|
||||
container = get_container(bpy.context.active_object)
|
||||
return True if container else False
|
||||
|
||||
def execute(self, context):
|
||||
bioxels_objs = []
|
||||
container = get_container(bpy.context.active_object)
|
||||
|
||||
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.")
|
||||
if not container:
|
||||
self.report({"WARNING"}, "Cannot find any bioxel container.")
|
||||
return {'FINISHED'}
|
||||
|
||||
for bioxels_obj in bioxels_objs:
|
||||
name = bioxels_obj.parent.name
|
||||
for layer in get_container_layers(container):
|
||||
try:
|
||||
save_layer(layer, context.scene.bioxel_layer_dir)
|
||||
except:
|
||||
self.report(
|
||||
{"WARNING"}, f"Fail to save {layer.name}, skiped")
|
||||
|
||||
# "//"
|
||||
bioxels_dir = bpy.path.abspath(context.scene.bioxels_dir)
|
||||
source_dir = bpy.path.abspath(bioxels_obj.data.filepath)
|
||||
|
||||
output_path: Path = Path(bioxels_dir, f"{name}.vdb").resolve()
|
||||
source_path: Path = Path(source_dir).resolve()
|
||||
|
||||
if output_path != source_path:
|
||||
shutil.copy(source_path, output_path)
|
||||
|
||||
blend_path = Path(bpy.path.abspath("//")).resolve()
|
||||
bioxels_obj.data.filepath = bpy.path.relpath(
|
||||
str(output_path), start=str(blend_path))
|
||||
|
||||
self.report({"INFO"}, f"Successfully saved bioxels")
|
||||
self.report({"INFO"}, f"Successfully saved bioxel layers.")
|
||||
|
||||
return {'FINISHED'}
|
||||
|
||||
|
||||
class SaveAllBioxels(bpy.types.Operator):
|
||||
bl_idname = "bioxelnodes.save_all_bioxels"
|
||||
bl_label = "Save All Bioxels"
|
||||
bl_description = "Save All Bioxels to Directory."
|
||||
class SaveAllBioxelLayers(bpy.types.Operator):
|
||||
bl_idname = "bioxelnodes.save_all_bioxel_layers"
|
||||
bl_label = "Save All Bioxel Layers"
|
||||
bl_description = "Save All Bioxel Layers to Directory."
|
||||
bl_options = {'UNDO'}
|
||||
|
||||
def execute(self, context):
|
||||
|
||||
bioxels_objs = get_all_bioxels_objs()
|
||||
layers = get_all_layers()
|
||||
|
||||
if len(bioxels_objs) == 0:
|
||||
self.report({"WARNING"}, "Cannot find any bioxels.")
|
||||
if len(layers) == 0:
|
||||
self.report({"WARNING"}, "Cannot find any bioxel layer.")
|
||||
return {'FINISHED'}
|
||||
|
||||
for bioxels_obj in bioxels_objs:
|
||||
name = bioxels_obj.parent.name
|
||||
for layer in layers:
|
||||
try:
|
||||
save_layer(layer, context.scene.bioxel_layer_dir)
|
||||
except:
|
||||
self.report(
|
||||
{"WARNING"}, f"Fail to save {layer.name}, skiped")
|
||||
|
||||
# "//"
|
||||
bioxels_dir = bpy.path.abspath(context.scene.bioxels_dir)
|
||||
source_dir = bpy.path.abspath(bioxels_obj.data.filepath)
|
||||
|
||||
output_path: Path = Path(bioxels_dir, f"{name}.vdb").resolve()
|
||||
source_path: Path = Path(source_dir).resolve()
|
||||
|
||||
if output_path != source_path:
|
||||
shutil.copy(source_path, output_path)
|
||||
|
||||
blend_path = Path(bpy.path.abspath("//")).resolve()
|
||||
bioxels_obj.data.filepath = bpy.path.relpath(
|
||||
str(output_path), start=str(blend_path))
|
||||
|
||||
self.report({"INFO"}, f"Successfully saved bioxels")
|
||||
self.report({"INFO"}, f"Successfully saved bioxel layers.")
|
||||
|
||||
return {'FINISHED'}
|
||||
|
||||
|
||||
class BIOXELNODES_PT_Bioxels(bpy.types.Panel):
|
||||
bl_idname = "BIOXELNODES_PT_Bioxels"
|
||||
bl_label = "Bioxels"
|
||||
bl_label = "Bioxel Nodes"
|
||||
bl_space_type = "PROPERTIES"
|
||||
bl_region_type = "WINDOW"
|
||||
bl_context = "scene"
|
||||
@@ -99,5 +88,5 @@ class BIOXELNODES_PT_Bioxels(bpy.types.Panel):
|
||||
def draw(self, context):
|
||||
layout = self.layout
|
||||
scene = context.scene
|
||||
layout.prop(scene, 'bioxels_dir')
|
||||
layout.operator(SaveAllBioxels.bl_idname)
|
||||
layout.prop(scene, 'bioxel_layer_dir')
|
||||
layout.operator(SaveAllBioxelLayers.bl_idname)
|
||||
|
||||
@@ -7,7 +7,7 @@ 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
|
||||
from .utils import add_direct_driver, get_bioxels_obj
|
||||
bioxels_obj = get_bioxels_obj(bpy.context.active_object)
|
||||
if bioxels_obj:
|
||||
container_obj = bioxels_obj.parent
|
||||
@@ -26,7 +26,7 @@ else:
|
||||
def set_prop_to_node_factory(source_prop, target_prop):
|
||||
callback_str = f"""
|
||||
import bpy
|
||||
from bioxelnodes.utils import get_bioxels_obj
|
||||
from .utils import get_bioxels_obj
|
||||
bioxels_obj = get_bioxels_obj(bpy.context.active_object)
|
||||
if bioxels_obj:
|
||||
container_obj = bioxels_obj.parent
|
||||
@@ -38,112 +38,265 @@ else:
|
||||
return callback_str
|
||||
|
||||
|
||||
MENU_ITEMS = [
|
||||
{
|
||||
'label': 'Presets',
|
||||
'icon': 'MESH_MONKEY',
|
||||
'items': [
|
||||
{
|
||||
'label': 'Segment',
|
||||
'icon': 'BONE_DATA',
|
||||
'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': 'CONSTRAINT_BONE',
|
||||
# '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': 'EMPTY_SINGLE_ARROW',
|
||||
'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': 'IPO_CONSTANT',
|
||||
'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': 'ALIGN_JUSTIFY',
|
||||
# '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': ''
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
NODE_FILE = "BioxelNodes_4.0"
|
||||
|
||||
if bpy.app.version >= (4, 1, 0):
|
||||
MENU_ITEMS.append({
|
||||
'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': '',
|
||||
}
|
||||
]
|
||||
})
|
||||
NODE_FILE = "BioxelNodes_4.1"
|
||||
|
||||
MENU_ITEMS = [
|
||||
{
|
||||
'label': 'Methods',
|
||||
'icon': 'OUTLINER_DATA_VOLUME',
|
||||
'items': [
|
||||
{
|
||||
'label': 'Mask by Threshold',
|
||||
'icon': 'EMPTY_SINGLE_ARROW',
|
||||
'node_type': 'BioxelNodes_MaskByThreshold',
|
||||
'node_description': ''
|
||||
},
|
||||
{
|
||||
'label': 'Mask by Range',
|
||||
'icon': 'IPO_CONSTANT',
|
||||
'node_type': 'BioxelNodes_MaskByRange',
|
||||
'node_description': ''
|
||||
},
|
||||
{
|
||||
'label': 'Mask by Label',
|
||||
'icon': 'MESH_CAPSULE',
|
||||
'node_type': 'BioxelNodes_MaskByLabel',
|
||||
'node_description': ''
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
'label': 'Shaders',
|
||||
'icon': 'SHADING_RENDERED',
|
||||
'items': [
|
||||
{
|
||||
'label': 'Solid Shader',
|
||||
'icon': 'SHADING_SOLID',
|
||||
'node_type': 'BioxelNodes_AssignSolidShader',
|
||||
'node_description': ''
|
||||
},
|
||||
{
|
||||
'label': 'Slime Shader',
|
||||
'icon': 'OUTLINER_OB_META',
|
||||
'node_type': 'BioxelNodes_AssignSlimeShader',
|
||||
'node_description': ''
|
||||
},
|
||||
{
|
||||
'label': 'Volume Shader',
|
||||
'icon': 'OUTLINER_OB_VOLUME',
|
||||
'node_type': 'BioxelNodes_AssignVolumeShader',
|
||||
'node_description': ''
|
||||
},
|
||||
{
|
||||
'label': 'Universal Shader',
|
||||
'icon': 'SHADING_RENDERED',
|
||||
'node_type': 'BioxelNodes_AssignUniversalShader',
|
||||
'node_description': ''
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
'label': 'Colors',
|
||||
'icon': 'COLOR',
|
||||
'items': [
|
||||
{
|
||||
'label': 'Color Presets',
|
||||
'icon': 'COLOR',
|
||||
'node_type': 'BioxelNodes_SetColorPresets',
|
||||
'node_description': ''
|
||||
},
|
||||
{
|
||||
'label': 'Color Ramp 2',
|
||||
'icon': 'IPO_QUAD',
|
||||
'node_type': 'BioxelNodes_SetColorRamp2',
|
||||
'node_description': ''
|
||||
},
|
||||
{
|
||||
'label': 'Color Ramp 3',
|
||||
'icon': 'IPO_CUBIC',
|
||||
'node_type': 'BioxelNodes_SetColorRamp3',
|
||||
'node_description': ''
|
||||
},
|
||||
{
|
||||
'label': 'Color Ramp 4',
|
||||
'icon': 'IPO_QUART',
|
||||
'node_type': 'BioxelNodes_SetColorRamp4',
|
||||
'node_description': ''
|
||||
},
|
||||
{
|
||||
'label': 'Color Ramp 5',
|
||||
'icon': 'IPO_QUINT',
|
||||
'node_type': 'BioxelNodes_SetColorRamp5',
|
||||
'node_description': ''
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
'label': 'Cutters',
|
||||
'icon': 'MOD_BEVEL',
|
||||
'items': [
|
||||
{
|
||||
'label': 'Cut',
|
||||
'icon': 'MOD_BEVEL',
|
||||
'node_type': 'BioxelNodes_Cut',
|
||||
'node_description': ''
|
||||
},
|
||||
"separator",
|
||||
{
|
||||
'label': 'Plane Cutter',
|
||||
'icon': 'MOD_LATTICE',
|
||||
'node_type': 'BioxelNodes_PlaneCutter',
|
||||
'node_description': '',
|
||||
},
|
||||
{
|
||||
'label': 'Plane Object Cutter',
|
||||
'icon': 'OUTLINER_OB_LATTICE',
|
||||
'node_type': 'BioxelNodes_PlaneObjectCutter',
|
||||
'node_description': '',
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
'label': 'Utils',
|
||||
'icon': 'MODIFIER',
|
||||
'items': [
|
||||
{
|
||||
'label': 'Join Component',
|
||||
'icon': 'CONSTRAINT_BONE',
|
||||
'node_type': 'BioxelNodes_JoinComponent',
|
||||
'node_description': ''
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
else:
|
||||
NODE_FILE = "BioxelNodes_4.0"
|
||||
MENU_ITEMS = [
|
||||
{
|
||||
'label': 'Methods',
|
||||
'icon': 'OUTLINER_DATA_VOLUME',
|
||||
'items': [
|
||||
{
|
||||
'label': 'Mask by Threshold',
|
||||
'icon': 'EMPTY_SINGLE_ARROW',
|
||||
'node_type': 'BioxelNodes_MaskByThreshold',
|
||||
'node_description': ''
|
||||
},
|
||||
{
|
||||
'label': 'Mask by Range',
|
||||
'icon': 'IPO_CONSTANT',
|
||||
'node_type': 'BioxelNodes_MaskByRange',
|
||||
'node_description': ''
|
||||
},
|
||||
{
|
||||
'label': 'Mask by Label',
|
||||
'icon': 'MESH_CAPSULE',
|
||||
'node_type': 'BioxelNodes_MaskByLabel',
|
||||
'node_description': ''
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
'label': 'Shaders',
|
||||
'icon': 'SHADING_RENDERED',
|
||||
'items': [
|
||||
{
|
||||
'label': 'Solid Shader',
|
||||
'icon': 'SHADING_SOLID',
|
||||
'node_type': 'BioxelNodes_AssignSolidShader',
|
||||
'node_description': ''
|
||||
},
|
||||
{
|
||||
'label': 'Slime Shader',
|
||||
'icon': 'OUTLINER_OB_META',
|
||||
'node_type': 'BioxelNodes_AssignSlimeShader',
|
||||
'node_description': ''
|
||||
},
|
||||
{
|
||||
'label': 'Volume Shader',
|
||||
'icon': 'OUTLINER_OB_VOLUME',
|
||||
'node_type': 'BioxelNodes_AssignVolumeShader',
|
||||
'node_description': ''
|
||||
},
|
||||
{
|
||||
'label': 'Universal Shader',
|
||||
'icon': 'SHADING_RENDERED',
|
||||
'node_type': 'BioxelNodes_AssignUniversalShader',
|
||||
'node_description': ''
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
'label': 'Colors',
|
||||
'icon': 'COLOR',
|
||||
'items': [
|
||||
{
|
||||
'label': 'Color Ramp 2',
|
||||
'icon': 'IPO_QUAD',
|
||||
'node_type': 'BioxelNodes_SetColorRamp2',
|
||||
'node_description': ''
|
||||
},
|
||||
{
|
||||
'label': 'Color Ramp 3',
|
||||
'icon': 'IPO_CUBIC',
|
||||
'node_type': 'BioxelNodes_SetColorRamp3',
|
||||
'node_description': ''
|
||||
},
|
||||
{
|
||||
'label': 'Color Ramp 4',
|
||||
'icon': 'IPO_QUART',
|
||||
'node_type': 'BioxelNodes_SetColorRamp4',
|
||||
'node_description': ''
|
||||
},
|
||||
{
|
||||
'label': 'Color Ramp 5',
|
||||
'icon': 'IPO_QUINT',
|
||||
'node_type': 'BioxelNodes_SetColorRamp5',
|
||||
'node_description': ''
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
'label': 'Cutters',
|
||||
'icon': 'MOD_BEVEL',
|
||||
'items': [
|
||||
{
|
||||
'label': 'Cut',
|
||||
'icon': 'MOD_BEVEL',
|
||||
'node_type': 'BioxelNodes_Cut',
|
||||
'node_description': ''
|
||||
},
|
||||
"separator",
|
||||
{
|
||||
'label': 'Plane Cutter',
|
||||
'icon': 'MOD_LATTICE',
|
||||
'node_type': 'BioxelNodes_PlaneCutter',
|
||||
'node_description': '',
|
||||
},
|
||||
{
|
||||
'label': 'Plane Object Cutter',
|
||||
'icon': 'OUTLINER_OB_LATTICE',
|
||||
'node_type': 'BioxelNodes_PlaneObjectCutter',
|
||||
'node_description': '',
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
'label': 'Utils',
|
||||
'icon': 'MODIFIER',
|
||||
'items': [
|
||||
{
|
||||
'label': 'Join Component',
|
||||
'icon': 'CONSTRAINT_BONE',
|
||||
'node_type': 'BioxelNodes_JoinComponent',
|
||||
'node_description': ''
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
custom_nodes = CustomNodes(
|
||||
menu_items=MENU_ITEMS,
|
||||
|
||||
234
bioxelnodes/operators.py
Normal file
@@ -0,0 +1,234 @@
|
||||
from pathlib import Path
|
||||
import random
|
||||
import bpy
|
||||
import pyopenvdb as vdb
|
||||
from uuid import uuid4
|
||||
from .nodes import custom_nodes
|
||||
from .utils import (get_container, get_container_layers,
|
||||
get_layer, get_node_by_type, hide_in_ray, lock_transform)
|
||||
|
||||
|
||||
def get_scalar_layer_selection(self, context):
|
||||
items = [("None", "None", "")]
|
||||
base_layer = bpy.data.objects[self.base_layer]
|
||||
container = base_layer.parent
|
||||
for layer in get_container_layers(container):
|
||||
if layer.get("bioxel_layer_type") == "scalar":
|
||||
items.append((
|
||||
layer.name,
|
||||
layer.name,
|
||||
""
|
||||
))
|
||||
|
||||
return items
|
||||
|
||||
|
||||
def get_label_layer_selection(self, context):
|
||||
items = [("None", "None", "")]
|
||||
base_layer = bpy.data.objects[self.base_layer]
|
||||
container = base_layer.parent
|
||||
for layer in get_container_layers(container):
|
||||
if layer.get("bioxel_layer_type") == "label":
|
||||
items.append((
|
||||
layer.name,
|
||||
layer.name,
|
||||
""
|
||||
))
|
||||
|
||||
return items
|
||||
|
||||
|
||||
class JoinLayers(bpy.types.Operator):
|
||||
bl_idname = "bioxelnodes.join_layers"
|
||||
bl_label = "Join Additinal Layers"
|
||||
bl_description = "Join Layers"
|
||||
bl_options = {'UNDO'}
|
||||
|
||||
base_layer: bpy.props.StringProperty(
|
||||
options={"HIDDEN"}
|
||||
) # type: ignore
|
||||
|
||||
scalar_layer: bpy.props.EnumProperty(
|
||||
name="Scaler Layer",
|
||||
items=get_scalar_layer_selection
|
||||
) # type: ignore
|
||||
|
||||
label_layer: bpy.props.EnumProperty(
|
||||
name="Label Layer",
|
||||
items=get_label_layer_selection
|
||||
) # type: ignore
|
||||
# color_layer: bpy.props.StringProperty() # type: ignore
|
||||
|
||||
@classmethod
|
||||
def poll(cls, context):
|
||||
layer = get_layer(bpy.context.active_object)
|
||||
return True if layer else False
|
||||
|
||||
def execute(self, context):
|
||||
base_layer = bpy.data.objects[self.base_layer]
|
||||
|
||||
if not base_layer:
|
||||
self.report({"WARNING"}, "Cannot find any bioxel layer as base.")
|
||||
return {'FINISHED'}
|
||||
|
||||
base_layer_dir = bpy.path.abspath(base_layer.data.filepath)
|
||||
base_grids, base_metadata = vdb.readAll(base_layer_dir)
|
||||
|
||||
preferences = context.preferences.addons[__package__].preferences
|
||||
cache_dir = Path(preferences.cache_dir, 'VDBs')
|
||||
cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
layers = []
|
||||
if self.scalar_layer != "None":
|
||||
scalar_layer = bpy.data.objects[self.scalar_layer]
|
||||
layers.append(scalar_layer)
|
||||
|
||||
if self.label_layer != "None":
|
||||
label_layer = bpy.data.objects[self.label_layer]
|
||||
layers.append(label_layer)
|
||||
|
||||
# TODO: add color and vector
|
||||
|
||||
if len(layers) == 0:
|
||||
self.report({"WARNING"}, "No additinal layers setted.")
|
||||
return {'FINISHED'}
|
||||
|
||||
for layer in layers:
|
||||
layer_dir = bpy.path.abspath(layer.data.filepath)
|
||||
grids, metadata = vdb.readAll(layer_dir)
|
||||
base_grids.extend(grids)
|
||||
|
||||
vdb_path = Path(cache_dir, f"{uuid4()}.vdb")
|
||||
print(f"Storing the VDB file ({str(vdb_path)})...")
|
||||
vdb.write(str(vdb_path), grids=base_grids)
|
||||
|
||||
# Read VDB
|
||||
print(f"Loading the cache to Blender scene...")
|
||||
bpy.ops.object.volume_import(
|
||||
filepath=str(vdb_path), align='WORLD', location=(0, 0, 0), scale=(1, 1, 1))
|
||||
|
||||
joined_layer = bpy.context.active_object
|
||||
|
||||
# Set props to VDB object
|
||||
joined_layer.name = f"{base_layer.name}_Joined"
|
||||
joined_layer.data.name = f"{base_layer.name}_Joined"
|
||||
|
||||
lock_transform(joined_layer)
|
||||
hide_in_ray(joined_layer)
|
||||
joined_layer.hide_select = True
|
||||
joined_layer.hide_render = True
|
||||
joined_layer.hide_viewport = True
|
||||
joined_layer.data.display.use_slice = True
|
||||
joined_layer.data.display.density = 1e-05
|
||||
|
||||
joined_layer['bioxel_layer'] = True
|
||||
joined_layer.parent = base_layer.parent
|
||||
|
||||
for collection in layer.users_collection:
|
||||
collection.objects.unlink(layer)
|
||||
|
||||
for collection in base_layer.users_collection:
|
||||
collection.objects.link(layer)
|
||||
|
||||
# add convert to layer node
|
||||
base_layer_node = base_layer.modifiers[0].node_group.nodes['BioxelNodes__ConvertToLayer']
|
||||
bioxel_size = base_layer_node.inputs['Bioxel Size'].default_value
|
||||
layer_shape = base_layer_node.inputs['Shape'].default_value
|
||||
layer_origin = base_layer_node.inputs['Origin'].default_value
|
||||
layer_rotation = base_layer_node.inputs['Rotation'].default_value
|
||||
scalar_offset = base_layer_node.inputs['Scalar Offset'].default_value
|
||||
scalar_min = base_layer_node.inputs['Scalar Min'].default_value
|
||||
scalar_max = base_layer_node.inputs['Scalar Max'].default_value
|
||||
|
||||
if self.scalar_layer != "None":
|
||||
scalar_layer_node = scalar_layer.modifiers[0].node_group.nodes['BioxelNodes__ConvertToLayer']
|
||||
scalar_offset = scalar_layer_node.inputs['Scalar Offset'].default_value
|
||||
scalar_min = scalar_layer_node.inputs['Scalar Min'].default_value
|
||||
scalar_max = scalar_layer_node.inputs['Scalar Max'].default_value
|
||||
|
||||
bpy.ops.node.new_geometry_nodes_modifier()
|
||||
node_tree = joined_layer.modifiers[0].node_group
|
||||
nodes = node_tree.nodes
|
||||
links = node_tree.links
|
||||
|
||||
input_node = get_node_by_type(nodes, 'NodeGroupInput')[0]
|
||||
output_node = get_node_by_type(nodes, 'NodeGroupOutput')[0]
|
||||
|
||||
joined_layer_node = custom_nodes.add_node(
|
||||
nodes, "BioxelNodes__ConvertToLayer")
|
||||
|
||||
links.new(input_node.outputs[0], joined_layer_node.inputs[0])
|
||||
links.new(joined_layer_node.outputs[0], output_node.inputs[0])
|
||||
|
||||
joined_layer_node.inputs['Layer ID'].default_value = random.randint(-200000000,
|
||||
200000000)
|
||||
joined_layer_node.inputs['Bioxel Size'].default_value = bioxel_size
|
||||
joined_layer_node.inputs['Shape'].default_value = layer_shape
|
||||
joined_layer_node.inputs['Origin'].default_value = layer_origin
|
||||
joined_layer_node.inputs['Rotation'].default_value = layer_rotation
|
||||
joined_layer_node.inputs['Scalar Offset'].default_value = scalar_offset
|
||||
joined_layer_node.inputs['Scalar Min'].default_value = scalar_min
|
||||
joined_layer_node.inputs['Scalar Max'].default_value = scalar_max
|
||||
|
||||
return {'FINISHED'}
|
||||
|
||||
def invoke(self, context, event):
|
||||
base_layer = get_layer(bpy.context.active_object)
|
||||
self.base_layer = base_layer.name
|
||||
context.window_manager.invoke_props_dialog(self, width=400)
|
||||
return {'RUNNING_MODAL'}
|
||||
|
||||
|
||||
class ConvertToMesh(bpy.types.Operator):
|
||||
bl_idname = "bioxelnodes.convert_to_mesh"
|
||||
bl_label = "Bioxel Components To Mesh"
|
||||
bl_description = "Convert Bioxel Components To Mesh"
|
||||
bl_options = {'UNDO'}
|
||||
|
||||
@classmethod
|
||||
def poll(cls, context):
|
||||
container = get_container(bpy.context.active_object)
|
||||
return True if container else False
|
||||
|
||||
def execute(self, context):
|
||||
container = get_container(bpy.context.active_object)
|
||||
|
||||
if not container:
|
||||
self.report({"WARNING"}, "Cannot find any bioxel container.")
|
||||
return {'FINISHED'}
|
||||
|
||||
bpy.ops.mesh.primitive_cube_add(
|
||||
size=2, enter_editmode=False, align='WORLD', location=(0, 0, 0), scale=(1, 1, 1))
|
||||
mesh = bpy.context.active_object
|
||||
|
||||
mesh.name = f"Mesh_{container.name}"
|
||||
|
||||
bpy.ops.object.constraint_add(type='COPY_TRANSFORMS')
|
||||
mesh.constraints[0].target = container
|
||||
|
||||
bpy.ops.node.new_geometry_nodes_modifier()
|
||||
modifier = mesh.modifiers[0]
|
||||
nodes = modifier.node_group.nodes
|
||||
links = modifier.node_group.links
|
||||
|
||||
output_node = get_node_by_type(nodes, 'NodeGroupOutput')[0]
|
||||
object_node = nodes.new("GeometryNodeObjectInfo")
|
||||
realize_nodes = nodes.new("GeometryNodeRealizeInstances")
|
||||
separate_node = custom_nodes.add_node(nodes,
|
||||
"BioxelNodes__SeparateComponent")
|
||||
|
||||
object_node.inputs[0].default_value = container
|
||||
separate_node.inputs[1].default_value = 1
|
||||
|
||||
links.new(object_node.outputs['Geometry'], separate_node.inputs[0])
|
||||
links.new(separate_node.outputs[0], realize_nodes.inputs[0])
|
||||
links.new(realize_nodes.outputs[0], output_node.inputs[0])
|
||||
|
||||
bpy.ops.object.convert(target='MESH')
|
||||
bpy.ops.constraint.apply(constraint="Copy Transforms", owner='OBJECT')
|
||||
bpy.context.object.active_material_index = 1
|
||||
bpy.ops.object.material_slot_remove()
|
||||
|
||||
self.report({"INFO"}, f"Successfully convert to mesh")
|
||||
|
||||
return {'FINISHED'}
|
||||
@@ -12,11 +12,6 @@ class BioxelNodesPreferences(bpy.types.AddonPreferences, ExternalPackagePreferen
|
||||
default=str(Path(Path.home(), '.bioxelnodes'))
|
||||
) # 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,
|
||||
@@ -31,6 +26,4 @@ class BioxelNodesPreferences(bpy.types.AddonPreferences, ExternalPackagePreferen
|
||||
|
||||
layout.label(text="Configuration")
|
||||
layout.prop(self, 'cache_dir')
|
||||
|
||||
layout.prop(self, "do_change_render_setting")
|
||||
layout.prop(self, "do_add_segmentnode")
|
||||
|
||||
@@ -9,6 +9,7 @@ def get_type(cls):
|
||||
def get_node_by_type(nodes, type_name: str):
|
||||
return [node for node in nodes if get_type(node) == type_name]
|
||||
|
||||
|
||||
def show_message(message="", title="Message Box", icon='INFO'):
|
||||
|
||||
def draw(self, context):
|
||||
@@ -67,33 +68,57 @@ def calc_bbox_verts(origin, size):
|
||||
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 lock_transform(obj):
|
||||
obj.lock_location[0] = True
|
||||
obj.lock_location[1] = True
|
||||
obj.lock_location[2] = True
|
||||
obj.lock_rotation[0] = True
|
||||
obj.lock_rotation[1] = True
|
||||
obj.lock_rotation[2] = True
|
||||
obj.lock_scale[0] = True
|
||||
obj.lock_scale[1] = True
|
||||
obj.lock_scale[2] = True
|
||||
|
||||
|
||||
def get_all_bioxels_objs():
|
||||
bioxels_objs = []
|
||||
def hide_in_ray(obj):
|
||||
obj.visible_camera = False
|
||||
obj.visible_diffuse = False
|
||||
obj.visible_glossy = False
|
||||
obj.visible_transmission = False
|
||||
obj.visible_volume_scatter = False
|
||||
obj.visible_shadow = False
|
||||
|
||||
|
||||
def get_container(current_obj):
|
||||
if current_obj:
|
||||
return current_obj if current_obj.get('bioxel_container') else None
|
||||
return None
|
||||
|
||||
|
||||
def get_layer(current_obj):
|
||||
if current_obj:
|
||||
if current_obj.get('bioxel_layer') and current_obj.parent:
|
||||
if current_obj.parent.get('bioxel_container'):
|
||||
return current_obj
|
||||
return None
|
||||
|
||||
|
||||
def get_container_layers(container):
|
||||
layers = []
|
||||
for obj in bpy.data.objects:
|
||||
if obj.parent:
|
||||
if obj.parent.get('bioxels_container') and obj.get('bioxels'):
|
||||
bioxels_objs.append(obj)
|
||||
if obj.parent == container and get_layer(obj):
|
||||
layers.append(obj)
|
||||
|
||||
return list(set(bioxels_objs))
|
||||
return layers
|
||||
|
||||
|
||||
def get_all_layers():
|
||||
layers = []
|
||||
for obj in bpy.data.objects:
|
||||
if get_layer(obj):
|
||||
layers.append(obj)
|
||||
|
||||
return layers
|
||||
|
||||
|
||||
def get_text_index_str(text):
|
||||
|
||||
|
Before Width: | Height: | Size: 6.3 KiB |
|
Before Width: | Height: | Size: 220 KiB |
|
Before Width: | Height: | Size: 50 KiB |
BIN
docs/assets/cover.png
Normal file
|
After Width: | Height: | Size: 2.0 MiB |
|
Before Width: | Height: | Size: 9.1 KiB After Width: | Height: | Size: 9.1 KiB |
BIN
docs/assets/features_concept.png
Normal file
|
After Width: | Height: | Size: 148 KiB |
BIN
docs/assets/features_container.png
Normal file
|
After Width: | Height: | Size: 423 KiB |
|
Before Width: | Height: | Size: 8.6 KiB After Width: | Height: | Size: 8.6 KiB |
|
Before Width: | Height: | Size: 19 KiB After Width: | Height: | Size: 19 KiB |
|
Before Width: | Height: | Size: 126 KiB |
|
Before Width: | Height: | Size: 126 KiB |
|
Before Width: | Height: | Size: 22 KiB After Width: | Height: | Size: 22 KiB |
BIN
docs/assets/getting-started_graph.png
Normal file
|
After Width: | Height: | Size: 96 KiB |
|
Before Width: | Height: | Size: 252 KiB After Width: | Height: | Size: 252 KiB |
|
Before Width: | Height: | Size: 770 KiB After Width: | Height: | Size: 770 KiB |
BIN
docs/assets/getting-started_share-file.png
Normal file
|
After Width: | Height: | Size: 30 KiB |
|
Before Width: | Height: | Size: 44 KiB |
BIN
docs/assets/nodes_bake.png
Normal file
|
After Width: | Height: | Size: 174 KiB |
BIN
docs/assets/nodes_color-presets.png
Normal file
|
After Width: | Height: | Size: 45 KiB |
BIN
docs/assets/nodes_color-ramp-2.png
Normal file
|
After Width: | Height: | Size: 66 KiB |
BIN
docs/assets/nodes_color-ramp-3.png
Normal file
|
After Width: | Height: | Size: 71 KiB |
BIN
docs/assets/nodes_color-ramp-4.png
Normal file
|
After Width: | Height: | Size: 77 KiB |
BIN
docs/assets/nodes_color-ramp-5.png
Normal file
|
After Width: | Height: | Size: 81 KiB |
BIN
docs/assets/nodes_concept.png
Normal file
|
After Width: | Height: | Size: 75 KiB |
BIN
docs/assets/nodes_cut.png
Normal file
|
After Width: | Height: | Size: 45 KiB |
BIN
docs/assets/nodes_example.png
Normal file
|
After Width: | Height: | Size: 140 KiB |
BIN
docs/assets/nodes_join-component.png
Normal file
|
After Width: | Height: | Size: 62 KiB |
BIN
docs/assets/nodes_mask-by-label.png
Normal file
|
After Width: | Height: | Size: 57 KiB |
BIN
docs/assets/nodes_mask-by-range.png
Normal file
|
After Width: | Height: | Size: 96 KiB |
BIN
docs/assets/nodes_mask-by-threshold.png
Normal file
|
After Width: | Height: | Size: 86 KiB |
BIN
docs/assets/nodes_plane-cutter.png
Normal file
|
After Width: | Height: | Size: 53 KiB |
BIN
docs/assets/nodes_plane-object-cutter.png
Normal file
|
After Width: | Height: | Size: 41 KiB |
BIN
docs/assets/nodes_separate-component.png
Normal file
|
After Width: | Height: | Size: 40 KiB |
BIN
docs/assets/nodes_slime-shader.png
Normal file
|
After Width: | Height: | Size: 75 KiB |
BIN
docs/assets/nodes_solid-shader.png
Normal file
|
After Width: | Height: | Size: 75 KiB |
BIN
docs/assets/nodes_universal-shader.png
Normal file
|
After Width: | Height: | Size: 75 KiB |
BIN
docs/assets/nodes_volume-shader.png
Normal file
|
After Width: | Height: | Size: 59 KiB |
|
Before Width: | Height: | Size: 108 KiB |
|
Before Width: | Height: | Size: 17 KiB |
@@ -1,45 +1,81 @@
|
||||
# Features & Options
|
||||
|
||||
## Import Volume Data as Biovels
|
||||
## Bioxel Design Concept
|
||||
|
||||
File > Import > Volume Data as Biovels
|
||||
According to Bioxel design concept, Bioxel Nodes imports volume data and put it into a **Container** as a **Layer**. One container may has more than one layer, and each layer stores the information of different fields under the same location, which is similar to the view layers in map app, except that here it is in 3D space. In order to render the volume the way we want it to, we need to build renderable objects from layers. We call those objects **Component**. The following diagram shows the relationship of **Container**, **Layer**, and **Component**:
|
||||
|
||||

|
||||
|
||||
Bioxel Nodes staging the layer as an openvdb file. The process of building from layers to a component is taking place in blender geometry nodes graph with blender native geometry nodes. Therefore, **the blender file works without Bioxel Nodes.**
|
||||
|
||||
## Container Structure
|
||||
|
||||
In Blender, container structure is like this:
|
||||
|
||||
```bash
|
||||
Case_0000 # Container
|
||||
|-- Case_0000_CT # Layer
|
||||
|-- Case_0000_Label_1 # Layer
|
||||
`-- Case_0000_Label_2 # Layer
|
||||
```
|
||||
|
||||
The container also stores the build process in geometry nodes:
|
||||
|
||||

|
||||
|
||||
The layer is categorized into these by data type:
|
||||
|
||||
- Scalar
|
||||
- Label
|
||||
- Vector (Not implemented yet)
|
||||
- Color (Not implemented yet)
|
||||
|
||||
## First Time Import Volume Data
|
||||
|
||||
File > Import > Volume Data as Bioxel Layer
|
||||
|
||||
### Resample
|
||||
|
||||

|
||||

|
||||
|
||||
Sometimes the original data is too big, or the spacing in the original data is not reasonable, you can modify the `Bioxel Size` and `Original Spacing` to adjust the Shape of the Bixoels.
|
||||
Sometimes the original data is too big, or the spacing in the original data is not reasonable, you can modify the `Bioxel Size` and `Original Spacing` to adjust the Shape of the layer.
|
||||
|
||||
A bioxel is like a pixel, the larger the `Bioxel Size`, the lower the resolution of the image, Original Spacing will be read from the original data record, but sometimes the image doesn't have original spacing, you may need to input it manually to get the correct shape.
|
||||
|
||||
### Read as
|
||||
|
||||
#### as Scalar
|
||||
- as Scalar
|
||||
|
||||

|
||||

|
||||
|
||||
In some cases the environment value is higher than the value of the target object, you can check `Invert Scalar` to adjust the value for better result.
|
||||
In some cases the environment value is higher than the value of the target object, you can check `Invert Scalar` to adjust the value for better result.
|
||||
|
||||
#### as Labels
|
||||
- as Labels
|
||||
|
||||

|
||||
Many AI segmentation task datasets, provide segmentation data, which are often an integer value representing a layer of segmentation labels. You can set it to `Labels` to load them.
|
||||
|
||||
Many AI segmentation task datasets, provide segmentation data, which are often an integer value representing a layer of segmentation labels. You can set the Label Index to determine exactly which labels to load.
|
||||
- _as Vector (Not implemented yet)_
|
||||
|
||||
#### as Vector (Not implemented)
|
||||
|
||||
#### as Color (Not implemented)
|
||||
- _as Color (Not implemented yet)_
|
||||
|
||||
### Others
|
||||
|
||||

|
||||

|
||||
|
||||
## Convert Bioxels to Mesh
|
||||
`Scene Scale` determines how many units of length in the Blender world correspond to one unit of length in the Bioxel world. Since Blender defaults to meters, and the default size of blender primitives are around 1 blender unit. Therefore `Scene Scale` set to 0.01 is appropriate.
|
||||
|
||||
In 3D view, select bioxels and right-click, Bioxels > Bioxels To Mesh
|
||||
`Orient to RAS` determines whether the layer should be converted to the RAS coordinate system. Regardless of the format of the medical image data, the coordinate system is mostly the LPS coordinate system. Bioxel, however, are in the RAS coordinate system and therefore need to be transformed in most cases.
|
||||
|
||||

|
||||
## Adding Volume Data to an existing container
|
||||
|
||||
## Export Biovels as VDB
|
||||
In 3D view or outliner panel, select the container and right click, Bioxel Nodes > Add Volume Data to Container.
|
||||
The import settings are the same as for the first time import.
|
||||
|
||||
File > Export > Biovels as VDB
|
||||
## Convert Bioxel Components to Mesh
|
||||
|
||||
In 3D view or outliner panel, select the container and right click, Bioxel Nodes > Bioxel Components To Mesh
|
||||
Once it has been turned into a mesh model, you can perform any traditional 3D editing operations on it, such as sculpting, boolean, etc.
|
||||
|
||||
## Export Biovel Layer as VDB
|
||||
|
||||
File > Export > Biovel Layer as VDB
|
||||
|
||||
@@ -4,18 +4,31 @@ Currently only support Blender 4.0 or above, make sure you have the correct vers
|
||||
|
||||
## Add-on Installation
|
||||
|
||||
Download the latest version https://github.com/OmooLab/BioxelNodes/releases/latest
|
||||
In Blender, Edit > Preferences > Add-ons > Install, select the `BioxelNodes_{version}.zip` you just downloaded.
|
||||
#### For Blender 4.2 or higher
|
||||
|
||||
Download the **Extension** version `BioxelNodes_Extension_{version}.zip` from https://github.com/OmooLab/BioxelNodes/releases/latest
|
||||
In Blender, Edit > Preferences > Extensions > Install from Disk, select the zip file you just downloaded.
|
||||
|
||||
Thats it!
|
||||
|
||||
> If it cannot be enable, just reboot blender.
|
||||
|
||||
#### For Blender 4.0 or 4.1
|
||||
|
||||
Download the **Addon** version `BioxelNodes_Addon_{version}.zip` from https://github.com/OmooLab/BioxelNodes/releases/latest
|
||||
In Blender, Edit > Preferences > Add-ons > Install, select the zip file you just downloaded.
|
||||
|
||||
The add-on requires a third-party python dependency called SimpleITK, click `Install SimpleITK` button below to install the dependency. After clicking, blender may get stuck, it is downloading and installing, just wait for a moment. After that, click `Reboot Blender` button.
|
||||
|
||||

|
||||

|
||||
|
||||
This step may have failed due to network factors, just click "Set PyPI Mirror" to change the mirror.
|
||||
|
||||
## Prepare Your Data
|
||||
|
||||
First you need to have your volumetric data ready. If not, you can access open research data from list below:
|
||||
First you need to have your volumetric data ready. If not, you can access open research data from list below.
|
||||
|
||||
> 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 |
|
||||
| ------------------------------------------------------------------------------------ | ------------------ |
|
||||
@@ -30,34 +43,30 @@ First you need to have your volumetric data ready. If not, you can access open r
|
||||
|
||||
## Import Volume Data
|
||||
|
||||
File > Import > Volume Data as Bioxels, select **one** of the .dcm files and click on "Volume Data as Bioxels" (you can also drag one of the .dcm files directly into the 3D viewport to trigger the import)
|
||||
File > Import > Volume Data as Bioxel Layer, select **one** of the .dcm files and click on "Volume Data as Bioxel Layer" (you can also drag one of the .dcm files directly into the 3D viewport to trigger the import)
|
||||
|
||||

|
||||

|
||||
|
||||
It may take a while to read data. After finishing reading, it will pop up a dialog box
|
||||
It may take a while to read data. After finishing reading, it will pop up a dialog box. Ignore all the options, just click OK (we will tell about these options later).
|
||||
|
||||

|
||||
After importing the data, the add-on will automatically add the necessary nodes to build the component. Click on the new created object in outliner, open the geometry nodes panel, set `Threshold` in "Mask by Threshold" node to 200, and then connect a Slime Shader node (Add > Bioxel Nodes > Slime Shader) after it. The node graph should be as following:
|
||||
|
||||
Ignore the options, just click OK!
|
||||
|
||||
After importing, the necessary nodes are automatically added, the reconstruction and shader are created. Click select Bioxels Object, and open the Geometry Nodes panel, change the "Threshold" in segment node.
|
||||
|
||||

|
||||

|
||||
|
||||
and then turned on the cycles rendering to directly see the result.
|
||||
|
||||

|
||||

|
||||
|
||||
You can change the "Threshold" to modify the reconstruction model, or change the "Color", "Density" to modify the shader effect. All the parameters are straightforward, you can understand them by changing the values.
|
||||
You can change the "Threshold" to modify the preview model, or change the "Color", "Density" to modify the shader effect. All the parameters are straightforward, you can understand them by changing the values.
|
||||
|
||||
## Share Your File
|
||||
|
||||
The VDB cache and the Bioxel nodes are not reachable to computers if you don't save them. If you need to give your blender file to someone else, you will need to perform the following steps:
|
||||
The VDB cache and the Bioxel nodes are not reachable to other computers if you don't save them. If you want to give your blender file to someone else, you will need to perform the following steps first:
|
||||
|
||||
1. Save your blender file
|
||||
2. Click Scene > Bioxels > Save All Bioxels in the Properties panel.
|
||||
3. Click Scene > Custom Nodes > Save All Custom Nodes under the Properties panel.
|
||||
2. Click Scene > Bioxels > Save All Bioxels in the properties panel.
|
||||
3. Click Scene > Custom Nodes > Save All Custom Nodes in the properties panel.
|
||||
|
||||

|
||||

|
||||
|
||||
After that, both the VDB cache and the Bioxel nodes are stored in relative locations. When you share a file with someone, pack the entire directory so that the resources are not lost. The other person will be able to load correctly, regardless of whether they have BioxelNodes installed.
|
||||
After that, both the VDB cache and the Bioxel nodes are restored in relative locations. When you share this file with someone, pack the entire directory so that the resources will be not lost. The other person will be able to open it correctly, regardless of whether they have Bioxel Nodes installed or not.
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
[中文文档](https://uj6xfhbzp0.feishu.cn/wiki/Qx3VwHuNPimeI8kr6nDcvl1DnHf?from=from_copylink)
|
||||
|
||||
# Bioxel Nodes
|
||||
|
||||

|
||||
@@ -9,17 +7,17 @@
|
||||
|
||||
Bioxel Nodes is a Blender add-on for scientific volumetric data visualization. It using Blender's powerful Geometry Nodes | Cycles to process and render volumetric data.
|
||||
|
||||
# About
|
||||
## About
|
||||
|
||||
Before us, there have been many tutorials and add-ons for importing volumetric data into Blender. However, we found that there were many details that were not addressed in place, some scientific facts were ignored, and the volume rendering was not pretty enough. With Bioxel Nodes, you can easily import the volumetric data into Blender, and more importantly, it can quickly make a beautiful realistic rendering of it.
|
||||
|
||||
Below are some examples with Bioxel Nodes. Thanks to Cycles Render, the volumetric data can be rendered with great detail:
|
||||
|
||||

|
||||

|
||||
|
||||
The "Bioxel" in "BioxelNodes", is a combination of the words "Bio-" and "Voxel". Bioxel is a voxel that stores biological data. The volumetric data made up of Bioxel is called Bioxels. We are developing a toolkit around Bioxels for better biological data visualization. but before its release, we made this Blender version of bioxels toolkit first, in order to let more people to have fun with volumetric data. [Getting Started](https://omoolab.github.io/BioxelNodes/latest/getting-started)
|
||||
The "Bioxel" in "Bioxel Nodes", is a combination of the words "Bio-" and "Voxel". Bioxel is a voxel that stores biological data. We are developing a toolkit around Bioxel for better biological data visualization. but before its release, we made this Blender version of bioxels toolkit first, in order to let more people to have fun with volumetric data. [Getting Started](https://omoolab.github.io/BioxelNodes/latest/getting-started)
|
||||
|
||||
# Supported Format
|
||||
## Supported Format
|
||||
|
||||
| Format | EXT | Test |
|
||||
| ------ | ---------------------------------------- | ------- |
|
||||
@@ -39,7 +37,32 @@ The "Bioxel" in "BioxelNodes", is a combination of the words "Bio-" and "Voxel".
|
||||
| MINC | .mnc, .MNC | yet |
|
||||
| MRC | .mrc, .rec | yet |
|
||||
|
||||
# Known limitations
|
||||
## Known Limitations
|
||||
|
||||
- Sections cannot be generated
|
||||
- Time sequence volume not supported (will be supported soon)
|
||||
- Sections cannot be generated (will be supported soon)
|
||||
- Time sequence volume not supported (will be supported soon)
|
||||
|
||||
## To Upgrade Add-on
|
||||
|
||||
To upgrade from an older version of the add-on to the latest, you need to do the following:
|
||||
|
||||
1. Remove the old version of Bioxel Nodes at Preferences > Add-ons
|
||||
2. Add the new version and restart Blender.
|
||||
|
||||
It is not support editing the same blender file across add-on versions. In order to make sure that the previous file works properly. You need to save the staged data before upgrading ( read the last section of [Getting Started](https://omoolab.github.io/BioxelNodes/latest/getting-started/#share-your-file) ).
|
||||
|
||||
But even then, there is still no guarantee that the new version of the add-on will work on the old blender file. Therefore, it is highly recommended to open a new blender file to start the creating, not based on the old one.
|
||||
|
||||
Alternatively, objects from the old file that have nothing to do with Bioxel Nodes could be append to the new blender file.
|
||||
|
||||
## About EEVEE Render
|
||||
|
||||
Bioxel Nodes is designed for Cycles Render. However, it does support eevee render partially. "Solid Shader" node and "Volume Shader" node have a toggle called "EEVEE Render". If you want to render Bioxel Component in real-time, turn it on.
|
||||
|
||||
Also, there are some limitations:
|
||||
|
||||
1. Only one cutter supported.
|
||||
2. You cannot use "Color Ramp" over 2 colors.
|
||||
3. EEVEE Render result is not that great as Cycles does.
|
||||
|
||||
> "Volume Shader" node is not work properly in EEVEE Next since 4.2. It is because EEVEE Next is not support attributes from instances of volume shader by now. But the Blender 4.2 docs still say attributes reading is ok, so I suppose this feature will eventually be implemented.
|
||||
|
||||
394
docs/nodes.md
@@ -1,19 +1,391 @@
|
||||
# Geometry Nodes
|
||||
# Nodes
|
||||
|
||||
The node, that named "Segment", is a preset node that combines the steps of 3D reconstruction process and shading process. In general, you need to add one of the segmentation node to reconstruction first, and followed by one of the shader node to set the shader. As you can see in the following figure:
|
||||
## Nodes Design Concept
|
||||
|
||||

|
||||
In order to build a component, the general process is to first use a "Mask Method" node to build the surface of the component based on its layers, and then connect to a "Assign Shader" node to add the material physical properties. Finally, if you need to cut the cross-section, then connect to a "Cut" node. The whole process is shown in the following diagram
|
||||
|
||||
Currently there are 3 types of nodes
|
||||

|
||||
|
||||
- Segmentation nodes, responsible for splitting the volume into a reconstructed model (we call them "Segment").
|
||||
- Shader nodes, responsible for giving shader to the Segment.
|
||||
- Slicer nodes, responsible for partially cutting the Segment.
|
||||
A typical example looks like this:
|
||||
|
||||
For example:
|
||||

|
||||
|
||||

|
||||
The "Mask Method" node tends to be very computationally intensive, and if it consumes too much time, then you can bake it with a "Bake" node after it (but you need to save the Blender file first).
|
||||
|
||||
You can add a "Bake" node between segmentation node and shader node, if the reconstruction process consumes too much computing time. But be sure, you are selecting the volume object, not the container object.
|
||||

|
||||
|
||||

|
||||
## Mask Methods
|
||||
|
||||
This type of node is responsible for culling out the extent of the component that does not need to be rendered, forming the interface between the object and the object, or the surface of the object (i.e., the interface between the object and the air)
|
||||
|
||||
### ⬆️ Mask by Threshold
|
||||
|
||||
<div class="grid cards" markdown>
|
||||
|
||||
- 
|
||||
|
||||
- Generate a mask by keeping only the positions that exceed the threshold (this only works with scalar)
|
||||
|
||||
***
|
||||
|
||||
Node Parameter:
|
||||
|
||||
- **Layer**, _the input scalar_
|
||||
- **Threshold**, _the threshold value_
|
||||
- Preview
|
||||
- **Detail Factor**, _the fineness of the preview, the larger the factor, the coarser preview is_
|
||||
- (Label Mask)
|
||||
- **Layer**, _the input label_
|
||||
- **Invert**, _invert mask_
|
||||
- **Sample Size**, _the mask sample size_
|
||||
- (Replacement)
|
||||
- **Joined**, _the joined layer_
|
||||
|
||||
</div>
|
||||
|
||||
### ↕ Mask by Range
|
||||
|
||||
<div class="grid cards" markdown>
|
||||
|
||||
- 
|
||||
|
||||
- Generate a mask by keeping only the positions that in range (this only works with scalar)
|
||||
|
||||
***
|
||||
|
||||
Node Parameter:
|
||||
|
||||
- **Layer**, _the input scalar_
|
||||
- **Fram Min**, _the lower limit_
|
||||
- **Fram Max**, _the upper limit_
|
||||
- Preview
|
||||
- **Detail Factor**, _the fineness of the preview, the larger the factor, the coarser preview is_
|
||||
- (Label Mask)
|
||||
- **Layer**, _the input label_
|
||||
- **Invert**, _invert mask_
|
||||
- **Sample Size**, _the mask sample size_
|
||||
- (Replacement)
|
||||
- **Joined**, _the joined layer_
|
||||
|
||||
</div>
|
||||
|
||||
### 🔤 Mask by Label
|
||||
|
||||
<div class="grid cards" markdown>
|
||||
|
||||
- 
|
||||
|
||||
- Generate a mask by keeping only the positions that in label (this only works with label)
|
||||
|
||||
***
|
||||
|
||||
Node Parameter:
|
||||
|
||||
- **Layer**, _the input label_
|
||||
- Preview
|
||||
- **Detail Factor**, _the fineness of the preview, the larger the factor, the coarser preview is_
|
||||
- (Replacement)
|
||||
- **Joined**, _the joined layer_
|
||||
|
||||
</div>
|
||||
|
||||
## Shaders
|
||||
|
||||
This type of node is responsible for setting material physical properties to the component to reflect the differences in rendering effects of different components.
|
||||
|
||||
### 🥚 Solid Shader
|
||||
|
||||
<div class="grid cards" markdown>
|
||||
|
||||
- 
|
||||
|
||||
- Assign a opaque shader based on a preview mesh with no inclusions visible. Fastest rendering speed. Does not support cross-section and color ramp.
|
||||
|
||||
***
|
||||
|
||||
Node Parameter:
|
||||
|
||||
- **Component**, _the upstream component_
|
||||
- Base
|
||||
- **Color**, _albedo or emission color_
|
||||
- **Subsurface**, _the subsurface scale_
|
||||
- **Opacity**, _the opacity of all_
|
||||
- Specular
|
||||
- **Specular**, _the specular of surface_
|
||||
- **Roughness**, _the roughness of surface_
|
||||
- Emission
|
||||
- **Emission**, _the emission strength_
|
||||
|
||||
</div>
|
||||
|
||||
### 🦠 Slime Shader
|
||||
|
||||
<div class="grid cards" markdown>
|
||||
|
||||
- 
|
||||
|
||||
- Assign a semi-transparent shader based on the preview mesh with visible inclusions. Does not support cross-section and color ramp.
|
||||
|
||||
***
|
||||
|
||||
Node Parameter:
|
||||
|
||||
- **Component**, _the upstream component_
|
||||
- Base
|
||||
- **Color**, _albedo or emission color_
|
||||
- **Density**, _the degree of solidity_
|
||||
- **Anisotropy**, _the anisotropy of scatting_
|
||||
- Specular
|
||||
- **Specular**, _the specular of surface_
|
||||
- **Roughness**, _the roughness of surface_
|
||||
- Emission
|
||||
- **Emission**, _the emission strength_
|
||||
|
||||
</div>
|
||||
|
||||
### ☁️ Volume Shader
|
||||
|
||||
<div class="grid cards" markdown>
|
||||
|
||||
- 
|
||||
|
||||
- Assign a volume-based shader with support for cross-section and color ramp.
|
||||
|
||||
***
|
||||
|
||||
Node Parameter:
|
||||
|
||||
- **Component**, _the upstream component_
|
||||
- Base
|
||||
- **Color**, _albedo or emission color_
|
||||
- **Density**, _the degree of solidity_
|
||||
- **Anisotropy**, _the anisotropy of scatting_
|
||||
- Emission
|
||||
- **Emission**, _the emission strength_
|
||||
|
||||
</div>
|
||||
|
||||
### 🔬 Universal Shader
|
||||
|
||||
<div class="grid cards" markdown>
|
||||
|
||||
- 
|
||||
|
||||
- Assign a ultimate shader, supporting all features of Bioxel Nodes. Of course, the price is slow rendering, which can be greatly improved by adjusting the Volumes > Step Rate to 100 in the Render Settings Panel.
|
||||
|
||||
***
|
||||
|
||||
Node Parameter:
|
||||
|
||||
- **Component**, _the upstream component_
|
||||
- Base
|
||||
- **Color**, _albedo or emission color_
|
||||
- **Density**, _the degree of solidity_
|
||||
- **Anisotropy**, _the anisotropy of scatting_
|
||||
- Specular
|
||||
- **Specular**, _the specular of surface_
|
||||
- **Roughness**, _the roughness of surface_
|
||||
- Emission
|
||||
- **Emission**, _the emission strength_
|
||||
|
||||
</div>
|
||||
|
||||
## Cutters
|
||||
|
||||
This type of node is responsible for cutting components to present cross-section
|
||||
|
||||
### 🪚 Cut
|
||||
|
||||
<div class="grid cards" markdown>
|
||||
|
||||
- 
|
||||
|
||||
- Execute all cutters on one component.
|
||||
|
||||
***
|
||||
|
||||
Node Parameter:
|
||||
|
||||
- **Component**, _the upstream component_
|
||||
- **Cutter 0~4**, _the cutters_
|
||||
- **Hide Guide**, _hide the cutter guide_
|
||||
|
||||
</div>
|
||||
|
||||
### 🧀 Plane Cutter
|
||||
|
||||
<div class="grid cards" markdown>
|
||||
|
||||
- 
|
||||
|
||||
- Flat plane cutter, cuts off above Z-axis in local.
|
||||
|
||||
***
|
||||
|
||||
Node Parameter:
|
||||
|
||||
- **Origin**, _plane cutter position_
|
||||
- **Direction**, _plane cutter orientation_
|
||||
- Guide
|
||||
- **Show**, _show the cutter guide_
|
||||
- **Scale**, _scale the cutter guide_
|
||||
|
||||
</div>
|
||||
|
||||
### 🧀 Plane Object Cutter
|
||||
|
||||
<div class="grid cards" markdown>
|
||||
|
||||
- 
|
||||
|
||||
- Also a plane cutter, but origin and direction are based on exist object.
|
||||
|
||||
***
|
||||
|
||||
Node Parameter:
|
||||
|
||||
- **Plane**, _the plane object_
|
||||
- Guide
|
||||
- **Show**, _show the cutter guide_
|
||||
- **Scale**, _scale the cutter guide_
|
||||
|
||||
</div>
|
||||
|
||||
## Colors
|
||||
|
||||
This type of node is responsible for setting the color properties of the shader
|
||||
|
||||
### 🎨 Color Presents
|
||||
|
||||
<div class="grid cards" markdown>
|
||||
|
||||
- 
|
||||
|
||||
- Set color from presets.
|
||||
|
||||
***
|
||||
|
||||
Node Parameter:
|
||||
|
||||
- **Component**, _the upstream component_
|
||||
- **Presets**, _select color presents_
|
||||
- **Fram Min**, _ramp factor lower limit_
|
||||
- **Fram Max**, _ramp factor upper limit_
|
||||
|
||||
</div>
|
||||
|
||||
### 2️⃣ Color Ramp 2
|
||||
|
||||
<div class="grid cards" markdown>
|
||||
|
||||
- 
|
||||
|
||||
- Set color ramp base on scalar value.
|
||||
|
||||
***
|
||||
|
||||
Node Parameter:
|
||||
|
||||
- **Component**, _the upstream component_
|
||||
- **Fram Min**, _ramp factor lower limit_
|
||||
- **Fram Max**, _ramp factor upper limit_
|
||||
- Ramp
|
||||
- **Pos0 Color**, _position 0% Color_
|
||||
- **Pos1 Color**, _position 100% Color_
|
||||
- **Gamma**, _non-linear coefficient, the larger the coefficient, the more lower value color_
|
||||
- **Contrast**, _the larger the contrast, the harder color ramp will be_
|
||||
|
||||
</div>
|
||||
|
||||
### 3️⃣ Color Ramp 3
|
||||
|
||||
<div class="grid cards" markdown>
|
||||
|
||||
- 
|
||||
|
||||
- Set color ramp base on scalar value.
|
||||
|
||||
***
|
||||
|
||||
Node Parameter:
|
||||
|
||||
- **Component**, _the upstream component_
|
||||
- **Fram Min**, _ramp factor lower limit_
|
||||
- **Fram Max**, _ramp factor upper limit_
|
||||
- Ramp
|
||||
- **Pos0 Color**, _position 0% Color_
|
||||
- **Pos1 Color**, _position 50% Color_
|
||||
- **Pos2 Color**, _position 100% Color_
|
||||
- **Gamma**, _non-linear coefficient, the larger the coefficient, the more lower value color_
|
||||
- **Contrast**, _the larger the contrast, the harder color ramp will be_
|
||||
|
||||
</div>
|
||||
|
||||
### 4️⃣ Color Ramp 4
|
||||
|
||||
<div class="grid cards" markdown>
|
||||
|
||||
- 
|
||||
|
||||
- Set color ramp base on scalar value.
|
||||
|
||||
***
|
||||
|
||||
Node Parameter:
|
||||
|
||||
- **Component**, _the upstream component_
|
||||
- **Fram Min**, _ramp factor lower limit_
|
||||
- **Fram Max**, _ramp factor upper limit_
|
||||
- Ramp
|
||||
- **Pos0 Color**, _position 0% Color_
|
||||
- **Pos1 Color**, _position 33.3% Color_
|
||||
- **Pos2 Color**, _position 66.6% Color_
|
||||
- **Pos3 Color**, _position 100% Color_
|
||||
- **Gamma**, _non-linear coefficient, the larger the coefficient, the more lower value color_
|
||||
- **Contrast**, _the larger the contrast, the harder color ramp will be_
|
||||
|
||||
</div>
|
||||
|
||||
### 5️⃣ Color Ramp 5
|
||||
|
||||
<div class="grid cards" markdown>
|
||||
|
||||
- 
|
||||
|
||||
- Set color ramp base on scalar value.
|
||||
|
||||
***
|
||||
|
||||
Node Parameter:
|
||||
|
||||
- **Component**, _the upstream component_
|
||||
- **Fram Min**, _ramp factor lower limit_
|
||||
- **Fram Max**, _ramp factor upper limit_
|
||||
- Ramp
|
||||
- **Pos0 Color**, _position 0% Color_
|
||||
- **Pos1 Color**, _position 25% Color_
|
||||
- **Pos2 Color**, _position 50% Color_
|
||||
- **Pos3 Color**, _position 75% Color_
|
||||
- **Pos4 Color**, _position 100% Color_
|
||||
- **Gamma**, _non-linear coefficient, the larger the coefficient, the more lower value color_
|
||||
- **Contrast**, _the larger the contrast, the harder color ramp will be_
|
||||
|
||||
</div>
|
||||
|
||||
## Utils
|
||||
|
||||
### 📦 Join Component
|
||||
|
||||
<div class="grid cards" markdown>
|
||||
|
||||
- 
|
||||
|
||||
- Components' combination should not be done by "Join Geometry" node because Blender Cycles can't render volumes in the same position, so the node will slightly offset all components randomly to avoid this problem.
|
||||
|
||||
***
|
||||
|
||||
Node Parameter:
|
||||
|
||||
- **Component 0~4**, _the components_
|
||||
|
||||
</div>
|
||||
|
||||
22
extension/__init__.py
Normal file
@@ -0,0 +1,22 @@
|
||||
import bpy
|
||||
|
||||
from . import auto_load
|
||||
from . import menus
|
||||
|
||||
|
||||
auto_load.init()
|
||||
|
||||
|
||||
def register():
|
||||
auto_load.register()
|
||||
menus.add()
|
||||
bpy.types.Scene.bioxel_layer_dir = bpy.props.StringProperty(
|
||||
name="Bioxel Layers Directory",
|
||||
subtype='DIR_PATH',
|
||||
default="//"
|
||||
)
|
||||
|
||||
|
||||
def unregister():
|
||||
menus.remove()
|
||||
auto_load.unregister()
|
||||
56
extension/blender_manifest.toml
Normal file
@@ -0,0 +1,56 @@
|
||||
schema_version = "1.0.0"
|
||||
|
||||
# Example of manifest file for a Blender extension
|
||||
# Change the values according to your extension
|
||||
id = "bioxelnodes"
|
||||
version = "0.2.2"
|
||||
name = "Bioxel Nodes"
|
||||
tagline = "For scientific volumetric data visualization in Blender"
|
||||
maintainer = "Ma Nan <icrdr2010@outlook.com>"
|
||||
# Supported types: "add-on", "theme"
|
||||
type = "add-on"
|
||||
|
||||
# Optional: add-ons can list which resources they will require:
|
||||
# * "files" (for access of any filesystem operations)
|
||||
# * "network" (for internet access)
|
||||
# * "clipboard" (to read and/or write the system clipboard)
|
||||
# * "camera" (to capture photos and videos)
|
||||
# * "microphone" (to capture audio)
|
||||
permissions = ["files"]
|
||||
|
||||
# Optional link to documentation, support, source files, etc
|
||||
website = "https://omoolab.github.io/BioxelNodes/latest"
|
||||
|
||||
# Optional list defined by Blender and server, see:
|
||||
# https://docs.blender.org/manual/en/dev/extensions/tags.html
|
||||
tags = ["Geometry Nodes", "Render", "Material"]
|
||||
|
||||
blender_version_min = "4.2.0"
|
||||
# Optional: maximum supported Blender version
|
||||
# blender_version_max = "5.1.0"
|
||||
|
||||
# License conforming to https://spdx.org/licenses/ (use "SPDX: prefix)
|
||||
# https://docs.blender.org/manual/en/dev/extensions/licenses.html
|
||||
license = ["SPDX:MIT"]
|
||||
# Optional: required by some licenses.
|
||||
copyright = ["2024 OmooLab"]
|
||||
|
||||
# Optional list of supported platforms. If omitted, the extension will be available in all operating systems.
|
||||
platforms = ["windows-amd64", "macos-x86_64"]
|
||||
# Other supported platforms: "windows-arm64", "macos-x86_64"
|
||||
|
||||
# TODO: externalpackage to wheels
|
||||
# Optional: bundle 3rd party Python modules.
|
||||
# https://docs.blender.org/manual/en/dev/extensions/python_wheels.html
|
||||
wheels = [
|
||||
"./wheels/SimpleITK-2.3.1-cp311-cp311-win_amd64.whl",
|
||||
"./wheels/SimpleITK-2.3.1-cp311-cp311-macosx_11_0_arm64.whl",
|
||||
]
|
||||
|
||||
# Optional: build setting.
|
||||
# https://docs.blender.org/manual/en/dev/extensions/command_line_arguments.html#command-line-args-extension-build
|
||||
# [build]
|
||||
# paths_exclude_pattern = [
|
||||
# "/.git/"
|
||||
# "__pycache__/"
|
||||
# ]
|
||||
23
extension/preferences.py
Normal file
@@ -0,0 +1,23 @@
|
||||
import bpy
|
||||
from pathlib import Path
|
||||
|
||||
class BioxelNodesPreferences(bpy.types.AddonPreferences):
|
||||
bl_idname = __package__
|
||||
|
||||
cache_dir: bpy.props.StringProperty(
|
||||
name="Set Cache Directory",
|
||||
subtype='DIR_PATH',
|
||||
default=str(Path(Path.home(), '.bioxelnodes'))
|
||||
) # type: ignore
|
||||
|
||||
do_change_render_setting: bpy.props.BoolProperty(
|
||||
name="Change Render Setting",
|
||||
default=True,
|
||||
) # type: ignore
|
||||
|
||||
def draw(self, context):
|
||||
layout = self.layout
|
||||
|
||||
layout.label(text="Configuration")
|
||||
layout.prop(self, 'cache_dir')
|
||||
layout.prop(self, "do_change_render_setting")
|
||||
13
mkdocs.yml
@@ -8,11 +8,11 @@ repo_url: https://github.com/OmooLab/BioxelNodes
|
||||
|
||||
nav:
|
||||
- BioxelNodes:
|
||||
- index.md
|
||||
- Getting Started: getting-started.md
|
||||
- Features & Options: features.md
|
||||
- Geometry Nodes: nodes.md
|
||||
- Future Features: misc.md
|
||||
- index.md
|
||||
- Getting Started: getting-started.md
|
||||
- Features & Options: features.md
|
||||
- Nodes: nodes.md
|
||||
- Future Features: misc.md
|
||||
|
||||
theme:
|
||||
name: material
|
||||
@@ -57,6 +57,7 @@ theme:
|
||||
extra:
|
||||
version:
|
||||
provider: mike
|
||||
default: latest
|
||||
|
||||
extra_css:
|
||||
- stylesheets/extra.css
|
||||
@@ -68,6 +69,8 @@ plugins:
|
||||
- mkdocstrings
|
||||
|
||||
markdown_extensions:
|
||||
- attr_list
|
||||
- md_in_html
|
||||
- mkdocs-click
|
||||
- admonition
|
||||
- pymdownx.highlight:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "bioxelnodes"
|
||||
version = "0.1.1"
|
||||
version = "0.2.2"
|
||||
description = ""
|
||||
authors = ["Ma Nan <icrdr2010@outlook.com>"]
|
||||
license = "MIT"
|
||||
|
||||