Cleanup: trailing space
authorCampbell Barton <ideasman42@gmail.com>
Fri, 7 Sep 2018 20:14:37 +0000 (06:14 +1000)
committerCampbell Barton <ideasman42@gmail.com>
Fri, 7 Sep 2018 20:14:37 +0000 (06:14 +1000)
74 files changed:
add_dimension.py
add_mesh_clusters/add_mesh_cluster.py
add_mesh_rocks/rockgen.py
amaranth/node_editor/switch_material.py
amaranth/render/unsimplify.py
automat/AdjOp.py
automat/JSONOps.py
cacharanth/__init__.py
cacharanth/util.py
cmu_mocap_browser/data.py
cmu_mocap_browser/makehuman.py
curve_tools/Curves.py
curve_tools/Math.py
curve_tools/Operators.py
curve_tools/Properties.py
curve_tools/Surfaces.py
curve_tools/Util.py
curve_tools/auto_loft.py
curve_tools/curve_outline.py
data_overrides/__init__.py
data_overrides/override.py
data_overrides/ui.py
data_overrides/util.py
io_atomblend_utilities/io_atomblend_utilities.py
io_directx_bel/__init__.py
io_directx_bel/bel/__init__.py
io_directx_bel/bel/fs.py
io_directx_bel/bel/group.py
io_directx_bel/bel/image.py
io_directx_bel/bel/material.py
io_directx_bel/bel/mesh.py
io_directx_bel/bel/ob.py
io_directx_bel/bel/uv.py
io_directx_bel/import_x.py
io_import_BrushSet.py
io_import_sound_to_anim.py
io_mesh_gwyddion/import_gwyddion.py
io_mesh_xyz/export_xyz.py
io_mesh_xyz/import_xyz.py
io_points_pcd/__init__.py
io_points_pcd/pcd_utils.py
io_points_pcd/pcdparser.py
io_scene_cod/export_xanim.py
io_scene_cod/export_xmodel.py
io_scene_cod/import_xmodel.py
io_scene_map/__init__.py
io_scene_map/export_map.py
mesh_copy_uvs_from_joined.py
mesh_insert_edge_ring.py
mesh_ktools.py
mesh_xoffsets.py
np_station/__init__.py
np_station/np_float_box.py
np_station/np_float_poly.py
np_station/np_float_rectangle.py
np_station/np_point_align.py
np_station/np_point_array.py
np_station/np_point_copy.py
np_station/np_point_instance.py
np_station/utils_function.py
np_station/utils_geometry.py
np_station/utils_graphics.py
object_particle_hair_lab.py
object_particle_hair_net.py
oscurart_mesh_thread.py
render_auto_save.py
render_shots.py
space_view3d_enhanced_3d_cursor.py
space_view3d_library_hide.py
space_view3d_quickPrefs.py
sun_position/map.py
sun_position/operators.py
sun_position/properties.py
text_editor_hastebin.py

index 1b95bbb..e62b56f 100644 (file)
@@ -1724,7 +1724,7 @@ def createCurve(vertArray, self, align_matrix):
         DimensionCurve.rotation_euler[0] = radians(self.Dimension_rotation)
         DimensionCurve.rotation_euler[1] = u1
         DimensionCurve.rotation_euler[2] = u2
-    
+
     # Align to view
     if self.Dimension_align_to_camera :
         obj_camera = bpy.context.scene.camera
@@ -1747,7 +1747,7 @@ def createCurve(vertArray, self, align_matrix):
     group_name = 'Dimensions'
 
     bpy.ops.object.mode_set(mode = 'OBJECT')
-        
+
     if group_name in bpy.data.groups:
         group = bpy.data.groups[group_name]
     else:
@@ -1764,7 +1764,7 @@ def createCurve(vertArray, self, align_matrix):
     if self.Dimension_appoint_parent and not self.Dimension_parent == '':
         const =  DimensionCurve.constraints.new(type='CHILD_OF')
         const.target =  bpy.data.objects[self.Dimension_parent]
-        const.inverse_matrix = bpy.data.objects[self.Dimension_parent].matrix_world.inverted() 
+        const.inverse_matrix = bpy.data.objects[self.Dimension_parent].matrix_world.inverted()
         bpy.context.scene.update()
 
     bpy.ops.object.select_all(action='DESELECT')
@@ -1818,7 +1818,7 @@ def createCurve(vertArray, self, align_matrix):
     #### Parent
     DimensionCurve.Dimension_parent = self.Dimension_parent
     DimensionCurve.Dimension_appoint_parent = self.Dimension_appoint_parent
-    
+
     #### Units
     DimensionCurve.Dimension_units = self.Dimension_units
     DimensionCurve.Dimension_add_units_name = self.Dimension_add_units_name
index 9e30203..53e54e1 100644 (file)
@@ -171,14 +171,14 @@ class CLASS_atom_cluster_Elements(object):
         self.radii_ionic = radii_ionic
 
 # This is the class, which stores the properties of one atom.
-class CLASS_atom_cluster_atom(object):  
+class CLASS_atom_cluster_atom(object):
     __slots__ = ('location')
     def __init__(self, location):
         self.location = location
 
 # -----------------------------------------------------------------------------
 #                                                                Read atom data
-        
+
 def DEF_atom_read_atom_data():
 
     del ATOM_CLUSTER_ELEMENTS[:]
@@ -195,7 +195,7 @@ def DEF_atom_read_atom_data():
                                          radii,radii_ionic)
         ATOM_CLUSTER_ELEMENTS.append(li)
 
-  
+
 # -----------------------------------------------------------------------------
 #                                                           Routines for shapes
 
@@ -217,19 +217,19 @@ def vec_in_parabole(atom_pos, height, diameter):
 
     regular = True
     inner   = True
-      
-    px = atom_pos[0]  
-    py = atom_pos[1]  
+
+    px = atom_pos[0]
+    py = atom_pos[1]
     pz = atom_pos[2] + height/2.0
-    
+
     a = diameter / sqrt(4 * height)
-    
-    
+
+
     if pz < 0.0:
         return (False, False)
     if px == 0.0 and py == 0.0:
         return (True, True)
-         
+
     if py == 0.0:
         y = 0.0
         x = a * a * pz / px
@@ -238,17 +238,17 @@ def vec_in_parabole(atom_pos, height, diameter):
         y = pz * py * a * a / (px*px + py*py)
         x = y * px / py
         z = (x*x + y*y) / (a * a)
-    
+
     if( atom_pos.length > sqrt(x*x+y*y+z*z) ):
         regular = False
-    
+
     return (regular, inner)
 
 
 def vec_in_pyramide_square(atom_pos, size, skin):
-    
+
     """
-    Please, if possible leave all this! The code documents the 
+    Please, if possible leave all this! The code documents the
     mathemetical way of cutting a pyramide with square base.
 
     P1 = Vector((-size/2, 0.0, -size/4))
@@ -262,7 +262,7 @@ def vec_in_pyramide_square(atom_pos, size, skin):
     v12 = P1 - P6
     n1 = v11.cross(v12)
     g1 = -n1 * P1
-    
+
     # Second face
     v21 = P6 - P4
     v22 = P6 - P5
@@ -274,20 +274,20 @@ def vec_in_pyramide_square(atom_pos, size, skin):
     v32 = P1 - P6
     n3 = v32.cross(v31)
     g3 = -n3 * P1
-    
+
     # Forth face
     v41 = P6 - P2
     v42 = P2 - P4
     n4 = v41.cross(v42)
     g4 = -n4 * P2
-    
+
     # Fith face, base
     v51 = P2 - P1
     v52 = P2 - P4
     n5 = v51.cross(v52)
     g5 = -n5 * P2
     """
+
     # A much faster way for calculation:
     size2 = size  * size
     size3 = size2 * size
@@ -300,7 +300,7 @@ def vec_in_pyramide_square(atom_pos, size, skin):
     n4 = Vector(( 1/4, -1/4,  1/4)) * size2
     g4 = g1
     n5 = Vector(( 0.0,  0.0, -1/2)) * size2
-    g5 = -1/8 * size3  
+    g5 = -1/8 * size3
 
     distance_plane_1 = abs((n1 * atom_pos - g1)/n1.length)
     on_plane_1 = (atom_pos - n1 * (distance_plane_1/n1.length)).length
@@ -330,7 +330,7 @@ def vec_in_pyramide_square(atom_pos, size, skin):
         return (regular, inner)
 
     size = size * (1.0 - skin)
-    
+
     size2 = size  * size
     size3 = size2 * size
     n1 = Vector((-1/4, -1/4,  1/4)) * size2
@@ -342,7 +342,7 @@ def vec_in_pyramide_square(atom_pos, size, skin):
     n4 = Vector(( 1/4, -1/4,  1/4)) * size2
     g4 = g1
     n5 = Vector(( 0.0,  0.0, -1/2)) * size2
-    g5 = -1/8 * size3  
+    g5 = -1/8 * size3
 
     distance_plane_1 = abs((n1 * atom_pos - g1)/n1.length)
     on_plane_1 = (atom_pos - n1 * (distance_plane_1/n1.length)).length
@@ -354,7 +354,7 @@ def vec_in_pyramide_square(atom_pos, size, skin):
     on_plane_4 = (atom_pos - n4 * (distance_plane_4/n4.length)).length
     distance_plane_5 = abs((n5 * atom_pos - g5)/n5.length)
     on_plane_5 = (atom_pos - n5 * (distance_plane_5/n5.length)).length
-    
+
     inner = False
     if(atom_pos.length > on_plane_1):
         inner = True
@@ -371,22 +371,22 @@ def vec_in_pyramide_square(atom_pos, size, skin):
 
 
 def vec_in_pyramide_hex_abc(atom_pos, size, skin):
-    
+
     a = size/2.0
     #c = size/2.0*cos((30/360)*2.0*pi)
     c = size * 0.4330127020
-    #s = size/2.0*sin((30/360)*2.0*pi)  
-    s = size * 0.25   
+    #s = size/2.0*sin((30/360)*2.0*pi)
+    s = size * 0.25
     #h = 2.0 * (sqrt(6.0)/3.0) * c
     h = 1.632993162 * c
 
     """
-    Please, if possible leave all this! The code documents the 
+    Please, if possible leave all this! The code documents the
     mathemetical way of cutting a tetraeder.
 
     P1 = Vector((0.0,   a, 0.0))
     P2 = Vector(( -c,  -s, 0.0))
-    P3 = Vector((  c,  -s, 0.0))    
+    P3 = Vector((  c,  -s, 0.0))
     P4 = Vector((0.0, 0.0,  h))
     C = (P1+P2+P3+P4)/4.0
     P1 = P1 - C
@@ -399,7 +399,7 @@ def vec_in_pyramide_hex_abc(atom_pos, size, skin):
     v12 = P1 - P4
     n1 = v11.cross(v12)
     g1 = -n1 * P1
-    
+
     # Second face
     v21 = P2 - P3
     v22 = P2 - P4
@@ -411,7 +411,7 @@ def vec_in_pyramide_hex_abc(atom_pos, size, skin):
     v32 = P3 - P4
     n3 = v31.cross(v32)
     g3 = -n3 * P3
-    
+
     # Forth face
     v41 = P2 - P1
     v42 = P2 - P3
@@ -452,12 +452,12 @@ def vec_in_pyramide_hex_abc(atom_pos, size, skin):
         return (regular, inner)
 
     size = size * (1.0 - skin)
-    
+
     a = size/2.0
     #c = size/2.0*cos((30/360)*2.0*pi)
     c= size * 0.4330127020
-    #s = size/2.0*sin((30/360)*2.0*pi)  
-    s = size * 0.25   
+    #s = size/2.0*sin((30/360)*2.0*pi)
+    s = size * 0.25
     #h = 2.0 * (sqrt(6.0)/3.0) * c
     h = 1.632993162 * c
 
@@ -478,7 +478,7 @@ def vec_in_pyramide_hex_abc(atom_pos, size, skin):
     on_plane_3 = (atom_pos - n3 * (distance_plane_3/n3.length)).length
     distance_plane_4 = abs((n4 * atom_pos - g4)/n4.length)
     on_plane_4 = (atom_pos - n4 * (distance_plane_4/n4.length)).length
-    
+
     inner = False
     if(atom_pos.length > on_plane_1):
         inner = True
@@ -490,7 +490,7 @@ def vec_in_pyramide_hex_abc(atom_pos, size, skin):
         inner = True
 
     return (regular, inner)
-    
+
 
 
 def vec_in_octahedron(atom_pos,size, skin):
@@ -499,7 +499,7 @@ def vec_in_octahedron(atom_pos,size, skin):
     inner   = True
 
     """
-    Please, if possible leave all this! The code documents the 
+    Please, if possible leave all this! The code documents the
     mathemetical way of cutting an octahedron.
 
     P1 = Vector((-size/2, 0.0, 0.0))
@@ -514,19 +514,19 @@ def vec_in_octahedron(atom_pos,size, skin):
     v12 = P2 - P3
     n1 = v11.cross(v12)
     g1 = -n1 * P2
-    
+
     # Second face
     v21 = P1 - P5
     v22 = P1 - P3
     n2 = v21.cross(v22)
-    g2 = -n2 * P1 
-    
+    g2 = -n2 * P1
+
     # Third face
     v31 = P1 - P2
     v32 = P1 - P6
     n3 = v31.cross(v32)
     g3 = -n3 * P1
-    
+
     # Forth face
     v41 = P6 - P2
     v42 = P2 - P4
@@ -557,7 +557,7 @@ def vec_in_octahedron(atom_pos,size, skin):
     n8 = v82.cross(v81)
     g8 = -n8 * P1
     """
+
     # A much faster way for calculation:
     size2 = size  * size
     size3 = size2 * size
@@ -720,12 +720,12 @@ def vec_in_truncated_octahedron(atom_pos,size, skin):
     # pp = (size/2.0) - (sqrt(2.0)/2.0) * ((size/sqrt(2.0))/3.0)
     pp = size / 3.0
 
-    n_1 = Vector((1.0,0.0,0.0)) 
-    n_2 = Vector((-1.0,0.0,0.0))           
-    n_3 = Vector((0.0,1.0,0.0))    
+    n_1 = Vector((1.0,0.0,0.0))
+    n_2 = Vector((-1.0,0.0,0.0))
+    n_3 = Vector((0.0,1.0,0.0))
     n_4 = Vector((0.0,-1.0,0.0))
-    n_5 = Vector((0.0,0.0,1.0))    
-    n_6 = Vector((0.0,0.0,-1.0))   
+    n_5 = Vector((0.0,0.0,1.0))
+    n_6 = Vector((0.0,0.0,-1.0))
 
     distance_plane_1b = abs((n_1 * atom_pos + pp)/n_1.length)
     on_plane_1b = (atom_pos - n_1 * (distance_plane_1b/n_1.length)).length
@@ -773,7 +773,7 @@ def vec_in_truncated_octahedron(atom_pos,size, skin):
         return (regular, inner)
 
     size = size * (1.0 - skin)
-    
+
     # The normal octahedron
     size2 = size  * size
     size3 = size2 * size
@@ -815,13 +815,13 @@ def vec_in_truncated_octahedron(atom_pos,size, skin):
     # pp = (size/2.0) - (sqrt(2.0)/2.0) * ((size/sqrt(2.0))/3.0)
     pp = size / 3.0
 
-    n_1 = Vector((1.0,0.0,0.0)) 
-    n_2 = Vector((-1.0,0.0,0.0))           
-    n_3 = Vector((0.0,1.0,0.0))    
+    n_1 = Vector((1.0,0.0,0.0))
+    n_2 = Vector((-1.0,0.0,0.0))
+    n_3 = Vector((0.0,1.0,0.0))
     n_4 = Vector((0.0,-1.0,0.0))
-    n_5 = Vector((0.0,0.0,1.0))    
-    n_6 = Vector((0.0,0.0,-1.0))   
-    
+    n_5 = Vector((0.0,0.0,1.0))
+    n_6 = Vector((0.0,0.0,-1.0))
+
     distance_plane_1b = abs((n_1 * atom_pos + pp)/n_1.length)
     on_plane_1b = (atom_pos - n_1 * (distance_plane_1b/n_1.length)).length
     distance_plane_2b = abs((n_2 * atom_pos + pp)/n_2.length)
@@ -865,7 +865,7 @@ def vec_in_truncated_octahedron(atom_pos,size, skin):
         inner = True
     if(atom_pos.length > on_plane_6b):
         inner = True
-    
+
     return (regular, inner)
 
 # -----------------------------------------------------------------------------
@@ -906,11 +906,11 @@ def create_hexagonal_abcabc_lattice(ctype, size, skin, lattice):
     for k in range(-number_z,number_z+1):
         for j in range(-number_y,number_y+1):
             for i in range(-number_x,number_x+1):
-                atom = Vector((float(i)*e,float(j)*f,float(k)*g)) 
+                atom = Vector((float(i)*e,float(j)*f,float(k)*g))
 
                 if y_displ == 1:
                     if z_displ == 1:
-                        atom[0] += e/2.0  
+                        atom[0] += e/2.0
                     else:
                         atom[0] -= e/2.0
                 if z_displ == 1:
@@ -926,7 +926,7 @@ def create_hexagonal_abcabc_lattice(ctype, size, skin, lattice):
                     # size = height, skin = diameter
                     message = vec_in_pyramide_hex_abc(atom, size, skin)
                 elif ctype == "parabolid_abc":
-                    message = vec_in_parabole(atom, size, skin)          
+                    message = vec_in_parabole(atom, size, skin)
 
                 if message[0] == True and message[1] == True:
                     atom_add = CLASS_atom_cluster_atom(atom)
@@ -934,8 +934,8 @@ def create_hexagonal_abcabc_lattice(ctype, size, skin, lattice):
                     atom_number_total += 1
                     atom_number_drawn += 1
                 if message[0] == True and message[1] == False:
-                    atom_number_total += 1                 
-          
+                    atom_number_total += 1
+
             if y_displ == 1:
                 y_displ = 0
             else:
@@ -990,10 +990,10 @@ def create_hexagonal_abab_lattice(ctype, size, skin, lattice):
             for i in range(-number_x,number_x+1):
 
                 atom = Vector((float(i)*e,float(j)*f,float(k)*g))
-          
+
                 if "odd" in y_displ:
                     if "odd" in z_displ:
-                        atom[0] += e/2.0  
+                        atom[0] += e/2.0
                     else:
                         atom[0] -= e/2.0
                 if "odd" in z_displ:
@@ -1004,16 +1004,16 @@ def create_hexagonal_abab_lattice(ctype, size, skin, lattice):
                     message = vec_in_sphere(atom, size, skin)
                 elif ctype == "parabolid_ab":
                     # size = height, skin = diameter
-                    message = vec_in_parabole(atom, size, skin)          
-          
+                    message = vec_in_parabole(atom, size, skin)
+
                 if message[0] == True and message[1] == True:
                     atom_add = CLASS_atom_cluster_atom(atom)
                     ATOM_CLUSTER_ALL_ATOMS.append(atom_add)
                     atom_number_total += 1
                     atom_number_drawn += 1
                 if message[0] == True and message[1] == False:
-                    atom_number_total += 1  
-          
+                    atom_number_total += 1
+
             if "even" in y_displ:
                 y_displ = "odd"
             else:
@@ -1034,7 +1034,7 @@ def create_square_lattice(ctype, size, skin, lattice):
 
     atom_number_total = 0
     atom_number_drawn = 0
-    
+
     if ctype == "parabolid_square":
         # size = height, skin = diameter
         number_k = int(size/(2.0*lattice))
@@ -1043,14 +1043,14 @@ def create_square_lattice(ctype, size, skin, lattice):
     else:
         number_k = int(size/(2.0*lattice))
         number_j = int(size/(2.0*lattice))
-        number_i = int(size/(2.0*lattice))       
+        number_i = int(size/(2.0*lattice))
 
 
     for k in range(-number_k,number_k+1):
         for j in range(-number_j,number_j+1):
             for i in range(-number_i,number_i+1):
 
-                atom = Vector((float(i),float(j),float(k))) * lattice 
+                atom = Vector((float(i),float(j),float(k))) * lattice
 
                 if ctype == "sphere_square":
                     message = vec_in_sphere(atom, size, skin)
@@ -1058,9 +1058,9 @@ def create_square_lattice(ctype, size, skin, lattice):
                     message = vec_in_pyramide_square(atom, size, skin)
                 elif ctype == "parabolid_square":
                     # size = height, skin = diameter
-                    message = vec_in_parabole(atom, size, skin)          
+                    message = vec_in_parabole(atom, size, skin)
                 elif ctype == "octahedron":
-                    message = vec_in_octahedron(atom, size, skin)            
+                    message = vec_in_octahedron(atom, size, skin)
                 elif ctype == "truncated_octahedron":
                     message = vec_in_truncated_octahedron(atom,size, skin)
 
@@ -1070,7 +1070,7 @@ def create_square_lattice(ctype, size, skin, lattice):
                     atom_number_total += 1
                     atom_number_drawn += 1
                 if message[0] == True and message[1] == False:
-                    atom_number_total += 1 
+                    atom_number_total += 1
 
     print("Atom positions calculated")
 
@@ -1092,7 +1092,7 @@ def create_square_lattice(ctype, size, skin, lattice):
 
 # The following code is a translation from an existing Fortran code into Python.
 # The Fortran code has been created by Christine Mottet and translated by me
-# (Clemens Barth). 
+# (Clemens Barth).
 
 # Although a couple of code lines are non-typical for Python, it is best to
 # leave the code as is.
@@ -1138,7 +1138,7 @@ def create_icosahedron(size, lattice):
         z[i]   = 0.0
         y[i+4] = 0.0
         x[i+8] = 0.0
-    
+
     for i in range(2, 3+1):
         x[i]    =  tdef
         x[i+2]  = -tdef
@@ -1171,7 +1171,7 @@ def create_icosahedron(size, lattice):
             for i in range(1, 12+1):
                 for j in range(1, 12+1):
                     naret[i][j] = 0
-                    for k in range (1, 12+1): 
+                    for k in range (1, 12+1):
                         nfacet[i][j][k] = 0
 
             nl1 = 6
@@ -1195,7 +1195,7 @@ def create_icosahedron(size, lattice):
                 for j in range(2, 12+1):
                     if j <= i:
                         continue
-                    
+
                     xij = xs[j] - xs[i]
                     yij = ys[j] - ys[i]
                     zij = zs[j] - zs[i]
@@ -1208,11 +1208,11 @@ def create_icosahedron(size, lattice):
                     diffij = abs(dij2-dssn2)
                     if diffij >= epsi:
                         continue
-                    
+
                     for k in range(3, 12+1):
                         if k <= j:
                             continue
-                        
+
                         xjk = xs[k] - xs[j]
                         yjk = ys[k] - ys[j]
                         zjk = zs[k] - zs[j]
@@ -1223,7 +1223,7 @@ def create_icosahedron(size, lattice):
                         diffjk = abs(djk2-dssn2)
                         if diffjk >= epsi:
                             continue
-                        
+
                         xik = xs[k] - xs[i]
                         yik = ys[k] - ys[i]
                         zik = zs[k] - zs[i]
@@ -1234,7 +1234,7 @@ def create_icosahedron(size, lattice):
                         diffik = abs(dik2-dssn2)
                         if diffik >= epsi:
                             continue
-                        
+
                         if nfacet[i][j][k] != 0:
                             continue
 
@@ -1294,7 +1294,7 @@ def create_icosahedron(size, lattice):
 
     for i in range (1,natot+1):
 
-        atom = Vector((x[i],y[i],z[i])) * lattice 
+        atom = Vector((x[i],y[i],z[i])) * lattice
 
         atom_add = CLASS_atom_cluster_atom(atom)
         ATOM_CLUSTER_ALL_ATOMS.append(atom_add)
@@ -1302,20 +1302,3 @@ def create_icosahedron(size, lattice):
         atom_number_drawn += 1
 
     return (atom_number_total, atom_number_drawn)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
index 013d3e0..eb66c77 100644 (file)
@@ -995,7 +995,7 @@ def generateObject(context, muX, sigmaX, scaleX, upperSkewX, muY, sigmaY,
     if scaleDisplace:
 ##        bpy.data.objects[name].scale = Vector((averageX, averageY, averageZ))
         obj.object.scale = Vector((averageX, averageY, averageZ))
-    
+
     # For a slight speed bump / Readability:
 ##    mesh = bpy.data.meshes[name]
     mesh = obj.object.data
index bd5d6bc..c27e035 100644 (file)
@@ -54,7 +54,7 @@ class AMNodeEditorMaterialSelect(bpy.types.Operator):
     @classmethod
     def poll(cls, context):
         return context.active_object
-    
+
     def execute(self,context):
         bpy.context.active_object.active_material_index = int(self.material_select)
         return {'FINISHED'}
index 9d01b08..25f9df1 100644 (file)
@@ -81,4 +81,3 @@ def unregister():
             bpy.types.CYCLES_SCENE_PT_simplify.remove(unsimplify_ui)
         else:
             bpy.types.CyclesScene_PT_simplify.remove(unsimplify_ui)
-
index 846ba77..c9feb1d 100644 (file)
@@ -5,34 +5,34 @@ if "bpy" in locals():
        importlib.reload(JSONOps)
 else:
        from . import JSONOps
-       
+
 import bpy
 import os
 
 class AdjustableOperatorFromTexture(bpy.types.Operator):
-    
+
     """This operator generates adjustable materials from textures in Cycles.
 
 This is a subclass from bpy.types.Operator.
 """
 
     # Metadata of the operator
-    
+
     bl_idname = "com.new_adj_automat"
     bl_label = "Adjustable Material from Image"
     bl_options = {"UNDO"}
-    
+
     # Variables used for storing the filepath given by blender's file manager
-    
+
     filepath = bpy.props.StringProperty(subtype="FILE_PATH")
     filename = bpy.props.StringProperty()
     directory = bpy.props.StringProperty(subtype="FILE_PATH")
-    
-    
+
+
 
 
     def execute(self, context):
-        
+
         """This is the main runnable method of the operator.
 
 This creates all the node setup."""
@@ -40,12 +40,12 @@ This creates all the node setup."""
         # Create the material
 
         mat = bpy.data.materials.new("Material")
-            
+
         mat.use_nodes = True
         nodes = mat.node_tree.nodes
 
         # Empty whatever nodes we allready had.
-    
+
         for node in nodes.keys():
             nodes.remove(nodes[node])
 
@@ -70,7 +70,7 @@ This creates all the node setup."""
         # We set one of our blurs to be stronger
 
         blurs[1]["Blur strength"].outputs[0].default_value = 1000
-        
+
         # We link the blurs up to the rest of the material
 
         links = mat.node_tree.links
@@ -89,26 +89,26 @@ This creates all the node setup."""
         nodes_dict["Bump Image"].image = image_data
 
         # Try to add the material to the selected object
-        
+
         try:
             bpy.context.object.data.materials.append(mat)
         except AttributeError:
-            
+
             # If there is no object with materials selected,
             # don't add the material to anythinng.
-            
+
             pass
-        
+
         # Tell that all went well
-        
+
         return {"FINISHED"}
-    
+
     def invoke(self, context, event):
-        
+
         """This method opens the file browser. After that, the
 execute(...) method gets ran, creating the node setup.
 It also checks that the render engine is Cycles.  """
-        
+
         if bpy.context.scene.render.engine == 'CYCLES':
             self.filename = ""
             context.window_manager.fileselect_add(self)
index b080084..30d79ba 100644 (file)
@@ -75,7 +75,7 @@ The file is read using Python's built-in JSON parser, so indentation or line bre
     nodes_dict = {}
     nodes = mat.node_tree.nodes
 
-    # We iterate a first time to create the nodes with their settings 
+    # We iterate a first time to create the nodes with their settings
 
     for node in nodes_JSON["NodeSetup"]:
         technical_name = node["type"]
@@ -116,7 +116,7 @@ The file is read using Python's built-in JSON parser, so indentation or line bre
                 if len(node["in"][i]) == 3:
 
                     # Contruct and execute the line adding a link
-           
+
                     exec ("links.new(nodes_dict[\"" + node["in"][i][0] +
                           "\"].outputs[" + str(node["in"][i][1]) +
                           "], nodes_dict[\"" + node["label"] + "\"].inputs["
@@ -133,4 +133,4 @@ The file is read using Python's built-in JSON parser, so indentation or line bre
 
     # We return the nodes for purposes of further access to them
 
-    return nodes_dict
\ No newline at end of file
+    return nodes_dict
index 6a1aada..6c6cf0e 100644 (file)
@@ -33,7 +33,7 @@ bl_info = {
 
 import bpy
 from cacharanth import ui, meshcache
+
 def register():
     ui.register()
     meshcache.register()
index 2e79345..f8386fb 100644 (file)
@@ -42,14 +42,14 @@ class OperatorCallContext():
         # store active/selected state to restore it after operator execution
         self.curact = scene.objects.active
         self.cursel = { ob : ob.select for ob in scene.objects }
-        
+
         # undo can store files a lot when running operators internally,
         # disable since we only need one undo step after main operators anyway
         self.use_global_undo = prefs.edit.use_global_undo
         prefs.edit.use_global_undo = False
 
         return (self.curact, self.cursel)
-    
+
     def __exit__(self, exc_type, exc_value, traceback):
         scene = bpy.context.scene
         prefs = bpy.context.user_preferences
@@ -63,7 +63,7 @@ class OperatorCallContext():
 
 def select_single_object(ob):
     scene = bpy.context.scene
-    
+
     scene.objects.active = ob
     for tob in scene.objects:
         tob.select = (tob == ob)
index c201c89..ddec7a4 100644 (file)
@@ -123,4 +123,3 @@ class CMUMocapLib(bpy.types.AddonPreferences):
         layout.prop(self, "local_storage")
         layout.prop(self, "follow_structure")
         layout.prop(self, "automatically_import")
-
index 6c5c951..466a40b 100644 (file)
@@ -32,13 +32,13 @@ lfoot LegIK_L
 
 
 T_pose_align = [d.split() for d in """\
-clavicle UpArmRot 
-humerus LoArm 
+clavicle UpArmRot
+humerus LoArm
 radius Hand .8
 wrist Hand
-hipjoint UpLeg 
-femur LoLeg 
-tibia Foot 
+hipjoint UpLeg
+femur LoLeg
+tibia Foot
 foot Toe""".splitlines()]
 
 
@@ -126,7 +126,7 @@ class CMUMocapAlignArmatures(bpy.types.Operator):
         c_d = DPB['Hip_L'].matrix.translation
         b_d = .5 * (c_d + DPB['Hip_R'].matrix.translation)
 
-        # get alignment matrix        
+        # get alignment matrix
         S = Matrix().to_3x3()
         S[0] = (c_s - b_s).normalized()
         S[1] = (a_s - b_s).normalized()
@@ -142,14 +142,14 @@ class CMUMocapAlignArmatures(bpy.types.Operator):
         # scale source to match destination
         s = (a_d - b_d).length / (a_s - b_s).length
         bpy.ops.transform.resize(value=(s, s, s))
-        
+
         # align armatures
         rot = T.to_quaternion()
         bpy.ops.transform.rotate(value=rot.angle, axis=rot.axis)
         a_s = SPB['upperneck'].matrix.translation
         a_s = SMW * a_s
         bpy.ops.transform.translate(value=a_d - a_s)
-        
+
         bpy.ops.pose.select_all(action='DESELECT')
         for bdef in T_pose_align:
             for side in "lr":
@@ -280,7 +280,7 @@ class CMUMocapTransferer(bpy.types.Operator):
                     c = DPB[db].constraints["Floor"]
                     c.name = name
                     c.target = floor
-        
+
         bpy.ops.mhx.toggle_fk_ik(toggle="MhaArmIk_L 1 2 3")
         bpy.ops.mhx.toggle_fk_ik(toggle="MhaArmIk_R 1 18 19")
         bpy.ops.mhx.toggle_fk_ik(toggle="MhaLegIk_L 1 4 5")
@@ -296,4 +296,3 @@ class CMUMocapTransferer(bpy.types.Operator):
         bpy.context.scene.frame_set(bpy.context.scene.frame_current)
         context.window_manager.event_timer_remove(self.timer)
         bpy.ops.object.mode_set(mode='OBJECT')
-
index 6f74a2b..e2608ee 100644 (file)
@@ -7,17 +7,17 @@ class BezierPoint:
     @staticmethod
     def FromBlenderBezierPoint(blenderBezierPoint):
         return BezierPoint(blenderBezierPoint.handle_left, blenderBezierPoint.co, blenderBezierPoint.handle_right)
-        
-        
+
+
     def __init__(self, handle_left, co, handle_right):
         self.handle_left = handle_left
         self.co = co
         self.handle_right = handle_right
-    
-    
+
+
     def Copy(self):
         return BezierPoint(self.handle_left.copy(), self.co.copy(), self.handle_right.copy())
-        
+
     def Reversed(self):
         return BezierPoint(self.handle_right, self.co, self.handle_left)
 
@@ -34,14 +34,14 @@ class BezierSegment:
         bp2 = BezierPoint.FromBlenderBezierPoint(blenderBezierPoint2)
 
         return BezierSegment(bp1, bp2)
-        
-        
+
+
     def Copy(self):
         return BezierSegment(self.bezierPoint1.Copy(), self.bezierPoint2.Copy())
-        
+
     def Reversed(self):
         return BezierSegment(self.bezierPoint2.Reversed(), self.bezierPoint1.Reversed())
-        
+
     def Reverse(self):
         # make a copy, otherwise neighboring segment may be affected
         tmp = self.bezierPoint1.Copy()
@@ -49,41 +49,41 @@ class BezierSegment:
         self.bezierPoint2 = tmp
         self.bezierPoint1.Reverse()
         self.bezierPoint2.Reverse()
-    
-    
+
+
     def __init__(self, bezierPoint1, bezierPoint2):
         # bpy.types.BezierSplinePoint
         # ## NOTE/TIP: copy() helps with repeated (intersection) action -- ??
         self.bezierPoint1 = bezierPoint1.Copy()
         self.bezierPoint2 = bezierPoint2.Copy()
-        
+
         self.ctrlPnt0 = self.bezierPoint1.co
         self.ctrlPnt1 = self.bezierPoint1.handle_right
         self.ctrlPnt2 = self.bezierPoint2.handle_left
         self.ctrlPnt3 = self.bezierPoint2.co
-        
+
         self.coeff0 = self.ctrlPnt0
         self.coeff1 = self.ctrlPnt0 * (-3.0) + self.ctrlPnt1 * (+3.0)
         self.coeff2 = self.ctrlPnt0 * (+3.0) + self.ctrlPnt1 * (-6.0) + self.ctrlPnt2 * (+3.0)
         self.coeff3 = self.ctrlPnt0 * (-1.0) + self.ctrlPnt1 * (+3.0) + self.ctrlPnt2 * (-3.0) + self.ctrlPnt3
-        
-        
+
+
     def CalcPoint(self, parameter = 0.5):
         parameter2 = parameter * parameter
         parameter3 = parameter * parameter2
-        
+
         rvPoint = self.coeff0 + self.coeff1 * parameter + self.coeff2 * parameter2 + self.coeff3 * parameter3
-        
+
         return rvPoint
-        
-        
+
+
     def CalcDerivative(self, parameter = 0.5):
         parameter2 = parameter * parameter
-        
+
         rvPoint = self.coeff1 + self.coeff2 * parameter * 2.0 + self.coeff3 * parameter2 * 3.0
-        
+
         return rvPoint
-        
+
 
     def CalcLength(self, nrSamples = 2):
         nrSamplesFloat = float(nrSamples)
@@ -91,101 +91,101 @@ class BezierSegment:
         for iSample in range(nrSamples):
             par1 = float(iSample) / nrSamplesFloat
             par2 = float(iSample + 1) / nrSamplesFloat
-            
+
             point1 = self.CalcPoint(parameter = par1)
             point2 = self.CalcPoint(parameter = par2)
             diff12 = point1 - point2
-            
+
             rvLength += diff12.magnitude
-        
+
         return rvLength
-        
-    
+
+
     #http://en.wikipedia.org/wiki/De_Casteljau's_algorithm
     def CalcSplitPoint(self, parameter = 0.5):
         par1min = 1.0 - parameter
-        
+
         bez00 = self.ctrlPnt0
         bez01 = self.ctrlPnt1
         bez02 = self.ctrlPnt2
         bez03 = self.ctrlPnt3
-        
+
         bez10 = bez00 * par1min + bez01 * parameter
         bez11 = bez01 * par1min + bez02 * parameter
         bez12 = bez02 * par1min + bez03 * parameter
-        
+
         bez20 = bez10 * par1min + bez11 * parameter
         bez21 = bez11 * par1min + bez12 * parameter
-        
+
         bez30 = bez20 * par1min + bez21 * parameter
-        
+
         bezPoint1 = BezierPoint(self.bezierPoint1.handle_left, bez00, bez10)
         bezPointNew = BezierPoint(bez20, bez30, bez21)
         bezPoint2 = BezierPoint(bez12, bez03, self.bezierPoint2.handle_right)
-        
+
         return [bezPoint1, bezPointNew, bezPoint2]
-            
+
 
 class BezierSpline:
     @staticmethod
     def FromSegments(listSegments):
         rvSpline = BezierSpline(None)
-        
+
         rvSpline.segments = listSegments
-        
+
         return rvSpline
-    
-    
+
+
     def __init__(self, blenderBezierSpline):
         if not blenderBezierSpline is None:
-            if blenderBezierSpline.type != 'BEZIER': 
+            if blenderBezierSpline.type != 'BEZIER':
                 print("## ERROR:", "blenderBezierSpline.type != 'BEZIER'")
                 raise Exception("blenderBezierSpline.type != 'BEZIER'")
             if len(blenderBezierSpline.bezier_points) < 1:
                 if not blenderBezierSpline.use_cyclic_u:
                     print("## ERROR:", "len(blenderBezierSpline.bezier_points) < 1")
                     raise Exception("len(blenderBezierSpline.bezier_points) < 1")
-        
+
         self.bezierSpline = blenderBezierSpline
-        
+
         self.resolution = 12
         self.isCyclic = False
         if not self.bezierSpline is None:
             self.resolution = self.bezierSpline.resolution_u
             self.isCyclic = self.bezierSpline.use_cyclic_u
-            
+
         self.segments = self.SetupSegments()
-        
-        
+
+
     def __getattr__(self, attrName):
         if attrName == "nrSegments":
             return len(self.segments)
-        
+
         if attrName == "bezierPoints":
             rvList = []
-            
+
             for seg in self.segments: rvList.append(seg.bezierPoint1)
             if not self.isCyclic: rvList.append(self.segments[-1].bezierPoint2)
-            
+
             return rvList
-        
+
         if attrName == "resolutionPerSegment":
             try: rvResPS = int(self.resolution / self.nrSegments)
             except: rvResPS = 2
             if rvResPS < 2: rvResPS = 2
-            
+
             return rvResPS
-        
+
         if attrName == "length":
             return self.CalcLength()
-        
+
         return None
-        
-        
+
+
     def SetupSegments(self):
         rvSegments = []
         if self.bezierSpline is None: return rvSegments
-        
+
         nrBezierPoints = len(self.bezierSpline.bezier_points)
         for iBezierPoint in range(nrBezierPoints - 1):
             bezierPoint1 = self.bezierSpline.bezier_points[iBezierPoint]
@@ -195,10 +195,10 @@ class BezierSpline:
             bezierPoint1 = self.bezierSpline.bezier_points[-1]
             bezierPoint2 = self.bezierSpline.bezier_points[0]
             rvSegments.append(BezierSegment.FromBlenderBezierPoints(bezierPoint1, bezierPoint2))
-        
+
         return rvSegments
-        
-        
+
+
     def UpdateSegments(self, newSegments):
         prevNrSegments = len(self.segments)
         diffNrSegments = len(newSegments) - prevNrSegments
@@ -206,154 +206,154 @@ class BezierSpline:
             newBezierPoints = []
             for segment in newSegments: newBezierPoints.append(segment.bezierPoint1)
             if not self.isCyclic: newBezierPoints.append(newSegments[-1].bezierPoint2)
-        
+
             self.bezierSpline.bezier_points.add(diffNrSegments)
-            
+
             for i, bezPoint in enumerate(newBezierPoints):
                 blBezPoint = self.bezierSpline.bezier_points[i]
-                
+
                 blBezPoint.tilt = 0
                 blBezPoint.radius = 1.0
-                
+
                 blBezPoint.handle_left_type = 'FREE'
                 blBezPoint.handle_left = bezPoint.handle_left
                 blBezPoint.co = bezPoint.co
                 blBezPoint.handle_right_type = 'FREE'
-                blBezPoint.handle_right = bezPoint.handle_right    
+                blBezPoint.handle_right = bezPoint.handle_right
 
             self.segments = newSegments
         else:
             print("### WARNING: UpdateSegments(): not diffNrSegments > 0")
-            
-    
+
+
     def Reversed(self):
         revSegments = []
-        
+
         for iSeg in reversed(range(self.nrSegments)): revSegments.append(self.segments[iSeg].Reversed())
-        
+
         rvSpline = BezierSpline.FromSegments(revSegments)
         rvSpline.resolution = self.resolution
         rvSpline.isCyclic = self.isCyclic
-        
+
         return rvSpline
-            
-    
+
+
     def Reverse(self):
         revSegments = []
-        
-        for iSeg in reversed(range(self.nrSegments)): 
+
+        for iSeg in reversed(range(self.nrSegments)):
             self.segments[iSeg].Reverse()
             revSegments.append(self.segments[iSeg])
-        
+
         self.segments = revSegments
-        
-        
+
+
     def CalcDivideResolution(self, segment, parameter):
         if not segment in self.segments:
             print("### WARNING: InsertPoint(): not segment in self.segments")
             return None
-            
+
         iSeg = self.segments.index(segment)
         dPar = 1.0 / self.nrSegments
         splinePar = dPar * (parameter + float(iSeg))
-        
+
         res1 = int(splinePar * self.resolution)
         if res1 < 2:
             print("### WARNING: CalcDivideResolution(): res1 < 2 -- res1: %d" % res1, "-- setting it to 2")
             res1 = 2
-            
+
         res2 = int((1.0 - splinePar) * self.resolution)
         if res2 < 2:
             print("### WARNING: CalcDivideResolution(): res2 < 2 -- res2: %d" % res2, "-- setting it to 2")
             res2 = 2
-        
+
         return [res1, res2]
         # return [self.resolution, self.resolution]
-        
-        
+
+
     def CalcPoint(self, parameter):
         nrSegs = self.nrSegments
-        
+
         segmentIndex = int(nrSegs * parameter)
         if segmentIndex < 0: segmentIndex = 0
         if segmentIndex > (nrSegs - 1): segmentIndex = nrSegs - 1
-        
+
         segmentParameter = nrSegs * parameter - segmentIndex
         if segmentParameter < 0.0: segmentParameter = 0.0
         if segmentParameter > 1.0: segmentParameter = 1.0
-        
+
         return self.segments[segmentIndex].CalcPoint(parameter = segmentParameter)
-        
-        
+
+
     def CalcDerivative(self, parameter):
         nrSegs = self.nrSegments
-        
+
         segmentIndex = int(nrSegs * parameter)
         if segmentIndex < 0: segmentIndex = 0
         if segmentIndex > (nrSegs - 1): segmentIndex = nrSegs - 1
-        
+
         segmentParameter = nrSegs * parameter - segmentIndex
         if segmentParameter < 0.0: segmentParameter = 0.0
         if segmentParameter > 1.0: segmentParameter = 1.0
-        
+
         return self.segments[segmentIndex].CalcDerivative(parameter = segmentParameter)
-        
-        
+
+
     def InsertPoint(self, segment, parameter):
         if not segment in self.segments:
             print("### WARNING: InsertPoint(): not segment in self.segments")
             return
         iSeg = self.segments.index(segment)
         nrSegments = len(self.segments)
-            
+
         splitPoints = segment.CalcSplitPoint(parameter = parameter)
         bezPoint1 = splitPoints[0]
         bezPointNew = splitPoints[1]
         bezPoint2 = splitPoints[2]
-        
+
         segment.bezierPoint1.handle_right = bezPoint1.handle_right
         segment.bezierPoint2 = bezPointNew
-        
-        if iSeg < (nrSegments - 1): 
+
+        if iSeg < (nrSegments - 1):
             nextSeg = self.segments[iSeg + 1]
             nextSeg.bezierPoint1.handle_left = bezPoint2.handle_left
         else:
             if self.isCyclic:
                 nextSeg = self.segments[0]
                 nextSeg.bezierPoint1.handle_left = bezPoint2.handle_left
-            
-        
+
+
         newSeg = BezierSegment(bezPointNew, bezPoint2)
         self.segments.insert(iSeg + 1, newSeg)
-        
-        
+
+
     def Split(self, segment, parameter):
         if not segment in self.segments:
             print("### WARNING: InsertPoint(): not segment in self.segments")
             return None
         iSeg = self.segments.index(segment)
         nrSegments = len(self.segments)
-            
+
         splitPoints = segment.CalcSplitPoint(parameter = parameter)
         bezPoint1 = splitPoints[0]
         bezPointNew = splitPoints[1]
         bezPoint2 = splitPoints[2]
-        
-                
+
+
         newSpline1Segments = []
         for iSeg1 in range(iSeg): newSpline1Segments.append(self.segments[iSeg1])
         if len(newSpline1Segments) > 0: newSpline1Segments[-1].bezierPoint2.handle_right = bezPoint1.handle_right
         newSpline1Segments.append(BezierSegment(bezPoint1, bezPointNew))
-        
+
         newSpline2Segments = []
         newSpline2Segments.append(BezierSegment(bezPointNew, bezPoint2))
         for iSeg2 in range(iSeg + 1, nrSegments): newSpline2Segments.append(self.segments[iSeg2])
         if len(newSpline2Segments) > 1: newSpline2Segments[1].bezierPoint1.handle_left = newSpline2Segments[0].bezierPoint2.handle_left
-        
-        
+
+
         newSpline1 = BezierSpline.FromSegments(newSpline1Segments)
         newSpline2 = BezierSpline.FromSegments(newSpline2Segments)
-        
+
         return [newSpline1, newSpline2]
 
 
@@ -361,27 +361,27 @@ class BezierSpline:
         if mode == 'At midpoint':
             self.JoinAtMidpoint(spline2)
             return
-            
+
         if mode == 'Insert segment':
             self.JoinInsertSegment(spline2)
             return
-            
-        print("### ERROR: Join(): unknown mode:", mode)        
+
+        print("### ERROR: Join(): unknown mode:", mode)
 
 
     def JoinAtMidpoint(self, spline2):
         bezPoint1 = self.segments[-1].bezierPoint2
         bezPoint2 = spline2.segments[0].bezierPoint1
-    
+
         mpHandleLeft = bezPoint1.handle_left.copy()
         mpCo = (bezPoint1.co + bezPoint2.co) * 0.5
         mpHandleRight = bezPoint2.handle_right.copy()
         mpBezPoint = BezierPoint(mpHandleLeft, mpCo, mpHandleRight)
-        
+
         self.segments[-1].bezierPoint2 = mpBezPoint
         spline2.segments[0].bezierPoint1 = mpBezPoint
         for seg2 in spline2.segments: self.segments.append(seg2)
-        
+
         self.resolution += spline2.resolution
         self.isCyclic = False    # is this ok?
 
@@ -389,25 +389,25 @@ class BezierSpline:
     def JoinInsertSegment(self, spline2):
         self.segments.append(BezierSegment(self.segments[-1].bezierPoint2, spline2.segments[0].bezierPoint1))
         for seg2 in spline2.segments: self.segments.append(seg2)
-        
+
         self.resolution += spline2.resolution    # extra segment will usually be short -- impact on resolution negligable
-        
+
         self.isCyclic = False    # is this ok?
-        
-        
+
+
     def RefreshInScene(self):
         bezierPoints = self.bezierPoints
-        
+
         currNrBezierPoints = len(self.bezierSpline.bezier_points)
         diffNrBezierPoints = len(bezierPoints) - currNrBezierPoints
         if diffNrBezierPoints > 0: self.bezierSpline.bezier_points.add(diffNrBezierPoints)
-        
+
         for i, bezPoint in enumerate(bezierPoints):
             blBezPoint = self.bezierSpline.bezier_points[i]
-            
+
             blBezPoint.tilt = 0
             blBezPoint.radius = 1.0
-            
+
             blBezPoint.handle_left_type = 'FREE'
             blBezPoint.handle_left = bezPoint.handle_left
             blBezPoint.co = bezPoint.co
@@ -416,179 +416,179 @@ class BezierSpline:
 
         self.bezierSpline.use_cyclic_u = self.isCyclic
         self.bezierSpline.resolution_u = self.resolution
-        
-    
+
+
     def CalcLength(self):
         try: nrSamplesPerSegment = int(self.resolution / self.nrSegments)
         except: nrSamplesPerSegment = 2
         if nrSamplesPerSegment < 2: nrSamplesPerSegment = 2
-        
+
         rvLength = 0.0
         for segment in self.segments:
             rvLength += segment.CalcLength(nrSamples = nrSamplesPerSegment)
-        
+
         return rvLength
-        
-    
+
+
     def GetLengthIsSmallerThan(self, threshold):
         try: nrSamplesPerSegment = int(self.resolution / self.nrSegments)
         except: nrSamplesPerSegment = 2
         if nrSamplesPerSegment < 2: nrSamplesPerSegment = 2
-        
+
         length = 0.0
         for segment in self.segments:
             length += segment.CalcLength(nrSamples = nrSamplesPerSegment)
             if not length < threshold: return False
-        
+
         return True
-        
-        
+
+
 class Curve:
     def __init__(self, blenderCurve):
         self.curve = blenderCurve
         self.curveData = blenderCurve.data
-        
+
         self.splines = self.SetupSplines()
-        
-        
+
+
     def __getattr__(self, attrName):
         if attrName == "nrSplines":
             return len(self.splines)
-        
+
         if attrName == "length":
             return self.CalcLength()
-        
+
         if attrName == "worldMatrix":
             return self.curve.matrix_world
-        
+
         if attrName == "location":
             return self.curve.location
-        
+
         return None
-        
-        
+
+
     def SetupSplines(self):
         rvSplines = []
         for spline in self.curveData.splines:
             if spline.type != 'BEZIER':
                 print("## WARNING: only bezier splines are supported, atm; other types are ignored")
                 continue
-            
+
             try: newSpline = BezierSpline(spline)
-            except: 
+            except:
                 print("## EXCEPTION: newSpline = BezierSpline(spline)")
                 continue
-            
+
             rvSplines.append(newSpline)
-        
+
         return rvSplines
-        
-        
+
+
     def RebuildInScene(self):
         self.curveData.splines.clear()
-        
+
         for spline in self.splines:
             blSpline = self.curveData.splines.new('BEZIER')
             blSpline.use_cyclic_u = spline.isCyclic
             blSpline.resolution_u = spline.resolution
-            
+
             bezierPoints = []
             for segment in spline.segments: bezierPoints.append(segment.bezierPoint1)
             if not spline.isCyclic: bezierPoints.append(spline.segments[-1].bezierPoint2)
             #else: print("????", "spline.isCyclic")
-            
+
             nrBezierPoints = len(bezierPoints)
             blSpline.bezier_points.add(nrBezierPoints - 1)
-                        
+
             for i, blBezPoint in enumerate(blSpline.bezier_points):
                 bezPoint = bezierPoints[i]
-                
+
                 blBezPoint.tilt = 0
                 blBezPoint.radius = 1.0
-                
+
                 blBezPoint.handle_left_type = 'FREE'
                 blBezPoint.handle_left = bezPoint.handle_left
                 blBezPoint.co = bezPoint.co
                 blBezPoint.handle_right_type = 'FREE'
                 blBezPoint.handle_right = bezPoint.handle_right
-        
-    
+
+
     def CalcLength(self):
         rvLength = 0.0
         for spline in self.splines:
             rvLength += spline.length
-        
+
         return rvLength
-        
-        
+
+
     def RemoveShortSplines(self, threshold):
         splinesToRemove = []
-        
+
         for spline in self.splines:
             if spline.GetLengthIsSmallerThan(threshold): splinesToRemove.append(spline)
-            
+
         for spline in splinesToRemove: self.splines.remove(spline)
-        
+
         return len(splinesToRemove)
-        
-        
+
+
     def JoinNeighbouringSplines(self, startEnd, threshold, mode):
         nrJoins = 0
-        
+
         while True:
             firstPair = self.JoinGetFirstPair(startEnd, threshold)
             if firstPair is None: break
-            
+
             firstPair[0].Join(firstPair[1], mode)
             self.splines.remove(firstPair[1])
-            
+
             nrJoins += 1
-            
+
         return nrJoins
-            
-    
+
+
     def JoinGetFirstPair(self, startEnd, threshold):
         nrSplines = len(self.splines)
-        
+
         if startEnd:
             for iCurrentSpline in range(nrSplines):
                 currentSpline = self.splines[iCurrentSpline]
-                
+
                 for iNextSpline in range(iCurrentSpline + 1, nrSplines):
                     nextSpline = self.splines[iNextSpline]
-                    
+
                     currEndPoint = currentSpline.segments[-1].bezierPoint2.co
                     nextStartPoint = nextSpline.segments[0].bezierPoint1.co
                     if Math.IsSamePoint(currEndPoint, nextStartPoint, threshold): return [currentSpline, nextSpline]
-                    
+
                     nextEndPoint = nextSpline.segments[-1].bezierPoint2.co
                     currStartPoint = currentSpline.segments[0].bezierPoint1.co
                     if Math.IsSamePoint(nextEndPoint, currStartPoint, threshold): return [nextSpline, currentSpline]
-                    
+
             return None
         else:
             for iCurrentSpline in range(nrSplines):
                 currentSpline = self.splines[iCurrentSpline]
-                
+
                 for iNextSpline in range(iCurrentSpline + 1, nrSplines):
                     nextSpline = self.splines[iNextSpline]
-                    
+
                     currEndPoint = currentSpline.segments[-1].bezierPoint2.co
                     nextStartPoint = nextSpline.segments[0].bezierPoint1.co
                     if Math.IsSamePoint(currEndPoint, nextStartPoint, threshold): return [currentSpline, nextSpline]
-                    
+
                     nextEndPoint = nextSpline.segments[-1].bezierPoint2.co
                     currStartPoint = currentSpline.segments[0].bezierPoint1.co
                     if Math.IsSamePoint(nextEndPoint, currStartPoint, threshold): return [nextSpline, currentSpline]
-                    
+
                     if Math.IsSamePoint(currEndPoint, nextEndPoint, threshold):
                         nextSpline.Reverse()
                         #print("## ", "nextSpline.Reverse()")
                         return [currentSpline, nextSpline]
-                    
+
                     if Math.IsSamePoint(currStartPoint, nextStartPoint, threshold):
                         currentSpline.Reverse()
                         #print("## ", "currentSpline.Reverse()")
                         return [currentSpline, nextSpline]
-                        
+
             return None
index 208f769..8ac6ff4 100644 (file)
@@ -3,110 +3,110 @@ from mathutils import *
 
 def IsSamePoint(v31, v32, limitDistance):
     if (v31 - v32).magnitude < limitDistance: return True
-    
+
     return False
 
-    
+
 class Plane:
     @staticmethod
     def XY():
         p1 = Vector((0, 0, 0))
         p2 = Vector((1, 0, 0))
         p3 = Vector((0, 1, 0))
-        
+
         return Plane(p1, p2, p3)
-        
+
 
     # plane equation: (p - position).dot(normal) = 0
     def __init__(self, P1, P2, P3):
         self.normal = (P2 - P1).cross(P3 - P1)
         self.normal.normalize()
-        
+
         self.position = P1
-        
-        
+
+
     def CalcIntersectionPointLineSegment(self, PL1, PL2):
         DL = PL2 - PL1
-        
+
         try: rvPar = ((self.position - PL1).dot(self.normal)) / (DL.dot(self.normal))
         except: return None
-        
+
         return rvPar
-        
-        
+
+
     def CalcNormalParameter(self, vector):
         return (vector - self.position).dot(self.normal)
-        
-        
+
+
     def CalcProjection(self, vector):
         normalParameter = self.CalcNormalParameter(vector)
-        
+
         rvv3 = vector - (self.normal * normalParameter)
-        
+
         return [normalParameter, rvv3]
-        
-        
-    
+
+
+
 # http://geomalgorithms.com/a07-_distance.html
 def CalcClosestPointLineSegments(v3P0, v3P1, v3Q0, v3Q1):
     u = v3P1 - v3P0
     v = v3Q1 - v3Q0
-    
+
     w0 = v3P0 - v3Q0
     a = u.dot(u)
     b = u.dot(v)
     c = v.dot(v)
     d = u.dot(w0)
     e = v.dot(w0)
-    
-    
+
+
     try: parP = (b * e - c * d) / (a * c - b * b)
     except: return None
-    
+
     try: parQ = (a * e - b * d) / (a * c - b * b)
     except: return None
-    
-    
+
+
     return [parP, parQ]
 
-    
+
 def CalcIntersectionPointLineSegments(v3P0, v3P1, v3Q0, v3Q1, limitDistance):
     rvList = CalcClosestPointLineSegments(v3P0, v3P1, v3Q0, v3Q1)
     if rvList is None: return None
-    
-    
+
+
     parP = rvList[0]
     if parP < 0.0: return None
     if parP > 1.0: return None
-    
+
     parQ = rvList[1]
     if parQ < 0.0: return None
     if parQ > 1.0: return None
-    
-    
+
+
     pointP = v3P0 + ((v3P1 - v3P0) * parP)
     pointQ = v3Q0 + ((v3Q1 - v3Q0) * parQ)
     if not IsSamePoint(pointP, pointQ, limitDistance): return None
-    
+
     return [parP, parQ, pointP, pointQ]
 
-    
+
 def CalcIntersectionPointsLineSegmentsPOV(v3P0, v3P1, v3Q0, v3Q1, v3POV):
     planeQ = Plane(v3POV, v3Q0, v3Q1)
     parP = planeQ.CalcIntersectionPointLineSegment(v3P0, v3P1)
     if parP is None: return None
     if parP < 0.0: return None
     if parP > 1.0: return None
-    
+
     planeP = Plane(v3POV, v3P0, v3P1)
     parQ = planeP.CalcIntersectionPointLineSegment(v3Q0, v3Q1)
     if parQ is None: return None
     if parQ < 0.0: return None
     if parQ > 1.0: return None
-    
+
     return [parP, parQ]
 
-    
+
 def CalcIntersectionPointsLineSegmentsDIR(v3P0, v3P1, v3Q0, v3Q1, v3DIR):
     v3POV = v3Q0 + v3DIR
     planeQ = Plane(v3POV, v3Q0, v3Q1)
@@ -114,24 +114,22 @@ def CalcIntersectionPointsLineSegmentsDIR(v3P0, v3P1, v3Q0, v3Q1, v3DIR):
     if parP is None: return None
     if parP < 0.0: return None
     if parP > 1.0: return None
-    
+
     v3POV = v3P0 + v3DIR
     planeP = Plane(v3POV, v3P0, v3P1)
     parQ = planeP.CalcIntersectionPointLineSegment(v3Q0, v3Q1)
     if parQ is None: return None
     if parQ < 0.0: return None
     if parQ > 1.0: return None
-    
+
     return [parP, parQ]
-    
+
 
 
 def CalcRotationMatrix(v3From, v3To):
     cross = v3From.cross(v3To)
-    
+
     try: angle = v3From.angle(v3To)
     except: return Matrix.Identity(4)
-    
+
     return Matrix.Rotation(angle, 4, cross)        # normalize axis?
-    
-    
index ac226e2..6c9eed5 100644 (file)
@@ -16,34 +16,34 @@ class OperatorSelectionInfo(bpy.types.Operator):
     bl_idname = "curvetools2.operatorselectioninfo"
     bl_label = "Selection Info"
     bl_description = "Maintains a list of selected objects in the order they were selected"
-    
-    
+
+
     @classmethod
     def poll(cls, context):
         selectedObjectNames = Properties.CurveTools2SelectedObject.GetSelectedObjectNames()
         selectedBlenderObjectNames = Properties.CurveTools2SelectedObject.GetSelectedBlenderObjectNames()
-        
+
         sleepTime = 0.02
-        
+
         lock = threading.Lock()
         lock_holder = threading.Thread(target = Properties.CurveTools2SelectedObject.UpdateThreadTarget, args=(lock, sleepTime, selectedObjectNames, selectedBlenderObjectNames), name='OperatorSelectionInfoThread')
         # lock_holder = threading.Thread(target = Properties.CurveTools2SelectedObject.UpdateThreadTarget2, args=(lock, sleepTime, selectedObjectNames, selectedBlenderObjectNames, context), name='OperatorSelectionInfoThread')
         lock_holder.setDaemon(True)
         lock_holder.start()
-        
+
         return True
 
-            
+
     def execute(self, context):
         nrSelectedObjects = bpy.context.scene.curvetools.NrSelectedObjects
-        
+
         self.report({'INFO'}, "Selection Info: nrSelectedObjects: %d" % nrSelectedObjects)
-        
+
         selectedObjects = bpy.context.scene.curvetools.SelectedObjects
         selectedObjectValues = selectedObjects.values()
         for i, selectedObject in enumerate(selectedObjectValues):
             print("--", "selected object %d of %d: %s" % (i + 1, nrSelectedObjects, selectedObject.name))
-        
+
         return {'FINISHED'}
 
 
@@ -54,26 +54,26 @@ class OperatorCurveInfo(bpy.types.Operator):
     bl_idname = "curvetools2.operatorcurveinfo"
     bl_label = "Info"
     bl_description = "Displays general info about the active/selected curve"
-    
-    
+
+
     @classmethod
     def poll(cls, context):
         return Util.Selected1Curve()
 
-            
+
     def execute(self, context):
         curve = Curves.Curve(context.active_object)
-        
+
         nrSplines = len(curve.splines)
         nrSegments = 0
         nrEmptySplines = 0
-        for spline in curve.splines: 
+        for spline in curve.splines:
             nrSegments += spline.nrSegments
             if spline.nrSegments < 1: nrEmptySplines += 1
-        
-        
+
+
         self.report({'INFO'}, "nrSplines: %d; nrSegments: %d; nrEmptySplines: %d" % (nrSplines, nrSegments, nrEmptySplines))
-        
+
         return {'FINISHED'}
 
 
@@ -82,18 +82,18 @@ class OperatorCurveLength(bpy.types.Operator):
     bl_idname = "curvetools2.operatorcurvelength"
     bl_label = "Length"
     bl_description = "Calculates the length of the active/selected curve"
-    
-    
+
+
     @classmethod
     def poll(cls, context):
         return Util.Selected1Curve()
 
-            
+
     def execute(self, context):
         curve = Curves.Curve(context.active_object)
-        
+
         context.scene.curvetools.CurveLength = curve.length
-        
+
         return {'FINISHED'}
 
 
@@ -102,31 +102,31 @@ class OperatorSplinesInfo(bpy.types.Operator):
     bl_idname = "curvetools2.operatorsplinesinfo"
     bl_label = "Info"
     bl_description = "Displays general info about the splines of the active/selected curve"
-    
-    
+
+
     @classmethod
     def poll(cls, context):
         return Util.Selected1Curve()
 
-            
+
     def execute(self, context):
         curve = Curves.Curve(context.active_object)
         nrSplines = len(curve.splines)
-        
+
         print("")
-        print("OperatorSplinesInfo:", "nrSplines:", nrSplines)        
-        
+        print("OperatorSplinesInfo:", "nrSplines:", nrSplines)
+
         nrEmptySplines = 0
         for iSpline, spline in enumerate(curve.splines):
-            print("--", "spline %d of %d: nrSegments: %d" % (iSpline + 1, nrSplines, spline.nrSegments))        
-            
-            if spline.nrSegments < 1: 
+            print("--", "spline %d of %d: nrSegments: %d" % (iSpline + 1, nrSplines, spline.nrSegments))
+
+            if spline.nrSegments < 1:
                 nrEmptySplines += 1
-                print("--", "--", "## WARNING: spline has no segments and will therefor be ignored in any further calculations")        
-        
-        
+                print("--", "--", "## WARNING: spline has no segments and will therefor be ignored in any further calculations")
+
+
         self.report({'INFO'}, "nrSplines: %d; nrEmptySplines: %d" % (nrSplines, nrEmptySplines) + " -- more info: see console")
-        
+
         return {'FINISHED'}
 
 
@@ -135,39 +135,39 @@ class OperatorSegmentsInfo(bpy.types.Operator):
     bl_idname = "curvetools2.operatorsegmentsinfo"
     bl_label = "Info"
     bl_description = "Displays general info about the segments of the active/selected curve"
-    
-    
+
+
     @classmethod
     def poll(cls, context):
         return Util.Selected1Curve()
 
-            
+
     def execute(self, context):
         curve = Curves.Curve(context.active_object)
         nrSplines = len(curve.splines)
         nrSegments = 0
-        
+
         print("")
-        print("OperatorSegmentsInfo:", "nrSplines:", nrSplines)        
-        
+        print("OperatorSegmentsInfo:", "nrSplines:", nrSplines)
+
         nrEmptySplines = 0
         for iSpline, spline in enumerate(curve.splines):
             nrSegmentsSpline = spline.nrSegments
-            print("--", "spline %d of %d: nrSegments: %d" % (iSpline + 1, nrSplines, nrSegmentsSpline))        
-            
-            if nrSegmentsSpline < 1: 
+            print("--", "spline %d of %d: nrSegments: %d" % (iSpline + 1, nrSplines, nrSegmentsSpline))
+
+            if nrSegmentsSpline < 1:
                 nrEmptySplines += 1
                 print("--", "--", "## WARNING: spline has no segments and will therefor be ignored in any further calculations")
                 continue
-                
+
             for iSegment, segment in enumerate(spline.segments):
-                print("--", "--", "segment %d of %d coefficients:" % (iSegment + 1, nrSegmentsSpline))        
+                print("--", "--", "segment %d of %d coefficients:" % (iSegment + 1, nrSegmentsSpline))
                 print("--", "--", "--", "C0: %.6f, %.6f, %.6f" % (segment.coeff0.x, segment.coeff0.y, segment.coeff0.z))
-                
+
             nrSegments += nrSegmentsSpline
-        
+
         self.report({'INFO'}, "nrSplines: %d; nrSegments: %d; nrEmptySplines: %d" % (nrSplines, nrSegments, nrEmptySplines))
-        
+
         return {'FINISHED'}
 
 
@@ -176,31 +176,31 @@ class OperatorOriginToSpline0Start(bpy.types.Operator):
     bl_idname = "curvetools2.operatororigintospline0start"
     bl_label = "OriginToSpline0Start"
     bl_description = "Sets the origin of the active/selected curve to the starting point of the (first) spline. Nice for curve modifiers."
-    
-    
+
+
     @classmethod
     def poll(cls, context):
         return Util.Selected1Curve()
 
-            
+
     def execute(self, context):
         blCurve = context.active_object
         blSpline = blCurve.data.splines[0]
         newOrigin = blCurve.matrix_world * blSpline.bezier_points[0].co
-    
+
         origOrigin = bpy.context.scene.cursor_location.copy()
         print("--", "origOrigin: %.6f, %.6f, %.6f" % (origOrigin.x, origOrigin.y, origOrigin.z))
         print("--", "newOrigin: %.6f, %.6f, %.6f" % (newOrigin.x, newOrigin.y, newOrigin.z))
-        
+
         bpy.context.scene.cursor_location = newOrigin
         bpy.ops.object.origin_set(type='ORIGIN_CURSOR')
         bpy.context.scene.cursor_location = origOrigin
-        
+
         self.report({'INFO'}, "TODO: OperatorOriginToSpline0Start")
-        
+
         return {'FINISHED'}
 
-        
+
 
 # 2 CURVES SELECTED
 # #################
@@ -208,35 +208,35 @@ class OperatorIntersectCurves(bpy.types.Operator):
     bl_idname = "curvetools2.operatorintersectcurves"
     bl_label = "Intersect"
     bl_description = "Intersects selected curves"
-    
-    
+
+
     @classmethod
     def poll(cls, context):
         return Util.Selected2Curves()
 
-            
+
     def execute(self, context):
         print("### TODO: OperatorIntersectCurves.execute()")
-        
+
         algo = context.scene.curvetools.IntersectCurvesAlgorithm
         print("-- algo:", algo)
-                    
-            
+
+
         mode = context.scene.curvetools.IntersectCurvesMode
         print("-- mode:", mode)
         # if mode == 'Split':
             # self.report({'WARNING'}, "'Split' mode is not implemented yet -- <<STOPPING>>")
             # return {'CANCELLED'}
-        
+
         affect = context.scene.curvetools.IntersectCurvesAffect
         print("-- affect:", affect)
-        
-        
+
+
         curveIntersector = CurveIntersections.CurvesIntersector.FromSelection()
         rvIntersectionNrs = curveIntersector.CalcAndApplyIntersections()
-        
+
         self.report({'INFO'}, "Active curve points: %d; other curve points: %d" % (rvIntersectionNrs[0], rvIntersectionNrs[1]))
-        
+
         return {'FINISHED'}
 
 
@@ -245,21 +245,21 @@ class OperatorLoftCurves(bpy.types.Operator):
     bl_idname = "curvetools2.operatorloftcurves"
     bl_label = "Loft"
     bl_description = "Lofts selected curves"
-    
-    
+
+
     @classmethod
     def poll(cls, context):
         return Util.Selected2Curves()
 
-            
+
     def execute(self, context):
         #print("### TODO: OperatorLoftCurves.execute()")
-        
+
         loftedSurface = Surfaces.LoftedSurface.FromSelection()
         loftedSurface.AddToScene()
-        
+
         self.report({'INFO'}, "OperatorLoftCurves.execute()")
-        
+
         return {'FINISHED'}
 
 
@@ -268,24 +268,24 @@ class OperatorSweepCurves(bpy.types.Operator):
     bl_idname = "curvetools2.operatorsweepcurves"
     bl_label = "Sweep"
     bl_description = "Sweeps the active curve along to other curve (rail)"
-    
-    
+
+
     @classmethod
     def poll(cls, context):
         return Util.Selected2Curves()
 
-            
+
     def execute(self, context):
         #print("### TODO: OperatorSweepCurves.execute()")
-        
+
         sweptSurface = Surfaces.SweptSurface.FromSelection()
         sweptSurface.AddToScene()
-        
+
         self.report({'INFO'}, "OperatorSweepCurves.execute()")
-        
+
         return {'FINISHED'}
 
-        
+
 
 # 3 CURVES SELECTED
 # #################
@@ -293,77 +293,77 @@ class OperatorBirail(bpy.types.Operator):
     bl_idname = "curvetools2.operatorbirail"
     bl_label = "Birail"
     bl_description = "Generates a birailed surface from 3 selected curves -- in order: rail1, rail2 and profile"
-    
-    
+
+
     @classmethod
     def poll(cls, context):
         return Util.Selected3Curves()
 
-            
-    def execute(self, context):        
+
+    def execute(self, context):
         birailedSurface = Surfaces.BirailedSurface.FromSelection()
         birailedSurface.AddToScene()
-        
+
         self.report({'INFO'}, "OperatorBirail.execute()")
-        
+
         return {'FINISHED'}
 
 
-        
+
 # 1 OR MORE CURVES SELECTED
 # #########################
 class OperatorSplinesSetResolution(bpy.types.Operator):
     bl_idname = "curvetools2.operatorsplinessetresolution"
     bl_label = "SplinesSetResolution"
     bl_description = "Sets the resolution of all splines"
-    
-    
+
+
     @classmethod
     def poll(cls, context):
         return Util.Selected1OrMoreCurves()
 
-            
+
     def execute(self, context):
         splRes = context.scene.curvetools.SplineResolution
         selCurves = Util.GetSelectedCurves()
-        
+
         for blCurve in selCurves:
             for spline in blCurve.data.splines:
                 spline.resolution_u = splRes
-        
+
         return {'FINISHED'}
-        
-        
-        
+
+
+
 class OperatorSplinesRemoveZeroSegment(bpy.types.Operator):
     bl_idname = "curvetools2.operatorsplinesremovezerosegment"
     bl_label = "SplinesRemoveZeroSegment"
     bl_description = "Removes splines with no segments -- they seem to creep up, sometimes.."
-    
-    
+
+
     @classmethod
     def poll(cls, context):
         return Util.Selected1OrMoreCurves()
 
-            
+
     def execute(self, context):
         selCurves = Util.GetSelectedCurves()
-        
+
         for blCurve in selCurves:
             curve = Curves.Curve(blCurve)
             nrSplines = curve.nrSplines
-            
+
             splinesToRemove = []
             for spline in curve.splines:
                 if len(spline.segments) < 1: splinesToRemove.append(spline)
-            nrRemovedSplines = len(splinesToRemove)    
-                
+            nrRemovedSplines = len(splinesToRemove)
+
             for spline in splinesToRemove: curve.splines.remove(spline)
-            
+
             if nrRemovedSplines > 0: curve.RebuildInScene()
-            
+
             self.report({'INFO'}, "Removed %d of %d splines" % (nrRemovedSplines, nrSplines))
-        
+
         return {'FINISHED'}
 
 
@@ -372,26 +372,26 @@ class OperatorSplinesRemoveShort(bpy.types.Operator):
     bl_idname = "curvetools2.operatorsplinesremoveshort"
     bl_label = "SplinesRemoveShort"
     bl_description = "Removes splines with a length smaller than the threshold"
-    
-    
+
+
     @classmethod
     def poll(cls, context):
         return Util.Selected1OrMoreCurves()
 
-            
+
     def execute(self, context):
         threshold = context.scene.curvetools.SplineRemoveLength
         selCurves = Util.GetSelectedCurves()
-        
+
         for blCurve in selCurves:
             curve = Curves.Curve(blCurve)
             nrSplines = curve.nrSplines
-            
+
             nrRemovedSplines = curve.RemoveShortSplines(threshold)
             if nrRemovedSplines > 0: curve.RebuildInScene()
-            
+
             self.report({'INFO'}, "Removed %d of %d splines" % (nrRemovedSplines, nrSplines))
-        
+
         return {'FINISHED'}
 
 
@@ -400,27 +400,27 @@ class OperatorSplinesJoinNeighbouring(bpy.types.Operator):
     bl_idname = "curvetools2.operatorsplinesjoinneighbouring"
     bl_label = "SplinesJoinNeighbouring"
     bl_description = "Joins neighbouring splines within a distance smaller than the threshold"
-    
-    
+
+
     @classmethod
     def poll(cls, context):
         return Util.Selected1OrMoreCurves()
 
-            
+
     def execute(self, context):
         selCurves = Util.GetSelectedCurves()
-        
+
         for blCurve in selCurves:
             curve = Curves.Curve(blCurve)
             nrSplines = curve.nrSplines
-            
+
             threshold = context.scene.curvetools.SplineJoinDistance
             startEnd = context.scene.curvetools.SplineJoinStartEnd
             mode = context.scene.curvetools.SplineJoinMode
-            
+
             nrJoins = curve.JoinNeighbouringSplines(startEnd, threshold, mode)
             if nrJoins > 0: curve.RebuildInScene()
-            
+
             self.report({'INFO'}, "Applied %d joins on %d splines; resulting nrSplines: %d" % (nrJoins, nrSplines, curve.nrSplines))
-        
+
         return {'FINISHED'}
index 9481184..84c469f 100644 (file)
@@ -8,20 +8,20 @@ from bpy.props import *
 class CurveTools2SelectedObjectHeader(bpy.types.Header):
     bl_label = "Selection"
     bl_space_type = "VIEW_3D"
-    
+
     def __init__(self):
         self.update()
 
-        
+
     def update(self):
         blenderSelectedObjects = bpy.context.selected_objects
         selectedObjects = bpy.context.scene.curvetools.SelectedObjects
-        
+
         selectedObjectsToRemove = []
         for selectedObject in selectedObjects:
             if not selectedObject.IsElementOf(blenderSelectedObjects): selectedObjectsToRemove.append(selectedObject)
         for selectedObject in selectedObjectsToRemove: selectedObjects.remove(selectedObject)
-        
+
         blenderObjectsToAdd = []
         for blenderObject in blenderSelectedObjects:
             if not CurveTools2SelectedObject.ListContains(selectedObjects, blenderObject): blenderObjectsToAdd.append(blenderObject)
@@ -29,11 +29,11 @@ class CurveTools2SelectedObjectHeader(bpy.types.Header):
             newSelectedObject = CurveTools2SelectedObject(blenderObject)
             selectedObjects.append(newSelectedObject)
 
-        
+
     def draw(self, context):
         selectedObjects = bpy.context.scene.curvetools.SelectedObjects
         nrSelectedObjects = len(selectedObjects)
-        
+
         layout = self.layout
         row = layout.row()
         row.label("Sel:", nrSelectedObjects)
@@ -42,24 +42,24 @@ class CurveTools2SelectedObjectHeader(bpy.types.Header):
 class CurveTools2SelectedObject(bpy.types.PropertyGroup):
     name = StringProperty(name = "name", default = "??")
 
-    
+
     @staticmethod
     def UpdateThreadTarget(lock, sleepTime, selectedObjectNames, selectedBlenderObjectNames):
         time.sleep(sleepTime)
-        
+
         newSelectedObjectNames = []
-        
+
         for name in selectedObjectNames:
             if name in selectedBlenderObjectNames: newSelectedObjectNames.append(name)
-            
+
         for name in selectedBlenderObjectNames:
             if not (name in selectedObjectNames): newSelectedObjectNames.append(name)
-            
+
         # sometimes it still complains about the context
         try:
             nrNewSelectedObjects = len(newSelectedObjectNames)
             bpy.context.scene.curvetools.NrSelectedObjects = nrNewSelectedObjects
-            
+
             selectedObjects = bpy.context.scene.curvetools.SelectedObjects
             selectedObjects.clear()
             for i in range(nrNewSelectedObjects): selectedObjects.add()
@@ -67,24 +67,23 @@ class CurveTools2SelectedObject(bpy.types.PropertyGroup):
                 selectedObjects[i].name = newSelectedObjectName
         except: pass
 
-        
+
     @staticmethod
     def GetSelectedObjectNames():
         selectedObjects = bpy.context.scene.curvetools.SelectedObjects
-        
+
         rvNames = []
         selectedObjectValues = selectedObjects.values()
         for selectedObject in selectedObjectValues: rvNames.append(selectedObject.name)
-        
+
         return rvNames
-        
-        
+
+
     @staticmethod
     def GetSelectedBlenderObjectNames():
         blenderSelectedObjects = bpy.context.selected_objects
-        
+
         rvNames = []
         for blObject in blenderSelectedObjects: rvNames.append(blObject.name)
-        
+
         return rvNames
-        
index 7e31a6e..cfbf59c 100644 (file)
@@ -10,115 +10,115 @@ class LoftedSplineSurface:
     def __init__(self, activeSpline, otherSpline, bMesh, vert0Index, resolution):
         self.splineA = activeSpline
         self.splineO = otherSpline
-        
+
         self.bMesh = bMesh
         self.vert0Index = vert0Index
         self.resolution = resolution
 
-        
+
     def Apply(self, worldMatrixA, worldMatrixO):
         #deltaPar = 1.0 / float(self.resolution - 1)
-        
+
         par = 0.0
         pointA = worldMatrixA * self.splineA.CalcPoint(par)
         pointO = worldMatrixO * self.splineO.CalcPoint(par)
         self.bMesh.verts[self.vert0Index].co = pointA
         self.bMesh.verts[self.vert0Index + 1].co = pointO
-        
+
         fltResm1 = float(self.resolution - 1)
         for i in range(1, self.resolution):
             par = float(i) / fltResm1
-        
+
             pointA = worldMatrixA * self.splineA.CalcPoint(par)
             pointO = worldMatrixO * self.splineO.CalcPoint(par)
             self.bMesh.verts[self.vert0Index + 2 * i].co = pointA
             self.bMesh.verts[self.vert0Index + 2 * i + 1].co = pointO
 
-        
+
     def AddFaces(self):
         currIndexA = self.vert0Index
         currIndexO = self.vert0Index + 1
-        
+
         bmVerts = self.bMesh.verts
         bmVerts.ensure_lookup_table()
 
         for i in range(1, self.resolution):
             nextIndexA = self.vert0Index + 2 * i
             nextIndexO = nextIndexA + 1
-            
+
             self.bMesh.faces.new([bmVerts[currIndexA], bmVerts[currIndexO], bmVerts[nextIndexO], bmVerts[nextIndexA]])
-            
+
             currIndexA = nextIndexA
             currIndexO = nextIndexO
-            
+
 
 class LoftedSurface:
     @staticmethod
     def FromSelection():
         selObjects = bpy.context.selected_objects
         if len(selObjects) != 2: raise Exception("len(selObjects) != 2") # shouldn't be possible
-        
+
         blenderActiveCurve = bpy.context.active_object
         blenderOtherCurve = selObjects[0]
         if blenderActiveCurve == blenderOtherCurve: blenderOtherCurve = selObjects[1]
-        
+
         aCurve = Curves.Curve(blenderActiveCurve)
         oCurve = Curves.Curve(blenderOtherCurve)
-        
+
         name = "TODO: autoname"
-        
+
         return LoftedSurface(aCurve, oCurve, name)
-    
+
 
     def __init__(self, activeCurve, otherCurve, name = "LoftedSurface"):
         self.curveA = activeCurve
         self.curveO = otherCurve
         self.name  = name
-        
+
         self.nrSplines = self.curveA.nrSplines
         if self.curveO.nrSplines < self.nrSplines: self.nrSplines = self.curveO.nrSplines
-        
+
         self.bMesh = bmesh.new()
-        
+
         self.splineSurfaces = self.SetupSplineSurfaces()
-        
+
         self.Apply()
-        
-        
+
+
     def SetupSplineSurfaces(self):
         rvSplineSurfaces = []
-        
+
         currV0Index = 0
         for i in range(self.nrSplines):
             splineA = self.curveA.splines[i]
             splineO = self.curveO.splines[i]
-            
+
             res = splineA.resolution
             if splineO.resolution < res: res = splineO.resolution
-            
+
             for iv in range(2 * res): self.bMesh.verts.new()
-            
+
             splSurf = LoftedSplineSurface(splineA, splineO, self.bMesh, currV0Index, res)
             splSurf.AddFaces()
             rvSplineSurfaces.append(splSurf)
-            
+
             currV0Index += 2 * res
-        
+
         return rvSplineSurfaces
-        
-        
+
+
     def Apply(self):
         for splineSurface in self.splineSurfaces: splineSurface.Apply(self.curveA.worldMatrix, self.curveO.worldMatrix)
-        
-        
+
+
     def AddToScene(self):
         mesh = bpy.data.meshes.new("Mesh" + self.name)
-        
+
         self.bMesh.to_mesh(mesh)
         mesh.update()
-        
+
         meshObject = bpy.data.objects.new(self.name, mesh)
-        
+
         bpy.context.scene.objects.link(meshObject)
 
 
@@ -128,13 +128,13 @@ class SweptSplineSurface:
     def __init__(self, activeSpline, otherSpline, bMesh, vert0Index, resolutionA, resolutionO):
         self.splineA = activeSpline
         self.splineO = otherSpline
-        
+
         self.bMesh = bMesh
         self.vert0Index = vert0Index
         self.resolutionA = resolutionA
         self.resolutionO = resolutionO
 
-        
+
     def Apply(self, worldMatrixA, worldMatrixO):
         localPointsA = []
         fltResAm1 = float(self.resolutionA - 1)
@@ -143,132 +143,132 @@ class SweptSplineSurface:
             pointA = self.splineA.CalcPoint(par)
             localPointsA.append(pointA)
 
-        
+
         worldPointsO = []
         localDerivativesO = []
         fltResOm1 = float(self.resolutionO - 1)
         for i in range(self.resolutionO):
             par = float(i) / fltResOm1
-            
+
             pointO = self.splineO.CalcPoint(par)
             worldPointsO.append(worldMatrixO * pointO)
-            
+
             derivativeO = self.splineO.CalcDerivative(par)
             localDerivativesO.append(derivativeO)
-        
-        
+
+
         currWorldMatrixA = worldMatrixA
         worldMatrixOInv = worldMatrixO.inverted()
         prevDerivativeO = localDerivativesO[0]
         for iO in range(self.resolutionO):
             currDerivativeO = localDerivativesO[iO]
             localRotMatO = Math.CalcRotationMatrix(prevDerivativeO, currDerivativeO)
-            
-            currLocalAToLocalO = worldMatrixOInv * currWorldMatrixA       
+
+            currLocalAToLocalO = worldMatrixOInv * currWorldMatrixA
             worldPointsA = []
             for iA in range(self.resolutionA):
                 pointALocalToO = currLocalAToLocalO * localPointsA[iA]
                 rotatedPointA = localRotMatO * pointALocalToO
                 worldPointsA.append(worldMatrixO * rotatedPointA)
-                
+
             worldOffsetsA = []
             worldPoint0A = worldPointsA[0]
             for i in range(self.resolutionA): worldOffsetsA.append(worldPointsA[i] - worldPoint0A)
-            
-            
+
+
             for iA in range(self.resolutionA):
                 iVert = self.vert0Index + (self.resolutionA * iO) + iA
                 currVert = worldPointsO[iO] + worldOffsetsA[iA]
                 self.bMesh.verts[iVert].co = currVert
-                
+
             prevDerivativeO = currDerivativeO
             currWorldMatrixA = worldMatrixO * localRotMatO * currLocalAToLocalO
 
-        
+
     def AddFaces(self):
         bmVerts = self.bMesh.verts
         bmVerts.ensure_lookup_table()
-        
+
         for iO in range(self.resolutionO - 1):
             for iA in range(self.resolutionA - 1):
                 currIndexA1 = self.vert0Index + (self.resolutionA * iO) + iA
                 currIndexA2 = currIndexA1 + 1
                 nextIndexA1 = self.vert0Index + (self.resolutionA * (iO + 1)) + iA
                 nextIndexA2 = nextIndexA1 + 1
-        
+
                 self.bMesh.faces.new([bmVerts[currIndexA1], bmVerts[currIndexA2], bmVerts[nextIndexA2], bmVerts[nextIndexA1]])
-        
-        
+
+
 
 class SweptSurface:
     @staticmethod
     def FromSelection():
         selObjects = bpy.context.selected_objects
         if len(selObjects) != 2: raise Exception("len(selObjects) != 2") # shouldn't be possible
-        
+
         blenderActiveCurve = bpy.context.active_object
         blenderOtherCurve = selObjects[0]
         if blenderActiveCurve == blenderOtherCurve: blenderOtherCurve = selObjects[1]
-        
+
         aCurve = Curves.Curve(blenderActiveCurve)
         oCurve = Curves.Curve(blenderOtherCurve)
-        
+
         name = "TODO: autoname"
-        
+
         return SweptSurface(aCurve, oCurve, name)
-    
+
 
     def __init__(self, activeCurve, otherCurve, name = "SweptSurface"):
         self.curveA = activeCurve
         self.curveO = otherCurve
         self.name  = name
-        
+
         self.nrSplines = self.curveA.nrSplines
         if self.curveO.nrSplines < self.nrSplines: self.nrSplines = self.curveO.nrSplines
-        
+
         self.bMesh = bmesh.new()
-        
+
         self.splineSurfaces = self.SetupSplineSurfaces()
-        
+
         self.Apply()
-        
-        
+
+
     def SetupSplineSurfaces(self):
         rvSplineSurfaces = []
-        
+
         currV0Index = 0
         for i in range(self.nrSplines):
             splineA = self.curveA.splines[i]
             splineO = self.curveO.splines[i]
-            
+
             resA = splineA.resolution
             resO = splineO.resolution
-            
+
             for iv in range(resA * resO): self.bMesh.verts.new()
-            
+
             splSurf = SweptSplineSurface(splineA, splineO, self.bMesh, currV0Index, resA, resO)
             splSurf.AddFaces()
             rvSplineSurfaces.append(splSurf)
-            
+
             currV0Index += resA * resO
-        
+
         return rvSplineSurfaces
-        
-        
+
+
     def Apply(self):
         for splineSurface in self.splineSurfaces: splineSurface.Apply(self.curveA.worldMatrix, self.curveO.worldMatrix)
-        
-        
+
+
     def AddToScene(self):
         mesh = bpy.data.meshes.new("Mesh" + self.name)
-        
+
         self.bMesh.to_mesh(mesh)
         mesh.update()
-        
+
         meshObject = bpy.data.objects.new(self.name, mesh)
-        
+
         bpy.context.scene.objects.link(meshObject)
-        
+
 
 
 # profileSpline is swept over rail1Spline and scaled/rotated to have its endpoint on rail2Spline
@@ -277,13 +277,13 @@ class BirailedSplineSurface:
         self.rail1Spline = rail1Spline
         self.rail2Spline = rail2Spline
         self.profileSpline = profileSpline
-        
+
         self.bMesh = bMesh
         self.vert0Index = vert0Index
         self.resolutionRails = resolutionRails
         self.resolutionProfile = resolutionProfile
 
-        
+
     def Apply(self, worldMatrixRail1, worldMatrixRail2, worldMatrixProfile):
         localPointsProfile = []
         fltResProfilem1 = float(self.resolutionProfile - 1)
@@ -292,86 +292,86 @@ class BirailedSplineSurface:
             pointProfile = self.profileSpline.CalcPoint(par)
             localPointsProfile.append(pointProfile)
 
-        
+
         worldPointsRail1 = []
         localDerivativesRail1 = []
         worldPointsRail2 = []
         fltResRailsm1 = float(self.resolutionRails - 1)
         for i in range(self.resolutionRails):
             par = float(i) / fltResRailsm1
-            
+
             pointRail1 = self.rail1Spline.CalcPoint(par)
             worldPointsRail1.append(worldMatrixRail1 * pointRail1)
-            
+
             derivativeRail1 = self.rail1Spline.CalcDerivative(par)
             localDerivativesRail1.append(derivativeRail1)
-            
+
             pointRail2 = self.rail2Spline.CalcPoint(par)
             worldPointsRail2.append(worldMatrixRail2 * pointRail2)
-        
-        
+
+
         currWorldMatrixProfile = worldMatrixProfile
         worldMatrixRail1Inv = worldMatrixRail1.inverted()
         prevDerivativeRail1 = localDerivativesRail1[0]
         for iRail in range(self.resolutionRails):
             currDerivativeRail1 = localDerivativesRail1[iRail]
             localRotMatRail1 = Math.CalcRotationMatrix(prevDerivativeRail1, currDerivativeRail1)
-            
-            currLocalProfileToLocalRail1 = worldMatrixRail1Inv * currWorldMatrixProfile       
+
+            currLocalProfileToLocalRail1 = worldMatrixRail1Inv * currWorldMatrixProfile
             worldPointsProfileRail1 = []
             for iProfile in range(self.resolutionProfile):
                 pointProfileLocalToRail1 = currLocalProfileToLocalRail1 * localPointsProfile[iProfile]
                 rotatedPointProfile = localRotMatRail1 * pointProfileLocalToRail1
                 worldPointsProfileRail1.append(worldMatrixRail1 * rotatedPointProfile)
-                
+
             worldOffsetsProfileRail1 = []
             worldPoint0ProfileRail1 = worldPointsProfileRail1[0]
             for iProfile in range(self.resolutionProfile): worldOffsetsProfileRail1.append(worldPointsProfileRail1[iProfile] - worldPoint0ProfileRail1)
-                
+
             worldStartPointProfileRail1 = worldPointsRail1[iRail]
             worldEndPointProfileRail1 = worldStartPointProfileRail1 + worldOffsetsProfileRail1[-1]
             v3From = worldEndPointProfileRail1 - worldStartPointProfileRail1
             v3To = worldPointsRail2[iRail] - worldStartPointProfileRail1
             scaleFactorRail2 = v3To.magnitude / v3From.magnitude
             rotMatRail2 = Math.CalcRotationMatrix(v3From, v3To)
-            
+
             worldOffsetsProfileRail2 = []
             for iProfile in range(self.resolutionProfile):
                 offsetProfileRail1 = worldOffsetsProfileRail1[iProfile]
                 worldOffsetsProfileRail2.append(rotMatRail2 * (offsetProfileRail1 * scaleFactorRail2))
-            
-            
+
+
             for iProfile in range(self.resolutionProfile):
                 iVert = self.vert0Index + (self.resolutionProfile * iRail) + iProfile
                 currVert = worldPointsRail1[iRail] + worldOffsetsProfileRail2[iProfile]
                 self.bMesh.verts[iVert].co = currVert
-                
+
             prevDerivativeRail1 = currDerivativeRail1
             currWorldMatrixProfile = worldMatrixRail1 * localRotMatRail1 * currLocalProfileToLocalRail1
 
-        
+
     def AddFaces(self):
         bmVerts = self.bMesh.verts
         bmVerts.ensure_lookup_table()
-        
+
         for iRail in range(self.resolutionRails - 1):
             for iProfile in range(self.resolutionProfile - 1):
                 currIndex1 = self.vert0Index + (self.resolutionProfile * iRail) + iProfile
                 currIndex2 = currIndex1 + 1
                 nextIndex1 = self.vert0Index + (self.resolutionProfile * (iRail + 1)) + iProfile
                 nextIndex2 = nextIndex1 + 1
-        
+
                 self.bMesh.faces.new([bmVerts[currIndex1], bmVerts[currIndex2], bmVerts[nextIndex2], bmVerts[nextIndex1]])
-        
-        
+
+
 
 class BirailedSurface:
     @staticmethod
     def FromSelection():
         nrSelectedObjects = bpy.context.scene.curvetools.NrSelectedObjects
         if nrSelectedObjects != 3: raise Exception("nrSelectedObjects != 3") # shouldn't be possible
-        
-        
+
+
         selectedObjects = bpy.context.scene.curvetools.SelectedObjects
         selectedObjectValues = selectedObjects.values()
 
@@ -392,70 +392,68 @@ class BirailedSurface:
         try: profileBlenderCurve = bpy.data.objects[curveName]
         except: profileBlenderCurve = None
         if profileBlenderCurve is None: raise Exception("profileBlenderCurve is None")
-        
-        
+
+
         rail1Curve = Curves.Curve(rail1BlenderCurve)
         rail2Curve = Curves.Curve(rail2BlenderCurve)
         profileCurve = Curves.Curve(profileBlenderCurve)
-        
+
         name = "TODO: autoname"
-        
+
         return BirailedSurface(rail1Curve, rail2Curve, profileCurve, name)
-    
+
 
     def __init__(self, rail1Curve, rail2Curve, profileCurve, name = "BirailedSurface"):
         self.rail1Curve = rail1Curve
         self.rail2Curve = rail2Curve
         self.profileCurve = profileCurve
         self.name  = name
-        
+
         self.nrSplines = self.rail1Curve.nrSplines
         if self.rail2Curve.nrSplines < self.nrSplines: self.nrSplines = self.rail2Curve.nrSplines
         if self.profileCurve.nrSplines < self.nrSplines: self.nrSplines = self.profileCurve.nrSplines
-        
+
         self.bMesh = bmesh.new()
-        
+
         self.splineSurfaces = self.SetupSplineSurfaces()
-        
+
         self.Apply()
-        
-        
+
+
     def SetupSplineSurfaces(self):
         rvSplineSurfaces = []
-        
+
         currV0Index = 0
         for i in range(self.nrSplines):
             splineRail1 = self.rail1Curve.splines[i]
             splineRail2 = self.rail2Curve.splines[i]
             splineProfile = self.profileCurve.splines[i]
-            
+
             resProfile = splineProfile.resolution
             resRails = splineRail1.resolution
             if splineRail2.resolution < resRails: resRails = splineRail2.resolution
-            
+
             for iv in range(resProfile * resRails): self.bMesh.verts.new()
-            
+
             splSurf = BirailedSplineSurface(splineRail1, splineRail2, splineProfile, self.bMesh, currV0Index, resRails, resProfile)
             splSurf.AddFaces()
             rvSplineSurfaces.append(splSurf)
-            
+
             currV0Index += resProfile * resRails
-        
+
         return rvSplineSurfaces
-        
-        
+
+
     def Apply(self):
         for splineSurface in self.splineSurfaces: splineSurface.Apply(self.rail1Curve.worldMatrix, self.rail2Curve.worldMatrix, self.profileCurve.worldMatrix)
-        
-        
+
+
     def AddToScene(self):
         mesh = bpy.data.meshes.new("Mesh" + self.name)
-        
+
         self.bMesh.to_mesh(mesh)
         mesh.update()
-        
+
         meshObject = bpy.data.objects.new(self.name, mesh)
-        
-        bpy.context.scene.objects.link(meshObject)
 
-    
+        bpy.context.scene.objects.link(meshObject)
index 731460c..6ebd20b 100644 (file)
@@ -4,118 +4,116 @@ from mathutils import *
 
 def GetSelectedCurves():
     rvList = []
-    
+
     for obj in bpy.context.selected_objects:
         if obj.type == "CURVE": rvList.append(obj)
-    
+
     return rvList
 
 
 def Selected1Curve():
     if len(GetSelectedCurves()) == 1:
         return (bpy.context.active_object.type == "CURVE")
-    
+
     return False
 
 
 def Selected1SingleSplineCurve():
     if Selected1Curve():
         return (len(bpy.context.active_object.data.splines) == 1)
-    
+
     return False
 
 
 def Selected2Curves():
     if len(GetSelectedCurves()) == 2:
         return (bpy.context.active_object.type == "CURVE")
-    
+
     return False
 
 
 def Selected3Curves():
     if len(GetSelectedCurves()) == 3:
         return (bpy.context.active_object.type == "CURVE")
-    
+
     return False
 
 
 def Selected1OrMoreCurves():
     if len(GetSelectedCurves()) > 0:
         return (bpy.context.active_object.type == "CURVE")
-    
+
     return False
-    
+
 
 def GetToolsRegion():
     for area in bpy.context.screen.areas:
         if area.type == 'VIEW_3D':
             for region in area.regions:
                 if region.type == 'TOOLS': return region
-            
+
     return None
-    
+
 
 def GetFirstRegionView3D():
     for area in bpy.context.screen.areas:
         if area.type == 'VIEW_3D':
             return area.spaces[0].region_3d
-            
+
     return None
-    
-    
+
+
 def LogFirstRegionView3D():
     print("LogFirstRegionView3D()")
     regionView3D = GetFirstRegionView3D()
     if regionView3D is None:
         print("--", "ERROR:", "regionView3D is None")
         return
-        
+
     print("--", "view_matrix:")
     print("--", "--", regionView3D.view_matrix)
     print("--", "view_location:")
     print("--", "--", regionView3D.view_location)
-    
-    
+
+
 class Intersection:
     # listIP: list of BezierSplineIntersectionPoint
     # return: list of splines
     @staticmethod
     def GetBezierSplines(listIP):
         rvList = []
-        
+
         for ip in listIP:
             if not (ip.spline in rvList): rvList.append(ip.spline)
-        
+
         return rvList
 
-        
+
     # listIP: list of BezierSplineIntersectionPoint
     # return: list of segments
     @staticmethod
     def GetBezierSegments(listIP, spline):
         rvList = []
-        
+
         for ip in listIP:
             if not ip.spline is spline: continue
-            
+
             segIP = ip.bezierSegmentIntersectionPoint
             if not (segIP.segment in rvList): rvList.append(segIP.segment)
-        
+
         return rvList
 
-        
+
     # listIP: list of BezierSplineIntersectionPoint
     # return: list of floats (not necessarily ordered)
     @staticmethod
     def GetBezierSegmentParameters(listIP, segment):
         rvList = []
-        
+
         for ip in listIP:
             segIP = ip.bezierSegmentIntersectionPoint
             if not segIP.segment is segment: continue
-            
+
             rvList.append(segIP.parameter)
-        
-        return rvList
 
-   
\ No newline at end of file
+        return rvList
index 5b1808e..70ecc4c 100644 (file)
@@ -10,28 +10,28 @@ class OperatorAutoLoftCurves(Operator):
     bl_idname = "curvetools2.create_auto_loft"
     bl_label = "Loft"
     bl_description = "Lofts selected curves"
-    
-    
+
+
     @classmethod
     def poll(cls, context):
         return Util.Selected2Curves()
 
-            
+
     def execute(self, context):
         #print("### TODO: OperatorLoftCurves.execute()")
         scene = context.scene
         mesh = bpy.data.meshes.new("LoftMesh")
-        
+
         curve0 = context.selected_objects[0]
-        curve1 = context.selected_objects[1]      
+        curve1 = context.selected_objects[1]
 
-        ls = LoftedSurface(Curve(curve0), Curve(curve1), "AutoLoft")        
+        ls = LoftedSurface(Curve(curve0), Curve(curve1), "AutoLoft")
+
+        ls.bMesh.to_mesh(mesh)
 
-        ls.bMesh.to_mesh(mesh)        
-        
         loftobj = bpy.data.objects.new(self.name, mesh)
-        
-        scene.objects.link(loftobj)  
+
+        scene.objects.link(loftobj)
         loftobj["autoloft"] = True
         if loftobj.get('_RNA_UI') is None:
             loftobj['_RNA_UI'] = {}
@@ -42,10 +42,10 @@ class OperatorAutoLoftCurves(Operator):
                            "curve1": curve1.name}
         print(loftobj['_RNA_UI'].to_dict())
         self.report({'INFO'}, "OperatorAutoLoftCurves.execute()")
-        
+
         return {'FINISHED'}
 
-        
+
 class AutoLoftModalOperator(Operator):
     """Auto Loft"""
     bl_idname = "wm.auto_loft_curve"
@@ -57,14 +57,14 @@ class AutoLoftModalOperator(Operator):
     def poll(cls, context):
         # two curves selected.
         return True
-    
+
     def modal(self, context, event):
         scene = context.scene
         wm = context.window_manager
         if event.type in {'ESC'}:
             wm.auto_loft = False
-            
-        if not wm.auto_loft:            
+
+        if not wm.auto_loft:
             self.cancel(context)
             return {'CANCELLED'}
 
@@ -81,13 +81,13 @@ class AutoLoftModalOperator(Operator):
                 if curve0 and curve1:
                     ls = LoftedSurface(Curve(curve0), Curve(curve1), loftmesh.name)
                     ls.bMesh.to_mesh(loftmesh.data)
-  
+
         return {'PASS_THROUGH'}
 
     def execute(self, context):
         wm = context.window_manager
         self._timer = wm.event_timer_add(0.1, context.window)
-        wm.modal_handler_add(self)        
+        wm.modal_handler_add(self)
         return {'RUNNING_MODAL'}
 
     def cancel(self, context):
@@ -108,14 +108,14 @@ def register():
                                                      name="Auto Loft",
                                                      update=run_auto_loft)
     bpy.context.window_manager.auto_loft = False
-    
+
 def unregister():
     bpy.utils.unregister_class(AutoLoftModalOperator)
     bpy.utils.unregister_class(OperatorAutoLoftCurves)
 
 if __name__ == "__main__":
     register()
-    
+
+
     # test call
     #bpy.ops.wm.modal_timer_operator()
index 8dcf60f..6be15ff 100644 (file)
@@ -1,22 +1,22 @@
 '''
 by Yann Bertrand, january 2014.
+
 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
 END GPL LICENCE BLOCK
 '''
 
@@ -39,44 +39,44 @@ def createOutline(curve, outline):
     for spline in curve.data.splines[:]:
         p = spline.bezier_points
         out = []
-        
+
         n = ((p[0].handle_right-p[0].co).normalized()-(p[0].handle_left-p[0].co).normalized()).normalized()
         n = Vector((-n[1], n[0], n[2]))
         o = p[0].co+outline*n
         out.append(o)
-        
+
         for i in range(1,len(p)):
             n = ((p[i].handle_right-p[i].co).normalized()-(p[i].handle_left-p[i].co).normalized()).normalized()
             n = Vector((-n[1], n[0], n[2]))
             o = intersect_line_line(out[-1], (out[-1]+p[i].co-p[i-1].co), p[i].co, p[i].co+n)[0]
             out.append(o)
-            
+
         curve.data.splines.new('BEZIER')
         if spline.use_cyclic_u:
             curve.data.splines[-1].use_cyclic_u = True
         p_out = curve.data.splines[-1].bezier_points
         p_out.add(len(out)-1)
-    
+
         for i in range(len(out)):
-            p_out[i].handle_left_type = 'FREE'  
+            p_out[i].handle_left_type = 'FREE'
             p_out[i].handle_right_type = 'FREE'
-            
+
             p_out[i].co = out[i]
-            
+
             if i<len(out)-1:
                 l = (p[i+1].co-p[i].co).length
                 l2 = (out[i]-out[i+1]).length
-            
+
             if i==0:
                 p_out[i].handle_left = out[i] + ((p[i].handle_left-p[i].co)*l2/l)
             if i<len(out)-1:
                 p_out[i+1].handle_left = out[i+1] + ((p[i+1].handle_left-p[i+1].co)*l2/l)
             p_out[i].handle_right = out[i] + ((p[i].handle_right-p[i].co)*l2/l)
-    
+
         for i in range(len(p)):
             p_out[i].handle_left_type = p[i].handle_left_type
             p_out[i].handle_right_type = p[i].handle_right_type
-            
+
     return
 
 
@@ -86,7 +86,7 @@ class CurveOutline(bpy.types.Operator):
     bl_label = "Create Outline"
     bl_options = {'REGISTER', 'UNDO'}
     outline = bpy.props.FloatProperty(name="Amount", default=0.1, min=-10, max=10)
-    
+
     @classmethod
     def poll(cls, context):
         return (context.object is not None and
@@ -98,10 +98,10 @@ class CurveOutline(bpy.types.Operator):
 
     def invoke(self, context, event):
         return context.window_manager.invoke_props_popup(self, event)
-    
+
 def menu_func(self, context):
     self.layout.operator(CurveOutline.bl_idname)
-    
+
 def register():
     bpy.utils.register_class(CurveOutline)
 
index 08f6bb1..2998bcf 100644 (file)
@@ -33,7 +33,7 @@ bl_info = {
 
 import bpy
 from data_overrides import override, ui
+
 def register():
     override.register()
     ui.register()
index 1158576..a15e9c6 100644 (file)
@@ -81,7 +81,7 @@ class Override(PropertyGroup):
             row = layout.row(align=True)
             row.label(prop.name, icon='DOT')
             row.prop(prop, '["{}"]'.format(escape_identifier("value")), text="")
-        
+
         row = layout.row()
         row.operator_context = 'INVOKE_SCREEN'
         row.context_pointer_set("id_data_override", self)
index 81ca1be..e518cfe 100644 (file)
@@ -99,7 +99,7 @@ class SCENE_OT_Override_Add(Operator):
 
         id_data = id_data_from_enum(self.id_block)
         add_override(scene, id_data)
-        
+
         return {'FINISHED'}
 
 
index 4c2cec0..a22cddb 100644 (file)
@@ -84,14 +84,14 @@ class OperatorCallContext():
         # store active/selected state to restore it after operator execution
         self.curact = scene.objects.active
         self.cursel = { ob : ob.select for ob in scene.objects }
-        
+
         # undo can store files a lot when running operators internally,
         # disable since we only need one undo step after main operators anyway
         self.use_global_undo = prefs.edit.use_global_undo
         prefs.edit.use_global_undo = False
 
         return (self.curact, self.cursel)
-    
+
     def __exit__(self, exc_type, exc_value, traceback):
         scene = bpy.context.scene
         prefs = bpy.context.user_preferences
@@ -105,7 +105,7 @@ class OperatorCallContext():
 
 def select_single_object(ob):
     scene = bpy.context.scene
-    
+
     scene.objects.active = ob
     for tob in scene.objects:
         tob.select = (tob == ob)
index da88cf4..ef77962 100644 (file)
@@ -149,7 +149,7 @@ ELEMENTS_DEFAULT = (
 
 # The list 'ELEMENTS' contains all data of the elements and will be used during
 # runtime. The list will be initialized with the fixed
-# data from above via the class below (ElementProp). One fixed list (above), 
+# data from above via the class below (ElementProp). One fixed list (above),
 # which cannot be changed, and a list of classes with same data (ELEMENTS) exist.
 # The list 'ELEMENTS' can be modified by e.g. loading a separate custom
 # data file.
@@ -181,10 +181,10 @@ def distance():
         for v in bm.verts:
             if v.select:
                 locations.append(atom.matrix_world * v.co)
-                
+
         if len(locations) > 1:
             location1 = locations[0]
-            location2 = locations[1]        
+            location2 = locations[1]
         else:
             return "N.A"
     # In the 'OBJECT' mode
@@ -201,15 +201,15 @@ def distance():
     pos = str.find(dist, ".")
     dist = dist[:pos+4]
     dist = dist + " A"
-  
+
     return dist
 
 
-def choose_objects(action_type, 
-                   who, 
-                   radius_all, 
-                   radius_pm, 
-                   radius_type, 
+def choose_objects(action_type,
+                   who,
+                   radius_all,
+                   radius_pm,
+                   radius_type,
                    radius_type_ionic,
                    sticks_all):
 
@@ -220,23 +220,23 @@ def choose_objects(action_type,
         for i, layer in enumerate(bpy.context.scene.layers):
             if layer == True:
                 layers.append(i)
-                
+
         # Put all objects, which are in the layers, into a list.
         change_objects_all = []
         for atom in bpy.context.scene.objects:
             for layer in layers:
                 if atom.layers[layer] == True:
-                    change_objects_all.append(atom)                                  
-    # For selected objects of the visible layer                               
+                    change_objects_all.append(atom)
+    # For selected objects of the visible layer
     elif who == "ALL_ACTIVE":
         change_objects_all = []
         # Note all selected objects first.
         for atom in bpy.context.selected_objects:
-            change_objects_all.append(atom)   
-                    
-    # This is very important now: If there are dupliverts structures, note 
-    # only the parents and NOT the children! Otherwise the double work is 
-    # done or the system can even crash if objects are deleted. - The 
+            change_objects_all.append(atom)
+
+    # This is very important now: If there are dupliverts structures, note
+    # only the parents and NOT the children! Otherwise the double work is
+    # done or the system can even crash if objects are deleted. - The
     # chidlren are accessed anyways (see below).
     change_objects = []
     for atom in change_objects_all:
@@ -245,92 +245,92 @@ def choose_objects(action_type,
             for atom2 in change_objects:
                 if atom2 == atom.parent:
                    FLAG = True
-            if FLAG == False:        
+            if FLAG == False:
                 change_objects.append(atom)
         else:
             change_objects.append(atom)
-        
+
     # And now, consider all objects, which are in the list 'change_objects'.
     for atom in change_objects:
         if len(atom.children) != 0:
             for atom_child in atom.children:
-                if atom_child.type in {'SURFACE', 'MESH', 'META'}: 
-                    modify_objects(action_type, 
+                if atom_child.type in {'SURFACE', 'MESH', 'META'}:
+                    modify_objects(action_type,
                                    atom_child,
-                                   radius_all, 
-                                   radius_pm, 
+                                   radius_all,
+                                   radius_pm,
                                    radius_type,
                                    radius_type_ionic,
                                    sticks_all)
         else:
             if atom.type in {'SURFACE', 'MESH', 'META'}:
-                modify_objects(action_type, 
-                                   atom,  
-                                   radius_all, 
-                                   radius_pm, 
+                modify_objects(action_type,
+                                   atom,
+                                   radius_all,
+                                   radius_pm,
                                    radius_type,
                                    radius_type_ionic,
                                    sticks_all)
 
 
 # Modifying the radius of a selected atom or stick
-def modify_objects(action_type, 
-                   atom, 
-                   radius_all, 
-                   radius_pm, 
-                   radius_type, 
+def modify_objects(action_type,
+                   atom,
+                   radius_all,
+                   radius_pm,
+                   radius_type,
                    radius_type_ionic,
                    sticks_all):
 
-    # Modify atom radius (in pm) 
+    # Modify atom radius (in pm)
     if action_type == "ATOM_RADIUS_PM" and "Stick" not in atom.name:
         if radius_pm[0] in atom.name:
             atom.scale = (radius_pm[1]/100,) * 3
-            
+
     # Modify atom radius (all selected)
     if action_type == "ATOM_RADIUS_ALL" and "Stick" not in atom.name:
-        atom.scale *= radius_all      
-              
-    # Modify atom radius (type, van der Waals, atomic or ionic) 
+        atom.scale *= radius_all
+
+    # Modify atom radius (type, van der Waals, atomic or ionic)
     if action_type == "ATOM_RADIUS_TYPE" and "Stick" not in atom.name:
-        for element in ELEMENTS:                
+        for element in ELEMENTS:
             if element.name in atom.name:
                 # For ionic radii
                 if radius_type == '3':
                     charge_states = element.radii_ionic[::2]
                     charge_radii =  element.radii_ionic[1::2]
                     charge_state_chosen = int(radius_type_ionic) - 4
-                    
-                    find = (lambda searchList, elem: 
-                            [[i for i, x in enumerate(searchList) if x == e] 
+
+                    find = (lambda searchList, elem:
+                            [[i for i, x in enumerate(searchList) if x == e]
                             for e in elem])
                     index = find(charge_states,[charge_state_chosen])[0]
 
-                    # Is there a charge state?                    
+                    # Is there a charge state?
                     if index != []:
                         atom.scale = (charge_radii[index[0]],) * 3
-                                            
+
                 # For atomic and van der Waals radii.
-                else:        
+                else:
                     atom.scale = (element.radii[int(radius_type)],) * 3
 
-    # Modify atom sticks 
-    if action_type == "STICKS_RADIUS_ALL" and ('Sticks_Cups' in atom.name or 
+    # Modify atom sticks
+    if action_type == "STICKS_RADIUS_ALL" and ('Sticks_Cups' in atom.name or
                                                'Sticks_Cylinder' in atom.name or
                                                'Stick_Cylinder' in atom.name):
-    
+
         bpy.context.scene.objects.active = atom
         bpy.ops.object.mode_set(mode='EDIT', toggle=False)
         bm = bmesh.from_edit_mesh(atom.data)
-        
+
         locations = []
         for v in bm.verts:
             locations.append(v.co)
 
         center = Vector((0.0,0.0,0.0))
         center = sum([location for location in locations], center)/len(locations)
-        
-        radius = sum([(loc[0]-center[0])**2+(loc[1]-center[1])**2 
+
+        radius = sum([(loc[0]-center[0])**2+(loc[1]-center[1])**2
                      for loc in locations], 0)
         radius_new = radius * sticks_all
 
@@ -345,51 +345,51 @@ def modify_objects(action_type,
     if action_type == "ATOM_REPLACE_OBJ" and "Stick" not in atom.name:
 
         scn = bpy.context.scene.atom_blend
-        
-        new_material = draw_obj_material(scn.replace_objs_material, 
+
+        new_material = draw_obj_material(scn.replace_objs_material,
                                          atom.active_material)
-        
+
         # Special object (like halo, etc.)
         if scn.replace_objs_special != '0':
             new_atom = draw_obj_special(scn.replace_objs_special, atom)
             new_atom.parent = atom.parent
-        # Standard geomtrical objects    
+        # Standard geomtrical objects
         else:
             # If the atom shape shall not be changed, then:
             if scn.replace_objs == '0':
-                atom.active_material = new_material 
+                atom.active_material = new_material
                 return {'FINISHED'}
             # If the atom shape shall change, then:
             else:
                 new_atom = draw_obj(scn.replace_objs, atom)
-                new_atom.active_material = new_material                
+                new_atom.active_material = new_material
                 new_atom.parent = atom.parent
-                
+
                 if "_repl" not in atom.name:
                     new_atom.name = atom.name + "_repl"
                 else:
-                    new_atom.name = atom.name 
-                    
+                    new_atom.name = atom.name
+
         # Delete the old object.
         bpy.ops.object.select_all(action='DESELECT')
         atom.select = True
-        bpy.ops.object.delete()   
-        del(atom)      
+        bpy.ops.object.delete()
+        del(atom)
 
     # Default shapes and colors for atoms
     if action_type == "ATOM_DEFAULT_OBJ" and "Stick" not in atom.name:
 
-        scn = bpy.context.scene.atom_blend     
+        scn = bpy.context.scene.atom_blend
 
         # Create new material
         new_material = bpy.data.materials.new("tmp")
-        
+
         # Create new object (NURBS sphere = '1b')
         new_atom = draw_obj('1b', atom)
         new_atom.active_material = new_material
         new_atom.parent = atom.parent
 
-        # Change size and color of the new object            
+        # Change size and color of the new object
         for element in ELEMENTS:
             if element.name in atom.name:
                 new_atom.scale = (element.radii[0],) * 3
@@ -406,22 +406,22 @@ def modify_objects(action_type,
                         new_material.name = name+"_standard1"
                 else:
                     new_material.name = name+"_standard1"
-             
+
         # Finally, delete the old object
         bpy.ops.object.select_all(action='DESELECT')
         atom.select = True
-        bpy.ops.object.delete()    
+        bpy.ops.object.delete()
 
 
 # Separating atoms from a dupliverts strucutre.
 def separate_atoms(scn):
 
     atom = bpy.context.edit_object
-        
+
     # Do nothing if it is not a dupliverts structure.
     if not atom.dupli_type == "VERTS":
        return {'FINISHED'}
-        
+
     bm = bmesh.from_edit_mesh(atom.data)
     locations = []
     for v in bm.verts:
@@ -443,13 +443,13 @@ def separate_atoms(scn):
     # ... delete the new mesh including the separated vertex
     bpy.ops.object.select_all(action='DESELECT')
     new_object.select = True
-    bpy.ops.object.delete()  
+    bpy.ops.object.delete()
 
     # Create new atoms/vacancies at the position of the old atoms
     # For all selected positions do:
     for location in locations:
         # Create a new object by duplication of the child of the dupliverts
-        # structure. <= this is done 'len(locations)' times. After each 
+        # structure. <= this is done 'len(locations)' times. After each
         # duplication, move the new object onto the positions
         bpy.ops.object.select_all(action='DESELECT')
         atom.children[0].select = True
@@ -458,8 +458,8 @@ def separate_atoms(scn):
         new_atom = bpy.context.scene.objects.active
         new_atom.parent = None
         new_atom.location = location
-        new_atom.name = atom.name + "_sep"    
-        
+        new_atom.name = atom.name + "_sep"
+
     bpy.context.scene.objects.active = atom
 
 
@@ -468,11 +468,11 @@ def draw_obj_material(material_type, material):
 
     if material_type == '0': # Unchanged
         material_new = material
-    if material_type == '1': # Normal   
+    if material_type == '1': # Normal
         material_new = bpy.data.materials.new(material.name + "_normal")
-    if material_type == '2': # Transparent    
+    if material_type == '2': # Transparent
         material_new = bpy.data.materials.new(material.name + "_transparent")
-        material_new.use_transparency = True        
+        material_new.use_transparency = True
         material_new.transparency_method = 'Z_TRANSPARENCY'
         material_new.alpha = 1.3
         material_new.raytrace_transparency.fresnel = 1.6
@@ -480,13 +480,13 @@ def draw_obj_material(material_type, material):
     if material_type == '3': # Reflecting
         material_new = bpy.data.materials.new(material.name + "_reflecting")
         material_new.raytrace_mirror.use = True
-        material_new.raytrace_mirror.reflect_factor = 0.6       
+        material_new.raytrace_mirror.reflect_factor = 0.6
         material_new.raytrace_mirror.fresnel = 0.0
-        material_new.raytrace_mirror.fresnel_factor = 1.250          
+        material_new.raytrace_mirror.fresnel_factor = 1.250
         material_new.raytrace_mirror.depth = 2
-        material_new.raytrace_mirror.distance = 0.0        
-        material_new.raytrace_mirror.gloss_factor = 1.0                   
-    if material_type == '4': # Transparent + reflecting   
+        material_new.raytrace_mirror.distance = 0.0
+        material_new.raytrace_mirror.gloss_factor = 1.0
+    if material_type == '4': # Transparent + reflecting
         material_new = bpy.data.materials.new(material.name + "_trans+refl")
         material_new.use_transparency = True
         material_new.transparency_method = 'Z_TRANSPARENCY'
@@ -494,16 +494,16 @@ def draw_obj_material(material_type, material):
         material_new.raytrace_transparency.fresnel = 1.6
         material_new.raytrace_transparency.fresnel_factor = 1.6
         material_new.raytrace_mirror.use = True
-        material_new.raytrace_mirror.reflect_factor = 0.6       
+        material_new.raytrace_mirror.reflect_factor = 0.6
         material_new.raytrace_mirror.fresnel = 0.0
-        material_new.raytrace_mirror.fresnel_factor = 1.250          
+        material_new.raytrace_mirror.fresnel_factor = 1.250
         material_new.raytrace_mirror.depth = 2
-        material_new.raytrace_mirror.distance = 0.0        
-        material_new.raytrace_mirror.gloss_factor = 1.0 
-        
-    # Always, when the material is changed, a new name is created. Note that 
-    # this makes sense: Imagine, an other object uses the same material as the 
-    # selected one. After changing the material of the selected object the old 
+        material_new.raytrace_mirror.distance = 0.0
+        material_new.raytrace_mirror.gloss_factor = 1.0
+
+    # Always, when the material is changed, a new name is created. Note that
+    # this makes sense: Imagine, an other object uses the same material as the
+    # selected one. After changing the material of the selected object the old
     # material should certainly not change and remain the same.
     if material_type in {'1','2','3','4'}:
         if "_repl" in material.name:
@@ -515,8 +515,8 @@ def draw_obj_material(material_type, material):
                 material_new.name = material.name+"_repl1"
         else:
             material_new.name = material.name+"_repl1"
-        material_new.diffuse_color = material.diffuse_color        
-        
+        material_new.diffuse_color = material.diffuse_color
+
     return material_new
 
 
@@ -532,115 +532,115 @@ def draw_obj(atom_shape, atom):
     if atom_shape == '1a': #Sphere mesh
         bpy.ops.mesh.primitive_uv_sphere_add(
             segments=32,
-            ring_count=32,                    
-            size=1, 
-            view_align=False, 
+            ring_count=32,
+            size=1,
+            view_align=False,
             enter_editmode=False,
             location=atom.location,
             rotation=(0, 0, 0),
             layers=current_layers)
     if atom_shape == '1b': #Sphere NURBS
         bpy.ops.surface.primitive_nurbs_surface_sphere_add(
-            view_align=False, 
+            view_align=False,
             enter_editmode=False,
             location=atom.location,
             rotation=(0.0, 0.0, 0.0),
             layers=current_layers)
     if atom_shape == '2': #Cube
         bpy.ops.mesh.primitive_cube_add(
-            view_align=False, 
+            view_align=False,
             enter_editmode=False,
             location=atom.location,
             rotation=(0.0, 0.0, 0.0),
             layers=current_layers)
-    if atom_shape == '3': #Plane       
+    if atom_shape == '3': #Plane
         bpy.ops.mesh.primitive_plane_add(
-            view_align=False, 
-            enter_editmode=False, 
-            location=atom.location, 
-            rotation=(0.0, 0.0, 0.0), 
+            view_align=False,
+            enter_editmode=False,
+            location=atom.location,
+            rotation=(0.0, 0.0, 0.0),
             layers=current_layers)
     if atom_shape == '4a': #Circle
         bpy.ops.mesh.primitive_circle_add(
-            vertices=32, 
-            radius=1, 
-            fill_type='NOTHING', 
-            view_align=False, 
-            enter_editmode=False, 
-            location=atom.location, 
-            rotation=(0, 0, 0), 
-            layers=current_layers)      
+            vertices=32,
+            radius=1,
+            fill_type='NOTHING',
+            view_align=False,
+            enter_editmode=False,
+            location=atom.location,
+            rotation=(0, 0, 0),
+            layers=current_layers)
     if atom_shape == '4b': #Circle NURBS
         bpy.ops.surface.primitive_nurbs_surface_circle_add(
-            view_align=False, 
-            enter_editmode=False, 
-            location=atom.location, 
-            rotation=(0, 0, 0), 
+            view_align=False,
+            enter_editmode=False,
+            location=atom.location,
+            rotation=(0, 0, 0),
             layers=current_layers)
-    if atom_shape in {'5a','5b','5c','5d','5e'}: #Icosphere        
-        index = {'5a':1,'5b':2,'5c':3,'5d':4,'5e':5}  
+    if atom_shape in {'5a','5b','5c','5d','5e'}: #Icosphere
+        index = {'5a':1,'5b':2,'5c':3,'5d':4,'5e':5}
         bpy.ops.mesh.primitive_ico_sphere_add(
-            subdivisions=int(index[atom_shape]), 
-            size=1, 
-            view_align=False, 
-            enter_editmode=False, 
-            location=atom.location, 
-            rotation=(0, 0, 0), 
+            subdivisions=int(index[atom_shape]),
+            size=1,
+            view_align=False,
+            enter_editmode=False,
+            location=atom.location,
+            rotation=(0, 0, 0),
             layers=current_layers)
     if atom_shape == '6a': #Cylinder
         bpy.ops.mesh.primitive_cylinder_add(
-            vertices=32, 
-            radius=1, 
-            depth=2, 
-            end_fill_type='NGON', 
-            view_align=False, 
-            enter_editmode=False, 
-            location=atom.location, 
-            rotation=(0, 0, 0), 
+            vertices=32,
+            radius=1,
+            depth=2,
+            end_fill_type='NGON',
+            view_align=False,
+            enter_editmode=False,
+            location=atom.location,
+            rotation=(0, 0, 0),
             layers=current_layers)
     if atom_shape == '6b': #Cylinder NURBS
         bpy.ops.surface.primitive_nurbs_surface_cylinder_add(
-            view_align=False, 
-            enter_editmode=False, 
-            location=atom.location, 
-            rotation=(0, 0, 0), 
-            layers=current_layers)          
+            view_align=False,
+            enter_editmode=False,
+            location=atom.location,
+            rotation=(0, 0, 0),
+            layers=current_layers)
     if atom_shape == '7': #Cone
         bpy.ops.mesh.primitive_cone_add(
-            vertices=32, 
-            radius1=1, 
-            radius2=0, 
-            depth=2, 
-            end_fill_type='NGON', 
-            view_align=False, 
-            enter_editmode=False, 
-            location=atom.location, 
-            rotation=(0, 0, 0), 
+            vertices=32,
+            radius1=1,
+            radius2=0,
+            depth=2,
+            end_fill_type='NGON',
+            view_align=False,
+            enter_editmode=False,
+            location=atom.location,
+            rotation=(0, 0, 0),
             layers=current_layers)
     if atom_shape == '8a': #Torus
         bpy.ops.mesh.primitive_torus_add(
-            rotation=(0, 0, 0), 
-            location=atom.location, 
-            view_align=False, 
-            major_radius=1, 
-            minor_radius=0.25, 
-            major_segments=48, 
-            minor_segments=12, 
-            abso_major_rad=1, 
-            abso_minor_rad=0.5)     
+            rotation=(0, 0, 0),
+            location=atom.location,
+            view_align=False,
+            major_radius=1,
+            minor_radius=0.25,
+            major_segments=48,
+            minor_segments=12,
+            abso_major_rad=1,
+            abso_minor_rad=0.5)
     if atom_shape == '8b': #Torus NURBS
         bpy.ops.surface.primitive_nurbs_surface_torus_add(
-            view_align=False, 
-            enter_editmode=False, 
-            location=atom.location, 
-            rotation=(0, 0, 0), 
+            view_align=False,
+            enter_editmode=False,
+            location=atom.location,
+            rotation=(0, 0, 0),
             layers=current_layers)
 
     new_atom = bpy.context.scene.objects.active
     new_atom.scale = atom.scale + Vector((0.0,0.0,0.0))
-    new_atom.name = atom.name + "_tmp"   
+    new_atom.name = atom.name + "_tmp"
     new_atom.select = True
-        
+
     return new_atom
 
 
@@ -660,7 +660,7 @@ def draw_obj_special(atom_shape, atom):
         new_atom.location = atom.location
         material_new = bpy.data.materials.new(atom.active_material.name + "_sep")
         material_new.name = atom.name + "_halo"
-        material_new.diffuse_color = atom.active_material.diffuse_color       
+        material_new.diffuse_color = atom.active_material.diffuse_color
         material_new.type = 'HALO'
         material_new.halo.size = atom.scale[0]*1.5
         material_new.halo.hardness = 25
@@ -671,19 +671,19 @@ def draw_obj_special(atom_shape, atom):
     # F2+ center
     if atom_shape == '2':
         # Create first a cube
-        bpy.ops.mesh.primitive_cube_add(view_align=False, 
+        bpy.ops.mesh.primitive_cube_add(view_align=False,
                                         enter_editmode=False,
                                         location=atom.location,
                                         rotation=(0.0, 0.0, 0.0),
                                         layers=current_layers)
         cube = bpy.context.scene.objects.active
         cube.scale = atom.scale + Vector((0.0,0.0,0.0))
-        cube.name = atom.name + "_F2+-center"   
-        cube.select = True                                        
+        cube.name = atom.name + "_F2+-center"
+        cube.select = True
         # New material for this cube
         material_cube = bpy.data.materials.new(atom.name + "_F2+-center")
-        material_cube.diffuse_color = [0.8,0.0,0.0]     
-        material_cube.use_transparency = True        
+        material_cube.diffuse_color = [0.8,0.0,0.0]
+        material_cube.use_transparency = True
         material_cube.transparency_method = 'Z_TRANSPARENCY'
         material_cube.alpha = 1.0
         material_cube.raytrace_transparency.fresnel = 1.6
@@ -692,32 +692,32 @@ def draw_obj_special(atom_shape, atom):
         # Put a nice point lamp inside the defect
         lamp_data = bpy.data.lamps.new(name="F2+_lamp", type="POINT")
         lamp_data.distance = atom.scale[0] * 2.0
-        lamp_data.energy = 20.0     
-        lamp_data.use_sphere = True   
-        lamp_data.color = [0.8,0.8,0.8]           
+        lamp_data.energy = 20.0
+        lamp_data.use_sphere = True
+        lamp_data.color = [0.8,0.8,0.8]
         lamp = bpy.data.objects.new("F2+_lamp", lamp_data)
         lamp.location = Vector((0.0, 0.0, 0.0))
         lamp.layers = current_layers
-        bpy.context.scene.objects.link(lamp) 
+        bpy.context.scene.objects.link(lamp)
         lamp.parent = cube
-        # The new 'atom' is the F2+ defect 
-        new_atom = cube        
+        # The new 'atom' is the F2+ defect
+        new_atom = cube
     # F+ center
     if atom_shape == '3':
         # Create first a cube
-        bpy.ops.mesh.primitive_cube_add(view_align=False, 
+        bpy.ops.mesh.primitive_cube_add(view_align=False,
                                         enter_editmode=False,
                                         location=atom.location,
                                         rotation=(0.0, 0.0, 0.0),
                                         layers=current_layers)
         cube = bpy.context.scene.objects.active
         cube.scale = atom.scale + Vector((0.0,0.0,0.0))
-        cube.name = atom.name + "_F+-center"   
-        cube.select = True                                        
+        cube.name = atom.name + "_F+-center"
+        cube.select = True
         # New material for this cube
         material_cube = bpy.data.materials.new(atom.name + "_F+-center")
-        material_cube.diffuse_color = [0.8,0.8,0.0]     
-        material_cube.use_transparency = True        
+        material_cube.diffuse_color = [0.8,0.8,0.0]
+        material_cube.use_transparency = True
         material_cube.transparency_method = 'Z_TRANSPARENCY'
         material_cube.alpha = 1.0
         material_cube.raytrace_transparency.fresnel = 1.6
@@ -726,21 +726,21 @@ def draw_obj_special(atom_shape, atom):
         # Create now an electron
         scale = atom.scale / 10.0
         bpy.ops.surface.primitive_nurbs_surface_sphere_add(
-                                        view_align=False, 
+                                        view_align=False,
                                         enter_editmode=False,
                                         location=(0.0, 0.0, 0.0),
                                         rotation=(0.0, 0.0, 0.0),
-                                        layers=current_layers)     
+                                        layers=current_layers)
         electron = bpy.context.scene.objects.active
         electron.scale = scale
-        electron.name = atom.name + "_F+_electron"   
-        electron.parent = cube 
+        electron.name = atom.name + "_F+_electron"
+        electron.parent = cube
         # New material for the electron
         material_electron = bpy.data.materials.new(atom.name + "_F+-center")
         material_electron.diffuse_color = [0.0,0.0,0.8]
         material_electron.specular_hardness = 200
         material_electron.emit = 1.0
-        material_electron.use_transparency = True        
+        material_electron.use_transparency = True
         material_electron.transparency_method = 'Z_TRANSPARENCY'
         material_electron.alpha = 1.3
         material_electron.raytrace_transparency.fresnel = 1.2
@@ -749,32 +749,32 @@ def draw_obj_special(atom_shape, atom):
         # Put a nice point lamp inside the electron
         lamp_data = bpy.data.lamps.new(name="F+_lamp", type="POINT")
         lamp_data.distance = atom.scale[0] * 2.0
-        lamp_data.energy = 20.0     
-        lamp_data.use_sphere = True   
-        lamp_data.color = [0.8,0.8,0.8]           
+        lamp_data.energy = 20.0
+        lamp_data.use_sphere = True
+        lamp_data.color = [0.8,0.8,0.8]
         lamp = bpy.data.objects.new("F+_lamp", lamp_data)
         lamp.location = Vector((0.0, 0.0, 0.0))
         lamp.layers = current_layers
-        bpy.context.scene.objects.link(lamp) 
+        bpy.context.scene.objects.link(lamp)
         lamp.parent = cube
         # The new 'atom' is the F+ defect complex + lamp
         new_atom = cube
     # F0 center
     if atom_shape == '4':
         # Create first a cube
-        bpy.ops.mesh.primitive_cube_add(view_align=False, 
+        bpy.ops.mesh.primitive_cube_add(view_align=False,
                                         enter_editmode=False,
                                         location=atom.location,
                                         rotation=(0.0, 0.0, 0.0),
                                         layers=current_layers)
         cube = bpy.context.scene.objects.active
         cube.scale = atom.scale + Vector((0.0,0.0,0.0))
-        cube.name = atom.name + "_F0-center"   
-        cube.select = True                                        
+        cube.name = atom.name + "_F0-center"
+        cube.select = True
         # New material for this cube
         material_cube = bpy.data.materials.new(atom.name + "_F0-center")
-        material_cube.diffuse_color = [0.8,0.8,0.8]     
-        material_cube.use_transparency = True        
+        material_cube.diffuse_color = [0.8,0.8,0.8]
+        material_cube.use_transparency = True
         material_cube.transparency_method = 'Z_TRANSPARENCY'
         material_cube.alpha = 1.0
         material_cube.raytrace_transparency.fresnel = 1.6
@@ -783,31 +783,31 @@ def draw_obj_special(atom_shape, atom):
         # Create now two electrons
         scale = atom.scale / 10.0
         bpy.ops.surface.primitive_nurbs_surface_sphere_add(
-                                        view_align=False, 
+                                        view_align=False,
                                         enter_editmode=False,
                                         location=(scale[0]*1.5,0.0,0.0),
                                         rotation=(0.0, 0.0, 0.0),
-                                        layers=current_layers)     
+                                        layers=current_layers)
         electron1 = bpy.context.scene.objects.active
         electron1.scale = scale
-        electron1.name = atom.name + "_F0_electron1"   
-        electron1.parent = cube 
+        electron1.name = atom.name + "_F0_electron1"
+        electron1.parent = cube
         bpy.ops.surface.primitive_nurbs_surface_sphere_add(
-                                        view_align=False, 
+                                        view_align=False,
                                         enter_editmode=False,
                                         location=(-scale[0]*1.5,0.0,0.0),
                                         rotation=(0.0, 0.0, 0.0),
-                                        layers=current_layers)     
+                                        layers=current_layers)
         electron2 = bpy.context.scene.objects.active
         electron2.scale = scale
-        electron2.name = atom.name + "_F0_electron2"   
-        electron2.parent = cube 
+        electron2.name = atom.name + "_F0_electron2"
+        electron2.parent = cube
         # New material for the electrons
         material_electron = bpy.data.materials.new(atom.name + "_F0-center")
         material_electron.diffuse_color = [0.0,0.0,0.8]
         material_electron.specular_hardness = 200
         material_electron.emit = 1.0
-        material_electron.use_transparency = True        
+        material_electron.use_transparency = True
         material_electron.transparency_method = 'Z_TRANSPARENCY'
         material_electron.alpha = 1.3
         material_electron.raytrace_transparency.fresnel = 1.2
@@ -817,30 +817,30 @@ def draw_obj_special(atom_shape, atom):
         # Put two nice point lamps inside the electrons
         lamp1_data = bpy.data.lamps.new(name="F0_lamp1", type="POINT")
         lamp1_data.distance = atom.scale[0] * 2.0
-        lamp1_data.energy = 8.0     
-        lamp1_data.use_sphere = True   
-        lamp1_data.color = [0.8,0.8,0.8]           
+        lamp1_data.energy = 8.0
+        lamp1_data.use_sphere = True
+        lamp1_data.color = [0.8,0.8,0.8]
         lamp1 = bpy.data.objects.new("F0_lamp", lamp1_data)
         lamp1.location = Vector((scale[0]*1.5, 0.0, 0.0))
         lamp1.layers = current_layers
-        bpy.context.scene.objects.link(lamp1) 
+        bpy.context.scene.objects.link(lamp1)
         lamp1.parent = cube
         lamp2_data = bpy.data.lamps.new(name="F0_lamp2", type="POINT")
         lamp2_data.distance = atom.scale[0] * 2.0
-        lamp2_data.energy = 8.0     
-        lamp2_data.use_sphere = True   
-        lamp2_data.color = [0.8,0.8,0.8]           
+        lamp2_data.energy = 8.0
+        lamp2_data.use_sphere = True
+        lamp2_data.color = [0.8,0.8,0.8]
         lamp2 = bpy.data.objects.new("F0_lamp", lamp2_data)
         lamp2.location = Vector((-scale[0]*1.5, 0.0, 0.0))
         lamp2.layers = current_layers
-        bpy.context.scene.objects.link(lamp2) 
-        lamp2.parent = cube        
+        bpy.context.scene.objects.link(lamp2)
+        lamp2.parent = cube
         # The new 'atom' is the F0 defect complex + lamps
         new_atom = cube
-        
+
     return new_atom
-                     
-                         
+
+
 # Initialization of the list 'ELEMENTS'.
 def read_elements():
 
@@ -853,7 +853,7 @@ def read_elements():
         # The handling of the ionic radii will be done later. So far, it is an
         # empty list.
         radii_ionic = item[7:]
-        
+
         li = ElementProp(item[0],item[1],item[2],item[3],
                                      radii,radii_ionic)
         ELEMENTS.append(li)
@@ -935,4 +935,4 @@ def custom_datafile(path_datafile):
 
     data_file_p.close()
 
-    return True                           
+    return True
index 8841e72..f8a346e 100644 (file)
@@ -292,4 +292,4 @@ def unregister():
     #bpy.types.INFO_MT_file_export.remove(menu_func_export)
 
 if __name__ == "__main__":
-    register()
\ No newline at end of file
+    register()
index 6db2d81..f8ce1d1 100644 (file)
@@ -21,4 +21,4 @@ def nested(lst) :
         t = lst[0][0][0]
         return lst, True
     except :
-        return [lst], False
\ No newline at end of file
+        return [lst], False
index 169cae3..07239a6 100644 (file)
@@ -10,7 +10,7 @@ def clean(path) :
     path = path.strip().replace('\\','/')
     if ('/') not in path : path = '//'+path
     return path
-    
+
 ## test for existence of a file or a dir
 def exist(path) :
     if isfile(path) or isdir(path) : return True
@@ -67,8 +67,7 @@ def saveOptions(op,operator_name, tokens, filename='last_run'):
                     value = value[:]
                 except:
                     pass
-    
+
                 file_preset.write("op.%s = %r\n" % (key, value))
 
         file_preset.close()
-    
index a295d6e..05f3846 100644 (file)
@@ -4,7 +4,7 @@ given name < 21
 if material name exists :
 naming_method = 0   blender default (increment name)
 naming_method = 1   do nothing, abort creation and use existing
-naming_method = 2   create new, rename existing, 
+naming_method = 2   create new, rename existing,
 naming_method = 3   create new, replace existing
 '''
 
@@ -53,7 +53,7 @@ def remove(ob,with_data=True) :
                     and_data=False
             except :
                 and_data=False # empties
-                
+
             # odd (pre 2.60) :
             # ob=bpy.data.objects[ob.name]
             # if the ob (board) argument comes from bpy.data.groups['aGroup'].objects,
@@ -72,4 +72,3 @@ def remove(ob,with_data=True) :
             # never wipe data before unlink the ex-user object of the scene else crash (2.58 3 770 2)
             if and_data :
                 wipeOutData(data)
-
index 74f45b2..9db42d9 100644 (file)
@@ -11,7 +11,7 @@ def dprint(str,l=2) :
         print(str)
 
 # create or retrieve a bdata image
-# given its path 
+# given its path
 def new(path, name=False, relative = True) :
     path = fs.clean(path)
     # check file
@@ -23,9 +23,9 @@ def new(path, name=False, relative = True) :
         try :
             path = bpy.path.relpath(path)
             path = fs.clean(path)
-        except : 
+        except :
             print('cant turn path into relative one (.blend and img path drive letters ?) ')
-        
+
     # retrieve paths to image file from existing image slot
     # returns img if paths match
     for img in bpy.data.images :
@@ -34,7 +34,7 @@ def new(path, name=False, relative = True) :
                 return img
 
     # create a unique name in image slot
-    if name == False : 
+    if name == False :
         name = bpy.path.basename(path)
     name = bel.bpyname(name,bpy.data.images.keys())
 
@@ -52,7 +52,7 @@ def applyShader(mat,config) :
     texslot = mat.texture_slots[0]
     tex = texslot.texture
     img = tex.image
-    
+
     #config = shaders[shadername]
     alpha = True if 'alpha' in config else False
 
@@ -184,12 +184,12 @@ def BSshader(nodes,pointer) :
         for key in RenderMaterial.keys() :
             if key not in ['DiffuseColor','SpecularColor','AmbientColor','EmissionColor','Shininess','Transparency'] :
                 print('NEW RENDERMATERIAL PROP ! : %s'%key)
-        
+
         #print(AmbientColor)
         if DiffuseColor : mat.diffuse_color = Color(DiffuseColor) #[0][0],DiffuseColor[0][1],DiffuseColor[0][2])
         if SpecularColor : mat.specular_color = Color(SpecularColor)#[0][0],SpecularColor[0][1],SpecularColor[0][2])
-        if AmbientColor : mat.ambient = AmbientColor[0] # source value is a vector3f with x=y=z 
-        if EmissionColor : mat.emit = EmissionColor[0] # source value is a vector3f with x=y=z 
+        if AmbientColor : mat.ambient = AmbientColor[0] # source value is a vector3f with x=y=z
+        if EmissionColor : mat.emit = EmissionColor[0] # source value is a vector3f with x=y=z
         #if Shininess : mat.
         #alpha is a boolean, whereas Transparency is a float or False
         if Transparency :
@@ -221,7 +221,7 @@ def BSshader(nodes,pointer) :
         imgname = imgpath.split('/')[-1]
         imgpath = tkm.path_archives+'/Images/Q=Tex032M/'+imgpath
 
-        if imgname not in bpy.data.images :        
+        if imgname not in bpy.data.images :
             if os.path.isfile(imgpath+'.png') : ext = '.png'
             elif os.path.isfile(imgpath+'.jp2') : ext = '.jp2'
             else :
@@ -231,13 +231,13 @@ def BSshader(nodes,pointer) :
             img = bpy.data.images.load(filepath=imgpath+ext)
             img.name = imgname
         else : img = bpy.data.images[imgname]
-        
+
         '''
         texslot = mat.texture_slots[0]
         mat.texture_slots[0]
         tex = texslot.texture
         tex.type = 'IMAGE'
-        img = tex.image        
+        img = tex.image
         img.name
         '''
         #img = bpy.data.images.new(name='imgname',width=640, height=512)
@@ -256,4 +256,4 @@ def BSshader(nodes,pointer) :
         texslot.use_map_alpha = alpha
         texslot.alpha_factor = 1.0
 
-    return mat
\ No newline at end of file
+    return mat
index 048dfc3..0f6d823 100644 (file)
@@ -5,24 +5,24 @@ given name < 21
 if material name exists :
 naming_method = 0   blender default (increment name)
 naming_method = 1   do nothing, abort creation and use existing
-naming_method = 2   create new, rename existing, 
+naming_method = 2   create new, rename existing,
 naming_method = 3   create new, replace existing
 '''
 
 def new(name, naming_method=0) :
     if name not in bpy.data.materials or naming_method == 0:
         return bpy.data.materials.new(name=name)
-    
+
     elif naming_method == 1 :
         return bpy.data.materials[name]
-    
+
     mat = bpy.data.materials.new(name=name)
-    
+
     if naming_method == 2 :
         mat.name = name
         return mat
-    
-    # naming_method = 3 : replace 
+
+    # naming_method = 3 : replace
     prevmat = bpy.data.materials[name]
     for ob in bpy.data.objects :
         for matslot in ob.material_slots :
@@ -30,4 +30,3 @@ def new(name, naming_method=0) :
                 matslot.material = mat
     bpy.data.materials.remove(prevmat)
     return mat
-
index 5c60746..af29032 100644 (file)
@@ -16,9 +16,9 @@ no : create
 yes :
     naming_method = 0   blender default (increment name)
     naming_method = 1   do nothing, abort creation and use existing
-    naming_method = 2   create new, rename existing, 
+    naming_method = 2   create new, rename existing,
     naming_method = 3   create new, remove existing
-    
+
 for now, and mesh data, 0 2 or 3
 '''
 
@@ -27,7 +27,7 @@ given name < 21
 if material name exists :
 naming_method = 0   blender default (increment name)
 naming_method = 1   do nothing, abort creation and use existing
-naming_method = 2   create new, rename existing, 
+naming_method = 2   create new, rename existing,
 naming_method = 3   create new, replace existing
 '''
 
@@ -42,7 +42,7 @@ def new(name, naming_method=0) :
         me = bpy.data.meshes.new(name=name)
         me.name = name
         return me
-    
+
     # naming_method = 3 : replace, keep users
     me = bpy.data.meshes[name]
     bm = bmesh.new()
@@ -51,15 +51,15 @@ def new(name, naming_method=0) :
 
 ## material listed in matslots must exist before creation of material slots
 
-def write(obname,name, 
-          verts=[], edges=[], faces=[], 
-          matslots=[], mats=[], uvs=[], 
+def write(obname,name,
+          verts=[], edges=[], faces=[],
+          matslots=[], mats=[], uvs=[],
           groupnames=[], vindices=[], vweights=[],
           smooth=False,
           naming_method = 0,
           ) :
 
-    
+
     obj = bpy.data.objects[obname] if obname in bpy.data.objects else False
     me = bpy.data.meshes[name] if name in bpy.data.meshes else False
 
@@ -69,19 +69,19 @@ def write(obname,name,
     if naming_method == 1 and me and obj and obj.data == me :
         #print('%s and %s exist, reuse'%(obj.name,me.name))
         return obj
-       
+
     if naming_method == 3 :
-        if obj : 
+        if obj :
             #print('remove ob %s'%obj.name)
             bob.remove(obj,False)
         if me :
             #print('remove me %s'%me.name)
             bob.removeData(me)
-    
+
 
     me = bpy.data.meshes.new(name)
     if naming_method == 2 : me.name = name
-    
+
     me.from_pydata(verts, edges, faces)
     me.update()
 
@@ -126,26 +126,26 @@ def write(obname,name,
     obj = bpy.data.objects.new(name=obname, object_data=me)
     if naming_method != 0 :
         obj.name = obname
-            
+
     '''
     else :
         ob = bpy.data.objects[name]
         ob.data = me
-        if naming_method == 2 : ob.name = 
+        if naming_method == 2 : ob.name =
         ob.parent = None
         ob.matrix_local = Matrix()
         print('  reuse object %s'%ob.name)
     '''
-            
+
     # vertexgroups
     if len(groupnames) > 0 :
         for gpi, groupname in enumerate(groupnames) :
             weightsadd(obj, groupname, vindices[gpi], vweights[gpi])
-    
+
     # scene link check
     if obj.name not in bpy.context.scene.objects.keys() :
         bpy.context.scene.objects.link(obj)
-        
+
     return obj
 
 def shadesmooth(me,lst=True) :
@@ -155,7 +155,7 @@ def shadesmooth(me,lst=True) :
     else :
         for fi,face in enumerate(me.polygons) :
             face.use_smooth = True
+
 def shadeflat(me,lst=True) :
     if type(lst) == list :
         for fi in lst :
@@ -185,7 +185,7 @@ def objectBuild(elm, verts, edges=[], faces=[], matslots=[], mats=[], uvs=[] ) :
     city = bpy.context.scene.city
     # apply current scale
     verts = metersToBu(verts)
-    
+
     if type(elm) != str :
         obname = elm.objectName()
         if obname == 'not built' :
@@ -232,5 +232,3 @@ def materialsCheck(bld) :
                     method = 'random'
                     mat.diffuse_color=( random.uniform(0.0,1.0),random.uniform(0.0,1.0),random.uniform(0.0,1.0))
                 dprint('Created missing material %s (%s)'%(matname,method),2)
-
-
index 486bced..52e6352 100644 (file)
@@ -53,7 +53,7 @@ def remove(ob,with_data=True) :
                     and_data=False
             except :
                 and_data=False # empties
-                
+
             # odd (pre 2.60) :
             # ob=bpy.data.objects[ob.name]
             # if the ob (board) argument comes from bpy.data.groups['aGroup'].objects,
@@ -78,12 +78,12 @@ def remove(ob,with_data=True) :
 ## or rename it _dead if there's still users
 def removeData(data) :
     #print('%s has %s user(s) !'%(data.name,data.users))
-    
+
     if data.users <= 0 :
 
             #data.user_clear()
             data_type = type(data)
-            
+
             # mesh
             if data_type == Mesh :
                 bpy.data.meshes.remove(data)
@@ -113,4 +113,3 @@ def removeData(data) :
     else :
         #print('  not done, %s has %s user'%(data.name,data.users))
         data.name = '_dead'
-        
\ No newline at end of file
index 2827819..9b21bb9 100644 (file)
@@ -3,7 +3,7 @@ from .__init__ import *
 from time import clock
 
 # uvs :
-# 
+#
 def write(me, uvs, matimage = False) :
     t = clock()
     uvs, nest = nested(uvs)
@@ -13,9 +13,9 @@ def write(me, uvs, matimage = False) :
 
         uv = me.uv_textures.new()
         uv.name = 'UV%s'%uvi
-        
+
         uvlayer = me.uv_layers[-1].data
-        
+
         for uvfi, uvface in enumerate(uvlist) :
             #uv.data[uvfi].use_twoside = True # 2.60 changes mat ways
             mslotid = me.polygons[uvfi].material_index
@@ -24,17 +24,17 @@ def write(me, uvs, matimage = False) :
                 if matimage[mslotid] :
                     img = matimage[mslotid]
                     uv.data[uvfi].image=img
-            
+
             vi = 0
             for fi in me.polygons[uvfi].loop_indices :
                 uvlayer[fi].uv = Vector((uvface[vi],uvface[vi+1]))
                 vi += 2
-                
+
         newuvs.append(uv)
     print('uvs in ',clock() - t)
     if nest : return newuvs
     return newuvs[0]
-    
+
 ## WAY faster
 def flatwrite(me, uvs, matimage = False) :
     #t = clock()
@@ -56,7 +56,7 @@ def flatwrite(me, uvs, matimage = False) :
     #print('uvs in ',clock() - t)
     return newuvs
 
-# face are squared or rectangular, 
+# face are squared or rectangular,
 # any orientation
 # vert order width then height 01 and 23 = x 12 and 03 = y
 # normal default when face has been built
@@ -106,4 +106,4 @@ def asFlatList(uvlist,faces) :
         for vi in f :
             uv.extend(uvlist[vi])
     #print('uvs convert in %s len : %s'%(str(clock() - t),len(uv)))
-    return uv
\ No newline at end of file
+    return uv
index f96dc7e..895af3a 100644 (file)
@@ -77,13 +77,13 @@ def load(operator, context, filepath,
          use_image_search=True,
          global_matrix=None,
          ):
-    
-    
+
+
     if quickmode :
         parented = False
-    
+
     bone_minlength = bone_maxlength / 100.0
-    
+
     #global templates, tokens
     rootTokens = []
     namelookup = {}
@@ -102,7 +102,7 @@ def load(operator, context, filepath,
     '''
     '''
     with * : defined in dXdata
-    
+
     WORD     16 bits
     * DWORD     32 bits
     * FLOAT     IEEE float
@@ -147,13 +147,13 @@ BINARY FORMAT
 #define TOKEN_UNICODE     50
 #define TOKEN_CSTRING     51
 #define TOKEN_ARRAY       52
-    
+
     '''
-    
+
     # COMMON REGEX
     space = '[\ \t]{1,}' # at least one space / tab
     space0 = '[\ \t]{0,}' # zero or more space / tab
-    
+
     # DIRECTX REGEX TOKENS
     r_template = r'template' + space + '[\w]*' + space0 + '\{'
     if quickmode :
@@ -162,10 +162,10 @@ BINARY FORMAT
         r_sectionname = r'[\w]*' + space + '[\w-]*' + space0 + '\{'
     r_refsectionname = r'\{' + space0 + '[\w-]*' + space0 + '\}'
     r_endsection = r'\{|\}'
-    
+
     # dX comments
     r_ignore = r'#|//'
-    
+
     #r_frame = r'Frame' + space + '[\w]*'
     #r_matrix = r'FrameTransformMatrix' + space + '\{[\s\d.,-]*'
     #r_mesh = r'Mesh' + space + '[\W]*'
@@ -173,7 +173,7 @@ BINARY FORMAT
     ###################
     ## STEP 1 FUNCTIONS
     ###################
-    
+
     ## HEADER
     # returns header values or False if directx reco tag is missing
     # assuming there's never comment header and that xof if the 1st
@@ -183,9 +183,9 @@ BINARY FORMAT
      4       Magic Number (required) "xof "
      2       Minor Version 03
      2       Major Version 02
-     4       Format Type (required) 
+     4       Format Type (required)
         "txt " Text File
-        "bin " Binary File  
+        "bin " Binary File
         "tzip" MSZip Compressed Text File
         "bzip" MSZip Compressed Binary File
      4       Float Accuracy "0032" 32 bit or "0064" 64 bit
@@ -202,8 +202,8 @@ BINARY FORMAT
         accuracy = int(data.read(4).decode())
         data.seek(0)
         return ( minor, major, format, accuracy )
-        
-    
+
+
     ##
     def dXtree(data,quickmode = False) :
         tokens = {}
@@ -221,7 +221,7 @@ BINARY FORMAT
             lines, trunkated = nextFileChunk(data,trunkated)
             if lines == None : break
             for l in lines :
-                
+
                 # compute pointer position
                 ptr += eol
                 c += 1
@@ -230,16 +230,16 @@ BINARY FORMAT
                 #if l != '' : print('***',l)
                 #if l == ''  : break
                 l = l.strip()
-                
+
                 # remove blank and comment lines
                 if l == '' or re.match(r_ignore,l) :
                     continue
-                
+
                 # one line token cases level switch
                 if previouslvl :
                     lvl -= 1
                     previouslvl = False
-                
+
                 #print('%s lines in %.2f\''%(c,time.clock()-t),end='\r')
                 #print(c,len(l)+1,ptr,data.tell())
                 if '{' in l :
@@ -248,14 +248,14 @@ BINARY FORMAT
                 elif '}' in l :
                     lvl -= 1
                 #print(c,lvl,tree)
-                
+
                 if quickmode == False :
                     ## look for templates
                     if re.match(r_template,l) :
                         tname = l.split(' ')[1]
                         templates[tname] = {'pointer' : ptr, 'line' : c}
                         continue
-    
+
                     ## look for {references}
                     if re.match(r_refsectionname,l) :
                         refname = namelookup[ l[1:-1].strip() ]
@@ -271,7 +271,7 @@ BINARY FORMAT
                         if 'user' not in tokens[refname] : tokens[refname]['users'] = [parent]
                         else : tokens[refname]['users'].append(parent)
                         continue
-    
+
                 ## look for any token or only Mesh token in quickmode
                 if re.match(r_sectionname,l) :
                     tokenname = getName(l,tokens)
@@ -289,7 +289,7 @@ BINARY FORMAT
                         tokens[tokenname]['parent'] = parent
                         tokens[tokenname]['childs'] = []
                         tokens[tokenname]['type'] = typ
-                        
+
                     else : tokens[tokenname] = {'pointer': ptr,
                                                 'line'   : c,
                                                 'parent' : parent,
@@ -300,9 +300,9 @@ BINARY FORMAT
                     tree.append(tokenname)
                     if lvl > 1 and quickmode == False :
                         tokens[parent]['childs'].append(tokenname)
-                    
+
         return tokens, templates, tokentypes
-        
+
     ## returns file binary chunks
     def nextFileChunk(data,trunkated=False,chunksize=1024) :
         if chunksize == 0 : chunk = data.read()
@@ -312,7 +312,7 @@ BINARY FORMAT
             #if stream : return lines.replace('\r','').replace('\n','')
             lines = lines.replace('\r','\n').split('\n')
             if trunkated : lines[0] = trunkated + lines[0]
-            if len(lines) == 1 : 
+            if len(lines) == 1 :
                 if lines[0] == '' : return None, None
                 return lines, False
             return lines, lines.pop()
@@ -323,28 +323,28 @@ BINARY FORMAT
                 w = chunk[word:word+4]
                 print(word,w,struct.unpack("<l", w),binascii.unhexlify(w))
 
-    
+
     # name unnamed tokens, watchout for x duplicate
     # for blender, referenced token in x should be named and unique..
     def getName(l,tokens) :
         xnam = l.split(' ')[1].strip()
-        
+
         #if xnam[0] == '{' : xnam = ''
         if xnam and xnam[-1] == '{' : xnam = xnam[:-1]
-        
+
         name = xnam
         if len(name) == 0 : name = l.split(' ')[0].strip()
-        
+
         namelookup[xnam] = bel.bpyname(name,tokens,4)
 
         return namelookup[xnam]
-    
-    
+
+
     ###################
     ## STEP 2 FUNCTIONS
     ###################
     # once the internal dict is populated the functions below can be used
-    
+
     ## from a list of tokens, displays every child, users and references
     '''
       walk_dxtree( [ 'Mesh01', 'Mesh02' ] ) # for particular pieces
@@ -357,21 +357,21 @@ BINARY FORMAT
                     tokenname = tokenname[1:]
                     ref = 'ref: '
                 else : ref = False
-                
+
                 frame_type = tokens[tokenname]['type']
                 line = ('{:7}'.format(tokens[tokenname]['line']))
                 log = ' %s%s (%s)'%( ref if ref else '', tokenname, frame_type )
                 print('%s.%s%s'%(line, tab, log))
                 if fi == len(field) - 1 : tab = tab[:-3] + '   '
-    
+
                 if ref == False :
                     for user in tokens[tokenname]['users'] :
                          print('%s.%s |__ user: %s'%(line, tab.replace('_',' '), user))
                     walk_dXtree(tokens[tokenname]['childs'],lvl+1,tab.replace('_',' ')+' |__')
-                
+
                 if fi == len(field) - 1 and len(tokens[tokenname]['childs']) == 0 :
                     print('%s.%s'%(line,tab))
-    
+
     ## remove eol, comments, spaces from a raw block of datas
     def cleanBlock(block) :
         while '//' in block :
@@ -384,7 +384,7 @@ BINARY FORMAT
             block = block[0:s] + block[e:]
         block = block.replace('\n','').replace(' ','').replace('\t ','')
         return block
-        
+
     def readToken(tokenname) :
         token = tokens[tokenname]
         datatype = token['type'].lower()
@@ -401,7 +401,7 @@ BINARY FORMAT
         if datatype in templatesConvert :
             fields = eval( templatesConvert[datatype] )
         return fields
-    
+
     def dXtemplateData(tpl,block,ptr=0) :
         #print('dxTPL',block[ptr])
         pack = []
@@ -422,14 +422,14 @@ BINARY FORMAT
             else :
                 length = 1
                 datavalue, ptr = dXdata(block, datatype, length, ptr)
-    
+
             #if len(str(datavalue)) > 50 : dispvalue = str(datavalue[0:25]) + ' [...] ' + str(datavalue[-25:])
             #else : dispvalue = str(datavalue)
             #print('%s :  %s %s'%(dataname,dispvalue,type(datavalue)))
             exec('%s = datavalue'%(dataname))
             pack.append( datavalue )
         return pack, ptr + 1
-    
+
     def dXdata(block,datatype,length,s=0,eof=';') :
         #print('dxDTA',block[s])
         # at last, the data we need
@@ -458,7 +458,7 @@ BINARY FORMAT
             if datatype in templatesConvert :
                 fields = eval( templatesConvert[datatype] )
             return fields, ptr
-    
+
     def dXarray(block, datatype, length, s=0) :
         #print('dxARR',block[s])
         lst = []
@@ -468,7 +468,7 @@ BINARY FORMAT
                 if i+1 == length : eoi = ';'
                 datavalue, s = dXdata(block,datatype,1,s,eoi)
                 lst.append( datavalue )
-            
+
         else :
             eoi = ';,'
             for i in range(length) :
@@ -480,7 +480,7 @@ BINARY FORMAT
                 lst.append( datavalue )
                 s = e + 2
         return lst, s
-    
+
     ###################################################
 
     ## populate a template with its datas
@@ -495,7 +495,7 @@ BINARY FORMAT
         go = True
         while go :
             lines, trunkated = nextFileChunk(data,trunkated,chunksize) # stream ?
-            if lines == None : 
+            if lines == None :
                 break
             for l in lines :
                 #l = data.readline().decode().strip()
@@ -503,21 +503,21 @@ BINARY FORMAT
                 if '}' in l :
                     go = False
                     break
-        
+
         uuid = re.search(r'<.+>',block).group()
         templates[tpl_name]['uuid'] = uuid.lower()
         templates[tpl_name]['members'] = []
         templates[tpl_name]['restriction'] = 'closed'
-        
+
         members = re.search(r'>.+',block).group()[1:-1].split(';')
         for member in members :
             if member == '' : continue
             if member[0] == '[' :
                 templates[tpl_name]['restriction'] = member
-                continue  
+                continue
             templates[tpl_name]['members'].append( member.split(' ') )
-    
-        if display : 
+
+        if display :
             print('\ntemplate %s :'%tpl_name)
             for k,v in templates[tpl_name].items() :
                 if k != 'members' :
@@ -525,7 +525,7 @@ BINARY FORMAT
                 else :
                     for member in v :
                         print('  %s'%str(member)[1:-1].replace(',',' ').replace("'",''))
-                
+
             if tpl_name in defaultTemplates :
                 defaultTemplates[tpl_name]['line'] = templates[tpl_name]['line']
                 defaultTemplates[tpl_name]['pointer'] = templates[tpl_name]['pointer']
@@ -543,8 +543,8 @@ BINARY FORMAT
                     #            print('  %s'%str(member)[1:-1].replace(',',' ').replace("'",''))
                 else :
                     print('MATCHES BUILTIN TEMPLATE')
-    
-            
+
+
     ##  read any kind of token data block
     # by default the block is cleaned from inline comment space etc to allow data parsing
     # useclean = False (retrieve all bytes) if you need to compute a file byte pointer
@@ -572,7 +572,7 @@ BINARY FORMAT
         block = block[s:e]
         if clean : block = cleanBlock(block)
         return block
-    
+
     def getChilds(tokenname) :
         childs = []
         # '*' in childname means it's a reference. always perform this test
@@ -581,12 +581,12 @@ BINARY FORMAT
             if childname[0] == '*' : childname = childname[1:]
             childs.append( childname )
         return childs
-    
+
     # the input nested list of [bonename, matrix, [child0,child1..]] is given by import_dXtree()
     def buildArm(armdata, child,lvl=0,parent_matrix=False) :
-        
+
         bonename, bonemat, bonechilds = child
-        
+
         if lvl == 0 :
             armname = armdata
             armdata = bpy.data.armatures.new(name=armname)
@@ -596,7 +596,7 @@ BINARY FORMAT
             bpy.context.scene.objects.active = arm
             bpy.ops.object.mode_set(mode='EDIT')
             parent_matrix = Matrix()
-        
+
         bone = armdata.edit_bones.new(name=bonename)
         bonematW = parent_matrix * bonemat
         bone.head = bonematW.to_translation()
@@ -611,10 +611,10 @@ BINARY FORMAT
             bpy.ops.object.mode_set(mode='OBJECT')
             return arm
         return bone
-    
+
     def import_dXtree(field,lvl=0) :
         tab = ' '*lvl*2
-        if field == [] : 
+        if field == [] :
             if show_geninfo : print('%s>> no childs, return False'%(tab))
             return False
         ob = False
@@ -622,14 +622,14 @@ BINARY FORMAT
         is_root = False
         frames = []
         obs = []
-        
+
         parentname = tokens[field[0]]['parent']
         if show_geninfo : print('%s>>childs in frame %s :'%(tab,parentname))
-        
+
         for tokenname in field :
 
             tokentype = tokens[tokenname]['type']
-            
+
             # frames can contain more than one mesh
             if tokentype  == 'mesh' :
                 # object and mesh naming :
@@ -638,35 +638,35 @@ BINARY FORMAT
                 if parentname :
                     meshcount = 0
                     for child in getChilds(parentname) :
-                        if tokens[child]['type'] == 'mesh' : 
+                        if tokens[child]['type'] == 'mesh' :
                             meshcount += 1
                             if meshcount == 2 :
                                 parentname = tokenname
                                 break
                 else : parentname = tokenname
-                
+
                 ob = getMesh(parentname,tokenname)
                 obs.append(ob)
 
                 if show_geninfo : print('%smesh : %s'%(tab,tokenname))
-            
+
             # frames contain one matrix (empty or bone)
             elif tokentype  == 'frametransformmatrix' :
                 [mat] = readToken(tokenname)
                 if show_geninfo : print('%smatrix : %s'%(tab,tokenname))
-            
+
             # frames can contain 0 or more frames
             elif tokentype  == 'frame' :
                 frames.append(tokenname)
                 if show_geninfo : print('%sframe : %s'%(tab,tokenname))
-        
-        # matrix is used for mesh transform if some mesh(es) exist(s)      
+
+        # matrix is used for mesh transform if some mesh(es) exist(s)
         if ob :
             is_root = True
             if mat == False :
                 mat = Matrix()
                 if show_geninfo : print('%smesh token without matrix, set it to default\n%splease report in bug tracker if you read this !'%(tab,tab))
-            if parentname == '' : 
+            if parentname == '' :
                 mat = mat * global_matrix
             if len(obs) == 1 :
                 ob.matrix_world = mat
@@ -675,7 +675,7 @@ BINARY FORMAT
                 ob.matrix_world = mat
                 for child in obs :
                     child.parent = ob
-        
+
         # matrix only, store it as a list as we don't know if
         # it's a bone or an empty yet
         elif mat :
@@ -687,25 +687,25 @@ BINARY FORMAT
             if show_geninfo : print('%snothing here'%(tab))
 
         childs = []
-        
+
         for tokenname in frames :
             if show_geninfo : print('%s<Begin %s :'%(tab,tokenname))
-            
+
             # child is either False, empty, object, or a list or undefined name matrices hierarchy
             child = import_dXtree(getChilds(tokenname),lvl+1)
             if child and type(child) != list :
                 is_root = True
             childs.append( [tokenname, child] )
             if show_geninfo : print('%sEnd %s>'%(tab,tokenname))
-        
+
         if is_root and parentname != '' :
-            
+
             if show_geninfo : print('%send of tree a this point'%(tab))
             if type(ob) == list :
                 mat = ob[1]
                 ob = bel.ob.new(parentname, None, naming_method)
             ob.matrix_world = mat
-            
+
         for tokenname, child in childs :
             if show_geninfo : print('%sbegin2 %s>'%(tab,tokenname))
             # returned a list of object(s) or matrice(s)
@@ -718,14 +718,14 @@ BINARY FORMAT
                     if type(child) == list :
                         if show_geninfo : print('%sconvert to armature %s'%(tab,tokenname))
                         child = buildArm(tokenname, child)
-                        
+
                     # parent the obj/empty/arm to current
                     # or apply the global user defined matrix to the object root
                     if parentname != '' :
                         child.parent = ob
                     else :
                         child.matrix_world = global_matrix
-                        
+
                 # returned a list of parented matrices. append it in childs list
                 elif type(child[0]) == str :
                     ob[2].append(child)
@@ -735,7 +735,7 @@ BINARY FORMAT
                     #print('  child data type: %s'%type(child.data))
                     child.parent = ob
                     #print('%s parented to %s'%(child.name,ob.name))
-                
+
             # returned False
             else :
                  if show_geninfo : print('%sreturned %s, nothing'%(tab,child))
@@ -745,9 +745,9 @@ BINARY FORMAT
 
     # build from mesh token type
     def getMesh(obname,tokenname,debug = False):
-    
+
         if debug : print('\nmesh name : %s'%tokenname)
-        
+
         verts = []
         edges = []
         faces = []
@@ -758,36 +758,36 @@ BINARY FORMAT
         groupindices = []
         groupweights = []
 
-        nVerts, verts, nFaces, faces = readToken(tokenname) 
+        nVerts, verts, nFaces, faces = readToken(tokenname)
 
         if debug :
             print('verts    : %s %s\nfaces    : %s %s'%(nVerts, len(verts),nFaces, len(faces)))
-        
+
         #for childname in token['childs'] :
         for childname in getChilds(tokenname) :
-            
+
             tokentype = tokens[childname]['type']
-            
+
             # UV
             if tokentype == 'meshtexturecoords' :
                 uv = readToken(childname)
                 #uv = bel.uv.asVertsLocation(uv, faces)
                 uv = bel.uv.asFlatList(uv, faces)
                 uvs.append(uv)
-                
+
                 if debug : print('uv       : %s'%(len(uv)))
-            
+
             # MATERIALS
             elif tokentype == 'meshmateriallist' :
                 nbslots, facemats = readToken(childname)
-                
+
                 if debug : print('facemats : %s'%(len(facemats)))
-                
+
                 # mat can exist but with no datas so we prepare the mat slot
                 # with dummy ones
                 for slot in range(nbslots) :
                     matslots.append('dXnoname%s'%slot )
-        
+
                 # length does not match (could be tuned more, need more cases)
                 if len(facemats) != len(faces) :
                     facemats = [ facemats[0] for i in faces ]
@@ -795,14 +795,14 @@ BINARY FORMAT
                 # seek for materials then textures if any mapped in this mesh.
                 # no type test, only one option type in token meshmateriallist : 'Material'
                 for slotid, matname in enumerate(getChilds(childname)) :
-                    
+
                     # rename dummy mats with the right name
                     matslots[slotid] = matname
 
                     # blender material creation (need tuning)
                     mat = bel.material.new(matname,naming_method)
                     matslots[slotid] = mat.name
-                    
+
                     if naming_method != 1 :
                         #print('matname : %s'%matname)
                         (diffuse_color,alpha), power, specCol, emitCol = readToken(matname)
@@ -811,9 +811,9 @@ BINARY FORMAT
                         mat.diffuse_intensity = power
                         mat.specular_color = specCol
                         # dX emit don't use diffuse color but is a color itself
-                        # convert it to a kind of intensity 
+                        # convert it to a kind of intensity
                         mat.emit = (emitCol[0] + emitCol[1] + emitCol[2] ) / 3
-                        
+
                         if alpha != 1.0 :
                             mat.use_transparency = True
                             mat.transparency_method = 'Z_TRANSPARENCY'
@@ -821,29 +821,29 @@ BINARY FORMAT
                             mat.specular_alpha = 0
                             transp = True
                         else : transp = False
-            
+
                         # texture
                         # only 'TextureFilename' can be here, no type test
-                        # textures have no name in .x so we build 
+                        # textures have no name in .x so we build
                         # image and texture names from the image file name
                         # bdata texture slot name = bdata image name
                         btexnames = []
                         for texname in getChilds(matname) :
-                            
+
                             # create/rename/reuse etc corresponding data image
                             # (returns False if not found)
                             [filename] = readToken(texname)
                             img = bel.image.new(path+'/'+filename)
-                            
+
                             if img == False :
                                 imgname = 'not_found'
                             else :
                                 imgname = img.name
-                                
+
                             #print('texname : %s'%texname)
                             #print('filename : %s'%filename)
                             #print('btex/img name : %s'%imgname)
-                            
+
                             # associated texture (no naming check.. maybe tune more)
                             # tex and texslot are created even if img not found
                             if imgname in bpy.data.textures and ( img == False or bpy.data.textures[imgname].image == img ) :
@@ -851,10 +851,10 @@ BINARY FORMAT
                             else :
                                 tex = bpy.data.textures.new(name=imgname,type='IMAGE')
                                 if img : tex.image = img
-                                
+
                             tex.use_alpha = transp
                             tex.use_preview_alpha = transp
-                                
+
                             # then create texture slot
                             texslot = mat.texture_slots.create(index=0)
                             texslot.texture = tex
@@ -868,35 +868,35 @@ BINARY FORMAT
                     if matname not in bpy.data.materials :
                         mat = bel.material.new(matname,naming_method)
                         matslots[slotid] = mat.name
-                        
+
                 if debug : print('matslots : %s'%matslots)
-                
+
             # VERTICES GROUPS/WEIGHTS
             elif tokentype == 'skinweights' :
                 groupname, nverts, vindices, vweights, mat = readToken(childname)
                 groupname = namelookup[groupname]
-                if debug : 
+                if debug :
                     print('vgroup    : %s (%s/%s verts) %s'%(groupname,len(vindices),len(vweights),'bone' if groupname in tokens else ''))
 
                 #if debug : print('matrix : %s\n%s'%(type(mat),mat))
-                
+
                 groupnames.append(groupname)
                 groupindices.append(vindices)
                 groupweights.append(vweights)
-                
-        ob = bel.mesh.write(obname,tokenname, 
-                            verts, edges, faces, 
-                            matslots, facemats, uvs, 
+
+        ob = bel.mesh.write(obname,tokenname,
+                            verts, edges, faces,
+                            matslots, facemats, uvs,
                             groupnames, groupindices, groupweights,
                             use_smooth_groups,
                             naming_method)
-        
+
         return ob
-                           
+
     ## here we go
-     
+
     file = os.path.basename(filepath)
-    
+
     print('\nimporting %s...'%file)
     start = time.clock()
     path = os.path.dirname(filepath)
@@ -909,7 +909,7 @@ BINARY FORMAT
 
     if header :
         minor, major, format, accuracy = header
-        
+
         if show_geninfo :
             print('\n%s directX header'%file)
             print('  minor  : %s'%(minor))
@@ -934,9 +934,9 @@ BINARY FORMAT
             if show_tree :
                 print('\nDirectX Data Tree :\n')
                 walk_dXtree(tokens.keys())
-            
+
             ## DATA IMPORTATION
-            if show_geninfo : 
+            if show_geninfo :
                 #print(tokens)
                 print('Root frames :\n %s'%rootTokens)
             if parented :
@@ -950,7 +950,7 @@ BINARY FORMAT
                     if obname :
                         meshcount = 0
                         for child in getChilds(obname) :
-                            if tokens[child]['type'] == 'mesh' : 
+                            if tokens[child]['type'] == 'mesh' :
                                 meshcount += 1
                                 if meshcount == 2 :
                                     obname = tokenname
@@ -959,13 +959,12 @@ BINARY FORMAT
 
                     ob = getMesh(obname,tokenname,show_geninfo)
                     ob.matrix_world = global_matrix
-                    
+
             print('done in %.2f\''%(time.clock()-start)) # ,end='\r')
-            
+
         else :
             print('only .x files in text format are currently supported')
             print('please share your file to make the importer evolve')
 
 
         return {'FINISHED'}
-        
\ No newline at end of file
index 0abe7ed..fd8cfe4 100644 (file)
@@ -104,18 +104,18 @@ class BrushSetImporter(bpy.types.Operator):
     bl_idname = "import_image.brushset"
     bl_label = "Import BrushSet"
 
-    filename = StringProperty(name = "File Name", 
-                              description = "filepath", 
-                              default = "", 
-                              maxlen = 1024, 
-                              options = {'ANIMATABLE'}, 
+    filename = StringProperty(name = "File Name",
+                              description = "filepath",
+                              default = "",
+                              maxlen = 1024,
+                              options = {'ANIMATABLE'},
                               subtype = 'NONE')
-    
-    filepath = StringProperty(name = "File Name", 
-                              description = "filepath", 
-                              default = "", 
-                              maxlen = 1024, 
-                              options = {'ANIMATABLE'}, 
+
+    filepath = StringProperty(name = "File Name",
+                              description = "filepath",
+                              default = "",
+                              maxlen = 1024,
+                              options = {'ANIMATABLE'},
                               subtype = 'NONE')
 
     def execute(self, context):
index 9c3b546..851da57 100644 (file)
@@ -1924,7 +1924,3 @@ def unregister():
 
 if __name__ == "__main__":
     register()
-
-
-
-
index 896a3f3..f880d15 100644 (file)
@@ -26,12 +26,12 @@ import struct
 # All data for the images. Basically, each variable is a list with a length,
 # which equals the number of images.
 # Some of the variables are still not used. However, I keep them for purposes
-# in future.  
+# in future.
 class AFMData(object):
-    def __init__(self, date, x_size, y_size, x_pixel, y_pixel, x_off, y_off, 
-                 voltage, feedback, gain, speed, amplitude, angle, datfile, 
-                 channel, unit, z_factor, spec_x_unit, spec_x_label, spec_y_unit, 
-                 spec_y_label, spec_y_factor, spec_points, spec_feedback, 
+    def __init__(self, date, x_size, y_size, x_pixel, y_pixel, x_off, y_off,
+                 voltage, feedback, gain, speed, amplitude, angle, datfile,
+                 channel, unit, z_factor, spec_x_unit, spec_x_label, spec_y_unit,
+                 spec_y_label, spec_y_factor, spec_points, spec_feedback,
                  spec_acquisition, spec_delay):
         self.date = date
         self.x_size = x_size
@@ -50,58 +50,58 @@ class AFMData(object):
         self.channel = channel
         self.unit = unit
         self.z_factor = z_factor
-        self.spec_x_unit = spec_x_unit    
-        self.spec_x_label = spec_x_label     
+        self.spec_x_unit = spec_x_unit
+        self.spec_x_label = spec_x_label
         self.spec_y_unit = spec_y_unit
         self.spec_y_label = spec_y_label
-        self.spec_y_factor = spec_y_factor      
+        self.spec_y_factor = spec_y_factor
         self.spec_points = spec_points
         self.spec_feedback = spec_feedback
         self.spec_acquisition = spec_acquisition
-        self.spec_delay = spec_delay     
-      
+        self.spec_delay = spec_delay
 
-# For loading the Gwyddion images. I basically have followed rules described 
+
+# For loading the Gwyddion images. I basically have followed rules described
 # here: http://gwyddion.net/documentation/user-guide-en/gwyfile-format.html
 def load_gwyddion_images(data_file, channels):
-   
+
     if not os.path.isfile(data_file):
-        return False  
+        return False
 
     AFMdata = AFMData([],[],[],[],[],[],[],
                       [],[],[],[],[],[],[],
                       [],[],[],[],[],[],[],
                       [],[],[],[],[])
     AFMdata.datfile = data_file
-    
+
     datafile = open(data_file, 'rb')
     data = datafile.read()
-    datafile.close()   
-    
+    datafile.close()
+
     # Search the title of each image
-    for a in list(re.finditer(b"data/title\x00", data)):    
-            
+    for a in list(re.finditer(b"data/title\x00", data)):
+
         pos = a.start()
         channel_number = int(data[pos-2:pos-1])
-        
+
         if channels[channel_number] == False:
             continue
-                
+
         pos1 = data[pos:].find(b"\x00") + pos + len("\x00") + 1
         pos2 = data[pos1:].find(b"\x00") + pos1
 
         channel_name = data[pos1:pos2].decode("utf-8")
-        
-        AFMdata.channel.append([channel_number, channel_name])    
-        
-    # Search important parameters and finally the image data.    
-    images = []    
+
+        AFMdata.channel.append([channel_number, channel_name])
+
+    # Search important parameters and finally the image data.
+    images = []
     for a in list(re.finditer(b"/data\x00", data)):
-    
-        pos = a.start()    
+
+        pos = a.start()
 
         channel_number = int(data[pos-1:pos])
-        
+
         if channels[channel_number] == False:
             continue
 
@@ -122,16 +122,16 @@ def load_gwyddion_images(data_file, channels):
         size_y_real = struct.unpack("d",data[pos1+2:pos1+8+2])[0]
 
         # If it is a z image, multiply with 10^9 nm
-        factor = 1.0        
+        factor = 1.0
         pos1 = data[pos:].find(b"si_unit_z") + pos
         unit = data[pos1+34:pos1+36].decode("utf-8")
         if "m" in unit:
             factor = 1000000000.0
-        
+
         # Now, find the image data and store it
         pos1 = data[pos:].find(b"\x00data\x00") + pos + len("\x00data\x00") + 5
 
-        image = []        
+        image = []
         for i in range(size_y_pixel):
             line = []
             for j in range(size_x_pixel):
@@ -139,47 +139,47 @@ def load_gwyddion_images(data_file, channels):
                 k = pos1 + (i*size_x_pixel+j)   * 8
                 l = pos1 + (i*size_x_pixel+j+1) * 8
                 line.append(struct.unpack("d",data[k:l])[0]*factor)
-            image.append(line)     
-            
+            image.append(line)
+
         images.append(image)
-   
+
         # Note all parameters of the image.
         AFMdata.x_pixel.append(int(size_x_pixel))
         AFMdata.y_pixel.append(int(size_y_pixel))
         AFMdata.x_size.append(size_x_real * 1000000000.0)
         AFMdata.y_size.append(size_y_real * 1000000000.0)
-    
+
     return (images, AFMdata)
 
 # Routine to create the mesh and finally the image
-def create_mesh(data_list, 
-                AFMdata, 
-                use_smooth, 
+def create_mesh(data_list,
+                AFMdata,
+                use_smooth,
                 scale_size,
                 scale_height,
                 use_camera,
                 use_lamp):
-    # This is for the image name.       
-    path_list = AFMdata.datfile.strip('/').split('/') 
+    # This is for the image name.
+    path_list = AFMdata.datfile.strip('/').split('/')
 
     number_img = len(data_list)
     image_x_offset_gap = 10.0 * scale_size
-    image_x_all = sum(AFMdata.x_size)*scale_size 
+    image_x_all = sum(AFMdata.x_size)*scale_size
     image_x_offset = -(image_x_all+image_x_offset_gap*(number_img-1)) / 2.0
-                                
+
     # For each image do:
     for k, data in enumerate(data_list):
-      
+
         size_x = AFMdata.x_pixel[k]
         size_y = AFMdata.y_pixel[k]
-        
-        image_scale = AFMdata.x_size[k] / float(AFMdata.x_pixel[k])    
-        image_scale = image_scale * scale_size    
-        image_x_size = AFMdata.x_size[k] * scale_size        
+
+        image_scale = AFMdata.x_size[k] / float(AFMdata.x_pixel[k])
+        image_scale = image_scale * scale_size
+        image_x_size = AFMdata.x_size[k] * scale_size
         image_x_offset += image_x_size / 2.0
-      
+
         image_name = path_list[-1] + "_" + AFMdata.channel[k][1]
-        
+
         data_mesh = []
         data_faces = []
 
@@ -187,27 +187,27 @@ def create_mesh(data_list,
 
         for i, line in enumerate(data):
             for j, pixel in enumerate(line):
-            
+
                # The vertices
-               data_mesh.append(Vector((float(i) * image_scale, 
-                                        float(j) * image_scale, 
+               data_mesh.append(Vector((float(i) * image_scale,
+                                        float(j) * image_scale,
                                         float(pixel)*scale_height)))
-               
+
                # The faces
                if i < size_y-1 and j < size_x-1:
-                   data_faces.append( [size_x*i+j      , size_x*(i+1)+j, 
-                                       size_x*(i+1)+j+1, size_x*i+j+1    ]) 
+                   data_faces.append( [size_x*i+j      , size_x*(i+1)+j,
+                                       size_x*(i+1)+j+1, size_x*i+j+1    ])
 
         #print("passed - create_mesh ---- 2")
-               
+
         # Build the mesh
         surface_mesh = bpy.data.meshes.new("Mesh")
         surface_mesh.from_pydata(data_mesh, [], data_faces)
         surface_mesh.update()
         surface = bpy.data.objects.new(image_name, surface_mesh)
         bpy.context.scene.objects.link(surface)
-        bpy.ops.object.select_all(action='DESELECT')        
-        surface.select = True 
+        bpy.ops.object.select_all(action='DESELECT')
+        surface.select = True
 
         bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY')
         # sum((v.co for v in mesh.vertices), Vector()) / len(mesh.vertices)
@@ -216,21 +216,21 @@ def create_mesh(data_list,
             for polygon in surface.data.polygons:
                 polygon.use_smooth = True
 
-        surface.location = Vector((0.0, image_x_offset, 0.0)) 
+        surface.location = Vector((0.0, image_x_offset, 0.0))
         image_x_offset += image_x_size / 2.0 + image_x_offset_gap
 
         #print("passed - create_mesh ---- 3")
 
 
-        
+
     object_center_vec = Vector((0.0,0.0,0.0))
-    object_size = (sum(AFMdata.x_size) * scale_size 
+    object_size = (sum(AFMdata.x_size) * scale_size
                    +image_x_offset_gap * (len(data_list)-1))
 
     # ------------------------------------------------------------------------
     # CAMERA AND LAMP
     camera_factor = 20.0
-    
+
     # If chosen a camera is put into the scene.
     if use_camera == True:
 
@@ -245,14 +245,14 @@ def create_mesh(data_list,
         camera_xyz_vec = object_center_vec + object_camera_vec
 
         # Create the camera
-        current_layers=bpy.context.scene.layers 
+        current_layers=bpy.context.scene.layers
         camera_data = bpy.data.cameras.new("A_camera")
         camera_data.lens = 45
         camera_data.clip_end = 50000.0
         camera = bpy.data.objects.new("A_camera", camera_data)
         camera.location = camera_xyz_vec
         camera.layers = current_layers
-        bpy.context.scene.objects.link(camera) 
+        bpy.context.scene.objects.link(camera)
 
         # Here the camera is rotated such it looks towards the center of
         # the object. The [0.0, 0.0, 1.0] vector along the z axis
@@ -267,8 +267,8 @@ def create_mesh(data_list,
 
         # Rotate the camera around its axis by 90° such that we have a nice
         # camera position and view onto the object.
-        bpy.ops.object.select_all(action='DESELECT')        
-        camera.select = True         
+        bpy.ops.object.select_all(action='DESELECT')
+        camera.select = True
         bpy.ops.transform.rotate(value=(90.0*2*pi/360.0),
                                  axis=object_camera_vec,
                                  constraint_axis=(False, False, False),
@@ -299,11 +299,11 @@ def create_mesh(data_list,
         lamp_data = bpy.data.lamps.new(name="A_lamp", type="POINT")
         lamp_data.distance = 5000.0
         lamp_data.energy = 3.0
-        lamp_data.shadow_method = 'RAY_SHADOW'        
+        lamp_data.shadow_method = 'RAY_SHADOW'
         lamp = bpy.data.objects.new("A_lamp", lamp_data)
         lamp.location = lamp_xyz_vec
         lamp.layers = current_layers
-        bpy.context.scene.objects.link(lamp)         
+        bpy.context.scene.objects.link(lamp)
 
         bpy.context.scene.world.light_settings.use_ambient_occlusion = True
-        bpy.context.scene.world.light_settings.ao_factor = 0.1      
+        bpy.context.scene.world.light_settings.ao_factor = 0.1
index 093d6e9..eba9273 100644 (file)
@@ -20,7 +20,7 @@ import bpy
 from . import import_xyz
 
 
-class AtomsExport(object):  
+class AtomsExport(object):
     __slots__ = ('element', 'location')
     def __init__(self, element, location):
         self.element  = element
@@ -32,13 +32,13 @@ def export_xyz(obj_type, filepath_xyz):
     list_atoms = []
     counter = 0
     for obj in bpy.context.selected_objects:
-    
+
         if "Stick" in obj.name:
             continue
-            
+
         if obj.type not in {'MESH', 'SURFACE', 'META'}:
-            continue 
-       
+            continue
+
         name = ""
         for element in import_xyz.ELEMENTS_DEFAULT:
             if element[1] in obj.name:
@@ -46,7 +46,7 @@ def export_xyz(obj_type, filepath_xyz):
                     name = "X"
                 else:
                     name = element[2]
-        
+
         if name == "":
             if obj_type == "0":
                 name = "?"
@@ -57,12 +57,12 @@ def export_xyz(obj_type, filepath_xyz):
             for vertex in obj.data.vertices:
                 location = obj.matrix_world*vertex.co
                 list_atoms.append(AtomsExport(name, location))
-                counter += 1                                       
+                counter += 1
         else:
             if not obj.parent:
                 location = obj.location
-                list_atoms.append(AtomsExport(name, location))                                   
-                counter += 1                                               
+                list_atoms.append(AtomsExport(name, location))
+                counter += 1
 
     xyz_file_p = open(filepath_xyz, "w")
     xyz_file_p.write("%d\n" % counter)
@@ -82,4 +82,3 @@ def export_xyz(obj_type, filepath_xyz):
     xyz_file_p.close()
 
     return True
-
index 9a575f2..eedd5c3 100644 (file)
@@ -153,8 +153,8 @@ ELEMENTS_DEFAULT = (
 # custom data file for instance.
 ELEMENTS = []
 
-# This is the list, which contains all atoms of all frames! Each item is a 
-# list which contains the atoms of a single frame. It is a list of  
+# This is the list, which contains all atoms of all frames! Each item is a
+# list which contains the atoms of a single frame. It is a list of
 # 'AtomProp'.
 ALL_FRAMES = []
 
@@ -174,7 +174,7 @@ class ElementProp(object):
         self.radii_ionic = radii_ionic
 
 # This is the class, which stores the properties of one atom.
-class AtomProp(object):  
+class AtomProp(object):
     __slots__ = ('element', 'name', 'location', 'radius', 'color', 'material')
     def __init__(self, element, name, location, radius, color, material):
         self.element = element
@@ -186,7 +186,7 @@ class AtomProp(object):
 
 
 # -----------------------------------------------------------------------------
-#                                                           Some basic routines        
+#                                                           Some basic routines
 
 def read_elements():
 
@@ -230,12 +230,12 @@ def read_xyz_file(filepath_xyz,radiustype):
         if len(split_list) == 1:
             number_atoms = int(split_list[0])
             FLAG = True
-            
+
         if FLAG == True:
-        
+
             line = filepath_xyz_p.readline()
             line = line.rstrip()
-            
+
             all_atoms= []
             for i in range(number_atoms):
 
@@ -246,18 +246,18 @@ def read_xyz_file(filepath_xyz,radiustype):
                 # may increase (or decrease). If it decreases, the addon crashes.
                 # If it increases, only the tot number of atoms of the first frame
                 # is used.
-                # By time, I will allow varying atom numbers ... but this takes 
-                # some time ...            
+                # By time, I will allow varying atom numbers ... but this takes
+                # some time ...
                 if number_frames != 0:
                     if i >= total_number_atoms:
                         break
-                        
-       
+
+
                 line = filepath_xyz_p.readline()
                 line = line.rstrip()
                 split_list = line.rsplit()
                 short_name = str(split_list[0])
-                     
+
                 # Go through all elements and find the element of the current atom.
                 FLAG_FOUND = False
                 for element in ELEMENTS:
@@ -270,7 +270,7 @@ def read_xyz_file(filepath_xyz,radiustype):
                         color = element.color
                         FLAG_FOUND = True
                         break
-                
+
                 # Is it a vacancy or an 'unknown atom' ?
                 if FLAG_FOUND == False:
                     # Give this atom also a name. If it is an 'X' then it is a
@@ -287,44 +287,44 @@ def read_xyz_file(filepath_xyz,radiustype):
                         name = str.upper(short_name)
                         radius = float(ELEMENTS[-2].radii[int(radiustype)])
                         color = ELEMENTS[-2].color
-              
+
                 x = float(split_list[1])
                 y = float(split_list[2])
                 z = float(split_list[3])
-                
+
                 location = Vector((x,y,z))
-            
+
                 all_atoms.append([short_name, name, location, radius, color])
-            
-            # We note here all elements. This needs to be done only once. 
+
+            # We note here all elements. This needs to be done only once.
             if number_frames == 0:
-            
+
                 # This is a guarantee that only the total number of atoms of the
                 # first frame is used. Condition is, so far, that the number of
                 # atoms in a xyz file is constant. However, sometimes the number
                 # may increase (or decrease). If it decreases, the addon crashes.
                 # If it increases, only the tot number of atoms of the first frame
                 # is used.
-                # By time, I will allow varying atom numbers ... but this takes 
+                # By time, I will allow varying atom numbers ... but this takes
                 # some time ...
                 total_number_atoms = number_atoms
-                
-                
+
+
                 elements = []
                 for atom in all_atoms:
                     FLAG_FOUND = False
                     for element in elements:
-                        # If the atom name is already in the list, 
+                        # If the atom name is already in the list,
                         # FLAG on 'True'.
                         if element == atom[1]:
                             FLAG_FOUND = True
                             break
                     # No name in the current list has been found? => New entry.
                     if FLAG_FOUND == False:
-                        # Stored are: Atom label (e.g. 'Na'), the corresponding 
+                        # Stored are: Atom label (e.g. 'Na'), the corresponding
                         # atom name (e.g. 'Sodium') and its color.
                         elements.append(atom[1])
-            
+
             # Sort the atoms: create lists of atoms of one type
             structure = []
             for element in elements:
@@ -343,7 +343,7 @@ def read_xyz_file(filepath_xyz,radiustype):
             FLAG = False
 
     filepath_xyz_p.close()
-    
+
     return total_number_atoms
 
 
@@ -356,7 +356,7 @@ def import_xyz(Ball_type,
                Ball_radius_factor,
                radiustype,
                Ball_distance_factor,
-               put_to_center, 
+               put_to_center,
                put_to_center_all,
                use_camera,
                use_lamp,
@@ -373,9 +373,9 @@ def import_xyz(Ball_type,
     # ------------------------------------------------------------------------
     # READING DATA OF ATOMS
 
-    Number_of_total_atoms = read_xyz_file(filepath_xyz, 
+    Number_of_total_atoms = read_xyz_file(filepath_xyz,
                                                        radiustype)
-                                               
+
     # We show the atoms of the first frame.
     first_frame = ALL_FRAMES[0]
 
@@ -441,7 +441,7 @@ def import_xyz(Ball_type,
     if put_to_center_all == True:
 
         # For all frames
-        for frame in ALL_FRAMES: 
+        for frame in ALL_FRAMES:
 
             sum_vec = Vector((0.0,0.0,0.0))
 
@@ -454,7 +454,7 @@ def import_xyz(Ball_type,
                 # may increase (or decrease). If it decreases, the addon crashes.
                 # If it increases, only the tot number of atoms of the first frame
                 # is used.
-                # By time, I will allow varying atom numbers ... but this takes 
+                # By time, I will allow varying atom numbers ... but this takes
                 # some time ...
                 if i >= Number_of_total_atoms:
                     break
@@ -469,7 +469,7 @@ def import_xyz(Ball_type,
                 for atom in atoms_of_one_type:
                     atom.location -= sum_vec
 
-   
+
     # ------------------------------------------------------------------------
     # SCALING
 
@@ -477,7 +477,7 @@ def import_xyz(Ball_type,
     for atoms_of_one_type in first_frame:
         for atom in atoms_of_one_type:
             atom.location *= Ball_distance_factor
-    
+
     # ------------------------------------------------------------------------
     # DETERMINATION OF SOME GEOMETRIC PROPERTIES
 
@@ -521,14 +521,14 @@ def import_xyz(Ball_type,
         camera_xyz_vec = object_center_vec + object_camera_vec
 
         # Create the camera
-        current_layers=bpy.context.scene.layers 
+        current_layers=bpy.context.scene.layers
         camera_data = bpy.data.cameras.new("A_camera")
         camera_data.lens = 45
         camera_data.clip_end = 500.0
         camera = bpy.data.objects.new("A_camera", camera_data)
         camera.location = camera_xyz_vec
         camera.layers = current_layers
-        bpy.context.scene.objects.link(camera) 
+        bpy.context.scene.objects.link(camera)
 
         # Here the camera is rotated such it looks towards the center of
         # the object. The [0.0, 0.0, 1.0] vector along the z axis
@@ -543,8 +543,8 @@ def import_xyz(Ball_type,
 
         # Rotate the camera around its axis by 90° such that we have a nice
         # camera position and view onto the object.
-        bpy.ops.object.select_all(action='DESELECT')        
-        camera.select = True         
+        bpy.ops.object.select_all(action='DESELECT')
+        camera.select = True
         bpy.ops.transform.rotate(value=(90.0*2*pi/360.0),
                                  axis=object_camera_vec,
                                  constraint_axis=(False, False, False),
@@ -575,15 +575,15 @@ def import_xyz(Ball_type,
         lamp_data = bpy.data.lamps.new(name="A_lamp", type="POINT")
         lamp_data.distance = 500.0
         lamp_data.energy = 3.0
-        lamp_data.shadow_method = 'RAY_SHADOW'        
+        lamp_data.shadow_method = 'RAY_SHADOW'
         lamp = bpy.data.objects.new("A_lamp", lamp_data)
         lamp.location = lamp_xyz_vec
         lamp.layers = current_layers
-        bpy.context.scene.objects.link(lamp)         
+        bpy.context.scene.objects.link(lamp)
 
         bpy.context.scene.world.light_settings.use_ambient_occlusion = True
         bpy.context.scene.world.light_settings.ao_factor = 0.2
-        
+
 
     # ------------------------------------------------------------------------
     # DRAWING THE ATOMS
@@ -634,8 +634,8 @@ def import_xyz(Ball_type,
                             layers=current_layers)
             # Meta balls
             elif Ball_type == "2":
-                bpy.ops.object.metaball_add(type='BALL', view_align=False, 
-                            enter_editmode=False, location=(0, 0, 0), 
+                bpy.ops.object.metaball_add(type='BALL', view_align=False,
+                            enter_editmode=False, location=(0, 0, 0),
                             rotation=(0, 0, 0), layers=current_layers)
 
         ball = bpy.context.scene.objects.active
@@ -654,7 +654,7 @@ def import_xyz(Ball_type,
 
     # ------------------------------------------------------------------------
     # SELECT ALL LOADED OBJECTS
-    
+
     bpy.ops.object.select_all(action='DESELECT')
     obj = None
     for obj in STRUCTURE:
@@ -669,71 +669,68 @@ def build_frames(frame_delta, frame_skip):
 
     scn = bpy.context.scene
 
-    # Introduce the basis for all elements that appear in the structure.     
+    # Introduce the basis for all elements that appear in the structure.
     for element in STRUCTURE:
-     
-        bpy.ops.object.select_all(action='DESELECT')   
+
+        bpy.ops.object.select_all(action='DESELECT')
         bpy.context.scene.objects.active = element
         element.select = True
         bpy.ops.object.shape_key_add(True)
-        
-    frame_skip += 1    
 
-    # Introduce the keys and reference the atom positions for each key.     
+    frame_skip += 1
+
+    # Introduce the keys and reference the atom positions for each key.
     i = 0
-    for j, frame in enumerate(ALL_FRAMES):        
-           
+    for j, frame in enumerate(ALL_FRAMES):
+
         if j % frame_skip == 0:
-           
+
             for elements_frame, elements_structure in zip(frame,STRUCTURE):
-             
+
                 key = elements_structure.shape_key_add()
-    
+
                 for atom_frame, atom_structure in zip(elements_frame, key.data):
-    
-                    atom_structure.co = (atom_frame.location 
+
+                    atom_structure.co = (atom_frame.location
                                        - elements_structure.location)
-    
-                key.name = atom_frame.name + "_frame_" + str(i) 
+
+                key.name = atom_frame.name + "_frame_" + str(i)
 
             i += 1
 
     num_frames = i
-        
+
     scn.frame_start = 0
     scn.frame_end = frame_delta * num_frames
 
     # Manage the values of the keys
     for element in STRUCTURE:
-        scn.frame_current = 0 
+
+        scn.frame_current = 0
 
         element.data.shape_keys.key_blocks[1].value = 1.0
         element.data.shape_keys.key_blocks[2].value = 0.0
-        element.data.shape_keys.key_blocks[1].keyframe_insert("value")     
-        element.data.shape_keys.key_blocks[2].keyframe_insert("value")         
+        element.data.shape_keys.key_blocks[1].keyframe_insert("value")
+        element.data.shape_keys.key_blocks[2].keyframe_insert("value")
 
         scn.frame_current += frame_delta
 
         number = 0
-    
+
         for number in range(num_frames)[2:]:#-1]:
-    
+
             element.data.shape_keys.key_blocks[number-1].value = 0.0
             element.data.shape_keys.key_blocks[number].value = 1.0
             element.data.shape_keys.key_blocks[number+1].value = 0.0
-            element.data.shape_keys.key_blocks[number-1].keyframe_insert("value")     
-            element.data.shape_keys.key_blocks[number].keyframe_insert("value")     
-            element.data.shape_keys.key_blocks[number+1].keyframe_insert("value")         
-                
+            element.data.shape_keys.key_blocks[number-1].keyframe_insert("value")
+            element.data.shape_keys.key_blocks[number].keyframe_insert("value")
+            element.data.shape_keys.key_blocks[number+1].keyframe_insert("value")
+
             scn.frame_current += frame_delta
-            
-        number += 1    
-            
-        element.data.shape_keys.key_blocks[number].value = 1.0
-        element.data.shape_keys.key_blocks[number-1].value = 0.0
-        element.data.shape_keys.key_blocks[number].keyframe_insert("value")     
-        element.data.shape_keys.key_blocks[number-1].keyframe_insert("value")    
-        
 
+        number += 1
 
+        element.data.shape_keys.key_blocks[number].value = 1.0
+        element.data.shape_keys.key_blocks[number-1].value = 0.0
+        element.data.shape_keys.key_blocks[number].keyframe_insert("value")
+        element.data.shape_keys.key_blocks[number-1].keyframe_insert("value")
index 1cf1689..b5ca0dd 100644 (file)
-# ##### BEGIN GPL LICENSE BLOCK #####\r
-#\r
-#  This program is free software; you can redistribute it and/or\r
-#  modify it under the terms of the GNU General Public License\r
-#  as published by the Free Software Foundation; either version 2\r
-#  of the License, or (at your option) any later version.\r
-#\r
-#  This program is distributed in the hope that it will be useful,\r
-#  but WITHOUT ANY WARRANTY; without even the implied warranty of\r
-#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
-#  GNU General Public License for more details.\r
-#\r
-#  You should have received a copy of the GNU General Public License\r
-#  along with this program; if not, write to the Free Software Foundation,\r
-#  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r
-#\r
-# ##### END GPL LICENSE BLOCK #####\r
-\r
-bl_info = {\r
-    "name": "PCD",\r
-    "author": "Aurel Wildfellner",\r
-    "version": (0, 2),\r
-    "blender": (2, 57, 0),\r
-    "location": "File > Import-Export > Point Cloud Data",\r
-    "description": "Imports and Exports PCD (Point Cloud Data) files. PCD files are the default format used by  pcl (Point Cloud Library).",\r
-    "warning": "",\r
-    "wiki_url": "http://wiki.blender.org/index.php?title=Extensions:2.6/Py/Scripts/Import-Export/Point_Cloud_Data_IO",\r
-    "tracker_url": "https://developer.blender.org/maniphest/task/edit/form/2/",\r
-#    "support": 'OFFICAL',\r
-    "category": "Import-Export"}\r
-\r
-\r
-if "bpy" in locals():\r
-    import imp\r
-    imp.reload(pcd_utils)\r
-else:\r
-    from . import pcd_utils\r
-\r
-import itertools\r
-import os\r
-\r
-\r
-import bpy\r
-from bpy.props import *\r
-from bpy_extras.io_utils import ExportHelper, ImportHelper\r
-\r
-\r
-class ImportPCD(bpy.types.Operator, ImportHelper):\r
-    """Load PCD (Point Cloud Data) files"""\r
-    bl_idname = "import_points.stl"\r
-    bl_label = "Import PCD"\r
-\r
-    filename_ext = ".pcd"\r
-\r
-    filter_glob = StringProperty(default="*.pcd", options={'HIDDEN'})\r
-    object_name = StringProperty(default="", options={'HIDDEN'})\r
-\r
-    files = CollectionProperty(name="File Path",\r
-                          description="File path used for importing "\r
-                                      "the PCD file",\r
-                          type=bpy.types.OperatorFileListElement)\r
-\r
-    directory = StringProperty(subtype='DIR_PATH')\r
-\r
-    def execute(self, context):\r
-        paths = [os.path.join(self.directory, name.name) for name in self.files]\r
-        if not paths:\r
-            paths.append(self.filepath)\r
-\r
-        for path in paths:\r
-\r
-            objname = ""\r
-\r
-            if self.object_name == "":\r
-                # name the object with the filename exluding .pcd\r
-                objname = os.path.basename(path)[:-4]\r
-            else:\r
-                # use name set by calling the operator with the arg\r
-                objname = self.object_name\r
-\r
-            pcd_utils.import_pcd(path, objname)\r
-\r
-        return {'FINISHED'}\r
-\r
-\r
-\r
-\r
-class ExportPCD(bpy.types.Operator, ExportHelper):\r
-    """Save PCD (Point Cloud Data) files"""\r
-    bl_idname = "export_points.pcd"\r
-    bl_label = "Export PCD"\r
-\r
-    filename_ext = ".pcd"\r
-\r
-    filter_glob = StringProperty(default="*.pcd", options={'HIDDEN'})\r
-\r
-\r
-    def execute(self, context):\r
-        pcd_utils.export_pcd(self.filepath)\r
-\r
-        return {'FINISHED'}\r
-\r
-\r
-\r
-\r
-def menu_func_import(self, context):\r
-    self.layout.operator(ImportPCD.bl_idname, text="Point Cloud Data (.pcd)").filepath = "*.pcd"\r
-\r
-\r
-def menu_func_export(self, context):\r
-    self.layout.operator(ExportPCD.bl_idname, text="Point Cloud Data (.pcd)")\r
-\r
-\r
-def register():\r
-    bpy.utils.register_module(__name__)\r
-\r
-    bpy.types.INFO_MT_file_import.append(menu_func_import)\r
-    bpy.types.INFO_MT_file_export.append(menu_func_export)\r
-\r
-\r
-def unregister():\r
-    bpy.utils.unregister_module(__name__)\r
-\r
-    bpy.types.INFO_MT_file_import.remove(menu_func_import)\r
-    bpy.types.INFO_MT_file_export.remove(menu_func_export)\r
-\r
-\r
-if __name__ == "__main__":\r
-    register()\r
-\r
+# ##### 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": "PCD",
+    "author": "Aurel Wildfellner",
+    "version": (0, 2),
+    "blender": (2, 57, 0),
+    "location": "File > Import-Export > Point Cloud Data",
+    "description": "Imports and Exports PCD (Point Cloud Data) files. PCD files are the default format used by  pcl (Point Cloud Library).",
+    "warning": "",
+    "wiki_url": "http://wiki.blender.org/index.php?title=Extensions:2.6/Py/Scripts/Import-Export/Point_Cloud_Data_IO",
+    "tracker_url": "https://developer.blender.org/maniphest/task/edit/form/2/",
+#    "support": 'OFFICAL',
+    "category": "Import-Export"}
+
+
+if "bpy" in locals():
+    import imp
+    imp.reload(pcd_utils)
+else:
+    from . import pcd_utils
+
+import itertools
+import os
+
+
+import bpy
+from bpy.props import *
+from bpy_extras.io_utils import ExportHelper, ImportHelper
+
+
+class ImportPCD(bpy.types.Operator, ImportHelper):
+    """Load PCD (Point Cloud Data) files"""
+    bl_idname = "import_points.stl"
+    bl_label = "Import PCD"
+
+    filename_ext = ".pcd"
+
+    filter_glob = StringProperty(default="*.pcd", options={'HIDDEN'})
+    object_name = StringProperty(default="", options={'HIDDEN'})
+
+    files = CollectionProperty(name="File Path",
+                          description="File path used for importing "
+                                      "the PCD file",
+                          type=bpy.types.OperatorFileListElement)
+
+    directory = StringProperty(subtype='DIR_PATH')
+
+    def execute(self, context):
+        paths = [os.path.join(self.directory, name.name) for name in self.files]
+        if not paths:
+            paths.append(self.filepath)
+
+        for path in paths:
+
+            objname = ""
+
+            if self.object_name == "":
+                # name the object with the filename exluding .pcd
+                objname = os.path.basename(path)[:-4]
+            else:
+                # use name set by calling the operator with the arg
+                objname = self.object_name
+
+            pcd_utils.import_pcd(path, objname)
+
+        return {'FINISHED'}
+
+
+
+
+class ExportPCD(bpy.types.Operator, ExportHelper):
+    """Save PCD (Point Cloud Data) files"""
+    bl_idname = "export_points.pcd"
+    bl_label = "Export PCD"
+
+    filename_ext = ".pcd"
+
+    filter_glob = StringProperty(default="*.pcd", options={'HIDDEN'})
+
+
+    def execute(self, context):
+        pcd_utils.export_pcd(self.filepath)
+
+        return {'FINISHED'}
+
+
+
+
+def menu_func_import(self, context):
+    self.layout.operator(ImportPCD.bl_idname, text="Point Cloud Data (.pcd)").filepath = "*.pcd"
+
+
+def menu_func_export(self, context):
+    self.layout.operator(ExportPCD.bl_idname, text="Point Cloud Data (.pcd)")
+
+
+def register():
+    bpy.utils.register_module(__name__)
+
+    bpy.types.INFO_MT_file_import.append(menu_func_import)
+    bpy.types.INFO_MT_file_export.append(menu_func_export)
+
+
+def unregister():
+    bpy.utils.unregister_module(__name__)
+
+    bpy.types.INFO_MT_file_import.remove(menu_func_import)
+    bpy.types.INFO_MT_file_export.remove(menu_func_export)
+
+
+if __name__ == "__main__":
+    register()
index c38a14f..b2e94ab 100644 (file)
@@ -1,97 +1,95 @@
-# ##### BEGIN GPL LICENSE BLOCK #####\r
-#\r
-#  This program is free software; you can redistribute it and/or\r
-#  modify it under the terms of the GNU General Public License\r
-#  as published by the Free Software Foundation; either version 2\r
-#  of the License, or (at your option) any later version.\r
-#\r
-#  This program is distributed in the hope that it will be useful,\r
-#  but WITHOUT ANY WARRANTY; without even the implied warranty of\r
-#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
-#  GNU General Public License for more details.\r
-#\r
-#  You should have received a copy of the GNU General Public License\r
-#  along with this program; if not, write to the Free Software Foundation,\r
-#  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r
-#\r
-# ##### END GPL LICENSE BLOCK #####\r
-\r
-import bpy\r
-\r
-import os\r
-import subprocess\r
-import tempfile\r
-\r
-from . import pcdparser\r
-\r
-\r
-def create_and_link_mesh(name, points):\r
-    """\r
-    Create a blender mesh and object called name from a list of\r
-    *points* and link it in the current scene.\r
-    """\r
-\r
-    mesh = bpy.data.meshes.new(name)\r
-    mesh.from_pydata(points, [], [])\r
-\r
-    # update mesh to allow proper display\r
-    mesh.validate()\r
-    mesh.update()\r
-\r
-    scene = bpy.context.scene\r
-\r
-    obj = bpy.data.objects.new(name, mesh)\r
-    scene.objects.link(obj)\r
-    obj.select = True\r
-\r
-\r
-def import_pcd(filepath, name="new_pointcloud"):\r
-    # check if the file is binary compressed\r
-    parser = pcdparser.PCDParser.factory(filepath, pcdparser.PointXYZ)\r
-    parser.onlyParseHeader()\r
-    is_binary_compressed = parser.datatype == 'BINARY_COMPRESSED'\r
-\r
-    # create a temp uncompressed pcd file\r
-    if (is_binary_compressed):\r
-        tmpdir = tempfile.TemporaryDirectory()\r
-        tmpfilepath = tmpdir.name + "blender_pcd_io_tmp.pcd"\r
-        try:\r
-            subprocess.call(["pcl_convert_pcd_ascii_binary", filepath, tmpfilepath, "1"])\r
-        except FileNotFoundError:\r
-            print("[ERROR] Can't read BINARY COMPRESSED PCD. No pcl_convert_pcd_ascii_binary found! Have you installed libPCL?")\r
-            return\r
-        filepath = tmpfilepath\r
-\r
-\r
-    # do actual parsing\r
-    parser = pcdparser.PCDParser.factory(filepath, pcdparser.PointXYZ)\r
-    parser.parseFile()\r
-    points = parser.getPoints()\r
-\r
-    blender_points = []\r
-    for point in points:\r
-        blender_points.append((point.x, point.y, point.z))\r
-\r
-    create_and_link_mesh(name, blender_points)\r
-  \r
-\r
-def export_pcd(filepath):\r
-    obj = bpy.context.active_object\r
-\r
-    # apply object transformation and modifiers\r
-    mesh = obj.to_mesh(bpy.context.scene, True, "PREVIEW")\r
-    objmat = obj.matrix_world\r
-    \r
-    points = []\r
-    for vert in mesh.vertices:\r
-        co = objmat * vert.co\r
-        point = pcdparser.PointXYZ()\r
-        point.x = co.x\r
-        point.y = co.y\r
-        point.z = co.z\r
-        points.append(point)\r
-\r
-    writer = pcdparser.PCDWriter(points)\r
-    writer.write(filepath)\r
-\r
-\r
+# ##### 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
+
+import os
+import subprocess
+import tempfile
+
+from . import pcdparser
+
+
+def create_and_link_mesh(name, points):
+    """
+    Create a blender mesh and object called name from a list of
+    *points* and link it in the current scene.
+    """
+
+    mesh = bpy.data.meshes.new(name)
+    mesh.from_pydata(points, [], [])
+
+    # update mesh to allow proper display
+    mesh.validate()
+    mesh.update()
+
+    scene = bpy.context.scene
+
+    obj = bpy.data.objects.new(name, mesh)
+    scene.objects.link(obj)
+    obj.select = True
+
+
+def import_pcd(filepath, name="new_pointcloud"):
+    # check if the file is binary compressed
+    parser = pcdparser.PCDParser.factory(filepath, pcdparser.PointXYZ)
+    parser.onlyParseHeader()
+    is_binary_compressed = parser.datatype == 'BINARY_COMPRESSED'
+
+    # create a temp uncompressed pcd file
+    if (is_binary_compressed):
+        tmpdir = tempfile.TemporaryDirectory()
+        tmpfilepath = tmpdir.name + "blender_pcd_io_tmp.pcd"
+        try:
+            subprocess.call(["pcl_convert_pcd_ascii_binary", filepath, tmpfilepath, "1"])
+        except FileNotFoundError:
+            print("[ERROR] Can't read BINARY COMPRESSED PCD. No pcl_convert_pcd_ascii_binary found! Have you installed libPCL?")
+            return
+        filepath = tmpfilepath
+
+
+    # do actual parsing
+    parser = pcdparser.PCDParser.factory(filepath, pcdparser.PointXYZ)
+    parser.parseFile()
+    points = parser.getPoints()
+
+    blender_points = []
+    for point in points:
+        blender_points.append((point.x, point.y, point.z))
+
+    create_and_link_mesh(name, blender_points)
+
+
+def export_pcd(filepath):
+    obj = bpy.context.active_object
+
+    # apply object transformation and modifiers
+    mesh = obj.to_mesh(bpy.context.scene, True, "PREVIEW")
+    objmat = obj.matrix_world
+
+    points = []
+    for vert in mesh.vertices:
+        co = objmat * vert.co
+        point = pcdparser.PointXYZ()
+        point.x = co.x
+        point.y = co.y
+        point.z = co.z
+        points.append(point)
+
+    writer = pcdparser.PCDWriter(points)
+    writer.write(filepath)
index 269cf15..7827785 100644 (file)
-# ##### BEGIN GPL LICENSE BLOCK #####\r
-#\r
-#  This program is free software; you can redistribute it and/or\r
-#  modify it under the terms of the GNU General Public License\r
-#  as published by the Free Software Foundation; either version 2\r
-#  of the License, or (at your option) any later version.\r
-#   \r
-#  This program is distributed in the hope that it will be useful,\r
-#  but WITHOUT ANY WARRANTY; without even the implied warranty of\r
-#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
-#  GNU General Public License for more details.\r
-#\r
-#  You should have received a copy of the GNU General Public License\r
-#  along with this program; if not, write to the Free Software Foundation,\r
-#  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r
-#\r
-# ##### END GPL LICENSE BLOCK #####\r
-\r
-\r
-import struct\r
-import io\r
-\r
-try:\r
-    import lzf\r
-    GOT_LZF_MODULE=True\r
-except:\r
-    GOT_LZF_MODULE=False\r
-\r
-\r
-\r
-def dumpHexData(data):\r
-    for byte in data:\r
-        print(hex(byte) + " ", end="")\r
-    print()\r
-\r
-\r
-def encodeASCIILine(line):\r
-    return line.decode(encoding='ASCII')\r
-\r
-\r
-\r
-class Point:\r
-\r
-    def __init__(self):\r
-        pass\r
-\r
-\r
-    def setField(self, fieldname, values):\r
-        pass\r
-\r
-\r
-\r
-\r
-class PointXYZ(Point):\r
-\r
-    def __init__(self):\r
-        super().__init__()\r
-        self.x = 0\r
-        self.y = 0\r
-        self.z = 0\r
-\r
-\r
-    def setField(self, fieldname, values):\r
-        value = values[0]\r
-        if fieldname == 'x':\r
-            self.x = value\r
-        elif fieldname == 'y':\r
-            self.y = value\r
-        elif fieldname == 'z':\r
-            self.z = value\r
-\r
-\r
-\r
-\r
-class PCDParser:\r
-\r
-    filepath = ''\r
-    file = None\r
-\r
-    points = []\r
-    PointClass = None\r
-\r
-    headerEnd = False\r
-\r
-\r
-    @staticmethod\r
-    def factory(filepath, PointClass):\r
-        version = 'NO_VERSION_NUMBER'\r
-        with open(filepath, 'rb') as f:\r
-            for b in f:\r
-                line = encodeASCIILine(b)\r
-                line_split = line.split()\r
-                if line_split[0] == 'VERSION' and len(line_split) > 1:\r
-                    version = line_split[1]\r
-                    break\r
-      \r
-        if version == ".7" or version == "0.7": \r
-            return PCDParser_v0_7(filepath, PointClass)\r
-        else:\r
-            return None\r
-\r
-\r
-    def __init__(self, filepath, PointClass):\r
-        self.filepath = filepath\r
-        self.PointClass = PointClass\r
-\r
-        self.file = None\r
-        self.headerEnd = False\r
-        self.points = []\r
-\r
-\r
-    def parserWarning(self, msg):\r
-        print("[WARNING] ", msg)\r
-    \r
-\r
-    def rmComment(self, line):\r
-        return line[:line.find('#')] \r
-\r
-\r
-    def parseFile(self):\r
-        with open(self.filepath, 'rb') as self.file:\r
-            self.parseHeader()\r
-            self.parsePoints()\r
-\r
-    def onlyParseHeader(self):\r
-        with open(self.filepath, 'rb') as self.file:\r
-            self.parseHeader()\r
-\r
-\r
-    def parseHeader(self):\r
-        for b in self.file:\r
-            line = encodeASCIILine(b)\r
-            line = self.rmComment(line)\r
-\r
-            split = line.split()\r
-            if len(split) > 0:\r
-                self.parseHeaderLine(split)\r
-\r
-            if self.headerEnd:\r
-                self.finalizeHeader()\r
-                break\r
-\r
-\r
-    def parseHeaderLine(self, split):\r
-        keyword = split[0]\r
-        self.parserWarning("Uknown header Keyword '" + keyword + "' gets ignored")\r
-\r
-    \r
-    def finalizeHeader(self):\r
-        pass\r
-\r
-\r
-    def parsePoints(self):\r
-        pass\r
-\r
-\r
-    def getPoints(self):\r
-        return self.points\r
-\r
-\r
-    def version(self):\r
-        return 'NO_VERSION_NUMBER'\r
-\r
-\r
-\r
-\r
-class PCDParser_v0_7(PCDParser):\r
-\r
-    fields = []\r
-\r
-    def __init__(self, filepath, PointClass):\r
-        super().__init__(filepath, PointClass)\r
-        self.fields = []\r
-\r
-\r
-    def version(self):\r
-        return '.7'\r
-\r
-\r
-    def parseHeaderLine(self, split):\r
-        keyword = split[0]\r
-        if keyword == 'VERSION':\r
-            self.parseVERSION(split[1:])\r
-        elif keyword == 'FIELDS':\r
-            self.parseFIELDS(split[1:])\r
-        elif keyword == 'SIZE':\r
-            self.parseSIZE(split[1:])\r
-        elif keyword == 'TYPE':\r
-            self.parseTYPE(split[1:])\r
-        elif keyword == 'COUNT':\r
-            self.parseCOUNT(split[1:])\r
-        elif keyword == 'WIDTH':\r
-            self.parseWIDTH(split[1:])\r
-        elif keyword == 'HEIGHT':\r
-            self.parseHEIGHT(split[1:])\r
-        elif keyword == 'POINTS':\r
-            self.parsePOINTS(split[1:])\r
-        elif keyword == 'DATA':\r
-            self.parseDATA(split[1:])\r
-        else:\r
-            super().parseHeaderLine(split)\r
-\r
-\r
-    def parseVERSION(self, split):\r
-        pass\r
-\r
-\r
-    def parseFIELDS(self, split):\r
-        print("SPLIT FIELDS:", split)\r
-        for field in split:\r
-            self.fields.append([field, None, None, None])\r
-        print("FIELDS, after parsing:", self.fields)\r
-\r
-\r
-    def parseSIZE(self, split):\r
-        for i, size in enumerate(split):\r
-            self.fields[i][1] = int(size)\r
-\r
-\r
-    def parseTYPE(self, split):\r
-        for i, type in enumerate(split):\r
-            self.fields[i][2] = type\r
-\r
-\r
-    def parseCOUNT(self, split):\r
-        for i, count in enumerate(split):\r
-            self.fields[i][3] = int(count)\r
-\r
-\r
-    def parseWIDTH(self, split):\r
-        self.width = int(split[0])\r
-\r
-\r
-    def parseHEIGHT(self, split):\r
-        self.height = int(split[0])\r
-\r
-\r
-    def parsePOINTS(self, split):\r
-        pass\r
-\r
-\r
-    def parseDATA(self, split):\r
-        if split[0] == "ascii":\r
-            self.datatype = 'ASCII'\r
-        elif split[0] == "binary":\r
-            self.datatype = 'BINARY'\r
-        elif split[0] == "binary_compressed":\r
-            self.datatype = 'BINARY_COMPRESSED'\r
-        self.headerEnd = True\r
-\r
-\r
-    def finalizeHeader(self):\r
-        self.numPoints = self.width * self.height\r
-        print("FIELDS - finalized", self.fields)\r
-\r
-\r
-    def parsePoints(self):\r
-        if self.datatype == 'ASCII':\r
-            self.parseASCII()\r
-        elif self.datatype == 'BINARY':\r
-            self.parseBINARY()\r
-        elif self.datatype == 'BINARY_COMPRESSED':\r
-            if not GOT_LZF_MODULE:\r
-                print("[ERROR] No support for BINARY COMPRESSED data format.")\r
-                return\r
-            else:\r
-                self.parseBINARY_COMPRESSED()\r
-\r
-\r
-    def parseASCII(self):\r
-        parsedPoints = 0\r
-        while parsedPoints < self.numPoints:\r
-           \r
-            try: \r
-                b = self.file.readline()\r
-                line = encodeASCIILine(b)\r
-            except:\r
-                self.parserError("Unexpected end of data")\r
-                return\r
-            line = self.rmComment(line)\r
-            split = line.split()\r
-\r
-            if (len(split) == 0):\r
-                continue\r
-            else:\r
-                parsedPoints += 1\r
-\r
-            point = self.PointClass()\r
-\r
-            for field in self.fields:\r
-                fieldname = field[0]\r
-                fieldtype = field[2]\r
-                fieldcount = field[3]\r
-\r
-                values = []\r
-                for i in range(fieldcount):\r
-                    vs = split.pop(0)\r
-                    if fieldtype == 'F':\r
-                        values.append(float(vs))\r
-                    elif fieldtype in ['U', 'I']:\r
-                        values.append(int(vs))\r
-\r
-                point.setField(fieldname, values)\r
-\r
-            self.points.append(point)\r
-\r
-\r
-    def parseBINARY_COMPRESSED(self):\r
-        """ BROKEN!!! - There seem to be uncompatiblities \r
-            with pcl LZF and liblzf"""\r
-        max_size = 1024**3 # 1GB \r
-        fs = '<i'\r
-        compressed_len = struct.unpack('<i', self.file.read(4))[0]\r
-        decompressed_len = struct.unpack('<i', self.file.read(4))[0]\r
-\r
-        compressed_body = self.file.read(compressed_len)\r
-        decompressed_body = lzf.decompress(compressed_body, max_size)\r
-\r
-        fobj = io.BytesIO(decompressed_body)\r
-        self.parseBINARY(fobj)\r
-\r
-\r
-\r
-    def parseBINARY(self, infile=""):\r
-        \r
-        if infile == "":\r
-            infile = self.file\r
-\r
-        for pointi in range(self.numPoints):\r
-            point = self.PointClass()\r
-\r
-            for field in self.fields:\r
-                fieldname = field[0]\r
-                fieldsize = field[1]\r
-                fieldtype = field[2]\r
-                fieldcount = field[3]\r
-\r
-                values = []\r
-                for i in range(fieldcount):\r
-\r
-                    fs = None\r
-                    if fieldtype == 'F':\r
-                        if fieldsize == 4: #float\r
-                            fs = '<f'\r
-                        elif fieldsize == 8: #double\r
-                            fs = '<d'\r
-                    elif fieldtype == 'U':\r
-                        if fieldsize == 1: #unsinged char\r
-                            fs = '<B'\r
-                        elif fieldsize == 2: #unsinged short\r
-                            fs = '<H'\r
-                        elif fieldsize == 4: #unsinged int\r
-                            fs =  '<I'\r
-                    elif fieldtype == 'I':\r
-                        if fieldsize == 1: #char\r
-                            fs = '<c'\r
-                        elif fieldsize == 2: #short\r
-                            fs = '<h'\r
-                        elif fieldsize == 4: #signed int\r
-                            fs =  '<i'\r
-\r
-                    raw = infile.read(fieldsize)\r
-                    if (fs):\r
-                        data = struct.unpack(fs, raw)\r
-                        values.append(data[0])\r
-\r
-                point.setField(fieldname, values)\r
-\r
-            self.points.append(point)\r
-\r
-\r
-\r
-\r
-class PCDWriter:\r
-\r
-    def __init__(self, points):\r
-        self.points = points\r
-\r
-\r
-    def _header(self):\r
-        header =  "# .PCD v0.7 - Point Cloud Data file format\n"\r
-        header += "VERSION 0.7\n"\r
-        header += "FIELDS x y z\n"\r
-        header += "SIZE 4 4 4\n"\r
-        header += "TYPE F F F\n"\r
-        header += "COUNT 1 1 1\n"\r
-        header += "WIDTH " + str(len(self.points)) + "\n"\r
-        header += "HEIGHT 1\n"\r
-        header += "VIEWPOINT 0 0 0 1 0 0 0\n"\r
-        header += "POINTS " + str(len(self.points)) + "\n"\r
-        header += "DATA ascii\n"\r
-\r
-        return header\r
-\r
-\r
-    def write(self, filepath):\r
-\r
-        with open(filepath, "w") as f:\r
-            f.write(self._header())\r
-            for point in self.points:\r
-                f.write(str(point.x))\r
-                f.write(" ")\r
-                f.write(str(point.y))\r
-                f.write(" ")\r
-                f.write(str(point.z))\r
-                f.write("\n")\r
-\r
-\r
-\r
-def test():\r
-    parser = PCDParser.factory('test.pcd', PointXYZ)\r
-    if parser:\r
-        parser.parseFile()\r
-        points = parser.getPoints()\r
-        for point in points:\r
-            print(point.x, point.y, point.z)\r
-    else:\r
-        print("Can't create parser for this file")\r
-\r
+# ##### 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 struct
+import io
+
+try:
+    import lzf
+    GOT_LZF_MODULE=True
+except:
+    GOT_LZF_MODULE=False
+
+
+
+def dumpHexData(data):
+    for byte in data:
+        print(hex(byte) + " ", end="")
+    print()
+
+
+def encodeASCIILine(line):
+    return line.decode(encoding='ASCII')
+
+
+
+class Point:
+
+    def __init__(self):
+        pass
+
+
+    def setField(self, fieldname, values):
+        pass
+
+
+
+
+class PointXYZ(Point):
+
+    def __init__(self):
+        super().__init__()
+        self.x = 0
+        self.y = 0
+        self.z = 0
+
+
+    def setField(self, fieldname, values):
+        value = values[0]
+        if fieldname == 'x':
+            self.x = value
+        elif fieldname == 'y':
+            self.y = value
+        elif fieldname == 'z':
+            self.z = value
+
+
+
+
+class PCDParser:
+
+    filepath = ''
+    file = None
+
+    points = []
+    PointClass = None
+
+    headerEnd = False
+
+
+    @staticmethod
+    def factory(filepath, PointClass):
+        version = 'NO_VERSION_NUMBER'
+        with open(filepath, 'rb') as f:
+            for b in f:
+                line = encodeASCIILine(b)
+                line_split = line.split()
+                if line_split[0] == 'VERSION' and len(line_split) > 1:
+                    version = line_split[1]
+                    break
+
+        if version == ".7" or version == "0.7":
+            return PCDParser_v0_7(filepath, PointClass)
+        else:
+            return None
+
+
+    def __init__(self, filepath, PointClass):
+        self.filepath = filepath
+        self.PointClass = PointClass
+
+        self.file = None
+        self.headerEnd = False
+        self.points = []
+
+
+    def parserWarning(self, msg):
+        print("[WARNING] ", msg)
+
+
+    def rmComment(self, line):
+        return line[:line.find('#')]
+
+
+    def parseFile(self):
+        with open(self.filepath, 'rb') as self.file:
+            self.parseHeader()
+            self.parsePoints()
+
+    def onlyParseHeader(self):
+        with open(self.filepath, 'rb') as self.file:
+            self.parseHeader()
+
+
+    def parseHeader(self):
+        for b in self.file:
+            line = encodeASCIILine(b)
+            line = self.rmComment(line)
+
+            split = line.split()
+            if len(split) > 0:
+                self.parseHeaderLine(split)
+
+            if self.headerEnd:
+                self.finalizeHeader()
+                break
+
+
+    def parseHeaderLine(self, split):
+        keyword = split[0]
+        self.parserWarning("Uknown header Keyword '" + keyword + "' gets ignored")
+
+
+    def finalizeHeader(self):
+        pass
+
+
+    def parsePoints(self):
+        pass
+
+
+    def getPoints(self):
+        return self.points
+
+
+    def version(self):
+        return 'NO_VERSION_NUMBER'
+
+
+
+
+class PCDParser_v0_7(PCDParser):
+
+    fields = []
+
+    def __init__(self, filepath, PointClass):
+        super().__init__(filepath, PointClass)
+        self.fields = []
+
+
+    def version(self):
+        return '.7'
+
+
+    def parseHeaderLine(self, split):
+        keyword = split[0]
+        if keyword == 'VERSION':
+            self.parseVERSION(split[1:])
+        elif keyword == 'FIELDS':
+            self.parseFIELDS(split[1:])
+        elif keyword == 'SIZE':
+            self.parseSIZE(split[1:])
+        elif keyword == 'TYPE':
+            self.parseTYPE(split[1:])
+        elif keyword == 'COUNT':
+            self.parseCOUNT(split[1:])
+        elif keyword == 'WIDTH':
+            self.parseWIDTH(split[1:])
+        elif keyword == 'HEIGHT':
+            self.parseHEIGHT(split[1:])
+        elif keyword == 'POINTS':