diff --git a/README.md b/README.md index 68481a1..fde3373 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ Below are some examples with Bioxel Nodes. Thanks to Cycles Render, the volumetr ![gallery](docs/assets/gallery.png) -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 @@ -41,5 +41,18 @@ The "Bioxel" in "BioxelNodes", is a combination of the words "Bio-" and "Voxel". # 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. diff --git a/bioxelnodes/__init__.py b/bioxelnodes/__init__.py index 999d860..7c982eb 100644 --- a/bioxelnodes/__init__.py +++ b/bioxelnodes/__init__.py @@ -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="//" ) diff --git a/bioxelnodes/assets/Nodes/BioxelNodes_4.0.blend b/bioxelnodes/assets/Nodes/BioxelNodes_4.0.blend index b938d23..fe2f780 100644 --- a/bioxelnodes/assets/Nodes/BioxelNodes_4.0.blend +++ b/bioxelnodes/assets/Nodes/BioxelNodes_4.0.blend @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:62d5d5bc44343f9bca7d73c6b447661720a5b2de0be4cd5fafeeb204dc32e886 -size 1635596 +oid sha256:b77277826c07703a1df84a4831e6c381591253a43b4ec9939232a5eeb0eb3998 +size 4849415 diff --git a/bioxelnodes/assets/Nodes/BioxelNodes_4.1.blend b/bioxelnodes/assets/Nodes/BioxelNodes_4.1.blend index 70cc114..b2eaa79 100644 --- a/bioxelnodes/assets/Nodes/BioxelNodes_4.1.blend +++ b/bioxelnodes/assets/Nodes/BioxelNodes_4.1.blend @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:d6832d20cb556ff904cfd7c5574b048ea54011cb531fe6423c4689186de2c8aa -size 1749214 +oid sha256:175a8dfa1fa2e77f3491df8261868fe96a4fc262763c2f649b9727526995984b +size 4176434 diff --git a/bioxelnodes/convert.py b/bioxelnodes/convert.py deleted file mode 100644 index 42b3162..0000000 --- a/bioxelnodes/convert.py +++ /dev/null @@ -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'} diff --git a/bioxelnodes/customnodes/menus.py b/bioxelnodes/customnodes/menus.py index eac702f..dfd93f8 100644 --- a/bioxelnodes/customnodes/menus.py +++ b/bioxelnodes/customnodes/menus.py @@ -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) @@ -169,7 +172,7 @@ class CustomNodes(): op.node_callback = item.get('node_callback') or "" return op.add_node(node_tree) else: - raise RuntimeError("No custom node type found.") + raise RuntimeError("Not found in menu.") def register(self): for cls in self.menu_classes: diff --git a/bioxelnodes/io.py b/bioxelnodes/io.py index 4a3fea0..f885943 100644 --- a/bioxelnodes/io.py +++ b/bioxelnodes/io.py @@ -6,16 +6,18 @@ 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 + from .nodes import custom_nodes from .props import BIOXELNODES_Series +from .utils import (calc_bbox_verts, 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 +33,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 +53,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 +134,31 @@ 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() # type: ignore + layer_name: bpy.props.StringProperty() # type: ignore + series_id: bpy.props.StringProperty() # type: ignore resample_method: bpy.props.EnumProperty( @@ -163,6 +169,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 +178,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 +196,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,20 +213,20 @@ class ImportVolumeDataDialog(bpy.types.Operator): ) # type: ignore def execute(self, context): - image, bioxels_name = read_image(self.filepath, self.series_id) - + 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": @@ -254,11 +257,11 @@ class ImportVolumeDataDialog(bpy.types.Operator): 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 +284,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 +320,237 @@ 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') + node_type = 'BioxelNodes_AsLabel' if layer_type == "label" else 'BioxelNodes_AsScalar' + source_node = custom_nodes.add_node(nodes, node_type) - segment_node.inputs['Threshold'].default_value = bioxels_default_threshold + links.new(input_node.outputs[0], source_node.inputs[0]) + links.new(source_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]) + source_node.inputs['Bioxel Size'].default_value = bioxel_size + source_node.inputs['Shape'].default_value = layer_shape + source_node.inputs['Origin'].default_value = layer_origin + source_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 + source_node = layer_node_tree.nodes['BioxelNodes_AsScalar'] + source_node.inputs['Offset'].default_value = scalar_offset + source_node.inputs['Max'].default_value = orig_max + source_node.inputs['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: 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) 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 +558,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 +585,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 +611,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 +695,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 +719,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 +729,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 +773,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() diff --git a/bioxelnodes/menus.py b/bioxelnodes/menus.py index 82d3c65..e1c937e 100644 --- a/bioxelnodes/menus.py +++ b/bioxelnodes/menus.py @@ -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) diff --git a/bioxelnodes/misc.py b/bioxelnodes/misc.py index 5ef4b00..9d3d1db 100644 --- a/bioxelnodes/misc.py +++ b/bioxelnodes/misc.py @@ -1,97 +1,86 @@ import bpy from pathlib import Path import shutil -from bioxelnodes.utils import get_all_bioxels_objs, get_bioxels_obj +from bioxelnodes.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) diff --git a/bioxelnodes/nodes.py b/bioxelnodes/nodes.py index 74729f2..899b1b3 100644 --- a/bioxelnodes/nodes.py +++ b/bioxelnodes/nodes.py @@ -38,112 +38,311 @@ 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': 'Slicers', + 'icon': 'MOD_BEVEL', + 'items': [ + { + 'label': 'Apply Slicers', + 'icon': 'MOD_BEVEL', + 'node_type': 'BioxelNodes_ApplySlicers', + 'node_description': '' + }, + "separator", + { + 'label': 'Plane Slicer', + 'icon': 'MOD_LATTICE', + 'node_type': 'BioxelNodes_PlaneSlicer', + 'node_description': '', + }, + { + 'label': 'Object Plane Slicer', + 'icon': 'OUTLINER_OB_LATTICE', + 'node_type': 'BioxelNodes_ObjectPlaneSlicer', + 'node_description': '', + } + ] + }, + { + 'label': 'Utils', + 'icon': 'MODIFIER', + 'items': [ + { + 'label': 'Join Component', + 'icon': 'CONSTRAINT_BONE', + 'node_type': 'BioxelNodes_JoinComponent', + 'node_description': '' + }, + { + 'label': 'Separate Component', + 'node_type': 'BioxelNodes_SeparateComponent', + 'node_description': '' + } + ] + }, + { + 'label': 'Others', + 'icon': 'PACKAGE', + 'items': [ + { + 'label': 'Source As Label', + 'icon': 'GP_SELECT_POINTS', + 'node_type': 'BioxelNodes_AsLabel', + 'node_description': '' + }, + { + 'label': 'Source As Scalar', + 'icon': 'GP_SELECT_STROKES', + 'node_type': 'BioxelNodes_AsScalar', + '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': 'Slicers', + 'icon': 'MOD_BEVEL', + 'items': [ + { + 'label': 'Apply Slicers', + 'icon': 'MOD_BEVEL', + 'node_type': 'BioxelNodes_ApplySlicers', + 'node_description': '' + }, + "separator", + { + 'label': 'Plane Slicer', + 'icon': 'MOD_LATTICE', + 'node_type': 'BioxelNodes_PlaneSlicer', + 'node_description': '', + }, + { + 'label': 'Object Plane Slicer', + 'icon': 'OUTLINER_OB_LATTICE', + 'node_type': 'BioxelNodes_ObjectPlaneSlicer', + 'node_description': '', + } + ] + }, + { + 'label': 'Utils', + 'icon': 'MODIFIER', + 'items': [ + { + 'label': 'Join Component', + 'icon': 'CONSTRAINT_BONE', + 'node_type': 'BioxelNodes_JoinComponent', + 'node_description': '' + }, + { + 'label': 'Separate Component', + 'node_type': 'BioxelNodes_SeparateComponent', + 'node_description': '' + } + ] + }, + { + 'label': 'Others', + 'icon': 'PACKAGE', + 'items': [ + { + 'label': 'Source As Label', + 'icon': 'GP_SELECT_POINTS', + 'node_type': 'BioxelNodes_AsLabel', + 'node_description': '' + }, + { + 'label': 'Source As Scalar', + 'icon': 'GP_SELECT_STROKES', + 'node_type': 'BioxelNodes_AsScalar', + 'node_description': '' + } + ] + } + ] + custom_nodes = CustomNodes( menu_items=MENU_ITEMS, diff --git a/bioxelnodes/operators.py b/bioxelnodes/operators.py new file mode 100644 index 0000000..c842f8d --- /dev/null +++ b/bioxelnodes/operators.py @@ -0,0 +1,188 @@ +from pathlib import Path +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": + layers.append(bpy.data.objects[self.scalar_layer]) + + if self.label_layer != "None": + layers.append(bpy.data.objects[self.label_layer]) + + # if self.color_layer: + # layers.append(bpy.data.objects[self.color_layer]) + + 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 + bpy.ops.object.modifier_add(type='NODES') + joined_layer.modifiers[0].node_group = base_layer.modifiers[0].node_group + + # 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 + + 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["Copy Transforms"].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'} diff --git a/bioxelnodes/preferences.py b/bioxelnodes/preferences.py index 7972589..e239a0c 100644 --- a/bioxelnodes/preferences.py +++ b/bioxelnodes/preferences.py @@ -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, @@ -33,4 +28,3 @@ class BioxelNodesPreferences(bpy.types.AddonPreferences, ExternalPackagePreferen layout.prop(self, 'cache_dir') layout.prop(self, "do_change_render_setting") - layout.prop(self, "do_add_segmentnode") diff --git a/bioxelnodes/utils.py b/bioxelnodes/utils.py index cbd5d0d..e563104 100644 --- a/bioxelnodes/utils.py +++ b/bioxelnodes/utils.py @@ -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 + else: + return None + + +def get_layer(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): diff --git a/docs/getting-started.md b/docs/getting-started.md index 3ae1ff5..c433390 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -60,4 +60,4 @@ The VDB cache and the Bioxel nodes are not reachable to computers if you don't s ![before sharin](assets/before-sharing.png) -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. \ No newline at end of file +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 Bioxel Nodes installed. \ No newline at end of file diff --git a/docs/index.md b/docs/index.md index 2c01e8c..4eb71fb 100644 --- a/docs/index.md +++ b/docs/index.md @@ -17,7 +17,7 @@ Below are some examples with Bioxel Nodes. Thanks to Cycles Render, the volumetr ![gallery](assets/gallery.png) -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. 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) # Supported Format diff --git a/pyproject.toml b/pyproject.toml index b8e4f2d..2e8fcf8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "bioxelnodes" -version = "0.1.1" +version = "0.2.0" description = "" authors = ["Ma Nan "] license = "MIT"