diff options
Diffstat (limited to 'add_mesh_extra_objects')
-rw-r--r-- | add_mesh_extra_objects/__init__.py | 134 | ||||
-rw-r--r-- | add_mesh_extra_objects/add_mesh_3d_function_surface.py | 617 | ||||
-rw-r--r-- | add_mesh_extra_objects/add_mesh_extra_objects.py | 490 | ||||
-rw-r--r-- | add_mesh_extra_objects/add_mesh_gears.py | 798 | ||||
-rw-r--r-- | add_mesh_extra_objects/add_mesh_gemstones.py | 331 | ||||
-rw-r--r-- | add_mesh_extra_objects/add_mesh_twisted_torus.py | 250 |
6 files changed, 2620 insertions, 0 deletions
diff --git a/add_mesh_extra_objects/__init__.py b/add_mesh_extra_objects/__init__.py new file mode 100644 index 00000000..ad231d02 --- /dev/null +++ b/add_mesh_extra_objects/__init__.py @@ -0,0 +1,134 @@ +# ##### 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 2 +# 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": "Extra Objects", + "author": "Pontiac, Fourmadmen, varkenvarken, tuga3d, meta-androcto", + "version": (0, 1), + "blender": (2, 5, 7), + "api": 35853, + "location": "View3D > Add > Mesh > Extra Objects", + "description": "Adds More Object Types.", + "warning": "", + "wiki_url": "http://wiki.blender.org/index.php/Extensions:2.5/Py/"\ + "Scripts/Add_Mesh/Add_Extra", + "tracker_url": "http://projects.blender.org/tracker/index.php?"\ + "func=detail&aid=22457", + "category": "Add Mesh"} + + +if "bpy" in locals(): + import imp + imp.reload(add_mesh_extra_objects) + imp.reload(add_mesh_twisted_torus) + imp.reload(add_mesh_gemstones) + imp.reload(add_mesh_gears) + imp.reload(add_mesh_3d_function_surface) +else: + from . import add_mesh_extra_objects + from . import add_mesh_twisted_torus + from . import add_mesh_gemstones + from . import add_mesh_gears + from . import add_mesh_3d_function_surface + +import bpy + + +class INFO_MT_mesh_extras_add(bpy.types.Menu): + # Define the "Extras" menu + bl_idname = "INFO_MT_mesh_extra_objects_add" + bl_label = "Extra Objects" + + def draw(self, context): + layout = self.layout + layout.operator_context = 'INVOKE_REGION_WIN' + layout.menu("INFO_MT_mesh_gemstones_add", text="Gemstones") + layout.menu("INFO_MT_mesh_gears_add", text="Gears") + layout.menu("INFO_MT_mesh_math_add", text="Math Function") + layout.operator("mesh.primitive_twisted_torus_add", + text="Twisted Torus") + layout.operator("mesh.primitive_sqorus_add", + text="Sqorus") + layout.operator("mesh.primitive_wedge_add") + layout.operator("mesh.primitive_star_add", + text="Star") + layout.operator("mesh.primitive_trapezohedron_add", + text="Trapezohedron") + +class INFO_MT_mesh_gemstones_add(bpy.types.Menu): + # Define the "Gemstones" menu + bl_idname = "INFO_MT_mesh_gemstones_add" + bl_label = "Gemstones" + + def draw(self, context): + layout = self.layout + layout.operator_context = 'INVOKE_REGION_WIN' + layout.operator("mesh.primitive_diamond_add", + text="Diamond") + layout.operator("mesh.primitive_gem_add", + text="Gem") + + +class INFO_MT_mesh_gears_add(bpy.types.Menu): + # Define the "Gears" menu + bl_idname = "INFO_MT_mesh_gears_add" + bl_label = "Gears" + + def draw(self, context): + layout = self.layout + layout.operator_context = 'INVOKE_REGION_WIN' + layout.operator("mesh.primitive_gear", + text="Gear") + layout.operator("mesh.primitive_worm_gear", + text="Worm") + +class INFO_MT_mesh_math_add(bpy.types.Menu): + # Define the "Math Function" menu + bl_idname = "INFO_MT_mesh_math_add" + bl_label = "Math Functions" + + def draw(self, context): + layout = self.layout + layout.operator_context = 'INVOKE_REGION_WIN' + layout.operator("mesh.primitive_z_function_surface", + text="Z Math Surface") + layout.operator("mesh.primitive_xyz_function_surface", + text="XYZ Math Surface") + +# Register all operators and panels + +# Define "Extras" menu +def menu_func(self, context): + self.layout.menu("INFO_MT_mesh_extra_objects_add", icon="PLUGIN") + + +def register(): + bpy.utils.register_module(__name__) + + # Add "Extras" menu to the "Add Mesh" menu + bpy.types.INFO_MT_mesh_add.append(menu_func) + + +def unregister(): + bpy.utils.unregister_module(__name__) + + # Remove "Extras" menu from the "Add Mesh" menu. + bpy.types.INFO_MT_mesh_add.remove(menu_func) + +if __name__ == "__main__": + register() diff --git a/add_mesh_extra_objects/add_mesh_3d_function_surface.py b/add_mesh_extra_objects/add_mesh_3d_function_surface.py new file mode 100644 index 00000000..8965a820 --- /dev/null +++ b/add_mesh_extra_objects/add_mesh_3d_function_surface.py @@ -0,0 +1,617 @@ +# ##### 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 2 +# 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": "3D Function Surfaces", + "author": "Buerbaum Martin (Pontiac), Elod Csirmaz", + "version": (0, 3, 8), + "blender": (2, 5, 7), + "api": 37329, + "location": "View3D > Add > Mesh", + "description": "Create Objects using Math Formulas", + "warning": "", + "wiki_url": "http://wiki.blender.org/index.php/Extensions:2.5/Py/"\ + "Scripts/Add_Mesh/Add_3d_Function_Surface", + "tracker_url": "https://projects.blender.org/tracker/index.php?"\ + "func=detail&aid=21444", + "category": "Add Mesh"} +""" +""" +Z Function Surface + +This script lets the user create a surface where the z coordinate +is a function of the x and y coordinates. + + z = F1(x,y) + +X,Y,Z Function Surface + +This script lets the user create a surface where the x, y and z +coordinates are defiend by a function. + + x = F1(u,v) + y = F2(u,v) + z = F3(u,v) + +Usage: +You have to activated the script in the "Add-Ons" tab (user preferences). +The functionality can then be accessed via the +"Add Mesh" -> "Z Function Surface" +and +"Add Mesh" -> "X,Y,Z Function Surface" +menu. + +Version history: +v0.3.8 - Patch by Elod Csirmaz + Modified the "Add X,Y,Z Function Surface" part: + Changed how wrapping is done to avoid + generating unnecessary vertices and make the result more intuitive. + Added helper functions the results of which can be used in + x(u,v), y(u,v), z(u,v). + The script can now close the ends of an U-wrapped surface. + It's now possible to create multiple objects with one set of formulae. +v0.3.7 + Removed the various "edit" properties - not used anymore. + Use generic tracker URL (Blender-Extensions r1369) + bl_addon_info now called bl_info + Removed align_matrix + create_mesh_object now doesn't handle editmode. (See create_mesh_object) + This script is now used by the "Extra Objects" script +v0.3.6 - Various updates to match current Blender API. + Removed recall functionality. + Better code for align_matrix + Hopefully fixed bug where uMax was never reached. May cause other stuff. +v0.3.5 - createFaces can now "Flip" faces and create fan/star like faces. +v0.3.4 - Updated store_recall_properties, apply_object_align + and create_mesh_object. + Changed how recall data is stored. +v0.3.3 - API change Mathutils -> mathutils (r557) +v0.3.2 - Various fixes&streamlining by ideasman42/Campbell Barton. + r544 Compile expressions for faster execution + r544 Use operator reports for errors too + r544 Avoid type checks by converting to a float, errors + converting to a float are reported too. + Fixed an error Campbell overlooked (appending tuples to an + array, not single values) Thamnks for the report wild_doogy. + Added 'description' field, updated 'wiki_url'. + Made the script PEP8 compatible again. +v0.3.1 - Use hidden "edit" property for "recall" operator. + Bugfix: Z Function was mixing up div_x and div_y +v0.3 - X,Y,Z Function Surface (by Ed Mackey & tuga3d). + Renamed old function to "Z Function Surface". + Align the geometry to the view if the user preference says so. + Store recall properties in newly created object. +v0.2.3 - Use bl_info for Add-On information. +v0.2.2 - Fixed Add-On registration text. +v0.2.1 - Fixed some new API stuff. + Mainly we now have the register/unregister functions. + Also the new() function for objects now accepts a mesh object. + Changed the script so it can be managed from the "Add-Ons" tab + in the user preferences. + Added dummy "PLUGIN" icon. + Corrected FSF address. + Clean up of tooltips. +v0.2 - Added security check for eval() function + Check return value of eval() for complex numbers. +v0.1.1 - Use 'CANCELLED' return value when failing. + Updated web links. +v0.1 - Initial revision. +More Links: +http://gitorious.org/blender-scripts/blender-3d-function-surface +http://blenderartists.org/forum/showthread.php?t=179043 +""" +import bpy +from mathutils import * +from math import * +from bpy.props import * + +# List of safe functions for eval() +safe_list = ['math', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', + 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', + 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', + 'sin', 'sinh', 'sqrt', 'tan', 'tanh'] + +# Use the list to filter the local namespace +safe_dict = dict((k, globals().get(k, None)) for k in safe_list) + + +# Stores the values of a list of properties and the +# operator id in a property group ('recall_op') inside the object. +# Could (in theory) be used for non-objects. +# Note: Replaces any existing property group with the same name! +# ob ... Object to store the properties in. +# op ... The operator that should be used. +# op_args ... A dictionary with valid Blender +# properties (operator arguments/parameters). + + +# Create a new mesh (object) from verts/edges/faces. +# verts/edges/faces ... List of vertices/edges/faces for the +# new mesh (as used in from_pydata). +# name ... Name of the new mesh (& object). +def create_mesh_object(context, verts, edges, faces, name): + + # Create new mesh + mesh = bpy.data.meshes.new(name) + + # Make a mesh from a list of verts/edges/faces. + mesh.from_pydata(verts, edges, faces) + + # Update mesh geometry after adding stuff. + mesh.update() + + from bpy_extras import object_utils + return object_utils.object_data_add(context, mesh, operator=None) + + +# A very simple "bridge" tool. +# Connects two equally long vertex rows with faces. +# Returns a list of the new faces (list of lists) +# +# vertIdx1 ... First vertex list (list of vertex indices). +# vertIdx2 ... Second vertex list (list of vertex indices). +# closed ... Creates a loop (first & last are closed). +# flipped ... Invert the normal of the face(s). +# +# Note: You can set vertIdx1 to a single vertex index to create +# a fan/star of faces. +# Note: If both vertex idx list are the same length they have +# to have at least 2 vertices. +def createFaces(vertIdx1, vertIdx2, closed=False, flipped=False): + faces = [] + + if not vertIdx1 or not vertIdx2: + return None + + if len(vertIdx1) < 2 and len(vertIdx2) < 2: + return None + + fan = False + if (len(vertIdx1) != len(vertIdx2)): + if (len(vertIdx1) == 1 and len(vertIdx2) > 1): + fan = True + else: + return None + + total = len(vertIdx2) + + if closed: + # Bridge the start with the end. + if flipped: + face = [ + vertIdx1[0], + vertIdx2[0], + vertIdx2[total - 1]] + if not fan: + face.append(vertIdx1[total - 1]) + faces.append(face) + + else: + face = [vertIdx2[0], vertIdx1[0]] + if not fan: + face.append(vertIdx1[total - 1]) + face.append(vertIdx2[total - 1]) + faces.append(face) + + # Bridge the rest of the faces. + for num in range(total - 1): + if flipped: + if fan: + face = [vertIdx2[num], vertIdx1[0], vertIdx2[num + 1]] + else: + face = [vertIdx2[num], vertIdx1[num], + vertIdx1[num + 1], vertIdx2[num + 1]] + faces.append(face) + else: + if fan: + face = [vertIdx1[0], vertIdx2[num], vertIdx2[num + 1]] + else: + face = [vertIdx1[num], vertIdx2[num], + vertIdx2[num + 1], vertIdx1[num + 1]] + faces.append(face) + + return faces + + +class AddZFunctionSurface(bpy.types.Operator): + '''Add a surface defined defined by a function z=f(x,y)''' + bl_idname = "mesh.primitive_z_function_surface" + bl_label = "Add Z Function Surface" + bl_options = {'REGISTER', 'UNDO'} + + equation = StringProperty(name="Z Equation", + description="Equation for z=f(x,y)", + default="1 - ( x**2 + y**2 )") + + div_x = IntProperty(name="X Subdivisions", + description="Number of vertices in x direction.", + default=16, + min=3, + max=256) + div_y = IntProperty(name="Y Subdivisions", + description="Number of vertices in y direction.", + default=16, + min=3, + max=256) + + size_x = FloatProperty(name="X Size", + description="Size of the x axis.", + default=2.0, + min=0.01, + max=100.0, + unit="LENGTH") + size_y = FloatProperty(name="Y Size", + description="Size of the y axis.", + default=2.0, + min=0.01, + max=100.0, + unit="LENGTH") + + def execute(self, context): + equation = self.equation + div_x = self.div_x + div_y = self.div_y + size_x = self.size_x + size_y = self.size_y + + verts = [] + faces = [] + + delta_x = size_x / float(div_x - 1) + delta_y = size_y / float(div_y - 1) + start_x = -(size_x / 2.0) + start_y = -(size_y / 2.0) + + edgeloop_prev = [] + + try: + expr_args = ( + compile(equation, __file__, 'eval'), + {"__builtins__": None}, + safe_dict) + except: + import traceback + self.report({'ERROR'}, "Error parsing expression: " + + traceback.format_exc(limit=1)) + return {'CANCELLED'} + + for row_x in range(div_x): + edgeloop_cur = [] + x = start_x + row_x * delta_x + + for row_y in range(div_y): + y = start_y + row_y * delta_y + z = 0.0 + + safe_dict['x'] = x + safe_dict['y'] = y + + # Try to evaluate the equation. + try: + z = float(eval(*expr_args)) + except: + import traceback + self.report({'ERROR'}, "Error evaluating expression: " + + traceback.format_exc(limit=1)) + return {'CANCELLED'} + + edgeloop_cur.append(len(verts)) + verts.append((x, y, z)) + + if len(edgeloop_prev) > 0: + faces_row = createFaces(edgeloop_prev, edgeloop_cur) + faces.extend(faces_row) + + edgeloop_prev = edgeloop_cur + + base = create_mesh_object(context, verts, [], faces, "Z Function") + + return {'FINISHED'} + + +def xyz_function_surface_faces(self, x_eq, y_eq, z_eq, + range_u_min, range_u_max, range_u_step, wrap_u, + range_v_min, range_v_max, range_v_step, wrap_v, + a_eq, b_eq, c_eq, f_eq, g_eq, h_eq, n, close_v): + + verts = [] + faces = [] + + # Distance of each step in Blender Units + uStep = (range_u_max - range_u_min) / range_u_step + vStep = (range_v_max - range_v_min) / range_v_step + + # Number of steps in the vertex creation loops. + # Number of steps is the number of faces + # => Number of points is +1 unless wrapped. + uRange = range_u_step + 1 + vRange = range_v_step + 1 + + if wrap_u: + uRange = uRange - 1 + + if wrap_v: + vRange = vRange - 1 + + try: + expr_args_x = ( + compile(x_eq, __file__.replace(".py", "_x.py"), 'eval'), + {"__builtins__": None}, + safe_dict) + expr_args_y = ( + compile(y_eq, __file__.replace(".py", "_y.py"), 'eval'), + {"__builtins__": None}, + safe_dict) + expr_args_z = ( + compile(z_eq, __file__.replace(".py", "_z.py"), 'eval'), + {"__builtins__": None}, + safe_dict) + expr_args_a = ( + compile(a_eq, __file__.replace(".py", "_a.py"), 'eval'), + {"__builtins__": None}, + safe_dict) + expr_args_b = ( + compile(b_eq, __file__.replace(".py", "_b.py"), 'eval'), + {"__builtins__": None}, + safe_dict) + expr_args_c = ( + compile(c_eq, __file__.replace(".py", "_c.py"), 'eval'), + {"__builtins__": None}, + safe_dict) + expr_args_f = ( + compile(f_eq, __file__.replace(".py", "_f.py"), 'eval'), + {"__builtins__": None}, + safe_dict) + expr_args_g = ( + compile(g_eq, __file__.replace(".py", "_g.py"), 'eval'), + {"__builtins__": None}, + safe_dict) + expr_args_h = ( + compile(h_eq, __file__.replace(".py", "_h.py"), 'eval'), + {"__builtins__": None}, + safe_dict) + except: + import traceback + self.report({'ERROR'}, "Error parsing expression: " + + traceback.format_exc(limit=1)) + return [], [] + + for vN in range(vRange): + v = range_v_min + (vN * vStep) + + for uN in range(uRange): + u = range_u_min + (uN * uStep) + + safe_dict['u'] = u + safe_dict['v'] = v + + safe_dict['n'] = n + + # Try to evaluate the equations. + try: + a = float(eval(*expr_args_a)) + b = float(eval(*expr_args_b)) + c = float(eval(*expr_args_c)) + + safe_dict['a'] = a + safe_dict['b'] = b + safe_dict['c'] = c + + f = float(eval(*expr_args_f)) + g = float(eval(*expr_args_g)) + h = float(eval(*expr_args_h)) + + safe_dict['f'] = f + safe_dict['g'] = g + safe_dict['h'] = h + + verts.append(( + float(eval(*expr_args_x)), + float(eval(*expr_args_y)), + float(eval(*expr_args_z)))) + + except: + import traceback + self.report({'ERROR'}, "Error evaluating expression: " + + traceback.format_exc(limit=1)) + return [], [] + + for vN in range(range_v_step): + vNext = vN + 1 + + if wrap_v and (vNext >= vRange): + vNext = 0 + + for uN in range(range_u_step): + uNext = uN + 1 + + if wrap_u and (uNext >= uRange): + uNext = 0 + + faces.append([(vNext * uRange) + uNext, + (vNext * uRange) + uN, + (vN * uRange) + uN, + (vN * uRange) + uNext]) + + if close_v and wrap_u and (not wrap_v): + for uN in range(1, range_u_step - 1): + faces.append([ + range_u_step - 1, + range_u_step - 1 - uN, + range_u_step - 2 - uN]) + faces.append([ + range_v_step * uRange, + range_v_step * uRange + uN, + range_v_step * uRange + uN + 1]) + + return verts, faces + + +# Original Script "Parametric.py" by Ed Mackey. +# -> http://www.blinken.com/blender-plugins.php +# Partly converted for Blender 2.5 by tuga3d. +# +# Sphere: +# x = sin(2*pi*u)*sin(pi*v) +# y = cos(2*pi*u)*sin(pi*v) +# z = cos(pi*v) +# u_min = v_min = 0 +# u_max = v_max = 1 +# +# "Snail shell" +# x = 1.2**v*(sin(u)**2 *sin(v)) +# y = 1.2**v*(sin(u)*cos(u)) +# z = 1.2**v*(sin(u)**2 *cos(v)) +# u_min = 0 +# u_max = pi +# v_min = -pi/4, +# v max = 5*pi/2 +class AddXYZFunctionSurface(bpy.types.Operator): + '''Add a surface defined defined by 3 functions:''' \ + + ''' x=F1(u,v), y=F2(u,v) and z=F3(u,v)''' + bl_idname = "mesh.primitive_xyz_function_surface" + bl_label = "Add X,Y,Z Function Surface" + bl_options = {'REGISTER', 'UNDO'} + + x_eq = StringProperty(name="X equation", + description="Equation for x=F(u,v). " \ + "Also available: n, a, b, c, f, g, h", + default="cos(v)*(1+cos(u))*sin(v/8)") + + y_eq = StringProperty(name="Y equation", + description="Equation for y=F(u,v). " \ + "Also available: n, a, b, c, f, g, h", + default="sin(u)*sin(v/8)+cos(v/8)*1.5") + + z_eq = StringProperty(name="Z equation", + description="Equation for z=F(u,v). " \ + "Also available: n, a, b, c, f, g, h", + default="sin(v)*(1+cos(u))*sin(v/8)") + + range_u_min = FloatProperty(name="U min", + description="Minimum U value. Lower boundary of U range.", + min=-100.00, + max=0.00, + default=0.00) + + range_u_max = FloatProperty(name="U max", + description="Maximum U value. Upper boundary of U range.", + min=0.00, + max=100.00, + default=2 * pi) + + range_u_step = IntProperty(name="U step", + description="U Subdivisions", + min=1, + max=1024, + default=32) + + wrap_u = BoolProperty(name="U wrap", + description="U Wrap around", + default=True) + + range_v_min = FloatProperty(name="V min", + description="Minimum V value. Lower boundary of V range.", + min=-100.00, + max=0.00, + default=0.00) + + range_v_max = FloatProperty(name="V max", + description="Maximum V value. Upper boundary of V range.", + min=0.00, + max=100.00, + default=4 * pi) + + range_v_step = IntProperty(name="V step", + description="V Subdivisions", + min=1, + max=1024, + default=128) + + wrap_v = BoolProperty(name="V wrap", + description="V Wrap around", + default=False) + + close_v = BoolProperty(name="Close V", + description="Create faces for first and last " \ + "V values (only if U is wrapped)", + default=False) + + n_eq = IntProperty(name="Number of objects (n=0..N-1)", + description="The parameter n will be the index " \ + "of the current object, 0 to N-1", + min=1, + max=100, + default=1) + + a_eq = StringProperty(name="A helper function", + description="Equation for a=F(u,v). Also available: n", + default="0") + + b_eq = StringProperty(name="B helper function", + description="Equation for b=F(u,v). Also available: n", + default="0") + + c_eq = StringProperty(name="C helper function", + description="Equation for c=F(u,v). Also available: n", + default="0") + + f_eq = StringProperty(name="F helper function", + description="Equation for f=F(u,v). Also available: n, a, b, c", + default="0") + + g_eq = StringProperty(name="G helper function", + description="Equation for g=F(u,v). Also available: n, a, b, c", + default="0") + + h_eq = StringProperty(name="H helper function", + description="Equation for h=F(u,v). Also available: n, a, b, c", + default="0") + + def execute(self, context): + + for n in range(0, self.n_eq): + + verts, faces = xyz_function_surface_faces( + self, + self.x_eq, + self.y_eq, + self.z_eq, + self.range_u_min, + self.range_u_max, + self.range_u_step, + self.wrap_u, + self.range_v_min, + self.range_v_max, + self.range_v_step, + self.wrap_v, + self.a_eq, + self.b_eq, + self.c_eq, + self.f_eq, + self.g_eq, + self.h_eq, + n, + self.close_v) + + if not verts: + return {'CANCELLED'} + + obj = create_mesh_object(context, verts, [], faces, "XYZ Function") + + return {'FINISHED'} diff --git a/add_mesh_extra_objects/add_mesh_extra_objects.py b/add_mesh_extra_objects/add_mesh_extra_objects.py new file mode 100644 index 00000000..c545056a --- /dev/null +++ b/add_mesh_extra_objects/add_mesh_extra_objects.py @@ -0,0 +1,490 @@ +# ##### 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 2 +# 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 bpy +from mathutils import * +from math import * +from bpy.props import * + +# Create a new mesh (object) from verts/edges/faces. +# verts/edges/faces ... List of vertices/edges/faces for the +# new mesh (as used in from_pydata). +# name ... Name of the new mesh (& object). +def create_mesh_object(context, verts, edges, faces, name): + + # Create new mesh + mesh = bpy.data.meshes.new(name) + + # Make a mesh from a list of verts/edges/faces. + mesh.from_pydata(verts, edges, faces) + + # Update mesh geometry after adding stuff. + mesh.update() + + from bpy_extras import object_utils + return object_utils.object_data_add(context, mesh, operator=None) + + +# A very simple "bridge" tool. +# Connects two equally long vertex rows with faces. +# Returns a list of the new faces (list of lists) +# +# vertIdx1 ... First vertex list (list of vertex indices). +# vertIdx2 ... Second vertex list (list of vertex indices). +# closed ... Creates a loop (first & last are closed). +# flipped ... Invert the normal of the face(s). +# +# Note: You can set vertIdx1 to a single vertex index to create +# a fan/star of faces. +# Note: If both vertex idx list are the same length they have +# to have at least 2 vertices. +def createFaces(vertIdx1, vertIdx2, closed=False, flipped=False): + faces = [] + + if not vertIdx1 or not vertIdx2: + return None + + if len(vertIdx1) < 2 and len(vertIdx2) < 2: + return None + + fan = False + if (len(vertIdx1) != len(vertIdx2)): + if (len(vertIdx1) == 1 and len(vertIdx2) > 1): + fan = True + else: + return None + + total = len(vertIdx2) + + if closed: + # Bridge the start with the end. + if flipped: + face = [ + vertIdx1[0], + vertIdx2[0], + vertIdx2[total - 1]] + if not fan: + face.append(vertIdx1[total - 1]) + faces.append(face) + + else: + face = [vertIdx2[0], vertIdx1[0]] + if not fan: + face.append(vertIdx1[total - 1]) + face.append(vertIdx2[total - 1]) + faces.append(face) + + # Bridge the rest of the faces. + for num in range(total - 1): + if flipped: + if fan: + face = [vertIdx2[num], vertIdx1[0], vertIdx2[num + 1]] + else: + face = [vertIdx2[num], vertIdx1[num], + vertIdx1[num + 1], vertIdx2[num + 1]] + faces.append(face) + else: + if fan: + face = [vertIdx1[0], vertIdx2[num], vertIdx2[num + 1]] + else: + face = [vertIdx1[num], vertIdx2[num], + vertIdx2[num + 1], vertIdx1[num + 1]] + faces.append(face) + + return faces + + +# @todo Clean up vertex&face creation process a bit. +def add_sqorus(hole_size, subdivide): + verts = [] + faces = [] + + size = 2.0 + + thickness = (size - hole_size) / 2.0 + distances = [ + -size / 2.0, + -size / 2.0 + thickness, + size / 2.0 - thickness, + size / 2.0] + + if subdivide: + for i in range(4): + y = distances[i] + + for j in range(4): + x = distances[j] + + verts.append(Vector((x, y, size / 2.0))) + verts.append(Vector((x, y, -size / 2.0))) + + # Top outer loop (vertex indices) + vIdx_out_up = [0, 2, 4, 6, 14, 22, 30, 28, 26, 24, 16, 8] + # Lower outer loop (vertex indices) + vIdx_out_low = [i + 1 for i in vIdx_out_up] + + faces_outside = createFaces(vIdx_out_up, vIdx_out_low, closed=True) + faces.extend(faces_outside) + + # Top inner loop (vertex indices) + vIdx_inner_up = [10, 12, 20, 18] + + # Lower inner loop (vertex indices) + vIdx_inner_low = [i + 1 for i in vIdx_inner_up] + + faces_inside = createFaces(vIdx_inner_up, vIdx_inner_low, + closed=True, flipped=True) + faces.extend(faces_inside) + + row1_top = [0, 8, 16, 24] + row2_top = [i + 2 for i in row1_top] + row3_top = [i + 2 for i in row2_top] + row4_top = [i + 2 for i in row3_top] + + faces_top1 = createFaces(row1_top, row2_top) + faces.extend(faces_top1) + faces_top2_side1 = createFaces(row2_top[:2], row3_top[:2]) + faces.extend(faces_top2_side1) + faces_top2_side2 = createFaces(row2_top[2:], row3_top[2:]) + faces.extend(faces_top2_side2) + faces_top3 = createFaces(row3_top, row4_top) + faces.extend(faces_top3) + + row1_bot = [1, 9, 17, 25] + row2_bot = [i + 2 for i in row1_bot] + row3_bot = [i + 2 for i in row2_bot] + row4_bot = [i + 2 for i in row3_bot] + + faces_bot1 = createFaces(row1_bot, row2_bot, flipped=True) + faces.extend(faces_bot1) + faces_bot2_side1 = createFaces(row2_bot[:2], row3_bot[:2], + flipped=True) + faces.extend(faces_bot2_side1) + faces_bot2_side2 = createFaces(row2_bot[2:], row3_bot[2:], + flipped=True) + faces.extend(faces_bot2_side2) + faces_bot3 = createFaces(row3_bot, row4_bot, flipped=True) + faces.extend(faces_bot3) + + else: + # Do not subdivde outer faces + + vIdx_out_up = [] + vIdx_out_low = [] + vIdx_in_up = [] + vIdx_in_low = [] + + for i in range(4): + y = distances[i] + + for j in range(4): + x = distances[j] + + append = False + inner = False + # Outer + if (i in [0, 3] and j in [0, 3]): + append = True + + # Inner + if (i in [1, 2] and j in [1, 2]): + append = True + inner = True + + if append: + vert_up = len(verts) + verts.append(Vector((x, y, size / 2.0))) + vert_low = len(verts) + verts.append(Vector((x, y, -size / 2.0))) + + if inner: + vIdx_in_up.append(vert_up) + vIdx_in_low.append(vert_low) + + else: + vIdx_out_up.append(vert_up) + vIdx_out_low.append(vert_low) + + # Flip last two vertices + vIdx_out_up = vIdx_out_up[:2] + list(reversed(vIdx_out_up[2:])) + vIdx_out_low = vIdx_out_low[:2] + list(reversed(vIdx_out_low[2:])) + vIdx_in_up = vIdx_in_up[:2] + list(reversed(vIdx_in_up[2:])) + vIdx_in_low = vIdx_in_low[:2] + list(reversed(vIdx_in_low[2:])) + + # Create faces + faces_top = createFaces(vIdx_in_up, vIdx_out_up, closed=True) + faces.extend(faces_top) + faces_bottom = createFaces(vIdx_out_low, vIdx_in_low, closed=True) + faces.extend(faces_bottom) + faces_inside = createFaces(vIdx_in_low, vIdx_in_up, closed=True) + faces.extend(faces_inside) + faces_outside = createFaces(vIdx_out_up, vIdx_out_low, closed=True) + faces.extend(faces_outside) + + return verts, faces + + +def add_wedge(size_x, size_y, size_z): + verts = [] + faces = [] + + size_x /= 2.0 + size_y /= 2.0 + size_z /= 2.0 + + vIdx_top = [] + vIdx_bot = [] + + vIdx_top.append(len(verts)) + verts.append(Vector((-size_x, -size_y, size_z))) + vIdx_bot.append(len(verts)) + verts.append(Vector((-size_x, -size_y, -size_z))) + + vIdx_top.append(len(verts)) + verts.append(Vector((size_x, -size_y, size_z))) + vIdx_bot.append(len(verts)) + verts.append(Vector((size_x, -size_y, -size_z))) + + vIdx_top.append(len(verts)) + verts.append(Vector((-size_x, size_y, size_z))) + vIdx_bot.append(len(verts)) + verts.append(Vector((-size_x, size_y, -size_z))) + + faces.append(vIdx_top) + faces.append(vIdx_bot) + faces_outside = createFaces(vIdx_top, vIdx_bot, closed=True) + faces.extend(faces_outside) + + return verts, faces + +def add_star(points, outer_radius, inner_radius, height): + PI_2 = pi * 2 + z_axis = (0, 0, 1) + + verts = [] + faces = [] + + segments = points * 2 + + half_height = height / 2.0 + + vert_idx_top = len(verts) + verts.append(Vector((0.0, 0.0, half_height))) + + vert_idx_bottom = len(verts) + verts.append(Vector((0.0, 0.0, -half_height))) + + edgeloop_top = [] + edgeloop_bottom = [] + + for index in range(segments): + quat = Quaternion(z_axis, (index / segments) * PI_2) + + if index % 2: + # Uneven + radius = outer_radius + else: + # Even + radius = inner_radius + + edgeloop_top.append(len(verts)) + vec = quat * Vector((radius, 0, half_height)) + verts.append(vec) + + edgeloop_bottom.append(len(verts)) + vec = quat * Vector((radius, 0, -half_height)) + verts.append(vec) + + + + faces_top = createFaces([vert_idx_top], edgeloop_top, closed=True) + faces_outside = createFaces(edgeloop_top, edgeloop_bottom, closed=True) + faces_bottom = createFaces([vert_idx_bottom], edgeloop_bottom, + flipped=True, closed=True) + + faces.extend(faces_top) + faces.extend(faces_outside) + faces.extend(faces_bottom) + + return verts, faces + +def trapezohedron(s,r,h): + """ + s = segments + r = base radius + h = tip height + """ + + # calculate constants + a = 2*pi/(2*s) # angle between points along the equator + l = r*cos(a) # helper for e + e = h*(r-l)/(l+r) # the z offset for each vector along the equator so faces are planar + + # rotation for the points + quat = Quaternion((0,0,1),a) + + # first 3 vectors, every next one is calculated from the last, and the z-value is negated + verts = [Vector(i) for i in [(0,0,h),(0,0,-h),(r,0,e)]] + for i in range(2*s-1): + verts.append(quat*verts[-1]) # rotate further "a" radians around the z-axis + verts[-1].z *= -1 # negate last z-value to account for the zigzag + + faces = [] + for i in range(2,2+2*s,2): + n = [i+1,i+2,i+3] # vertices in current section + for j in range(3): # check whether the numbers dont go over len(verts) + if n[j]>=2*s+2: n[j]-=2*s # if so, subtract len(verts)-2 + + # add faces of current section + faces.append([0,i]+n[:2]) + faces.append([1,n[2],n[1],n[0]]) + + return verts,faces + +class AddSqorus(bpy.types.Operator): + '''Add a sqorus mesh.''' + bl_idname = "mesh.primitive_sqorus_add" + bl_label = "Add Sqorus" + bl_options = {'REGISTER', 'UNDO'} + + hole_size = FloatProperty(name="Hole Size", + description="Size of the Hole", + min=0.01, + max=1.99, + default=2.0 / 3.0) + subdivide = BoolProperty(name="Subdivide Outside", + description="Enable to subdivide the faces on the outside." \ + " This results in equally spaced vertices.", + default=True) + + def execute(self, context): + + # Create mesh geometry + verts, faces = add_sqorus( + self.hole_size, + self.subdivide) + + # Create mesh object (and meshdata) + obj = create_mesh_object(context, verts, [], faces, "Sqorus") + + return {'FINISHED'} + + +class AddWedge(bpy.types.Operator): + '''Add a wedge mesh.''' + bl_idname = "mesh.primitive_wedge_add" + bl_label = "Add Wedge" + bl_options = {'REGISTER', 'UNDO'} + + size_x = FloatProperty(name="Size X", + description="Size along the X axis", + min=0.01, + max=9999.0, + default=2.0) + size_y = FloatProperty(name="Size Y", + description="Size along the Y axis", + min=0.01, + max=9999.0, + default=2.0) + size_z = FloatProperty(name="Size Z", + description="Size along the Z axis", + min=0.01, + max=9999.0, + default=2.00) + + def execute(self, context): + + verts, faces = add_wedge( + self.size_x, + self.size_y, + self.size_z) + + obj = create_mesh_object(context, verts, [], faces, "Wedge") + + return {'FINISHED'} + + +class AddStar(bpy.types.Operator): + '''Add a star mesh.''' + bl_idname = "mesh.primitive_star_add" + bl_label = "Add Star" + bl_options = {'REGISTER', 'UNDO'} + + points = IntProperty(name="Points", + description="Number of points for the star", + min=2, + max=256, + default=5) + outer_radius = FloatProperty(name="Outer Radius", + description="Outer radius of the star", + min=0.01, + max=9999.0, + default=1.0) + innter_radius = FloatProperty(name="Inner Radius", + description="Inner radius of the star", + min=0.01, + max=9999.0, + default=0.5) + height = FloatProperty(name="Height", + description="Height of the star", + min=0.01, + max=9999.0, + default=0.5) + + def execute(self, context): + + verts, faces = add_star( + self.points, + self.outer_radius, + self.innter_radius, + self.height) + + obj = create_mesh_object(context, verts, [], faces, "Star") + + return {'FINISHED'} + + +class AddTrapezohedron(bpy.types.Operator): + """Add a trapezohedron""" + bl_idname = "mesh.primitive_trapezohedron_add" + bl_label = "Add trapezohedron" + bl_description = "Create one of the regular solids" + bl_options = {'REGISTER', 'UNDO'} + + segments = IntProperty(name = "Segments", + description = "Number of repeated segments", + default = 4, min = 2, max = 256) + radius = FloatProperty(name = "Base radius", + description = "Radius of the middle", + default = 1.0, min = 0.01, max = 100.0) + height = FloatProperty(name = "Tip height", + description = "Height of the tip", + default = 1, min = 0.01, max = 100.0) + + def execute(self,context): + # generate mesh + verts,faces = trapezohedron(self.segments, + self.radius, + self.height) + + obj = create_mesh_object(context, verts, [], faces, "Trapazohedron") + + return {'FINISHED'} + + + diff --git a/add_mesh_extra_objects/add_mesh_gears.py b/add_mesh_extra_objects/add_mesh_gears.py new file mode 100644 index 00000000..a8f7aac6 --- /dev/null +++ b/add_mesh_extra_objects/add_mesh_gears.py @@ -0,0 +1,798 @@ +# add_mesh_gear.py (c) 2009, 2010 Michel J. Anders (varkenvarken) +# +# ***** 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 2 +# 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 LICENCE BLOCK ***** +""" +bl_info = { + "name": "Gears", + "author": "Michel J. Anders (varkenvarken)", + "version": (2, 4, 2), + "blender": (2, 5, 7), + "api": 35853, + "location": "View3D > Add > Mesh > Gears ", + "description": "Adds a mesh Gear to the Add Mesh menu", + "warning": "", + "wiki_url": "http://wiki.blender.org/index.php/Extensions:2.5/Py/"\ + "Scripts/Add_Mesh/Add_Gear", + "tracker_url": "https://projects.blender.org/tracker/index.php?"\ + "func=detail&aid=21732", + "category": "Add Mesh"} +""" + +""" +What was needed to port it from 2.49 -> 2.50 alpha 0? + +The basic functions that calculate the geometry (verts and faces) are mostly +unchanged (add_tooth, add_spoke, add_gear) + +Also, the vertex group API is changed a little bit but the concepts +are the same: +========= +vertexgroup = ob.vertex_groups.new('NAME_OF_VERTEXGROUP') +vertexgroup.add(vertexgroup_vertex_indices, weight, 'ADD') +========= + +Now for some reason the name does not 'stick' and we have to set it this way: +vertexgroup.name = 'NAME_OF_VERTEXGROUP' + +Conversion to 2.50 also meant we could simply do away with our crude user +interface. +Just definining the appropriate properties in the AddGear() operator will +display the properties in the Blender GUI with the added benefit of making +it interactive: changing a property will redo the AddGear() operator providing +the user with instant feedback. + +Finally we had to convert/throw away some print statements to print functions +as Blender nows uses Python 3.x + +The code to actually implement the AddGear() function is mostly copied from +add_mesh_torus() (distributed with Blender). +""" + +import bpy +from math import * +from bpy.props import * + +# Create a new mesh (object) from verts/edges/faces. +# verts/edges/faces ... List of vertices/edges/faces for the +# new mesh (as used in from_pydata). +# name ... Name of the new mesh (& object). +def create_mesh_object(context, verts, edges, faces, name): + # Create new mesh + mesh = bpy.data.meshes.new(name) + + # Make a mesh from a list of verts/edges/faces. + mesh.from_pydata(verts, edges, faces) + + # Update mesh geometry after adding stuff. + mesh.update() + + from bpy_extras import object_utils + return object_utils.object_data_add(context, mesh, operator=None) + + +# A very simple "bridge" tool. +# Connects two equally long vertex rows with faces. +# Returns a list of the new faces (list of lists) +# +# vertIdx1 ... First vertex list (list of vertex indices). +# vertIdx2 ... Second vertex list (list of vertex indices). +# closed ... Creates a loop (first & last are closed). +# flipped ... Invert the normal of the face(s). +# +# Note: You can set vertIdx1 to a single vertex index to create +# a fan/star of faces. +# Note: If both vertex idx list are the same length they have +# to have at least 2 vertices. +def createFaces(vertIdx1, vertIdx2, closed=False, flipped=False): + faces = [] + + if not vertIdx1 or not vertIdx2: + return None + + if len(vertIdx1) < 2 and len(vertIdx2) < 2: + return None + + fan = False + if (len(vertIdx1) != len(vertIdx2)): + if (len(vertIdx1) == 1 and len(vertIdx2) > 1): + fan = True + else: + return None + + total = len(vertIdx2) + + if closed: + # Bridge the start with the end. + if flipped: + face = [ + vertIdx1[0], + vertIdx2[0], + vertIdx2[total - 1]] + if not fan: + face.append(vertIdx1[total - 1]) + faces.append(face) + + else: + face = [vertIdx2[0], vertIdx1[0]] + if not fan: + face.append(vertIdx1[total - 1]) + face.append(vertIdx2[total - 1]) + faces.append(face) + + # Bridge the rest of the faces. + for num in range(total - 1): + if flipped: + if fan: + face = [vertIdx2[num], vertIdx1[0], vertIdx2[num + 1]] + else: + face = [vertIdx2[num], vertIdx1[num], + vertIdx1[num + 1], vertIdx2[num + 1]] + faces.append(face) + else: + if fan: + face = [vertIdx1[0], vertIdx2[num], vertIdx2[num + 1]] + else: + face = [vertIdx1[num], vertIdx2[num], + vertIdx2[num + 1], vertIdx1[num + 1]] + faces.append(face) + + return faces + + +# Calculate the vertex coordinates for a single +# section of a gear tooth. +# Returns 4 lists of vertex coords (list of tuples): +# *-*---*---* (1.) verts_inner_base +# | | | | +# *-*---*---* (2.) verts_outer_base +# | | | +# *---*---* (3.) verts_middle_tooth +# \ | / +# *-*-* (4.) verts_tip_tooth +# +# a +# t +# d +# radius +# Ad +# De +# base +# p_angle +# rack +# crown +def add_tooth(a, t, d, radius, Ad, De, base, p_angle, rack=0, crown=0.0): + A = [a, a + t / 4, a + t / 2, a + 3 * t / 4] + C = [cos(i) for i in A] + S = [sin(i) for i in A] + + Ra = radius + Ad + Rd = radius - De + Rb = Rd - base + + # Pressure angle calc + O = Ad * tan(p_angle) + p_angle = atan(O / Ra) + + if radius < 0: + p_angle = -p_angle + + if rack: + S = [sin(t / 4) * I for I in range(-2, 3)] + Sp = [0, sin(-t / 4 + p_angle), 0, sin(t / 4 - p_angle)] + + verts_inner_base = [(Rb, radius * S[I], d) for I in range(4)] + verts_outer_base = [(Rd, radius * S[I], d) for I in range(4)] + verts_middle_tooth = [(radius, radius * S[I], d) for I in range(1, 4)] + verts_tip_tooth = [(Ra, radius * Sp[I], d) for I in range(1, 4)] + + else: + Cp = [ + 0, + cos(a + t / 4 + p_angle), + cos(a + t / 2), + cos(a + 3 * t / 4 - p_angle)] + Sp = [0, + sin(a + t / 4 + p_angle), + sin(a + t / 2), + sin(a + 3 * t / 4 - p_angle)] + + verts_inner_base = [(Rb * C[I], Rb * S[I], d) + for I in range(4)] + verts_outer_base = [(Rd * C[I], Rd * S[I], d) + for I in range(4)] + verts_middle_tooth = [(radius * C[I], radius * S[I], d + crown / 3) + for I in range(1, 4)] + verts_tip_tooth = [(Ra * Cp[I], Ra * Sp[I], d + crown) + for I in range(1, 4)] + + return (verts_inner_base, verts_outer_base, + verts_middle_tooth, verts_tip_tooth) + + +# EXPERIMENTAL Calculate the vertex coordinates for a single +# section of a gearspoke. +# Returns them as a list of tuples. +# +# a +# t +# d +# radius +# De +# base +# s +# w +# l +# gap +# width +# +# @todo Finish this. +def add_spoke(a, t, d, radius, De, base, s, w, l, gap=0, width=19): + Rd = radius - De + Rb = Rd - base + # Rl = Rb # UNUSED + + verts = [] + edgefaces = [] + edgefaces2 = [] + sf = [] + + if not gap: + for N in range(width, 1, -2): + edgefaces.append(len(verts)) + ts = t / 4 + tm = a + 2 * ts + te = asin(w / Rb) + td = te - ts + t4 = ts + td * (width - N) / (width - 3.0) + A = [tm + (i - int(N / 2)) * t4 for i in range(N)] + C = [cos(i) for i in A] + S = [sin(i) for i in A] + + verts.extend((Rb * I, Rb * J, d) for (I, J) in zip(C, S)) + edgefaces2.append(len(verts) - 1) + + Rb = Rb - s + + n = 0 + for N in range(width, 3, -2): + sf.extend([(i + n, i + 1 + n, i + 2 + n, i + N + n) + for i in range(0, N - 1, 2)]) + sf.extend([(i + 2 + n, i + N + n, i + N + 1 + n, i + N + 2 + n) + for i in range(0, N - 3, 2)]) + + n = n + N + + return verts, edgefaces, edgefaces2, sf + + +# Create gear geometry. +# Returns: +# * A list of vertices (list of tuples) +# * A list of faces (list of lists) +# * A list (group) of vertices of the tip (list of vertex indices). +# * A list (group) of vertices of the valley (list of vertex indices). +# +# teethNum ... Number of teeth on the gear. +# radius ... Radius of the gear, negative for crown gear +# Ad ... Addendum, extent of tooth above radius. +# De ... Dedendum, extent of tooth below radius. +# base ... Base, extent of gear below radius. +# p_angle ... Pressure angle. Skewness of tooth tip. (radiant) +# width ... Width, thickness of gear. +# skew ... Skew of teeth. (radiant) +# conangle ... Conical angle of gear. (radiant) +# rack +# crown ... Inward pointing extend of crown teeth. +# +# inner radius = radius - (De + base) +def add_gear(teethNum, radius, Ad, De, base, p_angle, + width=1, skew=0, conangle=0, rack=0, crown=0.0): + + if teethNum < 2: + return None, None, None, None + + t = 2 * pi / teethNum + + if rack: + teethNum = 1 + + scale = (radius - 2 * width * tan(conangle)) / radius + + verts = [] + faces = [] + vgroup_top = [] # Vertex group of top/tip? vertices. + vgroup_valley = [] # Vertex group of valley vertices + + verts_bridge_prev = [] + for toothCnt in range(teethNum): + a = toothCnt * t + + verts_bridge_start = [] + verts_bridge_end = [] + + verts_outside_top = [] + verts_outside_bottom = [] + for (s, d, c, top) \ + in [(0, -width, 1, True), \ + (skew, width, scale, False)]: + + verts1, verts2, verts3, verts4 = add_tooth(a + s, t, d, + radius * c, Ad * c, De * c, base * c, p_angle, + rack, crown) + + vertsIdx1 = list(range(len(verts), len(verts) + len(verts1))) + verts.extend(verts1) + vertsIdx2 = list(range(len(verts), len(verts) + len(verts2))) + verts.extend(verts2) + vertsIdx3 = list(range(len(verts), len(verts) + len(verts3))) + verts.extend(verts3) + vertsIdx4 = list(range(len(verts), len(verts) + len(verts4))) + verts.extend(verts4) + + verts_outside = [] + verts_outside.extend(vertsIdx2[:2]) + verts_outside.append(vertsIdx3[0]) + verts_outside.extend(vertsIdx4) + verts_outside.append(vertsIdx3[-1]) + verts_outside.append(vertsIdx2[-1]) + + if top: + #verts_inside_top = vertsIdx1 + verts_outside_top = verts_outside + + verts_bridge_start.append(vertsIdx1[0]) + verts_bridge_start.append(vertsIdx2[0]) + verts_bridge_end.append(vertsIdx1[-1]) + verts_bridge_end.append(vertsIdx2[-1]) + + else: + #verts_inside_bottom = vertsIdx1 + verts_outside_bottom = verts_outside + + verts_bridge_start.append(vertsIdx2[0]) + verts_bridge_start.append(vertsIdx1[0]) + verts_bridge_end.append(vertsIdx2[-1]) + verts_bridge_end.append(vertsIdx1[-1]) + + # Valley = first 2 vertices of outer base: + vgroup_valley.extend(vertsIdx2[:1]) + # Top/tip vertices: + vgroup_top.extend(vertsIdx4) + + faces_tooth_middle_top = createFaces(vertsIdx2[1:], vertsIdx3, + flipped=top) + faces_tooth_outer_top = createFaces(vertsIdx3, vertsIdx4, + flipped=top) + + faces_base_top = createFaces(vertsIdx1, vertsIdx2, flipped=top) + faces.extend(faces_base_top) + + faces.extend(faces_tooth_middle_top) + faces.extend(faces_tooth_outer_top) + + #faces_inside = createFaces(verts_inside_top, verts_inside_bottom) + #faces.extend(faces_inside) + + faces_outside = createFaces(verts_outside_top, verts_outside_bottom, + flipped=True) + faces.extend(faces_outside) + + if toothCnt == 0: + verts_bridge_first = verts_bridge_start + + # Bridge one tooth to the next + if verts_bridge_prev: + faces_bridge = createFaces(verts_bridge_prev, verts_bridge_start) + #, closed=True (for "inside" faces) + faces.extend(faces_bridge) + + # Remember "end" vertices for next tooth. + verts_bridge_prev = verts_bridge_end + + # Bridge the first to the last tooth. + faces_bridge_f_l = createFaces(verts_bridge_prev, verts_bridge_first) + #, closed=True (for "inside" faces) + faces.extend(faces_bridge_f_l) + + return verts, faces, vgroup_top, vgroup_valley + + +# Create spokes geometry. +# Returns: +# * A list of vertices (list of tuples) +# * A list of faces (list of lists) +# +# teethNum ... Number of teeth on the gear. +# radius ... Radius of the gear, negative for crown gear +# De ... Dedendum, extent of tooth below radius. +# base ... Base, extent of gear below radius. +# width ... Width, thickness of gear. +# conangle ... Conical angle of gear. (radiant) +# rack +# spoke +# spbevel +# spwidth +# splength +# spresol +# +# @todo Finish this +# @todo Create a function that takes a "Gear" and creates a +# matching "Gear Spokes" object. +def add_spokes(teethNum, radius, De, base, width=1, conangle=0, rack=0, + spoke=3, spbevel=0.1, spwidth=0.2, splength=1.0, spresol=9): + + if teethNum < 2: + return None, None, None, None + + if spoke < 2: + return None, None, None, None + + t = 2 * pi / teethNum + + if rack: + teethNum = 1 + + scale = (radius - 2 * width * tan(conangle)) / radius + + verts = [] + faces = [] + + c = scale # debug + + fl = len(verts) + for toothCnt in range(teethNum): + a = toothCnt * t + s = 0 # For test + + if toothCnt % spoke == 0: + for d in (-width, width): + sv, edgefaces, edgefaces2, sf = add_spoke(a + s, t, d, + radius * c, De * c, base * c, + spbevel, spwidth, splength, 0, spresol) + verts.extend(sv) + faces.extend([j + fl for j in i] for i in sf) + fl += len(sv) + + d1 = fl - len(sv) + d2 = fl - 2 * len(sv) + + faces.extend([(i + d2, j + d2, j + d1, i + d1) + for (i, j) in zip(edgefaces[:-1], edgefaces[1:])]) + faces.extend([(i + d2, j + d2, j + d1, i + d1) + for (i, j) in zip(edgefaces2[:-1], edgefaces2[1:])]) + + else: + for d in (-width, width): + sv, edgefaces, edgefaces2, sf = add_spoke(a + s, t, d, + radius * c, De * c, base * c, + spbevel, spwidth, splength, 1, spresol) + + verts.extend(sv) + fl += len(sv) + + d1 = fl - len(sv) + d2 = fl - 2 * len(sv) + + faces.extend([[i + d2, i + 1 + d2, i + 1 + d1, i + d1] + for (i) in range(0, 3)]) + faces.extend([[i + d2, i + 1 + d2, i + 1 + d1, i + d1] + for (i) in range(5, 8)]) + + return verts, faces + + +# Create worm geometry. +# Returns: +# * A list of vertices +# * A list of faces +# * A list (group) of vertices of the tip +# * A list (group) of vertices of the valley +# +# teethNum ... Number of teeth on the worm +# radius ... Radius of the gear, negative for crown gear +# Ad ... Addendum, extent of tooth above radius. +# De ... Dedendum, extent of tooth below radius. +# p_angle ... Pressure angle. Skewness of tooth tip. (radiant) +# width ... Width, thickness of gear. +# crown ... Inward pointing extend of crown teeth. +# +# @todo: Fix teethNum. Some numbers are not possible yet. +# @todo: Create start & end geoemtry (closing faces) +def add_worm(teethNum, rowNum, radius, Ad, De, p_angle, + width=1, skew=radians(11.25), crown=0.0): + + worm = teethNum + teethNum = 24 + + t = 2 * pi / teethNum + + verts = [] + faces = [] + vgroup_top = [] # Vertex group of top/tip? vertices. + vgroup_valley = [] # Vertex group of valley vertices + + #width = width / 2.0 + + edgeloop_prev = [] + for Row in range(rowNum): + edgeloop = [] + + for toothCnt in range(teethNum): + a = toothCnt * t + + s = Row * skew + d = Row * width + c = 1 + + isTooth = False + if toothCnt % (teethNum / worm) != 0: + # Flat + verts1, verts2, verts3, verts4 = add_tooth(a + s, t, d, + radius - De, 0.0, 0.0, 0, p_angle) + + # Ignore other verts than the "other base". + verts1 = verts3 = verts4 = [] + + else: + # Tooth + isTooth = True + verts1, verts2, verts3, verts4 = add_tooth(a + s, t, d, + radius * c, Ad * c, De * c, 0 * c, p_angle, 0, crown) + + # Remove various unneeded verts (if we are "inside" the tooth) + del(verts2[2]) # Central vertex in the base of the tooth. + del(verts3[1]) # Central vertex in the middle of the tooth. + + vertsIdx2 = list(range(len(verts), len(verts) + len(verts2))) + verts.extend(verts2) + vertsIdx3 = list(range(len(verts), len(verts) + len(verts3))) + verts.extend(verts3) + vertsIdx4 = list(range(len(verts), len(verts) + len(verts4))) + verts.extend(verts4) + + if isTooth: + verts_current = [] + verts_current.extend(vertsIdx2[:2]) + verts_current.append(vertsIdx3[0]) + verts_current.extend(vertsIdx4) + verts_current.append(vertsIdx3[-1]) + verts_current.append(vertsIdx2[-1]) + + # Valley = first 2 vertices of outer base: + vgroup_valley.extend(vertsIdx2[:1]) + # Top/tip vertices: + vgroup_top.extend(vertsIdx4) + + else: + # Flat + verts_current = vertsIdx2 + + # Valley - all of them. + vgroup_valley.extend(vertsIdx2) + + edgeloop.extend(verts_current) + + # Create faces between rings/rows. + if edgeloop_prev: + faces_row = createFaces(edgeloop, edgeloop_prev, closed=True) + faces.extend(faces_row) + + # Remember last ring/row of vertices for next ring/row iteration. + edgeloop_prev = edgeloop + + return verts, faces, vgroup_top, vgroup_valley + + +class AddGear(bpy.types.Operator): + '''Add a gear mesh.''' + bl_idname = "mesh.primitive_gear" + bl_label = "Add Gear" + bl_options = {'REGISTER', 'UNDO'} + + number_of_teeth = IntProperty(name="Number of Teeth", + description="Number of teeth on the gear", + min=2, + max=265, + default=12) + radius = FloatProperty(name="Radius", + description="Radius of the gear, negative for crown gear", + min=-100.0, + max=100.0, + default=1.0) + addendum = FloatProperty(name="Addendum", + description="Addendum, extent of tooth above radius", + min=0.01, + max=100.0, + default=0.1) + dedendum = FloatProperty(name="Dedendum", + description="Dedendum, extent of tooth below radius", + min=0.0, + max=100.0, + default=0.1) + angle = FloatProperty(name="Pressure Angle", + description="Pressure angle, skewness of tooth tip (degrees)", + min=0.0, + max=45.0, + default=20.0) + base = FloatProperty(name="Base", + description="Base, extent of gear below radius", + min=0.0, + max=100.0, + default=0.2) + width = FloatProperty(name="Width", + description="Width, thickness of gear", + min=0.05, + max=100.0, + default=0.2) + skew = FloatProperty(name="Skewness", + description="Skew of teeth (degrees)", + min=-90.0, + max=90.0, + default=0.0) + conangle = FloatProperty(name="Conical angle", + description="Conical angle of gear (degrees)", + min=0.0, + max=90.0, + default=0.0) + crown = FloatProperty(name="Crown", + description="Inward pointing extend of crown teeth", + min=0.0, + max=100.0, + default=0.0) + + def draw(self, context): + layout = self.layout + box = layout.box() + box.prop(self, 'number_of_teeth') + box = layout.box() + box.prop(self, 'radius') + box.prop(self, 'width') + box.prop(self, 'base') + box = layout.box() + box.prop(self, 'dedendum') + box.prop(self, 'addendum') + box = layout.box() + box.prop(self, 'angle') + box.prop(self, 'skew') + box.prop(self, 'conangle') + box.prop(self, 'crown') + + + def execute(self, context): + + verts, faces, verts_tip, verts_valley = add_gear( + self.number_of_teeth, + self.radius, + self.addendum, + self.dedendum, + self.base, + radians(self.angle), + width=self.width, + skew=radians(self.skew), + conangle=radians(self.conangle), + crown=self.crown) + + # Actually create the mesh object from this geometry data. + base = create_mesh_object(context, verts, [], faces, "Gear") + obj = base.object + + # Create vertex groups from stored vertices. + tipGroup = obj.vertex_groups.new('Tips') + tipGroup.add(verts_tip, 1.0, 'ADD') + + valleyGroup = obj.vertex_groups.new('Valleys') + valleyGroup.add(verts_valley, 1.0, 'ADD') + + return {'FINISHED'} + + +class AddWormGear(bpy.types.Operator): + '''Add a worm gear mesh.''' + bl_idname = "mesh.primitive_worm_gear" + bl_label = "Add Worm Gear" + bl_options = {'REGISTER', 'UNDO'} + + number_of_teeth = IntProperty(name="Number of Teeth", + description="Number of teeth on the gear", + min=2, + max=265, + default=12) + number_of_rows = IntProperty(name="Number of Rows", + description="Number of rows on the worm gear", + min=2, + max=265, + default=32) + radius = FloatProperty(name="Radius", + description="Radius of the gear, negative for crown gear", + min=-100.0, + max=100.0, + default=1.0) + addendum = FloatProperty(name="Addendum", + description="Addendum, extent of tooth above radius", + min=0.01, + max=100.0, + default=0.1) + dedendum = FloatProperty(name="Dedendum", + description="Dedendum, extent of tooth below radius", + min=0.0, + max=100.0, + default=0.1) + angle = FloatProperty(name="Pressure Angle", + description="Pressure angle, skewness of tooth tip (degrees)", + min=0.0, + max=45.0, + default=20.0) + row_height = FloatProperty(name="Row Height", + description="Height of each Row", + min=0.05, + max=100.0, + default=0.2) + skew = FloatProperty(name="Skewness per Row", + description="Skew of each row (degrees)", + min=-90.0, + max=90.0, + default=11.25) + crown = FloatProperty(name="Crown", + description="Inward pointing extend of crown teeth", + min=0.0, + max=100.0, + default=0.0) + + def draw(self, context): + layout = self.layout + box = layout.box() + box.prop(self, 'number_of_teeth') + box.prop(self, 'number_of_rows') + box.prop(self, 'radius') + box.prop(self, 'row_height') + box = layout.box() + box.prop(self, 'addendum') + box.prop(self, 'dedendum') + box = layout.box() + box.prop(self, 'angle') + box.prop(self, 'skew') + box.prop(self, 'crown') + + def execute(self, context): + + verts, faces, verts_tip, verts_valley = add_worm( + self.number_of_teeth, + self.number_of_rows, + self.radius, + self.addendum, + self.dedendum, + radians(self.angle), + width=self.row_height, + skew=radians(self.skew), + crown=self.crown) + + # Actually create the mesh object from this geometry data. + base = create_mesh_object(context, verts, [], faces, "Worm Gear") + obj = base.object + + # Create vertex groups from stored vertices. + tipGroup = obj.vertex_groups.new('Tips') + tipGroup.add(verts_tip, 1.0, 'ADD') + + valleyGroup = obj.vertex_groups.new('Valleys') + valleyGroup.add(verts_valley, 1.0, 'ADD') + + return {'FINISHED'} + diff --git a/add_mesh_extra_objects/add_mesh_gemstones.py b/add_mesh_extra_objects/add_mesh_gemstones.py new file mode 100644 index 00000000..02bc10f4 --- /dev/null +++ b/add_mesh_extra_objects/add_mesh_gemstones.py @@ -0,0 +1,331 @@ +# ##### 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 2 +# 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": "Gemstones", + "author": "Pontiac, Fourmadmen, Dreampainter", + "version": (0, 4), + "blender": (2, 5, 7), + "api": 35853, + "location": "View3D > Add > Mesh > Gemstones", + "description": "Adds various gemstone (Diamond & Gem) meshes.", + "warning": "", + "wiki_url": "http://wiki.blender.org/index.php/Extensions:2.5/Py/"\ + "Scripts/Add_Mesh/Add_Gemstones", + "tracker_url": "https://projects.blender.org/tracker/index.php?"\ + "func=detail&aid=21432", + "category": "Add Mesh"} +""" +import bpy +from mathutils import * +from math import * +from bpy.props import * + +# Create a new mesh (object) from verts/edges/faces. +# verts/edges/faces ... List of vertices/edges/faces for the +# new mesh (as used in from_pydata). +# name ... Name of the new mesh (& object). +def create_mesh_object(context, verts, edges, faces, name): + + # Create new mesh + mesh = bpy.data.meshes.new(name) + + # Make a mesh from a list of verts/edges/faces. + mesh.from_pydata(verts, edges, faces) + + # Update mesh geometry after adding stuff. + mesh.update() + + from bpy_extras import object_utils + return object_utils.object_data_add(context, mesh, operator=None) + + +# A very simple "bridge" tool. +# Connects two equally long vertex rows with faces. +# Returns a list of the new faces (list of lists) +# +# vertIdx1 ... First vertex list (list of vertex indices). +# vertIdx2 ... Second vertex list (list of vertex indices). +# closed ... Creates a loop (first & last are closed). +# flipped ... Invert the normal of the face(s). +# +# Note: You can set vertIdx1 to a single vertex index to create +# a fan/star of faces. +# Note: If both vertex idx list are the same length they have +# to have at least 2 vertices. +def createFaces(vertIdx1, vertIdx2, closed=False, flipped=False): + faces = [] + + if not vertIdx1 or not vertIdx2: + return None + + if len(vertIdx1) < 2 and len(vertIdx2) < 2: + return None + + fan = False + if (len(vertIdx1) != len(vertIdx2)): + if (len(vertIdx1) == 1 and len(vertIdx2) > 1): + fan = True + else: + return None + + total = len(vertIdx2) + + if closed: + # Bridge the start with the end. + if flipped: + face = [ + vertIdx1[0], + vertIdx2[0], + vertIdx2[total - 1]] + if not fan: + face.append(vertIdx1[total - 1]) + faces.append(face) + + else: + face = [vertIdx2[0], vertIdx1[0]] + if not fan: + face.append(vertIdx1[total - 1]) + face.append(vertIdx2[total - 1]) + faces.append(face) + + # Bridge the rest of the faces. + for num in range(total - 1): + if flipped: + if fan: + face = [vertIdx2[num], vertIdx1[0], vertIdx2[num + 1]] + else: + face = [vertIdx2[num], vertIdx1[num], + vertIdx1[num + 1], vertIdx2[num + 1]] + faces.append(face) + else: + if fan: + face = [vertIdx1[0], vertIdx2[num], vertIdx2[num + 1]] + else: + face = [vertIdx1[num], vertIdx2[num], + vertIdx2[num + 1], vertIdx1[num + 1]] + faces.append(face) + + return faces + + +# @todo Clean up vertex&face creation process a bit. +def add_gem(r1, r2, seg, h1, h2): + """ + r1 = pavilion radius + r2 = crown radius + seg = number of segments + h1 = pavilion height + h2 = crown height + Generates the vertices and faces of the gem + """ + + verts = [] + + a = 2.0 * pi / seg # Angle between segments + offset = a / 2.0 # Middle between segments + + r3 = ((r1 + r2) / 2.0) / cos(offset) # Middle of crown + r4 = (r1 / 2.0) / cos(offset) # Middle of pavilion + h3 = h2 / 2.0 # Middle of crown height + h4 = -h1 / 2.0 # Middle of pavilion height + + # Tip + vert_tip = len(verts) + verts.append(Vector((0.0, 0.0, -h1))) + + # Middle vertex of the flat side (crown) + vert_flat = len(verts) + verts.append(Vector((0.0, 0.0, h2))) + + edgeloop_flat = [] + for i in range(seg): + s1 = sin(i * a) + s2 = sin(offset + i * a) + c1 = cos(i * a) + c2 = cos(offset + i * a) + + verts.append((r4 * s1, r4 * c1, h4)) # Middle of pavilion + verts.append((r1 * s2, r1 * c2, 0.0)) # Pavilion + verts.append((r3 * s1, r3 * c1, h3)) # Middle crown + edgeloop_flat.append(len(verts)) + verts.append((r2 * s2, r2 * c2, h2)) # Crown + + faces = [] + + for index in range(seg): + i = index * 4 + j = ((index + 1) % seg) * 4 + + faces.append([j + 2, vert_tip, i + 2, i + 3]) # Tip -> Middle of pav + faces.append([j + 2, i + 3, j + 3]) # Middle of pav -> pav + faces.append([j + 3, i + 3, j + 4]) # Pav -> Middle crown + faces.append([j + 4, i + 3, i + 4, i + 5]) # Crown quads + faces.append([j + 4, i + 5, j + 5]) # Middle crown -> crown + + faces_flat = createFaces([vert_flat], edgeloop_flat, closed=True) + faces.extend(faces_flat) + + return verts, faces + + +def add_diamond(segments, girdle_radius, table_radius, + crown_height, pavilion_height): + + PI_2 = pi * 2.0 + z_axis = (0.0, 0.0, -1.0) + + verts = [] + faces = [] + + height_flat = crown_height + height_middle = 0.0 + height_tip = -pavilion_height + + # Middle vertex of the flat side (crown) + vert_flat = len(verts) + verts.append(Vector((0.0, 0.0, height_flat))) + + # Tip + vert_tip = len(verts) + verts.append(Vector((0.0, 0.0, height_tip))) + + verts_flat = [] + verts_girdle = [] + + for index in range(segments): + quat = Quaternion(z_axis, (index / segments) * PI_2) + + # angle = PI_2 * index / segments # UNUSED + + # Row for flat side + verts_flat.append(len(verts)) + vec = quat * Vector((table_radius, 0.0, height_flat)) + verts.append(vec) + + # Row for the middle/girdle + verts_girdle.append(len(verts)) + vec = quat * Vector((girdle_radius, 0.0, height_middle)) + verts.append(vec) + + # Flat face + faces_flat = createFaces([vert_flat], verts_flat, closed=True, + flipped=True) + # Side face + faces_side = createFaces(verts_girdle, verts_flat, closed=True) + # Tip faces + faces_tip = createFaces([vert_tip], verts_girdle, closed=True) + + faces.extend(faces_tip) + faces.extend(faces_side) + faces.extend(faces_flat) + + return verts, faces + + +class AddDiamond(bpy.types.Operator): + '''Add a diamond mesh.''' + bl_idname = "mesh.primitive_diamond_add" + bl_label = "Add Diamond" + bl_options = {'REGISTER', 'UNDO'} + + segments = IntProperty(name="Segments", + description="Number of segments for the diamond", + min=3, + max=256, + default=32) + girdle_radius = FloatProperty(name="Girdle Radius", + description="Girdle radius of the diamond", + min=0.01, + max=9999.0, + default=1.0) + table_radius = FloatProperty(name="Table Radius", + description="Girdle radius of the diamond", + min=0.01, + max=9999.0, + default=0.6) + crown_height = FloatProperty(name="Crown Height", + description="Crown height of the diamond", + min=0.01, + max=9999.0, + default=0.35) + pavilion_height = FloatProperty(name="Pavilion Height", + description="Pavilion height of the diamond", + min=0.01, + max=9999.0, + default=0.8) + + def execute(self, context): + verts, faces = add_diamond(self.segments, + self.girdle_radius, + self.table_radius, + self.crown_height, + self.pavilion_height) + + obj = create_mesh_object(context, verts, [], faces, "Diamond") + + return {'FINISHED'} + + +class AddGem(bpy.types.Operator): + """Add a diamond gem""" + bl_idname = "mesh.primitive_gem_add" + bl_label = "Add Gem" + bl_description = "Create an offset faceted gem." + bl_options = {'REGISTER', 'UNDO'} + + segments = IntProperty(name="Segments", + description="Longitudial segmentation", + min=3, + max=265, + default=8,) + pavilion_radius = FloatProperty(name="Radius", + description="Radius of the gem", + min=0.01, + max=9999.0, + default=1.0) + crown_radius = FloatProperty(name="Table Radius", + description="Radius of the table(top).", + min=0.01, + max=9999.0, + default=0.6) + crown_height = FloatProperty(name="Table height", + description="Height of the top half.", + min=0.01, + max=9999.0, + default=0.35) + pavilion_height = FloatProperty(name="Pavilion height", + description="Height of bottom half.", + min=0.01, + max=9999.0, + default=0.8) + + def execute(self, context): + + # create mesh + verts, faces = add_gem( + self.pavilion_radius, + self.crown_radius, + self.segments, + self.pavilion_height, + self.crown_height) + + obj = create_mesh_object(context, verts, [], faces, "Gem") + + return {'FINISHED'} + diff --git a/add_mesh_extra_objects/add_mesh_twisted_torus.py b/add_mesh_extra_objects/add_mesh_twisted_torus.py new file mode 100644 index 00000000..1fd872c5 --- /dev/null +++ b/add_mesh_extra_objects/add_mesh_twisted_torus.py @@ -0,0 +1,250 @@ +# add_mesh_twisted_torus.py Copyright (C) 2009-2010, Paulo Gomes +# tuga3d {at} gmail {dot} com +# add twisted torus to the blender 2.50 add->mesh menu +# ***** 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 2 +# 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 LICENCE BLOCK ***** +""" +bl_info = { + "name": "Twisted Torus", + "author": "Paulo_Gomes", + "version": (0, 11, 1), + "blender": (2, 5, 7), + "api": 35853, + "location": "View3D > Add > Mesh ", + "description": "Adds a mesh Twisted Torus to the Add Mesh menu", + "warning": "", + "wiki_url": "http://wiki.blender.org/index.php/Extensions:2.5/Py/"\ + "Scripts/Add_Mesh/Add_Twisted_Torus", + "tracker_url": "https://projects.blender.org/tracker/index.php?"\ + "func=detail&aid=21622", + "category": "Add Mesh"} + +Usage: + +* Launch from Add Mesh menu + +* Modify parameters as desired or keep defaults +""" + + +import bpy +from bpy.props import * + +from mathutils import * +from math import cos, sin, pi + + +# Create a new mesh (object) from verts/edges/faces. +# verts/edges/faces ... List of vertices/edges/faces for the +# new mesh (as used in from_pydata). +# name ... Name of the new mesh (& object). +def create_mesh_object(context, verts, edges, faces, name): + + # Create new mesh + mesh = bpy.data.meshes.new(name) + + # Make a mesh from a list of verts/edges/faces. + mesh.from_pydata(verts, edges, faces) + + # Update mesh geometry after adding stuff. + mesh.update() + + from bpy_extras import object_utils + return object_utils.object_data_add(context, mesh, operator=None) + +# A very simple "bridge" tool. +# Connects two equally long vertex rows with faces. +# Returns a list of the new faces (list of lists) +# +# vertIdx1 ... First vertex list (list of vertex indices). +# vertIdx2 ... Second vertex list (list of vertex indices). +# closed ... Creates a loop (first & last are closed). +# flipped ... Invert the normal of the face(s). +# +# Note: You can set vertIdx1 to a single vertex index to create +# a fan/star of faces. +# Note: If both vertex idx list are the same length they have +# to have at least 2 vertices. +def createFaces(vertIdx1, vertIdx2, closed=False, flipped=False): + faces = [] + + if not vertIdx1 or not vertIdx2: + return None + + if len(vertIdx1) < 2 and len(vertIdx2) < 2: + return None + + fan = False + if (len(vertIdx1) != len(vertIdx2)): + if (len(vertIdx1) == 1 and len(vertIdx2) > 1): + fan = True + else: + return None + + total = len(vertIdx2) + + if closed: + # Bridge the start with the end. + if flipped: + face = [ + vertIdx1[0], + vertIdx2[0], + vertIdx2[total - 1]] + if not fan: + face.append(vertIdx1[total - 1]) + faces.append(face) + + else: + face = [vertIdx2[0], vertIdx1[0]] + if not fan: + face.append(vertIdx1[total - 1]) + face.append(vertIdx2[total - 1]) + faces.append(face) + + # Bridge the rest of the faces. + for num in range(total - 1): + if flipped: + if fan: + face = [vertIdx2[num], vertIdx1[0], vertIdx2[num + 1]] + else: + face = [vertIdx2[num], vertIdx1[num], + vertIdx1[num + 1], vertIdx2[num + 1]] + faces.append(face) + else: + if fan: + face = [vertIdx1[0], vertIdx2[num], vertIdx2[num + 1]] + else: + face = [vertIdx1[num], vertIdx2[num], + vertIdx2[num + 1], vertIdx1[num + 1]] + faces.append(face) + + return faces + + +def add_twisted_torus(major_rad, minor_rad, major_seg, minor_seg, twists): + PI_2 = pi * 2.0 + z_axis = (0.0, 0.0, 1.0) + + verts = [] + faces = [] + + edgeloop_prev = [] + for major_index in range(major_seg): + quat = Quaternion(z_axis, (major_index / major_seg) * PI_2) + rot_twists = PI_2 * major_index / major_seg * twists + + edgeloop = [] + + # Create section ring + for minor_index in range(minor_seg): + angle = (PI_2 * minor_index / minor_seg) + rot_twists + + vec = Vector(( + major_rad + (cos(angle) * minor_rad), + 0.0, + sin(angle) * minor_rad)) + vec = quat * vec + + edgeloop.append(len(verts)) + verts.append(vec) + + # Remember very first edgeloop. + if major_index == 0: + edgeloop_first = edgeloop + + # Bridge last with current ring + if edgeloop_prev: + f = createFaces(edgeloop_prev, edgeloop, closed=True) + faces.extend(f) + + edgeloop_prev = edgeloop + + # Bridge first and last ring + f = createFaces(edgeloop_prev, edgeloop_first, closed=True) + faces.extend(f) + + return verts, faces + + +class AddTwistedTorus(bpy.types.Operator): + '''Add a torus mesh''' + bl_idname = "mesh.primitive_twisted_torus_add" + bl_label = "Add Torus" + bl_options = {'REGISTER', 'UNDO'} + + major_radius = FloatProperty(name="Major Radius", + description="Radius from the origin to the" \ + " center of the cross section", + min=0.01, + max=100.0, + default=1.0) + minor_radius = FloatProperty(name="Minor Radius", + description="Radius of the torus' cross section", + min=0.01, + max=100.0, + default=0.25) + major_segments = IntProperty(name="Major Segments", + description="Number of segments for the main ring of the torus", + min=3, + max=256, + default=48) + minor_segments = IntProperty(name="Minor Segments", + description="Number of segments for the minor ring of the torus", + min=3, + max=256, + default=12) + twists = IntProperty(name="Twists", + description="Number of twists of the torus", + min=0, + max=256, + default=1) + + use_abso = BoolProperty(name="Use Int+Ext Controls", + description="Use the Int / Ext controls for torus dimensions", + default=False) + abso_major_rad = FloatProperty(name="Exterior Radius", + description="Total Exterior Radius of the torus", + min=0.01, + max=100.0, + default=1.0) + abso_minor_rad = FloatProperty(name="Inside Radius", + description="Total Interior Radius of the torus", + min=0.01, + max=100.0, + default=0.5) + + def execute(self, context): + + if self.use_abso == True: + extra_helper = (self.abso_major_rad - self.abso_minor_rad) * 0.5 + self.major_radius = self.abso_minor_rad + extra_helper + self.minor_radius = extra_helper + + verts, faces = add_twisted_torus( + self.major_radius, + self.minor_radius, + self.major_segments, + self.minor_segments, + self.twists) + + # Actually create the mesh object from this geometry data. + obj = create_mesh_object(context, verts, [], faces, "TwistedTorus") + + return {'FINISHED'} + |