[Bf-extensions-cvs] [80853da] master: Fix T46885 : Update Torus Knot Plus - New features, code cleanup & UI modifications

Marius Giurgi noreply at git.blender.org
Mon Dec 7 06:18:07 CET 2015


Commit: 80853daea9394b9135bef342eefa0150a1c1a5f8
Author: Marius Giurgi
Date:   Sun Dec 6 22:33:06 2015 -0500
Branches: master
https://developer.blender.org/rBA80853daea9394b9135bef342eefa0150a1c1a5f8

Fix T46885 : Update Torus Knot Plus - New features, code cleanup & UI modifications

Reorganize the UI into categories and renamed some settings, clean up and document the code and add new feautures, main options and plus options (e.g. adaptive curve resolution, curve type, radius settings and multi-link generation).

===================================================================

M	add_curve_extra_objects/add_curve_torus_knots.py
A	presets/operator/curve.torus_knot_plus/13x8_wicker_globe.py
A	presets/operator/curve.torus_knot_plus/7x6.py
A	presets/operator/curve.torus_knot_plus/9x9_color.py
A	presets/operator/curve.torus_knot_plus/braided_coil.py
A	presets/operator/curve.torus_knot_plus/flower_mesh_(2d).py
A	presets/operator/curve.torus_knot_plus/slinky_knot.py
A	presets/operator/curve.torus_knot_plus/snowflake_(2d).py
A	presets/operator/curve.torus_knot_plus/sun_cross_(2d).py
A	presets/operator/curve.torus_knot_plus/tripple_dna.py
A	presets/operator/curve.torus_knot_plus/wicker_basket.py

===================================================================

diff --git a/add_curve_extra_objects/add_curve_torus_knots.py b/add_curve_extra_objects/add_curve_torus_knots.py
index 22fe48f..47524c0 100644
--- a/add_curve_extra_objects/add_curve_torus_knots.py
+++ b/add_curve_extra_objects/add_curve_torus_knots.py
@@ -19,9 +19,9 @@
 '''
 bl_info = {
     "name": "Torus Knots",
-    "author": "testscreenings",
-    "version": (0, 1),
-    "blender": (2, 59, 0),
+    "author": "Marius Giurgi (DolphinDream), testscreenings",
+    "version": (0, 2),
+    "blender": (2, 76, 0),
     "location": "View3D > Add > Curve",
     "description": "Adds many types of (torus) knots",
     "warning": "",
@@ -30,194 +30,659 @@ bl_info = {
     "category": "Add Curve"}
 '''
 
-##------------------------------------------------------------
+# ------------------------------------------------------------------------------
+
 #### import modules
 import bpy
-from bpy.props import *
-from math import sin, cos, pi
+from bpy.props import BoolProperty, EnumProperty, FloatProperty, IntProperty
+from math import sin, cos, pi, sqrt
+from mathutils import *
 from bpy_extras.object_utils import AddObjectHelper, object_data_add
+from random import random
+
+DEBUG = False
+
+# greatest common denominator
+def gcd(a, b):
+    if b == 0:
+        return a
+    else:
+        return gcd(b, a % b)
 
 
 ########################################################################
 ####################### Knot Definitions ###############################
 ########################################################################
-def Torus_Knot(self):
-    p = self.torus_p
-    q = self.torus_q
-    w = self.torus_w
-    res = self.torus_res
-    h = self.torus_h
-    u = self.torus_u
-    v = self.torus_v
-    rounds = self.torus_rounds
+def Torus_Knot(self, linkIndex=0):
+    p = self.torus_p # revolution count (around the torus center)
+    q = self.torus_q # spin count (around the torus tube)
 
-    newPoints = []
-    angle = 2*rounds
-    step = angle/(res-1)
-    scale = h
-    height = w
+    N = self.torus_res # curve resolution (number of control points)
+
+    # use plus options only when they are enabled
+    if self.options_plus:
+        u = self.torus_u # p multiplier
+        v = self.torus_v # q multiplier
+        h = self.torus_h # height (scale along Z)
+        s = self.torus_s # torus scale (radii scale factor)
+    else: # don't use plus settings
+        u = 1
+        v = 1
+        h = 1
+        s = 1
+
+    R = self.torus_R * s # major radius (scaled)
+    r = self.torus_r * s # minor radius (scaled)
+
+    # number of decoupled links when (p,q) are NOT co-primes
+    links = gcd(p,q) # = 1 when (p,q) are co-primes
+
+    # parametrized angle increment (cached outside of the loop for performance)
+    # NOTE: the total angle is divided by number of decoupled links to ensure
+    #       the curve does not overlap with itself when (p,q) are not co-primes
+    da = 2*pi/links/(N-1)
 
-    for i in range(res-1):
-        t = ( i*step*pi)
+    # link phase : each decoupled link is phased equally around the torus center
+    # NOTE: linkIndex value is in [0, links-1]
+    linkPhase = 2*pi/q * linkIndex # = 0 when there is just ONE link
 
-        x = (2 * scale + cos((q*t)/p*v)) * cos(t * u)
-        y = (2 * scale + cos((q*t)/p*v)) * sin(t * u)
-        z = sin(q*t/p) * height
+    # user defined phasing
+    if self.options_plus:
+        rPhase = self.torus_rP # user defined revolution phase
+        sPhase = self.torus_sP # user defined spin phase
+    else: # don't use plus settings
+        rPhase = 0
+        sPhase = 0
 
-        newPoints.extend([x,y,z,1])
+    rPhase += linkPhase # total revolution phase of the current link
+
+    if DEBUG:
+        print("")
+        print("Link: %i of %i" % (linkIndex, links))
+        print("gcd = %i" % links)
+        print("p = %i" % p)
+        print("q = %i" % q)
+        print("link phase = %.2f deg" % (linkPhase * 180/pi))
+        print("link phase = %.2f rad" % linkPhase)
+
+    # flip directions ? NOTE: flipping both is equivalent to no flip
+    if self.flip_p: p*=-1
+    if self.flip_q: q*=-1
+
+    # create the 3D point array for the current link
+    newPoints = []
+    for n in range(N-1):
+        # t = 2*pi / links * n/(N-1) with: da = 2*pi/links/(N-1) => t = n * da
+        t = n * da
+        theta = p*t*u + rPhase # revolution angle
+        phi   = q*t*v + sPhase # spin angle
+
+        x = (R + r*cos(phi)) * cos(theta)
+        y = (R + r*cos(phi)) * sin(theta)
+        z = r*sin(phi) * h
+
+        # append 3D point
+        # NOTE : the array is adjusted later as needed to 4D for POLY and NURBS
+        newPoints.append([x,y,z])
 
     return newPoints
 
+# ------------------------------------------------------------------------------
+# Calculate the align matrix for the new object (based on user preferences)
+def align_matrix(self, context):
+    if self.absolute_location:
+        loc = Matrix.Translation(Vector((0,0,0)))
+    else:
+        loc = Matrix.Translation(context.scene.cursor_location)
+
+    # user defined location & translation
+    userLoc = Matrix.Translation(self.location)
+    userRot = self.rotation.to_matrix().to_4x4()
 
-##------------------------------------------------------------
-# Main Function
+    obj_align = context.user_preferences.edit.object_align
+    if (context.space_data.type == 'VIEW_3D' and obj_align == 'VIEW'):
+        rot = context.space_data.region_3d.view_matrix.to_3x3().inverted().to_4x4()
+    else:
+        rot = Matrix()
+
+    align_matrix = userLoc * loc * rot * userRot
+    return align_matrix
+
+# ------------------------------------------------------------------------------
+# Set curve BEZIER handles to auto
+def setBezierHandles(obj, mode = 'AUTOMATIC'):
+    scene = bpy.context.scene
+    if obj.type != 'CURVE':
+        return
+    scene.objects.active = obj
+    bpy.ops.object.mode_set(mode='EDIT', toggle=True)
+    bpy.ops.curve.select_all(action='SELECT')
+    bpy.ops.curve.handle_type_set(type=mode)
+    bpy.ops.object.mode_set(mode='OBJECT', toggle=True)
+
+# ------------------------------------------------------------------------------
+# Convert array of vert coordinates to points according to spline type
+def vertsToPoints(Verts, splineType):
+    # main vars
+    vertArray = []
+
+    # array for BEZIER spline output (V3)
+    if splineType == 'BEZIER':
+        for v in Verts:
+            vertArray += v
+
+    # array for non-BEZIER output (V4)
+    else:
+        for v in Verts:
+            vertArray += v
+            if splineType == 'NURBS':
+                vertArray.append(1) # for NURBS w=1
+            else: # for POLY w=0
+                vertArray.append(0)
+
+    return vertArray
+
+# ------------------------------------------------------------------------------
+# Create the Torus Knot curve and object and add it to the scene
 def create_torus_knot(self, context):
-    verts = Torus_Knot(self)
-
-    curve_data = bpy.data.curves.new(name='Torus Knot', type='CURVE')
-    spline = curve_data.splines.new(type='NURBS')
-    spline.points.add(int(len(verts)*0.25 - 1))
-    spline.points.foreach_set('co', verts)
-    spline.use_endpoint_u = True
-    spline.use_cyclic_u = True
-    spline.order_u = 4
+    # pick a name based on (p,q) parameters
+    aName = "Torus Knot %i x %i" % (self.torus_p, self.torus_q)
+
+    # create curve
+    curve_data = bpy.data.curves.new(name=aName, type='CURVE')
+
+    # setup materials to be used for the TK links
+    if self.use_colors:
+        addLinkColors(self, curve_data)
+
+    # create torus knot link(s)
+    if self.multiple_links:
+        links = gcd(self.torus_p, self.torus_q);
+    else:
+        links = 1;
+
+    for l in range(links):
+        # get vertices for the current link
+        verts = Torus_Knot(self, l)
+
+        # output splineType 'POLY' 'NURBS' or 'BEZIER'
+        splineType = self.outputType
+
+        # turn verts into proper array (based on spline type)
+        vertArray = vertsToPoints(verts, splineType)
+
+        # create spline from vertArray (based on spline type)
+        spline = curve_data.splines.new(type=splineType)
+        if splineType == 'BEZIER':
+            spline.bezier_points.add(int(len(vertArray)*1.0/3-1))
+            spline.bezier_points.foreach_set('co', vertArray)
+        else:
+            spline.points.add(int(len(vertArray)*1.0/4 - 1))
+            spline.points.foreach_set('co', vertArray)
+            spline.use_endpoint_u = True
+
+        # set curve options
+        spline.use_cyclic_u = True
+        spline.order_u = 4
+
+        # set a color per link
+        if self.use_colors:
+            spline.material_index = l
+
     curve_data.dimensions = '3D'
+    curve_data.resolution_u = self.segment_res
 
-    if self.geo_surf:
+    # create surface ?
+    if self.geo_surface:
+        curve_data.fill_mode = 'FULL'
         curve_data.bevel_depth = self.geo_bDepth
         curve_data.bevel_resolution = self.geo_bRes
-        curve_data.fill_mode = 'FULL'
         curve_data.extrude = self.geo_extrude
-        #curve_data.offset = self.geo_width # removed, somehow screws things up all of a sudden
-        curve_data.resolution_u = self.geo_res
+        curve_data.offset = self.geo_offset
+
+    new_obj = bpy.data.objects.new(aName, curve_data)
+
+    # set object in the scene
+    scene = bpy.context.scene
+    scene.objects.link(new_obj) # place in active scene
+    new_obj.select = True # set as selected
+    scene.objects.active = new_obj  # set as active
+    new_obj.matrix_world = self.align_matrix # apply matrix
+
+    # set BEZIER handles
+    if splineType == 'BEZIER':
+        setBezierHandles(new_obj, self.handleType)
+
+    return
 
-    new_obj = object_data_add(context, curve_data, operator=self)
+# ------------------------------------------------------------------------------
+# Create materials to be assigned to each TK link
+def addLinkColors(self, curveData):
+    # some predefined colors for the torus knot links
+    colors = []
+    if self.colorSet == "1": # RGBish
+        colors += [ [0.0, 0.0, 1.0] ]
+        colors += [ [0.0, 1.0, 0.0] ]
+        colors += [ [1.0, 0.

@@ Diff output truncated at 10240 characters. @@



More information about the Bf-extensions-cvs mailing list