2025-12-01

This commit is contained in:
2026-03-17 14:58:51 -06:00
parent 183e865f8b
commit 4b82b57113
6846 changed files with 954887 additions and 162606 deletions
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -4,11 +4,14 @@
# SPDX-License-Identifier: GPL-2.0-or-later
__author__ = "Sebastian Sille <nrgsille@gmail.com>"
__version__ = "2.8.3"
__author__ = "Sebastian Sille <getmore@nrgsille.com>"
__version__ = "3.0.1"
__date__ = "24 Sep 2020"
import bpy
from . import import_3ds
from . import export_3ds
from bpy_extras.io_utils import (
ImportHelper,
ExportHelper,
@@ -23,7 +26,11 @@ from bpy.props import (
StringProperty,
CollectionProperty,
)
import bpy
from bpy.types import (
Operator,
FileHandler,
)
if "bpy" in locals():
import importlib
@@ -34,7 +41,7 @@ if "bpy" in locals():
@orientation_helper(axis_forward='Y', axis_up='Z')
class Import3DS(bpy.types.Operator, ImportHelper):
class Import3DS(Operator, ImportHelper):
"""Import from 3DS file format (.3ds)"""
bl_idname = "import_scene.max3ds"
bl_label = 'Import 3DS'
@@ -106,7 +113,6 @@ class Import3DS(bpy.types.Operator, ImportHelper):
import_transform(layout, self)
def execute(self, context):
from . import import_3ds
keywords = self.as_keywords(ignore=("axis_forward",
"axis_up",
"filter_glob",
@@ -129,14 +135,14 @@ def import_include(layout, operator):
line = body.row(align=True)
line.prop(operator, "use_image_search")
line.label(text="", icon='OUTLINER_OB_IMAGE' if operator.use_image_search else 'IMAGE_DATA')
line = body.row(align=True)
line.prop(operator, "use_collection")
line.label(text="", icon='OUTLINER_COLLECTION' if operator.use_collection else 'GROUP')
body.column().prop(operator, "object_filter")
line = body.row(align=True)
line.prop(operator, "use_keyframes")
line.label(text="", icon='ANIM' if operator.use_keyframes else 'DECORATE_DRIVER')
line = body.row(align=True)
line.prop(operator, "use_collection")
line.label(text="", icon='OUTLINER_COLLECTION' if operator.use_collection else 'GROUP')
line = body.row(align=True)
line.prop(operator, "use_cursor")
line.label(text="", icon='PIVOT_CURSOR' if operator.use_cursor else 'CURSOR')
@@ -157,7 +163,7 @@ def import_transform(layout, operator):
@orientation_helper(axis_forward='Y', axis_up='Z')
class Export3DS(bpy.types.Operator, ExportHelper):
class Export3DS(Operator, ExportHelper):
"""Export to 3DS file format (.3ds)"""
bl_idname = "export_scene.max3ds"
bl_label = 'Export 3DS'
@@ -183,6 +189,11 @@ class Export3DS(bpy.types.Operator, ExportHelper):
description="Take the scene unit length settings into account",
default=False,
)
use_images: BoolProperty(
name="Images",
description="Export all associated images from the scene",
default=True,
)
use_selection: BoolProperty(
name="Selection",
description="Export selected objects only",
@@ -200,11 +211,16 @@ class Export3DS(bpy.types.Operator, ExportHelper):
description="Object types to export",
default={'WORLD', 'MESH', 'LIGHT', 'CAMERA', 'EMPTY', 'OTHER'},
)
use_apply_transform: bpy.props.BoolProperty(
use_apply_transform: BoolProperty(
name="Apply Transform",
description="Apply matrix transform before export",
default=True,
)
use_invisible: BoolProperty(
name="Invisible",
description="Export invisible objects",
default=False,
)
use_keyframes: BoolProperty(
name="Animation",
description="Write the keyframe data",
@@ -237,7 +253,6 @@ class Export3DS(bpy.types.Operator, ExportHelper):
export_transform(layout, self)
def execute(self, context):
from . import export_3ds
keywords = self.as_keywords(ignore=("axis_forward",
"axis_up",
"filter_glob",
@@ -255,10 +270,19 @@ def export_include(layout, operator, browser):
header, body = layout.panel("MAX3DS_export_include", default_closed=False)
header.label(text="Include")
if body:
line = body.row(align=True)
line.prop(operator, "use_images")
line.label(text="", icon='OUTLINER_OB_IMAGE' if operator.use_images else 'IMAGE_DATA')
line = body.row(align=True)
line.prop(operator, "use_invisible")
line.label(text="", icon='HIDE_OFF' if operator.use_invisible else 'HIDE_ON')
line = body.row(align=True)
line.prop(operator, "use_selection")
line.label(text="", icon='RESTRICT_SELECT_OFF' if operator.use_selection else 'RESTRICT_SELECT_ON')
if browser:
line = body.row(align=True)
line.prop(operator, "use_selection")
line.label(text="", icon='RESTRICT_SELECT_OFF' if operator.use_selection else 'RESTRICT_SELECT_ON')
line.prop(operator, "use_collection")
line.label(text="", icon='OUTLINER_COLLECTION' if operator.use_collection else 'GROUP')
body.column().prop(operator, "object_filter")
line = body.row(align=True)
line.prop(operator, "use_keyframes")
@@ -266,10 +290,6 @@ def export_include(layout, operator, browser):
line = body.row(align=True)
line.prop(operator, "use_hierarchy")
line.label(text="", icon='OUTLINER' if operator.use_hierarchy else 'CON_CHILDOF')
if browser:
line = body.row(align=True)
line.prop(operator, "use_collection")
line.label(text="", icon='OUTLINER_COLLECTION' if operator.use_collection else 'GROUP')
line = body.row(align=True)
line.prop(operator, "use_cursor")
line.label(text="", icon='PIVOT_CURSOR' if operator.use_cursor else 'CURSOR')
@@ -290,7 +310,7 @@ def export_transform(layout, operator):
body.prop(operator, "axis_up")
class IO_FH_max3ds(bpy.types.FileHandler):
class IO_FH_max3ds(FileHandler):
bl_idname = "IO_FH_max3ds"
bl_label = "3DS"
bl_import_operator = "import_scene.max3ds"
@@ -1,7 +1,7 @@
schema_version = "1.0.0"
id = "autodesk_3ds_format"
name = "Autodesk 3D Studio (.3ds)"
version = "2.8.3"
version = "3.0.1"
tagline = "Import-Export 3DS scenes, objects, cameras, lights & animations"
maintainer = "Sebastian Sille"
type = "add-on"
@@ -10,9 +10,9 @@ blender_version_min = "4.2.0"
license = ["SPDX:GPL-3.0-or-later"]
website = "https://projects.blender.org/extensions/io_scene_3ds"
copyright = [
"2024 Bob Holcomb",
"2024 Campbell Barton",
"2024 Sebastian Schrand",
"2005 Bob Holcomb",
"2011 Campbell Barton",
"2020 Sebastian Schrand",
]
[permissions]
files = "Import-Export Autodesk 3DS files"
@@ -8,12 +8,14 @@ Exporting is based on 3ds loader from www.gametutorials.com(Thanks DigiBen) and
from the lib3ds project (http://lib3ds.sourceforge.net/) sourcecode.
"""
import os
import bpy
import time
import math
import struct
import mathutils
import bpy_extras
from pathlib import Path
from bpy_extras import node_shader_utils
###################
@@ -538,7 +540,7 @@ def get_material_image(material):
def get_uv_image(ma):
""" Get image from material wrapper."""
if ma and ma.use_nodes:
if ma and hasattr(ma, "use_nodes") and ma.use_nodes:
mat_wrap = node_shader_utils.PrincipledBSDFWrapper(ma)
mat_tex = mat_wrap.base_color_texture
if mat_tex and mat_tex.image is not None:
@@ -547,16 +549,28 @@ def get_uv_image(ma):
return get_material_image(ma)
def save_image(img, path):
""" Save image to destination filepath."""
if img and path is not None:
img_name = Path(img.filepath).name
file_path = os.path.join(path, img_name)
if not os.path.isfile(file_path):
try:
img.save(filepath=file_path)
except Exception as exc:
print("%s - Image %s not exported." % (exc, img_name))
def make_material_subchunk(chunk_id, color):
"""Make a material subchunk.
Used for color subchunks, such as diffuse color or ambient color subchunks."""
mat_sub = _3ds_chunk(chunk_id)
col1 = _3ds_chunk(RGB1)
col1.add_variable("color1", _3ds_rgb_color(color))
col1.add_variable("color1", _3ds_rgb_color(clamp_values(color, 0.0, 1.0)))
mat_sub.add_subchunk(col1)
# Optional
# col2 = _3ds_chunk(RGBI)
# col2.add_variable("color2", _3ds_rgb_color(color))
# col2.add_variable("color2", _3ds_rgb_color(clamp_values(color, 0.0, 1.0)))
# mat_sub.add_subchunk(col2)
return mat_sub
@@ -574,7 +588,6 @@ def make_percent_subchunk(chunk_id, percent):
return pct_sub
def make_mapping_chunks(tex_chunk, scale, translation, rotation):
"""Make Material Map mapping chunks."""
@@ -599,7 +612,7 @@ def make_mapping_chunks(tex_chunk, scale, translation, rotation):
tex_chunk.add_subchunk(tex_map_angle)
def make_texture_chunk(chunk_id, teximages, texmixer, pct, mapnode=None):
def make_texture_chunk(chunk_id, teximages, path=None, mapnode=None, pct=1, texmixer=False):
"""Make Material Map texture chunk."""
# Add texture percentage value (100 = 1.0)
mat_sub = make_percent_subchunk(chunk_id, pct)
@@ -627,7 +640,7 @@ def make_texture_chunk(chunk_id, teximages, texmixer, pct, mapnode=None):
make_mapping_chunks(mat_sub, mapnode.inputs[3].default_value, mapnode.inputs[1].default_value, mapnode.inputs[2].default_value)
if texmixer: # Add tint color
tint = (1.0, 1.0, 1.0)
tint = (0.0, 0.0, 0.0)
tint1 = _3ds_chunk(MAP_COL1)
tint2 = _3ds_chunk(MAP_COL2)
input1 = next((ip.default_value for ip in texmixer.inputs if ip.identifier in {'Color1', 'A_Color'}), tint)
@@ -637,10 +650,13 @@ def make_texture_chunk(chunk_id, teximages, texmixer, pct, mapnode=None):
mat_sub.add_subchunk(tint1)
mat_sub.add_subchunk(tint2)
for tex in teximages:
extend = tex.extension
add_image(tex.image, extend)
has_entry = True
if bool(teximages):
for tex in teximages:
if tex.image is not None:
extend = tex.extension
save_image(tex.image, path)
add_image(tex.image, extend)
has_entry = True
return mat_sub if has_entry else None
@@ -697,7 +713,7 @@ def make_material_texture_chunk(chunk_id, texslots, pct):
make_mapping_chunks(mat_sub, texslot.scale, texslot.translation, texslot.rotation)
if texslot.socket_dst.identifier == 'Specular Tint': # Add tint color
if texslot.socket_dst.identifier in {'Metallic', 'Roughness', 'Specular Tint'}: # Add tint color
tint1 = _3ds_chunk(MAP_COL1)
tint2 = _3ds_chunk(MAP_COL2)
color1 = clamp_values(texslot.node_dst.inputs['Coat Tint'].default_value[:3], 0.0, 1.0)
@@ -717,7 +733,7 @@ def make_material_texture_chunk(chunk_id, texslots, pct):
return mat_sub if has_entry else None
def make_material_chunk(material, image):
def make_material_chunk(material, image, path):
"""Make a material chunk out of a blender material.
Shading method is required for 3ds max, 0 for wireframe.
0x1 for flat, 0x2 for gouraud, 0x3 for phong and 0x4 for metal."""
@@ -738,7 +754,7 @@ def make_material_chunk(material, image):
material_chunk.add_subchunk(make_percent_subchunk(MATSHIN2, 0.5))
material_chunk.add_subchunk(shading)
elif material and material.use_nodes:
elif material and material.node_tree:
wrap = node_shader_utils.PrincipledBSDFWrapper(material)
shading.add_variable("shading", _3ds_ushort(3)) # Phong shading
material_chunk.add_subchunk(make_material_subchunk(MATAMBIENT, wrap.emission_color[:3]))
@@ -771,12 +787,13 @@ def make_material_chunk(material, image):
primary_map = wrap.base_color_texture.node_mapping
matmap = make_material_texture_chunk(MAT_DIFFUSEMAP, color, c_pct)
if matmap:
save_image(image, path)
material_chunk.add_subchunk(matmap)
primary_tex = True
if mxtex and not primary_tex:
primary_map = next((lk.from_node for lk in mtlks if lk.from_node.type == 'MAPPING' and lk.to_node.name == mxtex[0].name), None)
material_chunk.add_subchunk(make_texture_chunk(MAT_DIFFUSEMAP, mxtex, mixer, mxpct, primary_map))
material_chunk.add_subchunk(make_texture_chunk(MAT_DIFFUSEMAP, mxtex, path, primary_map, mxpct, mixer))
primary_tex = True
if wrap.specular_tint_texture:
@@ -784,6 +801,7 @@ def make_material_chunk(material, image):
s_pct = material.specular_intensity
matmap = make_material_texture_chunk(MAT_SPECMAP, spec, s_pct)
if matmap:
save_image(wrap.specular_tint_texture.image, path)
material_chunk.add_subchunk(matmap)
if wrap.alpha_texture:
@@ -791,6 +809,7 @@ def make_material_chunk(material, image):
a_pct = material.diffuse_color[3]
matmap = make_material_texture_chunk(MAT_OPACMAP, alpha, a_pct)
if matmap:
save_image(wrap.alpha_texture.image, path)
material_chunk.add_subchunk(matmap)
if wrap.metallic_texture:
@@ -798,6 +817,7 @@ def make_material_chunk(material, image):
m_pct = material.metallic
matmap = make_material_texture_chunk(MAT_REFLMAP, metallic, m_pct)
if matmap:
save_image(wrap.metallic_texture.image, path)
material_chunk.add_subchunk(matmap)
if wrap.normalmap_texture:
@@ -806,6 +826,7 @@ def make_material_chunk(material, image):
primary_map = wrap.normalmap_texture.node_mapping
matmap = make_material_texture_chunk(MAT_BUMPMAP, normal, b_pct)
if matmap:
save_image(wrap.normalmap_texture.image, path)
material_chunk.add_subchunk(matmap)
material_chunk.add_subchunk(make_percent_subchunk(MAT_BUMP_PERCENT, b_pct))
@@ -814,6 +835,7 @@ def make_material_chunk(material, image):
r_pct = 1 - material.roughness
matmap = make_material_texture_chunk(MAT_SHINMAP, roughness, r_pct)
if matmap:
save_image(wrap.roughness_texture.image, path)
material_chunk.add_subchunk(matmap)
if wrap.emission_color_texture:
@@ -821,6 +843,7 @@ def make_material_chunk(material, image):
e_pct = wrap.emission_strength
matmap = make_material_texture_chunk(MAT_SELFIMAP, emission, e_pct)
if matmap:
save_image(wrap.emission_color_texture.image, path)
material_chunk.add_subchunk(matmap)
if wrap.transmission_texture:
@@ -828,18 +851,21 @@ def make_material_chunk(material, image):
t_pct = wrap.transmission
matmap = make_material_texture_chunk(MAT_OPACMASK, transmission, t_pct)
if matmap:
save_image(wrap.transmission_texture.image, path)
material_chunk.add_subchunk(matmap)
if wrap.specular_texture:
specular = [wrap.specular_texture]
matmap = make_material_texture_chunk(MAT_SPECMASK, specular, 1)
if matmap:
save_image(wrap.specular_texture.image, path)
material_chunk.add_subchunk(matmap)
if wrap.emission_strength_texture:
luminous = [wrap.emission_strength_texture]
matmap = make_material_texture_chunk(MAT_SELFIMASK, luminous, 1)
if matmap:
save_image(wrap.emission_strength_texture.image, path)
material_chunk.add_subchunk(matmap)
matmap = diffmask = normalmask = shinmask = reflmask = None
@@ -852,15 +878,15 @@ def make_material_chunk(material, image):
sheenmask = link.from_node if link.from_node.type == tximg and link.to_socket.identifier == 'Sheen Weight' else None
coatmask = link.from_node if link.from_node.type == tximg and link.to_socket.identifier == 'Coat Weight' else None
if secondary:
matmap = make_texture_chunk(MAT_TEX2MAP, [secondary], mixer, 1 - mxpct, primary_map)
matmap = make_texture_chunk(MAT_TEX2MAP, [secondary], path, primary_map, 1 - mxpct, mixer)
if texmask:
diffmask = make_texture_chunk(MAT_TEXMASK, [texmask], False, mxpct, primary_map)
diffmask = make_texture_chunk(MAT_TEXMASK, [texmask], path, primary_map, mxpct)
if bumpmask:
normalmask = make_texture_chunk(MAT_BUMPMASK, [bumpmask], False, 1, primary_map)
normalmask = make_texture_chunk(MAT_BUMPMASK, [bumpmask], path, primary_map)
if sheenmask:
shinmask = make_texture_chunk(MAT_SHINMASK, [sheenmask], False, 1)
shinmask = make_texture_chunk(MAT_SHINMASK, [sheenmask], path)
if coatmask:
reflmask = make_texture_chunk(MAT_REFLMASK, [coatmask], False, 1)
reflmask = make_texture_chunk(MAT_REFLMASK, [coatmask], path)
if primary_tex and matmap:
material_chunk.add_subchunk(matmap)
if diffmask:
@@ -886,6 +912,7 @@ def make_material_chunk(material, image):
slots = [get_material_image(material)] # Can be None
if image:
save_image(image, path)
material_chunk.add_subchunk(make_texture_chunk(MAT_DIFFUSEMAP, slots))
return material_chunk
@@ -1198,108 +1225,108 @@ def make_track_chunk(ID, ob, ob_pos, ob_rot, ob_size, ob_mtx):
a position, rotation, scale, roll, color, fov, hotspot or falloff track."""
track_chunk = _3ds_chunk(ID)
if ID in {POS_TRACK_TAG, ROT_TRACK_TAG, SCL_TRACK_TAG, ROLL_TRACK_TAG} and ob.animation_data and ob.animation_data.action:
if (ID in {POS_TRACK_TAG, ROT_TRACK_TAG, SCL_TRACK_TAG, ROLL_TRACK_TAG} and
ob.animation_data and ob.animation_data.action and ob.animation_data.action.fcurves):
action = ob.animation_data.action
if action.fcurves:
fcurves = action.fcurves
kframes = [kf.co[0] for kf in [fc for fc in fcurves if fc is not None][0].keyframe_points]
nkeys = len(kframes)
if not 0 in kframes:
kframes.append(0)
nkeys += 1
kframes = sorted(set(kframes))
track_chunk.add_variable("track_flags", _3ds_ushort(0x40))
track_chunk.add_variable("frame_start", _3ds_uint(int(action.frame_start)))
track_chunk.add_variable("frame_total", _3ds_uint(int(action.frame_end)))
track_chunk.add_variable("nkeys", _3ds_uint(nkeys))
fcurves = action.fcurves
kframes = [kf.co[0] for kf in [fc for fc in fcurves if fc is not None][0].keyframe_points]
nkeys = len(kframes)
if not 0 in kframes:
kframes.append(0)
nkeys += 1
kframes = sorted(set(kframes))
track_chunk.add_variable("track_flags", _3ds_ushort(0x40))
track_chunk.add_variable("frame_start", _3ds_uint(int(action.frame_start)))
track_chunk.add_variable("frame_total", _3ds_uint(int(action.frame_end)))
track_chunk.add_variable("nkeys", _3ds_uint(nkeys))
if ID == POS_TRACK_TAG: # Position
for i, frame in enumerate(kframes):
pos_track = [fc for fc in fcurves if fc is not None and fc.data_path == 'location']
pos_x = next((tc.evaluate(frame) for tc in pos_track if tc.array_index == 0), ob_pos.x)
pos_y = next((tc.evaluate(frame) for tc in pos_track if tc.array_index == 1), ob_pos.y)
pos_z = next((tc.evaluate(frame) for tc in pos_track if tc.array_index == 2), ob_pos.z)
pos = ob_mtx @ mathutils.Vector((pos_x, pos_y, pos_z))
track_chunk.add_variable("tcb_frame", _3ds_uint(int(frame)))
track_chunk.add_variable("tcb_flags", _3ds_ushort())
track_chunk.add_variable("position", _3ds_point_3d((pos.x, pos.y, pos.z)))
if ID == POS_TRACK_TAG: # Position
for i, frame in enumerate(kframes):
pos_track = [fc for fc in fcurves if fc is not None and fc.data_path == 'location']
pos_x = next((tc.evaluate(frame) for tc in pos_track if tc.array_index == 0), ob_pos.x)
pos_y = next((tc.evaluate(frame) for tc in pos_track if tc.array_index == 1), ob_pos.y)
pos_z = next((tc.evaluate(frame) for tc in pos_track if tc.array_index == 2), ob_pos.z)
pos = ob_mtx @ mathutils.Vector((pos_x, pos_y, pos_z))
track_chunk.add_variable("tcb_frame", _3ds_uint(int(frame)))
track_chunk.add_variable("tcb_flags", _3ds_ushort())
track_chunk.add_variable("position", _3ds_point_3d((pos.x, pos.y, pos.z)))
elif ID == ROT_TRACK_TAG: # Rotation
for i, frame in enumerate(kframes):
rot_track = [fc for fc in fcurves if fc is not None and fc.data_path == 'rotation_euler']
rot_x = next((tc.evaluate(frame) for tc in rot_track if tc.array_index == 0), ob_rot.x)
rot_y = next((tc.evaluate(frame) for tc in rot_track if tc.array_index == 1), ob_rot.y)
rot_z = next((tc.evaluate(frame) for tc in rot_track if tc.array_index == 2), ob_rot.z)
quat = mathutils.Euler((rot_x, rot_y, rot_z)).to_quaternion().inverted()
track_chunk.add_variable("tcb_frame", _3ds_uint(int(frame)))
track_chunk.add_variable("tcb_flags", _3ds_ushort())
track_chunk.add_variable("rotation", _3ds_point_4d((quat.angle, quat.axis.x, quat.axis.y, quat.axis.z)))
elif ID == ROT_TRACK_TAG: # Rotation
for i, frame in enumerate(kframes):
rot_track = [fc for fc in fcurves if fc is not None and fc.data_path == 'rotation_euler']
rot_x = next((tc.evaluate(frame) for tc in rot_track if tc.array_index == 0), ob_rot.x)
rot_y = next((tc.evaluate(frame) for tc in rot_track if tc.array_index == 1), ob_rot.y)
rot_z = next((tc.evaluate(frame) for tc in rot_track if tc.array_index == 2), ob_rot.z)
quat = mathutils.Euler((rot_x, rot_y, rot_z)).to_quaternion().inverted()
track_chunk.add_variable("tcb_frame", _3ds_uint(int(frame)))
track_chunk.add_variable("tcb_flags", _3ds_ushort())
track_chunk.add_variable("rotation", _3ds_point_4d((quat.angle, quat.axis.x, quat.axis.y, quat.axis.z)))
elif ID == SCL_TRACK_TAG: # Scale
for i, frame in enumerate(kframes):
scale_track = [fc for fc in fcurves if fc is not None and fc.data_path == 'scale']
size_x = next((tc.evaluate(frame) for tc in scale_track if tc.array_index == 0), ob_size.x)
size_y = next((tc.evaluate(frame) for tc in scale_track if tc.array_index == 1), ob_size.y)
size_z = next((tc.evaluate(frame) for tc in scale_track if tc.array_index == 2), ob_size.z)
track_chunk.add_variable("tcb_frame", _3ds_uint(int(frame)))
track_chunk.add_variable("tcb_flags", _3ds_ushort())
track_chunk.add_variable("scale", _3ds_point_3d((size_x, size_y, size_z)))
elif ID == SCL_TRACK_TAG: # Scale
for i, frame in enumerate(kframes):
scale_track = [fc for fc in fcurves if fc is not None and fc.data_path == 'scale']
size_x = next((tc.evaluate(frame) for tc in scale_track if tc.array_index == 0), ob_size.x)
size_y = next((tc.evaluate(frame) for tc in scale_track if tc.array_index == 1), ob_size.y)
size_z = next((tc.evaluate(frame) for tc in scale_track if tc.array_index == 2), ob_size.z)
track_chunk.add_variable("tcb_frame", _3ds_uint(int(frame)))
track_chunk.add_variable("tcb_flags", _3ds_ushort())
track_chunk.add_variable("scale", _3ds_point_3d((size_x, size_y, size_z)))
elif ID == ROLL_TRACK_TAG: # Roll
for i, frame in enumerate(kframes):
roll_track = [fc for fc in fcurves if fc is not None and fc.data_path == 'rotation_euler']
roll = next((tc.evaluate(frame) for tc in roll_track if tc.array_index == 1), ob_rot.y)
track_chunk.add_variable("tcb_frame", _3ds_uint(int(frame)))
track_chunk.add_variable("tcb_flags", _3ds_ushort())
track_chunk.add_variable("roll", _3ds_float(round(math.degrees(roll), 4)))
elif ID == ROLL_TRACK_TAG: # Roll
for i, frame in enumerate(kframes):
roll_track = [fc for fc in fcurves if fc is not None and fc.data_path == 'rotation_euler']
roll = next((tc.evaluate(frame) for tc in roll_track if tc.array_index == 1), ob_rot.y)
track_chunk.add_variable("tcb_frame", _3ds_uint(int(frame)))
track_chunk.add_variable("tcb_flags", _3ds_ushort())
track_chunk.add_variable("roll", _3ds_float(round(math.degrees(roll), 4)))
elif ID in {COL_TRACK_TAG, FOV_TRACK_TAG, HOTSPOT_TRACK_TAG, FALLOFF_TRACK_TAG} and ob.data.animation_data and ob.data.animation_data.action:
elif (ID in {COL_TRACK_TAG, FOV_TRACK_TAG, HOTSPOT_TRACK_TAG, FALLOFF_TRACK_TAG} and
ob.data.animation_data and ob.data.animation_data.action and ob.data.animation_data.action.fcurves):
action = ob.data.animation_data.action
if action.fcurves:
fcurves = action.fcurves
kframes = [kf.co[0] for kf in [fc for fc in fcurves if fc is not None][0].keyframe_points]
nkeys = len(kframes)
if not 0 in kframes:
kframes.append(0)
nkeys += 1
kframes = sorted(set(kframes))
track_chunk.add_variable("track_flags", _3ds_ushort(0x40))
track_chunk.add_variable("frame_start", _3ds_uint(int(action.frame_start)))
track_chunk.add_variable("frame_total", _3ds_uint(int(action.frame_end)))
track_chunk.add_variable("nkeys", _3ds_uint(nkeys))
fcurves = action.fcurves
kframes = [kf.co[0] for kf in [fc for fc in fcurves if fc is not None][0].keyframe_points]
nkeys = len(kframes)
if not 0 in kframes:
kframes.append(0)
nkeys += 1
kframes = sorted(set(kframes))
track_chunk.add_variable("track_flags", _3ds_ushort(0x40))
track_chunk.add_variable("frame_start", _3ds_uint(int(action.frame_start)))
track_chunk.add_variable("frame_total", _3ds_uint(int(action.frame_end)))
track_chunk.add_variable("nkeys", _3ds_uint(nkeys))
if ID == COL_TRACK_TAG: # Color
for i, frame in enumerate(kframes):
color = [fc.evaluate(frame) for fc in fcurves if fc is not None and fc.data_path == 'color']
if not color:
color = ob.data.color[:3]
track_chunk.add_variable("tcb_frame", _3ds_uint(int(frame)))
track_chunk.add_variable("tcb_flags", _3ds_ushort())
track_chunk.add_variable("color", _3ds_float_color(color))
if ID == COL_TRACK_TAG: # Color
for i, frame in enumerate(kframes):
color = [fc.evaluate(frame) for fc in fcurves if fc is not None and fc.data_path == 'color']
if not color:
color = ob.data.color[:3]
track_chunk.add_variable("tcb_frame", _3ds_uint(int(frame)))
track_chunk.add_variable("tcb_flags", _3ds_ushort())
track_chunk.add_variable("color", _3ds_float_color(color))
elif ID == FOV_TRACK_TAG: # Field of view
for i, frame in enumerate(kframes):
lens = next((fc.evaluate(frame) for fc in fcurves if fc is not None and fc.data_path == 'lens'), ob.data.lens)
fov = 2 * math.atan(ob.data.sensor_width / (2 * lens))
track_chunk.add_variable("tcb_frame", _3ds_uint(int(frame)))
track_chunk.add_variable("tcb_flags", _3ds_ushort())
track_chunk.add_variable("fov", _3ds_float(round(math.degrees(fov), 4)))
elif ID == FOV_TRACK_TAG: # Field of view
for i, frame in enumerate(kframes):
lens = next((fc.evaluate(frame) for fc in fcurves if fc is not None and fc.data_path == 'lens'), ob.data.lens)
fov = 2 * math.atan(ob.data.sensor_width / (2 * lens))
track_chunk.add_variable("tcb_frame", _3ds_uint(int(frame)))
track_chunk.add_variable("tcb_flags", _3ds_ushort())
track_chunk.add_variable("fov", _3ds_float(round(math.degrees(fov), 4)))
elif ID == HOTSPOT_TRACK_TAG: # Hotspot
for i, frame in enumerate(kframes):
beamsize = next((fc.evaluate(frame) for fc in fcurves if fc is not None and fc.data_path == 'spot_size'), ob.data.spot_size)
blend = next((fc.evaluate(frame) for fc in fcurves if fc is not None and fc.data_path == 'spot_blend'), ob.data.spot_blend)
hot_spot = math.degrees(beamsize) - (blend * math.floor(math.degrees(beamsize)))
track_chunk.add_variable("tcb_frame", _3ds_uint(int(frame)))
track_chunk.add_variable("tcb_flags", _3ds_ushort())
track_chunk.add_variable("hotspot", _3ds_float(round(hot_spot, 4)))
elif ID == HOTSPOT_TRACK_TAG: # Hotspot
for i, frame in enumerate(kframes):
beamsize = next((fc.evaluate(frame) for fc in fcurves if fc is not None and fc.data_path == 'spot_size'), ob.data.spot_size)
blend = next((fc.evaluate(frame) for fc in fcurves if fc is not None and fc.data_path == 'spot_blend'), ob.data.spot_blend)
hot_spot = math.degrees(beamsize) - (blend * math.floor(math.degrees(beamsize)))
track_chunk.add_variable("tcb_frame", _3ds_uint(int(frame)))
track_chunk.add_variable("tcb_flags", _3ds_ushort())
track_chunk.add_variable("hotspot", _3ds_float(round(hot_spot, 4)))
elif ID == FALLOFF_TRACK_TAG: # Falloff
for i, frame in enumerate(kframes):
fall_off = next((fc.evaluate(frame) for fc in fcurves if fc is not None and fc.data_path == 'spot_size'), ob.data.spot_size)
track_chunk.add_variable("tcb_frame", _3ds_uint(int(frame)))
track_chunk.add_variable("tcb_flags", _3ds_ushort())
track_chunk.add_variable("falloff", _3ds_float(round(math.degrees(fall_off), 4)))
elif ID == FALLOFF_TRACK_TAG: # Falloff
for i, frame in enumerate(kframes):
fall_off = next((fc.evaluate(frame) for fc in fcurves if fc is not None and fc.data_path == 'spot_size'), ob.data.spot_size)
track_chunk.add_variable("tcb_frame", _3ds_uint(int(frame)))
track_chunk.add_variable("tcb_flags", _3ds_ushort())
track_chunk.add_variable("falloff", _3ds_float(round(math.degrees(fall_off), 4)))
else:
track_chunk.add_variable("track_flags", _3ds_ushort(0x40)) # Based on observation default flag is 0x40
@@ -1489,34 +1516,33 @@ def make_target_node(ob, name_id, transmtx, position, rotation):
# Add track chunks for target position
track_chunk = _3ds_chunk(POS_TRACK_TAG)
if ob.animation_data and ob.animation_data.action:
if ob.animation_data and ob.animation_data.action and ob.animation_data.action.fcurves:
action = ob.animation_data.action
if action.fcurves:
fcurves = action.fcurves
kframes = [kf.co[0] for kf in [fc for fc in fcurves if fc is not None][0].keyframe_points]
nkeys = len(kframes)
if not 0 in kframes:
kframes.append(0)
nkeys += 1
kframes = sorted(set(kframes))
track_chunk.add_variable("track_flags", _3ds_ushort(0x40))
track_chunk.add_variable("frame_start", _3ds_uint(int(action.frame_start)))
track_chunk.add_variable("frame_total", _3ds_uint(int(action.frame_end)))
track_chunk.add_variable("nkeys", _3ds_uint(nkeys))
fcurves = action.fcurves
kframes = [kf.co[0] for kf in [fc for fc in fcurves if fc is not None][0].keyframe_points]
nkeys = len(kframes)
if not 0 in kframes:
kframes.append(0)
nkeys += 1
kframes = sorted(set(kframes))
track_chunk.add_variable("track_flags", _3ds_ushort(0x40))
track_chunk.add_variable("frame_start", _3ds_uint(int(action.frame_start)))
track_chunk.add_variable("frame_total", _3ds_uint(int(action.frame_end)))
track_chunk.add_variable("nkeys", _3ds_uint(nkeys))
for i, frame in enumerate(kframes):
loc_target = [fc for fc in fcurves if fc is not None and fc.data_path == 'location']
loc_x = next((tc.evaluate(frame) for tc in loc_target if tc.array_index == 0), ob_pos.x)
loc_y = next((tc.evaluate(frame) for tc in loc_target if tc.array_index == 1), ob_pos.y)
loc_z = next((tc.evaluate(frame) for tc in loc_target if tc.array_index == 2), ob_pos.z)
rot_target = [fc for fc in fcurves if fc is not None and fc.data_path == 'rotation_euler']
rot_x = next((tc.evaluate(frame) for tc in rot_target if tc.array_index == 0), ob_rot.x)
rot_z = next((tc.evaluate(frame) for tc in rot_target if tc.array_index == 2), ob_rot.z)
target_distance = ob_mtx @ mathutils.Vector((loc_x, loc_y, loc_z))
target_pos = calc_target(target_distance, rot_x, rot_z)
track_chunk.add_variable("tcb_frame", _3ds_uint(int(frame)))
track_chunk.add_variable("tcb_flags", _3ds_ushort())
track_chunk.add_variable("position", _3ds_point_3d(target_pos))
for i, frame in enumerate(kframes):
loc_target = [fc for fc in fcurves if fc is not None and fc.data_path == 'location']
loc_x = next((tc.evaluate(frame) for tc in loc_target if tc.array_index == 0), ob_pos.x)
loc_y = next((tc.evaluate(frame) for tc in loc_target if tc.array_index == 1), ob_pos.y)
loc_z = next((tc.evaluate(frame) for tc in loc_target if tc.array_index == 2), ob_pos.z)
rot_target = [fc for fc in fcurves if fc is not None and fc.data_path == 'rotation_euler']
rot_x = next((tc.evaluate(frame) for tc in rot_target if tc.array_index == 0), ob_rot.x)
rot_z = next((tc.evaluate(frame) for tc in rot_target if tc.array_index == 2), ob_rot.z)
target_distance = ob_mtx @ mathutils.Vector((loc_x, loc_y, loc_z))
target_pos = calc_target(target_distance, rot_x, rot_z)
track_chunk.add_variable("tcb_frame", _3ds_uint(int(frame)))
track_chunk.add_variable("tcb_flags", _3ds_ushort())
track_chunk.add_variable("position", _3ds_point_3d(target_pos))
else: # Track header
track_chunk.add_variable("track_flags", _3ds_ushort(0x40)) # Based on observation default flag is 0x40
@@ -1553,19 +1579,21 @@ def make_ambient_node(world):
amb_node_header_chunk.add_variable("parent", _3ds_ushort(ROOT_OBJECT))
amb_node.add_subchunk(amb_node_header_chunk)
if world.use_nodes and world.node_tree.animation_data.action:
if world.node_tree and world.node_tree.animation_data.action and world.node_tree.animation_data.action.fcurves:
ambioutput = 'EMISSION' ,'MIX_SHADER', 'WORLD_OUTPUT'
action = world.node_tree.animation_data.action
links = world.node_tree.links
ambilinks = [lk for lk in links if lk.from_node.type in {'EMISSION', 'RGB'} and lk.to_node.type in ambioutput]
if ambilinks and action.fcurves:
if ambilinks:
fcurves = action.fcurves
fcurves.update()
emission = next((lk.from_socket.node for lk in ambilinks if lk.to_node.type in ambioutput), False)
ambinode = next((lk.from_socket.node for lk in ambilinks if lk.to_node.type == 'EMISSION'), emission)
kframes = [kf.co[0] for kf in [fc for fc in fcurves if fc is not None][0].keyframe_points]
ambipath = ('nodes[\"RGB\"].outputs[0].default_value' if ambinode and ambinode.type == 'RGB' else
'nodes[\"Emission\"].inputs[0].default_value')
if ambinode and ambinode.type == 'RGB':
ambipath = f'nodes[\"{ambinode.name}\"].outputs[0].default_value'
else:
ambipath = 'nodes[\"Emission\"].inputs[0].default_value'
nkeys = len(kframes)
if not 0 in kframes:
kframes.append(0)
@@ -1584,29 +1612,28 @@ def make_ambient_node(world):
track_chunk.add_variable("tcb_flags", _3ds_ushort())
track_chunk.add_variable("color", _3ds_float_color(ambient[:3]))
elif world.animation_data.action:
elif world.animation_data.action and world.animation_data.action.fcurves:
action = world.animation_data.action
if action.fcurves:
fcurves = action.fcurves
fcurves.update()
kframes = [kf.co[0] for kf in [fc for fc in fcurves if fc is not None][0].keyframe_points]
nkeys = len(kframes)
if not 0 in kframes:
kframes.append(0)
nkeys += 1
kframes = sorted(set(kframes))
track_chunk.add_variable("track_flags", _3ds_ushort(0x40))
track_chunk.add_variable("frame_start", _3ds_uint(int(action.frame_start)))
track_chunk.add_variable("frame_total", _3ds_uint(int(action.frame_end)))
track_chunk.add_variable("nkeys", _3ds_uint(nkeys))
fcurves = action.fcurves
fcurves.update()
kframes = [kf.co[0] for kf in [fc for fc in fcurves if fc is not None][0].keyframe_points]
nkeys = len(kframes)
if not 0 in kframes:
kframes.append(0)
nkeys += 1
kframes = sorted(set(kframes))
track_chunk.add_variable("track_flags", _3ds_ushort(0x40))
track_chunk.add_variable("frame_start", _3ds_uint(int(action.frame_start)))
track_chunk.add_variable("frame_total", _3ds_uint(int(action.frame_end)))
track_chunk.add_variable("nkeys", _3ds_uint(nkeys))
for i, frame in enumerate(kframes):
ambient = [fc.evaluate(frame) for fc in fcurves if fc is not None and fc.data_path == 'color']
if not ambient:
ambient = amb_color
track_chunk.add_variable("tcb_frame", _3ds_uint(int(frame)))
track_chunk.add_variable("tcb_flags", _3ds_ushort())
track_chunk.add_variable("color", _3ds_float_color(ambient))
for i, frame in enumerate(kframes):
ambient = [fc.evaluate(frame) for fc in fcurves if fc is not None and fc.data_path == 'color']
if not ambient:
ambient = amb_color
track_chunk.add_variable("tcb_frame", _3ds_uint(int(frame)))
track_chunk.add_variable("tcb_flags", _3ds_ushort())
track_chunk.add_variable("color", _3ds_float_color(ambient))
else: # Track header
track_chunk.add_variable("track_flags", _3ds_ushort(0x40))
@@ -1627,45 +1654,25 @@ def make_ambient_node(world):
# EXPORT #
##########
def save(operator, context, filepath="", collection="", scale_factor=1.0, use_scene_unit=False,
use_selection=False, object_filter=None, use_apply_transform=True, use_keyframes=True,
use_hierarchy=False, use_collection=False, global_matrix=None, use_cursor=False):
def save_3ds(context, filepath="", collection="", items=[], scale_factor=1.0, global_matrix=None,
use_selection=False, use_apply_transform=True, object_filter=None, use_invisible=False,
use_images=False, use_keyframes=True, use_hierarchy=False, use_cursor=False):
"""Save the Blender scene to a 3ds file."""
print("exporting 3DS: %r..." % (Path(filepath).name), end="")
image_path = Path(filepath).parent if use_images else None
# Time the export
duration = time.time()
context.window.cursor_set('WAIT')
scene = context.scene
layer = context.view_layer
depsgraph = context.evaluated_depsgraph_get()
items = scene.objects
world = scene.world
unit_measure = 1.0
if use_scene_unit:
unit_length = scene.unit_settings.length_unit
if unit_length == 'MILES':
unit_measure = 0.000621371
elif unit_length == 'KILOMETERS':
unit_measure = 0.001
elif unit_length == 'FEET':
unit_measure = 3.280839895
elif unit_length == 'INCHES':
unit_measure = 39.37007874
elif unit_length == 'CENTIMETERS':
unit_measure = 100
elif unit_length == 'MILLIMETERS':
unit_measure = 1000
elif unit_length == 'THOU':
unit_measure = 39370.07874
elif unit_length == 'MICROMETERS':
unit_measure = 1000000
mtx_scale = mathutils.Matrix.Scale((scale_factor),4)
mtx_scale = mathutils.Matrix.Scale((scale_factor * unit_measure),4)
if use_collection:
items = layer.active_layer_collection.collection.all_objects
elif collection:
if collection and not items:
item_collection = bpy.data.collections.get(collection)
if item_collection:
items = item_collection.all_objects
@@ -1704,7 +1711,7 @@ def save(operator, context, filepath="", collection="", scale_factor=1.0, use_sc
free_objects = []
if object_filter is None:
object_filter = {'WORLD', 'MESH', 'LIGHT', 'CAMERA', 'EMPTY', 'OTHER'}
object_filter = {'MESH', 'LIGHT', 'CAMERA', 'EMPTY', 'OTHER'}
if 'OTHER' in object_filter:
object_filter.remove('OTHER')
@@ -1712,10 +1719,14 @@ def save(operator, context, filepath="", collection="", scale_factor=1.0, use_sc
object_filter.update(OTHERS)
EMPTYS.update(DUMMYS)
if use_selection:
if use_selection and not use_invisible:
objects = [ob for ob in items if ob.type in object_filter and ob.visible_get(view_layer=layer) and ob.select_get(view_layer=layer)]
else:
elif use_selection and use_invisible:
objects = [ob for ob in items if ob.type in object_filter and ob.select_get(view_layer=layer) or not ob.visible_get(view_layer=layer)]
elif not use_selection and not use_invisible:
objects = [ob for ob in items if ob.type in object_filter and ob.visible_get(view_layer=layer)]
else:
objects = [ob for ob in items if ob.type in object_filter]
empty_objects = [ob for ob in objects if ob.type in EMPTYS]
light_objects = [ob for ob in objects if ob.type == 'LIGHT']
@@ -1778,7 +1789,7 @@ def save(operator, context, filepath="", collection="", scale_factor=1.0, use_sc
# Make MATERIAL chunks for all materials used in the meshes
for ma_image in materialDict.values():
object_info.add_subchunk(make_material_chunk(ma_image[0], ma_image[1]))
object_info.add_subchunk(make_material_chunk(ma_image[0], ma_image[1], image_path))
# Add MASTERSCALE element
mscale = _3ds_chunk(MASTERSCALE)
@@ -1800,7 +1811,7 @@ def save(operator, context, filepath="", collection="", scale_factor=1.0, use_sc
object_info.add_subchunk(ambient_chunk)
# Add BACKGROUND and BITMAP
if world.use_nodes:
if world.node_tree and world.node_tree.nodes.get("Background"):
bgtype = 'BACKGROUND'
ntree = world.node_tree.links
background_color_chunk = _3ds_chunk(RGB)
@@ -1817,6 +1828,7 @@ def save(operator, context, filepath="", collection="", scale_factor=1.0, use_sc
background_color_chunk.add_variable("color", _3ds_float_color(bg_color))
background_chunk.add_subchunk(background_color_chunk)
if bg_image and bg_image is not None:
save_image(bg_image, image_path)
background_image = _3ds_chunk(BITMAP)
background_flag = _3ds_chunk(USE_BITMAP)
background_image.add_variable("image", _3ds_string(sane_name(bg_image.name)))
@@ -1962,7 +1974,7 @@ def save(operator, context, filepath="", collection="", scale_factor=1.0, use_sc
if object_chunk.validate():
object_info.add_subchunk(object_chunk)
else:
operator.report({'WARNING'}, "Object %r can't be written into a 3DS file" % ob.name)
print("Object %r can't be written into a 3DS file" % ob.name)
# Export object node
if use_keyframes and not use_hierarchy:
@@ -2041,6 +2053,7 @@ def save(operator, context, filepath="", collection="", scale_factor=1.0, use_sc
bpnode = next((lk.from_node.type for lk in links if lk.from_node.type in bpmix and lk.to_node.type == bshade), bshade)
bitmap = next((lk.from_node.image for lk in links if lk.from_node.type in bptex and lk.to_node.type == bpnode), False)
if bitmap and bitmap is not None:
save_image(bitmap, image_path)
spot_projector_chunk = _3ds_chunk(LIGHT_SPOT_PROJECTOR)
spot_projector_chunk.add_variable("image", _3ds_string(sane_name(bitmap.name)))
spotlight_chunk.add_subchunk(spot_projector_chunk)
@@ -2135,9 +2148,48 @@ def save(operator, context, filepath="", collection="", scale_factor=1.0, use_sc
# Debugging only: report the exporting time
context.window.cursor_set('DEFAULT')
print("3ds export time: %.2f" % (time.time() - duration))
print(" done in %.4f sec." % (time.time() - duration))
# Debugging only: dump the chunk hierarchy
# primary.dump()
def save(operator, context, filepath="", collection="", scale_factor=1.0, use_scene_unit=False, use_images=True,
use_selection=False, object_filter=None, use_apply_transform=True, use_invisible=False, use_keyframes=True,
use_hierarchy=False, use_collection=False, global_matrix=None, use_cursor=False):
unit_measure = 1.0
if use_scene_unit:
unit_length = context.scene.unit_settings.length_unit
if unit_length == 'MILES':
unit_measure = 0.000621371
elif unit_length == 'KILOMETERS':
unit_measure = 0.001
elif unit_length == 'FEET':
unit_measure = 3.280839895
elif unit_length == 'INCHES':
unit_measure = 39.37007874
elif unit_length == 'CENTIMETERS':
unit_measure = 100
elif unit_length == 'MILLIMETERS':
unit_measure = 1000
elif unit_length == 'THOU':
unit_measure = 39370.07874
elif unit_length == 'MICROMETERS':
unit_measure = 1000000
items = context.scene.objects
viewlayer = context.view_layer
master_scale = scale_factor * unit_measure
if use_collection:
items = viewlayer.active_layer_collection.collection.all_objects
elif collection:
item_collection = bpy.data.collections.get(collection)
if item_collection:
items = item_collection.all_objects
save_3ds(context, filepath, collection, items, master_scale, global_matrix, use_selection, use_apply_transform,
object_filter, use_invisible, use_images, use_keyframes, use_hierarchy, use_cursor)
return {'FINISHED'}
@@ -255,7 +255,8 @@ def skip_to_end(file, skip_chunk):
# MATERIALS #
#############
def add_texture_to_material(image, contextWrapper, pct, extend, alpha, scale, offset, angle, tint1, tint2, mapto):
def add_texture_to_material(image, contextWrapper, pct, extend, alpha,
scale, offset, angle, luma, tint1, tint2, mapto):
shader = contextWrapper.node_principled_bsdf
nodetree = contextWrapper.material.node_tree
shader.location = (-300, 0)
@@ -272,9 +273,10 @@ def add_texture_to_material(image, contextWrapper, pct, extend, alpha, scale, of
img_wrap = contextWrapper.base_color_texture
img_wrap.node_mapping.name = 'Diffuse Mapping'
img_wrap.node_image.name = 'Diffuse Texture'
image.alpha_mode = 'CHANNEL_PACKED'
links.new(mixer.outputs[0], shader.inputs['Base Color'])
links.new(img_wrap.node_image.outputs[0], mixer.inputs[2])
if luma == 'alpha':
image.alpha_mode = 'CHANNEL_PACKED'
if tint2 is not None:
mixer.inputs[2].default_value = tint2[:3] + [1]
elif mapto == 'ROUGHNESS':
@@ -285,10 +287,6 @@ def add_texture_to_material(image, contextWrapper, pct, extend, alpha, scale, of
elif mapto == 'SPECULARITY':
shader.location = (300, -600)
img_wrap = contextWrapper.specular_tint_texture
if tint1:
img_wrap.node_dst.inputs['Coat Tint'].default_value = tint1[:3] + [1]
if tint2:
img_wrap.node_dst.inputs['Sheen Tint'].default_value = tint2[:3] + [1]
elif mapto == 'ALPHA':
shader.location = (300, 300)
img_wrap = contextWrapper.alpha_texture
@@ -301,6 +299,7 @@ def add_texture_to_material(image, contextWrapper, pct, extend, alpha, scale, of
shader.location = (300, 300)
img_wrap = contextWrapper.normalmap_texture
img_wrap.node_mapping.name = 'Normal Mapping'
image.alpha_mode = 'CHANNEL_PACKED'
elif mapto == 'TRANSMISSION':
shader.location = (-600, 900)
img_wrap = contextWrapper.transmission_texture
@@ -357,6 +356,11 @@ def add_texture_to_material(image, contextWrapper, pct, extend, alpha, scale, of
img_wrap.scale = scale
img_wrap.translation = offset
img_wrap.rotation[2] = angle
if mapto in {'ROUGHNESS', 'METALLIC', 'SPECULARITY'}:
if tint1:
img_wrap.node_dst.inputs['Coat Tint'].default_value = tint1[:3] + [1]
if tint2:
img_wrap.node_dst.inputs['Sheen Tint'].default_value = tint2[:3] + [1]
if alpha == 'alpha':
own_node = img_wrap.node_image
primary_tex = nodes.get('Diffuse Texture')
@@ -581,8 +585,10 @@ def process_next_chunk(context, file, previous_chunk, imported_objects, CONSTRAI
def read_texture(new_chunk, temp_chunk, mapto):
uscale, vscale, uoffset, voffset, angle = 1.0, 1.0, 0.0, 0.0, 0.0
contextWrapper.use_nodes = True
if hasattr(contextWrapper, "use_nodes"):
contextWrapper.use_nodes = True
tint1 = tint2 = None
luma = 'normal'
extend = 'wrap'
alpha = False
pct = 100
@@ -606,6 +612,8 @@ def process_next_chunk(context, file, previous_chunk, imported_objects, CONSTRAI
elif temp_chunk.ID == MAT_MAP_FILEPATH:
texture_name, read_str_len = read_string(file)
img = load_image(texture_name, dirname, place_holder=False, recursive=IMAGE_SEARCH, check_existing=True)
if img and img.depth in {32, 16}:
luma = 'alpha'
temp_chunk.bytes_read += read_str_len # plus one for the null character that gets removed
elif temp_chunk.ID == MAT_BUMP_PERCENT:
@@ -633,11 +641,11 @@ def process_next_chunk(context, file, previous_chunk, imported_objects, CONSTRAI
if tiling & 0x40:
alpha = 'alpha'
if tiling & 0x80:
tint = 'tint'
luma = 'tint'
if tiling & 0x100:
tint = 'noAlpha'
luma = 'noAlpha'
if tiling & 0x200:
tint = 'RGBtint'
luma = 'RGBtint'
elif temp_chunk.ID == MAT_MAP_USCALE:
uscale = read_float(temp_chunk)
@@ -660,7 +668,7 @@ def process_next_chunk(context, file, previous_chunk, imported_objects, CONSTRAI
# add the map to the material in the right channel
if img:
add_texture_to_material(img, contextWrapper, pct, extend, alpha, (uscale, vscale, 1),
(uoffset, voffset, 0), angle, tint1, tint2, mapto)
(uoffset, voffset, 0), angle, luma, tint1, tint2, mapto)
def apply_constrain(vec):
convector = mathutils.Vector.Fill(3, (CONSTRAIN * 0.1))
@@ -767,7 +775,10 @@ def process_next_chunk(context, file, previous_chunk, imported_objects, CONSTRAI
contextTransmission = False
contextColor = mathutils.Color((0.8, 0.8, 0.8))
contextMaterial = bpy.data.materials.new('Material')
contextWrapper = PrincipledBSDFWrapper(contextMaterial, is_readonly=False, use_nodes=False)
try:
contextWrapper = PrincipledBSDFWrapper(contextMaterial, is_readonly=False, use_nodes=False)
except:
contextWrapper = PrincipledBSDFWrapper(contextMaterial, is_readonly=False)
elif new_chunk.ID == MAT_NAME:
material_name, read_str_len = read_string(file)
@@ -884,7 +895,9 @@ def process_next_chunk(context, file, previous_chunk, imported_objects, CONSTRAI
elif new_chunk.ID == MAT_SHADING:
shading = read_short(new_chunk)
if shading >= 2:
contextWrapper.use_nodes = True
use_nodes = hasattr(contextWrapper, "use_nodes")
if use_nodes:
contextWrapper.use_nodes = True
contextWrapper.base_color = contextColor[:]
contextWrapper.metallic = contextMaterial.metallic
contextWrapper.roughness = contextMaterial.roughness
@@ -895,8 +908,9 @@ def process_next_chunk(context, file, previous_chunk, imported_objects, CONSTRAI
contextWrapper.emission_strength = contextMaterial.line_priority / 100
contextWrapper.alpha = contextMaterial.diffuse_color[3] = contextAlpha
contextWrapper.node_principled_bsdf.inputs['Coat Weight'].default_value = contextReflection
contextWrapper.use_nodes = False
if shading >= 3:
if use_nodes:
contextWrapper.use_nodes = False
if use_nodes and shading >= 3:
contextWrapper.use_nodes = True
elif new_chunk.ID == MAT_TEXTURE_MAP:
@@ -981,9 +995,18 @@ def process_next_chunk(context, file, previous_chunk, imported_objects, CONSTRAI
realname, ext = os.path.splitext(filename)
contextWorld = bpy.data.worlds.new("Background: " + realname)
context.scene.world = contextWorld
contextWorld.use_nodes = True
if hasattr(contextWorld, "use_nodes"):
contextWorld.use_nodes = True
worldnodes = contextWorld.node_tree.nodes
backgroundnode = worldnodes['Background']
backgroundnode = worldnodes.get("Background")
if backgroundnode is None:
worldlinks = contextWorld.node_tree.links
outputnode = worldnodes.get("World Output")
if outputnode is None:
outputnode = worldnodes.new("ShaderNodeOutputWorld")
backgroundnode = worldnodes.new("ShaderNodeBackground")
worldlinks.new(backgroundnode.outputs[0], outputnode.inputs[0])
backgroundnode.location = (10, 300)
read_chunk(file, temp_chunk)
if temp_chunk.ID == COLOR_F:
backgroundcolor = read_float_array(temp_chunk)
@@ -1005,26 +1028,35 @@ def process_next_chunk(context, file, previous_chunk, imported_objects, CONSTRAI
realname, ext = os.path.splitext(filename)
contextWorld = bpy.data.worlds.new("Bitmap: " + realname)
context.scene.world = contextWorld
contextWorld.use_nodes = True
if hasattr(contextWorld, "use_nodes"):
contextWorld.use_nodes = True
links = contextWorld.node_tree.links
nodes = contextWorld.node_tree.nodes
bitmap_mix = nodes.new(type='ShaderNodeMixRGB')
bitmapnode = nodes.new(type='ShaderNodeTexEnvironment')
bitmapping = nodes.new(type='ShaderNodeMapping')
backgroundnode = nodes.get("Background")
bitmap_mix = nodes.new(type="ShaderNodeMixRGB")
bitmapnode = nodes.new(type="ShaderNodeTexEnvironment")
bitmapping = nodes.new(type="ShaderNodeMapping")
if backgroundnode is None:
outputnode = nodes.get("World Output")
if outputnode is None:
outputnode = nodes.new("ShaderNodeOutputWorld")
backgroundnode = nodes.new("ShaderNodeBackground")
links.new(backgroundnode.outputs[0], outputnode.inputs[0])
bitmap_mix.label = "Background Mix"
bitmapnode.label = "Bitmap: " + bitmap_name
bitmap_mix.inputs[2].default_value = nodes['Background'].inputs[0].default_value
bitmap_mix.inputs[2].default_value = backgroundnode.inputs[0].default_value
bitmapnode.image = load_image(bitmap_name, dirname, place_holder=False, recursive=IMAGE_SEARCH, check_existing=True)
bitmap_mix.inputs[0].default_value = 0.5 if bitmapnode.image is not None else 1.0
coordinate = nodes.get("Texture Coordinate", nodes.new(type='ShaderNodeTexCoord'))
coordinate = nodes.get("Texture Coordinate", nodes.new(type="ShaderNodeTexCoord"))
bitmapnode.location = (-520, 400)
bitmap_mix.location = (-200, 360)
bitmapping.location = (-740, 400)
coordinate.location = (-1340, 400)
links.new(bitmap_mix.outputs[0], nodes['Background'].inputs[0])
backgroundnode.location = (10, 300)
links.new(bitmap_mix.outputs[0], backgroundnode.inputs[0])
links.new(bitmapnode.outputs[0], bitmap_mix.inputs[1])
links.new(bitmapping.outputs[0], bitmapnode.inputs[0])
if not bitmapping.inputs['Vector'].is_linked:
if not bitmapping.inputs["Vector"].is_linked:
links.new(coordinate.outputs[0], bitmapping.inputs[0])
new_chunk.bytes_read += read_str_len
@@ -1035,19 +1067,28 @@ def process_next_chunk(context, file, previous_chunk, imported_objects, CONSTRAI
realname, ext = os.path.splitext(filename)
contextWorld = bpy.data.worlds.new("Gradient: " + realname)
context.scene.world = contextWorld
contextWorld.use_nodes = True
if hasattr(contextWorld, "use_nodes"):
contextWorld.use_nodes = True
links = contextWorld.node_tree.links
nodes = contextWorld.node_tree.nodes
gradientnode = nodes.new(type='ShaderNodeValToRGB')
layerweight = nodes.new(type='ShaderNodeLayerWeight')
conversion = nodes.new(type='ShaderNodeMath')
normalnode = nodes.new(type='ShaderNodeNormal')
backgroundnode = nodes.get("Background")
gradientnode = nodes.new(type="ShaderNodeValToRGB")
layerweight = nodes.new(type="ShaderNodeLayerWeight")
conversion = nodes.new(type="ShaderNodeMath")
normalnode = nodes.new(type="ShaderNodeNormal")
mappingnode = nodes.get("Mapping", False)
coordinates = nodes.get("Texture Coordinate", False)
backgroundmix = next((wn for wn in nodes if wn.type in {'MIX', 'MIX_RGB'}), False)
if backgroundnode is None:
outputnode = nodes.get("World Output")
if outputnode is None:
outputnode = nodes.new("ShaderNodeOutputWorld")
backgroundnode = nodes.new("ShaderNodeBackground")
links.new(backgroundnode.outputs[0], outputnode.inputs[0])
conversion.location = (-740, -60)
layerweight.location = (-940, 170)
normalnode.location = (-1140, 300)
backgroundnode.location = (10, 300)
gradientnode.location = (-520, -20)
gradientnode.label = "Gradient"
conversion.operation = 'MULTIPLY_ADD'
@@ -1059,14 +1100,14 @@ def process_next_chunk(context, file, previous_chunk, imported_objects, CONSTRAI
links.new(normalnode.outputs[0], layerweight.inputs[1])
links.new(normalnode.outputs[1], layerweight.inputs[0])
if not coordinates:
coordinates = nodes.new(type='ShaderNodeTexCoord')
coordinates = nodes.new(type="ShaderNodeTexCoord")
coordinates.location = (-1340, 400)
links.new(coordinates.outputs[6], normalnode.inputs[0])
if backgroundmix:
links.new(gradientnode.outputs[0], backgroundmix.inputs[2])
else:
links.new(gradientnode.outputs[0], nodes['Background'].inputs[0])
if mappingnode and not mappingnode.inputs['Vector'].is_linked:
links.new(gradientnode.outputs[0], backgroundnode.inputs[0])
if mappingnode and not mappingnode.inputs["Vector"].is_linked:
links.new(coordinates.outputs[0], mappingnode.inputs[0])
gradientnode.color_ramp.elements.new(read_float(new_chunk))
read_chunk(file, temp_chunk)
@@ -1101,17 +1142,21 @@ def process_next_chunk(context, file, previous_chunk, imported_objects, CONSTRAI
realname, ext = os.path.splitext(filename)
contextWorld = bpy.data.worlds.new("Fog: " + realname)
context.scene.world = contextWorld
contextWorld.use_nodes = True
if hasattr(contextWorld, "use_nodes"):
contextWorld.use_nodes = True
links = contextWorld.node_tree.links
nodes = contextWorld.node_tree.nodes
fognode = nodes.new(type='ShaderNodeVolumeAbsorption')
fognode = nodes.new(type="ShaderNodeVolumeAbsorption")
fognode.label = "Fog"
fognode.location = (10, 20)
volumemix = nodes.get("Volume", False)
if volumemix:
links.new(fognode.outputs[0], volumemix.inputs[1])
else:
links.new(fognode.outputs[0], nodes['World Output'].inputs[1])
outputnode = nodes.get("World Output")
if outputnode is None:
outputnode = nodes.new("ShaderNodeOutputWorld")
links.new(fognode.outputs[0], outputnode.inputs[1])
contextWorld.mist_settings.use_mist = True
contextWorld.mist_settings.start = read_float(new_chunk)
nearfog = read_float(new_chunk) * 0.01
@@ -1138,23 +1183,30 @@ def process_next_chunk(context, file, previous_chunk, imported_objects, CONSTRAI
realname, ext = os.path.splitext(filename)
contextWorld = bpy.data.worlds.new("LayerFog: " + realname)
context.scene.world = contextWorld
contextWorld.use_nodes = True
if hasattr(contextWorld, "use_nodes"):
contextWorld.use_nodes = True
links = contextWorld.node_tree.links
nodes = contextWorld.node_tree.nodes
worldout = nodes.get("World Output")
background = nodes.get("Background")
if worldout is None:
worldout = nodes.new("ShaderNodeOutputWorld")
worldfog = worldout.inputs[1]
layerfog = nodes.new(type='ShaderNodeVolumeScatter')
litepath = nodes.get("Light Path", nodes.new('ShaderNodeLightPath'))
if background is None:
background = nodes.new("ShaderNodeBackground")
links.new(background.outputs[0], worldout.inputs[0])
layerfog = nodes.new(type="ShaderNodeVolumeScatter")
litepath = nodes.get("Light Path", nodes.new("ShaderNodeLightPath"))
fognode = nodes.get("Volume Absorption", False)
if fognode:
cuenode = nodes.get("Map Range", False)
mxvolume = nodes.new(type='ShaderNodeMixShader')
mxvolume = nodes.new(type="ShaderNodeMixShader")
mxvolume.label = mxvolume.name = "Volume"
mxvolume.location = (220, 0)
cuesource = cuenode.outputs[0] if cuenode else litepath.outputs[7]
cuesource = cuenode.outputs[0] if cuenode else litepath.outputs["Ray Length"]
cuetarget = cuenode.inputs[3] if cuenode else mxvolume.inputs[0]
links.new(litepath.outputs["Ray Length"], cuetarget)
links.new(fognode.outputs[0], mxvolume.inputs[1])
links.new(litepath.outputs[7], cuetarget)
links.new(cuesource, mxvolume.inputs[0])
links.new(mxvolume.outputs[0], worldfog)
worldfog = mxvolume.inputs[2]
@@ -1162,9 +1214,10 @@ def process_next_chunk(context, file, previous_chunk, imported_objects, CONSTRAI
layerfog.location = (10, -120)
worldout.location = (440, 160)
litepath.location = (-200, 70)
background.location = (10, 300)
links.new(layerfog.outputs[0], worldfog)
links.new(litepath.outputs[8], layerfog.inputs[2])
links.new(litepath.outputs[0], nodes['Background'].inputs[1])
links.new(litepath.outputs["Ray Depth"], layerfog.inputs[2])
links.new(litepath.outputs[0], background.inputs[1])
contextWorld.mist_settings.use_mist = True
contextWorld.mist_settings.start = read_float(new_chunk)
contextWorld.mist_settings.height = read_float(new_chunk)
@@ -1193,22 +1246,31 @@ def process_next_chunk(context, file, previous_chunk, imported_objects, CONSTRAI
realname, ext = os.path.splitext(filename)
contextWorld = bpy.data.worlds.new("DistanceCue: " + realname)
context.scene.world = contextWorld
contextWorld.use_nodes = True
if hasattr(contextWorld, "use_nodes"):
contextWorld.use_nodes = True
links = contextWorld.node_tree.links
nodes = contextWorld.node_tree.nodes
distcue_node = nodes.new(type='ShaderNodeMapRange')
camera_data = nodes.new(type='ShaderNodeCameraData')
background = nodes.get("Background")
distcue_node = nodes.new(type="ShaderNodeMapRange")
camera_data = nodes.new(type="ShaderNodeCameraData")
if background is None:
output = nodes.get("World Output")
if output is None:
output = nodes.new("ShaderNodeOutputWorld")
background = nodes.new("ShaderNodeBackground")
links.new(background.outputs[0], output.inputs[0])
distcue_node.label = "Distance Cue"
distcue_node.clamp = False
distcue_mix = nodes.get("Volume", False)
distcuepath = nodes.get("Light Path", False)
if not distcuepath:
distcuepath = nodes.new(type='ShaderNodeLightPath')
distcuepath = nodes.new(type="ShaderNodeLightPath")
background.location = (10, 300)
distcue_node.location = (-940, 10)
distcuepath.location = (-1140, 70)
camera_data.location = (-1340, 166)
raysource = distcuepath.outputs[7] if distcue_mix else distcuepath.outputs[0]
raytarget = distcue_mix.inputs[0] if distcue_mix else nodes['Background'].inputs[1]
raysource = distcuepath.outputs["Ray Length"] if distcue_mix else distcuepath.outputs[0]
raytarget = distcue_mix.inputs[0] if distcue_mix else background.inputs[1]
links.new(camera_data.outputs[1], distcue_node.inputs[1])
links.new(camera_data.outputs[2], distcue_node.inputs[0])
links.new(raysource, distcue_node.inputs[4])
@@ -1347,7 +1409,7 @@ def process_next_chunk(context, file, previous_chunk, imported_objects, CONSTRAI
elif CreateLightObject and new_chunk.ID == LIGHT_SPOT_SHADOWED: # Shadow flag
contextLamp.data.use_shadow = True
elif CreateLightObject and new_chunk.ID == LIGHT_LOCAL_SHADOW2: # Shadow parameters
if contextLamp.data.get('shadow_buffer_bias') is not None:
if contextLamp.data.get("shadow_buffer_bias") is not None:
contextLamp.data.shadow_buffer_bias = read_float(new_chunk)
else:
read_float(new_chunk)
@@ -1364,25 +1426,28 @@ def process_next_chunk(context, file, previous_chunk, imported_objects, CONSTRAI
contextLamp.data.use_nodes = True
nodes = contextLamp.data.node_tree.nodes
links = contextLamp.data.node_tree.links
mix = nodes.new(type='ShaderNodeMixRGB')
rgb = nodes.new(type='ShaderNodeRGB')
mix = nodes.new(type="ShaderNodeMixRGB")
rgb = nodes.new(type="ShaderNodeRGB")
mix.blend_type = 'LINEAR_LIGHT'
mix.label = "Emission Color"
emit = nodes.get("Emission")
emit.label = "Projector"
rgb.name = "RGB"
emit.location = (80, 300)
rgb.location = (-380, 60)
mix.location = (-140, 340)
gobo_name, read_str_len = read_string(file)
new_chunk.bytes_read += read_str_len
projection = nodes.new(type='ShaderNodeTexImage')
promapping = nodes.new(type='ShaderNodeMapping')
protxcoord = nodes.new(type='ShaderNodeTexCoord')
prolitpath = nodes.new(type='ShaderNodeLightPath')
prolitfall = nodes.new(type='ShaderNodeLightFalloff')
liteoutput = nodes.get("Light Output")
projection = nodes.new(type="ShaderNodeTexImage")
promapping = nodes.new(type="ShaderNodeMapping")
protxcoord = nodes.new(type="ShaderNodeTexCoord")
prolitpath = nodes.new(type="ShaderNodeLightPath")
prolitfall = nodes.new(type="ShaderNodeLightFalloff")
projection.label = "Gobo: " + gobo_name
protxcoord.label = "Gobo Coordinate"
promapping.vector_type = 'TEXTURE'
liteoutput.location = (300, 280)
prolitfall.location = (-720, 20)
projection.location = (-480, 440)
promapping.location = (-720, 440)
@@ -1390,11 +1455,11 @@ def process_next_chunk(context, file, previous_chunk, imported_objects, CONSTRAI
prolitpath.location = (-940, 180)
projection.image = load_image(gobo_name, dirname, place_holder=False, recursive=IMAGE_SEARCH, check_existing=True)
emit.inputs[0].default_value[:3] = mix.inputs[2].default_value[:3] = rgb.outputs[0].default_value[:3] = contextLamp.data.color
links.new(emit.outputs[0], nodes['Light Output'].inputs[0])
links.new(prolitpath.outputs["Ray Length"], prolitfall.inputs[1])
links.new(prolitpath.outputs["Ray Depth"], prolitfall.inputs[0])
links.new(promapping.outputs[0], projection.inputs[0])
links.new(protxcoord.outputs[2], promapping.inputs[0])
links.new(prolitpath.outputs[8], prolitfall.inputs[0])
links.new(prolitpath.outputs[7], prolitfall.inputs[1])
links.new(emit.outputs[0], liteoutput.inputs[0])
links.new(prolitfall.outputs[1], emit.inputs[1])
links.new(prolitfall.outputs[0], mix.inputs[0])
links.new(projection.outputs[0], mix.inputs[1])
@@ -1487,18 +1552,20 @@ def process_next_chunk(context, file, previous_chunk, imported_objects, CONSTRAI
if child is None:
if CreateWorld and tracking == 'AMBIENT':
child = context.scene.world
child.use_nodes = True
if hasattr(child, "use_nodes"):
child.use_nodes = True
nodetree = child.node_tree
links = nodetree.links
nodes = nodetree.nodes
backlite = nodes.get("Background")
worldout = nodes.get("World Output")
ambilite = nodes.new(type='ShaderNodeRGB')
raymixer = nodes.new(type='ShaderNodeMix')
mathnode = nodes.new(type='ShaderNodeMath')
ambinode = nodes.new(type='ShaderNodeEmission')
mixshade = nodes.new(type='ShaderNodeMixShader')
litefall = nodes.new(type='ShaderNodeLightFalloff')
ambilite = nodes.new(type="ShaderNodeRGB")
raymixer = nodes.new(type="ShaderNodeMix")
mathnode = nodes.new(type="ShaderNodeMath")
ambinode = nodes.new(type="ShaderNodeEmission")
mixshade = nodes.new(type="ShaderNodeMixShader")
litefall = nodes.new(type="ShaderNodeLightFalloff")
ambilite.name = "Ambient"
raymixer.label = "Ambient Mix"
ambilite.label = "Ambient Color"
raymixer.inputs[3].name = "Ambient"
@@ -1506,8 +1573,13 @@ def process_next_chunk(context, file, previous_chunk, imported_objects, CONSTRAI
mixshade.label = mixshade.name = "Surface"
litepath = nodes.get("Light Path", False)
ambinode.inputs[0].default_value[:3] = child.color
if not litepath:
litepath = nodes.new('ShaderNodeLightPath')
if litepath is None:
litepath = nodes.new("ShaderNodeLightPath")
if worldout is None:
worldout = nodes.new(type="ShaderNodeOutputWorld")
if backlite is None:
backlite = nodes.new(type="ShaderNodeBackground")
backlite.location = (10, 300)
ambinode.location = (10, 160)
worldout.location = (440, 160)
mixshade.location = (220, 280)
@@ -1577,7 +1649,7 @@ def process_next_chunk(context, file, previous_chunk, imported_objects, CONSTRAI
for keydata in keyframe_data.items():
child.color = ambilite.outputs[0].default_value[:3] = keydata[1]
child.keyframe_insert(data_path="color", frame=keydata[0])
nodetree.keyframe_insert(data_path="nodes[\"RGB\"].outputs[0].default_value", frame=keydata[0])
nodetree.keyframe_insert(data_path="nodes[\"Ambient\"].outputs[0].default_value", frame=keydata[0])
contextTrack_flag = False
elif KEYFRAME and new_chunk.ID == COL_TRACK_TAG and tracking == 'LIGHT': # Color
@@ -1591,16 +1663,17 @@ def process_next_chunk(context, file, previous_chunk, imported_objects, CONSTRAI
colornode = tree.nodes.get("RGB", False)
lightfall = tree.nodes.get("Light Falloff", False)
if not colornode:
colornode = tree.nodes.new('ShaderNodeRGB')
colornode = tree.nodes.new("ShaderNodeRGB")
colornode.name = "RGB"
colornode.location = (-380, 60)
tree.links.new(colornode.outputs[0], emitnode.inputs[0])
if not lightfall:
lightfall = tree.nodes.new('ShaderNodeLightFalloff')
lightpath = tree.nodes.new('ShaderNodeLightPath')
lightfall = tree.nodes.new("ShaderNodeLightFalloff")
lightpath = tree.nodes.new("ShaderNodeLightPath")
lightfall.location = (-720, 20)
lightpath.location = (-940, 180)
tree.links.new(lightpath.outputs[8], lightfall.inputs[0])
tree.links.new(lightpath.outputs[7], lightfall.inputs[1])
tree.links.new(lightpath.outputs["Ray Depth"], lightfall.inputs[0])
tree.links.new(lightpath.outputs["Ray Length"], lightfall.inputs[1])
tree.links.new(lightfall.outputs[1], emitnode.inputs[1])
colornode.outputs[0].default_value[:3] = child.data.color
for keydata in keyframe_data.items():
@@ -1677,7 +1750,7 @@ def process_next_chunk(context, file, previous_chunk, imported_objects, CONSTRAI
for i in range(nkeys):
nframe = read_long(new_chunk)
nflags = read_short(new_chunk)
for f in range(bin(nflags)[-5:].count('1')):
for f in range(bin(nflags)[-5:].count("1")):
temp_data = file.read(SZ_FLOAT) # Check for spline term values
new_chunk.bytes_read += SZ_FLOAT
temp_data = file.read(SZ_4FLOAT)
@@ -1757,7 +1830,7 @@ def process_next_chunk(context, file, previous_chunk, imported_objects, CONSTRAI
else:
buffer_size = new_chunk.length - new_chunk.bytes_read
binary_format = '%ic' % buffer_size
binary_format = "%ic" % buffer_size
temp_data = file.read(struct.calcsize(binary_format))
new_chunk.bytes_read += buffer_size
@@ -1788,7 +1861,8 @@ def process_next_chunk(context, file, previous_chunk, imported_objects, CONSTRAI
if ob.name in parent_dictionary.keys():
kids = parent_dictionary.get(ob.name)
for kid in kids:
kid.parent = ob
if kid is not None:
kid.parent = ob
elif not found:
if parent == ROOT_OBJECT:
ob.parent = None
@@ -1809,7 +1883,10 @@ def process_next_chunk(context, file, previous_chunk, imported_objects, CONSTRAI
trans_matrix = matrix_dictionary.get(ob.name, mathutils.Matrix())
pivot_matrix = mathutils.Matrix.Translation(trans_matrix.to_3x3() @ -pivot)
if APPLY_MATRIX and ob.type == 'MESH':
ob.data.transform(trans_matrix.inverted() @ pivot_matrix)
try:
ob.data.transform(trans_matrix.inverted() @ pivot_matrix)
except:
pass
##########
+25 -18
View File
@@ -1,20 +1,33 @@
# SPDX-License-Identifier: GPL-2.0-or-later
import bpy
from .operators import register as operators_register, unregister as operators_unregister
from .tools import register as tools_register, unregister as tools_unregister
from . import (
manual,
preferences,
properties,
ui,
versioning,
)
if "bpy" in locals():
import importlib
for mod in [operators,
tools,
manual,
preferences,
properties,
ui,
versioning,
]:
importlib.reload(mod)
print("Add-on Reloaded: Bool Tool")
else:
import bpy
from . import (
operators,
tools,
manual,
preferences,
properties,
ui,
versioning,
)
#### ------------------------------ REGISTRATION ------------------------------ ####
modules = [
operators,
tools,
manual,
preferences,
properties,
@@ -26,15 +39,9 @@ def register():
for module in modules:
module.register()
operators_register()
tools_register()
preferences.update_sidebar_category(bpy.context.preferences.addons[__package__].preferences, bpy.context)
def unregister():
for module in reversed(modules):
module.unregister()
operators_unregister()
tools_unregister()
@@ -2,15 +2,15 @@ schema_version = "1.0.0"
id = "bool_tool"
name = "Bool Tool"
version = "1.1.3"
tagline = "Quick boolean operations and tools for mesh modeling"
version = "1.1.5"
tagline = "Quick boolean operators and tools for hard surface modeling"
type = "add-on"
maintainer = "Nika Kutsniashvili <nickberckley@gmail.com>"
website = "https://github.com/nickberckley/bool_tool"
tags = ["Modeling", "Object"]
blender_version_min = "4.2.0"
blender_version_min = "4.5.0"
# License conforming to https://spdx.org/licenses/ (use "SPDX: prefix)
# https://docs.blender.org/manual/en/dev/advanced/extensions/licenses.html
@@ -1,8 +1,18 @@
import bpy, gpu, mathutils, math
from gpu_extras.batch import batch_for_shader
import bpy
import gpu
from bpy_extras import view3d_utils
from gpu_extras.batch import batch_for_shader
from .math import (
draw_circle,
draw_polygon,
draw_array,
)
magic_number = 1.41
color = (0.48, 0.04, 0.04, 1.0)
secondary_color = (0.28, 0.04, 0.04, 1.0)
#### ------------------------------ FUNCTIONS ------------------------------ ####
@@ -48,172 +58,74 @@ def draw_shader(color, alpha, type, coords, size=1, indices=None):
gpu.state.blend_set('NONE')
def carver_overlay(self, context):
"""Shape (rectangle, circle) overlay for carver tool"""
def carver_shape_box(self, context, shape):
"""Shape overlay for box carver tool"""
color = (0.48, 0.04, 0.04, 1.0)
secondary_color = (0.28, 0.04, 0.04, 1.0)
subdivision = self.subdivision if shape == 'CIRCLE' else 4
rotation = 0 if shape == 'CIRCLE' else 45
if self.shape == 'CIRCLE':
coords, indices, rows, columns = draw_circle(self, self.subdivision, 0)
# coords = coords[1:] # remove_extra_vertex
self.verts = coords
self.duplicates = {**{f"row_{k}": v for k, v in rows.items()}, **{f"column_{k}": v for k, v in columns.items()}}
# Create Shape
coords, indices, bounds = draw_circle(self, subdivision, rotation)
self.verts = coords
draw_shader(color, 0.4, 'SOLID', coords, size=2, indices=indices[:-2])
if not self.rotate:
bounds, __, __ = get_bounding_box_coords(self, coords)
draw_shader(color, 0.6, 'OUTLINE', bounds, size=2)
# Draw Shaders
draw_shader(color, 0.4, 'SOLID', coords, size=2, indices=indices[:-2])
if not self.rotate and not self.bevel:
draw_shader(color, 0.6, 'OUTLINE', bounds, size=2)
# Array
if self.rows > 1 or self.columns > 1:
carver_shape_array(self, coords, indices, 'SOLID')
elif self.shape == 'BOX':
coords, indices, rows, columns = draw_circle(self, 4, 45)
self.verts = coords
self.duplicates = {**{f"row_{k}": v for k, v in rows.items()}, **{f"column_{k}": v for k, v in columns.items()}}
draw_shader(color, 0.4, 'SOLID', coords, size=2, indices=indices[:-2])
if (self.rotate == False) and (self.bevel == False):
bounds, __, __ = get_bounding_box_coords(self, coords)
draw_shader(color, 0.6, 'OUTLINE', bounds, size=2)
elif self.shape == 'POLYLINE':
coords, indices, first_point, rows, columns = draw_polygon(self)
self.verts = list(dict.fromkeys(self.mouse_path))
self.duplicates = {**{f"row_{k}": v for k, v in rows.items()}, **{f"column_{k}": v for k, v in columns.items()}}
draw_shader(color, 1.0, 'LINE_LOOP' if self.closed else 'LINES', coords, size=2)
draw_shader(color, 1.0, 'POINTS', coords, size=5)
if self.closed and len(self.mouse_path) > 2:
# polygon_fill
draw_shader(color, 0.4, 'SOLID', coords, size=2, indices=indices[:-2])
if (self.closed and len(coords) > 3) or (self.closed == False and len(coords) > 4):
# circle_around_first_point
draw_shader(color, 0.8, 'OUTLINE', first_point, size=3)
# Snapping Grid
if self.snap and self.move == False:
if self.snap:
mini_grid(self, context)
# ARRAY
array_shader = 'LINE_LOOP' if self.shape == 'POLYLINE' and self.closed == False else 'SOLID'
if self.rows > 1:
for i, duplicate in rows.items():
draw_shader(secondary_color, 0.4, array_shader, duplicate, size=2, indices=indices[:-2])
if self.columns > 1:
for i, duplicate in columns.items():
draw_shader(secondary_color, 0.4, array_shader, duplicate, size=2, indices=indices[:-2])
gpu.state.blend_set('NONE')
def draw_polygon(self):
"""Returns polygonal 2d shape in which each cursor click is taken as a new vertice"""
def carver_shape_polyline(self, context):
"""Shape overlay for polyline carver tool"""
indices = []
coords = []
for idx, vals in enumerate(self.mouse_path):
vert = mathutils.Vector([vals[0], vals[1], 0.0])
vert += mathutils.Vector([self.position_x, self.position_y, 0.0])
coords.append(vert)
# Create Shape
coords, indices, first_point, array_coords = draw_polygon(self)
self.verts = list(dict.fromkeys(self.mouse_path))
i1 = idx + 1
i2 = idx + 2 if idx <= len(self.mouse_path) else 1
indices.append((0, i1, i2))
# Draw Shaders
draw_shader(color, 1.0, 'POINTS', coords, size=5)
draw_shader(color, 1.0, 'LINE_LOOP' if self.closed else 'LINES', coords, size=2)
# circle_around_first_point
radius = self.distance_from_first
segments = 4
if self.closed and len(self.mouse_path) > 2:
# polygon_fill
draw_shader(color, 0.4, 'SOLID', coords, size=2, indices=indices[:-2])
click_point = [coords[0]]
for i in range(segments + 1):
angle = i * (2 * math.pi / segments)
x = coords[0][0] + radius * math.cos(angle)
y = coords[0][1] + radius * math.sin(angle)
z = coords[0][2]
vector = mathutils.Vector((x, y, z))
click_point.append(vector)
if (self.closed and len(coords) > 3) or (self.closed == False and len(coords) > 4):
# circle_around_first_point
draw_shader(color, 0.8, 'OUTLINE', first_point, size=3)
# remove_duplicate_verts
# NOTE: This is needed to remove extra vertices for duplicates which are not removed because `dict.fromkeys()`...
# NOTE: can't be called on `coords` list, because it contains unfrozen Vectors.
unique_verts = []
for vert in coords:
if vert not in unique_verts:
unique_verts.append(vert)
# Array
if len(self.mouse_path) > 2 and (self.rows > 1 or self.columns > 1):
carver_shape_array(self, array_coords, indices, 'LINE_LOOP' if self.closed == False else 'SOLID')
# ARRAY
rows = columns = {}
if len(self.mouse_path) > 2:
array_coords = unique_verts if self.closed else unique_verts[:-1]
get_bounding_box_coords(self, array_coords)
rows, columns = array(self, array_coords)
if self.snap:
mini_grid(self, context)
return coords, indices, click_point, rows, columns
gpu.state.blend_set('NONE')
def draw_circle(self, subdivision, rotation):
"""Returns the coordinates & indices of a circle using a triangle fan"""
"""NOTE: Origin point code is duplicated on purpose (to experiment with different math easily)"""
def carver_shape_array(self, verts, indices, shader):
"""Draws given shape for each row and column of the array"""
def create_2d_circle(self, step, rotation):
"""Create the vertices of a 2d circle at (0, 0)"""
rows, columns = draw_array(self, verts)
self.duplicates = {**{f"row_{k}": v for k, v in rows.items()}, **{f"column_{k}": v for k, v in columns.items()}}
modifier = 2 if self.shape == 'CIRCLE' else magic_number
if self.origin == 'CENTER':
modifier /= 2
verts = []
for i in range(step):
angle = (360 / step) * i + rotation
verts.append(math.cos(math.radians(angle)) * ((self.mouse_path[1][0] - self.mouse_path[0][0]) / modifier))
verts.append(math.sin(math.radians(angle)) * ((self.mouse_path[1][1] - self.mouse_path[0][1]) / modifier))
verts.append(0.0)
verts.append(math.cos(math.radians(0.0 + rotation)) * ((self.mouse_path[1][0] - self.mouse_path[0][0]) / modifier))
verts.append(math.sin(math.radians(0.0 + rotation)) * ((self.mouse_path[1][1] - self.mouse_path[0][1]) / modifier))
verts.append(0.0)
return verts
tris_verts = []
indices = []
verts = create_2d_circle(self, int(subdivision), rotation)
rotation_matrix = mathutils.Matrix.Rotation(self.rotation, 4, 'Z')
fixed_point = mathutils.Vector((self.mouse_path[0][0], self.mouse_path[0][1], 0.0))
current_mouse_position = mathutils.Vector((self.mouse_path[1][0], self.mouse_path[1][1], 0.0))
shape_center = fixed_point + (current_mouse_position - fixed_point) / 2
min_x = min(verts[0::3]) if self.mouse_path[1][0] > self.mouse_path[0][0] else -min(verts[0::3])
min_y = min(verts[1::3]) if self.mouse_path[1][1] > self.mouse_path[0][1] else -min(verts[1::3])
for idx in range((len(verts) // 3) - 1):
x = verts[idx * 3]
y = verts[idx * 3 + 1]
z = verts[idx * 3 + 2]
vert = mathutils.Vector((x, y, z))
vert = rotation_matrix @ vert
vert = vert + fixed_point if self.origin == 'CENTER' else shape_center - vert
vert += mathutils.Vector((self.position_x, self.position_y, 0.0))
tris_verts.append(vert)
i1 = idx + 1
i2 = idx + 2 if idx + 2 <= ((360 / int(subdivision)) * (idx + 1) + rotation) else 1
indices.append((0, i1, i2))
# BEVEL
if self.use_bevel and self.bevel_radius > 0.01:
tris_verts, indices = bevel_verts(self, tris_verts, (self.bevel_radius * 50), self.bevel_segments)
# ARRAY
rows, columns = array(self, tris_verts)
return tris_verts, indices, rows, columns
if self.rows > 1:
for i, duplicate in rows.items():
draw_shader(secondary_color, 0.4, shader, duplicate, size=2, indices=indices[:-2])
if self.columns > 1:
for i, duplicate in columns.items():
draw_shader(secondary_color, 0.4, shader, duplicate, size=2, indices=indices[:-2])
def mini_grid(self, context):
@@ -222,8 +134,8 @@ def mini_grid(self, context):
region = context.region
rv3d = context.region_data
for i, a in enumerate(context.screen.areas):
if a.type == 'VIEW_3D':
for i, area in enumerate(context.screen.areas):
if area.type == 'VIEW_3D':
space = context.screen.areas[i].spaces.active
screen_height = context.screen.areas[i].height
screen_width = context.screen.areas[i].width
@@ -262,139 +174,3 @@ def mini_grid(self, context):
(mouse_coord[0] - 25 - snap_value, mouse_coord[1] - snap_value),]
draw_shader((1.0, 1.0, 1.0), 0.66, 'LINES', grid_coords, size=1.5)
def get_bounding_box_coords(self, verts):
"""Calculates the bounding box coordinates from a list of vertices in a counter-clockwise order"""
if verts:
min_x = min(v[0] for v in verts)
max_x = max(v[0] for v in verts)
min_y = min(v[1] for v in verts)
max_y = max(v[1] for v in verts)
self.center_origin = [(min_x, min_y), (max_x, max_y)]
bounding_box_coords = [
mathutils.Vector((min_x, min_y, 0)), # bottom-left
mathutils.Vector((max_x, min_y, 0)), # bottom-right
mathutils.Vector((max_x, max_y, 0)), # top-right
mathutils.Vector((min_x, max_y, 0)), # top-left
mathutils.Vector((min_x, min_y, 0)) # closing_the_loop_manually
]
width = max_x - min_x
height = max_y - min_y
return bounding_box_coords, width, height
else:
return None, None, None
def array(self, verts):
"""Duplicates given list of vertices in rows and columns (on x and y axis)"""
"""Returns two dicts of lists of vertices for rows and columns separately"""
# ensure_bounding_box_(needed_when_array_is_set_before_original_is_drawn)
if len(self.center_origin) == 0:
get_bounding_box_coords(self, verts)
rows = {}
if self.rows > 1:
# Offset
offset = mathutils.Vector((((self.center_origin[1][0] - self.center_origin[0][0]) + (self.rows_gap)), 0.0, 0.0))
if self.rows_direction == 'LEFT':
offset.x = -offset.x
for i in range(self.rows - 1):
accumulated_offset = offset * (i + 1)
rows[i] = [vert.copy() + accumulated_offset for vert in verts]
columns = {}
if self.columns > 1:
# Offset
offset = mathutils.Vector((0.0, -((self.center_origin[1][1] - self.center_origin[0][1]) + (self.columns_gap)), 0.0))
if self.columns_direction == 'UP':
offset.y = -offset.y
for i in range(self.columns - 1):
accumulated_offset = offset * (i + 1)
columns[i] = [vert.copy() + accumulated_offset for vert in verts]
for row_idx, row in rows.items():
columns[(i, row_idx)] = [vert.copy() + accumulated_offset for vert in row]
return rows, columns
def bevel_verts(self, verts, radius, segments):
"""Takes in list of verts(Vectors) and bevels them, Returns a new list with new vertices"""
def get_rounded_corner(self, angular_point, p1, p2, radius, segments):
# clamp_radius_to_reduce_clipping
__, width, height = get_bounding_box_coords(self, verts)
max_radius = min(width / 2.5, height / 2.5)
clamped_radius = min(radius, max_radius)
if radius > clamped_radius:
radius = clamped_radius
# calculate_vectors (NOTE: Why it only works when reversed like this is unknown to me)
if self.bevel_profile == 'CONVEX':
vector1 = -(p1 - angular_point)
vector2 = -(p2 - angular_point)
elif self.bevel_profile == 'CONCAVE':
vector1 = p2 - angular_point
vector2 = p1 - angular_point
# compute_lengths_of_vectors
length1 = vector1.length
length2 = vector2.length
if length1 == 0 or length2 == 0:
return [angular_point] * segments
vector1.normalize()
vector2.normalize()
# calculate_the_angle_between_the_vectors
dot_product = vector1.dot(vector2)
angle = math.acos(max(-1.0, min(1.0, dot_product)))
arc_length = radius * angle
segment_length = arc_length / (segments - 1)
bisector = (vector1 + vector2).normalized()
# generate_points_along_the_arc
rounded_corners = []
for i in range(segments):
fraction = i / (segments - 1)
theta = angle * fraction
interpolated_vector = (vector1 * math.sin(theta) + vector2 * math.cos(theta)).normalized() * radius
if self.bevel_profile == 'CONVEX':
point_on_arc = angular_point + interpolated_vector - bisector * (clamped_radius * magic_number)
elif self.bevel_profile == 'CONCAVE':
point_on_arc = angular_point + interpolated_vector - bisector / (clamped_radius)
rounded_corners.append(point_on_arc)
return rounded_corners
rounded_verts = []
indices = []
num_verts = len(verts)
for idx in range(num_verts):
angular_point = verts[idx]
prev_idx = (idx - 1) % num_verts
next_idx = (idx + 1) % num_verts
p1 = verts[prev_idx]
p2 = verts[next_idx]
corner_points = get_rounded_corner(self, angular_point, p1, p2, radius, segments)
rounded_verts.extend(corner_points)
for idx, vert in enumerate(reversed(rounded_verts)):
i1 = idx + 1
i2 = idx + 2 if idx + 2 <= len(rounded_verts) else 1
indices.append((0, i1, i2))
return rounded_verts, indices
@@ -1,5 +1,4 @@
import bpy
from .object import convert_to_mesh
#### ------------------------------ /all/ ------------------------------ ####
@@ -18,35 +17,6 @@ def list_canvases():
#### ------------------------------ /selected/ ------------------------------ ####
def list_candidate_objects(self, context, canvas):
"""Filter out objects from selected ones that can't be used as a cutter"""
cutters = []
for obj in context.selected_objects:
if obj != context.active_object and obj.type in ('MESH', 'CURVE', 'FONT'):
if obj.library or obj.override_library:
self.report({'ERROR'}, f"{obj.name} is linked and can not be used as a cutter")
else:
if obj.type in ('CURVE', 'FONT'):
if obj.data.bevel_depth != 0 or obj.data.extrude != 0:
convert_to_mesh(context, obj)
cutters.append(obj)
else:
# exclude_if_object_is_already_a_cutter_for_canvas
if canvas in list_cutter_users([obj]):
continue
# exclude_if_canvas_is_cutting_the_object_(avoid_dependancy_loop)
if obj in list_cutter_users([canvas]):
self.report({'WARNING'}, f"{obj.name} can not cut its own cutter (dependancy loop)")
continue
cutters.append(obj)
return cutters
def list_selected_cutters(context):
"""List selected cutters"""
@@ -175,17 +145,17 @@ def list_unused_cutters(cutters, *canvases, do_leftovers=False):
return cutters, leftovers
def list_pre_boolean_modifiers(obj):
"""Returns list of boolean modifiers + all modifiers that come before last boolean modifier"""
def list_pre_boolean_modifiers(obj) -> list:
"""Returns a list of boolean modifiers & modifiers that come before last boolean modifier"""
# find_the_index_of_last_boolean_modifier
# Find the index of a last boolean modifier
last_boolean_index = -1
for i in reversed(range(len(obj.modifiers))):
if obj.modifiers[i].type == 'BOOLEAN':
last_boolean_index = i
break
# if_boolean_modifier_found_list_all_modifiers_before
# If boolean modifier is found, list all modifiers that come before it.
if last_boolean_index != -1:
return [mod for mod in obj.modifiers[:last_boolean_index + 1]]
else:
@@ -0,0 +1,237 @@
import bpy
import math
import mathutils
magic_number = 1.41
#### ------------------------------ FUNCTIONS ------------------------------ ####
def draw_circle(self, subdivision, rotation):
"""Returns the coordinates & indices of a 2d circle in screen-space"""
def create_2d_circle(self, step, rotation):
"""Create the vertices of a 2d circle at (0, 0)"""
modifier = 2 if self.shape == 'CIRCLE' else magic_number
if self.origin == 'CENTER':
modifier /= 2
verts = []
for i in range(step):
angle = (360 / step) * i + rotation
verts.append(math.cos(math.radians(angle)) * ((self.mouse_path[1][0] - self.mouse_path[0][0]) / modifier))
verts.append(math.sin(math.radians(angle)) * ((self.mouse_path[1][1] - self.mouse_path[0][1]) / modifier))
verts.append(0.0)
verts.append(math.cos(math.radians(0.0 + rotation)) * ((self.mouse_path[1][0] - self.mouse_path[0][0]) / modifier))
verts.append(math.sin(math.radians(0.0 + rotation)) * ((self.mouse_path[1][1] - self.mouse_path[0][1]) / modifier))
verts.append(0.0)
return verts
tris_verts = []
indices = []
verts = create_2d_circle(self, int(subdivision), rotation)
rotation_matrix = mathutils.Matrix.Rotation(self.rotation, 4, 'Z')
fixed_point = mathutils.Vector((self.mouse_path[0][0], self.mouse_path[0][1], 0.0))
current_mouse_position = mathutils.Vector((self.mouse_path[1][0], self.mouse_path[1][1], 0.0))
shape_center = fixed_point + (current_mouse_position - fixed_point) / 2
for idx in range((len(verts) // 3) - 1):
x = verts[idx * 3]
y = verts[idx * 3 + 1]
z = verts[idx * 3 + 2]
vert = mathutils.Vector((x, y, z))
vert = rotation_matrix @ vert
vert = vert + fixed_point if self.origin == 'CENTER' else shape_center - vert
vert += mathutils.Vector((self.position_offset_x, self.position_offset_y, 0.0))
tris_verts.append(vert)
i1 = idx + 1
i2 = idx + 2 if idx + 2 <= ((360 / int(subdivision)) * (idx + 1) + rotation) else 1
indices.append((0, i1, i2))
# BEVEL
if self.use_bevel and self.bevel_radius > 0.01:
tris_verts, indices = bevel_verts(self, tris_verts, (self.bevel_radius * 50), self.bevel_segments)
# BOUNDING_BOX
min_x, min_y, max_x, max_y = get_bounding_box(tris_verts)
bounds = [
mathutils.Vector((min_x, min_y, 0)), # bottom-left
mathutils.Vector((max_x, min_y, 0)), # bottom-right
mathutils.Vector((max_x, max_y, 0)), # top-right
mathutils.Vector((min_x, max_y, 0)), # top-left
mathutils.Vector((min_x, min_y, 0)) # closing_the_loop_manually
]
return tris_verts, indices, bounds
def draw_polygon(self):
"""Returns polygonal 2d shape in screen-space where each cursor click is taken as a new vertice"""
indices = []
coords = []
for idx, vals in enumerate(self.mouse_path):
vert = mathutils.Vector([vals[0], vals[1], 0.0])
vert += mathutils.Vector([self.position_offset_x, self.position_offset_y, 0.0])
coords.append(vert)
i1 = idx + 1
i2 = idx + 2 if idx <= len(self.mouse_path) else 1
indices.append((0, i1, i2))
# circle_around_first_point
radius = self.distance_from_first
segments = 4
click_point = [coords[0]]
for i in range(segments + 1):
angle = i * (2 * math.pi / segments)
x = coords[0][0] + radius * math.cos(angle)
y = coords[0][1] + radius * math.sin(angle)
z = coords[0][2]
vector = mathutils.Vector((x, y, z))
click_point.append(vector)
# ARRAY (remove_duplicate_verts)
"""NOTE: This is needed to remove extra vertices for duplicates which are not removed because `dict.fromkeys()`..."""
"""NOTE: can't be called on `coords` list, because it contains unfrozen Vectors."""
unique_verts = []
for vert in coords:
if vert not in unique_verts:
unique_verts.append(vert)
array_coords = unique_verts if self.closed else unique_verts[:-1]
return coords, indices, click_point, array_coords
def draw_array(self, verts):
"""Duplicates given list of vertices in rows and columns (on screen-space x and y axis)"""
"""Returns two dicts of lists of vertices for rows and columns separately"""
# get_bounding_box_of_the_shape
"""NOTE: Calculated separately because verts needed for array differs from verts needed for shape for polyline"""
min_x, min_y, max_x, max_y = get_bounding_box(verts)
rows = {}
if self.rows > 1:
# Offset
offset = mathutils.Vector((((max_x - min_x) + (self.rows_gap)), 0.0, 0.0))
if self.rows_direction == 'LEFT':
offset.x = -offset.x
for i in range(self.rows - 1):
accumulated_offset = offset * (i + 1)
rows[i] = [vert.copy() + accumulated_offset for vert in verts]
columns = {}
if self.columns > 1:
# Offset
offset = mathutils.Vector((0.0, -((max_y - min_y) + (self.columns_gap)), 0.0))
if self.columns_direction == 'UP':
offset.y = -offset.y
for i in range(self.columns - 1):
accumulated_offset = offset * (i + 1)
columns[i] = [vert.copy() + accumulated_offset for vert in verts]
for row_idx, row in rows.items():
columns[(i, row_idx)] = [vert.copy() + accumulated_offset for vert in row]
return rows, columns
def bevel_verts(self, verts, radius, segments):
"""Takes in list of verts(Vectors) and bevels them, Returns a new list with new vertices"""
def get_rounded_corner(self, angular_point, p1, p2, radius, segments):
# get_bounding_box_of_the_shape
min_x, min_y, max_x, max_y = get_bounding_box(verts)
width = max_x - min_x
height = max_y - min_y
# clamp_radius_to_reduce_clipping
max_radius = min(width / 2.5, height / 2.5)
clamped_radius = min(radius, max_radius)
if radius > clamped_radius:
radius = clamped_radius
# calculate_vectors (NOTE: Why it only works when reversed like this is unknown to me)
if self.bevel_profile == 'CONVEX':
vector1 = -(p1 - angular_point)
vector2 = -(p2 - angular_point)
elif self.bevel_profile == 'CONCAVE':
vector1 = p2 - angular_point
vector2 = p1 - angular_point
# compute_lengths_of_vectors
length1 = vector1.length
length2 = vector2.length
if length1 == 0 or length2 == 0:
return [angular_point] * segments
vector1.normalize()
vector2.normalize()
# calculate_the_angle_between_the_vectors
dot_product = vector1.dot(vector2)
angle = math.acos(max(-1.0, min(1.0, dot_product)))
arc_length = radius * angle
segment_length = arc_length / (segments - 1)
bisector = (vector1 + vector2).normalized()
# generate_points_along_the_arc
rounded_corners = []
for i in range(segments):
fraction = i / (segments - 1)
theta = angle * fraction
interpolated_vector = (vector1 * math.sin(theta) + vector2 * math.cos(theta)).normalized() * radius
if self.bevel_profile == 'CONVEX':
point_on_arc = angular_point + interpolated_vector - bisector * (clamped_radius * magic_number)
elif self.bevel_profile == 'CONCAVE':
point_on_arc = angular_point + interpolated_vector - bisector / (clamped_radius)
rounded_corners.append(point_on_arc)
return rounded_corners
rounded_verts = []
indices = []
num_verts = len(verts)
for idx in range(num_verts):
angular_point = verts[idx]
prev_idx = (idx - 1) % num_verts
next_idx = (idx + 1) % num_verts
p1 = verts[prev_idx]
p2 = verts[next_idx]
corner_points = get_rounded_corner(self, angular_point, p1, p2, radius, segments)
rounded_verts.extend(corner_points)
for idx, vert in enumerate(reversed(rounded_verts)):
i1 = idx + 1
i2 = idx + 2 if idx + 2 <= len(rounded_verts) else 1
indices.append((0, i1, i2))
return rounded_verts, indices
def get_bounding_box(verts):
"""Calculates the bounding box coordinates from a list of vertices"""
min_x = min(v[0] for v in verts)
max_x = max(v[0] for v in verts)
min_y = min(v[1] for v in verts)
max_y = max(v[1] for v in verts)
return min_x, min_y, max_x, max_y
@@ -1,4 +1,7 @@
import bpy, bmesh, mathutils, math
import bpy
import bmesh
import mathutils
import math
from bpy_extras import view3d_utils
@@ -19,8 +22,8 @@ def create_cutter_shape(self, context):
if self.depth == 'CURSOR':
plane_point = context.scene.cursor.location
elif self.depth == 'VIEW':
plane_point = mathutils.Vector((0.0, 0.0, 0.0))
__, plane_point = combined_bounding_box(self.selected_objects)
plane_point = mathutils.Vector(plane_point)
# Create Mesh & Object
faces = {}
@@ -61,7 +64,7 @@ def extrude(self, mesh):
faces = [f for f in bm.faces]
# move_the_mesh_towards_view
box_bounding = combined_bounding_box(self.selected_objects)
box_bounding, __ = combined_bounding_box(self.selected_objects)
for face in faces:
for vert in face.verts:
vert.co += -self.view_depth * box_bounding
@@ -85,7 +88,7 @@ def extrude(self, mesh):
def combined_bounding_box(objects):
"""Calculate the combined bounding box of multiple objects."""
min_corner = mathutils.Vector((float('inf'), float('inf'), float('inf')))
max_corner = mathutils.Vector((-float('inf'), -float('inf'), -float('inf')))
@@ -103,7 +106,10 @@ def combined_bounding_box(objects):
# Calculate the diagonal of the combined bounding box
bounding_box_diag = (max_corner - min_corner).length
return bounding_box_diag
# Calculate the center of bounding box
bounding_box_center = (max_corner + min_corner) * 0.5
return bounding_box_diag, bounding_box_center
def create_face(context, direction, depth, bm, name, faces, verts, polyline=False):
@@ -0,0 +1,134 @@
import bpy
import bmesh
from contextlib import contextmanager
from .. import __package__ as base_package
from .object import (
convert_to_mesh,
)
from .poll import (
is_instanced_data,
)
#### ------------------------------ FUNCTIONS ------------------------------ ####
def add_boolean_modifier(self, context, obj, cutter, mode, solver, pin=False, redo=True):
"Adds boolean modifier with specified cutter and properties to a single object"
if bpy.app.version < (5, 0, 0) and solver == 'FLOAT':
solver = 'FAST'
prefs = context.preferences.addons[base_package].preferences
modifier = obj.modifiers.new("boolean_" + cutter.name, 'BOOLEAN')
modifier.operation = mode
modifier.object = cutter
modifier.solver = solver
# Set solver options (inherited from operator properties).
if redo:
modifier.material_mode = self.material_mode
modifier.use_self = self.use_self
modifier.use_hole_tolerant = self.use_hole_tolerant
modifier.double_threshold = self.double_threshold
if prefs.show_in_editmode:
modifier.show_in_editmode = True
# Move modifier to the index 0 (make it first in the stack).
if pin:
index = obj.modifiers.find(modifier.name)
obj.modifiers.move(index, 0)
return modifier
def apply_modifiers(context, obj, modifiers: list):
"""
Apply modifiers on object.
Instead of using `bpy.ops.object.modifier_apply`, this function uses
`bpy.data.meshes.new_from_object` built-in function to create a temporary
mesh from the evaluated object (basically with visible modifiers applied).
Temporary mesh is then transferred to objects mesh with `bmesh`.
This method is up to 2x faster, although it's considered experimental
and may fail in some cases, so a fallback to `bpy.ops.object.modifier_apply` is kept.
"""
prefs = context.preferences.addons[base_package].preferences
# Make object data unique if it's instanced.
if is_instanced_data(obj):
context.active_object.data = context.active_object.data.copy()
try:
# Don't use this method if it's not enabled by user in add-on preferences.
if not prefs.fast_modifier_apply:
raise Exception("")
with hide_modifiers(obj, excluding=modifiers):
# Create a temporary mesh from evaluated object.
evaluated_obj = obj.evaluated_get(context.evaluated_depsgraph_get())
temp_data = bpy.data.meshes.new_from_object(evaluated_obj)
# Create `bmesh` from temporary mesh and update edit mesh.
if context.mode == 'EDIT_MESH':
bm = bmesh.from_edit_mesh(obj.data)
bm.clear()
bm.from_mesh(temp_data)
bmesh.update_edit_mesh(obj.data)
else:
bm = bmesh.new()
bm.from_mesh(temp_data)
bm.to_mesh(obj.data)
bm.free()
evaluated_obj.to_mesh_clear()
# Remove modifiers and purge temporary mesh.
bpy.data.meshes.remove(temp_data)
for mod in modifiers:
obj.modifiers.remove(mod)
# Remove shape keys if there are any.
# (after above operations none of the shape keys have any effect).
if obj.data.shape_keys:
obj.shape_key_clear()
# Use `bpy.ops` operator to apply modifiers if above fails.
except Exception as e:
# print("Error applying modifiers with `bmesh` method:", e, "falling back to `bpy.ops` method")
context_override = {"object": obj, "mode": 'OBJECT'}
with context.temp_override(**context_override):
# Apply shape keys if there are any.
if obj.data.shape_keys:
bpy.ops.object.shape_key_remove(all=True, apply_mix=True)
# If all modifiers need to be applied convert to Mesh.
if modifiers == obj.modifiers.values():
print("Applying all modifiers by converting to Mesh")
convert_to_mesh(context, obj)
return
for mod in modifiers:
bpy.ops.object.modifier_apply(modifier=mod.name)
@contextmanager
def hide_modifiers(obj, excluding: list):
"""Hides all modifiers of a given object in viewport except those in excluding list"""
visible_modifiers = []
for mod in obj.modifiers:
if mod in excluding:
continue
if mod.show_viewport == True:
visible_modifiers.append(mod)
mod.show_viewport = False
try:
yield
finally:
for mod in visible_modifiers:
mod.show_viewport = True
@@ -1,86 +1,10 @@
import bpy, bmesh, mathutils
import bpy
import mathutils
from .. import __package__ as base_package
#### ------------------------------ FUNCTIONS ------------------------------ ####
def add_boolean_modifier(self, context, canvas, cutter, mode, solver, apply=False, pin=False, redo=True, single_user=False):
"Adds boolean modifier with specified cutter and properties to a single object"
prefs = context.preferences.addons[base_package].preferences
modifier = canvas.modifiers.new("boolean_" + cutter.name, 'BOOLEAN')
modifier.operation = mode
modifier.object = cutter
modifier.solver = solver
if redo:
modifier.material_mode = self.material_mode
modifier.use_self = self.use_self
modifier.use_hole_tolerant = self.use_hole_tolerant
modifier.double_threshold = self.double_threshold
if prefs.show_in_editmode:
modifier.show_in_editmode = True
if pin:
index = canvas.modifiers.find(modifier.name)
canvas.modifiers.move(index, 0)
if apply:
for face in cutter.data.polygons:
face.select = True
if context.mode == 'EDIT_MESH':
"""Applying boolean modifier in mesh edit mode:"""
"""1. Hiding other visible modifiers and creating new (temporary) mesh from evaluated object"""
"""2. Transfering temporary mesh to `bmesh` to update active mesh in edit mode"""
"""3. Removing boolean modifier and purging temporary mesh"""
"""4. Restoring visibility of other modifiers from (1)"""
visible_modifiers = []
for mod in canvas.modifiers:
if mod == modifier:
continue
if mod.show_viewport == True:
visible_modifiers.append(mod)
mod.show_viewport = False
evaluated_obj = canvas.evaluated_get(context.evaluated_depsgraph_get())
temp_data = bpy.data.meshes.new_from_object(evaluated_obj)
bm = bmesh.from_edit_mesh(canvas.data)
bm.clear()
bm.from_mesh(temp_data)
bmesh.update_edit_mesh(canvas.data)
evaluated_obj.to_mesh_clear()
canvas.modifiers.remove(modifier)
bpy.data.meshes.remove(temp_data)
for mod in visible_modifiers:
mod.show_viewport = True
else:
context_override = {'object': canvas, 'mode': 'OBJECT'}
with context.temp_override(**context_override):
apply_modifier(context, canvas, modifier, single_user=single_user)
def apply_modifier(context, obj, modifier, single_user=False):
"""Applies given modifier to object."""
context.view_layer.objects.active = obj
try:
bpy.ops.object.modifier_apply(modifier=modifier.name)
except:
if single_user:
# Make Single User
context.active_object.data = context.active_object.data.copy()
bpy.ops.object.modifier_apply(modifier=modifier.name)
def set_cutter_properties(context, canvas, cutter, mode, parent=True, hide=False, collection=True):
"""Ensures cutter is properly set: has right properties, is hidden, in a collection & parented"""
@@ -1,22 +1,38 @@
import bpy
from .list import list_canvas_cutters
from .list import (
list_canvas_cutters,
list_cutter_users,
)
from .object import (
convert_to_mesh,
)
#### ------------------------------ FUNCTIONS ------------------------------ ####
def basic_poll(context, check_linked=False):
if context.mode == 'OBJECT':
if context.active_object is not None:
if context.active_object.type == 'MESH':
if check_linked and is_linked(context) == True:
return False
def basic_poll(cls, context, check_linked=False):
"""Basic poll for boolean operators."""
return True
if context.mode != 'OBJECT':
return False
if context.active_object is None:
return False
obj = context.active_object
if obj.type != 'MESH':
cls.poll_message_set("Boolean operators can only be used for mesh objects")
return False
if check_linked and is_linked(context, obj) == True:
cls.poll_message_set("Boolean operators can not be executed on linked objects")
return False
return True
def is_linked(context, obj=None):
if not obj:
obj = context.active_object
def is_linked(context, obj):
"""Checks whether the object is linked from an external .blend file (including library-overrides)."""
if obj not in context.editable_objects:
if obj.library:
@@ -31,19 +47,22 @@ def is_linked(context, obj=None):
def is_canvas(obj):
"""Checks whether the object is a boolean canvas (i.e. has boolean cutters)."""
if obj.booleans.canvas == False:
return False
else:
# Even if object is marked as canvas, check if it actually has any cutters
cutters, __ = list_canvas_cutters([obj])
if len(cutters) != 0:
if len(cutters) > 0:
return True
else:
return False
def is_instanced_data(obj):
"""Checks if obj.data has more than one users, i.e. is instanced"""
"""Function only considers object types as users, and excludes pointers"""
"""Checks if `obj.data` has more than one users, i.e. is instanced."""
"""Function only considers object types as users, and excludes pointers."""
data = bpy.data.meshes.get(obj.data.name)
users = 0
@@ -59,18 +78,103 @@ def is_instanced_data(obj):
return False
def active_modifier_poll(context):
"""Checks whether the active modifier for active object is a boolean"""
def active_modifier_poll(obj):
"""Checks whether the active modifier for active object is a boolean."""
if context.object:
if len(context.object.modifiers) == 0:
return False
# Check if active modifier exists.
if len(obj.modifiers) == 0:
return False
if obj.modifiers.active is None:
return False
modifier = context.object.modifiers.active
if modifier and modifier.type == "BOOLEAN":
if modifier.object == None:
return False
else:
return True
# Check if active modifier is a boolean with a valid object.
modifier = obj.modifiers.active
if modifier.type != "BOOLEAN":
return False
if modifier.object is None:
return False
return True
def has_evaluated_mesh(context, obj):
"""Checks if an object (non-mesh type) has an evaluated mesh created by Geometry Nodes modifiers."""
depsgraph = context.view_layer.depsgraph
obj_eval = depsgraph.id_eval_get(obj)
geometry = obj_eval.evaluated_geometry()
if geometry.mesh:
return True
else:
return False
def list_candidate_objects(self, context, canvas):
"""Filter out objects from the selection that can't be used as a cutter."""
cutters = []
for obj in context.selected_objects:
if obj == context.active_object:
continue
if is_linked(context, obj):
self.report({'WARNING'}, f"{obj.name} is linked and can not be used as a cutter")
continue
if obj.type == 'MESH':
# Exclude if object is already a cutter for canvas.
if canvas in list_cutter_users([obj]):
continue
# Exclude if canvas is cutting the object (avoid dependancy loop).
if obj in list_cutter_users([canvas]):
self.report({'WARNING'}, f"{obj.name} can not cut its own cutter (dependancy loop)")
continue
cutters.append(obj)
elif obj.type in ('CURVE', 'FONT'):
if has_evaluated_mesh(context, obj):
convert_to_mesh(context, obj)
cutters.append(obj)
return cutters
def destructive_op_confirmation(self, context, event, canvases: list, title="Boolean Operation"):
"""
Creates & returns the confirmation pop-up window for destructive boolean operators.\n
Confirmation window is triggered by canvas objects that have instanced object data or shape keys.\n
If none of the canvas objects have them the operator is executed without any confirmation.
"""
has_instanced_data = any(obj for obj in canvases if is_instanced_data(obj))
has_shape_keys = any(obj for obj in canvases if obj.data.shape_keys)
if has_instanced_data or has_shape_keys:
# Instanced data message.
if has_instanced_data and not has_shape_keys:
message = ("Object(s) you're trying to cut have instanced object data.\n"
"In order to apply modifiers, they need to be made single-user.\n"
"Do you proceed?")
# Shape keys message.
if has_shape_keys and not has_instanced_data:
message = ("Object(s) you're trying to cut have shape keys.\n"
"In order to apply modifiers shape keys need to be applied as well.\n"
"Do you proceed?")
# Combined message.
if has_instanced_data and has_shape_keys:
message = ("Object(s) you're trying to cut have shape keys and instanced object data.\n"
"In order to apply modifiers shape keys need to be applied, and object data made single user.\n"
"Do you proceed?")
popup = context.window_manager.invoke_confirm(self, event, title=title,
confirm_text="Yes", icon='WARNING',
message=message)
return popup
# Execute without confirmation window.
else:
return self.execute(context)
@@ -1,6 +1,8 @@
import bpy, mathutils
import bpy
import mathutils
from bpy_extras import view3d_utils
from .draw import get_bounding_box_coords
from .math import get_bounding_box
from .poll import is_linked, is_instanced_data
@@ -59,7 +61,7 @@ def is_inside_selection(context, obj, rect_min, rect_max):
for corner_2d in bound_corners_2d:
if corner_2d and (rect_min.x <= corner_2d.x <= rect_max.x and rect_min.y <= corner_2d.y <= rect_max.y):
return True
# check_if_any_part_of_the_bounding_box_intersects_the_selection_rectangle
min_x = min(corner_2d.x for corner_2d in bound_corners_2d if corner_2d)
max_x = max(corner_2d.x for corner_2d in bound_corners_2d if corner_2d)
@@ -69,33 +71,30 @@ def is_inside_selection(context, obj, rect_min, rect_max):
return not (max_x < rect_min.x or min_x > rect_max.x or max_y < rect_min.y or min_y > rect_max.y)
def selection_fallback(self, context, objects, include_cutters=False):
"""Selects mesh objects that fall inside given 2d rectangle coordinates"""
"""Used to get exactly which objects should be cut and avoid adding and applying unnecessary modifiers"""
"""NOTE: bounding box isn't always returning correct results for objects, but full surface check would be too expensive"""
def selection_fallback(self, context, objects, shape='BOX', include_cutters=False):
"""Returns mesh objects that fall inside given 2d rectangle (bounding box of the shape) coordinates"""
"""Needed to know exactly which objects should be carved, to avoid adding and applying unnecessary modifiers"""
"""NOTE: bounding box isn't always returning correct results, but checking full shape would be too expensive"""
# convert_2d_rectangle_coordinates_to_world_coordinates
if self.origin == 'EDGE':
if self.shape == 'POLYLINE':
x_values = [point[0] for point in self.mouse_path]
y_values = [point[1] for point in self.mouse_path]
rect_min = mathutils.Vector((min(x_values), min(y_values)))
rect_max = mathutils.Vector((max(x_values), max(y_values)))
else:
if shape == 'POLYLINE':
x_values = [point[0] for point in self.mouse_path]
y_values = [point[1] for point in self.mouse_path]
rect_min = mathutils.Vector((min(x_values), min(y_values)))
rect_max = mathutils.Vector((max(x_values), max(y_values)))
elif shape == 'BOX':
if self.origin == 'EDGE':
rect_min = mathutils.Vector((min(self.mouse_path[0][0], self.mouse_path[1][0]),
min(self.mouse_path[0][1], self.mouse_path[1][1])))
rect_max = mathutils.Vector((max(self.mouse_path[0][0], self.mouse_path[1][0]),
max(self.mouse_path[0][1], self.mouse_path[1][1])))
elif self.origin == 'CENTER':
# ensure_bounding_box_(needed_when_array_is_set_before_original_is_drawn)
if len(self.center_origin) == 0:
get_bounding_box_coords(self, self.verts)
elif self.origin == 'CENTER':
# get_bounding_box_of_the_shape
min_x, min_y, max_x, max_y = get_bounding_box(self.verts)
rect_min = mathutils.Vector((min(self.center_origin[0][0], self.center_origin[1][0]),
min(self.center_origin[0][1], self.center_origin[1][1])))
rect_max = mathutils.Vector((max(self.center_origin[0][0], self.center_origin[1][0]),
max(self.center_origin[0][1], self.center_origin[1][1])))
rect_min = mathutils.Vector((min(min_x, max_x), min(min_y, max_y)))
rect_max = mathutils.Vector((max(min_x, max_x), max(min_y, max_y)))
# ARRAY
if self.rows > 1:
@@ -103,6 +102,7 @@ def selection_fallback(self, context, objects, include_cutters=False):
if self.columns > 1:
rect_min.y = rect_max.y - (rect_max.y - rect_min.y) * self.columns - (self.columns_gap * (self.columns - 1))
intersecting_objects = []
for obj in objects:
if obj.type != 'MESH':
@@ -120,11 +120,8 @@ def selection_fallback(self, context, objects, include_cutters=False):
continue
if self.mode == 'DESTRUCTIVE':
if obj.data.shape_keys:
self.report({'ERROR'}, f"Modifiers can't be applied to {obj.name} because it has shape keys")
continue
if is_instanced_data(obj):
self.report({'ERROR'}, f"Modifiers can't be applied to {obj.name} because it has instanced object data")
self.report({'ERROR'}, f"Modifiers cannot be applied to {obj.name} because it has instanced object data")
continue
intersecting_objects.append(obj)
@@ -1,10 +1,19 @@
import bpy
from . import (
boolean,
canvas,
cutter,
select,
)
if "bpy" in locals():
import importlib
for mod in [boolean,
canvas,
cutter,
select,
]:
importlib.reload(mod)
else:
import bpy
from . import (
boolean,
canvas,
cutter,
select,
)
#### ------------------------------ REGISTRATION ------------------------------ ####
@@ -1,35 +1,39 @@
import bpy
from collections import defaultdict
from .. import __package__ as base_package
from ..functions.poll import (
basic_poll,
is_linked,
is_instanced_data,
list_candidate_objects,
destructive_op_confirmation,
)
from ..functions.modifier import (
add_boolean_modifier,
apply_modifiers,
)
from ..functions.object import (
apply_modifier,
convert_to_mesh,
add_boolean_modifier,
set_cutter_properties,
change_parent,
create_slice,
delete_cutter,
)
from ..functions.list import (
list_candidate_objects,
list_cutter_users,
list_pre_boolean_modifiers,
)
#### ------------------------------ PROPERTIES ------------------------------ ####
class ModifierProperties():
material_mode: bpy.props.EnumProperty(
name = "Materials",
description = "Method for setting materials on the new faces",
items = (('INDEX', "Index Based", "Set the material on new faces based on the order of the material slot lists. If a material doesnt exist on the\n"
"modifier object, the face will use the same material slot or the first if the object doesnt have enough slots."),
('TRANSFER', "Transfer", "Transfer materials from non-empty slots to the result mesh, adding new materials as necessary.\n"
"For empty slots, fall back to using the same material index as the operand mesh.")),
items = (('INDEX', "Index Based", ("Set the material on new faces based on the order of the material slot lists. If a material doesn't exist on the\n"
"modifier object, the face will use the same material slot or the first if the object doesn't have enough slots.")),
('TRANSFER', "Transfer", ("Transfer materials from non-empty slots to the result mesh, adding new materials as necessary.\n"
"For empty slots, fall back to using the same material index as the operand mesh."))),
default = 'INDEX',
)
use_self: bpy.props.BoolProperty(
@@ -60,7 +64,7 @@ class ModifierProperties():
layout.prop(self, "material_mode")
layout.prop(self, "use_self")
layout.prop(self, "use_hole_tolerant")
elif prefs.solver == 'FAST':
elif prefs.solver == 'FLOAT':
layout.prop(self, "double_threshold")
@@ -68,20 +72,20 @@ class ModifierProperties():
#### ------------------------------ /brush_boolean/ ------------------------------ ####
class BrushBoolean(ModifierProperties):
@classmethod
def poll(cls, context):
return basic_poll(cls, context)
def invoke(self, context, event):
# abort_when_no_selected_objects
# Abort if there are less than 2 selected objects.
if len(context.selected_objects) < 2:
self.report({'WARNING'}, "Boolean operator needs at least two selected objects")
return {'CANCELLED'}
# abort_when_linked
# Abort if active object is linked.
if is_linked(context, context.active_object):
self.report({'WARNING'}, "Booleans can not be performed on linked objects")
return {'CANCELLED'}
self.cutters = list_candidate_objects(self, context, context.active_object)
if len(self.cutters) == 0:
self.report({'WARNING'}, "Boolean operators cannot be performed on linked objects")
return {'CANCELLED'}
return self.execute(context)
@@ -90,20 +94,23 @@ class BrushBoolean(ModifierProperties):
def execute(self, context):
prefs = context.preferences.addons[base_package].preferences
canvas = context.active_object
cutters = list_candidate_objects(self, context, context.active_object)
# Create Slices
if len(cutters) == 0:
return {'CANCELLED'}
# Create slices.
if self.mode == "SLICE":
for cutter in self.cutters:
"""NOTE: Slices need to be created in separate loop to avoid inheriting boolean modifiers that operator adds"""
for cutter in cutters:
"""NOTE: Slices need to be created in a separate loop to avoid inheriting boolean modifiers that the operator adds."""
slice = create_slice(context, canvas, modifier=True)
add_boolean_modifier(self, context, slice, cutter, "INTERSECT", prefs.solver)
add_boolean_modifier(self, context, slice, cutter, "INTERSECT", prefs.solver, pin=prefs.pin)
for cutter in self.cutters:
for cutter in cutters:
mode = "DIFFERENCE" if self.mode == "SLICE" else self.mode
set_cutter_properties(context, canvas, cutter, self.mode, parent=prefs.parent, collection=prefs.use_collection)
add_boolean_modifier(self, context, canvas, cutter, "DIFFERENCE" if self.mode == "SLICE" else self.mode, prefs.solver, pin=prefs.pin)
add_boolean_modifier(self, context, canvas, cutter, mode, prefs.solver, pin=prefs.pin)
context.view_layer.objects.active = canvas
canvas.booleans.canvas = True
return {'FINISHED'}
@@ -115,10 +122,6 @@ class OBJECT_OT_boolean_brush_union(bpy.types.Operator, BrushBoolean):
bl_description = "Merge selected objects into active one"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return basic_poll(context)
mode = "UNION"
@@ -128,10 +131,6 @@ class OBJECT_OT_boolean_brush_intersect(bpy.types.Operator, BrushBoolean):
bl_description = "Only keep the parts of the active object that are interesecting selected objects"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return basic_poll(context)
mode = "INTERSECT"
@@ -141,10 +140,6 @@ class OBJECT_OT_boolean_brush_difference(bpy.types.Operator, BrushBoolean):
bl_description = "Subtract selected objects from active one"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return basic_poll(context)
mode = "DIFFERENCE"
@@ -154,10 +149,6 @@ class OBJECT_OT_boolean_brush_slice(bpy.types.Operator, BrushBoolean):
bl_description = "Slice active object along the selected ones. Will create slices as separate objects"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return basic_poll(context)
mode = "SLICE"
@@ -165,90 +156,89 @@ class OBJECT_OT_boolean_brush_slice(bpy.types.Operator, BrushBoolean):
#### ------------------------------ /auto_boolean/ ------------------------------ ####
class AutoBoolean(ModifierProperties):
@classmethod
def poll(cls, context):
return basic_poll(cls, context)
def invoke(self, context, event):
# abort_when_no_selected_objects
# Abort if there are less than 2 selected objects.
if len(context.selected_objects) < 2:
self.report({'WARNING'}, "Boolean operator needs at least two selected objects")
return {'CANCELLED'}
# abort_when_linked
# Abort if active object is linked.
if is_linked(context, context.active_object):
self.report({'ERROR'}, "Modifiers can't be applied to linked object")
return {'CANCELLED'}
self.cutters = list_candidate_objects(self, context, context.active_object)
if len(self.cutters) == 0:
self.report({'ERROR'}, "Modifiers cannot be applied to linked object")
return {'CANCELLED'}
if is_instanced_data(context.active_object):
return context.window_manager.invoke_confirm(self, event,
title="Auto Boolean", confirm_text="Yes", icon='WARNING',
message=("Canvas object has instanced object data.\n"
"In order to apply modifiers, it needs to be made single-user.\n"
"Do you proceed?"))
else:
return self.execute(context)
return destructive_op_confirmation(self, context, event, [context.active_object], title="Auto Boolean")
def execute(self, context):
prefs = context.preferences.addons[base_package].preferences
canvas = context.active_object
cutters = list_candidate_objects(self, context, context.active_object)
new_modifiers = defaultdict(list)
# apply_modifiers
if (prefs.apply_order == 'ALL') or (prefs.apply_order == 'BEFORE' and prefs.pin == False):
convert_to_mesh(context, canvas)
else:
if canvas.data.shape_keys:
self.report({'ERROR'}, "Modifiers can't be applied to object with shape keys")
return {'CANCELLED'}
if len(cutters) == 0:
return {'CANCELLED'}
# Create Slices
# Create slices.
if self.mode == "SLICE":
for cutter in self.cutters:
"""NOTE: Slices need to be created in separate loop to avoid inheriting boolean modifiers that operator adds"""
for cutter in cutters:
"""NOTE: Slices need to be created in a separate loop to avoid inheriting boolean modifiers that the operator adds."""
slice = create_slice(context, canvas)
add_boolean_modifier(self, context, slice, cutter, "INTERSECT", prefs.solver, apply=True, single_user=True)
modifier = add_boolean_modifier(self, context, slice, cutter, "INTERSECT", prefs.solver, pin=prefs.pin)
new_modifiers[slice].append(modifier)
slice.select_set(True)
for cutter in self.cutters:
# Add Modifier (& Apply)
for cutter in cutters:
# Add boolean modifier on canvas.
mode = "DIFFERENCE" if self.mode == "SLICE" else self.mode
add_boolean_modifier(self, context, canvas, cutter, mode, prefs.solver, apply=True, pin=prefs.pin, single_user=True)
modifier = add_boolean_modifier(self, context, canvas, cutter, mode, prefs.solver, pin=prefs.pin)
new_modifiers[canvas].append(modifier)
# Transfer Children
# Transfer cutters children to canvas.
for child in cutter.children:
change_parent(child, canvas)
# Delete Cutter
# Select all faces of the cutter so that newly created faces in canvas
# are also selected after applying the modifier.
for face in cutter.data.polygons:
face.select = True
# Apply modifiers on canvas & slices.
for obj, modifiers in new_modifiers.items():
modifiers = self._get_modifiers_to_apply(prefs, obj, modifiers)
apply_modifiers(context, obj, modifiers)
# Delete cutters.
for cutter in cutters:
delete_cutter(cutter)
if self.mode == "SLICE":
slice.select_set(True)
context.view_layer.objects.active = slice
# apply_modifiers_before_final_boolean
if prefs.apply_order == 'BEFORE' and prefs.pin:
modifiers = list_pre_boolean_modifiers(canvas)
for mod in modifiers:
apply_modifier(context, canvas, mod, single_user=True)
return {'FINISHED'}
def _get_modifiers_to_apply(self, prefs, obj, new_modifiers) -> list:
"""Returns a list of modifiers that need to be applied based on add-on preferences."""
if prefs.apply_order == 'ALL':
modifiers = [mod for mod in obj.modifiers]
elif prefs.apply_order == 'BOOLEANS':
modifiers = new_modifiers
elif prefs.apply_order == 'BEFORE':
modifiers = list_pre_boolean_modifiers(obj)
return modifiers
class OBJECT_OT_boolean_auto_union(bpy.types.Operator, AutoBoolean):
bl_idname = "object.boolean_auto_union"
bl_label = "Boolean Union (Auto)"
bl_description = "Merge selected objects into active one"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return basic_poll(context)
mode = "UNION"
@@ -258,10 +248,6 @@ class OBJECT_OT_boolean_auto_difference(bpy.types.Operator, AutoBoolean):
bl_description = "Subtract selected objects from active one"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return basic_poll(context)
mode = "DIFFERENCE"
@@ -271,10 +257,6 @@ class OBJECT_OT_boolean_auto_intersect(bpy.types.Operator, AutoBoolean):
bl_description = "Only keep the parts of the active object that are interesecting selected objects"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return basic_poll(context)
mode = "INTERSECT"
@@ -284,10 +266,6 @@ class OBJECT_OT_boolean_auto_slice(bpy.types.Operator, AutoBoolean):
bl_description = "Slice active object along the selected ones. Will create slices as separate objects"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return basic_poll(context)
mode = "SLICE"
@@ -317,7 +295,7 @@ def register():
addon = bpy.context.window_manager.keyconfigs.addon
km = addon.keymaps.new(name="Object Mode")
# brush_operators
# Brush Operators
kmi = km.keymap_items.new("object.boolean_brush_union", 'NUMPAD_PLUS', 'PRESS', ctrl=True)
kmi.active = True
addon_keymaps.append((km, kmi))
@@ -334,7 +312,7 @@ def register():
kmi.active = True
addon_keymaps.append((km, kmi))
# auto_operators
# Auto Operators
kmi = km.keymap_items.new("object.boolean_auto_union", 'NUMPAD_PLUS', 'PRESS', ctrl=True, shift=True)
kmi.active = True
addon_keymaps.append((km, kmi))
@@ -1,14 +1,17 @@
import bpy, itertools
import bpy
import itertools
from .. import __package__ as base_package
from ..functions.poll import (
basic_poll,
is_canvas,
is_instanced_data,
destructive_op_confirmation,
)
from ..functions.modifier import (
apply_modifiers,
)
from ..functions.object import (
apply_modifier,
convert_to_mesh,
object_visibility_set,
delete_empty_collection,
delete_cutter,
@@ -36,7 +39,7 @@ class OBJECT_OT_boolean_toggle_all(bpy.types.Operator):
@classmethod
def poll(cls, context):
return basic_poll(context, check_linked=True) and is_canvas(context.active_object)
return basic_poll(cls, context, check_linked=True) and is_canvas(context.active_object)
def execute(self, context):
canvases = list_selected_canvases(context)
@@ -79,7 +82,7 @@ class OBJECT_OT_boolean_remove_all(bpy.types.Operator):
@classmethod
def poll(cls, context):
return basic_poll(context, check_linked=True) and is_canvas(context.active_object)
return basic_poll(cls, context, check_linked=True) and is_canvas(context.active_object)
def execute(self, context):
prefs = context.preferences.addons[base_package].preferences
@@ -153,29 +156,12 @@ class OBJECT_OT_boolean_apply_all(bpy.types.Operator):
@classmethod
def poll(cls, context):
return basic_poll(context, check_linked=True) and is_canvas(context.active_object)
return basic_poll(cls, context, check_linked=True) and is_canvas(context.active_object)
def invoke(self, context, event):
# Filter Objects
self.canvases = []
for obj in list_selected_canvases(context):
# excude_canvases_with_shape_keys
if obj.data.shape_keys:
self.report({'ERROR'}, f"Modifiers can't be applied to {obj.name} because it has shape keys")
continue
self.canvases.append(obj)
if any(obj for obj in self.canvases if is_instanced_data(obj)):
return context.window_manager.invoke_confirm(self, event,
title="Apply Boolean Cutters", confirm_text="Yes", icon='WARNING',
message=("Canvas object(s) have instanced object data.\n"
"In order to apply modifiers, they need to be made single-user.\n"
"Do you proceed?"))
else:
return self.execute(context)
self.canvases = list_selected_canvases(context)
return destructive_op_confirmation(self, context, event, self.canvases, title="Apply Boolean Cutters")
def execute(self, context):
@@ -184,6 +170,8 @@ class OBJECT_OT_boolean_apply_all(bpy.types.Operator):
cutters, __ = list_canvas_cutters(self.canvases)
slices = list_canvas_slices(self.canvases)
# Select all faces of the cutter so that newly created faces in canvas
# are also selected after applying the modifier.
for cutter in cutters:
for face in cutter.data.polygons:
face.select = True
@@ -193,17 +181,13 @@ class OBJECT_OT_boolean_apply_all(bpy.types.Operator):
# Apply Modifiers
if prefs.apply_order == 'ALL':
convert_to_mesh(context, canvas)
modifiers = [mod for mod in canvas.modifiers]
elif prefs.apply_order == 'BEFORE':
modifiers = list_pre_boolean_modifiers(canvas)
for mod in modifiers:
apply_modifier(context, canvas, mod, single_user=True)
elif prefs.apply_order == 'BOOLEANS':
for mod in canvas.modifiers:
if mod.type == 'BOOLEAN' and "boolean_" in mod.name:
apply_modifier(context, canvas, mod, single_user=True)
modifiers = [mod for mod in canvas.modifiers if mod.type == 'BOOLEAN' and "boolean_" in mod.name]
apply_modifiers(context, canvas, modifiers)
# remove_boolean_properties
canvas.booleans.canvas = False
@@ -4,9 +4,12 @@ from .. import __package__ as base_package
from ..functions.poll import (
basic_poll,
is_instanced_data,
destructive_op_confirmation,
)
from ..functions.modifier import (
apply_modifiers,
)
from ..functions.object import (
apply_modifier,
object_visibility_set,
delete_empty_collection,
delete_cutter,
@@ -45,7 +48,7 @@ class OBJECT_OT_boolean_toggle_cutter(bpy.types.Operator):
@classmethod
def poll(cls, context):
return basic_poll(context, check_linked=True)
return basic_poll(cls, context, check_linked=True)
def execute(self, context):
if self.method == 'SPECIFIED':
@@ -118,7 +121,7 @@ class OBJECT_OT_boolean_remove_cutter(bpy.types.Operator):
@classmethod
def poll(cls, context):
return basic_poll(context, check_linked=True)
return basic_poll(cls, context, check_linked=True)
def execute(self, context):
prefs = context.preferences.addons[base_package].preferences
@@ -220,7 +223,7 @@ class OBJECT_OT_boolean_apply_cutter(bpy.types.Operator):
@classmethod
def poll(cls, context):
return basic_poll(context, check_linked=True)
return basic_poll(cls, context, check_linked=True)
def invoke(self, context, event):
@@ -232,25 +235,9 @@ class OBJECT_OT_boolean_apply_cutter(bpy.types.Operator):
elif self.method == 'ALL':
self.cutters = list_selected_cutters(context)
self.canvases = []
self.canvases = list_cutter_users(self.cutters)
for obj in list_cutter_users(self.cutters):
# excude_canvases_with_shape_keys
if obj.data.shape_keys:
self.report({'ERROR'}, f"Modifiers can't be applied to {obj.name} because it has shape keys")
continue
self.canvases.append(obj)
if any(obj for obj in self.canvases if is_instanced_data(obj)):
return context.window_manager.invoke_confirm(self, event,
title="Apply Boolean Cutter", confirm_text="Yes", icon='WARNING',
message=("Canvas object(s) have instanced object data.\n"
"In order to apply modifiers, they need to be made single-user.\n"
"Do you proceed?"))
else:
return self.execute(context)
return destructive_op_confirmation(self, context, event, self.canvases, title="Apply Boolean Cutter")
def execute(self, context):
@@ -258,6 +245,8 @@ class OBJECT_OT_boolean_apply_cutter(bpy.types.Operator):
leftovers = []
if self.cutters:
# Select all faces of the cutter so that newly created faces in canvas
# are also selected after applying the modifier.
for cutter in self.cutters:
for face in cutter.data.polygons:
face.select = True
@@ -266,10 +255,12 @@ class OBJECT_OT_boolean_apply_cutter(bpy.types.Operator):
for canvas in self.canvases:
context.view_layer.objects.active = canvas
boolean_mods = []
for mod in canvas.modifiers:
if "boolean_" in mod.name:
if mod.object in self.cutters:
apply_modifier(context, canvas, mod, single_user=True)
boolean_mods.append(mod)
apply_modifiers(context, canvas, boolean_mods)
# remove_canvas_property_if_needed
other_cutters, __ = list_canvas_cutters([canvas])
@@ -281,9 +272,11 @@ class OBJECT_OT_boolean_apply_cutter(bpy.types.Operator):
if self.method == 'SPECIFIED':
# Apply Modifier for Slices (for_specified_method)
for slice in self.slices:
boolean_mods = []
for mod in slice.modifiers:
if mod.type == 'BOOLEAN' and mod.object in self.cutters:
apply_modifier(context, slice, mod, single_user=True)
boolean_mods.append(mod)
apply_modifiers(context, slice, boolean_mods)
unused_cutters, leftovers = list_unused_cutters(self.cutters, self.canvases, do_leftovers=True)
@@ -25,7 +25,7 @@ class OBJECT_OT_select_cutter_canvas(bpy.types.Operator):
@classmethod
def poll(cls, context):
return basic_poll(context) and context.active_object.booleans.cutter
return basic_poll(cls, context) and context.active_object.booleans.cutter
def execute(self, context):
cutters = list_selected_cutters(context)
@@ -48,7 +48,7 @@ class OBJECT_OT_boolean_select_all(bpy.types.Operator):
@classmethod
def poll(cls, context):
return basic_poll(context) and is_canvas(context.active_object)
return basic_poll(cls, context) and is_canvas(context.active_object)
def execute(self, context):
canvases = list_selected_canvases(context)
@@ -72,7 +72,7 @@ class OBJECT_OT_boolean_select_cutter(bpy.types.Operator):
@classmethod
def poll(cls, context):
prefs = context.preferences.addons[base_package].preferences
return (basic_poll(context) and active_modifier_poll(context) and
return (basic_poll(cls, context) and active_modifier_poll(context.active_object) and
context.area.type == 'PROPERTIES' and context.space_data.context == 'MODIFIER' and
prefs.double_click)
@@ -5,7 +5,7 @@ from . import ui
#### ------------------------------ FUNCTIONS ------------------------------ ####
def update_sidebar_category(self, context):
"""Change sidebar category of add-ons panels"""
"""Change sidebar category of add-ons panel."""
panel_classes = [
ui.VIEW3D_PT_boolean,
@@ -31,13 +31,12 @@ class BoolToolPreferences(bpy.types.AddonPreferences):
# UI
show_in_sidebar: bpy.props.BoolProperty(
name = "Show Addon Panel in Sidebar",
description = ("Add add-on operators and properties to 3D viewport sidebar category.\n"
"Most of the features are already available in 3D viewport's Object > Boolean menu, but brush list is only in sidebar panel"),
description = "Add a sidebar panel in 3D Viewport with add-ons operators and properties",
default = True,
)
sidebar_category: bpy.props.StringProperty(
name = "Category Name",
description = "Set sidebar category name. You can type in name of the existing category and panel will be added there, instead of creating new category",
description = "Sidebar category name. Using the name of the existing category will add panel there",
default = "Edit",
update = update_sidebar_category,
)
@@ -46,9 +45,10 @@ class BoolToolPreferences(bpy.types.AddonPreferences):
solver: bpy.props.EnumProperty(
name = "Boolean Solver",
description = "Which solver to use for automatic and brush booleans",
items = [('FAST', "Fast", ""),
('EXACT', "Exact", "")],
default = 'FAST',
items = [('FLOAT', "Float", ""),
('EXACT', "Exact", ""),
('MANIFOLD', "Manifold", "")],
default = 'FLOAT',
)
wireframe: bpy.props.BoolProperty(
name = "Display Cutters as Wireframe",
@@ -98,6 +98,14 @@ class BoolToolPreferences(bpy.types.AddonPreferences):
)
# Features
fast_modifier_apply: bpy.props.BoolProperty(
name = "Faster Destructive Booleans",
description = ("Experimental method of applying modifiers that results in 30-50% faster destructive booleans.\n"
"Performance improvements also affect the add-ons operators that apply cutters.\n"
"However, changing modifier properties in the redo panel (like material transfer)\n"
"is not available for this method yet."),
default = False,
)
double_click: bpy.props.BoolProperty(
name = "Double-click Select",
description = ("Select boolean cutters by dbl-clicking on the boolean modifier.\n"
@@ -157,6 +165,7 @@ class BoolToolPreferences(bpy.types.AddonPreferences):
# Features
layout.separator()
col = layout.column(align=True, heading="Features")
col.prop(self, "fast_modifier_apply")
col.prop(self, "double_click")
# Experimentals
@@ -1,19 +1,59 @@
import bpy
from . import (
carver,
)
if "bpy" in locals():
import importlib
for mod in [carver_box,
carver_circle,
carver_polyline,
ui,
]:
importlib.reload(mod)
else:
import bpy
from . import (
carver_box,
carver_circle,
carver_polyline,
)
from .common import (
ui,
)
#### ------------------------------ REGISTRATION ------------------------------ ####
modules = [
carver,
carver_box,
# carver_circle,
carver_polyline,
ui,
]
main_tools = [
carver_box.OBJECT_WT_carve_box,
carver_box.MESH_WT_carve_box,
]
secondary_tools = [
carver_circle.OBJECT_WT_carve_circle,
carver_circle.MESH_WT_carve_circle,
carver_polyline.OBJECT_WT_carve_polyline,
carver_polyline.MESH_WT_carve_polyline,
]
def register():
for module in modules:
module.register()
for tool in main_tools:
bpy.utils.register_tool(tool, separator=False, after="builtin.primitive_cube_add", group=True)
for tool in secondary_tools:
bpy.utils.register_tool(tool, separator=False, after="object.carve_box", group=False)
def unregister():
for module in reversed(modules):
module.unregister()
for tool in main_tools:
bpy.utils.unregister_tool(tool)
for tool in secondary_tools:
bpy.utils.unregister_tool(tool)
@@ -1,798 +0,0 @@
import bpy, mathutils, math, os
from .. import __package__ as base_package
from ..functions.draw import (
carver_overlay,
)
from ..functions.object import (
add_boolean_modifier,
set_cutter_properties,
delete_cutter,
set_object_origin,
)
from ..functions.mesh import (
create_cutter_shape,
extrude,
shade_smooth_by_angle,
)
from ..functions.select import (
cursor_snap,
selection_fallback,
)
#### ------------------------------ /tool_shelf_draw/ ------------------------------ ####
class CarverToolshelf():
def draw_settings(context, layout, tool):
props = tool.operator_properties("object.carve")
if context.object:
mode = "OBJECT" if context.object.mode == 'OBJECT' else "EDIT_MESH"
active_tool = context.workspace.tools.from_space_view3d_mode(mode, create=False).idname
layout.prop(props, "mode", text="")
layout.prop(props, "depth", text="")
row = layout.row()
row.prop(props, "solver", expand=True)
if context.object:
layout.popover("TOPBAR_PT_carver_shape", text="Shape")
layout.popover("TOPBAR_PT_carver_array", text="Array")
layout.popover("TOPBAR_PT_carver_cutter", text="Cutter")
class TOPBAR_PT_carver_shape(bpy.types.Panel):
bl_label = "Carver Shape"
bl_idname = "TOPBAR_PT_carver_shape"
bl_region_type = 'HEADER'
bl_space_type = 'TOPBAR'
bl_category = 'Tool'
def draw(self, context):
layout = self.layout
layout.use_property_split = True
prefs = context.preferences.addons[base_package].preferences
mode = "OBJECT" if context.object.mode == 'OBJECT' else "EDIT_MESH"
tool = context.workspace.tools.from_space_view3d_mode(mode, create=False)
op = tool.operator_properties("object.carve")
if tool.idname == "object.carve_polyline":
layout.prop(op, "closed")
else:
if tool.idname == "object.carve_circle":
layout.prop(op, "subdivision", text="Vertices")
layout.prop(op, "rotation")
layout.prop(op, "aspect", expand=True)
layout.prop(op, "origin", expand=True)
if tool.idname == 'object.carve_box':
layout.separator()
layout.prop(op, "use_bevel", text="Bevel")
col = layout.column(align=True)
row = col.row(align=True)
if prefs.experimental:
row.prop(op, "bevel_profile", text="Profile", expand=True)
col.prop(op, "bevel_segments", text="Segments")
col.prop(op, "bevel_radius", text="Radius")
if op.use_bevel == False:
col.enabled = False
class TOPBAR_PT_carver_array(bpy.types.Panel):
bl_label = "Carver Array"
bl_idname = "TOPBAR_PT_carver_array"
bl_region_type = 'HEADER'
bl_space_type = 'TOPBAR'
bl_category = 'Tool'
def draw(self, context):
layout = self.layout
layout.use_property_split = True
mode = "OBJECT" if context.object.mode == 'OBJECT' else "EDIT_MESH"
tool = context.workspace.tools.from_space_view3d_mode(mode, create=False)
op = tool.operator_properties("object.carve")
col = layout.column(align=True)
col.prop(op, "rows")
row = col.row(align=True)
row.prop(op, "rows_direction", text="Direction", expand=True)
col.prop(op, "rows_gap", text="Gap")
layout.separator()
col = layout.column(align=True)
col.prop(op, "columns")
row = col.row(align=True)
row.prop(op, "columns_direction", text="Direction", expand=True)
col.prop(op, "columns_gap", text="Gap")
class TOPBAR_PT_carver_cutter(bpy.types.Panel):
bl_label = "Carver Cutter"
bl_idname = "TOPBAR_PT_carver_cutter"
bl_region_type = 'HEADER'
bl_space_type = 'TOPBAR'
bl_category = 'Tool'
def draw(self, context):
layout = self.layout
layout.use_property_split = True
mode = "OBJECT" if context.object.mode == 'OBJECT' else "EDIT_MESH"
tool = context.workspace.tools.from_space_view3d_mode(mode, create=False)
op = tool.operator_properties("object.carve")
col = layout.column()
col.prop(op, "pin", text="Pin Modifier")
col.prop(op, "parent")
if op.mode == 'MODIFIER':
col.prop(op, "hide")
# auto_smooth
layout.separator()
col = layout.column(align=True)
col.prop(op, "auto_smooth", text="Auto Smooth")
col.prop(op, "sharp_angle")
#### ------------------------------ TOOLS ------------------------------ ####
class OBJECT_WT_carve_box(bpy.types.WorkSpaceTool, CarverToolshelf):
bl_idname = "object.carve_box"
bl_label = "Box Carve"
bl_description = ("Boolean cut rectangular shapes into mesh objects")
bl_space_type = 'VIEW_3D'
bl_context_mode = 'OBJECT'
bl_icon = os.path.join(os.path.join(os.path.dirname(os.path.dirname(__file__)), "icons") , "ops.object.carver_box")
# bl_widget = 'VIEW3D_GGT_placement'
bl_keymap = (
("object.carve", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG'}, {"properties": [("shape", 'BOX')]}),
("object.carve", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG', "shift": True}, {"properties": [("shape", 'BOX')]}),
("object.carve", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG', "alt": True}, {"properties": [("shape", 'BOX')]}),
("object.carve", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG', "shift": True, "alt": True}, {"properties": [("shape", 'BOX')]}),
("object.carve", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG', "ctrl": True}, {"properties": [("shape", 'BOX')]}),
("object.carve", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG', "ctrl": True, "shift": True}, {"properties": [("shape", 'BOX')]}),
("object.carve", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG', "ctrl": True, "alt": True}, {"properties": [("shape", 'BOX')]}),
("object.carve", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG', "ctrl": True, "shift": True, "alt": True}, {"properties": [("shape", 'BOX')]}),
)
class MESH_WT_carve_box(OBJECT_WT_carve_box):
bl_context_mode = 'EDIT_MESH'
class OBJECT_WT_carve_circle(bpy.types.WorkSpaceTool, CarverToolshelf):
bl_idname = "object.carve_circle"
bl_label = "Circle Carve"
bl_description = ("Boolean cut circlular shapes into mesh objects")
bl_space_type = 'VIEW_3D'
bl_context_mode = 'OBJECT'
bl_icon = os.path.join(os.path.join(os.path.dirname(os.path.dirname(__file__)), "icons") , "ops.object.carver_circle")
# bl_widget = 'VIEW3D_GGT_placement'
bl_keymap = (
("object.carve", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG'}, {"properties": [("shape", 'CIRCLE')]}),
("object.carve", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG', "shift": True}, {"properties": [("shape", 'CIRCLE')]}),
("object.carve", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG', "alt": True}, {"properties": [("shape", 'CIRCLE')]}),
("object.carve", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG', "shift": True, "alt": True}, {"properties": [("shape", 'CIRCLE')]}),
("object.carve", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG', "ctrl": True}, {"properties": [("shape", 'CIRCLE')]}),
("object.carve", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG', "ctrl": True, "shift": True}, {"properties": [("shape", 'CIRCLE')]}),
("object.carve", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG', "ctrl": True, "alt": True}, {"properties": [("shape", 'CIRCLE')]}),
("object.carve", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG', "ctrl": True, "shift": True, "alt": True}, {"properties": [("shape", 'CIRCLE')]}),
)
class MESH_WT_carve_circle(OBJECT_WT_carve_circle):
bl_context_mode = 'EDIT_MESH'
class OBJECT_WT_carve_polyline(bpy.types.WorkSpaceTool, CarverToolshelf):
bl_idname = "object.carve_polyline"
bl_label = "Polyline Carve"
bl_description = ("Boolean cut custom polygonal shapes into mesh objects")
bl_space_type = 'VIEW_3D'
bl_context_mode = 'OBJECT'
bl_icon = os.path.join(os.path.join(os.path.dirname(os.path.dirname(__file__)), "icons") , "ops.object.carver_polyline")
# bl_widget = 'VIEW3D_GGT_placement'
bl_keymap = (
("object.carve", {"type": 'LEFTMOUSE', "value": 'CLICK'}, {"properties": [("shape", 'POLYLINE')]}),
("object.carve", {"type": 'LEFTMOUSE', "value": 'CLICK', "ctrl": True}, {"properties": [("shape", 'POLYLINE')]}),
# select
("view3d.select_box", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG'}, None),
("view3d.select_box", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG', "shift": True}, {"properties": [("mode", 'ADD')]}),
("view3d.select_box", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG', "ctrl": True}, {"properties": [("mode", 'SUB')]}),
)
class MESH_WT_carve_polyline(OBJECT_WT_carve_polyline):
bl_context_mode = 'EDIT_MESH'
#### ------------------------------ OPERATORS ------------------------------ ####
class OBJECT_OT_carve(bpy.types.Operator):
bl_idname = "object.carve"
bl_label = "Carve"
bl_description = "Boolean cut square shapes into mesh objects"
bl_options = {'REGISTER', 'UNDO', 'DEPENDS_ON_CURSOR'}
bl_cursor_pending = 'PICK_AREA'
# OPERATOR-properties
shape: bpy.props.EnumProperty(
name = "Shape",
items = (('BOX', "Box", ""),
('CIRCLE', "Circle", ""),
('POLYLINE', "Polyline", "")),
default = 'BOX',
)
mode: bpy.props.EnumProperty(
name = "Mode",
items = (('DESTRUCTIVE', "Destructive", "Boolean cutters are immediatelly applied and removed after the cut", 'MESH_DATA', 0),
('MODIFIER', "Modifier", "Cuts are stored as boolean modifiers and cutters placed inside the collection", 'MODIFIER_DATA', 1)),
default = 'DESTRUCTIVE',
)
# orientation: bpy.props.EnumProperty(
# name = "Orientation",
# items = (('SURFACE', "Surface", "Surface normal of the mesh under the cursor"),
# ('VIEW', "View", "View-aligned orientation")),
# default = 'SURFACE',
# )
depth: bpy.props.EnumProperty(
name = "Depth",
items = (('VIEW', "View", "Depth is automatically calculated from view orientation", 'VIEW_CAMERA_UNSELECTED', 0),
('CURSOR', "Cursor", "Depth is automatically set at 3D cursor location", 'PIVOT_CURSOR', 1)),
default = 'VIEW',
)
# SHAPE-properties
aspect: bpy.props.EnumProperty(
name = "Aspect",
items = (('FREE', "Free", "Use an unconstrained aspect"),
('FIXED', "Fixed", "Use a fixed 1:1 aspect")),
default = 'FREE',
)
origin: bpy.props.EnumProperty(
name = "Origin",
description = "The initial position for placement",
items = (('EDGE', "Edge", ""),
('CENTER', "Center", "")),
default = 'EDGE',
)
rotation: bpy.props.FloatProperty(
name = "Rotation",
subtype = "ANGLE",
soft_min = -360, soft_max = 360,
default = 0,
)
subdivision: bpy.props.IntProperty(
name = "Circle Subdivisions",
description = "Number of vertices that will make up the circular shape that will be extruded into a cylinder",
min = 3, soft_max = 128,
default = 16,
)
closed: bpy.props.BoolProperty(
name = "Closed Polygon",
description = "When enabled, mouse position at the moment of execution will be registered as last point of the polygon",
default = True,
)
# CUTTER-properties
hide: bpy.props.BoolProperty(
name = "Hide Cutter",
description = ("Hide cutter objects in the viewport after they're created.\n"
"NOTE: They are hidden in render regardless of this property"),
default = True,
)
parent: bpy.props.BoolProperty(
name = "Parent to Canvas",
description = ("Cutters will be parented to active object being cut, even if cutting multiple objects.\n"
"If there is no active object in selection cutters parent might be chosen seemingly randomly"),
default = True,
)
auto_smooth: bpy.props.BoolProperty(
name = "Shade Auto Smooth",
description = ("Cutter object will be shaded smooth with sharp edges (above 30 degrees) marked as sharp\n"
"NOTE: This is one time operator. 'Smooth by Angle' modifier will not be added on object"),
default = True,
)
sharp_angle: bpy.props.FloatProperty(
name = "Angle",
description = "Maximum face angle for sharp edges",
subtype = "ANGLE",
min = 0, max = math.pi,
default = 0.523599,
)
# ARRAY-properties
rows: bpy.props.IntProperty(
name = "Rows",
description = "Number of times shape is duplicated on X axis",
min = 1, soft_max = 16,
default = 1,
)
rows_gap: bpy.props.FloatProperty(
name = "Gap between Rows",
min = 0, soft_max = 250,
default = 50,
)
rows_direction: bpy.props.EnumProperty(
name = "Direction of Rows",
items = (('LEFT', "Left", ""),
('RIGHT', "Right", "")),
default = 'RIGHT',
)
columns: bpy.props.IntProperty(
name = "Columns",
description = "Number of times shape is duplicated on Y axis",
min = 1, soft_max = 16,
default = 1,
)
columns_direction: bpy.props.EnumProperty(
name = "Direction of Rows",
items = (('UP', "Up", ""),
('DOWN', "Down", "")),
default = 'DOWN',
)
columns_gap: bpy.props.FloatProperty(
name = "Gap between Columns",
min = 0, soft_max = 250,
default = 50,
)
# BEVEL-properties
use_bevel: bpy.props.BoolProperty(
name = "Bevel Cutter",
description = "Bevel each side edge of the cutter",
default = False,
)
bevel_profile: bpy.props.EnumProperty(
name = "Bevel Profile",
items = (('CONVEX', "Convex", "Outside bevel (rounded corners)"),
('CONCAVE', "Concave", "Inside bevel")),
default = 'CONVEX',
)
bevel_segments: bpy.props.IntProperty(
name = "Bevel Segments",
description = "Segments for curved edge",
min = 2, soft_max = 32,
default = 8,
)
bevel_radius: bpy.props.FloatProperty(
name = "Bevel Radius",
description = "Amout of the bevel (in screen-space units)",
min = 0.01, soft_max = 5,
default = 1,
)
# MODIFIER-properties
solver: bpy.props.EnumProperty(
name = "Solver",
items = [('FAST', "Fast", ""),
('EXACT', "Exact", "")],
default = 'FAST',
)
pin: bpy.props.BoolProperty(
name = "Pin Boolean Modifier",
description = ("When enabled boolean modifier will be moved above every other modifier on the object (if there are any).\n"
"Order of modifiers can drastically affect the result (especially in destructive mode)"),
default = True,
)
@classmethod
def poll(cls, context):
return context.mode in ('OBJECT', 'EDIT_MESH') and context.area.type == 'VIEW_3D'
def invoke(self, context, event):
self.selected_objects = context.selected_objects
self.initial_selection = context.selected_objects
self.mouse_path = [(event.mouse_region_x, event.mouse_region_y),
(event.mouse_region_x, event.mouse_region_y)]
# initialize_empty_values
self.verts = []
self.cutter = None
self.duplicates = []
self.view_depth = mathutils.Vector()
self.cached_mouse_position = ()
# modifier_keys
self.initial_origin = self.origin
self.initial_aspect = self.aspect
self.snap = False
self.move = False
self.rotate = False
self.gap = False
self.bevel = False
# overlay_position
self.position_x = 0
self.position_y = 0
self.initial_position = False
self.center_origin = []
self.distance_from_first = 0
# Add Draw Handler
self._handle = bpy.types.SpaceView3D.draw_handler_add(carver_overlay, (self, bpy.context), 'WINDOW', 'POST_PIXEL')
context.window.cursor_set("MUTE")
context.window_manager.modal_handler_add(self)
return {'RUNNING_MODAL'}
def modal(self, context, event):
snap_text = ", [MOUSEWHEEL]: Change Snapping Increment" if self.snap else ""
if self.shape == 'POLYLINE':
shape_text = "[BACKSPACE]: Remove Last Point, [ENTER]: Confirm"
else:
shape_text = "[SHIFT]: Aspect, [ALT]: Origin, [R]: Rotate, [ARROWS]: Array"
array_text = ", [A]: Gap" if (self.rows > 1 or self.columns > 1) else ""
bevel_text = ", [B]: Bevel" if self.shape == 'BOX' else ""
context.workspace.status_text_set("[CTRL]: Snap Invert, [SPACEBAR]: Move, " + shape_text + bevel_text + array_text + snap_text)
# find_the_limit_of_the_3d_viewport_region
region_types = {'WINDOW', 'UI'}
for area in context.window.screen.areas:
if area.type == 'VIEW_3D':
for region in area.regions:
if not region_types or region.type in region_types:
region.tag_redraw()
# SNAP
# change_the_snap_increment_value_using_the_wheel_mouse
if (self.move is False) and (self.rotate is False):
for i, a in enumerate(context.screen.areas):
if a.type == 'VIEW_3D':
space = context.screen.areas[i].spaces.active
if event.type == 'WHEELUPMOUSE':
space.overlay.grid_subdivisions -= 1
elif event.type == 'WHEELDOWNMOUSE':
space.overlay.grid_subdivisions += 1
self.snap = context.scene.tool_settings.use_snap
if event.ctrl and (self.move is False) and (self.rotate is False):
self.snap = not self.snap
# ASPECT
if event.shift and (self.shape != 'POLYLINE'):
if self.initial_aspect == 'FREE':
self.aspect = 'FIXED'
elif self.initial_aspect == 'FIXED':
self.aspect = 'FREE'
else:
self.aspect = self.initial_aspect
# ORIGIN
if event.alt and (self.shape != 'POLYLINE'):
if self.initial_origin == 'EDGE':
self.origin = 'CENTER'
elif self.initial_origin == 'CENTER':
self.origin = 'EDGE'
else:
self.origin = self.initial_origin
# ROTATE
if event.type == 'R' and (self.shape != 'POLYLINE'):
if event.value == 'PRESS':
self.cached_mouse_position = (self.mouse_path[1][0], self.mouse_path[1][1])
context.window.cursor_set("NONE")
self.rotate = True
elif event.value == 'RELEASE':
context.window.cursor_set("MUTE")
context.window.cursor_warp(int(self.cached_mouse_position[0]), int(self.cached_mouse_position[1]))
self.rotate = False
# BEVEL
if event.type == 'B' and (self.shape == 'BOX'):
if event.value == 'PRESS':
self.use_bevel = True
self.cached_mouse_position = (self.mouse_path[1][0], self.mouse_path[1][1])
context.window.cursor_set("NONE")
self.bevel = True
elif event.value == 'RELEASE':
context.window.cursor_set("MUTE")
context.window.cursor_warp(int(self.cached_mouse_position[0]), int(self.cached_mouse_position[1]))
self.bevel = False
if self.bevel:
if event.type == 'WHEELUPMOUSE':
self.bevel_segments += 1
elif event.type == 'WHEELDOWNMOUSE':
self.bevel_segments -= 1
# ARRAY
if event.type == 'LEFT_ARROW' and event.value == 'PRESS':
self.rows -= 1
if event.type == 'RIGHT_ARROW' and event.value == 'PRESS':
self.rows += 1
if event.type == 'DOWN_ARROW' and event.value == 'PRESS':
self.columns -= 1
if event.type == 'UP_ARROW' and event.value == 'PRESS':
self.columns += 1
if (self.rows > 1 or self.columns > 1) and (event.type == 'A'):
if event.value == 'PRESS':
self.cached_mouse_position = (self.mouse_path[1][0], self.mouse_path[1][1])
context.window.cursor_set("NONE")
self.gap = True
elif event.value == 'RELEASE':
context.window.cursor_set("MUTE")
context.window.cursor_warp(self.cached_mouse_position[0], self.cached_mouse_position[1])
self.gap = False
# MOVE
if event.type == 'SPACE':
if event.value == 'PRESS':
self.move = True
elif event.value == 'RELEASE':
self.move = False
if self.move:
# initial_position_variable_before_moving_the_brush
if self.initial_position is False:
self.position_x = 0
self.position_y = 0
self.last_mouse_region_x = event.mouse_region_x
self.last_mouse_region_y = event.mouse_region_y
self.initial_position = True
self.move = True
# update_the_coordinates
if self.initial_position and self.move is False:
for i in range(0, len(self.mouse_path)):
l = list(self.mouse_path[i])
l[0] += self.position_x
l[1] += self.position_y
self.mouse_path[i] = tuple(l)
self.position_x = self.position_y = 0
self.initial_position = False
# Remove Point (Polyline)
if event.type == 'BACK_SPACE' and event.value == 'PRESS':
if len(self.mouse_path) > 2:
context.window.cursor_warp(self.mouse_path[-2][0], self.mouse_path[-2][1])
self.mouse_path = self.mouse_path[:-2]
if event.type in {'MIDDLEMOUSE', 'N', 'NUMPAD_1', 'NUMPAD_2', 'NUMPAD_3', 'NUMPAD_4',
'NUMPAD_5', 'NUMPAD_6', 'NUMPAD_7', 'NUMPAD_8', 'NUMPAD_9'}:
return {'PASS_THROUGH'}
if self.bevel == False and event.type in {'WHEELUPMOUSE', 'WHEELDOWNMOUSE'}:
return {'PASS_THROUGH'}
# mouse_move
if event.type == 'MOUSEMOVE':
if self.rotate:
self.rotation = event.mouse_region_x * 0.01
elif self.move:
# MOVE
self.position_x += (event.mouse_region_x - self.last_mouse_region_x)
self.position_y += (event.mouse_region_y - self.last_mouse_region_y)
self.last_mouse_region_x = event.mouse_region_x
self.last_mouse_region_y = event.mouse_region_y
elif self.gap:
self.rows_gap = event.mouse_region_x * 0.1
self.columns_gap = event.mouse_region_y * 0.1
elif self.bevel:
self.bevel_radius = event.mouse_region_x * 0.002
else:
if len(self.mouse_path) > 0:
# ASPECT
if self.aspect == 'FIXED':
side = max(abs(event.mouse_region_x - self.mouse_path[0][0]),
abs(event.mouse_region_y - self.mouse_path[0][1]))
self.mouse_path[len(self.mouse_path) - 1] = \
(self.mouse_path[0][0] + (side if event.mouse_region_x >= self.mouse_path[0][0] else -side),
self.mouse_path[0][1] + (side if event.mouse_region_y >= self.mouse_path[0][1] else -side))
elif self.aspect == 'FREE':
self.mouse_path[len(self.mouse_path) - 1] = (event.mouse_region_x, event.mouse_region_y)
# SNAP (find_the_closest_position_on_the_overlay_grid_and_snap_the_shape_to_it)
if self.snap:
cursor_snap(self, context, event, self.mouse_path)
if self.shape == 'POLYLINE':
# get_distance_from_first_point
distance = math.sqrt((self.mouse_path[-1][0] - self.mouse_path[0][0]) ** 2 +
(self.mouse_path[-1][1] - self.mouse_path[0][1]) ** 2)
min_radius = 0
max_radius = 30
self.distance_from_first = max(max_radius - distance, min_radius)
# Confirm
elif (event.type == 'LEFTMOUSE' and event.value == 'RELEASE') or (event.type == 'RET' and event.value == 'PRESS'):
# selection_fallback
if self.shape != 'POLYLINE':
if len(self.selected_objects) == 0:
self.selected_objects = selection_fallback(self, context, context.view_layer.objects)
for obj in self.selected_objects:
obj.select_set(True)
if len(self.selected_objects) == 0:
self.cancel(context)
return {'FINISHED'}
else:
empty = self.selection_fallback(context)
if empty:
return {'FINISHED'}
else:
if len(self.initial_selection) == 0:
# expand_selection_fallback_on_every_polyline_click
self.selected_objects = selection_fallback(self, context, context.view_layer.objects)
for obj in self.selected_objects:
obj.select_set(True)
# Polyline
if self.shape == 'POLYLINE':
if not (event.type == 'RET' and event.value == 'PRESS') and (self.distance_from_first < 15):
self.mouse_path.append((event.mouse_region_x, event.mouse_region_y))
if self.closed == False:
# NOTE: Additional vert is needed for open loop.
self.mouse_path.append((event.mouse_region_x, event.mouse_region_y))
else:
# Confirm Cut (Polyline)
if self.closed == False:
self.verts.pop() # dont_add_current_mouse_position_as_vert
if self.distance_from_first > 15:
self.verts[-1] = self.verts[0]
if len(self.verts) / 2 <= 1:
self.report({'INFO'}, "At least two points are required to make polygonal shape")
self.cancel(context)
return {'FINISHED'}
if self.closed and self.mouse_path[-1] == self.mouse_path[-2]:
context.window.cursor_warp(event.mouse_region_x - 1, event.mouse_region_y)
# NOTE: Polyline needs separate selection fallback, because it needs to calculate selection bounding box...
# NOTE: after all points are already drawn, i.e. before execution.
empty = self.selection_fallback(context)
if empty:
return {'FINISHED'}
self.confirm(context)
return {'FINISHED'}
# Confirm Cut (Box, Circle)
else:
# protection_against_returning_no_rectangle_by_clicking
delta_x = abs(event.mouse_region_x - self.mouse_path[0][0])
delta_y = abs(event.mouse_region_y - self.mouse_path[0][1])
min_distance = 5
if delta_x > min_distance or delta_y > min_distance:
self.confirm(context)
return {'FINISHED'}
# Cancel
elif event.type in {'RIGHTMOUSE', 'ESC'}:
self.cancel(context)
return {'FINISHED'}
return {'RUNNING_MODAL'}
def confirm(self, context):
create_cutter_shape(self, context)
extrude(self, self.cutter.data)
set_object_origin(self.cutter)
if self.auto_smooth:
shade_smooth_by_angle(self.cutter, angle=math.degrees(self.sharp_angle))
self.Cut(context)
self.cancel(context)
def cancel(self, context):
bpy.types.SpaceView3D.draw_handler_remove(self._handle, 'WINDOW')
context.workspace.status_text_set(None)
context.window.cursor_set('DEFAULT' if context.object.mode == 'OBJECT' else 'CROSSHAIR')
def selection_fallback(self, context):
# filter_out_objects_not_inside_the_selection_bounding_box
self.selected_objects = selection_fallback(self, context, self.selected_objects, include_cutters=True)
# silently_fail_if_no_objects_inside_selection_bounding_box
empty = False
if len(self.selected_objects) == 0:
self.cancel(context)
empty = True
return empty
def Cut(self, context):
# ensure_active_object
if not context.active_object:
context.view_layer.objects.active = self.selected_objects[0]
# Add Modifier
for obj in self.selected_objects:
if self.mode == 'DESTRUCTIVE':
add_boolean_modifier(self, context, obj, self.cutter, "DIFFERENCE", self.solver, apply=True, pin=self.pin, redo=False)
elif self.mode == 'MODIFIER':
add_boolean_modifier(self, context, obj, self.cutter, "DIFFERENCE", self.solver, pin=self.pin, redo=False)
obj.booleans.canvas = True
if self.mode == 'DESTRUCTIVE':
# Remove Cutter
delete_cutter(self.cutter)
elif self.mode == 'MODIFIER':
# Set Cutter Properties
canvas = None
if context.active_object and context.active_object in self.selected_objects:
canvas = context.active_object
else:
canvas = self.selected_objects[0]
set_cutter_properties(context, canvas, self.cutter, "Difference", parent=self.parent, hide=self.hide)
#### ------------------------------ REGISTRATION ------------------------------ ####
classes = [
OBJECT_OT_carve,
TOPBAR_PT_carver_shape,
TOPBAR_PT_carver_array,
TOPBAR_PT_carver_cutter,
]
main_tools = [
OBJECT_WT_carve_box,
MESH_WT_carve_box,
]
secondary_tools = [
OBJECT_WT_carve_circle,
OBJECT_WT_carve_polyline,
MESH_WT_carve_circle,
MESH_WT_carve_polyline,
]
def register():
for cls in classes:
bpy.utils.register_class(cls)
for tool in main_tools:
bpy.utils.register_tool(tool, separator=False, after="builtin.primitive_cube_add", group=True)
for tool in secondary_tools:
bpy.utils.register_tool(tool, separator=False, after="object.carve_box", group=False)
def unregister():
for cls in classes:
bpy.utils.unregister_class(cls)
for tool in main_tools:
bpy.utils.unregister_tool(tool)
for tool in secondary_tools:
bpy.utils.unregister_tool(tool)
@@ -0,0 +1,272 @@
import bpy
import mathutils
import os
from .. import __file__ as base_file
from .common.base import (
CarverModifierKeys,
CarverBase,
)
from .common.properties import (
CarverOperatorProperties,
CarverModifierProperties,
CarverCutterProperties,
CarverArrayProperties,
CarverBevelProperties,
)
from .common.ui import (
carver_ui_common,
)
from ..functions.draw import (
carver_shape_box,
)
from ..functions.select import (
cursor_snap,
selection_fallback,
)
description = "Cut primitive shapes into mesh objects by box drawing"
#### ------------------------------ TOOLS ------------------------------ ####
class OBJECT_WT_carve_box(bpy.types.WorkSpaceTool):
bl_idname = "object.carve_box"
bl_label = "Box Carve"
bl_description = description
bl_space_type = 'VIEW_3D'
bl_context_mode = 'OBJECT'
bl_icon = os.path.join(os.path.dirname(base_file), "icons", "ops.object.carver_box")
bl_keymap = (
("object.carve_box", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG'}, {"properties": [("shape", 'BOX')]}),
("object.carve_box", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG', "shift": True}, {"properties": [("shape", 'BOX')]}),
("object.carve_box", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG', "alt": True}, {"properties": [("shape", 'BOX')]}),
("object.carve_box", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG', "shift": True, "alt": True}, {"properties": [("shape", 'BOX')]}),
("object.carve_box", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG', "ctrl": True}, {"properties": [("shape", 'BOX')]}),
("object.carve_box", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG', "ctrl": True, "shift": True}, {"properties": [("shape", 'BOX')]}),
("object.carve_box", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG', "ctrl": True, "alt": True}, {"properties": [("shape", 'BOX')]}),
("object.carve_box", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG', "ctrl": True, "shift": True, "alt": True}, {"properties": [("shape", 'BOX')]}),
)
def draw_settings(context, layout, tool):
props = tool.operator_properties("object.carve_box")
carver_ui_common(context, layout, props)
class MESH_WT_carve_box(OBJECT_WT_carve_box):
bl_context_mode = 'EDIT_MESH'
#### ------------------------------ OPERATORS ------------------------------ ####
class OBJECT_OT_carve_box(CarverBase, CarverModifierKeys, bpy.types.Operator,
CarverOperatorProperties, CarverModifierProperties, CarverCutterProperties,
CarverArrayProperties, CarverBevelProperties):
bl_idname = "object.carve_box"
bl_label = "Box Carve"
bl_description = description
bl_options = {'REGISTER', 'UNDO', 'DEPENDS_ON_CURSOR'}
bl_cursor_pending = 'PICK_AREA'
shape: bpy.props.EnumProperty(
name = "Shape",
items = (('BOX', "Box", ""),
('CIRCLE', "Circle", ""),
('POLYLINE', "Polyline", "")),
default = 'BOX',
)
# SHAPE-properties
aspect: bpy.props.EnumProperty(
name = "Aspect",
items = (('FREE', "Free", "Use an unconstrained aspect"),
('FIXED', "Fixed", "Use a fixed 1:1 aspect")),
default = 'FREE',
)
origin: bpy.props.EnumProperty(
name = "Origin",
description = "The initial position for placement",
items = (('EDGE', "Edge", ""),
('CENTER', "Center", "")),
default = 'EDGE',
)
rotation: bpy.props.FloatProperty(
name = "Rotation",
subtype = "ANGLE",
soft_min = -360, soft_max = 360,
default = 0,
)
subdivision: bpy.props.IntProperty(
name = "Circle Subdivisions",
description = "Number of vertices that will make up the circular shape that will be extruded into a cylinder",
min = 3, soft_max = 128,
default = 16,
)
@classmethod
def poll(cls, context):
return context.mode in ('OBJECT', 'EDIT_MESH') and context.area.type == 'VIEW_3D'
def invoke(self, context, event):
self.selected_objects = context.selected_objects
self.mouse_path = [(event.mouse_region_x, event.mouse_region_y),
(event.mouse_region_x, event.mouse_region_y)]
# initialize_empty_values
self.verts = []
self.duplicates = []
self.cutter = None
self.view_depth = mathutils.Vector()
self.cached_mouse_position = () # needed_for_custom_modifier_keys
# cached_variables
"""Important for storing context as it was when operator was invoked (untouched by the modal)"""
self.initial_origin = self.origin
self.initial_aspect = self.aspect
# modifier_keys
self.snap = False
self.move = False
self.rotate = False
self.gap = False
self.bevel = False
# overlay_position (needed_for_moving_the_shape)
self.position_offset_x = 0
self.position_offset_y = 0
self.initial_position = False
# Add Draw Handler
self._handle = bpy.types.SpaceView3D.draw_handler_add(carver_shape_box, (self, context, self.shape), 'WINDOW', 'POST_PIXEL')
context.window.cursor_set("MUTE")
context.window_manager.modal_handler_add(self)
return {'RUNNING_MODAL'}
def modal(self, context, event):
# Status Bar Text
snap_text = ", [MOUSEWHEEL]: Change Snapping Increment" if self.snap else ""
shape_text = "[SHIFT]: Aspect, [ALT]: Origin, [R]: Rotate, [ARROWS]: Array"
array_text = ", [A]: Gap" if (self.rows > 1 or self.columns > 1) else ""
bevel_text = ", [B]: Bevel" if self.shape == 'BOX' else ""
context.workspace.status_text_set("[CTRL]: Snap Invert, [SPACEBAR]: Move, " + shape_text + bevel_text + array_text + snap_text)
# find_the_limit_of_the_3d_viewport_region
self.redraw_region(context)
# Modifier Keys
self.modifier_snap(context, event)
self.modifier_aspect(context, event)
self.modifier_origin(context, event)
self.modifier_rotate(context, event)
self.modifier_bevel(context, event)
self.modifier_array(context, event)
self.modifier_move(context, event)
if event.type in {'NUMPAD_1', 'NUMPAD_2', 'NUMPAD_3', 'NUMPAD_4',
'NUMPAD_5', 'NUMPAD_6', 'NUMPAD_7', 'NUMPAD_8', 'NUMPAD_9',
'MIDDLEMOUSE', 'N'}:
return {'PASS_THROUGH'}
if self.bevel == False and event.type in {'WHEELUPMOUSE', 'WHEELDOWNMOUSE'}:
return {'PASS_THROUGH'}
# Mouse Move
if event.type == 'MOUSEMOVE':
# move
if self.move:
self.position_offset_x += (event.mouse_region_x - self.last_mouse_region_x)
self.position_offset_y += (event.mouse_region_y - self.last_mouse_region_y)
self.last_mouse_region_x = event.mouse_region_x
self.last_mouse_region_y = event.mouse_region_y
# rotate
elif self.rotate:
self.rotation = event.mouse_region_x * 0.01
# array
elif self.gap:
self.rows_gap = event.mouse_region_x * 0.1
self.columns_gap = event.mouse_region_y * 0.1
# bevel
elif self.bevel:
self.bevel_radius = event.mouse_region_x * 0.002
# Draw Shape
else:
if len(self.mouse_path) > 0:
# aspect
if self.aspect == 'FIXED':
side = max(abs(event.mouse_region_x - self.mouse_path[0][0]),
abs(event.mouse_region_y - self.mouse_path[0][1]))
self.mouse_path[len(self.mouse_path) - 1] = \
(self.mouse_path[0][0] + (side if event.mouse_region_x >= self.mouse_path[0][0] else -side),
self.mouse_path[0][1] + (side if event.mouse_region_y >= self.mouse_path[0][1] else -side))
elif self.aspect == 'FREE':
self.mouse_path[len(self.mouse_path) - 1] = (event.mouse_region_x, event.mouse_region_y)
# snap (find_the_closest_position_on_the_overlay_grid_and_snap_the_shape_to_it)
if self.snap:
cursor_snap(self, context, event, self.mouse_path)
# Confirm
elif (event.type == 'LEFTMOUSE' and event.value == 'RELEASE') or (event.type == 'RET' and event.value == 'PRESS'):
# selection_fallback
if len(self.selected_objects) == 0:
self.selected_objects = selection_fallback(self, context, context.view_layer.objects, shape='BOX')
for obj in self.selected_objects:
obj.select_set(True)
if len(self.selected_objects) == 0:
self.cancel(context)
return {'FINISHED'}
else:
selection = self.validate_selection(context, shape='BOX')
if not selection:
self.cancel(context)
return {'FINISHED'}
# protection_against_returning_no_rectangle_by_clicking
delta_x = abs(event.mouse_region_x - self.mouse_path[0][0])
delta_y = abs(event.mouse_region_y - self.mouse_path[0][1])
min_distance = 5
if delta_x > min_distance or delta_y > min_distance:
self.confirm(context)
return {'FINISHED'}
# Cancel
elif event.type in {'RIGHTMOUSE', 'ESC'}:
self.cancel(context)
return {'FINISHED'}
return {'RUNNING_MODAL'}
#### ------------------------------ REGISTRATION ------------------------------ ####
classes = [
OBJECT_OT_carve_box,
]
def register():
for cls in classes:
bpy.utils.register_class(cls)
def unregister():
for cls in reversed(classes):
bpy.utils.unregister_class(cls)
@@ -0,0 +1,39 @@
import bpy
import os
from .. import __file__ as base_file
from .common.ui import (
carver_ui_common,
)
description = "Cut primitive shapes into mesh objects with brush"
#### ------------------------------ TOOLS ------------------------------ ####
class OBJECT_WT_carve_circle(bpy.types.WorkSpaceTool):
bl_idname = "object.carve_circle"
bl_label = "Circle Carve"
bl_description = description
bl_space_type = 'VIEW_3D'
bl_context_mode = 'OBJECT'
bl_icon = os.path.join(os.path.dirname(base_file), "icons", "ops.object.carver_circle")
bl_keymap = (
("object.carve_box", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG'}, {"properties": [("shape", 'CIRCLE')]}),
("object.carve_box", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG', "shift": True}, {"properties": [("shape", 'CIRCLE')]}),
("object.carve_box", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG', "alt": True}, {"properties": [("shape", 'CIRCLE')]}),
("object.carve_box", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG', "shift": True, "alt": True}, {"properties": [("shape", 'CIRCLE')]}),
("object.carve_box", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG', "ctrl": True}, {"properties": [("shape", 'CIRCLE')]}),
("object.carve_box", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG', "ctrl": True, "shift": True}, {"properties": [("shape", 'CIRCLE')]}),
("object.carve_box", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG', "ctrl": True, "alt": True}, {"properties": [("shape", 'CIRCLE')]}),
("object.carve_box", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG', "ctrl": True, "shift": True, "alt": True}, {"properties": [("shape", 'CIRCLE')]}),
)
def draw_settings(context, layout, tool):
props = tool.operator_properties("object.carve_box")
carver_ui_common(context, layout, props)
class MESH_WT_carve_circle(OBJECT_WT_carve_circle):
bl_context_mode = 'EDIT_MESH'
@@ -0,0 +1,241 @@
import bpy
import mathutils
import math
import os
from .. import __file__ as base_file
from .common.base import (
CarverModifierKeys,
CarverBase,
)
from .common.properties import (
CarverOperatorProperties,
CarverModifierProperties,
CarverCutterProperties,
CarverArrayProperties,
)
from .common.ui import (
carver_ui_common,
)
from ..functions.draw import (
carver_shape_polyline,
)
from ..functions.select import (
cursor_snap,
selection_fallback,
)
description = "Cut custom polygonal shapes into mesh objects"
#### ------------------------------ TOOLS ------------------------------ ####
class OBJECT_WT_carve_polyline(bpy.types.WorkSpaceTool):
bl_idname = "object.carve_polyline"
bl_label = "Polyline Carve"
bl_description = description
bl_space_type = 'VIEW_3D'
bl_context_mode = 'OBJECT'
bl_icon = os.path.join(os.path.dirname(base_file), "icons", "ops.object.carver_polyline")
bl_keymap = (
("object.carve_polyline", {"type": 'LEFTMOUSE', "value": 'CLICK'}, None),
("object.carve_polyline", {"type": 'LEFTMOUSE', "value": 'CLICK', "ctrl": True}, None),
# select
("view3d.select_box", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG'}, None),
("view3d.select_box", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG', "shift": True}, {"properties": [("mode", 'ADD')]}),
("view3d.select_box", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG', "ctrl": True}, {"properties": [("mode", 'SUB')]}),
)
def draw_settings(context, layout, tool):
props = tool.operator_properties("object.carve_polyline")
carver_ui_common(context, layout, props)
class MESH_WT_carve_polyline(OBJECT_WT_carve_polyline):
bl_context_mode = 'EDIT_MESH'
#### ------------------------------ OPERATORS ------------------------------ ####
class OBJECT_OT_carve_polyline(CarverBase, CarverModifierKeys, bpy.types.Operator,
CarverOperatorProperties, CarverModifierProperties, CarverCutterProperties, CarverArrayProperties):
bl_idname = "object.carve_polyline"
bl_label = "Polyline Carve"
bl_description = description
bl_options = {'REGISTER', 'UNDO', 'DEPENDS_ON_CURSOR'}
bl_cursor_pending = 'PICK_AREA'
# SHAPE-properties
closed: bpy.props.BoolProperty(
name = "Closed Polygon",
description = "When enabled, mouse position at the moment of execution will be registered as last point of the polygon",
default = True,
)
@classmethod
def poll(cls, context):
return context.mode in ('OBJECT', 'EDIT_MESH') and context.area.type == 'VIEW_3D'
def invoke(self, context, event):
self.selected_objects = context.selected_objects
self.mouse_path = [(event.mouse_region_x, event.mouse_region_y),
(event.mouse_region_x, event.mouse_region_y)]
# initialize_empty_values
self.verts = []
self.duplicates = []
self.cutter = None
self.view_depth = mathutils.Vector()
self.cached_mouse_position = () # needed_for_custom_modifier_keys
self.distance_from_first = 0
# cached_variables
"""Important for storing context as it was when operator was invoked (untouched by the modal)"""
self.initial_selection = context.selected_objects
# modifier_keys
self.snap = False
self.move = False
self.gap = False
# overlay_position (needed_for_moving_the_shape)
self.position_offset_x = 0
self.position_offset_y = 0
self.initial_position = False
# Add Draw Handler
self._handle = bpy.types.SpaceView3D.draw_handler_add(carver_shape_polyline, (self, context), 'WINDOW', 'POST_PIXEL')
context.window.cursor_set("MUTE")
context.window_manager.modal_handler_add(self)
return {'RUNNING_MODAL'}
def modal(self, context, event):
# Tool Settings Text
snap_text = ", [MOUSEWHEEL]: Change Snapping Increment" if self.snap else ""
shape_text = "[BACKSPACE]: Remove Last Point, [ENTER]: Confirm"
array_text = ", [A]: Gap" if (self.rows > 1 or self.columns > 1) else ""
context.workspace.status_text_set("[CTRL]: Snap Invert, [SPACEBAR]: Move, " + shape_text + array_text + snap_text)
# find_the_limit_of_the_3d_viewport_region
self.redraw_region(context)
# Modifier Keys
self.modifier_snap(context, event)
self.modifier_array(context, event)
self.modifier_move(context, event)
if event.type in {'NUMPAD_1', 'NUMPAD_2', 'NUMPAD_3', 'NUMPAD_4',
'NUMPAD_5', 'NUMPAD_6', 'NUMPAD_7', 'NUMPAD_8', 'NUMPAD_9',
'MIDDLEMOUSE', 'WHEELUPMOUSE', 'WHEELDOWNMOUSE', 'N'}:
return {'PASS_THROUGH'}
# Mouse Move
if event.type == 'MOUSEMOVE':
# move
if self.move:
self.position_offset_x += (event.mouse_region_x - self.last_mouse_region_x)
self.position_offset_y += (event.mouse_region_y - self.last_mouse_region_y)
self.last_mouse_region_x = event.mouse_region_x
self.last_mouse_region_y = event.mouse_region_y
# array
elif self.gap:
self.rows_gap = event.mouse_region_x * 0.1
self.columns_gap = event.mouse_region_y * 0.1
# Draw Shape
else:
if len(self.mouse_path) > 0:
self.mouse_path[len(self.mouse_path) - 1] = (event.mouse_region_x, event.mouse_region_y)
# snap (find_the_closest_position_on_the_overlay_grid_and_snap_the_shape_to_it)
if self.snap:
cursor_snap(self, context, event, self.mouse_path)
# get_distance_from_first_point
distance = math.sqrt((self.mouse_path[-1][0] - self.mouse_path[0][0]) ** 2 +
(self.mouse_path[-1][1] - self.mouse_path[0][1]) ** 2)
min_radius = 0
max_radius = 30
self.distance_from_first = max(max_radius - distance, min_radius)
# Add Points & Confirm
elif (event.type == 'LEFTMOUSE' and event.value == 'RELEASE') or (event.type == 'RET' and event.value == 'PRESS'):
# selection_fallback (expand_selection_on_every_polyline_click)
if len(self.initial_selection) == 0:
self.selected_objects = selection_fallback(self, context, context.view_layer.objects, shape='POLYLINE')
for obj in self.selected_objects:
obj.select_set(True)
# add_new_points
if not (event.type == 'RET' and event.value == 'PRESS') and (self.distance_from_first < 15):
self.mouse_path.append((event.mouse_region_x, event.mouse_region_y))
if self.closed == False:
"""NOTE: Additional vert is needed for open loop."""
self.mouse_path.append((event.mouse_region_x, event.mouse_region_y))
# confirm_cut
else:
if self.closed == False:
self.verts.pop() # dont_add_current_mouse_position_as_vert
if self.distance_from_first > 15:
self.verts[-1] = self.verts[0]
if len(self.verts) / 2 <= 1:
self.report({'INFO'}, "At least two points are required to make polygonal shape")
self.cancel(context)
return {'FINISHED'}
if self.closed and self.mouse_path[-1] == self.mouse_path[-2]:
context.window.cursor_warp(event.mouse_region_x - 1, event.mouse_region_y)
selection = self.validate_selection(context, shape='POLYLINE')
if not selection:
self.cancel(context)
return {'FINISHED'}
self.confirm(context)
return {'FINISHED'}
# Remove Last Point
if event.type == 'BACK_SPACE' and event.value == 'PRESS':
if len(self.mouse_path) > 2:
context.window.cursor_warp(int(self.mouse_path[-2][0]), int(self.mouse_path[-2][1]))
self.mouse_path = self.mouse_path[:-1]
# Cancel
elif event.type in {'RIGHTMOUSE', 'ESC'}:
self.cancel(context)
return {'FINISHED'}
return {'RUNNING_MODAL'}
#### ------------------------------ REGISTRATION ------------------------------ ####
classes = [
OBJECT_OT_carve_polyline,
]
def register():
for cls in classes:
bpy.utils.register_class(cls)
def unregister():
for cls in reversed(classes):
bpy.utils.unregister_class(cls)
@@ -0,0 +1,239 @@
import bpy
import math
from ...functions.mesh import (
create_cutter_shape,
extrude,
shade_smooth_by_angle,
)
from ...functions.modifier import (
add_boolean_modifier,
apply_modifiers,
)
from ...functions.object import (
set_cutter_properties,
delete_cutter,
set_object_origin,
)
from ...functions.select import (
selection_fallback,
)
#### ------------------------------ FUNCTIONS ------------------------------ ####
def custom_modifier_event(self, context, event, modifier):
"""Creates custom modifier event when key is held and hides cursor until it's released"""
if event.value == 'PRESS':
if not self.move:
self.cached_mouse_position = (self.mouse_path[1][0], self.mouse_path[1][1])
context.window.cursor_set("NONE")
setattr(self, modifier, True)
elif event.value == 'RELEASE':
if not self.move:
context.window.cursor_set("MUTE")
context.window.cursor_warp(int(self.cached_mouse_position[0]), int(self.cached_mouse_position[1]))
setattr(self, modifier, False)
#### ------------------------------ /base/ ------------------------------ ####
class CarverModifierKeys():
"""NOTE: Order of the modifier key events is important, because key value might change after function checks for it"""
"""Functions that check last are most important because they can overwrite all modifier states"""
def modifier_snap(self, context, event):
"""Modifier keys for snapping"""
self.snap = context.scene.tool_settings.use_snap
if (self.move == False) and (not hasattr(self, "rotate") or (hasattr(self, "rotate") and not self.rotate)):
# change_the_snap_increment_value_using_the_wheel_mouse
for i, area in enumerate(context.screen.areas):
if area.type == 'VIEW_3D':
space = context.screen.areas[i].spaces.active
if event.type == 'WHEELUPMOUSE':
space.overlay.grid_subdivisions -= 1
elif event.type == 'WHEELDOWNMOUSE':
space.overlay.grid_subdivisions += 1
# invert_snapping
if event.ctrl:
self.snap = not self.snap
def modifier_aspect(self, context, event):
"""Modifier keys for changing aspect of the shape"""
if event.shift:
if self.initial_aspect == 'FREE':
self.aspect = 'FIXED'
elif self.initial_aspect == 'FIXED':
self.aspect = 'FREE'
else:
self.aspect = self.initial_aspect
def modifier_origin(self, context, event):
"""Modifier keys for changing the origin of the shape"""
if event.alt:
if self.initial_origin == 'EDGE':
self.origin = 'CENTER'
elif self.initial_origin == 'CENTER':
self.origin = 'EDGE'
else:
self.origin = self.initial_origin
def modifier_rotate(self, context, event):
"""Modifier keys for rotating the shape"""
if event.type == 'R':
custom_modifier_event(self, context, event, "rotate")
def modifier_bevel(self, context, event):
"""Modifier keys for beveling the shape"""
if self.shape == 'BOX':
if event.type == 'B':
custom_modifier_event(self, context, event, "bevel")
if self.bevel:
self.use_bevel = True
if event.type == 'WHEELUPMOUSE':
self.bevel_segments += 1
elif event.type == 'WHEELDOWNMOUSE':
self.bevel_segments -= 1
def modifier_array(self, context, event):
"""Modifier keys for creating the array of the shape"""
if event.type == 'LEFT_ARROW' and event.value == 'PRESS':
self.rows -= 1
if event.type == 'RIGHT_ARROW' and event.value == 'PRESS':
self.rows += 1
if event.type == 'DOWN_ARROW' and event.value == 'PRESS':
self.columns -= 1
if event.type == 'UP_ARROW' and event.value == 'PRESS':
self.columns += 1
if (self.rows > 1 or self.columns > 1) and (event.type == 'A'):
custom_modifier_event(self, context, event, "gap")
def modifier_move(self, context, event):
"""Modifier keys for moving the shape"""
if event.type == 'SPACE':
if event.value == 'PRESS':
self.move = True
elif event.value == 'RELEASE':
self.move = False
if self.move:
# reset_initial_position_before_moving_the_shape
if self.initial_position is False:
self.position_offset_x = 0
self.position_offset_y = 0
self.last_mouse_region_x = event.mouse_region_x
self.last_mouse_region_y = event.mouse_region_y
self.initial_position = True
else:
# update_the_shape_coordinates
if self.initial_position:
for i in range(0, len(self.mouse_path)):
l = list(self.mouse_path[i])
l[0] += self.position_offset_x
l[1] += self.position_offset_y
self.mouse_path[i] = tuple(l)
self.position_offset_x = self.position_offset_y = 0
self.initial_position = False
class CarverBase():
def redraw_region(self, context):
"""Redraw region to find the limits of the 3D viewport"""
region_types = {'WINDOW', 'UI'}
for area in context.window.screen.areas:
if area.type == 'VIEW_3D':
for region in area.regions:
if not region_types or region.type in region_types:
region.tag_redraw()
def validate_selection(self, context, shape='BOX'):
"""Filters out objects that are not inside the selection shape bounding box"""
"""Returns selection state (so operator can be cancelled if there are no objects inside the selection bounding box)"""
self.selected_objects = selection_fallback(self, context, self.selected_objects, shape=shape, include_cutters=True)
# silently_fail_if_no_objects_inside_selection_bounding_box
if len(self.selected_objects) == 0:
selection = False
else:
selection = True
return selection
def confirm(self, context):
create_cutter_shape(self, context)
extrude(self, self.cutter.data)
set_object_origin(self.cutter)
if self.auto_smooth:
shade_smooth_by_angle(self.cutter, angle=math.degrees(self.sharp_angle))
self.Cut(context)
self.cancel(context)
def cancel(self, context):
bpy.types.SpaceView3D.draw_handler_remove(self._handle, 'WINDOW')
context.workspace.status_text_set(None)
context.window.cursor_set('DEFAULT' if context.mode == 'OBJECT' else 'CROSSHAIR')
def Cut(self, context):
# ensure_active_object
if not context.active_object:
context.view_layer.objects.active = self.selected_objects[0]
# Add Modifier
for obj in self.selected_objects:
if self.mode == 'DESTRUCTIVE':
# Select all faces of the cutter so that newly created faces in canvas
# are also selected after applying the modifier.
for face in self.cutter.data.polygons:
face.select = True
mod = add_boolean_modifier(self, context, obj, self.cutter, "DIFFERENCE", self.solver, pin=self.pin, redo=False)
apply_modifiers(context, obj, [mod])
elif self.mode == 'MODIFIER':
add_boolean_modifier(self, context, obj, self.cutter, "DIFFERENCE", self.solver, pin=self.pin, redo=False)
obj.booleans.canvas = True
if self.mode == 'DESTRUCTIVE':
# Remove Cutter
delete_cutter(self.cutter)
elif self.mode == 'MODIFIER':
# Set Cutter Properties
canvas = None
if context.active_object and context.active_object in self.selected_objects:
canvas = context.active_object
else:
canvas = self.selected_objects[0]
set_cutter_properties(context, canvas, self.cutter, "Difference", parent=self.parent, hide=self.hide)
@@ -0,0 +1,133 @@
import bpy
import math
#### ------------------------------ PROPERTIES ------------------------------ ####
class CarverOperatorProperties():
# OPERATOR-properties
mode: bpy.props.EnumProperty(
name = "Mode",
items = (('DESTRUCTIVE', "Destructive", "Boolean cutters are immediatelly applied and removed after the cut", 'MESH_DATA', 0),
('MODIFIER', "Modifier", "Cuts are stored as boolean modifiers and cutters are placed inside the collection", 'MODIFIER_DATA', 1)),
default = 'DESTRUCTIVE',
)
depth: bpy.props.EnumProperty(
name = "Depth",
items = (('VIEW', "View", "Depth is automatically calculated from view orientation", 'VIEW_CAMERA_UNSELECTED', 0),
('CURSOR', "Cursor", "Depth is derived from 3D cursors location", 'PIVOT_CURSOR', 1)),
default = 'VIEW',
)
class CarverModifierProperties():
# MODIFIER-properties
solver: bpy.props.EnumProperty(
name = "Solver",
items = [('FLOAT', "Float", ""),
('EXACT', "Exact", ""),
('MANIFOLD', "Manifold", "")],
default = 'FLOAT',
)
pin: bpy.props.BoolProperty(
name = "Pin Boolean Modifier",
description = ("Boolean modifier will be placed first in modifier stack, above other modifier (if there are any).\n"
"NOTE: Order of modifiers can drastically affect the result (especially in destructive mode)"),
default = True,
)
class CarverCutterProperties():
# CUTTER-properties
hide: bpy.props.BoolProperty(
name = "Hide Cutter",
description = ("Hide cutter objects in the viewport after they're created."),
default = True,
)
parent: bpy.props.BoolProperty(
name = "Parent to Canvas",
description = ("Cutters will be parented to active object being cut, even if cutting multiple objects.\n"
"If there is no active object in selection cutters parent might be chosen seemingly randomly"),
default = True,
)
auto_smooth: bpy.props.BoolProperty(
name = "Shade Auto Smooth",
description = ("Cutter object will be shaded smooth with sharp edges (above specified degrees) marked as sharp\n"
"NOTE: This is a one time operator. 'Smooth by Angle' modifier will not be added on cutter"),
default = True,
)
sharp_angle: bpy.props.FloatProperty(
name = "Angle",
description = "Maximum face angle for sharp edges",
subtype = "ANGLE",
min = 0, max = math.pi,
default = 0.523599,
)
class CarverArrayProperties():
# ARRAY-properties
rows: bpy.props.IntProperty(
name = "Rows",
description = "Number of times shape is duplicated horizontally",
min = 1, soft_max = 16,
default = 1,
)
rows_gap: bpy.props.FloatProperty(
name = "Gap between rows (relative unit)",
min = 0, soft_max = 250,
default = 50,
)
rows_direction: bpy.props.EnumProperty(
name = "Direction of Rows",
items = (('LEFT', "Left", ""),
('RIGHT', "Right", "")),
default = 'RIGHT',
)
columns: bpy.props.IntProperty(
name = "Columns",
description = "Number of times shape is duplicated vertically",
min = 1, soft_max = 16,
default = 1,
)
columns_direction: bpy.props.EnumProperty(
name = "Direction of Rows",
items = (('UP', "Up", ""),
('DOWN', "Down", "")),
default = 'DOWN',
)
columns_gap: bpy.props.FloatProperty(
name = "Gap between columns (relative unit)",
min = 0, soft_max = 250,
default = 50,
)
class CarverBevelProperties():
# BEVEL-properties
use_bevel: bpy.props.BoolProperty(
name = "Bevel Cutter",
description = "Bevel each side edge of the cutter",
default = False,
)
bevel_profile: bpy.props.EnumProperty(
name = "Bevel Profile",
items = (('CONVEX', "Convex", "Outside bevel (rounded corners)"),
('CONCAVE', "Concave", "Inside bevel")),
default = 'CONVEX',
)
bevel_segments: bpy.props.IntProperty(
name = "Bevel Segments",
description = "Segments for curved edge",
min = 2, soft_max = 32,
default = 8,
)
bevel_radius: bpy.props.FloatProperty(
name = "Bevel Radius",
description = "Amout of the bevel (in screen-space units)",
min = 0.01, soft_max = 5,
default = 1,
)
@@ -0,0 +1,149 @@
import bpy
from ... import __package__ as base_package
#### ------------------------------ /toolbar/ ------------------------------ ####
def carver_ui_common(context, layout, props):
"""Common tool properties for all Carver tools"""
layout.prop(props, "mode", text="")
layout.prop(props, "depth", text="")
layout.prop(props, "solver", expand=True)
# Popovers
layout.popover("TOPBAR_PT_carver_shape", text="Shape")
layout.popover("TOPBAR_PT_carver_array", text="Array")
layout.popover("TOPBAR_PT_carver_cutter", text="Cutter")
#### ------------------------------ /popovers/ ------------------------------ ####
class TOPBAR_PT_carver_shape(bpy.types.Panel):
bl_label = "Carver Shape"
bl_idname = "TOPBAR_PT_carver_shape"
bl_region_type = 'HEADER'
bl_space_type = 'TOPBAR'
bl_category = 'Tool'
def draw(self, context):
layout = self.layout
layout.use_property_split = True
layout.use_property_decorate = False
prefs = context.preferences.addons[base_package].preferences
tool = context.workspace.tools.from_space_view3d_mode('OBJECT' if context.mode == 'OBJECT' else 'EDIT_MESH')
# Box
if tool.idname == "object.carve_box" or tool.idname == "object.carve_circle":
props = tool.operator_properties("object.carve_box")
if tool.idname == "object.carve_circle":
layout.prop(props, "subdivision", text="Vertices")
layout.prop(props, "rotation")
layout.prop(props, "aspect", expand=True)
layout.prop(props, "origin", expand=True)
# bevel
if tool.idname == 'object.carve_box':
layout.separator()
layout.prop(props, "use_bevel", text="Bevel")
col = layout.column(align=True)
row = col.row(align=True)
if prefs.experimental:
row.prop(props, "bevel_profile", text="Profile", expand=True)
col.prop(props, "bevel_segments", text="Segments")
col.prop(props, "bevel_radius", text="Radius")
if props.use_bevel == False:
col.enabled = False
# Polyline
elif tool.idname == "object.carve_polyline":
props = tool.operator_properties("object.carve_polyline")
layout.prop(props, "closed")
class TOPBAR_PT_carver_array(bpy.types.Panel):
bl_label = "Carver Array"
bl_idname = "TOPBAR_PT_carver_array"
bl_region_type = 'HEADER'
bl_space_type = 'TOPBAR'
bl_category = 'Tool'
def draw(self, context):
layout = self.layout
layout.use_property_split = True
layout.use_property_decorate = False
tool = context.workspace.tools.from_space_view3d_mode('OBJECT' if context.mode == 'OBJECT' else 'EDIT_MESH')
if tool.idname == "object.carve_box" or tool.idname == "object.carve_circle":
props = tool.operator_properties("object.carve_box")
elif tool.idname == "object.carve_polyline":
props = tool.operator_properties("object.carve_polyline")
# Rows
col = layout.column(align=True)
col.prop(props, "rows")
row = col.row(align=True)
row.prop(props, "rows_direction", text="Direction", expand=True)
col.prop(props, "rows_gap", text="Gap")
# Columns
layout.separator()
col = layout.column(align=True)
col.prop(props, "columns")
row = col.row(align=True)
row.prop(props, "columns_direction", text="Direction", expand=True)
col.prop(props, "columns_gap", text="Gap")
class TOPBAR_PT_carver_cutter(bpy.types.Panel):
bl_label = "Carver Cutter"
bl_idname = "TOPBAR_PT_carver_cutter"
bl_region_type = 'HEADER'
bl_space_type = 'TOPBAR'
bl_category = 'Tool'
def draw(self, context):
layout = self.layout
layout.use_property_split = True
layout.use_property_decorate = False
tool = context.workspace.tools.from_space_view3d_mode('OBJECT' if context.mode == 'OBJECT' else 'EDIT_MESH')
if tool.idname == "object.carve_box" or tool.idname == "object.carve_circle":
props = tool.operator_properties("object.carve_box")
elif tool.idname == "object.carve_polyline":
props = tool.operator_properties("object.carve_polyline")
# modifier_&_cutter
col = layout.column()
col.prop(props, "pin", text="Pin Modifier")
if props.mode == 'MODIFIER':
col.prop(props, "parent")
col.prop(props, "hide")
# auto_smooth
layout.separator()
col = layout.column(align=True)
col.prop(props, "auto_smooth", text="Auto Smooth")
col.prop(props, "sharp_angle")
#### ------------------------------ REGISTRATION ------------------------------ ####
classes = [
TOPBAR_PT_carver_shape,
TOPBAR_PT_carver_array,
TOPBAR_PT_carver_cutter,
]
def register():
for cls in classes:
bpy.utils.register_class(cls)
def unregister():
for cls in reversed(classes):
bpy.utils.unregister_class(cls)
+6 -6
View File
@@ -7,9 +7,9 @@ from .functions.list import list_canvas_cutters
def carve_menu(self, context):
layout = self.layout
layout.operator("object.carve", text="Box Carve").shape='BOX'
layout.operator("object.carve", text="Circle Carve").shape='CIRCLE'
layout.operator("object.carve", text="Polyline Carve").shape='POLYLINE'
layout.operator("object.carve_box", text="Box Carve").shape='BOX'
layout.operator("object.carve_box", text="Circle Carve").shape='CIRCLE'
layout.operator("object.carve_polyline", text="Polyline Carve")
def boolean_operators_menu(self, context):
@@ -37,7 +37,7 @@ def boolean_extras_menu(self, context):
col = layout.column(align=True)
if context.active_object:
# canvas_operators
# Canvas operators
active_object = context.active_object
if active_object.booleans.canvas == True and any(mod.name.startswith("boolean_") for mod in active_object.modifiers):
col.separator()
@@ -45,7 +45,7 @@ def boolean_extras_menu(self, context):
col.operator("object.boolean_apply_all", text="Apply All Cutters")
col.operator("object.boolean_remove_all", text="Remove All Cutters")
# cutter_operators
# Cutter operators
if active_object.booleans.cutter:
col.separator()
col.operator("object.boolean_toggle_cutter", text="Toggle Cutter").method='ALL'
@@ -174,7 +174,7 @@ class VIEW3D_MT_carve(bpy.types.Menu):
carve_menu(self, context)
# Object > Menu
# 3D Viewport (Object Mode) -> Object
class VIEW3D_MT_boolean(bpy.types.Menu):
bl_label = "Boolean"
bl_idname = "VIEW3D_MT_boolean"
@@ -1,7 +1,7 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
@@ -631,8 +631,8 @@ to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
PlaySync
Copyright (C) 2020 Blender
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -645,14 +645,14 @@ the "copyright" line and a pointer to where the full notice is found.
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
PlaySync Copyright (C) 2020 Blender
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
@@ -664,11 +664,11 @@ might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
@@ -0,0 +1,32 @@
# SPDX-FileCopyrightText: 2025 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
from . import utils, icons, settings, preferences, ui, draw_tool, ops
import tomllib as toml
modules = [utils, icons, settings, preferences, ui, draw_tool, ops]
def register():
# register modules
for m in modules:
m.register()
# read addon meta-data
with open(f"{utils.get_addon_directory()}/blender_manifest.toml", 'rb') as f:
manifest = toml.load(f)
utils.addon_version = tuple([int(i) for i in manifest['version'].split('.')])
# Add addon asset library
utils.register_asset_lib()
# Copy resource files to config directory
utils.unpack_resources()
def unregister():
# un-register modules
for m in reversed(modules):
m.unregister()
# Remove addon asset library
utils.unregister_asset_lib()
@@ -0,0 +1,10 @@
# This is an Asset Catalog Definition file for Blender.
#
# Empty lines and lines starting with `#` will be ignored.
# The first non-ignored line should be the version indicator.
# Other lines are of the format "UUID:catalog/path/for/assets:simple catalog name"
VERSION 1
39d602da-9c11-471c-a99f-996e474e8e9a:Edge:Edge
4cee84fd-9d34-4ad1-b8f0-a6369e473f0d:Face:Face
@@ -0,0 +1,23 @@
schema_version = "1.0.0"
id = "brushstroke_tools"
version = "1.1.2"
name = "Brushstroke Tools"
tagline = "Brushstroke painting tools by the Blender Studio"
maintainer = "Simon Thommes <simon@blender.org>"
type = "add-on"
website = "https://studio.blender.org/tools/addons/brushstroke_tools"
tags = ["Paint", "Geometry Nodes", "Material", ]
blender_version_min = "4.2.0"
license = [
"SPDX:GPL-3.0-or-later",
]
copyright = [
"2024 Blender Foundation",
]
[permissions]
files = "Read/write brushstroke asset resources from/to disk"
@@ -0,0 +1,208 @@
# SPDX-FileCopyrightText: 2025 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
import bpy
from . import utils
from mathutils import Vector
from bpy.types import WorkSpaceTool
def preserve_draw_settings(context, restore=False):
props_list = ['curve_type',
'depth_mode',
'use_pressure_radius',
'use_project_only_selected',
'radius_taper_start',
'radius_taper_end',
'radius_min',
'radius_max',
'surface_offset',
'use_offset_absolute',
'use_stroke_endpoints',]
if restore:
draw_settings_dict = context.scene['BSBST-TMP-draw_settings_dict']
for k, v in draw_settings_dict.items():
setattr(context.tool_settings.curve_paint_settings, k, v)
del context.scene['BSBST-TMP-draw_settings_dict']
else:
draw_settings_dict = dict()
for item in props_list:
draw_settings_dict[item] = getattr(context.tool_settings.curve_paint_settings, item)
context.scene['BSBST-TMP-draw_settings_dict'] = draw_settings_dict
class BSBST_tool_settings(bpy.types.PropertyGroup):
brush_color: bpy.props.FloatVectorProperty(name='Brush Color',
size=3,
subtype='COLOR',
default=(0.,.5,1.),
soft_min=0,
soft_max=1,
update=None,
)
radius_taper_start: bpy.props.FloatProperty(name='Taper Start', default=0, min=0, max=1, subtype='FACTOR')
radius_taper_end: bpy.props.FloatProperty(name='Taper End', default=0, min=0, max=1, subtype='FACTOR')
radius_min: bpy.props.FloatProperty(name='Radius Min', default=0, min=0, soft_max=10)
radius_max: bpy.props.FloatProperty(name='Radius Max', default=1, min=0, soft_max=10)
surface_offset: bpy.props.FloatProperty(name='Surface Offset', default=0, soft_max=10)
use_project_only_selected: bpy.props.BoolProperty(name='Project Onto Selected',
default=True,
description='Project the strokes only on selected objects if applicable.')
use_pressure_radius: bpy.props.BoolProperty(name='Use Pressure',
default=True,
description='Map tablet pressure to curve radius',)
use_offset_absolute: bpy.props.BoolProperty(name='Absolute Offset',
default=False,
description="Apply a fixed offset. (Don't scale by the radius.)")
class BSBST_OT_draw(bpy.types.Macro):
"""
Custom draw operation for hair curves
"""
bl_idname = "brushstroke_tools.draw"
bl_label = "Custom Draw"
bl_options = {'REGISTER', 'UNDO'}
class BSBST_OT_pre_process_brushstroke(bpy.types.Operator):
"""
Set up custom draw tool for curve drawing
"""
bl_idname = "brushstroke_tools.pre_process_brushstroke"
bl_label = "Custom Draw Pre Process"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
tool_settings = context.scene.BSBST_tool_settings
preserve_draw_settings(context)
# fix some settings
context.tool_settings.curve_paint_settings.curve_type = 'POLY'
context.tool_settings.curve_paint_settings.depth_mode = 'SURFACE'
context.tool_settings.curve_paint_settings.use_stroke_endpoints = False
is_other_object_selected = len(set(context.selected_objects) - {context.object}) > 0
context.tool_settings.curve_paint_settings.use_project_only_selected = is_other_object_selected and tool_settings.use_project_only_selected
# propagate some settings from custom tool
props_list = ['use_pressure_radius',
'radius_taper_start',
'radius_taper_end',
'radius_min',
'radius_max',
'surface_offset',
'use_offset_absolute',]
for prop in props_list:
setattr(context.tool_settings.curve_paint_settings, prop, getattr(tool_settings, prop))
return {'FINISHED'}
class BSBST_OT_post_process_brushstroke(bpy.types.Operator):
"""
"""
bl_idname = "brushstroke_tools.post_process_brushstroke"
bl_label = "Custom Draw Post Process"
bl_options = {'REGISTER', 'UNDO'}
ng_process = None
gp = None
def execute(self, context):
if not self.ng_process:
preserve_draw_settings(context, restore=True)
return {'CANCELLED'}
tool_settings = context.scene.BSBST_tool_settings
self.ng_process.nodes['settings.color'].value = [*tool_settings.brush_color, 1.]
self.ng_process.nodes['view_vector'].vector = context.space_data.region_3d.view_rotation @ Vector((0.0, 0.0, 1.0))
self.ng_process.nodes['new_key'].boolean = context.scene.tool_settings.use_keyframe_insert_auto
self.ng_process.nodes['deform'].boolean = utils.get_deformable(context.object)
if 'BSBST_surface_object' in context.object.keys():
if context.object['BSBST_surface_object']:
self.ng_process.nodes['surface_object'].inputs[0].default_value = context.object['BSBST_surface_object']
bpy.ops.geometry.execute_node_group(name="set_brush_stroke_color", session_uid=self.ng_process.session_uid)
preserve_draw_settings(context, restore=True)
return {'FINISHED'}
def invoke(self, context, event):
utils.ensure_resources()
self.gp = None
self.ng_process = bpy.data.node_groups['.brushstroke_tools.draw_processing']
return self.execute(context)
def register_custom_draw_macro():
op = BSBST_OT_draw.define("brushstroke_tools.pre_process_brushstroke")
op = BSBST_OT_draw.define("curves.draw")
op.properties.wait_for_input = False
op = BSBST_OT_draw.define("brushstroke_tools.post_process_brushstroke")
class BrushstrokesCurves(WorkSpaceTool):
bl_space_type = 'VIEW_3D'
bl_context_mode = 'EDIT_CURVES'
bl_idname = "brushstroke_tools.draw"
bl_label = "Brushstroke Draw"
bl_description = (
"Brushstrokes on the visible surface"
)
bl_icon = "brush.sculpt.paint"
bl_widget = None
bl_keymap = (
("brushstroke_tools.draw", {"type": 'LEFTMOUSE', "value": 'CLICK_DRAG'},
{"properties": []}),
)
def draw_settings(context, layout, tool, *, extra=False):
props = tool.operator_properties("brushstroke_tools.draw")
tool_settings = context.scene.BSBST_tool_settings
region_type = context.region.type
if region_type == 'TOOL_HEADER':
if not extra:
layout.prop(tool_settings , "radius_max")
layout.prop(tool_settings , "surface_offset")
layout.prop(tool_settings, "brush_color")
layout.popover("TOPBAR_PT_tool_settings_extra", text="...")
return
layout.use_property_split = True
layout.use_property_decorate = False
col = layout.column(align=False)
col.template_color_picker(tool_settings, 'brush_color', value_slider=True)
col.prop(tool_settings, 'brush_color', text='')
col = layout.column(align=True)
col.prop(tool_settings, "radius_taper_start", text="Taper Start", slider=True)
col.prop(tool_settings, "radius_taper_end", text="End", slider=True)
col = layout.column(align=True)
col.prop(tool_settings, "radius_min", text="Radius Min")
col.prop(tool_settings, "radius_max", text="Max")
col.prop(tool_settings, "use_pressure_radius", icon='STYLUS_PRESSURE', emboss=True)
layout.separator()
col = layout.column()
col.prop(tool_settings, "use_project_only_selected")
col.prop(tool_settings, "surface_offset")
col.prop(tool_settings, "use_offset_absolute")
classes = [
BSBST_tool_settings,
BSBST_OT_pre_process_brushstroke,
BSBST_OT_post_process_brushstroke,
BSBST_OT_draw,
]
def register():
for c in classes:
bpy.utils.register_class(c)
bpy.types.Scene.BSBST_tool_settings = bpy.props.PointerProperty(type=BSBST_tool_settings)
register_custom_draw_macro()
bpy.utils.register_tool(BrushstrokesCurves, after={"builtin.draw"}, group=True)
def unregister():
for c in reversed(classes):
bpy.utils.unregister_class(c)
bpy.utils.unregister_tool(BrushstrokesCurves)
del bpy.types.Scene.BSBST_tool_settings
@@ -0,0 +1,27 @@
# SPDX-FileCopyrightText: 2025 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
import bpy
import bpy.utils.previews
import os
icon_previews = {}
def register():
# register custom icons
dir = os.path.join(os.path.dirname(__file__), "icons")
pcoll = bpy.utils.previews.new()
for entry in os.scandir(dir):
if entry.name.endswith(".png"):
name = os.path.splitext(entry.name)[0]
pcoll.load(name.upper(), entry.path, "IMAGE")
global icon_previews
icon_previews["main"] = pcoll
def unregister():
# unregister custom icons
global icon_previews
for pcoll in icon_previews.values():
bpy.utils.previews.remove(pcoll)
icon_previews.clear()
Binary file not shown.
@@ -0,0 +1,447 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
height="16000"
viewBox="0 0 16000 16000"
width="16000"
version="1.1"
id="svg3"
sodipodi:docname="random.svg"
inkscape:version="1.3.2 (091e20ef0f, 2023-11-25)"
inkscape:export-filename="random.png"
inkscape:export-xdpi="1"
inkscape:export-ydpi="1"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<defs
id="defs3">
<inkscape:path-effect
effect="fillet_chamfer"
id="path-effect17"
is_visible="true"
lpeversion="1"
nodesatellites_param="F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,96.61328,0,1 @ F,0,0,1,0,87.894951,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,96.130535,0,1 @ F,0,0,1,0,136.84977,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1"
radius="0"
unit="px"
method="auto"
mode="F"
chamfer_steps="1"
flexible="false"
use_knot_distance="true"
apply_no_radius="true"
apply_with_radius="true"
only_selected="false"
hide_knots="false" />
<inkscape:path-effect
effect="fillet_chamfer"
id="path-effect16"
is_visible="true"
lpeversion="1"
nodesatellites_param="F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1"
radius="0"
unit="px"
method="auto"
mode="F"
chamfer_steps="1"
flexible="false"
use_knot_distance="true"
apply_no_radius="true"
apply_with_radius="true"
only_selected="false"
hide_knots="false" />
<inkscape:path-effect
effect="fillet_chamfer"
id="path-effect14"
is_visible="true"
lpeversion="1"
nodesatellites_param="F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,38.11328,0,1"
radius="0"
unit="px"
method="auto"
mode="F"
chamfer_steps="1"
flexible="false"
use_knot_distance="true"
apply_no_radius="true"
apply_with_radius="true"
only_selected="false"
hide_knots="false" />
<inkscape:path-effect
effect="fillet_chamfer"
id="path-effect13"
is_visible="true"
lpeversion="1"
nodesatellites_param="F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,306.22768,0,1"
radius="0"
unit="px"
method="auto"
mode="F"
chamfer_steps="1"
flexible="false"
use_knot_distance="true"
apply_no_radius="true"
apply_with_radius="true"
only_selected="false"
hide_knots="false" />
<inkscape:path-effect
effect="fillet_chamfer"
id="path-effect22"
is_visible="true"
lpeversion="1"
nodesatellites_param="F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,50,0,1 @ F,0,0,1,0,50,0,1 @ F,0,0,1,0,0,0,1"
radius="0"
unit="px"
method="auto"
mode="F"
chamfer_steps="1"
flexible="false"
use_knot_distance="true"
apply_no_radius="true"
apply_with_radius="true"
only_selected="false"
hide_knots="false" />
<inkscape:path-effect
effect="fillet_chamfer"
id="path-effect21"
is_visible="true"
lpeversion="1"
nodesatellites_param="F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,50,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1"
radius="0"
unit="px"
method="auto"
mode="F"
chamfer_steps="1"
flexible="false"
use_knot_distance="true"
apply_no_radius="true"
apply_with_radius="true"
only_selected="false"
hide_knots="false" />
<inkscape:path-effect
effect="fillet_chamfer"
id="path-effect20"
is_visible="true"
lpeversion="1"
nodesatellites_param="F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,43.247149,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,21.653685,0,1 @ F,0,0,1,0,36.44727,0,1"
radius="0"
unit="px"
method="auto"
mode="F"
chamfer_steps="1"
flexible="false"
use_knot_distance="true"
apply_no_radius="true"
apply_with_radius="true"
only_selected="false"
hide_knots="false" />
<inkscape:path-effect
effect="fillet_chamfer"
id="path-effect19"
is_visible="true"
lpeversion="1"
nodesatellites_param="F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,50,0,1 @ F,0,0,1,0,50,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,80.166317,0,1 @ F,0,0,1,0,42.114857,0,1"
radius="0"
unit="px"
method="auto"
mode="F"
chamfer_steps="1"
flexible="false"
use_knot_distance="true"
apply_no_radius="true"
apply_with_radius="true"
only_selected="false"
hide_knots="false" />
<inkscape:path-effect
effect="powerclip"
id="path-effect18"
is_visible="true"
lpeversion="1"
inverse="true"
flatten="false"
hide_clip="false"
message="Use fill-rule evenodd on &lt;b&gt;fill and stroke&lt;/b&gt; dialog if no flatten result after convert clip to paths." />
<inkscape:path-effect
effect="powerclip"
id="path-effect15"
is_visible="true"
lpeversion="1"
inverse="true"
flatten="false"
hide_clip="false"
message="Use fill-rule evenodd on &lt;b&gt;fill and stroke&lt;/b&gt; dialog if no flatten result after convert clip to paths." />
<inkscape:path-effect
effect="fillet_chamfer"
id="path-effect6"
is_visible="true"
lpeversion="1"
nodesatellites_param="F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,159.98102,0,1"
radius="0"
unit="px"
method="auto"
mode="F"
chamfer_steps="1"
flexible="false"
use_knot_distance="true"
apply_no_radius="true"
apply_with_radius="true"
only_selected="false"
hide_knots="false" />
<inkscape:path-effect
effect="fillet_chamfer"
id="path-effect5"
is_visible="true"
lpeversion="1"
nodesatellites_param="F,0,0,1,0,131.34073,0,1 @ F,0,0,1,0,133.0127,0,1 @ F,0,0,1,0,133.01271,0,1"
radius="0"
unit="px"
method="auto"
mode="F"
chamfer_steps="1"
flexible="false"
use_knot_distance="true"
apply_no_radius="true"
apply_with_radius="true"
only_selected="false"
hide_knots="false" />
<inkscape:path-effect
effect="fillet_chamfer"
id="path-effect4"
is_visible="true"
lpeversion="1"
nodesatellites_param="F,0,0,1,0,204.97527,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,218.37273,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,208.56511,0,1 @ F,0,0,1,0,0,0,1"
radius="0"
unit="px"
method="auto"
mode="F"
chamfer_steps="1"
flexible="false"
use_knot_distance="true"
apply_no_radius="true"
apply_with_radius="true"
only_selected="false"
hide_knots="false" />
<inkscape:path-effect
effect="powermask"
id="path-effect12"
is_visible="true"
lpeversion="1"
uri="#mask-powermask-path-effect12"
invert="false"
hide_mask="false"
background="true"
background_color="#ffffffff" />
<inkscape:path-effect
effect="fillet_chamfer"
id="path-effect11"
is_visible="true"
lpeversion="1"
nodesatellites_param="F,0,0,1,0,223.48671,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1"
radius="0"
unit="px"
method="auto"
mode="F"
chamfer_steps="1"
flexible="false"
use_knot_distance="true"
apply_no_radius="true"
apply_with_radius="true"
only_selected="false"
hide_knots="false" />
<inkscape:path-effect
effect="powermask"
id="path-effect10"
is_visible="true"
lpeversion="1"
uri="#mask-powermask-path-effect10"
invert="false"
hide_mask="false"
background="true"
background_color="#ffffffff" />
<inkscape:path-effect
effect="fillet_chamfer"
id="path-effect8"
is_visible="true"
lpeversion="1"
nodesatellites_param="F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,0,0,1 @ F,0,0,1,0,231.93627,0,1 @ F,0,0,1,0,0,0,1"
radius="0"
unit="px"
method="auto"
mode="F"
chamfer_steps="1"
flexible="false"
use_knot_distance="true"
apply_no_radius="true"
apply_with_radius="true"
only_selected="false"
hide_knots="false" />
<inkscape:path-effect
effect="powermask"
id="path-effect7"
is_visible="true"
lpeversion="1"
uri="#mask-powermask-path-effect7"
invert="false"
hide_mask="false"
background="true"
background_color="#ffffffff" />
<inkscape:path-effect
effect="powermask"
id="path-effect2"
is_visible="true"
lpeversion="1"
uri="#mask-powermask-path-effect2"
invert="false"
hide_mask="false"
background="true"
background_color="#ffffffff" />
<inkscape:path-effect
effect="fillet_chamfer"
id="path-effect9"
is_visible="true"
lpeversion="1"
nodesatellites_param="F,0,0,1,0,60.467422,0,1 @ F,0,0,1,0,61.371837,0,1 @ F,0,0,1,0,63.489488,0,1 @ F,0,0,1,0,61.238588,0,1"
radius="0"
unit="px"
method="auto"
mode="F"
chamfer_steps="1"
flexible="false"
use_knot_distance="true"
apply_no_radius="true"
apply_with_radius="true"
only_selected="false"
hide_knots="false" />
<filter
id="mask-powermask-path-effect4_inverse"
inkscape:label="filtermask-powermask-path-effect4"
style="color-interpolation-filters:sRGB"
height="100"
width="100"
x="-50"
y="-50">
<feColorMatrix
id="mask-powermask-path-effect4_primitive1"
values="1"
type="saturate"
result="fbSourceGraphic" />
<feColorMatrix
id="mask-powermask-path-effect4_primitive2"
values="-1 0 0 0 1 0 -1 0 0 1 0 0 -1 0 1 0 0 0 1 0 "
in="fbSourceGraphic" />
</filter>
<filter
id="mask-powermask-path-effect13_inverse"
inkscape:label="filtermask-powermask-path-effect13"
style="color-interpolation-filters:sRGB"
height="100"
width="100"
x="-50"
y="-50">
<feColorMatrix
id="mask-powermask-path-effect13_primitive1"
values="1"
type="saturate"
result="fbSourceGraphic" />
<feColorMatrix
id="mask-powermask-path-effect13_primitive2"
values="-1 0 0 0 1 0 -1 0 0 1 0 0 -1 0 1 0 0 0 1 0 "
in="fbSourceGraphic" />
</filter>
<filter
id="mask-powermask-path-effect17_inverse"
inkscape:label="filtermask-powermask-path-effect17"
style="color-interpolation-filters:sRGB"
height="100"
width="100"
x="-50"
y="-50">
<feColorMatrix
id="mask-powermask-path-effect17_primitive1"
values="1"
type="saturate"
result="fbSourceGraphic" />
<feColorMatrix
id="mask-powermask-path-effect17_primitive2"
values="-1 0 0 0 1 0 -1 0 0 1 0 0 -1 0 1 0 0 0 1 0 "
in="fbSourceGraphic" />
</filter>
</defs>
<sodipodi:namedview
pagecolor="#303030"
showgrid="true"
id="namedview1"
bordercolor="#000000"
borderopacity="0.25"
inkscape:showpageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d1d1d1"
inkscape:zoom="0.0625"
inkscape:cx="7040"
inkscape:cy="7808"
inkscape:window-width="2560"
inkscape:window-height="1358"
inkscape:window-x="0"
inkscape:window-y="32"
inkscape:window-maximized="1"
inkscape:current-layer="layer1">
<inkscape:grid
id="grid5"
units="px"
spacingx="100"
spacingy="100"
color="#4772b3"
opacity="0.2"
visible="true"
originx="0"
originy="0" />
</sodipodi:namedview>
<g
fill="#ffffff"
id="g3"
style="display:none">
<g
id="g5">
<g
id="g4">
<g
enable-background="new"
opacity="0.99"
transform="matrix(100,0,0,100,-48800,-19899.963)"
id="g2">
<path
d="M 495.49219,199.99219 A 0.50005,0.50005 0 0 0 495,200.5 v 6.79297 l -3.85352,3.85351 a 0.50005,0.50005 0 1 0 0.70704,0.70704 L 495.70703,208 H 502.5 a 0.50005,0.50005 0 1 0 0,-1 H 496 v -6.5 a 0.50005,0.50005 0 0 0 -0.50781,-0.50781 z"
opacity="1"
id="path1" />
<path
d="m 499.49023,202.99609 a 0.50005,0.50005 0 0 0 -0.34375,0.15039 l -2,2 a 0.50005,0.50005 0 1 0 0.70704,0.70704 l 2,-2 a 0.50005,0.50005 0 0 0 -0.36329,-0.85743 z M 489.5,207 a 0.50005,0.50005 0 1 0 0,1 h 3.25 a 0.50005,0.50005 0 1 0 0,-1 z m 5.99219,2.74219 A 0.50005,0.50005 0 0 0 495,210.25 v 3.25 a 0.50005,0.50005 0 1 0 1,0 v -3.25 a 0.50005,0.50005 0 0 0 -0.50781,-0.50781 z"
opacity="0.6"
id="path2" />
</g>
</g>
</g>
</g>
<g
inkscape:groupmode="layer"
id="layer1"
inkscape:label="Layer 1">
<path
id="path3"
style="color:#000000;display:none;fill:#ffffff;fill-opacity:0.6;stroke-linejoin:round;-inkscape-stroke:none"
d="m 500,100 c -220.32124,0 -400,179.67876 -400,400 0,131.59237 64.13891,248.62332 162.72034,321.57873 22.18264,16.41632 45.30496,4.85701 54.36188,-21.19654 0.22088,-0.63538 0.44382,-1.26977 0.66883,-1.90317 9.23262,-25.98976 1.38973,-57.26331 -19.07836,-75.75221 C 238.01459,667.93412 200,588.61487 200,500 200,333.72266 333.72266,200 500,200 c 114.00907,0 212.65908,62.88761 263.42614,156.01778 21.12726,38.75714 46.45545,43.58478 68.59301,5.24196 l 3.34702,-5.79711 c 11.62982,-20.14315 12.65529,-53.4221 -0.0293,-72.90553 C 763.8993,172.82969 640.22189,100 500,100 Z"
inkscape:original-d="m 500,100 c -220.32124,0 -400,179.67876 -400,400 0,149.4376 82.71418,280.09665 204.65234,348.75391 5.86588,-34.27979 17.34855,-66.54493 33.73828,-95.75 C 255.06192,699.834 200,606.64908 200,500 200,333.72266 333.72266,200 500,200 c 142.38957,0 260.8216,98.09404 291.93555,230.68555 L 856.42383,318.99023 C 790.16805,189.24325 655.22057,100 500,100 Z"
inkscape:path-effect="#path-effect19" />
<g
id="path7"
inkscape:transform-center-y="-175.00286" />
<path
id="rect1"
style="fill:#ffffff;fill-opacity:0.6;stroke-width:979.022;stroke-linejoin:round;stroke-opacity:0.8"
d="m 6184.7961,1000 c -523.7731,0 -998.143,204.0121 -1348.2993,537.2416 -1524.5715,1450.8733 -1133.7259,1083.5981 -1994.5161,1968.3924 -400.6935,411.8671 -262.7586,742.7614 311.8659,742.7614 H 9998.66 a 2296.6616,2296.6616 0 0 0 1618.245,-666.9561 l 1378.483,-1368.786 c 101.339,-100.6267 238.505,-156.873 381.318,-156.3643 142.807,0.5062 279.562,57.7207 380.184,159.0566 209.529,211.0226 208.323,551.9455 -2.692,761.4813 l -1250.367,1241.5744 a 2486.9119,2486.9119 0 0 0 -734.6,1764.7027 v 6396.65 c 0,813.938 466.274,1006.895 1041.271,430.81 1022.07,-1024.006 1369.084,-1371.996 1591.49,-1585.979 369.022,-355.046 598.008,-854.484 598.008,-1409.3808 V 2954.0263 C 15000,1871.4958 14128.505,1000 13045.973,1000 Z M 8000.0004,2076.9231 A 1615.3846,538.46153 0 0 1 9615.385,2615.3846 1615.3846,538.46153 0 0 1 8000.0004,3153.8461 1615.3846,538.46153 0 0 1 6384.6158,2615.3846 1615.3846,538.46153 0 0 1 8000.0004,2076.9231 Z m 5923.0776,1615.3846 a 538.46153,1615.3846 0 0 1 538.461,1615.3845 538.46153,1615.3846 0 0 1 -538.461,1615.3847 538.46153,1615.3846 0 0 1 -538.462,-1615.3847 538.46153,1615.3846 0 0 1 538.462,-1615.3845 z m -1076.923,4846.1538 a 538.46153,1615.3846 0 0 1 538.46,1615.3845 538.46153,1615.3846 0 0 1 -538.46,1615.385 538.46153,1615.3846 0 0 1 -538.461,-1615.385 538.46153,1615.3846 0 0 1 538.461,-1615.3845 z" />
<path
id="rect6"
style="fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:969.226;stroke-linecap:round;stroke-linejoin:round;stroke-opacity:1"
d="m 2907.1639,5307.6922 c -1056.5657,0 -1907.1634,850.5979 -1907.1634,1907.1635 v 5877.9803 c 0,1056.566 850.5977,1907.164 1907.1634,1907.164 h 5877.9808 c 1056.5657,0 1907.1633,-850.598 1907.1633,-1907.164 V 7214.8557 c 0,-1056.5656 -850.5976,-1907.1635 -1907.1633,-1907.1635 z m 785.1443,1076.9231 A 1615.3846,1615.3846 0 0 1 5307.6927,7999.9999 1615.3846,1615.3846 0 0 1 3692.3082,9615.3845 1615.3846,1615.3846 0 0 1 2076.9236,7999.9999 1615.3846,1615.3846 0 0 1 3692.3082,6384.6153 Z m 4307.6922,0 A 1615.3846,1615.3846 0 0 1 9615.385,7999.9999 1615.3846,1615.3846 0 0 1 8000.0004,9615.3845 1615.3846,1615.3846 0 0 1 6384.6158,7999.9999 1615.3846,1615.3846 0 0 1 8000.0004,6384.6153 Z M 3692.3082,10692.307 a 1615.3846,1615.3846 0 0 1 1615.3845,1615.386 1615.3846,1615.3846 0 0 1 -1615.3845,1615.384 1615.3846,1615.3846 0 0 1 -1615.3846,-1615.384 1615.3846,1615.3846 0 0 1 1615.3846,-1615.386 z m 4307.6922,0 A 1615.3846,1615.3846 0 0 1 9615.385,12307.693 1615.3846,1615.3846 0 0 1 8000.0004,13923.077 1615.3846,1615.3846 0 0 1 6384.6158,12307.693 1615.3846,1615.3846 0 0 1 8000.0004,10692.307 Z" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 18 KiB

File diff suppressed because it is too large Load Diff
@@ -0,0 +1,227 @@
# SPDX-FileCopyrightText: 2025 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
import bpy
from bpy.app.handlers import persistent
from bpy_extras.io_utils import ImportHelper
from . import utils
import os
@persistent
def load_handler(dummy):
addon_prefs = bpy.context.preferences.addons[__package__].preferences
if not addon_prefs.resource_path:
utils.unpack_resources()
utils.refresh_brushstroke_styles()
def update_resource_path(self, context):
if utils.get_resource_directory() == utils.get_default_resource_directory():
utils.unpack_resources()
utils.update_asset_lib_path()
class BSBST_OT_install_brush_style_pack(bpy.types.Operator, ImportHelper):
bl_idname = "brushstroke_tools.install_brush_style_pack"
bl_label = "Install Brush Style Pack"
filter_glob: bpy.props.StringProperty(
default='*.zip;*.blend',
options={'HIDDEN'}
)
def execute(self, context):
""" Install selected brush style pack at resource location and refresh available brush styles.
"""
install_state = utils.install_brush_style_pack(self.filepath, ot=self)
if not install_state:
return {'CANCELLED'}
utils.refresh_brushstroke_styles()
return {'FINISHED'}
class BSBST_OT_refresh_brushstroke_styles(bpy.types.Operator):
"""
"""
bl_idname = "brushstroke_tools.refresh_styles"
bl_label = "Refresh Brushstroke Styles"
bl_description = "Refresh available brushstroke styles from library."
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
utils.refresh_brushstroke_styles()
return {"FINISHED"}
class BSBST_OT_copy_resources_to_path(bpy.types.Operator):
"""
Copy Resources to Directory.
"""
bl_idname = "brushstroke_tools.copy_resources"
bl_label = "Copy Resources"
bl_description = "Copy addon resources to local directory"
bl_options = {"REGISTER", "UNDO"}
update: bpy.props.BoolProperty(default=False)
@classmethod
def poll(cls, context):
addon_prefs = context.preferences.addons[__package__].preferences
return os.path.isdir(addon_prefs.resource_path)
def execute(self, context):
utils.copy_resources_to_dir()
return {"FINISHED"}
def invoke(self, context, event):
wm = context.window_manager
return wm.invoke_props_dialog(self)
def draw(self, context):
layout = self.layout
layout.label(text='This will overwrite the resource files in the target directory! Additional data, like brush styles, will be kept.', icon='ERROR')
layout.label(text=str(utils.get_resource_directory()))
class BSBST_OT_open_resource_directory(bpy.types.Operator):
"""
Open resource directory in system's default file manager.
"""
bl_idname = "brushstroke_tools.open_resource_directory"
bl_label = "Open Resource Directory"
bl_description = "Open directory in system's default file manager"
bl_options = {"REGISTER"}
path: bpy.props.StringProperty(default='', subtype='DIR_PATH')
def execute(self, context):
utils.open_in_file_manager(utils.get_resource_directory())
return {"FINISHED"}
class BSBST_UL_brush_styles(bpy.types.UIList):
def draw_item(self, context, layout, data, item, icon, active_data, active_propname):
resource_dir = utils.get_resource_directory()
if self.layout_type in {'DEFAULT', 'COMPACT'}:
main_split = layout.split(factor=0.5)
row = main_split.row()
split = row.split()
if not item.filepath:
split.label(text=item.name, icon='FILE_BLEND')
else:
split.label(text=item.name, icon='BRUSHES_ALL')
split = split.split()
split.label(text=item.category)
split.label(text=item.type)
row = main_split.row()
row.active = False
row.label(text=item.filepath.replace(str(resource_dir), '{LIB}'), icon='FILE_FOLDER')
elif self.layout_type == 'GRID':
layout.label(text=item.name)
def draw_filter(self, context, layout):
return
class BSBST_preferences(bpy.types.AddonPreferences):
bl_idname = __package__
resource_path: bpy.props.StringProperty(name='Resource Directory', subtype='DIR_PATH', update=update_resource_path)
import_relative_path: bpy.props.BoolProperty(name='Relative Path', default=True)
import_method: bpy.props.EnumProperty(name='Import Method', default='APPEND',
items= [('APPEND', 'Append', 'Append data-blocks and pack image data as local to this file.', 'APPEND_BLEND', 0),\
('LINK', 'Link', 'Link data-blocks from resource directory.', 'LINK_BLEND', 1),
])
brush_styles: bpy.props.CollectionProperty(type=utils.BSBST_brush_style)
active_brush_style_index: bpy.props.IntProperty()
def draw(self, context):
layout = self.layout
row = layout.row()
row.label(text='Brushstrokes Library', icon='ASSET_MANAGER')
layout.prop(self, 'import_method')
if self.import_method == 'LINK':
layout.prop(self, 'import_relative_path')
row = layout.row()
col = row.column()
dir_exists = os.path.isdir(utils.get_resource_directory())
resources_available = utils.check_resources_valid()
if not dir_exists or not resources_available:
col.alert = True
col.prop(self, 'resource_path', placeholder=str(utils.get_resource_directory()))
op = col.operator('brushstroke_tools.open_resource_directory', icon='ASSET_MANAGER')
split = layout.split(factor=0.25)
split.column()
col = split.column()
if not dir_exists:
col.alert = True
row = col.row()
row.label(text='The selected directory does not exist.', icon='ERROR')
elif not resources_available:
col.alert = True
split = col.split(factor=0.75)
split.label(text='The required resources were not found at the specified directory.', icon='ERROR')
op = split.operator('brushstroke_tools.copy_resources', icon='IMPORT')
op.update = False
elif self.resource_path:
lib_version = utils.read_lib_version()
version_comp = utils.compare_versions(lib_version, utils.addon_version)
if bool(version_comp):
col.label(text=f"Version mismatch: Local Data ({'.'.join([str(i) for i in lib_version])}) {'>' if version_comp>0 else '<'} Addon ({'.'.join([str(i) for i in utils.addon_version])})", icon='ERROR')
if abs(version_comp) in [1, 2, 3]:
split = col.split(factor=0.75)
if version_comp>0:
split.label(text="Consider upgrading the addon and re-copying the data.")
else:
split.label(text="Consider re-copying the data.")
op = split.operator('brushstroke_tools.copy_resources', icon='IMPORT')
op.update = False
if self.import_method == 'LINK' and not self.resource_path:
col.label(text='Linking the resources from the default addon directory is not recommended.', icon='ERROR')
style_box = layout.box()
style_box_header = style_box.row(align=True)
count_local = len([bs for bs in self.brush_styles if not bs.filepath])
if count_local:
count_info = f'Brush Styles ({len(self.brush_styles)-count_local} loaded, {count_local} local)'
else:
count_info = f'Brush Styles ({len(self.brush_styles)} loaded)'
style_box_header.label(text=count_info, icon='BRUSHES_ALL')
style_box_header.operator('brushstroke_tools.install_brush_style_pack')
style_box_header.operator('brushstroke_tools.refresh_styles', text='', icon='FILE_REFRESH')
if not self.brush_styles:
style_box.label(text='No Brush styles found in library directory', icon='ERROR')
else:
row = style_box.row(align=True)
row.active = False
main_split = style_box.split()
row = main_split.row()
split = row.split()
split.label(text='Name')
split = split.split()
split.label(text='Category')
split.label(text='Type')
main_split.label(text='Filepath')
style_box.template_list('BSBST_UL_brush_styles', "", self, "brush_styles",
self, "active_brush_style_index", rows=3, maxrows=5, sort_lock=True)
classes = [
BSBST_UL_brush_styles,
BSBST_preferences,
BSBST_OT_copy_resources_to_path,
BSBST_OT_refresh_brushstroke_styles,
BSBST_OT_install_brush_style_pack,
BSBST_OT_open_resource_directory,
]
def register():
for c in classes:
bpy.utils.register_class(c)
bpy.app.handlers.load_post.append(load_handler)
def unregister():
for c in classes:
bpy.utils.unregister_class(c)
bpy.app.handlers.load_post.remove(load_handler)
@@ -0,0 +1,319 @@
# SPDX-FileCopyrightText: 2025 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
import bpy
from . import utils, icons
def update_active_brushstrokes(self, context):
settings = context.scene.BSBST_settings
for i, el in enumerate(settings.context_brushstrokes):
ob = bpy.data.objects.get(el.name)
if not ob:
continue
is_active = i == settings.active_context_brushstrokes_index
ob['BSBST_active'] = is_active
if 'BSBST_material' in ob.keys() and is_active:
settings.silent_switch = True
settings.context_material = ob['BSBST_material']
settings.silent_switch = False
def update_brushstroke_method(self, context):
settings = context.scene.BSBST_settings
preset_name = f'BSBST-PRESET_{settings.brushstroke_method}'
preset_object = bpy.data.objects.get(preset_name)
settings.preset_object = preset_object
style_object = utils.get_active_context_brushstrokes_object(context)
if not style_object:
style_object = preset_object
settings.silent_switch = True
if not style_object:
settings.context_material = None
settings.silent_switch = False
return
if 'BSBST_material' in style_object.keys():
settings.context_material = style_object['BSBST_material']
else:
settings.context_material = None
settings.silent_switch = False
def update_context_material(self, context):
settings = context.scene.BSBST_settings
if settings.silent_switch:
return
style_object = utils.get_active_context_brushstrokes_object(context)
if not style_object:
style_object = settings.preset_object
if not style_object:
return
utils.set_brushstroke_material(style_object, self.context_material)
if not self.context_material:
utils.set_preview(None)
return
bs = utils.find_brush_style_by_name(self.context_material.brush_style)
if bs is None:
ng_name = self.context_material.brush_style
else:
ng_name = bs.id_name
ng = bpy.data.node_groups.get(ng_name)
if not ng:
utils.set_preview(None)
return
if ng.preview:
utils.set_preview(ng.preview.image_pixels_float, ng.preview.image_size[:], ng.name)
else:
utils.set_preview(None)
def update_link_context_type(self, context):
self.link_context = True
def get_brushstroke_name(self):
return self["name"]
def set_brushstroke_name(self, value):
prev_name = self.get('name')
self["name"] = value
if not prev_name:
return
ob = bpy.data.objects.get(prev_name)
if not ob:
return
ob.name = value
ob.data.name = value
flow_ob = utils.get_flow_object(ob)
if flow_ob:
flow_name = utils.flow_name(value)
flow_ob.name = flow_name
flow_ob.data.name = flow_name
def get_modifier_name(self):
return self["name"]
def set_modifier_name(self, value):
prev_name = self.get('name')
if not prev_name:
self["name"] = value
return
ob = self.id_data.modifiers.get(prev_name)
ob.name = value
self["name"] = ob.name
def get_hide_viewport_base(self):
return self["hide_viewport_base"]
def set_hide_viewport_base(self, value):
self["hide_viewport_base"] = value
ob = bpy.data.objects.get(self.name)
if not ob:
return
ob.hide_set(value)
def get_active_context_brushstrokes_index(self):
if not self.get('active_context_brushstrokes_index'):
return 0
return self["active_context_brushstrokes_index"]
def set_active_context_brushstrokes_index(self, value):
settings = bpy.context.scene.BSBST_settings
if not settings.context_brushstrokes:
if not settings.preset_object:
return
if 'BSBST_material' in settings.preset_object.keys():
settings.silent_switch = True
settings.context_material = settings.preset_object['BSBST_material']
settings.silent_switch = False
prev = self.get('active_context_brushstrokes_index')
if prev == abs(value):
return
self["active_context_brushstrokes_index"] = abs(value)
bs_ob = bpy.data.objects.get(self.context_brushstrokes[value].name)
if settings.silent_switch:
return
if not bs_ob:
return
if not bpy.context.object:
return
view_layer = bpy.context.view_layer
if bpy.context.object.visible_get(view_layer = view_layer):
bpy.ops.object.mode_set(mode='OBJECT')
bpy.context.view_layer.objects.active = bs_ob
if bs_ob.visible_get(view_layer = view_layer):
bpy.ops.object.mode_set(mode='OBJECT')
for ob in bpy.data.objects:
ob.select_set(False)
if utils.is_brushstrokes_object(ob):
ob['BSBST_active'] = False
bs_ob.select_set(True)
bs_ob['BSBST_active'] = True
if settings.edit_toggle and bs_ob.visible_get(view_layer = view_layer):
utils.edit_active_brushstrokes(bpy.context)
if 'BSBST_material' in bs_ob.keys():
settings.context_material = bs_ob['BSBST_material']
def get_brush_style(self):
node = self.node_tree.nodes.get('Brush Style')
if node is None:
return ''
name = node.node_tree.name
name, extension = utils.split_id_name(name)
name = name.split('.')[-1]
if extension:
name = f'{name}.{extension}'
return name
def set_brush_style(self, value):
addon_prefs = bpy.context.preferences.addons[__package__].preferences
brush_style = utils.find_brush_style_by_name(value)
if brush_style is None:
return
ng = utils.ensure_node_group(brush_style.id_name, brush_style.filepath)
if ng.preview:
utils.set_preview(ng.preview.image_pixels_float, ng.preview.image_size[:], ng.name)
else:
utils.set_preview(None)
node = self.node_tree.nodes['Brush Style']
node_prev_inputs = [input.name for input in node.inputs]
node.node_tree = ng
for in_new in node.inputs:
if in_new.name in node_prev_inputs:
continue
in_new.default_value = ng.interface.items_tree[in_new.name].default_value
self["brush_style"] = value
def link_context_type_items(self, context):
items = [
('SURFACE_OBJECT', 'Surface Object', 'Link socket preset to context surface object', 'OUTLINER_OB_SURFACE', 1),\
('FLOW_OBJECT', 'Flow Object', 'Link socket preset to context flow object', 'FORCE_WIND', 11),
('MATERIAL', 'Material', 'Link socket preset to context material', 'MATERIAL', 101),
('UVMAP', 'UV Map', 'Link socket preset to active context UVMap', 'UV', 201),
('RANDOM', 'Random', 'Randomize input value', icons.icon_previews['main']["RANDOM"].icon_id, 501),
]
return items
def icon_from_link_type(link_type):
items = link_context_type_items(None, bpy.context)
for enum_item in items:
if enum_item[0]==link_type:
icon = enum_item[3]
if type(icon) == int:
return icon
else:
return {k : i for i, k in enumerate(bpy.types.UILayout.bl_rna.functions["prop"].parameters["icon"].enum_items.keys())}[icon]
class BSBST_socket_info(bpy.types.PropertyGroup):
name: bpy.props.StringProperty(default='')
link_context: bpy.props.BoolProperty(default=False, name='Link to Context')
link_context_type: bpy.props.EnumProperty(default=1, name='Link to Context', update=update_link_context_type,
items=link_context_type_items)
hide_ui: bpy.props.BoolProperty(default=False)
class BSBST_modifier_info(bpy.types.PropertyGroup):
name: bpy.props.StringProperty(default='', get=get_modifier_name, set=set_modifier_name)
hide_ui: bpy.props.BoolProperty(default=False)
default_closed: bpy.props.BoolProperty(default=False)
socket_info: bpy.props.CollectionProperty(type=BSBST_socket_info)
class BSBST_context_brushstrokes(bpy.types.PropertyGroup):
name: bpy.props.StringProperty(default='', get=get_brushstroke_name, set=set_brushstroke_name)
method: bpy.props.StringProperty(default='')
hide_viewport_base: bpy.props.BoolProperty(default=False, get=get_hide_viewport_base, set=set_hide_viewport_base)
class BSBST_Settings(bpy.types.PropertyGroup):
attach_to_active_selection: bpy.props.BoolProperty(default=True)
preset_object: bpy.props.PointerProperty(type=bpy.types.Object, name="Default/Preset Object")
assign_materials: bpy.props.BoolProperty(name='Assign Modifier Materials', default=True)
brushstroke_method: bpy.props.EnumProperty(default='SURFACE_FILL', update=update_brushstroke_method,
items= [('SURFACE_FILL', 'Fill', 'Use surface fill method for new brushstroke object', 'OUTLINER_OB_FORCE_FIELD', 0),\
('SURFACE_DRAW', 'Draw', 'Use surface draw method for new brushstroke object', 'LINE_DATA', 1),
])
style_context: bpy.props.EnumProperty(default='BRUSHSTROKES',
name='Context',
items= [
('PRESET', 'Default', 'Specify the style of the current default used for new brushstrokes', 'SETTINGS', 0),\
('BRUSHSTROKES', 'Brushstrokes', 'Specify the style of the currently active brushstrokes', 'BRUSH_DATA', 1),
('AUTO', 'Auto', 'Specify the style of either the active brushstrokes or the preset depending on the context', 'AUTO', 2),
])
view_tab: bpy.props.EnumProperty(default='SHAPE',
name='Context',
items= [
('SHAPE', 'Shape', 'View Modifiers Settings', 'MODIFIER', 0),
('MATERIAL', 'Material', 'View Material Settings', 'MATERIAL', 1),
('SETTINGS', 'Settings', 'View Additional Settings', 'PREFERENCES', 2),
])
try:
gpv3 = bpy.context.preferences.experimental.use_grease_pencil_version3
except:
v0, v1, v3 = bpy.app.version
gpv3 = v0 >= 4 and v1 >= 3
curve_mode: bpy.props.EnumProperty(default='CURVES',
items= [('CURVE', 'Legacy', 'Use legacy curve type (Limited Support)', 'CURVE_DATA', 0),\
('CURVES', 'Curves', 'Use hair curves (Fully supported)', 'CURVES_DATA', 1),
('GP', 'Grease Pencil', 'Use Grease Pencil (Limited Support)', 'OUTLINER_OB_GREASEPENCIL', 2),
] if gpv3 else
[('CURVE', 'Legacy', 'Use legacy curve type (Limited Support)', 'CURVE_DATA', 0),\
('CURVES', 'Curves', 'Use hair curves (Full Support)', 'CURVES_DATA', 1),
])
context_brushstrokes: bpy.props.CollectionProperty(type=BSBST_context_brushstrokes)
context_material: bpy.props.PointerProperty(type=bpy.types.Material, name="Material", update=update_context_material)
active_context_brushstrokes_index: bpy.props.IntProperty( default = 0,
update=update_active_brushstrokes,
get=get_active_context_brushstrokes_index,
set=set_active_context_brushstrokes_index)
ui_options: bpy.props.BoolProperty(default=False,
name='UI Options',
description="Show advanced UI options to customize exposed parameters")
reuse_flow: bpy.props.BoolProperty(default=False,
name='Re-use Flow Object',
description="Re-use flow object from active brushstrokes when creating new brushstrokes")
deforming_surface: bpy.props.BoolProperty(default=False,
name='Deforming Surface',
description='Create brushstrokes layer for a deforming surface')
animated: bpy.props.BoolProperty(default=False,
name='Animated',
description='Create brushstrokes layer for animated brushstrokes/flow')
edit_toggle: bpy.props.BoolProperty(default=False,
name='Edit on Selection',
description="Jump into the corresponding edit mode when selecting a brushstrokes layer")
estimate_dimensions: bpy.props.BoolProperty(default=True,
name='Estimate Dimensions',
description="Estimate the length, width and distribution density of the brush strokes based on the bounding box to provide a reasonable starting point regardless of scale")
silent_switch: bpy.props.BoolProperty(default=False)
preview_texture: bpy.props.PointerProperty(type=bpy.types.Texture)
classes = [
BSBST_socket_info,
BSBST_modifier_info,
BSBST_context_brushstrokes,
BSBST_Settings,
]
def register():
for c in classes:
bpy.utils.register_class(c)
bpy.types.Scene.BSBST_settings = bpy.props.PointerProperty(type=BSBST_Settings)
bpy.types.Object.modifier_info = bpy.props.CollectionProperty(type=BSBST_modifier_info)
bpy.types.Material.brush_style = bpy.props.StringProperty(get=get_brush_style, set=set_brush_style, search_options={'SORT'})
bpy.app.handlers.depsgraph_update_post.append(utils.find_context_brushstrokes)
def unregister():
for c in reversed(classes):
bpy.utils.unregister_class(c)
del bpy.types.Scene.BSBST_settings
del bpy.types.Object.modifier_info
bpy.app.handlers.depsgraph_update_post.remove(utils.find_context_brushstrokes)
@@ -0,0 +1,611 @@
# SPDX-FileCopyrightText: 2025 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
import bpy
from . import utils
from . import settings as settings_py
warning_icons_dict = {
'ERROR': 'CANCEL',
'WARNING': 'ERROR',
'INFO': 'INFO',
}
def draw_panel_ui_recursive(panel, panel_name, mod, items, display_mode, hide_panel=False):
scene = bpy.context.scene
settings = scene.BSBST_settings
is_preset = mod.id_data == settings.preset_object and mod.id_data
if not panel:
return
mod_info = mod.id_data.modifier_info.get(mod.name)
icon_dict = {
bpy.types.NodeTreeInterfaceSocketObject: 'OBJECT_DATA',
bpy.types.NodeTreeInterfaceSocketMaterial: 'MATERIAL',
bpy.types.NodeTreeInterfaceSocketImage: 'IMAGE_DATA',
bpy.types.NodeTreeInterfaceSocketCollection: 'OUTLINER_COLLECTION',
}
data_dict = {
bpy.types.NodeTreeInterfaceSocketMaterial: 'materials',
bpy.types.NodeTreeInterfaceSocketImage: 'images',
bpy.types.NodeTreeInterfaceSocketCollection: 'collections',
}
mode_compare = []
for k, v in items:
if not v.parent.name == panel_name:
continue
if type(v) == bpy.types.NodeTreeInterfacePanel:
v_id = f'Panel_{v.index}' # TODO: replace with panel identifier once that is exposed in Blender 4.3
if not mod_info:
continue
s = mod_info.socket_info.get(v_id)
if not s:
continue
if display_mode == 0:
if s.hide_ui:
continue
subpanel_header, subpanel = panel.panel(k, default_closed = v.default_closed)
subpanel_header.label(text=k)
if display_mode != 0:
col = subpanel_header.column()
col.active = not (mod_info.hide_ui or hide_panel)
col.prop(s, 'hide_ui', icon_only=True, icon='UNPINNED' if s.hide_ui else 'PINNED', emboss=False)
draw_panel_ui_recursive(subpanel, k, mod, v.interface_items.items(), display_mode, s.hide_ui)
mode_compare = []
else:
if v.parent.name != panel_name:
continue
if f'{v.identifier}' not in mod.keys():
continue
if not mod_info:
continue
if type(v) == bpy.types.NodeTreeInterfaceSocketMenu:
for item in mod.id_properties_ui(f'{v.identifier}').as_dict()['items']:
if item[4] == mod[f'{v.identifier}']:
continue
mode_compare += [item[0]]
s = mod_info.socket_info.get(v.identifier)
if not s:
continue
if display_mode == 0:
comp_match = False
for c in mode_compare:
comp_match = c in v.name
if comp_match:
break
if comp_match:
continue
if s.hide_ui:
continue
row = panel.row(align=True)
row.active = not (mod_info.hide_ui or hide_panel or s.hide_ui)
col = row.column()
input_row = col.row(align=True)
attribute_toggle = False
if f'{v.identifier}_use_attribute' in mod.keys() and not v.force_non_field:
attribute_toggle = mod[f'{v.identifier}_use_attribute']
if attribute_toggle:
input_row.prop(mod, f'["{v.identifier}_attribute_name"]', text=k)
else:
input_row.prop(mod, f'["{v.identifier}"]', text=k)
if is_preset:
toggle = input_row.operator('brushstroke_tools.preset_toggle_attribute',
text='',
depress=mod[f'{v.identifier}_use_attribute'],
icon='SPREADSHEET')
else:
toggle = input_row.operator('brushstroke_tools.brushstrokes_toggle_attribute',
text='',
depress=mod[f'{v.identifier}_use_attribute'],
icon='SPREADSHEET')
toggle.modifier_name = mod.name
toggle.input_name = v.identifier
else:
if type(v) in icon_dict.keys():
icon = icon_dict[type(v)]
else:
icon='NONE'
if type(v) in data_dict.keys():
input_row.prop_search(mod, f'["{v.identifier}"]', bpy.data, data_dict[type(v)], text=k, icon=icon)
else:
input_row.prop(mod, f'["{v.identifier}"]', text=k, icon=icon)
if type(v) in utils.linkable_sockets:
col.active = not s.link_context
icon = settings_py.icon_from_link_type(s.link_context_type)
row.alignment = 'EXPAND'
if s.link_context:
row.prop(s, 'link_context', text='', icon_value=icon)
else:
if display_mode == -1:
row.prop(s, 'link_context_type', text='', emboss=True, icon='LINKED', icon_only=True)
if display_mode != 0:
col = row.column()
col.active = not (mod_info.hide_ui or hide_panel)
col.prop(s, 'hide_ui', icon_only=True, icon='UNPINNED' if s.hide_ui else 'PINNED', emboss=False)
def draw_material_settings(layout, material, surface_object=None):
addon_prefs = bpy.context.preferences.addons[__package__].preferences
settings = bpy.context.scene.BSBST_settings
material_row = layout.row(align=True)
material_row.template_ID(settings, 'context_material')
material_header, material_panel = layout.panel("brushstrokes_material", default_closed=False)
material_header.label(text='Properties', icon='MATERIAL')
if material_panel:
# draw color options
try:
n1 = material.node_tree.nodes['Color Attribute']
n2 = material.node_tree.nodes['Color Texture']
n3 = material.node_tree.nodes['Color']
n4 = material.node_tree.nodes['Image Texture']
n5 = material.node_tree.nodes['UV Map']
n6 = material.node_tree.nodes['Color Variation']
n7 = material.node_tree.nodes.get('Variation Scale')
n8 = material.node_tree.nodes.get('Variation Hue')
n9 = material.node_tree.nodes.get('Variation Saturation')
n10 = material.node_tree.nodes.get('Variation Luminance')
box = material_panel.box()
box.prop(n1, 'mute', text='Use Brush Color', invert_checkbox=True)
if n1.mute:
row = box.row(align=True)
if n2.mute:
row.prop(n3.outputs[0], 'default_value', text ='')
else:
col = row.column()
col.template_node_inputs(n4)
row.prop(n2, 'mute', icon_only=True, invert_checkbox=True, icon='IMAGE')
if not n2.mute:
if not surface_object:
box.prop(n5, 'uv_map', icon='UV')
else:
box.prop_search(n5, 'uv_map', surface_object.data, 'uv_layers', icon='UV')
variation_box = box.box()
variation_box.prop(n6.inputs[0], 'default_value', text='Color Variation')
if n7:
variation_box.prop(n7.outputs[0], 'default_value', text='Variation Scale')
col = variation_box.column(align=True)
if n8:
col.prop(n8.inputs[0], 'default_value', text='Hue')
if n9:
col.prop(n9.inputs[0], 'default_value', text='Saturation')
if n10:
col.prop(n10.inputs[0], 'default_value', text='Luminance')
except:
pass
# draw opacity options
try:
n1 = material.node_tree.nodes.get('Use Strength')
n2 = material.node_tree.nodes.get('Opacity')
n3 = material.node_tree.nodes.get('Backface Culling')
box = material_panel.box()
if n1:
box.prop(n1, 'mute', text='Use Brush Strength', invert_checkbox=True)
if n2:
box.prop(n2.inputs[0], 'default_value', text='Opacity')
if n3:
box.prop(n3, 'mute', text='Backface Culling', invert_checkbox=True)
except:
pass
# draw BSDF options
try:
n1 = material.node_tree.nodes['Principled BSDF']
n2 = material.node_tree.nodes['Bump']
box = material_panel.box()
box.prop(n1.inputs[1], 'default_value', text='Metallic')
box.prop(n1.inputs[2], 'default_value', text='Roughness')
box.prop(n2, 'mute', text='Bump', invert_checkbox=True)
row = box.row()
if n2.mute:
row.active = False
row.prop(n2.inputs[0], 'default_value', text='Bump Strength')
except:
pass
# draw translucency options
try:
n1 = material.node_tree.nodes['Translucency Add']
n2 = material.node_tree.nodes['Translucency Strength']
n3 = material.node_tree.nodes['Translucency Tint']
box = material_panel.box()
box.prop(n1, 'mute', text='Translucency', invert_checkbox=True)
box.prop(n2.inputs[0], 'default_value', text='Translucency Strength')
box.prop(n3.inputs[7], 'default_value', text='Translucency Tint')
except:
pass
material_panel.prop(material, 'diffuse_color', text='Viewport Color')
# draw brush style options
try:
n1 = material.node_tree.nodes['Brush Style']
n2 = material.node_tree.nodes['Brush Curve']
brush_header, brush_panel = layout.panel('brush_panel', default_closed = True)
brush_header.label(text='Brush Style', icon='BRUSHES_ALL')
if brush_panel:
if settings.preview_texture:
row = brush_panel.row(align=True)
row.template_preview(settings.preview_texture, show_buttons=False, preview_id='brushstroke_preview')
row = brush_panel.row(align=True)
brush_style_name = material.brush_style
brush_style_category = ''
bs = utils.find_brush_style_by_name(brush_style_name)
if bs is not None:
brush_style_name = bs.name
brush_style_category = bs.category
brush_style_label = f'{brush_style_category}: {brush_style_name}' if brush_style_category else brush_style_name
else:
brush_style_label = brush_style_name
row.operator('brushstroke_tools.select_brush_style', text=brush_style_label, icon='BRUSHES_ALL')
row.operator('brushstroke_tools.refresh_styles', text='', icon='FILE_REFRESH')
if n1.inputs:
for in_s in n1.inputs:
brush_panel.prop(in_s, 'default_value', text=f"{in_s.name}")
brush_panel.template_node_inputs(n2)
except:
pass
# draw effects options
try:
n1 = material.node_tree.nodes['Effects In']
effects_header, effects_panel = layout.panel('effects_panel', default_closed = True)
effects_header.label(text='Effects', icon='SHADERFX')
if effects_panel:
draw_effect_panel_recursive(effects_panel, material, n1)
except:
pass
def draw_effect_panel_recursive(effects_panel, material, prev_node):
if not prev_node:
return
if not prev_node.outputs[0].links:
return
node = prev_node.outputs[0].links[0].to_node
if node.name == 'Effects Out':
return
header, panel = effects_panel.panel(f'{node.name}_panel', default_closed = True)
header.alignment = 'LEFT'
header.prop(node, 'mute', invert_checkbox=True, icon_only=True)
header.label(text=node.label if node.label else node.name)
if panel:
if node.mute:
panel.active = False
for input in node.inputs[1:]:
panel.prop(input, 'default_value', text=input.name)
draw_effect_panel_recursive(effects_panel, material, node)
def draw_advanced_settings(layout, settings):
new_advanced_header, new_advanced_panel = layout.panel("new_advanced", default_closed=True)
new_advanced_header.label(text='Advanced')
if not new_advanced_panel:
return
new_advanced_panel.row().prop(settings, 'curve_mode', expand=True)
if settings.curve_mode in ['CURVE', 'GP']:
new_advanced_panel.label(text='Curve mode does not support drawing on deformed geometry', icon='ERROR')
new_advanced_panel.prop(settings, 'animated')
new_advanced_panel.prop(settings, 'deforming_surface')
new_advanced_panel.prop(settings, 'assign_materials')
new_advanced_panel.prop(settings, 'reuse_flow')
new_advanced_panel.prop(settings, 'estimate_dimensions')
new_advanced_panel.prop(settings, 'style_context')
new_advanced_panel.operator('brushstroke_tools.render_setup')
new_advanced_panel.operator('brushstroke_tools.upgrade_resources')
def draw_shape_properties(layout, settings, style_object, is_preset, display_mode):
if not style_object:
return
for mod in style_object.modifiers:
mod_info = mod.id_data.modifier_info.get(mod.name)
if not mod_info:
continue
if display_mode == 0:
if mod_info.hide_ui:
continue
mod_header, mod_panel = layout.panel(mod.name, default_closed = mod_info.default_closed)
row = mod_header.row(align=True)
row.label(text='', icon='GEOMETRY_NODES')
row.prop(mod_info, 'name', text='', emboss=False)
if display_mode != 0:
mod_header.prop(mod_info, 'hide_ui', icon_only=True, icon='UNPINNED' if mod_info.hide_ui else 'PINNED', emboss=False)
if is_preset:
op = row.operator('brushstroke_tools.preset_remove_mod', text='', icon='X')
else:
op = row.operator('object.modifier_remove', text='', icon='X')
# TODO Implement operator to remove modifier on brushstroke object, even when not active
op.modifier = mod.name
if not mod_panel:
continue
if not mod.type == 'NODES':
mod_panel.label(text="Only 'Nodes' modifiers supported")
continue
# show settings for nodes modifiers
if mod.show_group_selector:
mod_panel.prop(mod, 'node_group')
if not mod.node_group:
continue
draw_panel_ui_recursive(mod_panel,
'',
mod,
mod.node_group.interface.items_tree.items(),
display_mode)
draw_mod_warnings(layout, mod)
def draw_material_properties(layout, settings, surface_object):
if settings.context_material:
draw_material_settings(layout, settings.context_material, surface_object=surface_object)
else:
material_row = layout.row(align=True)
material_row.template_ID(settings, 'context_material', new='brushstroke_tools.new_material')
def draw_settings_properties(layout, settings, style_object):
deform = utils.get_deformable(style_object)
op = layout.operator('brushstroke_tools.switch_deformable', text='Deforming Surface', depress=deform, icon='MOD_SIMPLEDEFORM')
op.deformable = not deform
anim = utils.get_animated(style_object)
op = layout.operator('brushstroke_tools.switch_animated', text='Animated Strokes', depress=anim, icon='GP_MULTIFRAME_EDITING')
op.animated = not anim
layout.prop(style_object, 'visible_shadow', icon='LIGHT', emboss=True)
def draw_properties_panel(layout, settings, style_object, surface_object, is_preset, display_mode):
layout.separator(type='LINE')
row = layout.row(align=True)
row.prop(settings, 'view_tab', expand=True)
layout.separator(factor=.0, type='SPACE')
if settings.view_tab == 'MATERIAL':
draw_material_properties(layout, settings, surface_object)
elif settings.view_tab == 'SHAPE':
draw_shape_properties(layout, settings, style_object, is_preset, display_mode)
# expose add modifier operator for preset context
if is_preset:
layout.operator('brushstroke_tools.preset_add_mod', icon='ADD')
elif settings.view_tab == 'SETTINGS':
draw_settings_properties(layout, settings, style_object)
def draw_mod_warnings(layout, mod):
if utils.compare_versions(bpy.app.version, (4,3,0)) < 0:
return
if mod.node_warnings:
warnings_header, warnings_panel = layout.panel(mod.name+'_warnings', default_closed = True)
warnings_header.label(text=f'Warnings ({len(mod.node_warnings)})')
if warnings_panel:
for warning in mod.node_warnings: # TODO sort warnings by type and alphabet
warnings_panel.label(text=warning.message,icon=warning_icons_dict[warning.type])
class BSBST_UL_brushstroke_objects(bpy.types.UIList):
def draw_item(self, context, layout, data, item, icon, active_data, active_propname):
settings = data
context_brushstroke = item
if self.layout_type in {'DEFAULT', 'COMPACT'}:
if context_brushstroke:
method_icon = 'BRUSH_DATA'
method_icon = settings.bl_rna.properties['brushstroke_method'].enum_items[context_brushstroke.method].icon
col = layout.column()
row = col.row(align=True)
row.prop(context_brushstroke, 'name', text='', emboss=False, icon=method_icon)
bs_ob = bpy.data.objects.get(item.name)
if not bs_ob:
return
row.prop(context_brushstroke, 'hide_viewport_base', icon_only=True, emboss=False, icon='HIDE_ON' if context_brushstroke.hide_viewport_base else 'HIDE_OFF')
row.prop(bs_ob, 'hide_viewport', icon_only=True, emboss=False)
row.prop(bs_ob, 'hide_render', icon_only=True, emboss=False)
else:
layout.label(text="", translate=False, icon_value=icon)
elif self.layout_type == 'GRID':
layout.label(text="", icon_value=icon)
def draw_filter(self, context, layout):
return
class BSBST_MT_bs_context_menu(bpy.types.Menu):
bl_label = "Brushstroke Specials"
def draw(self, _context):
layout = self.layout
op = layout.operator('brushstroke_tools.copy_brushstrokes', text='Copy to Selected Objects')
op.copy_all = False
op = layout.operator('brushstroke_tools.copy_brushstrokes', text='Copy All to Selected Objects')
op.copy_all = True
op = layout.operator('brushstroke_tools.switch_deformable')
op.switch_all = False
op = layout.operator('brushstroke_tools.copy_flow')
op = layout.operator("brushstroke_tools.assign_surface")
class BSBST_PT_brushstroke_tools_panel(bpy.types.Panel):
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_label = "Brushstroke Tools"
bl_category = "Brushstroke Tools"
def draw_header_preset(self,context):
layout = self.layout
row = layout.row(align=True)
op = row.operator('brushstroke_tools.view_all', icon='RESTRICT_VIEW_OFF', text='')
op.disable = False
op = row.operator('brushstroke_tools.view_all', icon='RESTRICT_VIEW_ON', text='')
op.disable = True
def draw(self, context):
layout = self.layout
settings = context.scene.BSBST_settings
surface_object = utils.get_active_context_surface_object(context)
surface_row = layout.row()
if surface_object:
surface_row.label(text=f'{surface_object.name}', icon='OUTLINER_OB_SURFACE')
else:
surface_row.alert = True
surface_row.label(text='No Valid Surface Object', icon='OUTLINER_OB_SURFACE')
row = layout.row(align=True)
op = row.operator("brushstroke_tools.new_brushstrokes", text='Fill', icon='OUTLINER_OB_FORCE_FIELD')
op.method = 'SURFACE_FILL'
op = row.operator("brushstroke_tools.new_brushstrokes", text='Draw', icon='LINE_DATA')
op.method = 'SURFACE_DRAW'
draw_advanced_settings(layout, settings)
# identify style context
style_object = context.object if settings.style_context=='BRUSHSTROKES' else settings.preset_object
if settings.style_context=='PRESET':
style_object = settings.preset_object
else:
if utils.is_brushstrokes_object(context.object):
style_object = context.object
else:
if settings.context_brushstrokes:
bs_name = settings.context_brushstrokes[settings.active_context_brushstrokes_index].name
context_bs = bpy.data.objects.get(bs_name)
if context_bs:
style_object = context_bs
is_preset = style_object == settings.preset_object
display_mode = settings.ui_options
if is_preset:
display_mode = -1
style_header, style_panel = layout.panel("brushstrokes_style", default_closed=False)
if is_preset:
style_header.label(text="Default Settings", icon='SETTINGS')
else:
style_header.label(text="Brushstroke Settings", icon='BRUSH_DATA')
#style_header.operator('brushstroke_tools.make_preset', text='', icon='DECORATE_OVERRIDE')
style_header.row().prop(settings, 'ui_options', icon='OPTIONS', icon_only=True)
if style_panel:
if settings.style_context=='BRUSHSTROKES' and not utils.is_brushstrokes_object(style_object):
style_panel.label(text='No Brushstroke Context Found')
return
if not is_preset and len(settings.context_brushstrokes)>0:
row = style_panel.row()
row.template_list("BSBST_UL_brushstroke_objects", "", settings, "context_brushstrokes",
settings, "active_context_brushstrokes_index", rows=3, maxrows=5, sort_lock=True)
column = row.column(align=True)
column.operator('brushstroke_tools.duplicate_brushstrokes', text='', icon='DUPLICATE')
column.operator('brushstroke_tools.delete_brushstrokes', text='', icon='TRASH')
column.menu('BSBST_MT_bs_context_menu', text='', icon = 'DOWNARROW_HLT')
row = style_panel.row()
row_edit = row.row(align=True)
row_edit.operator('brushstroke_tools.select_surface', icon='OUTLINER_OB_SURFACE', text='')
bs_ob = utils.get_active_context_brushstrokes_object(context)
text = 'Edit Flow' if getattr(bs_ob, '["BSBST_method"]', None)=='SURFACE_FILL' else 'Edit Brushstrokes'
row_edit.operator('brushstroke_tools.edit_brushstrokes', icon='GREASEPENCIL', text = text)
row_edit.prop(settings, 'edit_toggle', icon='RESTRICT_SELECT_OFF' if settings.edit_toggle else 'RESTRICT_SELECT_ON', icon_only=True)
if not settings.preset_object and is_preset:
layout.operator("brushstroke_tools.init_preset", icon='MODIFIER')
else:
draw_properties_panel(style_panel, settings, style_object, surface_object, is_preset, display_mode)
class BSBST_MT_PIE_brushstroke_data_marking(bpy.types.Menu):
bl_idname= "BSBST_MT_PIE_brushstroke_data_marking"
bl_label = "Mark Brushstroke Flow"
items = {
"Brush Flow - Mark": ['FORCE_WIND'],
"Brush Flow - Clear": ['NONE'],
"Brush Break - Mark": ['MOD_PHYSICS'],
"Brush Break - Clear": ['NONE'],
"Brush Ignore - Mark": ['X'],
"Brush Ignore - Clear": ['NONE'],
}
def draw(self, context):
layout = self.layout
pie = layout.menu_pie()
for name, info in self.items.items():
pie.alert=True
op = pie.operator("geometry.execute_node_group", text=name, icon=info[0])
op.asset_library_type='CUSTOM'
op.asset_library_identifier=utils.asset_lib_name
op.relative_asset_identifier=f"core/brushstroke_tools-resources.blend/NodeTree/{name}"
class BSBST_OT_brushstroke_data_marking(bpy.types.Operator):
"""
Call pie menu for operators to mark brushstroke data on the surface mesh
"""
bl_idname = "brushstroke_tools.data_marking"
bl_label = "Mark Brushstroke Data"
bl_description = " Call pie menu for operators to mark brushstroke data on the surface mesh"
@classmethod
def poll(cls, context):
return context.mode == 'EDIT_MESH'
def execute(self, context):
bpy.ops.wm.call_menu_pie('INVOKE_DEFAULT', name=BSBST_MT_PIE_brushstroke_data_marking.bl_idname)
return {'FINISHED'}
classes = [
BSBST_UL_brushstroke_objects,
BSBST_MT_bs_context_menu,
BSBST_PT_brushstroke_tools_panel,
BSBST_MT_PIE_brushstroke_data_marking,
BSBST_OT_brushstroke_data_marking,
]
def register():
for c in classes:
bpy.utils.register_class(c)
# Register UI shortcuts
wm = bpy.context.window_manager
if wm.keyconfigs.addon is not None:
km = wm.keyconfigs.addon.keymaps.new(name="Mesh")
kmi = km.keymap_items.new("brushstroke_tools.data_marking","F", "PRESS",shift=False, ctrl=True, alt=True)
def unregister():
for c in reversed(classes):
bpy.utils.unregister_class(c)
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,39 @@
# Changelog
## [Unreleased]
## [0.5.0] - 2025-02-10
- Update code to work properly with the new slotted/layered Action APIs in Blender 4.4. Otherwise functionally identical to v0.4.0.
## [0.4.0] - 2025-02-10
- Added button to prep blend files for submission to render farms. A common issue that people ran into when working with Camera Shakify is that they would have to bake their camera animation for submission to a Render Farm, since Camera Shakify shakes don't function without the addon installed. This button addresses this by instead creating a small auto-execute Python script in the blend file that registers the minimal types and properties needed for the shakes to function.
## [0.3.0] - 2024-10-14
### Additions
- Turned into a [Blender Extension](https://extensions.blender.org/add-ons/camera-shakify/). No functional changes.
## [0.2.0]
To be filled out.
## [0.1.0]
To be filled out.
[Unreleased]: https://github.com/cessen/colorbox/compare/v0.5.0...HEAD
[0.5.0]: https://github.com/cessen/colorbox/compare/v0.4.0...v0.5.0
[0.4.0]: https://github.com/cessen/colorbox/compare/v0.3.0...v0.4.0
[0.3.0]: https://github.com/cessen/colorbox/compare/v0.2.0...v0.3.0
[0.2.0]: https://github.com/cessen/colorbox/compare/v0.1.0...v0.2.0
[0.1.0]: https://github.com/cessen/colorbox/releases/tag/v0.1.0
@@ -0,0 +1,693 @@
Copyright (c) 2021 Ian Hubert, Nathan Vegdahl
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
----
### GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
<https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
### Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom
to share and change all versions of a program--to make sure it remains
free software for all its users. We, the Free Software Foundation, use
the GNU General Public License for most of our software; it applies
also to any other work released this way by its authors. You can apply
it to your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you
have certain responsibilities if you distribute copies of the
software, or if you modify it: responsibilities to respect the freedom
of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the
manufacturer can do so. This is fundamentally incompatible with the
aim of protecting users' freedom to change the software. The
systematic pattern of such abuse occurs in the area of products for
individuals to use, which is precisely where it is most unacceptable.
Therefore, we have designed this version of the GPL to prohibit the
practice for those products. If such problems arise substantially in
other domains, we stand ready to extend this provision to those
domains in future versions of the GPL, as needed to protect the
freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish
to avoid the special danger that patents applied to a free program
could make it effectively proprietary. To prevent this, the GPL
assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
### TERMS AND CONDITIONS
#### 0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds
of works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of
an exact copy. The resulting work is called a "modified version" of
the earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user
through a computer network, with no transfer of a copy, is not
conveying.
An interactive user interface displays "Appropriate Legal Notices" to
the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
#### 1. Source Code.
The "source code" for a work means the preferred form of the work for
making modifications to it. "Object code" means any non-source form of
a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users can
regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same
work.
#### 2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey,
without conditions so long as your license otherwise remains in force.
You may convey covered works to others for the sole purpose of having
them make modifications exclusively for you, or provide you with
facilities for running those works, provided that you comply with the
terms of this License in conveying all material for which you do not
control copyright. Those thus making or running the covered works for
you must do so exclusively on your behalf, under your direction and
control, on terms that prohibit them from making any copies of your
copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the
conditions stated below. Sublicensing is not allowed; section 10 makes
it unnecessary.
#### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such
circumvention is effected by exercising rights under this License with
respect to the covered work, and you disclaim any intention to limit
operation or modification of the work as a means of enforcing, against
the work's users, your or third parties' legal rights to forbid
circumvention of technological measures.
#### 4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
#### 5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these
conditions:
- a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
- b) The work must carry prominent notices stating that it is
released under this License and any conditions added under
section 7. This requirement modifies the requirement in section 4
to "keep intact all notices".
- c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
- d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
#### 6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of
sections 4 and 5, provided that you also convey the machine-readable
Corresponding Source under the terms of this License, in one of these
ways:
- a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
- b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the Corresponding
Source from a network server at no charge.
- c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
- d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
- e) Convey the object code using peer-to-peer transmission,
provided you inform other peers where the object code and
Corresponding Source of the work are being offered to the general
public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal,
family, or household purposes, or (2) anything designed or sold for
incorporation into a dwelling. In determining whether a product is a
consumer product, doubtful cases shall be resolved in favor of
coverage. For a particular product received by a particular user,
"normally used" refers to a typical or common use of that class of
product, regardless of the status of the particular user or of the way
in which the particular user actually uses, or expects or is expected
to use, the product. A product is a consumer product regardless of
whether the product has substantial commercial, industrial or
non-consumer uses, unless such uses represent the only significant
mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to
install and execute modified versions of a covered work in that User
Product from a modified version of its Corresponding Source. The
information must suffice to ensure that the continued functioning of
the modified object code is in no case prevented or interfered with
solely because modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or
updates for a work that has been modified or installed by the
recipient, or for the User Product in which it has been modified or
installed. Access to a network may be denied when the modification
itself materially and adversely affects the operation of the network
or violates the rules and protocols for communication across the
network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
#### 7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders
of that material) supplement the terms of this License with terms:
- a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
- b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
- c) Prohibiting misrepresentation of the origin of that material,
or requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
- d) Limiting the use for publicity purposes of names of licensors
or authors of the material; or
- e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
- f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions
of it) with contractual assumptions of liability to the recipient,
for any liability that these contractual assumptions directly
impose on those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions; the
above requirements apply either way.
#### 8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your license
from a particular copyright holder is reinstated (a) provisionally,
unless and until the copyright holder explicitly and finally
terminates your license, and (b) permanently, if the copyright holder
fails to notify you of the violation by some reasonable means prior to
60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
#### 9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run
a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
#### 10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
#### 11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims owned
or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within the
scope of its coverage, prohibits the exercise of, or is conditioned on
the non-exercise of one or more of the rights that are specifically
granted under this License. You may not convey a covered work if you
are a party to an arrangement with a third party that is in the
business of distributing software, under which you make payment to the
third party based on the extent of your activity of conveying the
work, and under which the third party grants, to any of the parties
who would receive the covered work from you, a discriminatory patent
license (a) in connection with copies of the covered work conveyed by
you (or copies made from those copies), or (b) primarily for and in
connection with specific products or compilations that contain the
covered work, unless you entered into that arrangement, or that patent
license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
#### 12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under
this License and any other pertinent obligations, then as a
consequence you may not convey it at all. For example, if you agree to
terms that obligate you to collect a royalty for further conveying
from those to whom you convey the Program, the only way you could
satisfy both those terms and this License would be to refrain entirely
from conveying the Program.
#### 13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
#### 14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions
of the GNU General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in
detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies that a certain numbered version of the GNU General Public
License "or any later version" applies to it, you have the option of
following the terms and conditions either of that numbered version or
of any later version published by the Free Software Foundation. If the
Program does not specify a version number of the GNU General Public
License, you may choose any version ever published by the Free
Software Foundation.
If the Program specifies that a proxy can decide which future versions
of the GNU General Public License can be used, that proxy's public
statement of acceptance of a version permanently authorizes you to
choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
#### 15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND
PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
CORRECTION.
#### 16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR
CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT
NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR
LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM
TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER
PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
#### 17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
### How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these
terms.
To do so, attach the following notices to the program. It is safest to
attach them to the start of each source file to most effectively state
the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper
mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands \`show w' and \`show c' should show the
appropriate parts of the General Public License. Of course, your
program's commands might be different; for a GUI interface, you would
use an "about box".
You should also get your employer (if you work as a programmer) or
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. For more information on this, and how to apply and follow
the GNU GPL, see <https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your
program into proprietary programs. If your program is a subroutine
library, you may consider it more useful to permit linking proprietary
applications with the library. If this is what you want to do, use the
GNU Lesser General Public License instead of this License. But first,
please read <https://www.gnu.org/licenses/why-not-lgpl.html>.
@@ -0,0 +1,46 @@
The camera shake data in `shake_data.py` is dedicated to public domain as fully as possible via [CC0](https://creativecommons.org/publicdomain/zero/1.0/).
----
# Creative Commons CC0 1.0 Universal
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER.
## Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others.
For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights.
1. __Copyright and Related Rights.__ A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following:
i. the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or likeness depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data in a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and
vii. other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof.
2. __Waiver.__ To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose.
3. __Public License Fallback.__ Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose.
4. __Limitations and Disclaimers.__
a. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work.
d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work.
@@ -0,0 +1,20 @@
# Camera Shakify
An addon for Blender that lets you easily add [realistic camera shake](https://youtu.be/4lCm_jqoBrI) to your cameras.
Versions 0.3.x and 0.4.x of this addon require Blender 4.2 or 4.3.
Versions 0.5.0 or later require Blender 4.4 or later.
# License
The code in this addon is licensed under the GNU General Public License, version 3. Please see LICENSE_CODE.md for details.
The camera shake data is [CC0](https://creativecommons.org/publicdomain/zero/1.0/). Please see LICENSE_DATA.md for details.
# Contributing
Although we are not specifically looking for contributions right now, if you would like to contribute please keep in mind the following things:
- By submitting any work for inclusion in this addon, you agree to license it under the same terms as above, and you assert that you have the rights to do so.
- Larger changes to the addon are likely to be rejected unless by pure coincidence they happen to align with our goals for the project. So if you are considering a larger change, please either file an issue or otherwise contact us to discuss your idea before starting work on it, so that you don't inadvertantly waste your time.
@@ -0,0 +1,658 @@
#====================== BEGIN GPL LICENSE BLOCK ======================
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
#======================= END GPL LICENSE BLOCK ========================
bl_info = {
"name": "Camera Shakify",
"version": (0, 5, 0),
"author": "Nathan Vegdahl, Ian Hubert",
"blender": (4, 4, 0),
"description": "Add captured camera shake/wobble to your cameras",
"location": "Camera properties",
# "doc_url": "",
"category": "Animation",
}
import re
import math
import bpy
from bpy.types import Camera, Context
from .action_utils import action_to_python_data_text, ensure_shake_in_action, action_slot_frame_range, ensure_action
from .shake_data import SHAKE_LIST
from .farm_script import ensure_farm_script
# Note: the ".v#" number at the end is *not* the addon version. This number is
# incremented when the way shakes are constructed changes to prevent
# compatibility problems, and generally spans multiple addon versions.
BASE_NAME = "CameraShakify.v3"
ACTION_NAME = BASE_NAME + " Shakes"
COLLECTION_NAME = BASE_NAME
# Note: the addon used to be called "Camera Wobble" before it was publicly
# released, and had a "v1" and "v2" base name under that name. We don't include
# those here because those versions of the addon were only ever used internally
# by Ian, and there should be no files that exist anymore that use those base
# names. But that's why there's also no "CameraShakify.v1", because that never
# existed.
BASE_NAMES_OLD = ["CameraShakify.v2"]
# Maximum values of our per-camera scaling/influence properties.
INFLUENCE_MAX = 4.0
SCALE_MAX = 100.0
# The maximum supported world unit scale.
UNIT_SCALE_MAX = 1000.0
#========================================================
class CameraShakifyPanel(bpy.types.Panel):
"""Add shake to your Cameras."""
bl_label = "Camera Shakify"
bl_idname = "DATA_PT_camera_shakify"
bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'
bl_context = "data"
@classmethod
def poll(cls, context):
return context.active_object.type == 'CAMERA'
def draw(self, context):
wm = context.window_manager
layout = self.layout
camera = context.active_object
row = layout.row()
row.template_list(
listtype_name="OBJECT_UL_camera_shake_items",
list_id="Camera Shakes",
dataptr=camera,
propname="camera_shakes",
active_dataptr=camera,
active_propname="camera_shakes_active_index",
)
col = row.column()
col.operator("object.camera_shake_add", text="", icon='ADD')
col.operator("object.camera_shake_remove", text="", icon='REMOVE')
col.operator("object.camera_shake_move", text="", icon='TRIA_UP').type = 'UP'
col.operator("object.camera_shake_move", text="", icon='TRIA_DOWN').type = 'DOWN'
if camera.camera_shakes_active_index < len(camera.camera_shakes):
shake = camera.camera_shakes[camera.camera_shakes_active_index]
row = layout.row()
col = row.column(align=True)
col.alignment = 'RIGHT'
col.use_property_split = True
col.prop(shake, "shake_type", text="Shake")
col.separator()
col.prop(shake, "influence", slider=True)
col.separator()
col.prop(shake, "scale")
col.separator()
col.prop(shake, "use_manual_timing")
if shake.use_manual_timing:
col.prop(shake, "time")
else:
col.prop(shake, "speed")
col.prop(shake, "offset")
col.separator(factor=2.0)
row = layout.row()
row.alignment = 'LEFT'
header_text = "Misc Utilities"
if wm.camera_shake_show_utils:
row.prop(wm, "camera_shake_show_utils", icon="DISCLOSURE_TRI_DOWN", text=header_text, expand=False, emboss=False)
else:
row.prop(wm, "camera_shake_show_utils", icon="DISCLOSURE_TRI_RIGHT", text=header_text, emboss=False)
row.separator_spacer()
col = layout.column()
if wm.camera_shake_show_utils:
col.operator("object.camera_shakes_fix_global")
col.operator("wm.camera_shakify_prep_file_for_farm")
class OBJECT_UL_camera_shake_items(bpy.types.UIList):
def draw_item(self, context, layout, data, item, icon, active_data, active_propname):
ob = data
# draw_item must handle the three layout types... Usually 'DEFAULT' and 'COMPACT' can share the same code.
if self.layout_type in {'DEFAULT', 'COMPACT'}:
col = layout.column()
col.label(
text=str(item.shake_type).replace("_", " ").title(),
icon='FCURVE_SNAPSHOT',
)
col = layout.column()
col.alignment = 'RIGHT'
col.prop(item, "influence", text="", expand=False, slider=True, emboss=False)
# 'GRID' layout type should be as compact as possible (typically a single icon!).
elif self.layout_type in {'GRID'}:
layout.alignment = 'CENTER'
layout.label(text="", icon_value=icon)
#========================================================
# Creates a camera shake setup for the given camera and
# shake item index, using the given collection to store
# shake empties.
def build_single_shake(camera, shake_item_index, collection, context):
shake = camera.camera_shakes[shake_item_index]
shake_data = SHAKE_LIST[shake.shake_type]
shake_name = shake.shake_type.lower()
shake_object_name = BASE_NAME + "_" + camera.name + "_" + str(shake_item_index)
# Ensure the needed action and shake slot exist.
action = ensure_action(ACTION_NAME)
slot = ensure_shake_in_action(
shake_name,
action,
shake_data[2],
INFLUENCE_MAX,
INFLUENCE_MAX * SCALE_MAX * UNIT_SCALE_MAX
)
# Ensure the needed shake object exists.
shake_object = None
if shake_object_name in bpy.data.objects:
shake_object = bpy.data.objects[shake_object_name]
else:
shake_object = bpy.data.objects.new(shake_object_name, None)
# Make sure the shake object is linked into our collection.
if shake_object.name not in collection.objects:
collection.objects.link(shake_object)
#----------------
# Set up the constraints and drivers on the shake object.
#----------------
# Clear out all constraints and drivers, and fetch animation data block.
shake_object.constraints.clear()
shake_object.animation_data_clear()
anim_data = shake_object.animation_data_create()
# Some weird gymnastics needed because of a Blender bug.
# Without first assigning an action to the animation data,
# then on a fresh scene we won't be able to assign an action
# to the action constraint (below).
anim_data.action = action
anim_data.action = None
shake_object.location = (0,0,0)
shake_object.rotation_euler = (0,0,0)
shake_object.rotation_quaternion = (0,0,0,0)
shake_object.rotation_axis_angle = (0,0,0,0)
shake_object.scale = (1,1,1)
# Get action info for calculations below.
shake_fps = shake_data[1]
shake_range = action_slot_frame_range(action, slot)
shake_length = shake_range[1] - shake_range[0]
# Create the action constraint.
constraint = shake_object.constraints.new('ACTION')
constraint.use_eval_time = True
constraint.mix_mode = 'BEFORE'
constraint.action = action
constraint.action_slot = slot
constraint.frame_start = shake_range[0]
constraint.frame_end = shake_range[1]
# Create the driver for the constraint's eval time.
driver = constraint.driver_add("eval_time").driver
driver.type = 'SCRIPTED'
fps_factor = 1.0 / ((context.scene.render.fps / context.scene.render.fps_base) / shake_fps)
driver.expression = \
"((time if manual else ((-frame_offset + frame) * speed)) * {}) % 1.0" \
.format(fps_factor / shake_length)
manual_timing_var = driver.variables.new()
manual_timing_var.name = "manual"
manual_timing_var.type = 'SINGLE_PROP'
manual_timing_var.targets[0].id_type = 'OBJECT'
manual_timing_var.targets[0].id = camera
manual_timing_var.targets[0].data_path = 'camera_shakes[{}].use_manual_timing'.format(shake_item_index)
time_var = driver.variables.new()
time_var.name = "time"
time_var.type = 'SINGLE_PROP'
time_var.targets[0].id_type = 'OBJECT'
time_var.targets[0].id = camera
time_var.targets[0].data_path = 'camera_shakes[{}].time'.format(shake_item_index)
speed_var = driver.variables.new()
speed_var.name = "speed"
speed_var.type = 'SINGLE_PROP'
speed_var.targets[0].id_type = 'OBJECT'
speed_var.targets[0].id = camera
speed_var.targets[0].data_path = 'camera_shakes[{}].speed'.format(shake_item_index)
offset_var = driver.variables.new()
offset_var.name = "frame_offset"
offset_var.type = 'SINGLE_PROP'
offset_var.targets[0].id_type = 'OBJECT'
offset_var.targets[0].id = camera
offset_var.targets[0].data_path = 'camera_shakes[{}].offset'.format(shake_item_index)
#----------------
# Set up the constraints and drivers on the camera object.
#----------------
loc_constraint_name = BASE_NAME + "_loc_" + str(shake_item_index)
rot_constraint_name = BASE_NAME + "_rot_" + str(shake_item_index)
# Create the new constraints.
loc_constraint = camera.constraints.new(type='COPY_LOCATION')
rot_constraint = camera.constraints.new(type='COPY_ROTATION')
loc_constraint.name = loc_constraint_name
rot_constraint.name = rot_constraint_name
loc_constraint.show_expanded = False
rot_constraint.show_expanded = False
# Set up location constraint.
loc_constraint.target = shake_object
loc_constraint.target_space = 'WORLD'
loc_constraint.owner_space = 'LOCAL'
loc_constraint.use_offset = True
# Set up rotation constraint.
rot_constraint.target = shake_object
rot_constraint.target_space = 'WORLD'
rot_constraint.owner_space = 'LOCAL'
rot_constraint.mix_mode = 'AFTER'
# Set up the location constraint driver.
driver = loc_constraint.driver_add("influence").driver
driver.type = 'SCRIPTED'
driver.expression = "{} * influence * location_scale / unit_scale".format(1.0 / (UNIT_SCALE_MAX * INFLUENCE_MAX * SCALE_MAX))
if "influence" not in driver.variables:
var = driver.variables.new()
var.name = "influence"
var.type = 'SINGLE_PROP'
var.targets[0].id_type = 'OBJECT'
var.targets[0].id = camera
var.targets[0].data_path = 'camera_shakes[{}].influence'.format(shake_item_index)
if "location_scale" not in driver.variables:
var = driver.variables.new()
var.name = "location_scale"
var.type = 'SINGLE_PROP'
var.targets[0].id_type = 'OBJECT'
var.targets[0].id = camera
var.targets[0].data_path = 'camera_shakes[{}].scale'.format(shake_item_index)
if "unit_scale" not in driver.variables:
var = driver.variables.new()
var.name = "unit_scale"
var.type = 'SINGLE_PROP'
var.targets[0].id_type = 'SCENE'
var.targets[0].id = context.scene
var.targets[0].data_path ='unit_settings.scale_length'
# Set up the rotation constraint driver.
driver = rot_constraint.driver_add("influence").driver
driver.type = 'SCRIPTED'
driver.expression = "influence * {}".format(1.0 / INFLUENCE_MAX)
if "influence" not in driver.variables:
var = driver.variables.new()
var.name = "influence"
var.type = 'SINGLE_PROP'
var.targets[0].id_type = 'OBJECT'
var.targets[0].id = camera
var.targets[0].data_path = 'camera_shakes[{}].influence'.format(shake_item_index)
# Only for use in rebuilding camera shakes, to ensure that constraints, etc.
# from previous Camera Shakify versions get removed.
def starts_with_any_base_name(text):
base_names = BASE_NAMES_OLD + [BASE_NAME]
for base_name in base_names:
if text.startswith(base_name):
return True
return False
# Ensure that our camera shakify collection exists and fetch it.
def ensure_camera_shakify_collection(context):
if COLLECTION_NAME in context.scene.collection.children and context.scene.collection.children[COLLECTION_NAME].library == None:
return context.scene.collection.children[COLLECTION_NAME]
# Get the collection.
#
# The song-and-dance here is to make sure we get a *local* collection,
# not a library-linked collection.
collection = None
for col in bpy.data.collections:
if col.name == COLLECTION_NAME and col.library == None:
collection = col
break
if collection == None:
collection = bpy.data.collections.new(COLLECTION_NAME)
collection.hide_viewport = True
collection.hide_render = True
collection.hide_select = True
# Link the collection and get it appropriately set up.
context.scene.collection.children.link(collection)
for layer in context.scene.view_layers:
if collection.name in layer.layer_collection.children:
layer.layer_collection.children[collection.name].exclude = True
return collection
# The main function that actually does the real work of this addon.
# It's called whenever anything relevant in the shake list on a
# camera is changed, and just tears down and completely rebuilds
# the camera-shake setup for it.
def rebuild_camera_shakes(camera, context):
if camera.library != None:
# Skip library-linked cameras.
return
collection = ensure_camera_shakify_collection(context)
#----------------
# First, completely tear down the current setup, if any.
#----------------
# Remove shake constraints from the camera.
remove_list = []
for constraint in camera.constraints:
if starts_with_any_base_name(constraint.name):
constraint.driver_remove("influence")
remove_list += [constraint]
for constraint in remove_list:
camera.constraints.remove(constraint)
# Remove shake empties for this camera.
name_match = re.compile("{}_[0-9]+".format(re.escape(BASE_NAME + "_" + camera.name)))
for obj in collection.objects:
if name_match.fullmatch(obj.name) != None:
obj.constraints[0].driver_remove("eval_time")
obj.animation_data_clear()
bpy.data.objects.remove(obj)
#----------------
# Then build the new setup.
#----------------
for shake_item_index in range(0, len(camera.camera_shakes)):
build_single_shake(camera, shake_item_index, collection, context)
#----------------
# Finally, clean up any data that's no longer needed, up to and
# including removing the collection itself if there no shakes left.
#----------------
# If there's nothing left in the collection, delete it.
if len(collection.objects) == 0:
context.scene.collection.children.unlink(collection)
if collection.users == 0:
bpy.data.collections.remove(collection)
# Fixes camera shake setups across the whole scene.
# This can be necessary if e.g. a user has duplicated cameras
# around, etc.
def fix_camera_shakes_globally(context):
# Delete the collection and everything in it.
collection = ensure_camera_shakify_collection(context)
for obj in collection.objects:
obj.constraints[0].driver_remove("eval_time")
obj.animation_data_clear()
bpy.data.objects.remove(obj)
context.scene.collection.children.unlink(collection)
if collection.users == 0:
bpy.data.collections.remove(collection)
# Remove shake channelbags in the shake action, to force them to get
# re-built.
action = ensure_action(ACTION_NAME)
for channelbag in action.layers[0].strips[0].channelbags:
action.layers[0].strips[0].channelbags.remove(channelbag)
# Loop through all cameras and re-build their camera shakes.
for obj in context.scene.objects:
if obj.type == 'CAMERA':
rebuild_camera_shakes(obj, context)
def on_shake_type_update(shake_instance, context):
rebuild_camera_shakes(shake_instance.id_data, context)
#class ActionToPythonData(bpy.types.Operator):
# """Writes the action on the currently selected object to a text block as Python data"""
# bl_idname = "object.action_to_python_data"
# bl_label = "Action to Python Data"
# bl_options = {'UNDO'}
#
# @classmethod
# def poll(cls, context):
# return context.active_object is not None \
# and context.active_object.animation_data is not None \
# and context.active_object.animation_data.action is not None
#
# def execute(self, context):
# action_to_python_data_text(context.active_object.animation_data.action, "action_output.txt")
# return {'FINISHED'}
class CameraShakeAdd(bpy.types.Operator):
"""Adds the selected camera shake to the list"""
bl_idname = "object.camera_shake_add"
bl_label = "Add Shake Item"
bl_options = {'UNDO'}
@classmethod
def poll(cls, context):
return context.active_object is not None and context.active_object.type == 'CAMERA'
def execute(self, context):
camera = context.active_object
shake = camera.camera_shakes.add()
camera.camera_shakes_active_index = len(camera.camera_shakes) - 1
rebuild_camera_shakes(camera, context)
return {'FINISHED'}
class CameraShakeRemove(bpy.types.Operator):
"""Removes the selected camera shake item from the list"""
bl_idname = "object.camera_shake_remove"
bl_label = "Remove Shake Item"
bl_options = {'UNDO'}
@classmethod
def poll(cls, context):
obj = context.active_object
return obj is not None and obj.type == 'CAMERA' and len(obj.camera_shakes) > 0
def execute(self, context):
camera = context.active_object
if camera.camera_shakes_active_index < len(camera.camera_shakes):
camera.camera_shakes.remove(camera.camera_shakes_active_index)
rebuild_camera_shakes(camera, context)
if camera.camera_shakes_active_index >= len(camera.camera_shakes) and camera.camera_shakes_active_index > 0:
camera.camera_shakes_active_index -= 1
return {'FINISHED'}
class CameraShakeMove(bpy.types.Operator):
"""Moves the selected camera shake up/down in the list"""
bl_idname = "object.camera_shake_move"
bl_label = "Move Shake Item"
bl_options = {'UNDO'}
type: bpy.props.EnumProperty(items = [
('UP', "", ""),
('DOWN', "", ""),
])
@classmethod
def poll(cls, context):
obj = context.active_object
return obj is not None and obj.type == 'CAMERA' and len(obj.camera_shakes) > 1
def execute(self, context):
camera = context.active_object
index = int(camera.camera_shakes_active_index)
if self.type == 'UP' and index > 0:
camera.camera_shakes.move(index, index - 1)
camera.camera_shakes_active_index -= 1
elif self.type == 'DOWN' and (index + 1) < len(camera.camera_shakes):
camera.camera_shakes.move(index, index + 1)
camera.camera_shakes_active_index += 1
rebuild_camera_shakes(camera, context)
return {'FINISHED'}
class CameraShakesFixGlobal(bpy.types.Operator):
"""Ensures that all camera shakes in the scene are set up properly. This generally shouldn't be necessary, but if things are behaving strangely this should fix it"""
bl_idname = "object.camera_shakes_fix_global"
bl_label = "Fix All Camera Shakes"
bl_options = {'UNDO'}
@classmethod
def poll(cls, context):
return context.mode == 'OBJECT'
def execute(self, context):
fix_camera_shakes_globally(context)
return {'FINISHED'}
class CameraShakifyPrepFileForFarm(bpy.types.Operator):
"""Adds an auto-execute script to the blend file that makes Camera Shakes work even when the addon is not present. Particularly useful for sending files to a render farm. This only needs to be run once per file, not every time you submit a file to a farm"""
bl_idname = "wm.camera_shakify_prep_file_for_farm"
bl_label = "Prep Blend File For Render Farm"
bl_options = {'UNDO'}
@classmethod
def poll(cls, context):
return True
def execute(self, context):
ensure_farm_script(INFLUENCE_MAX, SCALE_MAX)
return {'FINISHED'}
# An actual instance of Camera shake added to a camera.
#
# IMPORTANT: when making changes here, make sure to also update the
# corresponding script text in farm_script.py.
class CameraShakeInstance(bpy.types.PropertyGroup):
shake_type: bpy.props.EnumProperty(
name = "Shake Type",
items = [(id, SHAKE_LIST[id][0], "") for id in SHAKE_LIST.keys()],
options = set(), # Not animatable.
override = set(), # Not library overridable.
update = on_shake_type_update,
)
influence: bpy.props.FloatProperty(
name="Influence",
description="How much the camera shake affects the camera",
default=1.0,
min=0.0, max=INFLUENCE_MAX,
soft_min=0.0, soft_max=1.0,
)
scale: bpy.props.FloatProperty(
name="Scale",
description="The scale of the shake's location component",
default=1.0,
min=0.0, max=SCALE_MAX,
soft_min=0.0, soft_max=2.0,
)
use_manual_timing: bpy.props.BoolProperty(
name="Manual Timing",
description="Manually animate the progression of time through the camera shake animation",
default=False,
)
time: bpy.props.FloatProperty(
name="Time",
description="Current time (in frame number) of the shake animation",
default=0.0,
precision=1,
step=100.0,
)
speed: bpy.props.FloatProperty(
name="Speed",
description="Multiplier for how fast the shake animation plays",
default=1.0,
soft_min=0.0, soft_max=4.0,
options = set(), # Not animatable.
)
offset: bpy.props.FloatProperty(
name="Frame Offset",
description="How many frames to offset the shake animation",
default=0.0,
precision=1,
step=100.0,
)
#========================================================
def register():
bpy.utils.register_class(CameraShakifyPanel)
bpy.utils.register_class(OBJECT_UL_camera_shake_items)
bpy.utils.register_class(CameraShakeInstance)
bpy.utils.register_class(CameraShakeAdd)
bpy.utils.register_class(CameraShakeRemove)
bpy.utils.register_class(CameraShakeMove)
bpy.utils.register_class(CameraShakesFixGlobal)
bpy.utils.register_class(CameraShakifyPrepFileForFarm)
# # Only needed for creating new shakes to add to this addon. Not for end users.
# bpy.utils.register_class(ActionToPythonData)
# bpy.types.VIEW3D_MT_object.append(
# lambda self, context : self.layout.operator(ActionToPythonData.bl_idname)
# )
# The list of camera shakes active on an camera, along with each shake's parameters.
bpy.types.Object.camera_shakes = bpy.props.CollectionProperty(type=CameraShakeInstance)
bpy.types.Object.camera_shakes_active_index = bpy.props.IntProperty(name="Camera Shake List Active Item Index")
bpy.types.WindowManager.camera_shake_show_utils = bpy.props.BoolProperty(name="Show Camera Shake Utils UI", default=False)
def unregister():
del bpy.types.Object.camera_shakes
del bpy.types.Object.camera_shakes_active_index
bpy.utils.unregister_class(CameraShakifyPanel)
bpy.utils.unregister_class(OBJECT_UL_camera_shake_items)
bpy.utils.unregister_class(CameraShakeInstance)
bpy.utils.unregister_class(CameraShakeAdd)
bpy.utils.unregister_class(CameraShakeRemove)
bpy.utils.unregister_class(CameraShakeMove)
bpy.utils.unregister_class(CameraShakesFixGlobal)
bpy.utils.unregister_class(CameraShakifyPrepFileForFarm)
#bpy.utils.unregister_class(ActionToPythonData)
if __name__ == "__main__":
register()
@@ -0,0 +1,136 @@
#====================== BEGIN GPL LICENSE BLOCK ======================
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
#======================= END GPL LICENSE BLOCK ========================
import math
import bpy
from bpy.types import Action, ActionSlot, Context
# TODO: update this function to work with slotted actions. This is only used
# when exporting actions as new shakes, and is never run for end users, so I've
# left it as-is for now. We can update it when we actually need to use it.
def action_to_python_data_text(act: Action, text_block_name):
channels = {}
act_range = action_frame_range(act)
for curve in act.fcurves:
baked_keys = []
for frame in range(int(act_range[0]), int(act_range[1]) + 1):
baked_keys += [(frame, curve.evaluate(frame))]
channels[(curve.data_path, curve.array_index)] = baked_keys
text = "{\n"
for k in channels:
text += " {}: [".format(k)
for point in channels[k]:
text += "({}, {:.6f}), ".format(point[0], point[1])
text += "],\n"
text += "}\n"
return bpy.data.texts.new(text_block_name).from_string(text)
# Ensure that an Action with the given name exists, and that it has a layer and
# a keyframe strip.
def ensure_action(action_name) -> Action:
# Ensure the action exists.
#
# The song-and-dance here is to make sure we get a *local* action, not a
# library-linked action.
action = None
for act in bpy.data.actions:
if act.name == action_name and act.library == None:
action = act
break
if action == None:
action = bpy.data.actions.new(action_name)
action.use_fake_user = False
# Ensure there's at least one layer.
if len(action.layers) > 0:
layer = action.layers[0]
else:
layer = action.layers.new("Layer")
# Ensure there's a keyframe strip.
if len(layer.strips) > 0:
assert(layer.strips[0].type == 'KEYFRAME')
else:
layer.strips.new(type='KEYFRAME')
return action
# Ensures that a shake with the given name exists as a slot in the given action.
#
# If it doesn't exist, it will be created from the passed `data`.
#
# rot_factor and loc_factor are scaling factors for rotation and location
# values, respectively.
#
# Returns the slot in the action corresponding to the shake.
def ensure_shake_in_action(shake_name, action: Action, data, rot_factor=1.0, loc_factor=1.0) -> ActionSlot:
slot_identifier = "OB" + shake_name
# Ensure a slot for the shake exists.
if slot_identifier in action.slots:
slot = action.slots[slot_identifier]
else:
slot = action.slots.new('OBJECT', shake_name)
assert(slot.identifier == slot_identifier)
# If there's already a channelbag for the slot, we assume it's filled with
# the correct shake animation.
if action.layers[0].strips[0].channelbag(slot) != None:
return slot
# Create channelbag and fill it in with the shake data.
channelbag = action.layers[0].strips[0].channelbags.new(slot)
for k in data:
curve = channelbag.fcurves.new(k[0], index=k[1])
curve.keyframe_points.add(len(data[k]))
for i in range(len(data[k])):
co = [data[k][i][0], data[k][i][1]]
if k[0].startswith("rotation"):
co[1] *= rot_factor
if k[0].startswith("location"):
co[1] *= loc_factor
curve.keyframe_points[i].co = co
curve.keyframe_points[i].handle_left_type = 'AUTO'
curve.keyframe_points[i].handle_right_type = 'AUTO'
curve.keyframe_points[-1].co[1] = curve.keyframe_points[0].co[1] # Ensure looping.
curve.modifiers.new('CYCLES')
curve.update()
return slot
def action_slot_frame_range(action: Action, slot: ActionSlot):
channelbag = action.layers[0].strips[0].channelbag(slot)
r = [9999999999, -9999999999]
for curve in channelbag.fcurves:
cr = curve.range()
r[0] = min(r[0], cr[0])
r[1] = max(r[1], cr[1])
# Ensure integer values.
r[0] = math.floor(r[0])
r[1] = math.ceil(r[1])
return r
@@ -1,37 +1,32 @@
schema_version = "1.0.0"
# Example of manifest file for a Blender extension
# Change the values according to your extension
id = "optiploy"
version = "1.5.0"
name = "optiploy"
tagline = "Append and link rigs, save space like never before"
maintainer = "hisanimations <hisprofile029@gmail.com"
# Supported types: "add-on", "theme"
id = "camera_shakify"
version = "0.5.0"
name = "Camera Shakify"
tagline = "Add captured camera shake/wobble to your cameras"
maintainer = "Nathan Vegadahl <cessen@cessen.com>"
type = "add-on"
# Optional link to documentation, support, source files, etc
# website = "https://github.com/hisprofile/OptiPloy"
website = "https://github.com/EatTheFuture/camera_shakify/"
# Optional list defined by Blender and server, see:
# https://docs.blender.org/manual/en/dev/advanced/extensions/tags.html
tags = ["Pipeline", "Animation", "Rigging", "Import-Export"]
tags = ["Animation", "Camera"]
blender_version_min = "4.2.0"
blender_version_min = "4.4.0"
# # Optional: Blender version that the extension does not support, earlier versions are supported.
# # This can be omitted and defined later on the extensions platform if an issue is found.
# blender_version_max = "5.1.0"
# blender_version_max = "5.0.0"
# License conforming to https://spdx.org/licenses/ (use "SPDX: prefix)
# https://docs.blender.org/manual/en/dev/advanced/extensions/licenses.html
license = [
"SPDX:GPL-3.0-or-later",
]
# Optional: required by some licenses.
# copyright = [
# "2002-2024 Developer Name",
# "1998 Company Name",
# ]
copyright = [
"2021-2025 Ian Hubert & Nathan Vegdahl",
]
# Optional list of supported platforms. If omitted, the extension will be available in all operating systems.
# platforms = ["windows-x64", "macos-arm64", "linux-x64"]
@@ -58,9 +53,9 @@ license = [
# # Keep this a single short sentence without a period (.) at the end.
# # For longer explanations use the documentation or detail page.
#
[permissions]
# [permissions]
# network = "Need to sync motion-capture data to server"
files = "Read and save .blend and folder entries"
# files = "Import/export FBX from/to disk"
# clipboard = "Copy and paste bone transforms"
# Optional: build settings.
@@ -0,0 +1,89 @@
# Code for managing a blend-file-local script that registers the minimal types
# and properties needed for Camera Shakify shakes to animate even without Camera
# Shakify installed. Useful mainly for submitting files to render farms.
import bpy
FARM_SCRIPT_NAME = "camera_shakify_init.py"
FARM_SCRIPT_CONTENTS = """\
import bpy
class CameraShakeInstance(bpy.types.PropertyGroup):
# Don't include the shake type in this stand-in version of the class, as it's not necessary
# for the shakes to animate (only for managing the shakes), and it would require including
# a bunch more cruft in this script.
#
# shake_type: bpy.props.EnumProperty(
# name = "Shake Type",
# items = [(id, SHAKE_LIST[id][0], "") for id in SHAKE_LIST.keys()],
# options = set(), # Not animatable.
# override = set(), # Not library overridable.
# update = on_shake_type_update,
# )
influence: bpy.props.FloatProperty(
name="Influence",
description="How much the camera shake affects the camera",
default=1.0,
min=0.0, max={influence_max},
soft_min=0.0, soft_max=1.0,
)
scale: bpy.props.FloatProperty(
name="Scale",
description="The scale of the shake's location component",
default=1.0,
min=0.0, max={scale_max},
soft_min=0.0, soft_max=2.0,
)
use_manual_timing: bpy.props.BoolProperty(
name="Manual Timing",
description="Manually animate the progression of time through the camera shake animation",
default=False,
)
time: bpy.props.FloatProperty(
name="Time",
description="Current time (in frame number) of the shake animation",
default=0.0,
precision=1,
step=100.0,
)
speed: bpy.props.FloatProperty(
name="Speed",
description="Multiplier for how fast the shake animation plays",
default=1.0,
soft_min=0.0, soft_max=4.0,
options = set(), # Not animatable.
)
offset: bpy.props.FloatProperty(
name="Frame Offset",
description="How many frames to offset the shake animation",
default=0.0,
precision=1,
step=100.0,
)
if __name__ == "__main__":
# Only register the property if it doesn't already exist. This is to guard against replacing
# the property with the stand-in class when the real one from the addon already exists.
if not hasattr(bpy.types.Object, "camera_shakes"):
bpy.utils.register_class(CameraShakeInstance)
bpy.types.Object.camera_shakes = bpy.props.CollectionProperty(type=CameraShakeInstance)
"""
def ensure_farm_script(influence_max, scale_max):
# Get existing script if it exists, or create it otherwise.
if FARM_SCRIPT_NAME in bpy.data.texts:
script = bpy.data.texts[FARM_SCRIPT_NAME]
else:
script = bpy.data.texts.new(FARM_SCRIPT_NAME)
script.clear()
script.write(FARM_SCRIPT_CONTENTS.format(influence_max = influence_max, scale_max = scale_max))
# Make sure it doesn't get garbage collected.
script.use_fake_user = True
# Mark for auto-execute on file load.
script.use_module = True
File diff suppressed because one or more lines are too long
@@ -0,0 +1,525 @@
# SPDX-FileCopyrightText: 2010-2022 Blender Foundation
#
# SPDX-License-Identifier: GPL-2.0-or-later
# if "bpy" in locals():
# import importlib
# importlib.reload(fracture_cell_setup)
import bpy
from bpy.props import (
StringProperty,
BoolProperty,
IntProperty,
FloatProperty,
FloatVectorProperty,
EnumProperty,
)
from bpy.types import Operator
def main_object(context, collection, obj, level, **kw):
import random
# pull out some args
kw_copy = kw.copy()
use_recenter = kw_copy.pop("use_recenter")
use_remove_original = kw_copy.pop("use_remove_original")
recursion = kw_copy.pop("recursion")
recursion_source_limit = kw_copy.pop("recursion_source_limit")
recursion_clamp = kw_copy.pop("recursion_clamp")
recursion_chance = kw_copy.pop("recursion_chance")
recursion_chance_select = kw_copy.pop("recursion_chance_select")
use_island_split = kw_copy.pop("use_island_split")
use_debug_bool = kw_copy.pop("use_debug_bool")
use_interior_vgroup = kw_copy.pop("use_interior_vgroup")
use_sharp_edges = kw_copy.pop("use_sharp_edges")
use_sharp_edges_apply = kw_copy.pop("use_sharp_edges_apply")
scene = context.scene
if level != 0:
kw_copy["source_limit"] = recursion_source_limit
from . import fracture_cell_setup
# not essential but selection is visual distraction.
obj.select_set(False)
if kw_copy["use_debug_redraw"]:
obj_display_type_prev = obj.display_type
obj.display_type = 'WIRE'
objects = fracture_cell_setup.cell_fracture_objects(context, collection, obj, **kw_copy)
objects = fracture_cell_setup.cell_fracture_boolean(
context, collection, obj, objects,
use_island_split=use_island_split,
use_interior_hide=(use_interior_vgroup or use_sharp_edges),
use_debug_bool=use_debug_bool,
use_debug_redraw=kw_copy["use_debug_redraw"],
level=level,
)
# must apply after boolean.
if use_recenter:
context_override = {"selected_editable_objects": objects}
with bpy.context.temp_override(**context_override):
bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY', center='MEDIAN')
# ----------
# Recursion
if level == 0:
for level_sub in range(1, recursion + 1):
objects_recurse_input = [(i, o) for i, o in enumerate(objects)]
if recursion_chance != 1.0:
from mathutils import Vector
if recursion_chance_select == 'RANDOM':
random.shuffle(objects_recurse_input)
elif recursion_chance_select in {'SIZE_MIN', 'SIZE_MAX'}:
objects_recurse_input.sort(key=lambda ob_pair: (
Vector(ob_pair[1].bound_box[0]) -
Vector(ob_pair[1].bound_box[6])
).length_squared)
if recursion_chance_select == 'SIZE_MAX':
objects_recurse_input.reverse()
elif recursion_chance_select in {'CURSOR_MIN', 'CURSOR_MAX'}:
c = scene.cursor.location.copy()
objects_recurse_input.sort(key=lambda ob_pair: (ob_pair[1].location - c).length_squared)
if recursion_chance_select == 'CURSOR_MAX':
objects_recurse_input.reverse()
objects_recurse_input[int(recursion_chance * len(objects_recurse_input)):] = []
objects_recurse_input.sort()
# reverse index values so we can remove from original list.
objects_recurse_input.reverse()
objects_recursive = []
for i, obj_cell in objects_recurse_input:
assert(objects[i] is obj_cell)
objects_recursive += main_object(context, collection, obj_cell, level_sub, **kw)
if use_remove_original:
collection.objects.unlink(obj_cell)
del objects[i]
if recursion_clamp and len(objects) + len(objects_recursive) >= recursion_clamp:
break
objects.extend(objects_recursive)
if recursion_clamp and len(objects) > recursion_clamp:
break
# --------------
# Level Options
if level == 0:
# import pdb; pdb.set_trace()
if use_interior_vgroup or use_sharp_edges:
fracture_cell_setup.cell_fracture_interior_handle(
objects,
use_interior_vgroup=use_interior_vgroup,
use_sharp_edges=use_sharp_edges,
use_sharp_edges_apply=use_sharp_edges_apply,
)
if kw_copy["use_debug_redraw"]:
obj.display_type = obj_display_type_prev
# testing only!
# obj.hide = True
return objects
def main(context, **kw):
import time
t = time.time()
objects_context = context.selected_editable_objects
kw_copy = kw.copy()
# mass
mass_mode = kw_copy.pop("mass_mode")
mass = kw_copy.pop("mass")
collection_name = kw_copy.pop("collection_name")
collection = context.collection
if collection_name:
collection_current = collection
collection = bpy.data.collections.get(collection_name)
if collection is None:
collection = bpy.data.collections.new(collection_name)
collection_current.children.link(collection)
del collection_current
objects = []
for obj in objects_context:
if obj.type == 'MESH':
objects += main_object(context, collection, obj, 0, **kw_copy)
bpy.ops.object.select_all(action='DESELECT')
for obj_cell in objects:
obj_cell.select_set(True)
# FIXME(campbell): we should be able to initialize rigid-body data.
if mass_mode == 'UNIFORM':
for obj_cell in objects:
rb = obj_cell.rigid_body
if rb is not None:
rb.mass = mass
elif mass_mode == 'VOLUME':
from mathutils import Vector
def _get_volume(obj_cell):
def _getObjectBBMinMax():
min_co = Vector((1000000.0, 1000000.0, 1000000.0))
max_co = -min_co
matrix = obj_cell.matrix_world.copy()
for i in range(0, 8):
bb_vec = matrix @ Vector(obj_cell.bound_box[i])
min_co[0] = min(bb_vec[0], min_co[0])
min_co[1] = min(bb_vec[1], min_co[1])
min_co[2] = min(bb_vec[2], min_co[2])
max_co[0] = max(bb_vec[0], max_co[0])
max_co[1] = max(bb_vec[1], max_co[1])
max_co[2] = max(bb_vec[2], max_co[2])
return (min_co, max_co)
def _getObjectVolume():
min_co, max_co = _getObjectBBMinMax()
x = max_co[0] - min_co[0]
y = max_co[1] - min_co[1]
z = max_co[2] - min_co[2]
volume = x * y * z
return volume
return _getObjectVolume()
obj_volume_ls = [_get_volume(obj_cell) for obj_cell in objects]
obj_volume_tot = sum(obj_volume_ls)
if obj_volume_tot > 0.0:
mass_fac = mass / obj_volume_tot
for i, obj_cell in enumerate(objects):
rb = obj_cell.rigid_body
if rb is not None:
rb.mass = obj_volume_ls[i] * mass_fac
else:
assert(0)
print("Done! %d objects in %.4f sec" % (len(objects), time.time() - t))
class FractureCell(Operator):
bl_idname = "object.add_fracture_cell_objects"
bl_label = "Cell fracture selected mesh objects"
bl_options = {'PRESET', 'UNDO'}
# -------------------------------------------------------------------------
# Source Options
source: EnumProperty(
name="Source",
items=(
('VERT_OWN', "Own Verts", "Use own vertices"),
('VERT_CHILD', "Child Verts", "Use child object vertices"),
('PARTICLE_OWN', "Own Particles", (
"All particle systems of the "
"source object"
)),
('PARTICLE_CHILD', "Child Particles", (
"All particle systems of the "
"child objects"
)),
('PENCIL', "Annotation Pencil", "Annotation Grease Pencil."),
),
options={'ENUM_FLAG'},
default={'PARTICLE_OWN'},
)
source_limit: IntProperty(
name="Source Limit",
description="Limit the number of input points, 0 for unlimited",
min=0, max=5000,
default=100,
)
source_noise: FloatProperty(
name="Noise",
description="Randomize point distribution",
min=0.0, max=1.0,
default=0.0,
)
cell_scale: FloatVectorProperty(
name="Scale",
description="Scale Cell Shape",
size=3,
min=0.0, max=1.0,
default=(1.0, 1.0, 1.0),
)
# -------------------------------------------------------------------------
# Recursion
recursion: IntProperty(
name="Recursion",
description="Break shards recursively",
min=0, max=5000,
default=0,
)
recursion_source_limit: IntProperty(
name="Source Limit",
description="Limit the number of input points, 0 for unlimited (applies to recursion only)",
min=0, max=5000,
default=8,
)
recursion_clamp: IntProperty(
name="Clamp Recursion",
description=(
"Finish recursion when this number of objects is reached "
"(prevents recursing for extended periods of time), zero disables"
),
min=0, max=10000,
default=250,
)
recursion_chance: FloatProperty(
name="Random Factor",
description="Likelihood of recursion",
min=0.0, max=1.0,
default=0.25,
)
recursion_chance_select: EnumProperty(
name="Recurse Over",
items=(
('RANDOM', "Random", ""),
('SIZE_MIN', "Small", "Recursively subdivide smaller objects"),
('SIZE_MAX', "Big", "Recursively subdivide bigger objects"),
('CURSOR_MIN', "Cursor Close", "Recursively subdivide objects closer to the cursor"),
('CURSOR_MAX', "Cursor Far", "Recursively subdivide objects farther from the cursor"),
),
default='SIZE_MIN',
)
# -------------------------------------------------------------------------
# Mesh Data Options
use_smooth_faces: BoolProperty(
name="Smooth Interior",
description="Smooth Faces of inner side",
default=False,
)
use_sharp_edges: BoolProperty(
name="Sharp Edges",
description="Set sharp edges when disabled",
default=True,
)
use_sharp_edges_apply: BoolProperty(
name="Apply Split Edge",
description="Split sharp hard edges",
default=True,
)
use_data_match: BoolProperty(
name="Match Data",
description="Match original mesh materials and data layers",
default=True,
)
use_island_split: BoolProperty(
name="Split Islands",
description="Split disconnected meshes",
default=True,
)
margin: FloatProperty(
name="Margin",
description="Gaps for the fracture (gives more stable physics)",
min=0.0, max=1.0,
default=0.001,
)
material_index: IntProperty(
name="Material",
description="Material index for interior faces",
default=0,
)
use_interior_vgroup: BoolProperty(
name="Interior VGroup",
description="Create a vertex group for interior verts",
default=False,
)
# -------------------------------------------------------------------------
# Physics Options
mass_mode: EnumProperty(
name="Mass Mode",
items=(
('VOLUME', "Volume", "Objects get part of specified mass based on their volume"),
('UNIFORM', "Uniform", "All objects get the specified mass"),
),
default='VOLUME',
)
mass: FloatProperty(
name="Mass",
description="Mass to give created objects",
min=0.001, max=1000.0,
default=1.0,
)
# -------------------------------------------------------------------------
# Object Options
use_recenter: BoolProperty(
name="Recenter",
description="Recalculate the center points after splitting",
default=True,
)
use_remove_original: BoolProperty(
name="Remove Original",
description="Removes the parents used to create the shatter",
default=True,
)
# -------------------------------------------------------------------------
# Scene Options
#
# .. different from object options in that this controls how the objects
# are setup in the scene.
collection_name: StringProperty(
name="Collection",
description=(
"Create objects in a collection "
"(use existing or create new)"
),
)
# -------------------------------------------------------------------------
# Debug
use_debug_points: BoolProperty(
name="Debug Points",
description="Create mesh data showing the points used for fracture",
default=False,
)
use_debug_redraw: BoolProperty(
name="Show Progress Realtime",
description="Redraw as fracture is done",
default=True,
)
use_debug_bool: BoolProperty(
name="Debug Boolean",
description="Skip applying the boolean modifier",
default=False,
)
def execute(self, context):
keywords = self.as_keywords() # ignore=("blah",)
main(context, **keywords)
return {'FINISHED'}
def invoke(self, context, event):
# print(self.recursion_chance_select)
wm = context.window_manager
return wm.invoke_props_dialog(self, width=600)
def draw(self, context):
layout = self.layout
box = layout.box()
col = box.column()
col.label(text="Point Source")
rowsub = col.row()
rowsub.prop(self, "source")
rowsub = col.row()
rowsub.prop(self, "source_limit")
rowsub.prop(self, "source_noise")
rowsub = col.row()
rowsub.prop(self, "cell_scale")
box = layout.box()
col = box.column()
col.label(text="Recursive Shatter")
rowsub = col.row(align=True)
rowsub.prop(self, "recursion")
rowsub.prop(self, "recursion_source_limit")
rowsub.prop(self, "recursion_clamp")
rowsub = col.row()
rowsub.prop(self, "recursion_chance")
rowsub.prop(self, "recursion_chance_select", expand=True)
box = layout.box()
col = box.column()
col.label(text="Mesh Data")
rowsub = col.row()
rowsub.prop(self, "use_smooth_faces")
rowsub.prop(self, "use_sharp_edges")
rowsub.prop(self, "use_sharp_edges_apply")
rowsub.prop(self, "use_data_match")
rowsub = col.row()
# on same row for even layout but in fact are not all that related
rowsub.prop(self, "material_index")
rowsub.prop(self, "use_interior_vgroup")
# could be own section, control how we subdiv
rowsub.prop(self, "margin")
rowsub.prop(self, "use_island_split")
box = layout.box()
col = box.column()
col.label(text="Physics")
rowsub = col.row(align=True)
rowsub.prop(self, "mass_mode")
rowsub.prop(self, "mass")
box = layout.box()
col = box.column()
col.label(text="Object")
rowsub = col.row(align=True)
rowsub.prop(self, "use_recenter")
box = layout.box()
col = box.column()
col.label(text="Scene")
rowsub = col.row(align=True)
rowsub.prop(self, "collection_name")
box = layout.box()
col = box.column()
col.label(text="Debug")
rowsub = col.row(align=True)
rowsub.prop(self, "use_debug_redraw")
rowsub.prop(self, "use_debug_points")
rowsub.prop(self, "use_debug_bool")
def menu_func(self, context):
layout = self.layout
layout.separator()
layout.operator("object.add_fracture_cell_objects", text="Cell Fracture")
def register():
bpy.utils.register_class(FractureCell)
bpy.types.VIEW3D_MT_object_quick_effects.append(menu_func)
def unregister():
bpy.utils.unregister_class(FractureCell)
bpy.types.VIEW3D_MT_object_quick_effects.remove(menu_func)
if __name__ == "__main__":
register()
@@ -0,0 +1,16 @@
schema_version = "1.0.0"
id = "cell_fracture"
name = "Cell Fracture"
version = "0.2.1"
tagline = "Fractured Object Creation"
maintainer = "Community"
type = "add-on"
tags = ["Object"]
blender_version_min = "4.2.0"
license = ["SPDX:GPL-3.0-or-later"]
website = "https://projects.blender.org/extensions/object_fracture_cell"
copyright = [
"2024 ideasman42",
"2024 phymec",
"2024 Sergey Sharybin",
]
@@ -0,0 +1,103 @@
# SPDX-FileCopyrightText: 2012 Blender Foundation
#
# SPDX-License-Identifier: GPL-2.0-or-later
def points_as_bmesh_cells(
verts,
points,
points_scale=None,
margin_bounds=0.05,
margin_cell=0.0,
):
from math import sqrt
import mathutils
from mathutils import Vector
cells = []
points_sorted_current = [p for p in points]
plane_indices = []
vertices = []
if points_scale is not None:
points_scale = tuple(points_scale)
if points_scale == (1.0, 1.0, 1.0):
points_scale = None
# there are many ways we could get planes - convex hull for eg
# but it ends up fastest if we just use bounding box
if 1:
xa = [v[0] for v in verts]
ya = [v[1] for v in verts]
za = [v[2] for v in verts]
xmin, xmax = min(xa) - margin_bounds, max(xa) + margin_bounds
ymin, ymax = min(ya) - margin_bounds, max(ya) + margin_bounds
zmin, zmax = min(za) - margin_bounds, max(za) + margin_bounds
convexPlanes = [
Vector((+1.0, 0.0, 0.0, -xmax)),
Vector((-1.0, 0.0, 0.0, +xmin)),
Vector((0.0, +1.0, 0.0, -ymax)),
Vector((0.0, -1.0, 0.0, +ymin)),
Vector((0.0, 0.0, +1.0, -zmax)),
Vector((0.0, 0.0, -1.0, +zmin)),
]
for i, point_cell_current in enumerate(points):
planes = [None] * len(convexPlanes)
for j in range(len(convexPlanes)):
planes[j] = convexPlanes[j].copy()
planes[j][3] += planes[j].xyz.dot(point_cell_current)
distance_max = 10000000000.0 # a big value!
points_sorted_current.sort(key=lambda p: (p - point_cell_current).length_squared)
for j in range(1, len(points)):
normal = points_sorted_current[j] - point_cell_current
nlength = normal.length
if points_scale is not None:
normal_alt = normal.copy()
normal_alt.x *= points_scale[0]
normal_alt.y *= points_scale[1]
normal_alt.z *= points_scale[2]
# rotate plane to new distance
# should always be positive!! - but abs incase
scalar = normal_alt.normalized().dot(normal.normalized())
# assert(scalar >= 0.0)
nlength *= scalar
normal = normal_alt
if nlength > distance_max:
break
plane = normal.normalized()
plane.resize_4d()
plane[3] = (-nlength / 2.0) + margin_cell
planes.append(plane)
vertices[:], plane_indices[:] = mathutils.geometry.points_in_planes(planes)
if len(vertices) == 0:
break
if len(plane_indices) != len(planes):
planes[:] = [planes[k] for k in plane_indices]
# for comparisons use length_squared and delay
# converting to a real length until the end.
distance_max = 10000000000.0 # a big value!
for v in vertices:
distance = v.length_squared
if distance_max < distance:
distance_max = distance
distance_max = sqrt(distance_max) # make real length
distance_max *= 2.0
if len(vertices) == 0:
continue
cells.append((point_cell_current, vertices[:]))
del vertices[:]
return cells
@@ -0,0 +1,448 @@
# SPDX-FileCopyrightText: 2012 Blender Foundation
#
# SPDX-License-Identifier: GPL-2.0-or-later
import bpy
import bmesh
if bpy.app.background:
def _redraw_yasiamevil():
pass
else:
def _redraw_yasiamevil():
_redraw_yasiamevil.opr(**_redraw_yasiamevil.arg)
_redraw_yasiamevil.opr = bpy.ops.wm.redraw_timer
_redraw_yasiamevil.arg = dict(type='DRAW_WIN_SWAP', iterations=1)
def _points_from_object(context, depsgraph, obj, source):
_source_all = {
'PARTICLE_OWN', 'PARTICLE_CHILD',
'PENCIL',
'VERT_OWN', 'VERT_CHILD',
}
# print(source - _source_all)
# print(source)
assert(len(source | _source_all) == len(_source_all))
assert(len(source))
points = []
def edge_center(mesh, edge):
v1, v2 = edge.vertices
return (mesh.vertices[v1].co + mesh.vertices[v2].co) / 2.0
def poly_center(mesh, poly):
from mathutils import Vector
co = Vector()
tot = 0
for i in poly.loop_indices:
co += mesh.vertices[mesh.loops[i].vertex_index].co
tot += 1
return co / tot
def points_from_verts(obj):
"""Takes points from _any_ object with geometry"""
if obj.type == 'MESH':
mesh = obj.data
matrix = obj.matrix_world.copy()
points.extend([matrix @ v.co for v in mesh.vertices])
else:
ob_eval = obj.evaluated_get(depsgraph)
try:
mesh = ob_eval.to_mesh()
except:
mesh = None
if mesh is not None:
matrix = obj.matrix_world.copy()
points.extend([matrix @ v.co for v in mesh.vertices])
ob_eval.to_mesh_clear()
def points_from_particles(obj):
obj_eval = obj.evaluated_get(depsgraph)
points.extend([p.location.copy()
for psys in obj_eval.particle_systems
for p in psys.particles])
# geom own
if 'VERT_OWN' in source:
points_from_verts(obj)
# geom children
if 'VERT_CHILD' in source:
for obj_child in obj.children:
points_from_verts(obj_child)
# geom particles
if 'PARTICLE_OWN' in source:
points_from_particles(obj)
if 'PARTICLE_CHILD' in source:
for obj_child in obj.children:
points_from_particles(obj_child)
# grease pencil
def get_points(stroke):
return [point.co.copy() for point in stroke.points]
def get_splines(gp):
if gp.layers.active_index:
for layer in gp.layers:
if layer.info == gp.layers.active_note:
frame = layer.active_frame
return [get_points(stroke) for stroke in frame.strokes]
else:
return []
if 'PENCIL' in source:
# Used to be from object in 2.7x, now from scene.
gp = context.annotation_data
if gp:
points.extend([p for spline in get_splines(gp) for p in spline])
print("Found %d points" % len(points))
return points
def cell_fracture_objects(
context, collection, obj,
source={'PARTICLE_OWN'},
source_limit=0,
source_noise=0.0,
clean=True,
# operator options
use_smooth_faces=False,
use_data_match=False,
use_debug_points=False,
margin=0.0,
material_index=0,
use_debug_redraw=False,
cell_scale=(1.0, 1.0, 1.0),
):
from . import fracture_cell_calc
depsgraph = context.evaluated_depsgraph_get()
scene = context.scene
view_layer = context.view_layer
# -------------------------------------------------------------------------
# GET POINTS
points = _points_from_object(context, depsgraph, obj, source)
if not points:
# print using fallback
points = _points_from_object(context, depsgraph, obj, {'VERT_OWN'})
if not points:
print("no points found")
return []
# apply optional clamp
if source_limit != 0 and source_limit < len(points):
import random
random.shuffle(points)
points[source_limit:] = []
# sadly we can't be sure there are no doubles
from mathutils import Vector
to_tuple = Vector.to_tuple
points = list({to_tuple(p, 4): p for p in points}.values())
del to_tuple
del Vector
# end remove doubles
# ------------------
if source_noise > 0.0:
from random import random
# boundbox approx of overall scale
from mathutils import Vector
matrix = obj.matrix_world.copy()
bb_world = [matrix @ Vector(v) for v in obj.bound_box]
scalar = source_noise * ((bb_world[0] - bb_world[6]).length / 2.0)
from mathutils.noise import random_unit_vector
points[:] = [p + (random_unit_vector() * (scalar * random())) for p in points]
if use_debug_points:
bm = bmesh.new()
for p in points:
bm.verts.new(p)
mesh_tmp = bpy.data.meshes.new(name="DebugPoints")
bm.to_mesh(mesh_tmp)
bm.free()
obj_tmp = bpy.data.objects.new(name=mesh_tmp.name, object_data=mesh_tmp)
collection.objects.link(obj_tmp)
del obj_tmp, mesh_tmp
mesh = obj.data
matrix = obj.matrix_world.copy()
verts = [matrix @ v.co for v in mesh.vertices]
cells = fracture_cell_calc.points_as_bmesh_cells(
verts,
points,
cell_scale,
margin_cell=margin,
)
# some hacks here :S
cell_name = obj.name + "_cell"
objects = []
for center_point, cell_points in cells:
# ---------------------------------------------------------------------
# BMESH
# create the convex hulls
bm = bmesh.new()
# WORKAROUND FOR CONVEX HULL BUG/LIMIT
# XXX small noise
import random
def R():
return (random.random() - 0.5) * 0.001
# XXX small noise
for i, co in enumerate(cell_points):
# XXX small noise
co.x += R()
co.y += R()
co.z += R()
# XXX small noise
bm_vert = bm.verts.new(co)
import mathutils
bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=0.005)
try:
bmesh.ops.convex_hull(bm, input=bm.verts)
except RuntimeError:
import traceback
traceback.print_exc()
if clean:
bm.normal_update()
try:
bmesh.ops.dissolve_limit(bm, verts=bm.verts, angle_limit=0.001)
except RuntimeError:
import traceback
traceback.print_exc()
# Smooth faces will remain only inner faces, after applying boolean modifier.
if use_smooth_faces:
for bm_face in bm.faces:
bm_face.smooth = True
if material_index != 0:
for bm_face in bm.faces:
bm_face.material_index = material_index
# ---------------------------------------------------------------------
# MESH
mesh_dst = bpy.data.meshes.new(name=cell_name)
bm.to_mesh(mesh_dst)
bm.free()
del bm
if use_data_match:
# match materials and data layers so boolean displays them
# currently only materials + data layers, could do others...
mesh_src = obj.data
for mat in mesh_src.materials:
mesh_dst.materials.append(mat)
for lay_attr in ("vertex_colors", "uv_layers"):
lay_src = getattr(mesh_src, lay_attr)
lay_dst = getattr(mesh_dst, lay_attr)
for key in lay_src.keys():
lay_dst.new(name=key)
# ---------------------------------------------------------------------
# OBJECT
obj_cell = bpy.data.objects.new(name=cell_name, object_data=mesh_dst)
collection.objects.link(obj_cell)
# scene.objects.active = obj_cell
obj_cell.location = center_point
objects.append(obj_cell)
# support for object materials
if use_data_match:
for i in range(len(mesh_dst.materials)):
slot_src = obj.material_slots[i]
slot_dst = obj_cell.material_slots[i]
slot_dst.link = slot_src.link
slot_dst.material = slot_src.material
if use_debug_redraw:
view_layer.update()
_redraw_yasiamevil()
view_layer.update()
return objects
def cell_fracture_boolean(
context, collection, obj, objects,
use_debug_bool=False,
clean=True,
use_island_split=False,
use_interior_hide=False,
use_debug_redraw=False,
level=0,
remove_doubles=True
):
objects_boolean = []
scene = context.scene
view_layer = context.view_layer
if use_interior_hide and level == 0:
# only set for level 0
obj.data.polygons.foreach_set("hide", [False] * len(obj.data.polygons))
for obj_cell in objects:
mod = obj_cell.modifiers.new(name="Boolean", type='BOOLEAN')
mod.object = obj
mod.operation = 'INTERSECT'
if not use_debug_bool:
if use_interior_hide:
obj_cell.data.polygons.foreach_set("hide", [True] * len(obj_cell.data.polygons))
# Calculates all booleans at once (faster).
depsgraph = context.evaluated_depsgraph_get()
for obj_cell in objects:
if not use_debug_bool:
obj_cell_eval = obj_cell.evaluated_get(depsgraph)
mesh_new = bpy.data.meshes.new_from_object(obj_cell_eval)
mesh_old = obj_cell.data
obj_cell.data = mesh_new
obj_cell.modifiers.remove(obj_cell.modifiers[-1])
# remove if not valid
if not mesh_old.users:
bpy.data.meshes.remove(mesh_old)
if not mesh_new.vertices:
collection.objects.unlink(obj_cell)
if not obj_cell.users:
bpy.data.objects.remove(obj_cell)
obj_cell = None
if not mesh_new.users:
bpy.data.meshes.remove(mesh_new)
mesh_new = None
# avoid unneeded bmesh re-conversion
if mesh_new is not None:
bm = None
if clean:
if bm is None: # ok this will always be true for now...
bm = bmesh.new()
bm.from_mesh(mesh_new)
bm.normal_update()
try:
bmesh.ops.dissolve_limit(bm, verts=bm.verts, edges=bm.edges, angle_limit=0.001)
except RuntimeError:
import traceback
traceback.print_exc()
if remove_doubles:
if bm is None:
bm = bmesh.new()
bm.from_mesh(mesh_new)
bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=0.005)
if bm is not None:
bm.to_mesh(mesh_new)
bm.free()
del mesh_new
del mesh_old
if obj_cell is not None:
objects_boolean.append(obj_cell)
if use_debug_redraw:
_redraw_yasiamevil()
if (not use_debug_bool) and use_island_split:
# this is ugly and Im not proud of this - campbell
for ob in view_layer.objects:
ob.select_set(False)
for obj_cell in objects_boolean:
obj_cell.select_set(True)
bpy.ops.mesh.separate(type='LOOSE')
objects_boolean[:] = [obj_cell for obj_cell in view_layer.objects if obj_cell.select_get()]
context.view_layer.update()
return objects_boolean
def cell_fracture_interior_handle(
objects,
use_interior_vgroup=False,
use_sharp_edges=False,
use_sharp_edges_apply=False,
):
"""Run after doing _all_ booleans"""
assert(use_interior_vgroup or use_sharp_edges or use_sharp_edges_apply)
for obj_cell in objects:
mesh = obj_cell.data
bm = bmesh.new()
bm.from_mesh(mesh)
if use_interior_vgroup:
for bm_vert in bm.verts:
bm_vert.tag = True
for bm_face in bm.faces:
if not bm_face.hide:
for bm_vert in bm_face.verts:
bm_vert.tag = False
# now add all vgroups
defvert_lay = bm.verts.layers.deform.verify()
for bm_vert in bm.verts:
if bm_vert.tag:
bm_vert[defvert_lay][0] = 1.0
# add a vgroup
obj_cell.vertex_groups.new(name="Interior")
if use_sharp_edges:
for bm_edge in bm.edges:
if len({bm_face.hide for bm_face in bm_edge.link_faces}) == 2:
bm_edge.smooth = False
if use_sharp_edges_apply:
edges = [edge for edge in bm.edges if edge.smooth is False]
if edges:
bm.normal_update()
bmesh.ops.split_edges(bm, edges=edges)
for bm_face in bm.faces:
bm_face.hide = False
bm.to_mesh(mesh)
bm.free()
@@ -1,6 +1,6 @@
schema_version = "1.0.0"
id = "datablock_utils"
version = "1.2.0"
version = "1.2.3"
name = "Data-Block Utilities"
tagline = "Show users, merge duplicates, find similar, and more"
maintainer = "Leonardo Pike-Excell <leonardopike.excell@gmail.com>"
@@ -32,7 +32,7 @@ def _assign(
if remove:
collections.remove(coll_prop)
enum = next(i for i in enums if i[0] == key)
enum = next(e for e in enums if e[0] == key)
collections.insert(enums.index(enum), coll_prop)
@@ -47,9 +47,15 @@ def _generate_id_types() -> dict[str, IDType]:
collections.sort(key=lambda c: c.identifier)
if bpy.app.version >= (4, 3, 0):
if bpy.app.version >= (5, 0, 0):
collections.remove(next(c for c in collections if c.identifier == 'annotations'))
_assign('CURVES', 'hair_curves', enums, collections)
_assign('GREASEPENCIL', 'grease_pencils', enums, collections)
_assign('GREASEPENCIL_V3', 'grease_pencils_v3', enums, collections)
if bpy.app.version >= (5, 0, 0):
_assign('GREASEPENCIL', 'grease_pencils', enums, collections, remove=False)
_assign('GREASEPENCIL_V3', 'grease_pencils', enums, collections)
else:
_assign('GREASEPENCIL', 'grease_pencils', enums, collections)
_assign('GREASEPENCIL_V3', 'grease_pencils_v3', enums, collections)
_assign('KEY', 'shape_keys', enums, collections)
_assign('LIGHT_PROBE', 'lightprobes', enums, collections)
else:
@@ -402,7 +402,9 @@ def find_similar_and_duplicate_ntrees(id_type: str) -> None:
def find_duplicate_images() -> None:
duplicates = []
for _, raw_group in groupby(sorted(bpy.data.images, key=get_image_props), get_image_props):
images = [i for i in bpy.data.images if not i.library]
images.sort(key=get_image_props)
for _, raw_group in groupby(images, get_image_props):
group = [i.name for i in raw_group]
if len(group) > 1:
duplicates.append(group)
@@ -0,0 +1,190 @@
import os
import signal
import subprocess
import sys
from pathlib import Path
import bpy # type: ignore
addon_dir = ""
server_pid = None
def get_addon_dir(file):
global addon_dir
addon_dir = os.path.dirname(file)
def select_object(self, obj):
try:
bpy.ops.object.select_all(action="DESELECT")
bpy.context.view_layer.objects.active = obj
obj.select_set(True)
except RuntimeError:
self.report({"INFO"}, "Object {} not in View Layer".format(obj.name))
def select_object_by_mat(self, mat):
for obj in bpy.context.scene.objects:
if obj.type != "MESH":
continue
object_materials = [slot.material for slot in obj.material_slots]
if mat in object_materials:
select_object(self, obj)
def start_server(glb_file_path, port):
global server_pid
if server_pid is not None:
stop_server()
server_file_path = Path(addon_dir, "Server", "server.py")
sub_args = [str(Path(sys.executable))]
if hasattr(bpy.app, "python_args"):
for a in bpy.app.python_args:
sub_args.append(a)
else:
sub_args.append("-I")
sub_args.append(str(server_file_path))
sub_args.append(glb_file_path)
sub_args.append(str(port))
server_process = subprocess.Popen(sub_args)
server_pid = server_process.pid
def stop_server():
global server_pid
if server_pid is None:
print("No process id for the server. Has it been started?")
return
try:
os.kill(server_pid, signal.SIGTERM)
print("Closed process " + str(server_pid))
except OSError:
print("Could not kill server process")
def convert_umlaut(str):
spcial_char_map = {ord("ä"): "ae", ord("ü"): "ue", ord("ö"): "oe", ord("ß"): "ss"}
return str.translate(spcial_char_map)
def rename_annotation():
for o in bpy.context.scene.objects:
if o.name.startswith("Under"):
o.data.name = o.name
def get_or_create_joined_collection(scene):
joined_collection = scene.collection.children.get("JoinedObjects")
if not joined_collection:
joined_collection = bpy.data.collections.new(name="JoinedObjects")
scene.collection.children.link(joined_collection)
return joined_collection
def has_material_variants(meshdata):
if not hasattr(meshdata, "gltf2_variant_mesh_data"):
return False
if len(meshdata.gltf2_variant_mesh_data) == 0:
return False
return True
def join_objects_without_visibility_property(export_only_visible, export_selected):
current_scene = bpy.context.scene
# If set, only visible objects get exported
if export_only_visible:
invisible_objects = []
for o in current_scene.objects:
if not o.visible_get():
invisible_objects.append(o)
for o in invisible_objects:
bpy.data.objects.remove(o)
# If set, export only objects that are selected
if export_selected:
not_selected_objects = []
for o in current_scene.objects:
if not o.select_get():
not_selected_objects.append(o)
for o in not_selected_objects:
bpy.data.objects.remove(o)
# Select only objects that can be joined
bpy.ops.object.select_all(action="SELECT")
for o in current_scene.objects:
if "visibility" in o.keys():
o.select_set(False)
# also deselect all children
for child in o.children_recursive:
child.select_set(False)
continue
if "clickablePart" in o.keys():
o.select_set(False)
# also deselect all children
for child in o.children_recursive:
child.select_set(False)
continue
if o.animation_data is not None:
o.select_set(False)
continue
if o.type != "MESH":
o.select_set(False)
continue
if has_material_variants(o.data):
o.select_set(False)
continue
if len(current_scene.objects) == 0:
print("No objects available to join")
return False
# make the first selected object active
for o in current_scene.objects:
if o.select_get():
current_scene.view_layers[0].objects.active = o
break
bpy.ops.object.join()
bpy.ops.object.select_all(action="SELECT")
return True
def optimize_scene(gltf_export_param):
bpy.ops.wm.save_mainfile()
# Work on a copy of the scene
bpy.ops.scene.new(type="FULL_COPY")
use_visible = False
use_selection = False
if "use_visible" in gltf_export_param:
use_visible = gltf_export_param["use_visible"]
if "use_selection" in gltf_export_param:
use_selection = gltf_export_param["use_selection"]
join_objects_without_visibility_property(
export_only_visible=use_visible, export_selected=use_selection
)
bpy.ops.export_scene.gltf(**gltf_export_param)
bpy.ops.scene.delete()
bpy.ops.wm.open_mainfile(filepath=bpy.data.filepath)
@@ -0,0 +1,25 @@
import bpy # type: ignore
from . import functions
def update_sel_item(self, value):
scene = self
list_object = scene.objects[scene.object_index]
functions.select_object(self, list_object)
def remap_vis_prop(self, value):
for obj in bpy.context.scene.objects:
if obj.get("visibility") is not None:
obj["visibility"] = int(obj.visibility_bool)
def headline(layout, *valueList):
box = layout.box()
row = box.row()
split = row.split()
for pair in valueList:
split = split.split(factor=pair[0])
split.label(text=pair[1])
@@ -1,190 +1,190 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
2. Basic Permissions.
All rights granted under this License are granted for the term of
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
@@ -192,9 +192,9 @@ modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
@@ -202,12 +202,12 @@ non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
@@ -232,19 +232,19 @@ terms of section 4, provided that you also meet all of these conditions:
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
@@ -290,75 +290,75 @@ in one of these ways:
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
@@ -385,74 +385,74 @@ that material) supplement the terms of this License with terms:
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
@@ -460,43 +460,43 @@ give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
@@ -504,13 +504,13 @@ then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
@@ -518,10 +518,10 @@ or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
@@ -533,73 +533,73 @@ for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
@@ -609,9 +609,9 @@ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
@@ -622,11 +622,11 @@ copy of the Program in return for a fee.
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
@@ -649,7 +649,7 @@ the "copyright" line and a pointer to where the full notice is found.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
@@ -658,17 +658,17 @@ notice like this when it starts in an interactive mode:
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
@@ -0,0 +1,168 @@
import bpy # type: ignore
class BakeParticlesOperator(bpy.types.Operator):
"""Bake all Particles to Keyframes. The particles need to have an instance object set. The baked instances are moved to a new collection."""
bl_idname = "object.bake_particles"
bl_label = "Bake Particles"
KEYFRAME_LOCATION: bpy.props.BoolProperty()
KEYFRAME_ROTATION: bpy.props.BoolProperty()
KEYFRAME_SCALE: bpy.props.BoolProperty()
# Viewport and render visibility.
KEYFRAME_VISIBILITY: bpy.props.BoolProperty()
@classmethod
def poll(cls, context):
obj = context.object
if not obj:
return False
if not hasattr(obj, "particle_systems"):
return False
if not len(obj.particle_systems) > 0:
return False
for particlesys in obj.particle_systems:
if bpy.data.particles[particlesys.settings.name].instance_object is None:
return False
return True
def create_particle_collection(self, collection_name):
# Create or clear the particle collection.
# Create a new collection and link it to the scene.
collection_name = bpy.context.scene.particle_settings.collection_name
particle_collection = bpy.data.collections.get(collection_name)
if particle_collection is None:
particle_collection = bpy.data.collections.new(collection_name)
if bpy.context.scene.collection.children.get(collection_name) is None:
bpy.context.scene.collection.children.link(particle_collection)
# remove all objects from the particle collection
if len(particle_collection.objects) > 0:
rem_obj_names = []
for obj in particle_collection.objects:
rem_obj_names.append(obj.name)
for rem_name in rem_obj_names:
bpy.data.objects.remove(bpy.data.objects[rem_name])
def create_objects_for_particles(self, ps, obj, collection_name):
# Duplicate the given object for every particle and return the duplicates.
# Use instances instead of full copies.
obj_list = []
mesh = obj.data
particle_collection = bpy.data.collections.get(collection_name)
for particle in ps.particles:
dupli = bpy.data.objects.new(name=obj.name, object_data=mesh)
particle_collection.objects.link(dupli)
obj_list.append(dupli)
# copy modifiers to duplicates
# adapted from: https://blender.stackexchange.com/a/4883
for modifierOrig in obj.modifiers:
modifierNew = dupli.modifiers.new(modifierOrig.name, modifierOrig.type)
# collect names of writable properties
properties = [
p.identifier
for p in modifierOrig.bl_rna.properties
if not p.is_readonly
]
# copy those properties
for prop in properties:
setattr(modifierNew, prop, getattr(modifierOrig, prop))
return obj_list
def match_and_keyframe_objects(self, ps, obj_list, start_frame, end_frame):
# Match and keyframe the objects to the particles for every frame in the
# given range.
frame_offset = bpy.context.scene.particle_settings.frame_offset
for frame in range(start_frame, end_frame + 1, frame_offset):
bpy.context.scene.frame_set(frame)
for p, obj in zip(ps.particles, obj_list):
self.match_object_to_particle(p, obj)
self.keyframe_obj(obj)
def match_object_to_particle(self, p, obj):
# Match the location, rotation, scale and visibility of the object to
# the particle.
loc = p.location
rot = p.rotation
size = p.size
# Set rotation mode to quaternion to match particle rotation.
obj.rotation_mode = "QUATERNION"
obj.rotation_quaternion = rot
if self.KEYFRAME_VISIBILITY:
if p.alive_state != "ALIVE":
size *= 0.01
obj.location = loc
obj.scale = (size, size, size)
# obj.hide_viewport = not(vis)
# obj.hide_render = not(vis)
def keyframe_obj(self, obj):
# Keyframe location, rotation, scale and visibility if specified.
if self.KEYFRAME_LOCATION:
obj.keyframe_insert("location")
if self.KEYFRAME_ROTATION:
obj.keyframe_insert("rotation_quaternion")
if self.KEYFRAME_SCALE:
obj.keyframe_insert("scale")
# if self.KEYFRAME_VISIBILITY:
# obj.keyframe_insert("hide_viewport")
# obj.keyframe_insert("hide_render")
def execute(self, context):
# go to start frame
bpy.context.scene.frame_set(0)
collection_name = bpy.context.scene.particle_settings.collection_name
self.create_particle_collection(collection_name)
# get emitter and instance
emitter = bpy.context.object
ps_list = emitter.particle_systems
for i, ps in enumerate(ps_list):
instance = ps.settings.instance_object
depsgraph = bpy.context.evaluated_depsgraph_get()
# Extract locations
ps = depsgraph.objects[emitter.name].particle_systems[i]
# update ps hack
# bpy.data.particles[ps.name].count += 1
# bpy.data.particles[ps.name].count -= 1
start_frame = bpy.context.scene.frame_start
end_frame = bpy.context.scene.frame_end
obj_list = self.create_objects_for_particles(ps, instance, collection_name)
self.match_and_keyframe_objects(ps, obj_list, start_frame, end_frame)
# Simplify
bpy.ops.object.select_all(action="DESELECT")
for obj in bpy.data.collections[collection_name].all_objects:
obj.select_set(True)
return {"FINISHED"}
def register():
bpy.utils.register_class(BakeParticlesOperator)
def unregister():
bpy.utils.unregister_class(BakeParticlesOperator)
@@ -0,0 +1,122 @@
import bpy # type: ignore
class JoinAnimationOperator(bpy.types.Operator):
bl_idname = "scene.join_anim"
bl_label = "Join Animation"
bl_description = "Join animations for all selected objects by making an NLA strip for each object and naming the track consistently"
bl_options = {"REGISTER"}
anim_name: bpy.props.StringProperty()
@classmethod
def poll(cls, context):
return True
def execute(self, context):
sel_objects = context.selected_objects
for obj in sel_objects:
if obj.animation_data is None:
continue
if obj.animation_data.action is None:
continue
# if hasattr(obj.animation_data,"action"):
action = obj.animation_data.action
track = obj.animation_data.nla_tracks.new()
track.strips.new(self.anim_name, int(action.frame_start), action)
track.name = self.anim_name
obj.animation_data.action = None
return {"FINISHED"}
class SeperateAnimationOperator(bpy.types.Operator):
bl_idname = "scene.seperate_anim"
bl_label = "Separate Animation"
bl_description = "Transform NLA strips back to Keyframes to make them editable again. Make sure to select all objects you want to transform back."
bl_options = {"REGISTER"}
@classmethod
def poll(cls, context):
return True
def execute(self, context):
sel_objects = context.selected_objects
for obj in sel_objects:
if obj.animation_data is None:
continue
if len(obj.animation_data.nla_tracks) == 0:
continue
# set actions
track = obj.animation_data.nla_tracks[0]
action_name = track.strips[0].name
action = bpy.data.actions.get(action_name)
obj.animation_data.action = action
# remove track
obj.animation_data.nla_tracks.remove(track)
return {"FINISHED"}
class RenameNLAAnimationOperator(bpy.types.Operator):
bl_idname = "scene.rename_anim"
bl_label = "Rename Animation"
bl_description = "Rename NLA Tracks on selected objects"
bl_options = {"REGISTER"}
anim_name: bpy.props.StringProperty()
index = 0
@classmethod
def poll(cls, context):
return True
def execute(self, context):
sel_objects = context.selected_objects
for obj in sel_objects:
track = obj.animation_data.nla_tracks[self.index]
track.name = self.anim_name
return {"FINISHED"}
class RenameActionOperator(bpy.types.Operator):
bl_idname = "scene.rename_action"
bl_label = "Rename Action"
bl_description = "Rename Action on active object"
bl_options = {"REGISTER"}
action_name: bpy.props.StringProperty()
index = 0
@classmethod
def poll(cls, context):
return True
def execute(self, context):
active_object = context.active_object
active_object.animation_data.action.name = self.action_name
return {"FINISHED"}
def register():
# Use actions instead of NLA Strips for Animation merging
if bpy.app.version < (4, 4, 0):
bpy.utils.register_class(JoinAnimationOperator)
bpy.utils.register_class(SeperateAnimationOperator)
bpy.utils.register_class(RenameNLAAnimationOperator)
else:
bpy.utils.register_class(RenameActionOperator)
def unregister():
# Use actions instead of NLA Strips for Animation merging
if bpy.app.version < (4, 4, 0):
bpy.utils.unregister_class(JoinAnimationOperator)
bpy.utils.unregister_class(SeperateAnimationOperator)
bpy.utils.unregister_class(RenameNLAAnimationOperator)
else:
bpy.utils.unregister_class(RenameActionOperator)
@@ -0,0 +1,361 @@
import bpy # type: ignore
from pathlib import Path
from ..Functions import functions
class GOVIE_open_export_folder_Operator(bpy.types.Operator):
bl_idname = "scene.open_export_folder"
bl_label = "Open Folder"
bl_description = "Open current GLB folder. You may need to export first for the folder to be created."
@classmethod
def poll(cls, context):
# get folder of blend file
blend_path = Path(bpy.data.filepath).parent
# get export settings
glb_filename = context.scene.export_settings.glb_filename
if blend_path.joinpath(glb_filename).parent.exists():
return True
else:
return False
def execute(self, context):
# get folder of blend file
blend_path = Path(bpy.data.filepath).parent
# get export settings
glb_filename = context.scene.export_settings.glb_filename
bpy.ops.wm.url_open(
url="file://{}".format(
str(blend_path.joinpath(glb_filename).parent.absolute())
)
)
return {"FINISHED"}
class GOVIE_Open_Link_Operator(bpy.types.Operator):
bl_idname = "scene.open_link"
bl_label = "Open Website"
bl_description = "Go to GOVIE Website"
url: bpy.props.StringProperty(name="url")
@classmethod
def poll(cls, context):
return True
def execute(self, context):
bpy.ops.wm.url_open(url=self.url)
return {"FINISHED"}
class GOVIE_Add_Property_Operator(bpy.types.Operator):
"""Add the custom property on the current selected object"""
bl_idname = "object.add_property"
bl_label = "Add custom Property"
property_type: bpy.props.StringProperty(name="custom_property_name")
@classmethod
def poll(cls, context):
if context.object is None:
return False
else:
return True
def execute(self, context):
selected_objects = context.selected_objects
for obj in selected_objects:
if self.property_type == "visibility":
obj["visibility"] = 1
# obj.visibility_bool = 1
if self.property_type == "clickable":
obj["clickablePart"] = "clickablePart"
return {"FINISHED"}
class GOVIE_Remove_Property_Operator(bpy.types.Operator):
"""Remove the custom property on the current selected object"""
bl_idname = "object.remove_property"
bl_label = "Remove visibility Property"
property_type: bpy.props.StringProperty(name="custom_property_name")
@classmethod
def poll(cls, context):
if context.object is None:
return False
else:
return True
def execute(self, context):
selected_objects = context.selected_objects
for obj in selected_objects:
if self.property_type == "visibility":
if "visibility" in obj.keys():
del obj["visibility"]
if self.property_type == "clickable":
if "clickablePart" in obj.keys():
del obj["clickablePart"]
return {"FINISHED"}
class GOVIE_Quick_Export_GLB_Operator(bpy.types.Operator):
bl_idname = "scene.gltf_quick_export"
bl_label = "EXPORT_GLTF"
bl_description = "Save Blend file first ! The GLB file will be saved to 'pathOfBlendFile/glb/filename.glb'"
@classmethod
def poll(cls, context):
if bpy.data.is_saved:
return True
else:
return False
def execute(self, context):
# check spelling
filename = context.scene.export_settings.glb_filename
context.scene.export_settings.glb_filename = functions.convert_umlaut(filename)
# check annotation names
functions.rename_annotation()
# blender file saved
file_is_saved = bpy.data.is_saved
if not file_is_saved:
self.report({"INFO"}, "You need to save the Blend file first!")
return {"FINISHED"}
# get folder of blend file
blend_path = Path(bpy.data.filepath).parent
# get export settings
glb_filename = context.scene.export_settings.glb_filename
glb_filepath = blend_path.joinpath(glb_filename)
if not glb_filepath.parent.exists():
glb_filepath.parent.mkdir(parents=True)
preset_path = "operator/export_scene.gltf/"
export_preset_name = context.scene.export_settings.export_preset
preset_filepath = bpy.utils.preset_find(export_preset_name, preset_path)
gltf_export_param = {}
# read preset parameters from file
if preset_filepath:
class Container(object):
__slots__ = ("__dict__",)
op = Container()
preset_file = open(preset_filepath, "r")
# storing the values from the preset on the class
for line in preset_file.readlines()[3::]:
exec(line, globals(), locals())
# pass class dictionary to the operator
gltf_export_param = op.__dict__
else:
gltf_export_param["export_extras"] = True
join_objects = context.scene.export_settings.join_objects
gltf_export_param["filepath"] = str(glb_filepath.absolute())
# export glb
if join_objects:
functions.optimize_scene(gltf_export_param)
else:
bpy.ops.export_scene.gltf(**gltf_export_param)
# change glb dropdown entry
# context.scene.glb_file_dropdown = context.scene.export_settings.glb_filename
return {"FINISHED"}
class GOVIE_CleanupMesh_Operator(bpy.types.Operator):
bl_idname = "object.cleanup_mesh"
bl_label = "Delete Loose and Degenerate Dissolve"
bl_description = "Mesh Cleanup -> Delete Loose and Degenerate Dissolve"
@classmethod
def poll(cls, context):
return context.mode == "OBJECT"
def execute(self, context):
exclude_temp_list = []
collections = bpy.context.view_layer.layer_collection.children
# switch on all layers but remember vis settings
for collection in collections:
exclude_temp_list.append(collection.exclude)
collection.exclude = False
for obj in context.scene.objects:
if obj.type == "MESH":
functions.select_object(self, obj)
bpy.ops.object.editmode_toggle()
bpy.ops.mesh.delete_loose()
bpy.ops.mesh.dissolve_degenerate()
bpy.ops.object.editmode_toggle()
# set back layer settings
for collection, exclude_temp_value in zip(collections, exclude_temp_list):
collection.exclude = exclude_temp_value
self.report({"INFO"}, "Meshes Cleaned !")
return {"FINISHED"}
class GOVIE_CheckTexNodes_Operator(bpy.types.Operator):
"""Check if there are any empty Texture Nodes in any Material and print that material"""
bl_idname = "object.check_tex_nodes"
bl_label = "Check Empty Tex Nodes"
bpy.types.Scene.mat_name_list = []
def execute(self, context):
mat_name_list = context.scene.mat_name_list
mat_name_list.clear()
# get materials with texture nodes that have no image assigned
for mat in bpy.data.materials:
if mat.node_tree is None:
continue
for node in mat.node_tree.nodes:
if node.type == "TEX_IMAGE" and node.image is None:
mat_name_list.append(mat.name)
self.report(
{"INFO"},
"Found empty image node in material {}".format(mat.name),
)
functions.select_object_by_mat(self, mat)
if len(mat_name_list) == 0:
self.report({"INFO"}, "No Empty Image Nodes")
return {"FINISHED"}
class GOVIE_Add_UV_Animation_Operator(bpy.types.Operator):
"""Create UV Animation for selected object"""
bl_idname = "object.add_uv_anim"
bl_label = "Add UV Animation"
@classmethod
def poll(cls, context):
if context.object is None:
return False
else:
return True
def execute(self, context):
active_object = context.active_object
new_name = active_object.name + "_uv_anim_controller"
if bpy.data.objects.get(new_name):
empty = bpy.data.objects[new_name]
else:
bpy.ops.object.empty_add(
type="PLAIN_AXES", align="WORLD", location=(0, 0, 0), scale=(1, 1, 1)
)
empty = context.active_object
empty.name = new_name
# add custom property
empty["uvAnim"] = active_object.name
# save emtpy name in scene for later use
context.scene["uv_anim_obj"] = empty.name
# add driver to material mapping node
if active_object and active_object.active_material:
material = active_object.active_material
# Find the Mapping node in the material's node tree
mapping_node = None
for node in material.node_tree.nodes:
print(node.type)
if node.type == "MAPPING":
mapping_node = node
break
if mapping_node:
# remove driver fist if there is one
mapping_node.inputs["Location"].driver_remove("default_value", 0)
driverX = (
mapping_node.inputs["Location"]
.driver_add("default_value", 0)
.driver
)
driverX.type = "SCRIPTED"
driverX.expression = empty.name
# Add the Empty object as a variable target
var = driverX.variables.new()
var.name = empty.name
var.type = "TRANSFORMS"
var.targets[0].id = bpy.data.objects[empty.name]
var.targets[0].transform_type = "LOC_X"
mapping_node.inputs["Location"].driver_remove("default_value", 1)
driverY = (
mapping_node.inputs["Location"]
.driver_add("default_value", 1)
.driver
)
driverY.type = "SCRIPTED"
driverY.expression = "-" + empty.name
var = driverY.variables.new()
var.name = empty.name
var.type = "TRANSFORMS"
var.targets[0].id = bpy.data.objects[empty.name]
var.targets[0].transform_type = "LOC_Z"
else:
print("Mapping node not found in the material's node tree.")
else:
print("Active object or active material not found.")
active_object.select_set(True)
context.view_layer.objects.active = active_object
return {"FINISHED"}
def register():
bpy.utils.register_class(GOVIE_open_export_folder_Operator)
bpy.utils.register_class(GOVIE_Open_Link_Operator)
bpy.utils.register_class(GOVIE_Add_Property_Operator)
bpy.utils.register_class(GOVIE_Remove_Property_Operator)
bpy.utils.register_class(GOVIE_Quick_Export_GLB_Operator)
bpy.utils.register_class(GOVIE_CleanupMesh_Operator)
bpy.utils.register_class(GOVIE_CheckTexNodes_Operator)
bpy.utils.register_class(GOVIE_Add_UV_Animation_Operator)
def unregister():
bpy.utils.unregister_class(GOVIE_open_export_folder_Operator)
bpy.utils.unregister_class(GOVIE_Open_Link_Operator)
bpy.utils.unregister_class(GOVIE_Add_Property_Operator)
bpy.utils.unregister_class(GOVIE_Remove_Property_Operator)
bpy.utils.unregister_class(GOVIE_Quick_Export_GLB_Operator)
bpy.utils.unregister_class(GOVIE_CleanupMesh_Operator)
bpy.utils.unregister_class(GOVIE_CheckTexNodes_Operator)
bpy.utils.unregister_class(GOVIE_Add_UV_Animation_Operator)
@@ -0,0 +1,53 @@
from pathlib import Path
import bpy # type: ignore
from ..Functions import functions
class GOVIE_Preview_Operator(bpy.types.Operator):
bl_idname = "scene.open_web_preview"
bl_label = "Open in Browser"
bl_description = "Press export to display a preview of the exported file"
port = 8000
url = (
"https://3dit-tools.s3.eu-central-1.amazonaws.com/StaticGLBViewerV2/index.html"
)
@classmethod
def poll(cls, context):
# get folder of blend file
blend_path = Path(bpy.data.filepath).parent
# get export settings
glb_filename = context.scene.export_settings.glb_filename
if not glb_filename.endswith(".glb"):
glb_filename = "{}.glb".format(glb_filename)
if blend_path.joinpath(glb_filename).exists():
return True
else:
return False
def execute(self, context):
# get folder of blend file
blend_path = Path(bpy.data.filepath).parent
# get export settings
glb_filename = context.scene.export_settings.glb_filename
if not glb_filename.endswith(".glb"):
glb_filename = "{}.glb".format(glb_filename)
functions.start_server(blend_path.joinpath(glb_filename).absolute(), self.port)
# run browser
bpy.ops.wm.url_open(url=self.url)
return {"FINISHED"}
def register():
bpy.utils.register_class(GOVIE_Preview_Operator)
def unregister():
bpy.utils.unregister_class(GOVIE_Preview_Operator)
@@ -0,0 +1,43 @@
import bpy # type: ignore
class SimplifyKeyframes(bpy.types.Operator):
bl_idname = "scene.simplify_keyframes"
bl_label = "Simplify Keyframes"
bl_description = "Simplify the Keyframes by the selected decimate ratio, higher values will reduce more keyframes"
bl_options = {"REGISTER"}
decimate_ratio: bpy.props.FloatProperty()
mode: bpy.props.StringProperty()
@classmethod
def poll(cls, context):
display_button = False
# at least one object with animation on it
sel_objects = context.selected_objects
for obj in sel_objects:
if obj.animation_data is not None:
display_button = True
return display_button
def execute(self, context):
context.area.type = "GRAPH_EDITOR"
bpy.ops.graph.select_all(action="SELECT")
bpy.ops.graph.decimate(
mode=self.mode,
factor=self.decimate_ratio,
remove_error_margin=self.decimate_ratio,
)
context.area.type = "VIEW_3D"
return {"FINISHED"}
def register():
bpy.utils.register_class(SimplifyKeyframes)
def unregister():
bpy.utils.unregister_class(SimplifyKeyframes)
@@ -0,0 +1,495 @@
import bpy # type: ignore
from ..Functions import gui_functions
from ..Properties import properties
class ANIM_UL_List(bpy.types.UIList):
def draw_item(
self,
context,
layout,
data,
item,
icon,
active_data,
active_propname,
index,
flt_flag,
):
if context.object is not None:
selOff = "RADIOBUT_OFF"
selOn = "RADIOBUT_ON"
row = layout.row(align=True)
split = row.split(factor=0.2)
if item.name == context.object.name:
split.label(text="", icon=selOn)
split = split.split(factor=0.4)
split.prop(item, "name", text="")
else:
split.label(text="", icon=selOff)
split = split.split(factor=0.4)
split.label(text=item.name)
split = split.split(factor=1)
has_action_name = getattr(
getattr(getattr(item, "animation_data", None), "action", None),
"name",
None,
)
has_nla_name = getattr(
getattr(getattr(item, "animation_data", None), "nla_tracks", None),
"active",
None,
)
if has_action_name:
split.prop(item.animation_data.action, "name", text="")
if has_nla_name:
split.prop(item.animation_data.nla_tracks.active, "name", text="")
def filter_items(self, context, data, propname):
objects_in_scene = data.objects
# Default return values.
flt_flags = []
flt_neworder = []
# flt_flags = [self.bitflag_filter_item if getattr(getattr(getattr(obj,"animation_data",None),"action",None),"name",None) and obj.visible_get(
# ) else 0 for obj in objects_in_scene]
for obj in objects_in_scene:
has_action_name = getattr(
getattr(getattr(obj, "animation_data", None), "action", None),
"name",
None,
)
has_nla_name = getattr(
getattr(getattr(obj, "animation_data", None), "nla_tracks", None),
"active",
None,
)
if has_action_name or has_nla_name:
flt_flags.append(self.bitflag_filter_item)
else:
flt_flags.append(0)
return flt_flags, flt_neworder
class VIS_UL_List(bpy.types.UIList):
def draw_item(
self,
context,
layout,
data,
item,
icon,
active_data,
active_propname,
index,
flt_flag,
):
selOff = "RADIOBUT_OFF"
selOn = "RADIOBUT_ON"
# 'DEFAULT' and 'COMPACT' layout types should usually use the same draw code.
if self.layout_type in {"DEFAULT", "COMPACT"}:
row = layout.row()
split = row.split(factor=0.2)
if context.object is not None:
if item.name == context.object.name:
split.label(text="", icon=selOn)
split = split.split(factor=0.6)
split.prop(item, "name", text="")
else:
split.label(text="", icon=selOff)
split = split.split(factor=0.6)
split.label(text=item.name)
split = split.split(factor=1)
split.prop(item, "visibility_bool", text="")
def filter_items(self, context, data, propname):
objects = getattr(data, propname)
objectList = objects.items()
# Default return values.
flt_flags = []
flt_neworder = []
# get only items that have visibility property
flt_flags = [
self.bitflag_filter_item
if obj[1].get("visibility") is not None and obj[1].visible_get()
else 0
for obj in objectList
]
return flt_flags, flt_neworder
class CLICK_UL_List(bpy.types.UIList):
def draw_item(
self,
context,
layout,
data,
item,
icon,
active_data,
active_propname,
index,
flt_flag,
):
selOff = "RADIOBUT_OFF"
selOn = "RADIOBUT_ON"
# 'DEFAULT' and 'COMPACT' layout types should usually use the same draw code.
if self.layout_type in {"DEFAULT", "COMPACT"}:
row = layout.row()
split = row.split(factor=0.2)
if context.object is not None:
if item.name == context.object.name:
split.label(text="", icon=selOn)
split = split.split(factor=0.6)
split.prop(item, "name", text="")
else:
split.label(text="", icon=selOff)
split = split.split(factor=0.6)
split.label(text=item.name)
def filter_items(self, context, data, propname):
objects = getattr(data, propname)
objectList = objects.items()
# Default return values.
flt_flags = []
flt_neworder = []
# get only items that have visibility property
flt_flags = [
self.bitflag_filter_item
if obj[1].get("clickablePart") is not None and obj[1].visible_get()
else 0
for obj in objectList
]
return flt_flags, flt_neworder
class GovieToolsPanel:
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
bl_category = "Govie Tools"
@classmethod
def poll(cls, context):
return context.object is not None
class ANIM_PT_Main(GovieToolsPanel, bpy.types.Panel):
bl_idname = "ANIM_PT_Main"
bl_label = "Animation"
bl_options = {"DEFAULT_CLOSED"}
bl_order = 1
def draw(self, context):
layout = self.layout
scene = context.scene
gui_functions.headline(
layout, (0.2, "ACTIVE"), (0.4, "OBJECT NAME"), (1, "ANIMATION NAME")
)
layout.template_list(
"ANIM_UL_List", "", scene, "objects", scene, "object_index"
)
class ANIM_PT_Sub_ManageActions(GovieToolsPanel, bpy.types.Panel):
bl_parent_id = "ANIM_PT_Main"
bl_label = "Manage Actions"
bl_options = {"DEFAULT_CLOSED"}
def draw(self, context):
anim_settings = context.scene.animation_settings
layout = self.layout
layout.prop(anim_settings, "action_name", text="Name")
layout.operator(
"scene.rename_action", text="Rename Action"
).action_name = anim_settings.action_name
layout.operator("anim.merge_animation", text="Join Action")
layout.operator("anim.separate_slots", text="Separate Action")
class ANIM_PT_Sub_Manage(GovieToolsPanel, bpy.types.Panel):
bl_parent_id = "ANIM_PT_Main"
bl_label = "Manage Animation"
bl_options = {"DEFAULT_CLOSED"}
def draw(self, context):
anim_settings = context.scene.animation_settings
layout = self.layout
layout.prop(anim_settings, "join_anim_name", text="Name")
layout.operator(
"scene.join_anim", text="Join Animation"
).anim_name = anim_settings.join_anim_name
layout.operator(
"scene.rename_anim", text="Rename Animation"
).anim_name = anim_settings.join_anim_name
layout.operator("scene.seperate_anim", text="Separate Animation")
class ANIM_PT_Sub_Particles(GovieToolsPanel, bpy.types.Panel):
bl_parent_id = "ANIM_PT_Main"
bl_label = "Bake Particles"
bl_options = {"DEFAULT_CLOSED"}
def draw(self, context):
particle_settings = context.scene.particle_settings
layout = self.layout
layout.use_property_split = True
layout.use_property_decorate = False
# particle settings
column = layout.column(align=True, heading="Key")
column.prop(particle_settings, "key_loc", text="Location")
column.prop(particle_settings, "key_rot", text="Rotation")
column.prop(particle_settings, "key_scale", text="Scale")
column.prop(particle_settings, "key_vis", text="Visibility")
layout.separator()
layout.prop(particle_settings, "frame_offset", text="Frame Offset")
layout.prop(particle_settings, "collection_name")
# Bake Operator
bake_particle_op = layout.operator(
"object.bake_particles", text="Bake Particles"
)
bake_particle_op.KEYFRAME_LOCATION = particle_settings.key_loc
bake_particle_op.KEYFRAME_ROTATION = particle_settings.key_rot
bake_particle_op.KEYFRAME_SCALE = particle_settings.key_scale
bake_particle_op.KEYFRAME_VISIBILITY = particle_settings.key_vis
class ANIM_PT_Sub_Simplify(GovieToolsPanel, bpy.types.Panel):
bl_parent_id = "ANIM_PT_Main"
bl_label = "Simplify Animation"
bl_options = {"DEFAULT_CLOSED"}
def draw(self, context):
layout = self.layout
anim_settings = context.scene.animation_settings
layout.prop(anim_settings, "simplify_keyframes_enum", text="Mode")
if anim_settings.simplify_keyframes_enum == "RATIO":
layout.prop(anim_settings, "decimate_ratio", text="Ratio")
else:
layout.prop(anim_settings, "decimate_ratio", text="Error Margin")
simplify_keyframe_op = layout.operator(
"scene.simplify_keyframes", text="Simplify Keyframes"
)
simplify_keyframe_op.mode = anim_settings.simplify_keyframes_enum
simplify_keyframe_op.decimate_ratio = anim_settings.decimate_ratio
class ANIM_PT_Sub_UVAnim(GovieToolsPanel, bpy.types.Panel):
bl_parent_id = "ANIM_PT_Main"
bl_label = "UV Animation"
bl_options = {"DEFAULT_CLOSED"}
def draw(self, context):
layout = self.layout
layout.operator("object.add_uv_anim", text="Add UV Animation Helper")
class VIS_PT_Main(GovieToolsPanel, bpy.types.Panel):
bl_idname = "VIS_PT_Main"
bl_label = "Visibility"
bl_order = 4
def draw(self, context):
layout = self.layout
scene = context.scene
layout.label(text="Make objects hideable in the govie editor")
gui_functions.headline(
layout, (0.2, "ACTIVE"), (0.6, "OBJECT NAME"), (1, "VISIBLE")
)
layout.template_list("VIS_UL_List", "", scene, "objects", scene, "object_index")
op_add = layout.operator("object.add_property", text="Add Property")
op_rm = layout.operator("object.remove_property", text="Remove Property")
op_add.property_type = "visibility"
op_rm.property_type = "visibility"
class CLICK_PT_Main(GovieToolsPanel, bpy.types.Panel):
bl_idname = "CLICK_PT_Main"
bl_label = "Clickable Object"
bl_order = 5
def draw(self, context):
layout = self.layout
scene = context.scene
layout.label(text="Make objects clickable in the govie editor")
gui_functions.headline(layout, (0.2, "ACTIVE"), (0.8, "OBJECT NAME"))
layout.template_list(
"CLICK_UL_List", "", scene, "objects", scene, "object_index"
)
op_add = layout.operator("object.add_property", text="Add Property")
op_rm = layout.operator("object.remove_property", text="Remove Property")
op_add.property_type = "clickable"
op_rm.property_type = "clickable"
class GOVIE_PT_Export_Main(GovieToolsPanel, bpy.types.Panel):
bl_idname = "GOVIE_PT_Export_Main"
bl_label = "GLB Export"
bl_order = 5
def draw(self, context):
return
class GOVIE_PT_Export_Sub_Verify(GovieToolsPanel, bpy.types.Panel):
bl_parent_id = "GOVIE_PT_Export_Main"
bl_label = "Cleanup"
bl_options = {"DEFAULT_CLOSED"}
def draw(self, context):
layout = self.layout
mat_name_list = context.scene.mat_name_list
if len(mat_name_list) > 0:
layout.label(text="Check Materials:")
for mat_name in mat_name_list:
layout.label(text=mat_name)
layout.operator("object.check_tex_nodes", text="Find Empty Image Nodes")
layout.operator("object.cleanup_mesh", text="Cleanup Mesh")
class GOVIE_PT_Export_Sub_Settings(GovieToolsPanel, bpy.types.Panel):
bl_parent_id = "GOVIE_PT_Export_Main"
bl_idname = "GOVIE_PT_Export_Sub_Settings"
bl_label = "Export Settings"
bl_options = {"DEFAULT_CLOSED"}
def draw(self, context):
layout = self.layout
# align properties to the right
layout.use_property_split = True
# hide keyframing icon
layout.use_property_decorate = False
exp_settings = context.scene.export_settings
column = layout.column(align=True, heading="Preset")
column.prop(context.scene, "glb_preset_dropdown")
# layout.separator()
column = layout.column(align=True, heading="Optimization")
column.prop(
exp_settings,
"join_objects",
)
class GOVIE_PT_EXPORT_Sub_Export(GovieToolsPanel, bpy.types.Panel):
bl_parent_id = "GOVIE_PT_Export_Main"
bl_label = "Export and Preview"
def draw(self, context):
layout = self.layout
scene = context.scene
layout.prop(scene.export_settings, "glb_filename")
# layout.prop(scene, "glb_file_dropdown")
layout.operator("scene.gltf_quick_export", text="Export")
row = layout.row()
row.operator("scene.open_export_folder", icon="FILEBROWSER")
row.operator("scene.open_web_preview", text="Preview", icon="WORLD")
class HelpPanel(GovieToolsPanel, bpy.types.Panel):
bl_idname = "GOVIE_PT_help_panel"
bl_label = "Help"
bl_order = 6
def draw(self, context):
scene = context.scene
layout = self.layout
lang = bpy.app.translations.locale
if lang == "en_US":
layout.label(text="To use the full potential of the add-on,")
layout.label(text="you may sign up for a free govie account.")
layout.label(text="Further documentation can be found here:")
layout.operator(
"scene.open_link", text="Govie Tools Documentation", icon="HELP"
).url = "https://govie-editor.de/en/help/govie-tools/"
if lang == "de_DE":
layout.label(text="Um das volle Potential dieses Add-ons zu nutzen,")
layout.label(
text="empfehlen wir einen kostenlosen Account des Govie Editors anzulegen"
)
layout.label(text="Weitere Dokumentation findet sich hier:")
layout.operator(
"scene.open_link", text="Add-on Documentation", icon="HELP"
).url = "https://govie-editor.de/help-section/blender/"
def register():
bpy.utils.register_class(ANIM_UL_List)
bpy.utils.register_class(VIS_UL_List)
bpy.utils.register_class(CLICK_UL_List)
bpy.utils.register_class(ANIM_PT_Main)
# Use actions instead of NLA Strips for Animation merging
if bpy.app.version < (4, 4, 0):
bpy.utils.register_class(ANIM_PT_Sub_Manage)
else:
bpy.utils.register_class(ANIM_PT_Sub_ManageActions)
bpy.utils.register_class(ANIM_PT_Sub_Particles)
bpy.utils.register_class(ANIM_PT_Sub_Simplify)
bpy.utils.register_class(ANIM_PT_Sub_UVAnim)
bpy.utils.register_class(VIS_PT_Main)
bpy.utils.register_class(CLICK_PT_Main)
bpy.utils.register_class(GOVIE_PT_Export_Main)
bpy.utils.register_class(GOVIE_PT_Export_Sub_Verify)
bpy.utils.register_class(GOVIE_PT_Export_Sub_Settings)
bpy.utils.register_class(GOVIE_PT_EXPORT_Sub_Export)
bpy.utils.register_class(HelpPanel)
def unregister():
bpy.utils.unregister_class(ANIM_UL_List)
bpy.utils.unregister_class(VIS_UL_List)
bpy.utils.unregister_class(CLICK_UL_List)
bpy.utils.unregister_class(ANIM_PT_Main)
# Use actions instead of NLA Strips for Animation merging
if bpy.app.version < (4, 4, 0):
bpy.utils.unregister_class(ANIM_PT_Sub_Manage)
else:
bpy.utils.unregister_class(ANIM_PT_Sub_ManageActions)
bpy.utils.unregister_class(ANIM_PT_Sub_Particles)
bpy.utils.unregister_class(ANIM_PT_Sub_Simplify)
bpy.utils.unregister_class(ANIM_PT_Sub_UVAnim)
bpy.utils.unregister_class(VIS_PT_Main)
bpy.utils.unregister_class(CLICK_PT_Main)
bpy.utils.unregister_class(GOVIE_PT_Export_Main)
bpy.utils.unregister_class(GOVIE_PT_Export_Sub_Verify)
bpy.utils.unregister_class(GOVIE_PT_Export_Sub_Settings)
bpy.utils.unregister_class(GOVIE_PT_EXPORT_Sub_Export)
bpy.utils.unregister_class(HelpPanel)
@@ -0,0 +1,115 @@
from pathlib import Path
import glob
import bpy # type: ignore
from bpy.props import ( # type: ignore
BoolProperty,
EnumProperty,
FloatProperty,
IntProperty,
PointerProperty,
StringProperty,
)
from ..Functions import gui_functions
class Export_Settings(bpy.types.PropertyGroup):
glb_filename: StringProperty(name="Filename", default="./glb/filename.glb")
join_objects: BoolProperty(name="Join Static Objects", default=False)
export_preset: StringProperty(name="Export Preset", default="")
bpy.utils.register_class(Export_Settings)
bpy.types.Scene.export_settings = PointerProperty(type=Export_Settings)
bpy.types.Scene.object_index = IntProperty(
name="Index for Visibility UI List", update=gui_functions.update_sel_item
)
bpy.types.Object.visibility_bool = BoolProperty(
name="Mapping for Property Value", update=gui_functions.remap_vis_prop, default=True
)
bpy.types.Scene.open_verification_menu = BoolProperty(default=False)
bpy.types.Scene.open_animation_manage = BoolProperty(default=False)
bpy.types.Scene.open_animation_particle = BoolProperty(default=False)
bpy.types.Scene.open_animation_simplifly = BoolProperty(default=False)
bpy.types.Scene.open_uv_animation_menu = BoolProperty(default=False)
class ParticleSettings(bpy.types.PropertyGroup):
key_loc: BoolProperty(name="Key Location", default=1)
key_rot: BoolProperty(name="Key Rotation", default=1)
key_scale: BoolProperty(name="Key Scale", default=1)
key_vis: BoolProperty(name="Key Visibility", default=0)
frame_offset: IntProperty(name="Frame Offset", default=1)
collection_name: StringProperty(name="Collection Name", default="Collection Name")
bpy.utils.register_class(ParticleSettings)
bpy.types.Scene.particle_settings = PointerProperty(type=ParticleSettings)
class AnimationSettings(bpy.types.PropertyGroup):
simplify_keyframes_modes = [
(
"RATIO",
"Ratio",
"Use a percentage to specify how many keyframes you want to remove.",
),
(
"ERROR",
"Error ",
"Use an error margin to specify how much the curve is allowed to deviate from the original path.",
),
]
simplify_keyframes_enum: EnumProperty(
name="Simplify Mode",
description="Choose mode to decimate keyframes",
items=simplify_keyframes_modes,
)
join_anim_name: StringProperty(name="Animation Name", default="Animation Name")
action_name: StringProperty(name="Action name", default="Action Name")
decimate_ratio: FloatProperty(name="Decimate Ratio", default=0.1)
bpy.utils.register_class(AnimationSettings)
bpy.types.Scene.animation_settings = PointerProperty(type=AnimationSettings)
def get_export_presets(self, context):
presets = []
presets.append(("none", "none", "Use selected export preset for export"))
# find all preset files for gltf exporter
preset_directory = Path(bpy.utils.preset_paths("operator/export_scene.gltf/")[0])
preset_files = glob.glob("*.py", root_dir=preset_directory.absolute())
for p in preset_files:
preset_name = p.split(".")[0]
presets.append(
(preset_name, preset_name, "Use selected export preset for export")
)
return presets
def update_presets(self, context):
scene = self
scene.export_settings.export_preset = scene.glb_preset_dropdown
bpy.types.Scene.glb_preset_dropdown = bpy.props.EnumProperty(
items=get_export_presets, name="Export Preset", update=update_presets
)
def register():
bpy.utils.register_class(Export_Settings)
bpy.utils.register_class(ParticleSettings)
bpy.utils.register_class(AnimationSettings)
def unregister():
bpy.utils.unregister_class(Export_Settings)
bpy.utils.unregister_class(ParticleSettings)
bpy.utils.unregister_class(AnimationSettings)
@@ -0,0 +1,4 @@
# Further information for the Blender Govie Tools
Documentation to all the functions of the add-on can be found on the [Govie Editor website](https://govie-editor.de/en/help/govie-tools/).
Please use the Github issues to report bugs or suggest new features.
@@ -0,0 +1,30 @@
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
port = int(sys.argv[2])
class RequestHandler(BaseHTTPRequestHandler):
file_path = sys.argv[1]
def _send_cors_headers(self):
"""Sets headers required for CORS"""
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Methods", "GET,POST,OPTIONS")
self.send_header("Access-Control-Allow-Headers", "x-api-key,Content-Type")
def do_GET(self):
self.send_response(200)
self._send_cors_headers()
self.end_headers()
with open(self.file_path, "rb") as file:
self.wfile.write(file.read())
response = {}
response["status"] = "OK"
httpd = HTTPServer(("127.0.0.1", port), RequestHandler)
print("Hosting server http://127.0.0.1:", port)
httpd.serve_forever()
@@ -0,0 +1,58 @@
# Copyright (c) 2024 Lorenz Wieseke via 3D Interaction Technologies GmbH
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTIBILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
from .Functions import functions
from .Operator import (
bake_particles,
join_animation,
operator,
preview_operator,
simplify_keyframes,
)
from .Panel import panel
bl_info = {
"name": "Govie Tools",
"author": "Lorenz Wieseke, 3D Interaction Technologies GmbH (contact@govie.de)",
"description": "Transform your model into a web-optimized GLB file for use in the Govie Editor.",
"blender": (4, 2, 0),
"version": (1, 0, 20),
"location": "View 3D > Property Panel (N-Key in 3D View)",
"warning": "",
"category": "Scene",
"wiki_url": "https://govie-editor.de/en/help/govie-tools?utm_source=blender-add-on&utm_medium=button",
"tracker_url": "https://github.com/3Dit-GmbH/GovieTools/issues",
}
def register():
bake_particles.register()
join_animation.register()
preview_operator.register()
simplify_keyframes.register()
operator.register()
panel.register()
functions.get_addon_dir(os.path.realpath(__file__))
def unregister():
bake_particles.unregister()
join_animation.unregister()
preview_operator.unregister()
simplify_keyframes.unregister()
operator.unregister()
panel.unregister()
functions.stop_server()
@@ -0,0 +1,25 @@
schema_version = "1.0.0"
id = "govietools"
version = "1.0.20"
name = "Govie Tools"
tagline = "Optimize your model for use in the Govie Editor"
maintainer = "Stefan Bernstein, 3D Interaction Technologies GmbH <contact@govie.de>"
type = "add-on"
website = "https://govie-editor.de/help/govie-tools/"
tags = ["Scene", "Import-Export"]
blender_version_min = "4.2.0"
license = [
"SPDX:GPL-3.0-or-later"
]
copyright = [
"2024 Lorenz Wieseke via 3D Interaction Technologies GmbH"
]
[permissions]
files = "Export GLB to disk"
@@ -0,0 +1,7 @@
[project]
name = "govietools"
version = "1.0.20"
description = "Optimize your model for use in the Govie Editor"
readme = "README.md"
requires-python = ">=3.11.13"
dependencies = []

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