INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Creates a plane with a specified number of vertices on it sides but no vertices on the interior.
def plane_hires_edges(script, size=1.0, x_segments=1, y_segments=1, center=False, color=None): """ Creates a plane with a specified number of vertices on it sides, but no vertices on the interior. Currently used to create a simpler bottom for cube_hires. """ size = util.make_list(size, 2) grid(script, size=[x_segments + y_segments - 1, 1], x_segments=(x_segments + y_segments - 1), y_segments=1) if ml_script1.ml_version == '1.3.4BETA': and_val = 'and' else: and_val = '&&' if script.ml_version == '1.3.4BETA': # muparser version: 1.3.2 # Deform left side transform.vert_function( script, x_func='if((y>0) and (x<%s),0,x)' % (y_segments), y_func='if((y>0) and (x<%s),(x+1)*%s,y)' % ( y_segments, size[1] / y_segments)) # Deform top transform.vert_function( script, x_func='if((y>0) and (x>=%s),(x-%s+1)*%s,x)' % ( y_segments, y_segments, size[0] / x_segments), y_func='if((y>0) and (x>=%s),%s,y)' % (y_segments, size[1])) # Deform right side transform.vert_function( script, x_func='if((y<.00001) and (x>%s),%s,x)' % ( x_segments, size[0]), y_func='if((y<.00001) and (x>%s),(x-%s)*%s,y)' % ( x_segments, x_segments, size[1] / y_segments)) # Deform bottom transform.vert_function( script, x_func='if((y<.00001) and (x<=%s) and (x>0),(x)*%s,x)' % ( x_segments, size[0] / x_segments), y_func='if((y<.00001) and (x<=%s) and (x>0),0,y)' % (x_segments)) else: # muparser version: 2.2.5 # Deform left side transform.vert_function( script, x_func='((y>0) && (x<{yseg}) ? 0 : x)'.format(yseg=y_segments), y_func='((y>0) && (x<%s) ? (x+1)*%s : y)' % ( y_segments, size[1] / y_segments)) # Deform top transform.vert_function( script, x_func='((y>0) && (x>=%s) ? (x-%s+1)*%s : x)' % ( y_segments, y_segments, size[0] / x_segments), y_func='((y>0) && (x>=%s) ? %s : y)' % (y_segments, size[1])) # Deform right side transform.vert_function( script, x_func='((y<.00001) && (x>%s) ? %s : x)' % ( x_segments, size[0]), y_func='((y<.00001) && (x>%s) ? (x-%s)*%s : y)' % ( x_segments, x_segments, size[1] / y_segments)) # Deform bottom transform.vert_function( script, x_func='((y<.00001) && (x<=%s) && (x>0) ? (x)*%s : x)' % ( x_segments, size[0] / x_segments), y_func='((y<.00001) && (x<=%s) && (x>0) ? 0 : y)' % (x_segments)) if center: transform.translate(script, [-size[0] / 2, -size[1] / 2]) if color is not None: vert_color.function(script, color=color) return None
Create a box with user defined number of segments in each direction.
def cube_hires(script, size=1.0, x_segments=1, y_segments=1, z_segments=1, simple_bottom=True, center=False, color=None): """Create a box with user defined number of segments in each direction. Grid spacing is the same as its dimensions (spacing = 1) and its thickness is one. Intended to be used for e.g. deforming using functions or a height map (lithopanes) and can be resized after creation. Warnings: function uses layers.join top_option 0 open 1 full 2 simple bottom_option 0 open 1 full 2 simple """ """# Convert size to list if it isn't already if not isinstance(size, list): size = list(size) # If a single value was supplied use it for all 3 axes if len(size) == 1: size = [size[0], size[0], size[0]]""" size = util.make_list(size, 3) # Top grid(script, size, x_segments, y_segments) transform.translate(script, [0, 0, size[2]]) # Bottom if simple_bottom: plane_hires_edges( script, size, x_segments, y_segments) else: layers.duplicate(script) transform.translate(script, [0, 0, -size[2]]) # Rotate to correct normals transform.rotate(script, 'x', 180) transform.translate(script, [0, size[1], 0]) # Sides cube_open_hires( script=script, size=size, x_segments=x_segments, y_segments=y_segments, z_segments=z_segments) # Join everything together layers.join(script) # Need some tolerance on merge_vert due to rounding errors clean.merge_vert(script, threshold=0.00002) if center: transform.translate(script, [-size[0] / 2, -size[1] / 2, -size[2] / 2]) if color is not None: vert_color.function(script, color=color) return None
Create a cylinder with user defined number of segments
def annulus_hires(script, radius=None, radius1=None, radius2=None, diameter=None, diameter1=None, diameter2=None, cir_segments=48, rad_segments=1, color=None): """Create a cylinder with user defined number of segments """ if radius is not None and diameter is None: if radius1 is None and diameter1 is None: radius1 = radius if radius2 is None and diameter2 is None: radius2 = 0 if diameter is not None: if radius1 is None and diameter1 is None: radius1 = diameter / 2 if radius2 is None and diameter2 is None: radius2 = 0 if diameter1 is not None: radius1 = diameter1 / 2 if diameter2 is not None: radius2 = diameter2 / 2 if radius1 is None: radius1 = 1 if radius2 is None: radius2 = 0 ring = (radius1 - radius2) / rad_segments for i in range(0, rad_segments): annulus(script, radius1=radius1 - i * ring, radius2=radius1 - (i + 1) * ring, cir_segments=cir_segments) layers.join(script, merge_vert=True) if color is not None: vert_color.function(script, color=color) return None
Create a cylinder with user defined number of segments
def tube_hires(script, height=1.0, radius=None, radius1=None, radius2=None, diameter=None, diameter1=None, diameter2=None, cir_segments=32, rad_segments=1, height_segments=1, center=False, simple_bottom=False, color=None): """Create a cylinder with user defined number of segments """ # TODO: add option to round the top of the cylinder, i.e. deform spherically # TODO: add warnings if values are ignored, e.g. if you specify both radius # and diameter. if radius is not None and diameter is None: if radius1 is None and diameter1 is None: radius1 = radius if radius2 is None and diameter2 is None: radius2 = 0 if diameter is not None: if radius1 is None and diameter1 is None: radius1 = diameter / 2 if radius2 is None and diameter2 is None: radius2 = 0 if diameter1 is not None: radius1 = diameter1 / 2 if diameter2 is not None: radius2 = diameter2 / 2 if radius1 is None: radius1 = 1 if radius2 is None: radius2 = 0 # Create top annulus_hires(script, radius1=radius1, radius2=radius2, cir_segments=cir_segments, rad_segments=rad_segments) transform.translate(script, [0, 0, height]) # Create bottom if simple_bottom: annulus(script, radius1=radius1, radius2=radius2, cir_segments=cir_segments) else: layers.duplicate(script) transform.translate(script, [0, 0, -height]) # Rotate to correct normals transform.rotate(script, 'x', 180) # Create outer tube cylinder_open_hires(script, height, radius1, cir_segments=cir_segments, height_segments=height_segments) # Create inner tube if radius2 != 0: cylinder_open_hires(script, height, radius2, cir_segments=cir_segments, height_segments=height_segments, invert_normals=True) # Join everything together layers.join(script) # Need some tolerance on merge_vert due to rounding errors clean.merge_vert(script, threshold=0.00002) if center: transform.translate(script, [0, 0, -height / 2]) if color is not None: vert_color.function(script, color=color) return None
Read color_names. txt and find the red green and blue values for a named color.
def color_values(color): """Read color_names.txt and find the red, green, and blue values for a named color. """ # Get the directory where this script file is located: this_dir = os.path.dirname( os.path.realpath( inspect.getsourcefile( lambda: 0))) color_name_file = os.path.join(this_dir, 'color_names.txt') found = False for line in open(color_name_file, 'r'): line = line.rstrip() if color.lower() == line.split()[0]: #hex_color = line.split()[1] red = line.split()[2] green = line.split()[3] blue = line.split()[4] found = True break if not found: print('Color name "%s" not found, using default (white)' % color) red = 255 green = 255 blue = 255 return red, green, blue
Check if a variable is a list and is the correct length.
def check_list(var, num_terms): """ Check if a variable is a list and is the correct length. If variable is not a list it will make it a list of the correct length with all terms identical. """ if not isinstance(var, list): if isinstance(var, tuple): var = list(var) else: var = [var] for _ in range(1, num_terms): var.append(var[0]) if len(var) != num_terms: print( '"%s" has the wrong number of terms; it needs %s. Exiting ...' % (var, num_terms)) sys.exit(1) return var
Make a variable a list if it is not already
def make_list(var, num_terms=1): """ Make a variable a list if it is not already If variable is not a list it will make it a list of the correct length with all terms identical. """ if not isinstance(var, list): if isinstance(var, tuple): var = list(var) else: var = [var] #if len(var) == 1: for _ in range(1, num_terms): var.append(var[0]) return var
Write filter to FilterScript object or filename
def write_filter(script, filter_xml): """ Write filter to FilterScript object or filename Args: script (FilterScript object or filename str): the FilterScript object or script filename to write the filter to. filter_xml (str): the xml filter string """ if isinstance(script, mlx.FilterScript): script.filters.append(filter_xml) elif isinstance(script, str): script_file = open(script, 'a') script_file.write(filter_xml) script_file.close() else: print(filter_xml) return None
Apply LS3 Subdivision Surface algorithm using Loop s weights.
def ls3loop(script, iterations=1, loop_weight=0, edge_threshold=0, selected=False): """ Apply LS3 Subdivision Surface algorithm using Loop's weights. This refinement method take normals into account. See: Boye', S. Guennebaud, G. & Schlick, C. "Least squares subdivision surfaces" Computer Graphics Forum, 2010. Alternatives weighting schemes are based on the paper: Barthe, L. & Kobbelt, L. "Subdivision scheme tuning around extraordinary vertices" Computer Aided Geometric Design, 2004, 21, 561-583. The current implementation of these schemes don't handle vertices of valence > 12 Args: script: the FilterScript object or script filename to write the filter to. iterations (int): Number of times the model is subdivided. loop_weight (int): Change the weights used. Allow to optimize some behaviours in spite of others. Valid values are: 0 - Loop (default) 1 - Enhance regularity 2 - Enhance continuity edge_threshold (float): All the edges longer than this threshold will be refined. Setting this value to zero will force a uniform refinement. selected (bool): If selected the filter is performed only on the selected faces. Layer stack: No impacts MeshLab versions: 2016.12 1.3.4BETA """ filter_xml = ''.join([ ' <filter name="Subdivision Surfaces: LS3 Loop">\n', ' <Param name="LoopWeight" ', 'value="{:d}" '.format(loop_weight), 'description="Weighting scheme" ', 'enum_val0="Loop" ', 'enum_val1="Enhance regularity" ', 'enum_val2="Enhance continuity" ', 'enum_cardinality="3" ', 'type="RichEnum" ', '/>\n', ' <Param name="Iterations" ', 'value="{:d}" '.format(iterations), 'description="Iterations" ', 'type="RichInt" ', '/>\n', ' <Param name="Threshold" ', 'value="{}" '.format(edge_threshold), 'description="Edge Threshold" ', 'min="0" ', 'max="100" ', 'type="RichAbsPerc" ', '/>\n', ' <Param name="Selected" ', 'value="{}" '.format(str(selected).lower()), 'description="Affect only selected faces" ', 'type="RichBool" ', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
Merge together all the vertices that are nearer than the specified threshold. Like a unify duplicate vertices but with some tolerance.
def merge_vert(script, threshold=0.0): """ Merge together all the vertices that are nearer than the specified threshold. Like a unify duplicate vertices but with some tolerance. Args: script: the FilterScript object or script filename to write the filter to. threshold (float): Merging distance. All the vertices that are closer than this threshold are merged together. Use very small values, default is zero. Layer stack: No impacts MeshLab versions: 2016.12 1.3.4BETA """ filter_xml = ''.join([ ' <filter name="Merge Close Vertices">\n', ' <Param name="Threshold" ', 'value="{}" '.format(threshold), 'description="Merging distance" ', 'min="0" ', 'max="1" ', 'type="RichAbsPerc" ', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
Close holes smaller than a given threshold
def close_holes(script, hole_max_edge=30, selected=False, sel_new_face=True, self_intersection=True): """ Close holes smaller than a given threshold Args: script: the FilterScript object or script filename to write the filter to. hole_max_edge (int): The size is expressed as number of edges composing the hole boundary. selected (bool): Only the holes with at least one of the boundary faces selected are closed. sel_new_face (bool): After closing a hole the faces that have been created are left selected. Any previous selection is lost. Useful for example for smoothing or subdividing the newly created holes. self_intersection (bool): When closing an holes it tries to prevent the creation of faces that intersect faces adjacent to the boundary of the hole. It is an heuristic, non intersecting hole filling can be NP-complete. Layer stack: No impacts MeshLab versions: 2016.12 1.3.4BETA """ filter_xml = ''.join([ ' <filter name="Close Holes">\n', ' <Param name="maxholesize" ', 'value="{:d}" '.format(hole_max_edge), 'description="Max size to be closed" ', 'type="RichInt" ', '/>\n', ' <Param name="Selected" ', 'value="{}" '.format(str(selected).lower()), 'description="Close holes with selected faces" ', 'type="RichBool" ', '/>\n', ' <Param name="NewFaceSelected" ', 'value="{}" '.format(str(sel_new_face).lower()), 'description="Select the newly created faces" ', 'type="RichBool" ', '/>\n', ' <Param name="SelfIntersection" ', 'value="{}" '.format(str(self_intersection).lower()), 'description="Prevent creation of selfIntersecting faces" ', 'type="RichBool" ', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
Split non - manifold vertices until it becomes two - manifold.
def split_vert_on_nonmanifold_face(script, vert_displacement_ratio=0.0): """ Split non-manifold vertices until it becomes two-manifold. Args: script: the FilterScript object or script filename to write the filter to. vert_displacement_ratio (float): When a vertex is split it is moved along the average vector going from its position to the centroid of the FF connected faces sharing it. Layer stack: No impacts MeshLab versions: 2016.12 1.3.4BETA """ filter_xml = ''.join([ ' <filter name="Split Vertexes Incident on Non Manifold Faces">\n', ' <Param name="VertDispRatio" ', 'value="{}" '.format(vert_displacement_ratio), 'description="Vertex Displacement Ratio" ', 'type="RichFloat" ', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
Try to snap together adjacent borders that are slightly mismatched.
def snap_mismatched_borders(script, edge_dist_ratio=0.01, unify_vert=True): """ Try to snap together adjacent borders that are slightly mismatched. This situation can happen on badly triangulated adjacent patches defined by high order surfaces. For each border vertex the filter snaps it onto the closest boundary edge only if it is closest of edge_legth*threshold. When vertex is snapped the corresponding face it split and a new vertex is created. Args: script: the FilterScript object or script filename to write the filter to. edge_dist_ratio (float): Collapse edge when the edge / distance ratio is greater than this value. E.g. for default value 1000 two straight border edges are collapsed if the central vertex dist from the straight line composed by the two edges less than a 1/1000 of the sum of the edges length. Larger values enforce that only vertexes very close to the line are removed. unify_vert (bool): If true the snap vertices are welded together. Layer stack: No impacts MeshLab versions: 2016.12 1.3.4BETA """ filter_xml = ''.join([ ' <filter name="Snap Mismatched Borders">\n', ' <Param name="EdgeDistRatio" ', 'value="{}" '.format(edge_dist_ratio), 'description="Edge Distance Ratio" ', 'type="RichFloat" ', '/>\n', ' <Param name="UnifyVertices" ', 'value="{}" '.format(str(unify_vert).lower()), 'description="UnifyVertices" ', 'type="RichBool" ', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
An alternative translate implementation that uses a geometric function. This is more accurate than the built - in version.
def translate(script, value=(0.0, 0.0, 0.0)): """An alternative translate implementation that uses a geometric function. This is more accurate than the built-in version.""" # Convert value to list if it isn't already if not isinstance(value, list): value = list(value) vert_function(script, x_func='x+(%s)' % value[0], y_func='y+(%s)' % value[1], z_func='z+(%s)' % value[2]) return None
An alternative rotate implementation that uses a geometric function. This is more accurate than the built - in version.
def rotate(script, axis='z', angle=0.0): """An alternative rotate implementation that uses a geometric function. This is more accurate than the built-in version.""" angle = math.radians(angle) if axis.lower() == 'x': vert_function(script, x_func='x', y_func='y*cos({angle})-z*sin({angle})'.format(angle=angle), z_func='y*sin({angle})+z*cos({angle})'.format(angle=angle)) elif axis.lower() == 'y': vert_function(script, x_func='z*sin({angle})+x*cos({angle})'.format(angle=angle), y_func='y', z_func='z*cos({angle})-x*sin({angle})'.format(angle=angle)) elif axis.lower() == 'z': vert_function(script, x_func='x*cos({angle})-y*sin({angle})'.format(angle=angle), y_func='x*sin({angle})+y*cos({angle})'.format(angle=angle), z_func='z') else: print('Axis name is not valid; exiting ...') sys.exit(1) return None
An alternative scale implementation that uses a geometric function. This is more accurate than the built - in version.
def scale(script, value=1.0): """An alternative scale implementation that uses a geometric function. This is more accurate than the built-in version.""" """# Convert value to list if it isn't already if not isinstance(value, list): value = list(value) # If a single value was supplied use it for all 3 axes if len(value) == 1: value = [value[0], value[0], value[0]]""" value = util.make_list(value, 3) vert_function(script, x_func='x*(%s)' % value[0], y_func='y*(%s)' % value[1], z_func='z*(%s)' % value[2]) return None
Freeze the current transformation matrix into the coordinates of the vertices of the mesh ( and set this matrix to the identity ).
def freeze_matrix(script, all_layers=False): """ Freeze the current transformation matrix into the coordinates of the vertices of the mesh (and set this matrix to the identity). In other words it applies in a definitive way the current matrix to the vertex coordinates. Args: script: the FilterScript object or script filename to write the filter to. all_layers (bool): If selected the filter will be applied to all visible mesh layers. """ filter_xml = ''.join([ ' <filter name="Freeze Current Matrix">\n', ' <Param name="allLayers" ', 'value="%s" ' % str(all_layers).lower(), 'description="Apply to all visible Layers" ', 'type="RichBool" ', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
Geometric function using muparser lib to generate new Coordinates
def function(script, x_func='x', y_func='y', z_func='z'): """Geometric function using muparser lib to generate new Coordinates You can change x, y, z for every vertex according to the function specified. See help(mlx.muparser_ref) for muparser reference documentation. It's possible to use the following per-vertex variables in the expression: Variables (per vertex): x, y, z (coordinates) nx, ny, nz (normal) r, g, b, a (color) q (quality) rad (radius) vi (vertex index) vtu, vtv (texture coordinates) ti (texture index) vsel (is the vertex selected? 1 yes, 0 no) and all custom vertex attributes already defined by user. Args: x_func (str): function to generate new coordinates for x y_func (str): function to generate new coordinates for y z_func (str): function to generate new coordinates for z Layer stack: No impacts MeshLab versions: 1.3.4BETA """ filter_xml = ''.join([ ' <filter name="Geometric Function">\n', ' <Param name="x" ', 'value="{}" '.format(str(x_func).replace('&', '&amp;').replace('<', '&lt;')), 'description="func x = " ', 'type="RichString" ', '/>\n', ' <Param name="y" ', 'value="{}" '.format(str(y_func).replace('&', '&amp;').replace('<', '&lt;')), 'description="func y = " ', 'type="RichString" ', '/>\n', ' <Param name="z" ', 'value="{}" '.format(str(z_func).replace('&', '&amp;').replace('<', '&lt;')), 'description="func z = " ', 'type="RichString" ', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
Geometric function using muparser lib to generate new Coordinates
def vert_function(script, x_func='x', y_func='y', z_func='z', selected=False): """Geometric function using muparser lib to generate new Coordinates You can change x, y, z for every vertex according to the function specified. See help(mlx.muparser_ref) for muparser reference documentation. It's possible to use the following per-vertex variables in the expression: Variables (per vertex): x, y, z (coordinates) nx, ny, nz (normal) r, g, b, a (color) q (quality) rad (radius) vi (vertex index) vtu, vtv (texture coordinates) ti (texture index) vsel (is the vertex selected? 1 yes, 0 no) and all custom vertex attributes already defined by user. Args: x_func (str): function to generate new coordinates for x y_func (str): function to generate new coordinates for y z_func (str): function to generate new coordinates for z selected (bool): if True, only affects selected vertices (ML ver 2016.12 & up) Layer stack: No impacts MeshLab versions: 2016.12 1.3.4BETA """ if script.ml_version == '1.3.4BETA': filter_xml = ''.join([ ' <filter name="Geometric Function">\n', ' <Param name="x" ', 'value="{}" '.format(str(x_func).replace('&', '&amp;').replace('<', '&lt;')), 'description="func x = " ', 'type="RichString" ', '/>\n', ' <Param name="y" ', 'value="{}" '.format(str(y_func).replace('&', '&amp;').replace('<', '&lt;')), 'description="func y = " ', 'type="RichString" ', '/>\n', ' <Param name="z" ', 'value="{}" '.format(str(z_func).replace('&', '&amp;').replace('<', '&lt;')), 'description="func z = " ', 'type="RichString" ', '/>\n', ' </filter>\n']) else: filter_xml = ''.join([ ' <filter name="Per Vertex Geometric Function">\n', ' <Param name="x" ', 'value="{}" '.format(str(x_func).replace('&', '&amp;').replace('<', '&lt;')), 'description="func x = " ', 'type="RichString" ', '/>\n', ' <Param name="y" ', 'value="{}" '.format(str(y_func).replace('&', '&amp;').replace('<', '&lt;')), 'description="func y = " ', 'type="RichString" ', '/>\n', ' <Param name="z" ', 'value="{}" '.format(str(z_func).replace('&', '&amp;').replace('<', '&lt;')), 'description="func z = " ', 'type="RichString" ', '/>\n', ' <Param name="onselected" ', 'value="%s" ' % str(selected).lower(), 'description="only on selection" ', 'type="RichBool" ', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
Geometric function using cylindrical coordinates.
def function_cyl_co(script, r_func='r', theta_func='theta', z_func='z'): """Geometric function using cylindrical coordinates. Define functions in Z up cylindrical coordinates, with radius 'r', angle 'theta', and height 'z' See "function" docs for additional usage info and accepted parameters. Args: r_func (str): function to generate new coordinates for radius theta_func (str): function to generate new coordinates for angle. 0 degrees is on the +X axis. z_func (str): function to generate new coordinates for height Layer stack: No impacts MeshLab versions: 2016.12 1.3.4BETA """ r = 'sqrt(x^2+y^2)' # In newer MeshLab atan2 is builtin to muparser if isinstance(script, FilterScript) and script.ml_version >= '2016.12': theta = 'atan2(y, x)' else: theta = mp_func.mp_atan2('y', 'x') # Use re matching to match whole word; this prevents matching # 'sqrt' and 'rint' when replacing 'r' r_func = re.sub(r"\br\b", r, r_func).replace('theta', theta) theta_func = re.sub(r"\br\b", r, theta_func).replace('theta', theta) z_func = re.sub(r"\br\b", r, z_func).replace('theta', theta) x_func = '(r)*cos(theta)'.replace('r', r_func).replace('theta', theta_func) y_func = '(r)*sin(theta)'.replace('r', r_func).replace('theta', theta_func) vert_function(script, x_func, y_func, z_func) return None
flare_radius must be > = end_height ( height ) end_radius max = flare_radius + r end_radius ( num ): radius of mesh at end of flare + 15 r = 8. 8205 - 15 r = 1. 1795 z = 10 5 +/ - 15 - +/ - 15 * 0. 74535599249992989880305788957709
def radial_flare2(script, flare_radius=None, start_radius=None, end_radius=None, end_height=None): """ flare_radius must be >= end_height (height) end_radius max = flare_radius + r end_radius (num): radius of mesh at end of flare +15 r= 8.8205 -15 r= 1.1795 z=10, 5 +/-15 - +/-15*0.74535599249992989880305788957709 """ # TODO: set radius limit, make it so flare continues to expand linearly after radius limit # if(r<=radius_limit, flare, factor*z+constant # TODO: add option to specify radius at height instead of radius if (end_radius is not None) and (end_height is not None): # this is only correct if r is constant # start_radius here is really r at end_height #flare_radius = '-((start_radius-end_radius)^2 + end_height^2)/(2*(start_radius-end_radius))' if (end_radius - start_radius) < end_height: flare_radius = -((start_radius-end_radius)**2 + end_height**2)/(2*(start_radius-end_radius)) #print('flare_radius = %s' % flare_radius) else: print('Error, end_radius is too large for end_height; angle is > 90d') r_func = 'if(z>0, (r) + (flare_radius) - (flare_radius)*sqrt(1-z^2/(flare_radius)^2), (r))'.replace('flare_radius', str(flare_radius)) #r_func = 'if(z>0, (r) + (flare_radius) - (flare_radius)*sqrt(1-z^2/(flare_radius)^2), (r))'.replace('flare_radius', str(flare_radius)).replace('start_radius', str(start_radius)).replace('end_radius', str(end_radius)).replace('end_height', str(end_height)) function_cyl_co(script, r_func) return None
flare_radius must be > = z2 ( height ) r2 max = flare_radius + r r2 ( num ): radius of mesh at end of flare + 15 r = 8. 8205 - 15 r = 1. 1795 z = 10 5 +/ - 15 - +/ - 15 * 0. 74535599249992989880305788957709
def radial_flare(script, flare_radius=None, start_radius=None, end_radius=None, end_height=None): """ flare_radius must be >= z2 (height) r2 max = flare_radius + r r2 (num): radius of mesh at end of flare +15 r= 8.8205 -15 r= 1.1795 z=10, 5 +/-15 - +/-15*0.74535599249992989880305788957709 """ # TODO: set radius limit, make it so flare continues to expand linearly after radius limit # if(r<=radius_limit, flare, factor*z+constant # TODO: add option to specify radius at height instead of radius effective_radius = '(flare_radius) + (start_radius) - (r)' r_func = 'if(z>0, (flare_radius) + (start_radius) - (effective_radius)*cos(z/(flare_radius)), (r))' z_func = 'if(z>0, (effective_radius)*sin(z/(flare_radius)), z)' r_func = r_func.replace('effective_radius', str(effective_radius)).replace('start_radius', str(start_radius)).replace('flare_radius', str(flare_radius)) z_func = z_func.replace('effective_radius', str(effective_radius)).replace('start_radius', str(start_radius)).replace('flare_radius', str(flare_radius)) function_cyl_co(script=script, r_func=r_func, z_func=z_func) return None
flare_radius must be > = z2 ( height ) r2 max = flare_radius + r r2 ( num ): radius of mesh at end of flare + 15 r = 8. 8205 - 15 r = 1. 1795 z = 10 5 +/ - 15 - +/ - 15 * 0. 74535599249992989880305788957709
def curl_rim(script, curl_radius=None, start_radius=None, end_radius=None, end_height=None): """ flare_radius must be >= z2 (height) r2 max = flare_radius + r r2 (num): radius of mesh at end of flare +15 r= 8.8205 -15 r= 1.1795 z=10, 5 +/-15 - +/-15*0.74535599249992989880305788957709 """ # TODO: set radius limit, make it so flare continues to expand linearly after radius limit # if(r<=radius_limit, flare, factor*z+constant # TODO: add option to specify radius at height instead of radius effective_radius = '(curl_radius) - z' r_func = 'if((r)>(start_radius), (start_radius) + (effective_radius)*sin(((r)-(start_radius))/(curl_radius)), (r))' z_func = 'if((r)>(start_radius), (curl_radius) - (effective_radius)*cos(((r)-(start_radius))/(curl_radius)), z)' r_func = r_func.replace('effective_radius', str(effective_radius)).replace('start_radius', str(start_radius)).replace('curl_radius', str(curl_radius)) z_func = z_func.replace('effective_radius', str(effective_radius)).replace('start_radius', str(start_radius)).replace('curl_radius', str(curl_radius)) function_cyl_co(script=script, r_func=r_func, z_func=z_func) return None
Deform mesh around cylinder of radius and axis z
def wrap2cylinder(script, radius=1, pitch=0, taper=0, pitch_func=None, taper_func=None): """Deform mesh around cylinder of radius and axis z y = 0 will be on the surface of radius "radius" pitch != 0 will create a helix, with distance "pitch" traveled in z for each rotation taper = change in r over z. E.g. a value of 0.5 will shrink r by 0.5 for every z length of 1 """ """vert_function(s=s, x='(%s+y-taper)*sin(x/(%s+y))' % (radius, radius), y='(%s+y)*cos(x/(%s+y))' % (radius, radius), z='z-%s*x/(2*%s*(%s+y))' % (pitch, pi, radius))""" if pitch_func is None: pitch_func = '-(pitch)*x/(2*pi*(radius))' pitch_func = pitch_func.replace( 'pitch', str(pitch)).replace( 'pi', str(math.pi)).replace( 'radius', str(radius)) if taper_func is None: taper_func = '-(taper)*(pitch_func)' taper_func = taper_func.replace( 'taper', str(taper)).replace( 'pitch_func', str(pitch_func)).replace( 'pi', str(math.pi)) x_func = '(y+(radius)+(taper_func))*sin(x/(radius))'.replace( 'radius', str(radius)).replace('taper_func', str(taper_func)) y_func = '(y+(radius)+(taper_func))*cos(x/(radius))'.replace( 'radius', str(radius)).replace('taper_func', str(taper_func)) z_func = 'z+(pitch_func)'.replace('pitch_func', str(pitch_func)) vert_function(script, x_func, y_func, z_func) return None
Bends mesh around cylinder of radius radius and axis z to a certain angle
def bend(script, radius=1, pitch=0, taper=0, angle=0, straght_start=True, straght_end=False, radius_limit=None, outside_limit_end=True): """Bends mesh around cylinder of radius radius and axis z to a certain angle straight_ends: Only apply twist (pitch) over the area that is bent outside_limit_end (bool): should values outside of the bend radius_limit be considered part of the end (True) or the start (False)? """ if radius_limit is None: radius_limit = 2 * radius # TODO: add limit so bend only applies over y<2*radius; add option to set # larger limit angle = math.radians(angle) segment = radius * angle """vert_function(s=s, x='if(x<%s and x>-%s, (%s+y)*sin(x/%s), (%s+y)*sin(%s/%s)+(x-%s)*cos(%s/%s))' % (segment, segment, radius, radius, radius, segment, radius, segment, segment, radius), y='if(x<%s*%s/2 and x>-%s*%s/2, (%s+y)*cos(x/%s), (%s+y)*cos(%s)-(x-%s*%s)*sin(%s))' % (radius, angle, radius, angle, radius, radius, radius, angle/2, radius, angle/2, angle/2),""" pitch_func = '-(pitch)*x/(2*pi*(radius))'.replace( 'pitch', str(pitch)).replace( 'pi', str(math.pi)).replace( 'radius', str(radius)) taper_func = '(taper)*(pitch_func)'.replace( 'taper', str(taper)).replace( 'pitch_func', str(pitch_func)).replace( 'pi', str(math.pi)) # y<radius_limit if outside_limit_end: x_func = 'if(x<(segment) and y<(radius_limit), if(x>0, (y+(radius)+(taper_func))*sin(x/(radius)), x), (y+(radius)+(taper_func))*sin(angle)+(x-(segment))*cos(angle))' else: x_func = 'if(x<(segment), if(x>0 and y<(radius_limit), (y+(radius)+(taper_func))*sin(x/(radius)), x), if(y<(radius_limit), (y+(radius)+(taper_func))*sin(angle)+(x-(segment))*cos(angle), x))' x_func = x_func.replace( # x_func = 'if(x<segment, if(x>0, (y+radius)*sin(x/radius), x), # (y+radius)*sin(angle)-segment)'.replace( 'segment', str(segment)).replace( 'radius_limit', str(radius_limit)).replace( 'radius', str(radius)).replace( 'taper_func', str(taper_func)).replace( 'angle', str(angle)) if outside_limit_end: y_func = 'if(x<(segment) and y<(radius_limit), if(x>0, (y+(radius)+(taper_func))*cos(x/(radius))-(radius), y), (y+(radius)+(taper_func))*cos(angle)-(x-(segment))*sin(angle)-(radius))' else: y_func = 'if(x<(segment), if(x>0 and y<(radius_limit), (y+(radius)+(taper_func))*cos(x/(radius))-(radius), y), if(y<(radius_limit), (y+(radius)+(taper_func))*cos(angle)-(x-(segment))*sin(angle)-(radius), y))' y_func = y_func.replace( 'segment', str(segment)).replace( 'radius_limit', str(radius_limit)).replace( 'radius', str(radius)).replace( 'taper_func', str(taper_func)).replace( 'angle', str(angle)) if straght_start: start = 'z' else: start = 'z+(pitch_func)' if straght_end: end = 'z-(pitch)*(angle)/(2*pi)' else: end = 'z+(pitch_func)' if outside_limit_end: z_func = 'if(x<(segment) and y<(radius_limit), if(x>0, z+(pitch_func), (start)), (end))' else: z_func = 'if(x<(segment), if(x>0 and y<(radius_limit), z+(pitch_func), (start)), if(y<(radius_limit), (end), z))' z_func = z_func.replace( 'start', str(start)).replace( 'end', str(end)).replace( 'segment', str(segment)).replace( 'radius_limit', str(radius_limit)).replace( 'radius', str(radius)).replace( 'angle', str(angle)).replace( 'pitch_func', str(pitch_func)).replace( 'pitch', str(pitch)).replace( 'pi', str(math.pi)) """ if straight_ends: z_func = 'if(x<segment, if(x>0, z+(pitch_func), z), z-pitch*angle/(2*pi))'.replace( 'segment', str(segment)).replace( 'radius', str(radius)).replace( 'angle', str(angle)).replace( 'pitch_func', str(pitch_func)).replace( 'pitch', str(pitch)).replace( 'pi', str(math.pi)) else: #z_func = 'if(x<segment, z+(pitch_func), z-(taper)*(pitch)*(x)/(2*pi*(radius)))'.replace( #z_func = 'if(x<segment, z+(pitch_func), z+(pitch_func))'.replace( #bestz_func = 'if(x<segment, z+(pitch_func), z+(pitch_func)+(-(taper)*(pitch)*(x-segment)/(2*pi*(radius))))'.replace( #z_func = 'if(x<segment, z+(pitch_func), z+(pitch_func)+(-(taper)*(pitch)*x/(2*pi*(radius))))'.replace( #z_func = 'if(x<segment, z+(pitch_func), z+(pitch_func)+((taper)*pitch*angle/(2*pi)))'.replace( z_func = 'z+(pitch_func)'.replace( 'radius', str(radius)).replace( 'segment', str(segment)).replace( 'angle', str(angle)).replace( 'taper', str(taper)).replace( 'pitch_func', str(pitch_func)).replace( 'pitch', str(pitch)).replace( 'pi', str(math.pi)) """ """ x_func = 'if(x<%s, if(x>-%s, (%s+y)*sin(x/%s), (%s+y)*sin(-%s)+(x+%s)*cos(-%s)), (%s+y)*sin(%s)+(x-%s)*cos(%s))' % ( segment, segment, radius, radius, radius, angle, segment, angle, radius, angle, segment, angle) y_func = 'if(x<%s, if(x>-%s, (%s+y)*cos(x/%s), (%s+y)*cos(-%s)-(x+%s)*sin(-%s)), (%s+y)*cos(%s)-(x-%s)*sin(%s))' % ( segment, segment, radius, radius, radius, angle, segment, angle, radius, angle, segment, angle) if straight_ends: z_func = 'if(x<%s, if(x>-%s, z-%s*x/(2*%s*%s), z+%s*%s/(2*%s)), z-%s*%s/(2*%s))' % ( segment, segment, pitch, math.pi, radius, pitch, angle, math.pi, pitch, angle, math.pi) else: z_func = 'z-%s*x/(2*%s*%s)' % (pitch, math.pi, radius) """ vert_function(script, x_func=x_func, y_func=y_func, z_func=z_func) return None
Deform a mesh along a parametric curve function
def deform2curve(script, curve=mp_func.torus_knot('t'), step=0.001): """ Deform a mesh along a parametric curve function Provide a parametric curve function with z as the parameter. This will deform the xy cross section of the mesh along the curve as z increases. Source: http://blackpawn.com/texts/pqtorus/ Methodology: T = P' - P N1 = P' + P B = T x N1 N = B x T newPoint = point.x*N + point.y*B """ curve_step = [] for idx, val in enumerate(curve): curve[idx] = val.replace('t', 'z') curve_step.append(val.replace('t', 'z+{}'.format(step))) tangent = mp_func.v_subtract(curve_step, curve) normal1 = mp_func.v_add(curve_step, curve) bee = mp_func.v_cross(tangent, normal1) normal = mp_func.v_cross(bee, tangent) bee = mp_func.v_normalize(bee) normal = mp_func.v_normalize(normal) new_point = mp_func.v_add(mp_func.v_multiply('x', normal), mp_func.v_multiply('y', bee)) function = mp_func.v_add(curve, new_point) vert_function(script, x_func=function[0], y_func=function[1], z_func=function[2]) return function
Transfer vertex colors to texture colors
def vc2tex(script, tex_name='TEMP3D_texture.png', tex_width=1024, tex_height=1024, overwrite_tex=False, assign_tex=False, fill_tex=True): """Transfer vertex colors to texture colors Args: script: the FilterScript object or script filename to write the filter to. tex_name (str): The texture file to be created tex_width (int): The texture width tex_height (int): The texture height overwrite_tex (bool): If current mesh has a texture will be overwritten (with provided texture dimension) assign_tex (bool): Assign the newly created texture fill_tex (bool): If enabled the unmapped texture space is colored using a pull push filling algorithm, if false is set to black """ filter_xml = ''.join([ ' <filter name="Vertex Color to Texture">\n', ' <Param name="textName" ', 'value="%s" ' % tex_name, 'description="Texture file" ', 'type="RichString" ', '/>\n', ' <Param name="textW" ', 'value="%d" ' % tex_width, 'description="Texture width (px)" ', 'type="RichInt" ', '/>\n', ' <Param name="textH" ', 'value="%d" ' % tex_height, 'description="Texture height (px)" ', 'type="RichInt" ', '/>\n', ' <Param name="overwrite" ', 'value="%s" ' % str(overwrite_tex).lower(), 'description="Overwrite texture" ', 'type="RichBool" ', '/>\n', ' <Param name="assign" ', 'value="%s" ' % str(assign_tex).lower(), 'description="Assign Texture" ', 'type="RichBool" ', '/>\n', ' <Param name="pullpush" ', 'value="%s" ' % str(fill_tex).lower(), 'description="Fill texture" ', 'type="RichBool" ', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
Transfer mesh colors to face colors
def mesh2fc(script, all_visible_layers=False): """Transfer mesh colors to face colors Args: script: the FilterScript object or script filename to write the filter to. all_visible_layers (bool): If true the color mapping is applied to all the meshes """ filter_xml = ''.join([ ' <filter name="Transfer Color: Mesh to Face">\n', ' <Param name="allVisibleMesh" ', 'value="%s" ' % str(all_visible_layers).lower(), 'description="Apply to all Meshes" ', 'type="RichBool" ', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
Vertex Attribute Transfer ( between 2 meshes )
def vert_attr_2_meshes(script, source_mesh=0, target_mesh=1, geometry=False, normal=False, color=True, quality=False, selection=False, quality_distance=False, max_distance=0.5): """Vertex Attribute Transfer (between 2 meshes) Transfer the chosen per-vertex attributes from one mesh to another. Useful to transfer attributes to different representations of the same object. For each vertex of the target mesh the closest point (not vertex!) on the source mesh is computed, and the requested interpolated attributes from that source point are copied into the target vertex. The algorithm assumes that the two meshes are reasonably similar and aligned. UpperBound: absolute value (not percentage) Args: script: the FilterScript object or script filename to write the filter to. source_mesh (int): The mesh that contains the source data that we want to transfer target_mesh (int): The mesh whose vertexes will receive the data from the source geometry (bool): If enabled, the position of each vertex of the target mesh will be snapped onto the corresponding closest point on the source mesh normal (bool): If enabled, the normal of each vertex of the target mesh will get the (interpolated) normal of the corresponding closest point on the source mesh color (bool): If enabled, the color of each vertex of the target mesh will become the color of the corresponding closest point on the source mesh quality (bool): If enabled, the quality of each vertex of the target mesh will become the quality of the corresponding closest point on the source mesh selection (bool): If enabled, each vertex of the target mesh will be selected if the corresponding closest point on the source mesh falls in a selected face quality_distance (bool): If enabled, we store the distance of the transferred value as in the vertex quality max_distance (float): Sample points for which we do not find anything within this distance are rejected and not considered for recovering attributes """ filter_xml = ''.join([ ' <filter name="Vertex Attribute Transfer">\n', ' <Param name="SourceMesh" ', 'value="{:d}" '.format(source_mesh), 'description="Source Mesh" ', 'type="RichMesh" ', '/>\n', ' <Param name="TargetMesh" ', 'value="{:d}" '.format(target_mesh), 'description="Target Mesh" ', 'type="RichMesh" ', '/>\n', ' <Param name="GeomTransfer" ', 'value="{}" '.format(str(geometry).lower()), 'description="Transfer Geometry" ', 'type="RichBool" ', '/>\n', ' <Param name="NormalTransfer" ', 'value="{}" '.format(str(normal).lower()), 'description="Transfer Normal" ', 'type="RichBool" ', '/>\n', ' <Param name="ColorTransfer" ', 'value="{}" '.format(str(color).lower()), 'description="Transfer Color" ', 'type="RichBool" ', '/>\n', ' <Param name="QualityTransfer" ', 'value="{}" '.format(str(quality).lower()), 'description="Transfer quality" ', 'type="RichBool" ', '/>\n', ' <Param name="SelectionTransfer" ', 'value="{}" '.format(str(selection).lower()), 'description="Transfer Selection" ', 'type="RichBool" ', '/>\n', ' <Param name="QualityDistance" ', 'value="{}" '.format(str(quality_distance).lower()), 'description="Store dist. as quality" ', 'type="RichBool" ', '/>\n', ' <Param name="UpperBound" ', 'value="{}" '.format(max_distance), 'description="Max Dist Search" ', 'min="0" ', 'max="100" ', 'type="RichAbsPerc" ', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
Transfer Vertex Attributes to Texture ( between 2 meshes )
def vert_attr2tex_2_meshes(script, source_mesh=0, target_mesh=1, attribute=0, max_distance=0.5, tex_name='TEMP3D_texture.png', tex_width=1024, tex_height=1024, overwrite_tex=True, assign_tex=False, fill_tex=True): """Transfer Vertex Attributes to Texture (between 2 meshes) Args: script: the FilterScript object or script filename to write the filter to. source_mesh (int): The mesh that contains the source data that we want to transfer target_mesh (int): The mesh whose texture will be filled according to source mesh data attribute (int): Choose what attribute has to be transferred onto the target texture. You can choose between Per vertex attributes (color, normal, quality) or to transfer color information from source mesh texture max_distance (float): Sample points for which we do not find anything within this distance are rejected and not considered for recovering data tex_name (str): The texture file to be created tex_width (int): The texture width tex_height (int): The texture height overwrite_tex (bool): If target mesh has a texture will be overwritten (with provided texture dimension) assign_tex (bool): Assign the newly created texture to target mesh fill_tex (bool): If enabled the unmapped texture space is colored using a pull push filling algorithm, if false is set to black Layer stack: No impacts MeshLab versions: 2016.12 1.3.4BETA """ if script.ml_version == '1.3.4BETA': filter_name = 'Transfer Vertex Attributes to Texture (between 2 meshes)' else: filter_name = 'Transfer: Vertex Attributes to Texture (1 or 2 meshes)' filter_xml = ''.join([ ' <filter name="{}">\n'.format(filter_name), ' <Param name="sourceMesh" ', 'value="%d" ' % source_mesh, 'description="Source Mesh" ', 'type="RichMesh" ', '/>\n', ' <Param name="targetMesh" ', 'value="%d" ' % target_mesh, 'description="Target Mesh" ', 'type="RichMesh" ', '/>\n', ' <Param name="AttributeEnum" ', 'value="%d" ' % attribute, 'description="Color Data Source" ', 'enum_val0="Vertex Color" ', 'enum_val1="Vertex Normal" ', 'enum_val2="Vertex Quality" ', 'enum_val3="Texture Color" ', 'enum_cardinality="4" ', 'type="RichEnum" ', '/>\n', ' <Param name="upperBound" ', 'value="%s" ' % max_distance, 'description="Max Dist Search" ', 'min="0" ', 'max="100" ', 'type="RichAbsPerc" ', '/>\n', ' <Param name="textName" ', 'value="%s" ' % tex_name, 'description="Texture file" ', 'type="RichString" ', '/>\n', ' <Param name="textW" ', 'value="%d" ' % tex_width, 'description="Texture width (px)" ', 'type="RichInt" ', '/>\n', ' <Param name="textH" ', 'value="%d" ' % tex_height, 'description="Texture height (px)" ', 'type="RichInt" ', '/>\n', ' <Param name="overwrite" ', 'value="%s" ' % str(overwrite_tex).lower(), 'description="Overwrite Target Mesh Texture" ', 'type="RichBool" ', '/>\n', ' <Param name="assign" ', 'value="%s" ' % str(assign_tex).lower(), 'description="Assign Texture" ', 'type="RichBool" ', '/>\n', ' <Param name="pullpush" ', 'value="%s" ' % str(fill_tex).lower(), 'description="Fill texture" ', 'type="RichBool" ', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
Transfer texture colors to vertex colors ( between 2 meshes )
def tex2vc_2_meshes(script, source_mesh=0, target_mesh=1, max_distance=0.5): """Transfer texture colors to vertex colors (between 2 meshes) Args: script: the FilterScript object or script filename to write the filter to. source_mesh (int): The mesh with associated texture that we want to sample from target_mesh (int): The mesh whose vertex color will be filled according to source mesh texture max_distance (float): Sample points for which we do not find anything within this distance are rejected and not considered for recovering color Layer stack: No impacts MeshLab versions: 2016.12 1.3.4BETA """ if script.ml_version == '1.3.4BETA': filter_name = 'Texture to Vertex Color (between 2 meshes)' else: filter_name = 'Transfer: Texture to Vertex Color (1 or 2 meshes)' filter_xml = ''.join([ ' <filter name="{}">\n'.format(filter_name), ' <Param name="sourceMesh" ', 'value="%d" ' % source_mesh, 'description="Source Mesh" ', 'type="RichMesh" ', '/>\n', ' <Param name="targetMesh" ', 'value="%d" ' % target_mesh, 'description="Target Mesh" ', 'type="RichMesh" ', '/>\n', ' <Param name="upperBound" ', 'value="%s" ' % max_distance, 'description="Max Dist Search" ', 'min="0" ', 'max="100" ', 'type="RichAbsPerc" ', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
Simplify a mesh using a Quadric based Edge Collapse Strategy better than clustering but slower. Optionally tries to preserve UV parametrization for textured meshes.
def simplify(script, texture=True, faces=25000, target_perc=0.0, quality_thr=0.3, preserve_boundary=False, boundary_weight=1.0, optimal_placement=True, preserve_normal=False, planar_quadric=False, selected=False, extra_tex_coord_weight=1.0, preserve_topology=True, quality_weight=False, autoclean=True): """ Simplify a mesh using a Quadric based Edge Collapse Strategy, better than clustering but slower. Optionally tries to preserve UV parametrization for textured meshes. Args: script: the FilterScript object or script filename to write the filter to. texture (bool): faces (int): The desired final number of faces target_perc (float): If non zero, this parameter specifies the desired final size of the mesh as a percentage of the initial mesh size. quality_thr (float): Quality threshold for penalizing bad shaped faces. The value is in the range [0..1]0 accept any kind of face (no penalties), 0.5 penalize faces with quality less than 0.5, proportionally to their shape. preserve_boundary (bool): The simplification process tries not to affect mesh boundaries boundary_weight (float): The importance of the boundary during simplification. Default (1.0) means that the boundary has the same importance of the rest. Values greater than 1.0 raise boundary importance and has the effect of removing less vertices on the border. Admitted range of values (0,+inf). optimal_placement (bool): Each collapsed vertex is placed in the position minimizing the quadric error. It can fail (creating bad spikes) in case of very flat areas. If disabled edges are collapsed onto one of the two original vertices and the final mesh is composed by a subset of the original vertices. preserve_normal (bool): Try to avoid face flipping effects and try to preserve the original orientation of the surface. planar_quadric (bool): Add additional simplification constraints that improves the quality of the simplification of the planar portion of the mesh. selected (bool): The simplification is applied only to the selected set of faces. Take care of the target number of faces! extra_tex_coord_weight (float): Additional weight for each extra Texture Coordinates for every (selected) vertex. Ignored if texture is False. preserve_topology (bool): Avoid all the collapses that should cause a topology change in the mesh (like closing holes, squeezing handles, etc). If checked the genus of the mesh should stay unchanged. quality_weight (bool): Use the Per-Vertex quality as a weighting factor for the simplification. The weight is used as a error amplification value, so a vertex with a high quality value will not be simplified and a portion of the mesh with low quality values will be aggressively simplified. autoclean (bool): After the simplification an additional set of steps is performed to clean the mesh (unreferenced vertices, bad faces, etc). Layer stack: Unchanged; current mesh is simplified in place. MeshLab versions: 2016.12 (different filter name) 1.3.4BETA """ if texture: if isinstance(script, FilterScript) and (script.ml_version == '2016.12'): filter_xml = ' <filter name="Simplification: Quadric Edge Collapse Decimation (with texture)">\n' else: filter_xml = ' <filter name="Quadric Edge Collapse Decimation (with texture)">\n' else: if isinstance(script, FilterScript) and (script.ml_version == '2016.12'): filter_xml = ' <filter name="Simplification: Quadric Edge Collapse Decimation">\n' else: filter_xml = ' <filter name="Quadric Edge Collapse Decimation">\n' # Parameters common to both 'with' and 'without texture' filter_xml = ''.join([ filter_xml, ' <Param name="TargetFaceNum" ', 'value="{:d}" '.format(faces), 'description="Target number of faces" ', 'type="RichInt" ', '/>\n', ' <Param name="TargetPerc" ', 'value="{}" '.format(target_perc), 'description="Percentage reduction (0..1)" ', 'type="RichFloat" ', '/>\n', ' <Param name="QualityThr" ', 'value="{}" '.format(quality_thr), 'description="Quality threshold" ', 'type="RichFloat" ', '/>\n', ' <Param name="PreserveBoundary" ', 'value="{}" '.format(str(preserve_boundary).lower()), 'description="Preserve Boundary of the mesh" ', 'type="RichBool" ', '/>\n', ' <Param name="BoundaryWeight" ', 'value="{}" '.format(boundary_weight), 'description="Boundary Preserving Weight" ', 'type="RichFloat" ', '/>\n', ' <Param name="OptimalPlacement" ', 'value="{}" '.format(str(optimal_placement).lower()), 'description="Optimal position of simplified vertices" ', 'type="RichBool" ', '/>\n', ' <Param name="PreserveNormal" ', 'value="{}" '.format(str(preserve_normal).lower()), 'description="Preserve Normal" ', 'type="RichBool" ', '/>\n', ' <Param name="PlanarQuadric" ', 'value="{}" '.format(str(planar_quadric).lower()), 'description="Planar Simplification" ', 'type="RichBool" ', '/>\n', ' <Param name="Selected" ', 'value="{}" '.format(str(selected).lower()), 'description="Simplify only selected faces" ', 'type="RichBool" ', '/>\n']) if texture: # Parameters unique to 'with texture' filter_xml = ''.join([ filter_xml, ' <Param name="Extratcoordw" ', 'value="{}" '.format(extra_tex_coord_weight), 'description="Texture Weight" ', 'type="RichFloat" ', '/>\n']) else: # Parameters unique to 'without texture' filter_xml = ''.join([ filter_xml, ' <Param name="PreserveTopology" ', 'value="{}" '.format(str(preserve_topology).lower()), 'description="Preserve Topology" ', 'type="RichBool" ', '/>\n', ' <Param name="QualityWeight" ', 'value="{}" '.format(str(quality_weight).lower()), 'description="Weighted Simplification" ', 'type="RichBool" ', '/>\n', ' <Param name="AutoClean" ', 'value="{}" '.format(str(autoclean).lower()), 'description="Post-simplification cleaning" ', 'type="RichBool" ', '/>\n']) filter_xml = ''.join([filter_xml, ' </filter>\n']) util.write_filter(script, filter_xml) return None
Create a new mesh that is a resampled version of the current one.
def uniform_resampling(script, voxel=1.0, offset=0.0, merge_vert=True, discretize=False, multisample=False, thicken=False): """ Create a new mesh that is a resampled version of the current one. The resampling is done by building a uniform volumetric representation where each voxel contains the signed distance from the original surface. The resampled surface is reconstructed using the marching cube algorithm over this volume. Args: script: the FilterScript object or script filename to write the filter to. voxel (float): voxel (cell) size for resampling. Smaller cells give better precision at a higher computational cost. Remember that halving the cell size means that you build a volume 8 times larger. offset (float): offset amount of the created surface (i.e. distance of the created surface from the original one). If offset is zero, the created surface passes on the original mesh itself. Values greater than zero mean an external surface (offset), and lower than zero mean an internal surface (inset). In practice this value is the threshold passed to the Marching Cube algorithm to extract the isosurface from the distance field representation. merge_vert (bool): if True the mesh generated by MC will be cleaned by unifying vertices that are almost coincident. discretize (bool): if True the position of the intersected edge of the marching cube grid is not computed by linear interpolation, but it is placed in fixed middle position. As a consequence the resampled object will look severely aliased by a stairstep appearance. Useful only for simulating the output of 3D printing devices. multisample (bool): if True the distance field is more accurately compute by multisampling the volume (7 sample for each voxel). Much slower but less artifacts. thicken (bool): if True, you have to choose a non zero Offset and a double surface is built around the original surface, inside and outside. Is useful to convert thin floating surfaces into solid, thick meshes. Layer stack: Creates 1 new layer 'Offset mesh' Current layer is changed to new layer MeshLab versions: 2016.12 1.3.4BETA """ filter_xml = ''.join([ ' <filter name="Uniform Mesh Resampling">\n', ' <Param name="CellSize" ', 'value="{}" '.format(voxel), 'description="Precision" ', 'min="0" ', 'max="100" ', 'type="RichAbsPerc" ', '/>\n', ' <Param name="Offset" ', 'value="{}" '.format(offset), 'description="Offset" ', 'min="-100" ', 'max="100" ', 'type="RichAbsPerc" ', '/>\n', ' <Param name="mergeCloseVert" ', 'value="{}" '.format(str(merge_vert).lower()), 'description="Clean Vertices" ', 'type="RichBool" ', '/>\n', ' <Param name="discretize" ', 'value="{}" '.format(str(discretize).lower()), 'description="Discretize" ', 'type="RichBool" ', '/>\n', ' <Param name="multisample" ', 'value="{}" '.format(str(multisample).lower()), 'description="Multisample" ', 'type="RichBool" ', '/>\n', ' <Param name="absDist" ', 'value="{}" '.format(str(thicken).lower()), 'description="Absolute Distance" ', 'type="RichBool" ', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) if isinstance(script, FilterScript): script.add_layer('Offset mesh') return None
Calculate the convex hull with Qhull library http:// www. qhull. org/ html/ qconvex. htm
def hull(script, reorient_normal=True): """ Calculate the convex hull with Qhull library http://www.qhull.org/html/qconvex.htm The convex hull of a set of points is the boundary of the minimal convex set containing the given non-empty finite set of points. Args: script: the FilterScript object or script filename to write the filter to. reorient_normal (bool): Re-orient all faces coherentely after hull operation. Layer stack: Creates 1 new layer 'Convex Hull' Current layer is changed to new layer MeshLab versions: 2016.12 1.3.4BETA """ filter_xml = ''.join([ ' <filter name="Convex Hull">\n', ' <Param name="reorient" ', 'value="{}" '.format(str(reorient_normal).lower()), 'description="Re-orient all faces coherentely" ', 'type="RichBool" ', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) if isinstance(script, FilterScript): script.add_layer('Convex Hull') return None
Use the points and normals to build a surface using the Poisson Surface reconstruction approach.
def surface_poisson(script, octree_depth=10, solver_divide=8, samples_per_node=1.0, offset=1.0): """ Use the points and normals to build a surface using the Poisson Surface reconstruction approach. Args: script: the FilterScript object or script filename to write the filter to. octree_depth (int): Set the depth of the Octree used for extracting the final surface. Suggested range 5..10. Higher numbers mean higher precision in the reconstruction but also higher processing times. Be patient. solver_divide (int): This integer argument specifies the depth at which a block Gauss-Seidel solver is used to solve the Laplacian equation. Using this parameter helps reduce the memory overhead at the cost of a small increase in reconstruction time. In practice, the authors have found that for reconstructions of depth 9 or higher a subdivide depth of 7 or 8 can reduce the memory usage. The default value is 8. samples_per_node (float): This floating point value specifies the minimum number of sample points that should fall within an octree node as the octree&#xa;construction is adapted to sampling density. For noise-free samples, small values in the range [1.0 - 5.0] can be used. For more noisy samples, larger values in the range [15.0 - 20.0] may be needed to provide a smoother, noise-reduced, reconstruction. The default value is 1.0. offset (float): This floating point value specifies a correction value for the isosurface threshold that is chosen. Values less than 1 mean internal offsetting, greater than 1 mean external offsetting. Good values are in the range 0.5 .. 2. The default value is 1.0 (no offsetting). Layer stack: Creates 1 new layer 'Poisson mesh' Current layer is changed to new layer MeshLab versions: 1.3.4BETA """ filter_xml = ''.join([ ' <filter name="Surface Reconstruction: Poisson">\n', ' <Param name="OctDepth" ', 'value="{:d}" '.format(octree_depth), 'description="Octree Depth" ', 'type="RichInt" ', '/>\n', ' <Param name="SolverDivide" ', 'value="{:d}" '.format(solver_divide), 'description="Solver Divide" ', 'type="RichInt" ', '/>\n', ' <Param name="SamplesPerNode" ', 'value="{}" '.format(samples_per_node), 'description="Samples per Node" ', 'type="RichFloat" ', '/>\n', ' <Param name="Offset" ', 'value="{}" '.format(offset), 'description="Surface offsetting" ', 'type="RichFloat" ', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) if isinstance(script, FilterScript): script.add_layer('Poisson mesh', change_layer=True) return None
This surface reconstruction algorithm creates watertight surfaces from oriented point sets.
def surface_poisson_screened(script, visible_layer=False, depth=8, full_depth=5, cg_depth=0, scale=1.1, samples_per_node=1.5, point_weight=4.0, iterations=8, confidence=False, pre_clean=False): """ This surface reconstruction algorithm creates watertight surfaces from oriented point sets. The filter uses the original code of Michael Kazhdan and Matthew Bolitho implementing the algorithm in the following paper: Michael Kazhdan, Hugues Hoppe, "Screened Poisson surface reconstruction" ACM Trans. Graphics, 32(3), 2013 Args: script: the FilterScript object or script filename to write the filter to. visible_layer (bool): If True all the visible layers will be used for providing the points depth (int): This integer is the maximum depth of the tree that will be used for surface reconstruction. Running at depth d corresponds to solving on a voxel grid whose resolution is no larger than 2^d x 2^d x 2^d. Note that since the reconstructor adapts the octree to the sampling density, the specified reconstruction depth is only an upper bound. The default value for this parameter is 8. full_depth (int): This integer specifies the depth beyond depth the octree will be adapted. At coarser depths, the octree will be complete, containing all 2^d x 2^d x 2^d nodes. The default value for this parameter is 5. cg_depth (int): This integer is the depth up to which a conjugate-gradients solver will be used to solve the linear system. Beyond this depth Gauss-Seidel relaxation will be used. The default value for this parameter is 0. scale (float): This floating point value specifies the ratio between the diameter of the cube used for reconstruction and the diameter of the samples' bounding cube. The default value is 1.1. samples_per_node (float): This floating point value specifies the minimum number of sample points that should fall within an octree node as the octree construction is adapted to sampling density. For noise-free samples, small values in the range [1.0 - 5.0] can be used. For more noisy samples, larger values in the range [15.0 - 20.0] may be needed to provide a smoother, noise-reduced, reconstruction. The default value is 1.5. point_weight (float): This floating point value specifies the importance that interpolation of the point samples is given in the formulation of the screened Poisson equation. The results of the original (unscreened) Poisson Reconstruction can be obtained by setting this value to 0. The default value for this parameter is 4. iterations (int): This integer value specifies the number of Gauss-Seidel relaxations to be performed at each level of the hierarchy. The default value for this parameter is 8. confidence (bool): If True this tells the reconstructor to use the quality as confidence information; this is done by scaling the unit normals with the quality values. When the flag is not enabled, all normals are normalized to have unit-length prior to reconstruction. pre_clean (bool): If True will force a cleaning pre-pass on the data removing all unreferenced vertices or vertices with null normals. Layer stack: Creates 1 new layer 'Poisson mesh' Current layer is not changed MeshLab versions: 2016.12 """ filter_xml = ''.join([ ' <xmlfilter name="Screened Poisson Surface Reconstruction">\n', ' <xmlparam name="cgDepth" value="{:d}"/>\n'.format(cg_depth), ' <xmlparam name="confidence" value="{}"/>\n'.format(str(confidence).lower()), ' <xmlparam name="depth" value="{:d}"/>\n'.format(depth), ' <xmlparam name="fullDepth" value="{:d}"/>\n'.format(full_depth), ' <xmlparam name="iters" value="{:d}"/>\n'.format(iterations), ' <xmlparam name="pointWeight" value="{}"/>\n'.format(point_weight), ' <xmlparam name="preClean" value="{}"/>\n'.format(str(pre_clean).lower()), ' <xmlparam name="samplesPerNode" value="{}"/>\n'.format(samples_per_node), ' <xmlparam name="scale" value="{}"/>\n'.format(scale), ' <xmlparam name="visibleLayer" value="{}"/>\n'.format(str(visible_layer).lower()), ' </xmlfilter>\n']) util.write_filter(script, filter_xml) if isinstance(script, FilterScript): script.add_layer('Poisson mesh', change_layer=False) return None
Use the points and normals to build a surface using the Poisson Surface reconstruction approach.
def curvature_flipping(script, angle_threshold=1.0, curve_type=0, selected=False): """ Use the points and normals to build a surface using the Poisson Surface reconstruction approach. Args: script: the FilterScript object or script filename to write the filter to. angle_threshold (float): To avoid excessive flipping/swapping we consider only couple of faces with a significant diedral angle (e.g. greater than the indicated threshold). curve_type (int): Choose a metric to compute surface curvature on vertices H = mean curv, K = gaussian curv, A = area per vertex 1: Mean curvature = H 2: Norm squared mean curvature = (H * H) / A 3: Absolute curvature: if(K >= 0) return 2 * H else return 2 * sqrt(H ^ 2 - A * K) Layer stack: No impacts MeshLab versions: 2016.12 1.3.4BETA """ filter_xml = ''.join([ ' <filter name="Curvature flipping optimization">\n', ' <Param name="selection" ', 'value="{}" '.format(str(selected).lower()), 'description="Update selection" ', 'type="RichBool" ', '/>\n', ' <Param name="pthreshold" ', 'value="{}" '.format(angle_threshold), 'description="Angle Thr (deg)" ', 'type="RichFloat" ', '/>\n', ' <Param name="curvtype" ', 'value="{:d}" '.format(curve_type), 'description="Curvature metric" ', 'enum_val0="mean" ', 'enum_val1="norm squared" ', 'enum_val2="absolute" ', 'enum_cardinality="3" ', 'type="RichEnum" ', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
Turn a model into a surface with Voronoi style holes in it
def voronoi(script, hole_num=50, target_layer=None, sample_layer=None, thickness=0.5, backward=True): """ Turn a model into a surface with Voronoi style holes in it References: http://meshlabstuff.blogspot.com/2009/03/creating-voronoi-sphere.html http://meshlabstuff.blogspot.com/2009/04/creating-voronoi-sphere-2.html Requires FilterScript object Args: script: the FilterScript object to write the filter to. Does not work with a script filename. Layer stack: No impacts MeshLab versions: 2016.12 1.3.4BETA """ if target_layer is None: target_layer = script.current_layer() if sample_layer is None: # Current layer is currently not changed after poisson_disk is run sampling.poisson_disk(script, sample_num=hole_num) sample_layer = script.last_layer() vert_color.voronoi(script, target_layer=target_layer, source_layer=sample_layer, backward=backward) select.vert_quality(script, min_quality=0.0, max_quality=thickness) if backward: select.invert(script) delete.selected(script) smooth.laplacian(script, iterations=3) return None
Select all the faces of the current mesh
def all(script, face=True, vert=True): """ Select all the faces of the current mesh Args: script: the FilterScript object or script filename to write the filter to. faces (bool): If True the filter will select all the faces. verts (bool): If True the filter will select all the vertices. Layer stack: No impacts MeshLab versions: 2016.12 1.3.4BETA """ filter_xml = ''.join([ ' <filter name="Select All">\n', ' <Param name="allFaces" ', 'value="{}" '.format(str(face).lower()), 'description="DSelect all Faces" ', 'type="RichBool" ', '/>\n', ' <Param name="allVerts" ', 'value="{}" '.format(str(vert).lower()), 'description="Select all Vertices" ', 'type="RichBool" ', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
Grow ( dilate expand ) the current set of selected faces
def grow(script, iterations=1): """ Grow (dilate, expand) the current set of selected faces Args: script: the FilterScript object or script filename to write the filter to. iterations (int): the number of times to grow the selection. Layer stack: No impacts MeshLab versions: 2016.12 1.3.4BETA """ filter_xml = ' <filter name="Dilate Selection"/>\n' for _ in range(iterations): util.write_filter(script, filter_xml) return None
Shrink ( erode reduce ) the current set of selected faces
def shrink(script, iterations=1): """ Shrink (erode, reduce) the current set of selected faces Args: script: the FilterScript object or script filename to write the filter to. iterations (int): the number of times to shrink the selection. Layer stack: No impacts MeshLab versions: 2016.12 1.3.4BETA """ filter_xml = ' <filter name="Erode Selection"/>\n' for _ in range(iterations): util.write_filter(script, filter_xml) return None
Select the small disconnected parts ( components ) of a mesh.
def small_parts(script, ratio=0.2, non_closed_only=False): """ Select the small disconnected parts (components) of a mesh. Args: script: the FilterScript object or script filename to write the filter to. ratio (float): This ratio (between 0 and 1) defines the meaning of 'small' as the threshold ratio between the number of faces of the largest component and the other ones. A larger value will select more components. non_closed_only (bool): Select only non-closed components. Layer stack: No impacts MeshLab versions: 2016.12 1.3.4BETA """ filter_xml = ''.join([ ' <filter name="Small component selection">\n', ' <Param name="NbFaceRatio" ', 'value="{}" '.format(ratio), 'description="Small component ratio" ', 'type="RichFloat" ', '/>\n', ' <Param name="NonClosedOnly" ', 'value="{}" '.format(str(non_closed_only).lower()), 'description="Select only non closed components" ', 'type="RichBool" ', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
Select all the faces and vertexes within the specified vertex quality range.
def vert_quality(script, min_quality=0.0, max_quality=0.05, inclusive=True): """ Select all the faces and vertexes within the specified vertex quality range. Args: script: the FilterScript object or script filename to write the filter] to. min_quality (float): Minimum acceptable quality value. max_quality (float): Maximum acceptable quality value. inclusive (bool): If True only the faces with ALL the vertices within the specified range are selected. Otherwise any face with at least one vertex within the range is selected. Layer stack: No impacts MeshLab versions: 2016.12 1.3.4BETA """ filter_xml = ''.join([ ' <filter name="Select by Vertex Quality">\n', ' <Param name="minQ" ', 'value="{}" '.format(min_quality), 'description="Min Quality" ', 'min="0" ', 'max="{}" '.format(2 * max_quality), 'type="RichDynamicFloat" ', '/>\n', ' <Param name="maxQ" ', 'value="{}" '.format(max_quality), 'description="Max Quality" ', 'min="0" ', 'max="{}" '.format(2 * max_quality), 'type="RichDynamicFloat" ', '/>\n', ' <Param name="Inclusive" ', 'value="{}" '.format(str(inclusive).lower()), 'description="Inclusive Sel." ', 'type="RichBool" ', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
Boolean function using muparser lib to perform face selection over current mesh.
def face_function(script, function='(fi == 0)'): """Boolean function using muparser lib to perform face selection over current mesh. See help(mlx.muparser_ref) for muparser reference documentation. It's possible to use parenthesis, per-vertex variables and boolean operator: (, ), and, or, <, >, = It's possible to use per-face variables like attributes associated to the three vertices of every face. Variables (per face): x0, y0, z0 for first vertex; x1,y1,z1 for second vertex; x2,y2,z2 for third vertex nx0, ny0, nz0, nx1, ny1, nz1, etc. for vertex normals r0, g0, b0, a0, etc. for vertex color q0, q1, q2 for quality wtu0, wtv0, wtu1, wtv1, wtu2, wtv2 (per wedge texture coordinates) ti for face texture index (>= ML2016.12) vsel0, vsel1, vsel2 for vertex selection (1 yes, 0 no) (>= ML2016.12) fr, fg, fb, fa for face color (>= ML2016.12) fq for face quality (>= ML2016.12) fnx, fny, fnz for face normal (>= ML2016.12) fsel face selection (1 yes, 0 no) (>= ML2016.12) Args: script: the FilterScript object or script filename to write the filter] to. function (str): a boolean function that will be evaluated in order to select a subset of faces. Layer stack: No impacts MeshLab versions: 2016.12 1.3.4BETA """ filter_xml = ''.join([ ' <filter name="Conditional Face Selection">\n', ' <Param name="condSelect" ', 'value="{}" '.format(str(function).replace('&', '&amp;').replace('<', '&lt;')), 'description="boolean function" ', 'type="RichString" ', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
Boolean function using muparser lib to perform vertex selection over current mesh.
def vert_function(script, function='(q < 0)', strict_face_select=True): """Boolean function using muparser lib to perform vertex selection over current mesh. See help(mlx.muparser_ref) for muparser reference documentation. It's possible to use parenthesis, per-vertex variables and boolean operator: (, ), and, or, <, >, = It's possible to use the following per-vertex variables in the expression: Variables: x, y, z (coordinates) nx, ny, nz (normal) r, g, b, a (color) q (quality) rad vi (vertex index) vtu, vtv (texture coordinates) ti (texture index) vsel (is the vertex selected? 1 yes, 0 no) and all custom vertex attributes already defined by user. Args: script: the FilterScript object or script filename to write the filter] to. function (str): a boolean function that will be evaluated in order to select a subset of vertices. Example: (y > 0) and (ny > 0) strict_face_select (bool): if True a face is selected if ALL its vertices are selected. If False a face is selected if at least one of its vertices is selected. ML v1.3.4BETA only; this is ignored in 2016.12. In 2016.12 only vertices are selected. Layer stack: No impacts MeshLab versions: 2016.12 1.3.4BETA """ if script.ml_version == '1.3.4BETA': strict_select = ''.join([ ' <Param name="strictSelect" ', 'value="{}" '.format(str(strict_face_select).lower()), 'description="Strict face selection" ', 'type="RichBool" ', '/>\n', ]) else: strict_select = '' filter_xml = ''.join([ ' <filter name="Conditional Vertex Selection">\n', ' <Param name="condSelect" ', 'value="{}" '.format(str(function).replace('&', '&amp;').replace('<', '&lt;')), 'description="boolean function" ', 'type="RichString" ', '/>\n', strict_select, ' </filter>\n']) util.write_filter(script, filter_xml) return None
Select all vertices within a cylindrical radius
def cylindrical_vert(script, radius=1.0, inside=True): """Select all vertices within a cylindrical radius Args: radius (float): radius of the sphere center_pt (3 coordinate tuple or list): center point of the sphere Layer stack: No impacts MeshLab versions: 2016.12 1.3.4BETA """ if inside: function = 'sqrt(x^2+y^2)<={}'.format(radius) else: function = 'sqrt(x^2+y^2)>={}'.format(radius) vert_function(script, function=function) return None
Select all vertices within a spherical radius
def spherical_vert(script, radius=1.0, center_pt=(0.0, 0.0, 0.0)): """Select all vertices within a spherical radius Args: radius (float): radius of the sphere center_pt (3 coordinate tuple or list): center point of the sphere Layer stack: No impacts MeshLab versions: 2016.12 1.3.4BETA """ function = 'sqrt((x-{})^2+(y-{})^2+(z-{})^2)<={}'.format( center_pt[0], center_pt[1], center_pt[2], radius) vert_function(script, function=function) return None
Flatten all or only the visible layers into a single new mesh.
def join(script, merge_visible=True, merge_vert=False, delete_layer=True, keep_unreferenced_vert=False): """ Flatten all or only the visible layers into a single new mesh. Transformations are preserved. Existing layers can be optionally deleted. Args: script: the mlx.FilterScript object or script filename to write the filter to. merge_visible (bool): merge only visible layers merge_vert (bool): merge the vertices that are duplicated among different layers. Very useful when the layers are spliced portions of a single big mesh. delete_layer (bool): delete all the merged layers. If all layers are visible only a single layer will remain after the invocation of this filter. keep_unreferenced_vert (bool): Do not discard unreferenced vertices from source layers. Necessary for point-only layers. Layer stack: Creates a new layer "Merged Mesh" Changes current layer to the new layer Optionally deletes all other layers MeshLab versions: 2016.12 1.3.4BETA Bugs: UV textures: not currently preserved, however will be in a future release. https://github.com/cnr-isti-vclab/meshlab/issues/128 merge_visible: it is not currently possible to change the layer visibility from meshlabserver, however this will be possible in the future https://github.com/cnr-isti-vclab/meshlab/issues/123 """ filter_xml = ''.join([ ' <filter name="Flatten Visible Layers">\n', ' <Param name="MergeVisible" ', 'value="{}" '.format(str(merge_visible).lower()), 'description="Merge Only Visible Layers" ', 'type="RichBool" ', '/>\n', ' <Param name="MergeVertices" ', 'value="{}" '.format(str(merge_vert).lower()), 'description="Merge duplicate vertices" ', 'type="RichBool" ', '/>\n', ' <Param name="DeleteLayer" ', 'value="{}" '.format(str(delete_layer).lower()), 'description="Delete Layers" ', 'type="RichBool" ', '/>\n', ' <Param name="AlsoUnreferenced" ', 'value="{}" '.format(str(keep_unreferenced_vert).lower()), 'description="Keep unreferenced vertices" ', 'type="RichBool" ', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) if isinstance(script, mlx.FilterScript): script.add_layer('Merged Mesh') if delete_layer: # As it is not yet possible to change the layer visibility, all # layers will be deleted. This will be updated once layer # visibility is tracked. for i in range(script.last_layer()): script.del_layer(0) return None
Delete layer
def delete(script, layer_num=None): """ Delete layer Args: script: the mlx.FilterScript object or script filename to write the filter to. layer_num (int): the number of the layer to delete. Default is the current layer. Not supported on the file base API. Layer stack: Deletes a layer will change current layer if deleted layer is lower in the stack MeshLab versions: 2016.12 1.3.4BETA """ filter_xml = ' <filter name="Delete Current Mesh"/>\n' if isinstance(script, mlx.FilterScript): if (layer_num is None) or (layer_num == script.current_layer()): util.write_filter(script, filter_xml) script.del_layer(script.current_layer()) else: cur_layer = script.current_layer() change(script, layer_num) util.write_filter(script, filter_xml) if layer_num < script.current_layer(): change(script, cur_layer - 1) else: change(script, cur_layer) script.del_layer(layer_num) else: util.write_filter(script, filter_xml) return None
Rename layer label
def rename(script, label='blank', layer_num=None): """ Rename layer label Can be useful for outputting mlp files, as the output file names use the labels. Args: script: the mlx.FilterScript object or script filename to write the filter to. label (str): new label for the mesh layer layer_num (int): layer number to rename. Default is the current layer. Not supported on the file base API. Layer stack: Renames a layer MeshLab versions: 2016.12 1.3.4BETA """ filter_xml = ''.join([ ' <filter name="Rename Current Mesh">\n', ' <Param name="newName" ', 'value="{}" '.format(label), 'description="New Label" ', 'type="RichString" ', '/>\n', ' </filter>\n']) if isinstance(script, mlx.FilterScript): if (layer_num is None) or (layer_num == script.current_layer()): util.write_filter(script, filter_xml) script.layer_stack[script.current_layer()] = label else: cur_layer = script.current_layer() change(script, layer_num) util.write_filter(script, filter_xml) change(script, cur_layer) script.layer_stack[layer_num] = label else: util.write_filter(script, filter_xml) return None
Change the current layer by specifying the new layer number.
def change(script, layer_num=None): """ Change the current layer by specifying the new layer number. Args: script: the mlx.FilterScript object or script filename to write the filter to. layer_num (int): the number of the layer to change to. Default is the last layer if script is a mlx.FilterScript object; if script is a filename the default is the first layer. Layer stack: Modifies current layer MeshLab versions: 2016.12 1.3.4BETA """ if layer_num is None: if isinstance(script, mlx.FilterScript): layer_num = script.last_layer() else: layer_num = 0 filter_xml = ''.join([ ' <filter name="Change the current layer">\n', ' <Param name="mesh" ', 'value="{:d}" '.format(layer_num), 'description="Mesh" ', 'type="RichMesh" ', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) if isinstance(script, mlx.FilterScript): script.set_current_layer(layer_num) #script.layer_stack[len(self.layer_stack) - 1] = layer_num return None
Duplicate a layer.
def duplicate(script, layer_num=None): """ Duplicate a layer. New layer label is '*_copy'. Args: script: the mlx.FilterScript object or script filename to write the filter to. layer_num (int): layer number to duplicate. Default is the current layer. Not supported on the file base API. Layer stack: Creates a new layer Changes current layer to the new layer MeshLab versions: 2016.12 1.3.4BETA """ filter_xml = ' <filter name="Duplicate Current layer"/>\n' if isinstance(script, mlx.FilterScript): if (layer_num is None) or (layer_num == script.current_layer()): util.write_filter(script, filter_xml) script.add_layer('{}_copy'.format(script.layer_stack[script.current_layer()]), True) else: change(script, layer_num) util.write_filter(script, filter_xml) script.add_layer('{}_copy'.format(script.layer_stack[layer_num]), True) else: util.write_filter(script, filter_xml) return None
Split current layer into many layers one for each part ( connected component )
def split_parts(script, part_num=None, layer_num=None): """ Split current layer into many layers, one for each part (connected component) Mesh is split so that the largest part is the lowest named layer "CC 0" and the smallest part is the highest numbered "CC" layer. Args: script: the mlx.FilterScript object or script filename to write the filter to. part_num (int): the number of parts in the model. This is needed in order to properly create and manage the layer stack. Can be found with mlx.compute.measure_topology. layer_num (int): the number of the layer to split. Default is the current layer. Not supported on the file base API. Layer stack: Creates a new layer for each part named "CC 0", "CC 1", etc. Changes current layer to the last new layer MeshLab versions: 2016.12 1.3.4BETA Bugs: UV textures: not currently preserved, however will be in a future release. https://github.com/cnr-isti-vclab/meshlab/issues/127 """ filter_xml = ' <filter name="Split in Connected Components"/>\n' if isinstance(script, mlx.FilterScript): if (layer_num is not None) and (layer_num != script.current_layer()): change(script, layer_num) util.write_filter(script, filter_xml) if part_num is not None: for i in range(part_num): script.add_layer('CC {}'.format(i), True) else: script.add_layer('CC 0', True) print('Warning: the number of parts was not provided and cannot', 'be determined automatically. The layer stack is likely', 'incorrect!') else: util.write_filter(script, filter_xml) return None
Delete all layers below the specified one.
def delete_lower(script, layer_num=None): """ Delete all layers below the specified one. Useful for MeshLab ver 2016.12, whcih will only output layer 0. """ if layer_num is None: layer_num = script.current_layer() if layer_num != 0: change(script, 0) for i in range(layer_num): delete(script, 0) return None
Subprocess program error handling
def handle_error(program_name, cmd, log=None): """Subprocess program error handling Args: program_name (str): name of the subprocess program Returns: break_now (bool): indicate whether calling program should break out of loop """ print('\nHouston, we have a problem.', '\n%s did not finish successfully. Review the log' % program_name, 'file and the input file(s) to see what went wrong.') print('%s command: "%s"' % (program_name, cmd)) if log is not None: print('log: "%s"' % log) print('Where do we go from here?') print(' r - retry running %s (probably after' % program_name, 'you\'ve fixed any problems with the input files)') print(' c - continue on with the script (probably after', 'you\'ve manually re-run and generated the desired', 'output file(s)') print(' x - exit, keeping the TEMP3D files and log') print(' xd - exit, deleting the TEMP3D files and log') while True: choice = input('Select r, c, x (default), or xd: ') if choice not in ('r', 'c', 'x', 'xd'): #print('Please enter a valid option.') choice = 'x' #else: break if choice == 'x': print('Exiting ...') sys.exit(1) elif choice == 'xd': print('Deleting TEMP3D* and log files and exiting ...') util.delete_all('TEMP3D*') if log is not None: os.remove(log) sys.exit(1) elif choice == 'c': print('Continuing on ...') break_now = True elif choice == 'r': print('Retrying %s cmd ...' % program_name) break_now = False return break_now
Run meshlabserver in a subprocess.
def run(script='TEMP3D_default.mlx', log=None, ml_log=None, mlp_in=None, mlp_out=None, overwrite=False, file_in=None, file_out=None, output_mask=None, cmd=None, ml_version=ML_VERSION, print_meshlabserver_output=True): """Run meshlabserver in a subprocess. Args: log (str): filename of the log file for meshlabxml. If not None, all meshlabserver stdout and stderr messages will be appended to this file. ml_log (str): filename of the log file output directly by meshlabserver. mlp_in (str or list): input meshlab project file. Can be a single filename or a list of filenames. Filenames will be loaded in the order given. All project files will be loaded before individual input files. If you want to load project and input files in a different order then you should use a custom cmd. mlp_out (str): output meshlab project file. Specify a single filename (meshlabserver accepts multiple output project filenames, however they will all be identical, so there is little use). When this option is used all layers will be saved as ply files. overwrite (bool): when specifying mlp_out, this determines whether any existing files will be overwritten (if True) or new filenames created (if False). If a new project file is created meshes will have '_out' added to their name. file_in (str or list): input mesh filename. Can be a single filename or a list of filenames. Filenames will be loaded in the order given. All project files will be loaded before individual input files. If you want to load project and input files in a different order then you should use a custom cmd. file_out (str or list): output mesh filename. Can be a single filename or a list of filenames. The current layer will be saved to this filename or filenames. Multiple filenames are useful for saving to multiple formats at the same time. Currently there is no way to output multiple layers except for saving a mlp project file. output_mask (str or list): output mask options for the output file. Values must include the flag, i.e. -m or -output_mask. If this is not provided for an output file then function "default_output_mask" is used to determine default values. script (str): the mlx filter script filename to execute. cmd (str): a full meshlabserver command line, such as "meshlabserver -input file.stl". If not None, this will override all other arguements except for log. print_meshlabserver_output (bool): Pass meshlabserver's output to stdout; useful for debugging. Only used if log is None. Notes: Meshlabserver can't handle spaces in paths or filenames (on Windows at least; haven't tested on other platforms). Enclosing the name in quotes or escaping the space has no effect. Returns: return code of meshlabserver process; 0 if successful """ if cmd is None: cmd = 'meshlabserver' if ml_log is not None: # Initialize ml_log ml_log_file = open(ml_log, 'w') ml_log_file.close() cmd += ' -l %s' % ml_log if mlp_in is not None: # make a list if it isn't already mlp_in = util.make_list(mlp_in) for val in mlp_in: cmd += ' -p "%s"' % val if mlp_out is not None: cmd += ' -w %s' % mlp_out if overwrite: cmd += ' -v' if (mlp_in is None) and (file_in is None): # If no input files are provided use the default created by begin(). # This works around the fact that meshlabserver will # not run without an input file. file_in = ['TEMP3D.xyz'] if file_in is not None: # make a list if it isn't already file_in = util.make_list(file_in) for val in file_in: if val == 'bunny': cmd += ' -i "%s"' % os.path.join(THIS_MODULEPATH, os.pardir, 'models', 'bunny_flat(1Z).ply') elif val == 'bunny_raw': cmd += ' -i "%s"' % os.path.join(THIS_MODULEPATH, os.pardir, 'models', 'bunny_raw(-1250Y).ply') else: cmd += ' -i "%s"' % val if file_out is not None: # make a list if it isn't already file_out = util.make_list(file_out) if output_mask is not None: output_mask = util.make_list(output_mask) else: output_mask = [] for index, val in enumerate(file_out): cmd += ' -o "%s"' % val try: cmd += ' %s' % output_mask[index] except IndexError: # If output_mask can't be found use defaults cmd += ' %s' % default_output_mask(val, ml_version=ml_version) if script is not None: cmd += ' -s "%s"' % script if log is not None: log_file = open(log, 'a') log_file.write('meshlabserver cmd = %s\n' % cmd) log_file.write('***START OF MESHLAB STDOUT & STDERR***\n') log_file.close() log_file = open(log, 'a') else: if print_meshlabserver_output: log_file = None print('meshlabserver cmd = %s' % cmd) print('***START OF MESHLAB STDOUT & STDERR***') else: log_file = open(os.devnull, 'w') while True: # TODO: test if shell=True is really needed return_code = subprocess.call(cmd, shell=True, stdout=log_file, stderr=log_file, universal_newlines=True) if log is not None: log_file.close() if (return_code == 0) or handle_error(program_name='MeshLab', cmd=cmd, log=log): break if log is not None: log_file = open(log, 'a') log_file.write('***END OF MESHLAB STDOUT & STDERR***\n') log_file.write('meshlabserver return code = %s\n\n' % return_code) log_file.close() return return_code
Finds the filenames of the referenced texture file ( s ) ( and material file for obj ) for the mesh.
def find_texture_files(fbasename, log=None): """Finds the filenames of the referenced texture file(s) (and material file for obj) for the mesh. Args: fbasename (str): input filename. Supported file extensions: obj ply dae x3d wrl log (str): filename to log output Returns: list: list of all of the texture filenames referenced by the input file. May contain duplicates if the texture files are referenced more than once. List is empty if no texture files are found. list: list of all of the unique texture filenames, also empty if no texture files are found. str: for obj files only, returns the name of the referenced material file. Returns None if no material file is found. """ fext = os.path.splitext(fbasename)[1][1:].strip().lower() material_file = None texture_files = [] vert_colors = False face_colors = False if fext == 'obj': # Material Format: mtllib ./model_mesh.obj.mtl with open(fbasename, 'r') as fread: for line in fread: if 'mtllib' in line: material_file = os.path.basename(line.split()[1]) break if material_file is not None: # Texture Format: map_Kd model_texture.jpg with open(material_file, 'r') as fread: for line in fread: if 'map_Kd' in line: texture_files.append(os.path.basename(line.split()[1])) elif fext == 'ply': # Texture Format: comment TextureFile model_texture.jpg # This works for MeshLab & itSeez3D, but may not work for # every ply file. face_element = False with open(fbasename, 'rb') as fread: # read ascii header; works for both ascii & binary files while True: line = fread.readline().strip().decode('ascii') # print(line) if 'element face' in line: face_element = True if 'red' in line: if face_element: face_colors = True else: vert_colors = True if 'TextureFile' in line: texture_files.append(os.path.basename(line.split()[2])) if 'end_header' in line: break elif fext == 'dae': # COLLADA # elif fext == 'mlp': # Texture Format: <image id="texture0" name="texture0"> # <init_from>model_texture.jpg</init_from> # </image> namespace = 'http://www.collada.org/2005/11/COLLADASchema' tree = ET.parse(fbasename) #root = tree.getroot() #print('root = ', root) #print('root.tag = ', root.tag, 'root.attrib = ', root.attrib) for elem in tree.findall( '{%s}library_images/{%s}image/{%s}init_from' % (namespace, namespace, namespace)): texture_files.append(elem.text) elif fext == 'x3d': # Texture Format: <ImageTexture url="model_texture.jpg"/> #ns = 'http://www.w3.org/2001/XMLSchema-instance' tree = ET.parse(fbasename) #root = tree.getroot() #print('root = ', root) #print('root.tag = ', root.tag, 'root.attrib = ', root.attrib) # for elem in root: # for elem in tree.iter(): # iterate through tree; very useful to see possible tags #print('elem.tag = ', elem.tag) #print('elem.attrib = ', elem.attrib) for elem in tree.iter(tag='ImageTexture'): #print('elem.attrib = ', elem.attrib) texture_files.append(elem.attrib['url']) elif fext == 'wrl': # Texture Format: texture ImageTexture { url "model_texture.jpg" } with open(fbasename, 'r') as fread: for line in fread: if 'ImageTexture' in line: texture_files.append(os.path.basename(line.split('"')[1])) elif fext != 'stl': # add other formats that don't support texture, e.g. xyz? print('File extension %s is not currently supported' % fext) # TODO: raise exception here texture_files_unique = list(set(texture_files)) if log is not None: log_file = open(log, 'a') log_file.write('Results of find_texture_files:\n') log_file.write('fbasename = %s\n' % fbasename) log_file.write('texture_files = %s\n' % texture_files) log_file.write('texture_files_unique = %s\n' % texture_files_unique) log_file.write('Number of texture files = %s\n' % len(texture_files)) log_file.write( 'Number of unique texture files = %s\n\n' % len(texture_files_unique)) log_file.write('vertex colors = %s\n' % vert_colors) log_file.write('face colors = %s\n' % face_colors) log_file.close() colors = {'texture':bool(texture_files), 'vert_colors':vert_colors, 'face_colors':face_colors} return texture_files, texture_files_unique, material_file, colors
Set default output mask options based on file extension Note: v1. 34BETA changed - om switch to - m Possible options ( not all options are available for every format ): vc - > vertex colors vf - > vertex flags vq - > vertex quality vn - > vertex normals vt - > vertex texture coords fc - > face colors ff - > face flags fq - > face quality fn - > face normals wc - > wedge colors wn - > wedge normals wt - > wedge texture coords
def default_output_mask(file_out, texture=True, vert_normals=True, vert_colors=False, face_colors=False, ml_version=ML_VERSION): """ Set default output mask options based on file extension Note: v1.34BETA changed -om switch to -m Possible options (not all options are available for every format): vc -> vertex colors vf -> vertex flags vq -> vertex quality vn -> vertex normals vt -> vertex texture coords fc -> face colors ff -> face flags fq -> face quality fn -> face normals wc -> wedge colors wn -> wedge normals wt -> wedge texture coords """ vn = '' wt = '' vc = '' fc = '' if ml_version < '1.3.4': om = '-om' else: om = '-m' fext = os.path.splitext(file_out)[1][1:].strip().lower() if fext in ['stl', 'dxf', 'xyz']: om = '' texture = False vert_normals = False vert_colors = False face_colors = False # elif fext == 'ply': # vert_colors = True if vert_normals: vn = ' vn' if texture: wt = ' wt' if vert_colors: vc = ' vc' if face_colors: fc = ' fc' output_mask = '{}{}{}{}{}'.format(om, vn, wt, vc, fc) return output_mask
Create new mlx script and write opening tags.
def begin(script='TEMP3D_default.mlx', file_in=None, mlp_in=None): """Create new mlx script and write opening tags. Performs special processing on stl files. If no input files are provided this will create a dummy file and delete it as the first filter. This works around the meshlab limitation that it must be provided an input file, even if you will be creating a mesh as the first filter. """ script_file = open(script, 'w') script_file.write(''.join(['<!DOCTYPE FilterScript>\n', '<FilterScript>\n'])) script_file.close() current_layer = -1 last_layer = -1 stl = False # Process project files first if mlp_in is not None: # make a list if it isn't already if not isinstance(mlp_in, list): mlp_in = [mlp_in] for val in mlp_in: tree = ET.parse(val) #root = tree.getroot() for elem in tree.iter(tag='MLMesh'): filename = (elem.attrib['filename']) current_layer += 1 last_layer += 1 # If the mesh file extension is stl, change to that layer and # run clean.merge_vert if os.path.splitext(filename)[1][1:].strip().lower() == 'stl': layers.change(script, current_layer) clean.merge_vert(script) stl = True # Process separate input files next if file_in is not None: # make a list if it isn't already if not isinstance(file_in, list): file_in = [file_in] for val in file_in: current_layer += 1 last_layer += 1 # If the mesh file extension is stl, change to that layer and # run clean.merge_vert if os.path.splitext(val)[1][1:].strip().lower() == 'stl': layers.change(script, current_layer) clean.merge_vert(script) stl = True # If some input files were stl, we need to change back to the last layer if stl: layers.change(script, last_layer) # Change back to the last layer elif last_layer == -1: # If no input files are provided, create a dummy file # with a single vertex and delete it first in the script. # This works around the fact that meshlabserver will # not run without an input file. file_in = ['TEMP3D.xyz'] file_in_descriptor = open(file_in[0], 'w') file_in_descriptor.write('0 0 0') file_in_descriptor.close() layers.delete(script) return current_layer, last_layer
Create mlp file mlp_mesh ( list containing dictionary ) filename * label matrix
def create_mlp(file_out, mlp_mesh=None, mlp_raster=None): """ Create mlp file mlp_mesh (list containing dictionary) filename* label matrix mlp_raster filename* label semantic camera trans_vector* rotation_matrix* focal_length* image_px* image_res_mm_per_px* lens_distortion center_px * Required http://vcg.isti.cnr.it/~cignoni/newvcglib/html/shot.html """ # Opening lines mlp_file = open(file_out, 'w') mlp_file.write('\n'.join([ '<!DOCTYPE MeshLabDocument>', '<MeshLabProject>\n'])) mlp_file.close() if mlp_mesh is not None: mlp_file = open(file_out, 'a') mlp_file.write(' <MeshGroup>\n') for i, val in enumerate(mlp_mesh): if 'label' not in mlp_mesh[i]: mlp_mesh[i]['label'] = mlp_mesh[i]['filename'] if 'matrix' not in mlp_mesh[i]: mlp_mesh[i]['matrix'] = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]] mlp_file.write(' <MLMesh filename="{}" label="{}">\n'.format(mlp_mesh[i]['filename'], mlp_mesh[i]['label'])) mlp_file.write('\n'.join([ ' <MLMatrix44>', '{m[0]} {m[1]} {m[2]} {m[3]} '.format(m=mlp_mesh[i]['matrix'][0]), '{m[0]} {m[1]} {m[2]} {m[3]} '.format(m=mlp_mesh[i]['matrix'][1]), '{m[0]} {m[1]} {m[2]} {m[3]} '.format(m=mlp_mesh[i]['matrix'][2]), '{m[0]} {m[1]} {m[2]} {m[3]} '.format(m=mlp_mesh[i]['matrix'][3]), '</MLMatrix44>', ' </MLMesh>\n'])) mlp_file.write(' </MeshGroup>\n') mlp_file.close() # print(mlp_mesh) else: mlp_file = open(file_out, 'a') mlp_file.write(' <MeshGroup/>\n') mlp_file.close() if mlp_raster is not None: mlp_file = open(file_out, 'a') mlp_file.write(' <RasterGroup>\n') for i, val in enumerate(mlp_raster): if 'label' not in mlp_raster[i]: mlp_raster[i]['label'] = mlp_raster[i]['filename'] if 'semantic' not in mlp_raster[i]: mlp_raster[i]['semantic'] = 1 if 'lens_distortion' not in mlp_raster[i]['camera']: mlp_raster[i]['camera']['lens_distortion'] = [0, 0] if 'center_px' not in mlp_raster[i]['camera']: mlp_raster[i]['camera']['center_px'] = [int(mlp_raster[i]['camera']['image_px'][0]/2), int(mlp_raster[i]['camera']['image_px'][1]/2)] mlp_file.write(' <MLRaster label="{}">\n'.format(mlp_raster[i]['label'])) mlp_file.write(' '.join([ ' <VCGCamera', 'TranslationVector="{m[0]} {m[1]} {m[2]} {m[3]}"'.format(m=mlp_raster[i]['camera']['trans_vector']), 'RotationMatrix="{m[0][0]} {m[0][1]} {m[0][2]} {m[0][3]} {m[1][0]} {m[1][1]} {m[1][2]} {m[1][3]} {m[2][0]} {m[2][1]} {m[2][2]} {m[2][3]} {m[3][0]} {m[3][1]} {m[3][2]} {m[3][3]} "'.format(m=mlp_raster[i]['camera']['rotation_matrix']), 'FocalMm="{}"'.format(mlp_raster[i]['camera']['focal_length']), 'ViewportPx="{m[0]} {m[1]}"'.format(m=mlp_raster[i]['camera']['image_px']), 'PixelSizeMm="{m[0]} {m[1]}"'.format(m=mlp_raster[i]['camera']['image_res_mm_per_px']), 'LensDistortion="{m[0]} {m[1]}"'.format(m=mlp_raster[i]['camera']['lens_distortion']), 'CenterPx="{m[0]} {m[1]}"'.format(m=mlp_raster[i]['camera']['center_px']), '/>\n'])) mlp_file.write(' <Plane semantic="{}" fileName="{}"/>\n'.format(mlp_raster[i]['semantic'], mlp_raster[i]['filename'])) mlp_file.write(' </MLRaster>\n') mlp_file.write(' </RasterGroup>\n') mlp_file.close() # print(mlp_raster) else: mlp_file = open(file_out, 'a') mlp_file.write(' <RasterGroup/>\n') mlp_file.close() # Closing lines mlp_file = open(file_out, 'a') mlp_file.write('</MeshLabProject>\n') mlp_file.close() return
Add new mesh layer to the end of the stack
def add_layer(self, label, change_layer=True): """ Add new mesh layer to the end of the stack Args: label (str): new label for the mesh layer change_layer (bool): change to the newly created layer """ self.layer_stack.insert(self.last_layer() + 1, label) if change_layer: self.set_current_layer(self.last_layer()) return None
Delete mesh layer
def del_layer(self, layer_num): """ Delete mesh layer """ del self.layer_stack[layer_num] # Adjust current layer if needed if layer_num < self.current_layer(): self.set_current_layer(self.current_layer() - 1) return None
Save filter script to an mlx file
def save_to_file(self, script_file): """ Save filter script to an mlx file """ # TODO: rasie exception here instead? if not self.filters: print('WARNING: no filters to save to file!') script_file_descriptor = open(script_file, 'w') script_file_descriptor.write(''.join(self.opening + self.filters + self.closing)) script_file_descriptor.close()
Run the script
def run_script(self, log=None, ml_log=None, mlp_out=None, overwrite=False, file_out=None, output_mask=None, script_file=None, print_meshlabserver_output=True): """ Run the script """ temp_script = False temp_ml_log = False if self.__no_file_in: # If no input files are provided, create a dummy file # with a single vertex and delete it first in the script. # This works around the fact that meshlabserver will # not run without an input file. temp_file_in_file = tempfile.NamedTemporaryFile(delete=False, suffix='.xyz', dir=os.getcwd()) temp_file_in_file.write(b'0 0 0') temp_file_in_file.close() self.file_in = [temp_file_in_file.name] if not self.filters: script_file = None elif script_file is None: # Create temporary script file temp_script = True temp_script_file = tempfile.NamedTemporaryFile(delete=False, suffix='.mlx') temp_script_file.close() self.save_to_file(temp_script_file.name) script_file = temp_script_file.name if (self.parse_geometry or self.parse_topology or self.parse_hausdorff) and (ml_log is None): # create temp ml_log temp_ml_log = True ml_log_file = tempfile.NamedTemporaryFile(delete=False, suffix='.txt') ml_log_file.close() ml_log = ml_log_file.name if file_out is None: file_out = self.file_out run(script=script_file, log=log, ml_log=ml_log, mlp_in=self.mlp_in, mlp_out=mlp_out, overwrite=overwrite, file_in=self.file_in, file_out=file_out, output_mask=output_mask, ml_version=self.ml_version, print_meshlabserver_output=print_meshlabserver_output) # Parse output # TODO: record which layer this is associated with? if self.parse_geometry: self.geometry = compute.parse_geometry(ml_log, log, print_output=print_meshlabserver_output) if self.parse_topology: self.topology = compute.parse_topology(ml_log, log, print_output=print_meshlabserver_output) if self.parse_hausdorff: self.hausdorff_distance = compute.parse_hausdorff(ml_log, log, print_output=print_meshlabserver_output) # Delete temp files if self.__no_file_in: os.remove(temp_file_in_file.name) if temp_script: os.remove(temp_script_file.name) if temp_ml_log: os.remove(ml_log_file.name)
Run main script
def main(): """Run main script""" # segments = number of segments to use for circles segments = 50 # star_points = number of points (or sides) of the star star_points = 5 # star_radius = radius of circle circumscribing the star star_radius = 2 # ring_thickness = thickness of the colored rings ring_thickness = 1 # sphere_radius = radius of sphere the shield will be deformed to sphere_radius = 2 * (star_radius + 3 * ring_thickness) # Star calculations: # Visually approximate a star by using multiple diamonds (i.e. scaled # squares) which overlap in the center. For the star calculations, # consider a central polygon with triangles attached to the edges, all # circumscribed by a circle. # polygon_radius = distance from center of circle to polygon edge midpoint polygon_radius = star_radius / \ (1 + math.tan(math.radians(180 / star_points)) / math.tan(math.radians(90 / star_points))) # width = 1/2 width of polygon edge/outer triangle bottom width = polygon_radius * math.tan(math.radians(180 / star_points)) # height = height of outer triangle height = width / math.tan(math.radians(90 / star_points)) shield = mlx.FilterScript(file_out="shield.ply") # Create the colored front of the shield using several concentric # annuluses; combine them together and subdivide so we have more vertices # to give a smoother deformation later. mlx.create.annulus(shield, radius=star_radius, cir_segments=segments, color='blue') mlx.create.annulus(shield, radius1=star_radius + ring_thickness, radius2=star_radius, cir_segments=segments, color='red') mlx.create.annulus(shield, radius1=star_radius + 2 * ring_thickness, radius2=star_radius + ring_thickness, cir_segments=segments, color='white') mlx.create.annulus(shield, radius1=star_radius + 3 * ring_thickness, radius2=star_radius + 2 * ring_thickness, cir_segments=segments, color='red') mlx.layers.join(shield) mlx.subdivide.midpoint(shield, iterations=2) # Create the inside surface of the shield & translate down slightly so it # doesn't overlap the front. mlx.create.annulus(shield, radius1=star_radius + 3 * ring_thickness, cir_segments=segments, color='silver') mlx.transform.rotate(shield, axis='y', angle=180) mlx.transform.translate(shield, value=[0, 0, -0.005]) mlx.subdivide.midpoint(shield, iterations=4) # Create a diamond for the center star. First create a plane, specifying # extra vertices to support the final deformation. The length from the # center of the plane to the corners should be 1 for ease of scaling, so # we use a side length of sqrt(2) (thanks Pythagoras!). Rotate the plane # by 45 degrees and scale it to stretch it out per the calculations above, # then translate it into place (including moving it up in z slightly so # that it doesn't overlap the shield front). mlx.create.grid(shield, size=math.sqrt(2), x_segments=10, y_segments=10, center=True, color='white') mlx.transform.rotate(shield, axis='z', angle=45) mlx.transform.scale(shield, value=[width, height, 1]) mlx.transform.translate(shield, value=[0, polygon_radius, 0.001]) # Duplicate the diamond and rotate the duplicates around, generating the # star. for _ in range(1, star_points): mlx.layers.duplicate(shield) mlx.transform.rotate(shield, axis='z', angle=360 / star_points) # Combine everything together and deform using a spherical function. mlx.layers.join(shield) mlx.transform.vert_function(shield, z_func='sqrt(%s-x^2-y^2)-%s+z' % (sphere_radius**2, sphere_radius)) # Run the script using meshlabserver and generate the model shield.run_script() return None
Select & delete the small disconnected parts ( components ) of a mesh.
def small_parts(script, ratio=0.2, non_closed_only=False): """ Select & delete the small disconnected parts (components) of a mesh. Args: script: the FilterScript object or script filename to write the filter to. ratio (float): This ratio (between 0 and 1) defines the meaning of 'small' as the threshold ratio between the number of faces of the largest component and the other ones. A larger value will select more components. non_closed_only (bool): Select only non-closed components. Layer stack: No impacts MeshLab versions: 2016.12 1.3.4BETA """ select.small_parts(script, ratio, non_closed_only) selected(script) return None
Delete selected vertices and/ or faces
def selected(script, face=True, vert=True): """ Delete selected vertices and/or faces Note: if the mesh has no faces (e.g. a point cloud) you must set face=False, or the vertices will not be deleted Args: script: the FilterScript object or script filename to write the filter to. face (bool): if True the selected faces will be deleted. If vert is also True, then all the vertices surrounded by those faces will also be deleted. Note that if no faces are selected (only vertices) then this filter will not do anything. For example, if you want to delete a point cloud selection, you must set this to False. vert (bool): if True the selected vertices will be deleted. Layer stack: No impacts MeshLab versions: 2016.12 1.3.4BETA """ if face and vert: filter_xml = ' <filter name="Delete Selected Faces and Vertices"/>\n' elif face and not vert: filter_xml = ' <filter name="Delete Selected Faces"/>\n' elif not face and vert: filter_xml = ' <filter name="Delete Selected Vertices"/>\n' util.write_filter(script, filter_xml) return None
Check for every vertex on the mesh: if it is NOT referenced by a face removes it.
def unreferenced_vert(script): """ Check for every vertex on the mesh: if it is NOT referenced by a face, removes it. Args: script: the FilterScript object or script filename to write the filter to. Layer stack: No impacts MeshLab versions: 2016.12 1.3.4BETA """ if script.ml_version == '1.3.4BETA': filter_xml = ' <filter name="Remove Unreferenced Vertex"/>\n' else: filter_xml = ' <filter name="Remove Unreferenced Vertices"/>\n' util.write_filter(script, filter_xml) return None
Check for every vertex on the mesh: if there are two vertices with the same coordinates they are merged into a single one.
def duplicate_verts(script): """ "Check for every vertex on the mesh: if there are two vertices with the same coordinates they are merged into a single one. Args: script: the FilterScript object or script filename to write the filter to. Layer stack: No impacts MeshLab versions: 2016.12 1.3.4BETA """ if script.ml_version == '1.3.4BETA': filter_xml = ' <filter name="Remove Duplicated Vertex"/>\n' else: filter_xml = ' <filter name="Remove Duplicate Vertices"/>\n' util.write_filter(script, filter_xml) return None
Compute the Hausdorff Distance between two meshes sampling one of the two and finding for each sample the closest point over the other mesh.
def hausdorff_distance(script, sampled_layer=1, target_layer=0, save_sample=False, sample_vert=True, sample_edge=True, sample_faux_edge=False, sample_face=True, sample_num=1000, maxdist=10): """ Compute the Hausdorff Distance between two meshes, sampling one of the two and finding for each sample the closest point over the other mesh. Args: script: the FilterScript object or script filename to write the filter to. sampled_layer (int): The mesh layer whose surface is sampled. For each sample we search the closest point on the target mesh layer. target_layer (int): The mesh that is sampled for the comparison. save_sample (bool): Save the position and distance of all the used samples on both the two surfaces, creating two new layers with two point clouds representing the used samples. sample_vert (bool): For the search of maxima it is useful to sample vertices and edges of the mesh with a greater care. It is quite probable that the farthest points falls along edges or on mesh vertexes, and with uniform montecarlo sampling approaches the probability of taking a sample over a vertex or an edge is theoretically null. On the other hand this kind of sampling could make the overall sampling distribution slightly biased and slightly affects the cumulative results. sample_edge (bool): see sample_vert sample_faux_edge (bool): see sample_vert sample_face (bool): see sample_vert sample_num (int): The desired number of samples. It can be smaller or larger than the mesh size, and according to the chosen sampling strategy it will try to adapt. maxdist (int): Sample points for which we do not find anything within this distance are rejected and not considered neither for averaging nor for max. Layer stack: If save_sample is True, two new layers are created: 'Hausdorff Closest Points' and 'Hausdorff Sample Point'; and the current layer is changed to the last newly created layer. If save_sample is False, no impacts MeshLab versions: 2016.12 1.3.4BETA """ # MeshLab defaults: # sample_num = number of vertices # maxdist = 0.05 * AABB['diag'] #5% of AABB[diag] # maxdist_max = AABB['diag'] maxdist_max = 2*maxdist # TODO: parse output (min, max, mean, etc.) filter_xml = ''.join([ ' <filter name="Hausdorff Distance">\n', ' <Param name="SampledMesh" ', 'value="{:d}" '.format(sampled_layer), 'description="Sampled Mesh" ', 'type="RichMesh" ', '/>\n', ' <Param name="TargetMesh" ', 'value="{:d}" '.format(target_layer), 'description="Target Mesh" ', 'type="RichMesh" ', '/>\n', ' <Param name="SaveSample" ', 'value="{}" '.format(str(save_sample).lower()), 'description="Save Samples" ', 'type="RichBool" ', '/>\n', ' <Param name="SampleVert" ', 'value="{}" '.format(str(sample_vert).lower()), 'description="Sample Vertexes" ', 'type="RichBool" ', '/>\n', ' <Param name="SampleEdge" ', 'value="{}" '.format(str(sample_edge).lower()), 'description="Sample Edges" ', 'type="RichBool" ', '/>\n', ' <Param name="SampleFauxEdge" ', 'value="{}" '.format(str(sample_faux_edge).lower()), 'description="Sample FauxEdge" ', 'type="RichBool" ', '/>\n', ' <Param name="SampleFace" ', 'value="{}" '.format(str(sample_face).lower()), 'value="%s" ' % str(sample_face).lower() + 'description="Sample Faces" ', 'type="RichBool" ', '/>\n', ' <Param name="SampleNum" ', 'value="{:d}" '.format(sample_num), 'description="Number of samples" ', 'type="RichInt" ', '/>\n', ' <Param name="MaxDist" ', 'value="{}" '.format(maxdist), 'value="%s" ' % maxdist + 'description="Max Distance" ', 'min="0" ', 'max="{}" '.format(maxdist_max), 'type="RichAbsPerc" ', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) if isinstance(script, FilterScript): script.parse_hausdorff = True if isinstance(script, FilterScript) and save_sample: script.add_layer('Hausdorff Closest Points') script.add_layer('Hausdorff Sample Point') return None
Create a new layer populated with a point sampling of the current mesh.
def poisson_disk(script, sample_num=1000, radius=0.0, montecarlo_rate=20, save_montecarlo=False, approx_geodesic_dist=False, subsample=False, refine=False, refine_layer=0, best_sample=True, best_sample_pool=10, exact_num=False, radius_variance=1.0): """ Create a new layer populated with a point sampling of the current mesh. Samples are generated according to a Poisson-disk distribution, using the algorithm described in: 'Efficient and Flexible Sampling with Blue Noise Properties of Triangular Meshes' Massimiliano Corsini, Paolo Cignoni, Roberto Scopigno IEEE TVCG 2012 Args: script: the FilterScript object or script filename to write the filter to. sample_num (int): The desired number of samples. The radius of the disk is calculated according to the sampling density. radius (float): If not zero this parameter overrides the previous parameter to allow exact radius specification. montecarlo_rate (int): The over-sampling rate that is used to generate the intial Monte Carlo samples (e.g. if this parameter is 'K' means that 'K * sample_num' points will be used). The generated Poisson-disk samples are a subset of these initial Monte Carlo samples. Larger numbers slow the process but make it a bit more accurate. save_montecarlo (bool): If True, it will generate an additional Layer with the Monte Carlo sampling that was pruned to build the Poisson distribution. approx_geodesic_dist (bool): If True Poisson-disk distances are computed using an approximate geodesic distance, e.g. an Euclidean distance weighted by a function of the difference between the normals of the two points. subsample (bool): If True the original vertices of the base mesh are used as base set of points. In this case the sample_num should be obviously much smaller than the original vertex number. Note that this option is very useful in the case you want to subsample a dense point cloud. refine (bool): If True the vertices of the refine_layer mesh layer are used as starting vertices, and they will be utterly refined by adding more and more points until possible. refine_layer (int): Used only if refine is True. best_sample (bool): If True it will use a simple heuristic for choosing the samples. At a small cost (it can slow the process a bit) it usually improves the maximality of the generated sampling. best_sample_pool (bool): Used only if best_sample is True. It controls the number of attempts that it makes to get the best sample. It is reasonable that it is smaller than the Monte Carlo oversampling factor. exact_num (bool): If True it will try to do a dicotomic search for the best Poisson-disk radius that will generate the requested number of samples with a tolerance of the 0.5%. Obviously it takes much longer. radius_variance (float): The radius of the disk is allowed to vary between r and r*var. If this parameter is 1 the sampling is the same as the Poisson-disk Sampling. Layer stack: Creates new layer 'Poisson-disk Samples'. Current layer is NOT changed to the new layer (see Bugs). If save_montecarlo is True, creates a new layer 'Montecarlo Samples'. Current layer is NOT changed to the new layer (see Bugs). MeshLab versions: 2016.12 1.3.4BETA Bugs: Current layer is NOT changed to the new layer, which is inconsistent with the majority of filters that create new layers. """ filter_xml = ''.join([ ' <filter name="Poisson-disk Sampling">\n', ' <Param name="SampleNum" ', 'value="{:d}" '.format(sample_num), 'description="Number of samples" ', 'type="RichInt" ', '/>\n', ' <Param name="Radius" ', 'value="{}" '.format(radius), 'description="Explicit Radius" ', 'min="0" ', 'max="100" ', 'type="RichAbsPerc" ', '/>\n', ' <Param name="MontecarloRate" ', 'value="{:d}" '.format(montecarlo_rate), 'description="MonterCarlo OverSampling" ', 'type="RichInt" ', '/>\n', ' <Param name="SaveMontecarlo" ', 'value="{}" '.format(str(save_montecarlo).lower()), 'description="Save Montecarlo" ', 'type="RichBool" ', '/>\n', ' <Param name="ApproximateGeodesicDistance" ', 'value="{}" '.format(str(approx_geodesic_dist).lower()), 'description="Approximate Geodesic Distance" ', 'type="RichBool" ', '/>\n', ' <Param name="Subsample" ', 'value="{}" '.format(str(subsample).lower()), 'description="Base Mesh Subsampling" ', 'type="RichBool" ', '/>\n', ' <Param name="RefineFlag" ', 'value="{}" '.format(str(refine).lower()), 'description="Refine Existing Samples" ', 'type="RichBool" ', '/>\n', ' <Param name="RefineMesh" ', 'value="{:d}" '.format(refine_layer), 'description="Samples to be refined" ', 'type="RichMesh" ', '/>\n', ' <Param name="BestSampleFlag" ', 'value="{}" '.format(str(best_sample).lower()), 'description="Best Sample Heuristic" ', 'type="RichBool" ', '/>\n', ' <Param name="BestSamplePool" ', 'value="{:d}" '.format(best_sample_pool), 'description="Best Sample Pool Size" ', 'type="RichInt" ', '/>\n', ' <Param name="ExactNumFlag" ', 'value="{}" '.format(str(exact_num).lower()), 'description="Exact number of samples" ', 'type="RichBool" ', '/>\n', ' <Param name="RadiusVariance" ', 'value="{}" '.format(radius_variance), 'description="Radius Variance" ', 'type="RichFloat" ', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) if isinstance(script, FilterScript): script.add_layer('Poisson-disk Samples') if save_montecarlo: script.add_layer('Montecarlo Samples') return None
Create a new layer populated with a point sampling of the current mesh at most one sample for each element of the mesh is created.
def mesh_element(script, sample_num=1000, element='VERT'): """ Create a new layer populated with a point sampling of the current mesh, at most one sample for each element of the mesh is created. Samples are taking in a uniform way, one for each element (vertex/edge/face); all the elements have the same probabilty of being choosen. Args: script: the FilterScript object or script filename to write the filter to. sample_num (int): The desired number of elements that must be chosen. Being a subsampling of the original elements if this number should not be larger than the number of elements of the original mesh. element (enum in ['VERT', 'EDGE', 'FACE']): Choose what mesh element will be used for the subsampling. At most one point sample will be added for each one of the chosen elements Layer stack: Creates new layer 'Sampled Mesh'. Current layer is changed to the new layer. MeshLab versions: 2016.12 1.3.4BETA """ if element.lower() == 'vert': element_num = 0 elif element.lower() == 'edge': element_num = 1 elif element.lower() == 'face': element_num = 2 filter_xml = ''.join([ ' <filter name="Mesh Element Subsampling">\n', ' <Param name="Sampling" ', 'value="{:d}" '.format(element_num), 'description="Element to sample:" ', 'enum_val0="Vertex" ', 'enum_val1="Edge" ', 'enum_val2="Face" ', 'enum_cardinality="3" ', 'type="RichEnum" ', '/>\n', ' <Param name="SampleNum" ', 'value="{:d}" '.format(sample_num), 'description="Number of samples" ', 'type="RichInt" ', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) if isinstance(script, FilterScript): script.add_layer('Sampled Mesh') return None
Create a new layer populated with a subsampling of the vertexes of the current mesh
def clustered_vert(script, cell_size=1.0, strategy='AVERAGE', selected=False): """ "Create a new layer populated with a subsampling of the vertexes of the current mesh The subsampling is driven by a simple one-per-gridded cell strategy. Args: script: the FilterScript object or script filename to write the filter to. cell_size (float): The size of the cell of the clustering grid. Smaller the cell finer the resulting mesh. For obtaining a very coarse mesh use larger values. strategy (enum 'AVERAGE' or 'CENTER'): &lt;b>Average&lt;/b>: for each cell we take the average of the sample falling into. The resulting point is a new point.&lt;br>&lt;b>Closest to center&lt;/b>: for each cell we take the sample that is closest to the center of the cell. Choosen vertices are a subset of the original ones. selected (bool): If true only for the filter is applied only on the selected subset of the mesh. Layer stack: Creates new layer 'Cluster Samples'. Current layer is changed to the new layer. MeshLab versions: 2016.12 1.3.4BETA """ if strategy.lower() == 'average': strategy_num = 0 elif strategy.lower() == 'center': strategy_num = 1 filter_xml = ''.join([ ' <filter name="Clustered Vertex Subsampling">\n', ' <Param name="Threshold" ', 'value="{}" '.format(cell_size), 'description="Cell Size" ', 'min="0" ', 'max="1000" ', 'type="RichAbsPerc" ', '/>\n', ' <Param name="Sampling" ', 'value="{:d}" '.format(strategy_num), 'description="Representative Strategy:" ', 'enum_val0="Average" ', 'enum_val1="Closest to center" ', 'enum_cardinality="2" ', 'type="RichEnum" ', '/>\n', ' <Param name="Selected" ', 'value="{}" '.format(str(selected).lower()), 'description="Selected" ', 'type="RichBool" ', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) if isinstance(script, FilterScript): script.add_layer('Cluster Samples') return None
Flat plane parameterization
def flat_plane(script, plane=0, aspect_ratio=False): """Flat plane parameterization """ filter_xml = ''.join([ ' <filter name="Parametrization: Flat Plane ">\n', ' <Param name="projectionPlane"', 'value="%d"' % plane, 'description="Projection plane"', 'enum_val0="XY"', 'enum_val1="XZ"', 'enum_val2="YZ"', 'enum_cardinality="3"', 'type="RichEnum"', 'tooltip="Choose the projection plane"', '/>\n', ' <Param name="aspectRatio"', 'value="%s"' % str(aspect_ratio).lower(), 'description="Preserve Ratio"', 'type="RichBool"', 'tooltip="If checked the resulting parametrization will preserve the original apsect ratio of the model otherwise it will fill up the whole 0..1 uv space"', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
Trivial Per - Triangle parameterization
def per_triangle(script, sidedim=0, textdim=1024, border=2, method=1): """Trivial Per-Triangle parameterization """ filter_xml = ''.join([ ' <filter name="Parametrization: Trivial Per-Triangle ">\n', ' <Param name="sidedim"', 'value="%d"' % sidedim, 'description="Quads per line"', 'type="RichInt"', 'tooltip="Indicates how many triangles have to be put on each line (every quad contains two triangles). Leave 0 for automatic calculation"', '/>\n', ' <Param name="textdim"', 'value="%d"' % textdim, 'description="Texture Dimension (px)"', 'type="RichInt"', 'tooltip="Gives an indication on how big the texture is"', '/>\n', ' <Param name="border"', 'value="%d"' % border, 'description="Inter-Triangle border (px)"', 'type="RichInt"', 'tooltip="Specifies how many pixels to be left between triangles in parametrization domain"', '/>\n', ' <Param name="method"', 'value="%d"' % method, 'description="Method"', 'enum_val0="Basic"', 'enum_val1="Space-optimizing"', 'enum_cardinality="2"', 'type="RichEnum"', 'tooltip="Choose space optimizing to map smaller faces into smaller triangles in parametrizazion domain"' '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
Voronoi Atlas parameterization
def voronoi(script, region_num=10, overlap=False): """Voronoi Atlas parameterization """ filter_xml = ''.join([ ' <filter name="Parametrization: Voronoi Atlas">\n', ' <Param name="regionNum"', 'value="%d"' % region_num, 'description="Approx. Region Num"', 'type="RichInt"', 'tooltip="An estimation of the number of regions that must be generated. Smaller regions could lead to parametrizations with smaller distortion."', '/>\n', ' <Param name="overlapFlag"', 'value="%s"' % str(overlap).lower(), 'description="Overlap"', 'type="RichBool"', 'tooltip="If checked the resulting parametrization will be composed by overlapping regions, e.g. the resulting mesh will have duplicated faces: each region will have a ring of ovelapping duplicate faces that will ensure that border regions will be parametrized in the atlas twice. This is quite useful for building mipmap robust atlases"', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
Isometric parameterization
def isometric(script, targetAbstractMinFaceNum=140, targetAbstractMaxFaceNum=180, stopCriteria=1, convergenceSpeed=1, DoubleStep=True): """Isometric parameterization """ filter_xml = ''.join([ ' <filter name="Iso Parametrization">\n', ' <Param name="targetAbstractMinFaceNum"', 'value="%d"' % targetAbstractMinFaceNum, 'description="Abstract Min Mesh Size"', 'type="RichInt"', 'tooltip="This number and the following one indicate the range face number of the abstract mesh that is used for the parametrization process. The algorithm will choose the best abstract mesh with the number of triangles within the specified interval. If the mesh has a very simple structure this range can be very low and strict; for a roughly spherical object if you can specify a range of [8,8] faces you get a octahedral abstract mesh, e.g. a geometry image. &lt;br>Large numbers (greater than 400) are usually not of practical use."', '/>\n', ' <Param name="targetAbstractMaxFaceNum"', 'value="%d"' % targetAbstractMaxFaceNum, 'description="Abstract Max Mesh Size"', 'type="RichInt"', 'tooltip="Please notice that a large interval requires huge amount of memory to be allocated, in order save the intermediate results. An interval of 40 should be fine."', '/>\n', ' <Param name="stopCriteria"', 'value="%d"' % stopCriteria, 'description="Optimization Criteria"', 'enum_val0="Best Heuristic"', 'enum_val1="Area + Angle"', 'enum_val2="Regularity"', 'enum_val3="L2"', 'enum_cardinality="4"', 'type="RichEnum"', 'tooltip="Choose a metric to stop the parametrization within the interval. 1: Best Heuristic : stop considering both isometry and number of faces of base domain. 2: Area + Angle : stop at minimum area and angle distorsion. 3: Regularity : stop at minimum number of irregular vertices. 4: L2 : stop at minimum OneWay L2 Stretch Eff"', '/>\n', ' <Param name="convergenceSpeed"', 'value="%d"' % convergenceSpeed, 'description="Convergence Precision"', 'type="RichInt"', 'tooltip="This parameter controls the convergence speed/precision of the optimization of the texture coordinates. Larger the number slower the processing and, eventually, slightly better results"', '/>\n', ' <Param name="DoubleStep"', 'value="%s"' % str(DoubleStep).lower(), 'description="Double Step"', 'type="RichBool"', 'tooltip="Use this bool to divide the parameterization in 2 steps. Double step makes the overall process faster and robust. Consider to disable this bool in case the object has topologycal noise or small handles."', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
Isometric parameterization: Build Atlased Mesh
def isometric_build_atlased_mesh(script, BorderSize=0.1): """Isometric parameterization: Build Atlased Mesh This actually generates the UV mapping from the isometric parameterization """ filter_xml = ''.join([ ' <filter name="Iso Parametrization Build Atlased Mesh">\n', ' <Param name="BorderSize"', 'value="%s"' % BorderSize, 'description="BorderSize ratio"', 'min="0.01"', 'max="0.5"', 'type="RichDynamicFloat"', 'tooltip="This parameter controls the amount of space that must be left between each diamond when building the atlas. It directly affects how many triangle are splitted during this conversion. In abstract parametrization mesh triangles can naturally cross the triangles of the abstract domain, so when converting to a standard parametrization we must cut all the triangles that protrudes outside each diamond more than the specified threshold. The unit of the threshold is in percentage of the size of the diamond, the bigger the threshold the less triangles are splitted, but the more UV space is used (wasted)."', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
Isometric parameterization: Save Abstract Domain
def isometric_save(script, AbsName="TEMP3D.abs"): """Isometric parameterization: Save Abstract Domain """ filter_xml = ''.join([ ' <filter name="Iso Parametrization Save Abstract Domain">\n', ' <Param name="AbsName"', 'value="%s"' % AbsName, 'description="Abstract Mesh file"', 'type="RichString"', 'tooltip="The filename where the abstract mesh has to be saved"', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
Isometric parameterization: Load Abstract Domain
def isometric_load(script, AbsName="TEMP3D.abs"): """Isometric parameterization: Load Abstract Domain """ filter_xml = ''.join([ ' <filter name="Iso Parametrization Load Abstract Domain">\n', ' <Param name="AbsName"', 'value="%s"' % AbsName, 'description="Abstract Mesh file"', 'type="RichString"', 'tooltip="The filename of the abstract mesh that has to be loaded"', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
Isometric parameterization: transfer between meshes
def isometric_transfer(script, sourceMesh=0, targetMesh=1): """Isometric parameterization: transfer between meshes Provide the layer numbers of the source and target meshes. """ filter_xml = ''.join([ ' <filter name="Iso Parametrization transfer between meshes">\n', ' <Param name="sourceMesh"', 'value="%s"' % sourceMesh, 'description="Source Mesh"', 'type="RichMesh"', 'tooltip="The mesh already having an Isoparameterization"', '/>\n', ' <Param name="targetMesh"', 'value="%s"' % targetMesh, 'description="Target Mesh"', 'type="RichMesh"', 'tooltip="The mesh to be Isoparameterized"', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
Isometric parameterization: remeshing
def isometric_remesh(script, SamplingRate=10): """Isometric parameterization: remeshing """ filter_xml = ''.join([ ' <filter name="Iso Parametrization Remeshing">\n', ' <Param name="SamplingRate"', 'value="%d"' % SamplingRate, 'description="Sampling Rate"', 'type="RichInt"', 'tooltip="This specify the sampling rate for remeshing."', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
Set texture
def set_texture(script, textName="TEMP3D.png", textDim=1024): """Set texture """ filter_xml = ''.join([ ' <filter name="Set Texture">\n', ' <Param name="textName"', 'value="%s"' % textName, 'description="Texture file"', 'type="RichString"', 'tooltip="If the file exists it will be associated to the mesh else a dummy one will be created"', '/>\n', ' <Param name="textDim"', 'value="%d"' % textDim, 'description="Texture Dimension (px)"', 'type="RichInt"', 'tooltip="If the named texture doesn\'t exists the dummy one will be squared with this size"', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
Set texture
def project_rasters(script, tex_file_out="TEMP3D.png", tex_size=1024, fill_atlas_gaps=False, depth_threshold=0.5, selected=False, use_angle=True, use_distance=True, use_borders=True, use_silhouettes=True, use_alpha=False): """Set texture Creates new texture file tex_file_out = must be png fill_atlas_gaps = setting this to false will leave the unprojected area transparent. This can then be easily composed with the original texture with PIL """ filter_xml = ''.join([ ' <filter name="Project active rasters color to current mesh, filling the texture">\n', ' <Param name="textName"', 'value="%s"' % tex_file_out, 'description="Texture file"', 'type="RichString"', 'tooltip="The texture file to be created"', '/>\n', ' <Param name="texsize"', 'value="%d"' % tex_size, 'description="pixel size of texture image"', 'type="RichInt"', 'tooltip="pixel size of texture image, the image will be a square tsize X tsize, most applications do require that tsize is a power of 2"', '/>\n', ' <Param name="dorefill"', 'value="%s"' % str(fill_atlas_gaps).lower(), 'description="fill atlas gaps"', 'type="RichBool"', 'tooltip="If true, unfilled areas of the mesh are interpolated, to avoid visible seams while mipmapping"', '/>\n', ' <Param name="deptheta"', 'value="%s"' % depth_threshold, 'description="depth threshold"', 'type="RichFloat"', 'tooltip="threshold value for depth buffer projection (shadow buffer)"', '/>\n', ' <Param name="onselection"', 'value="%s"' % str(selected).lower(), 'description="Only on selecton"', 'type="RichBool"', 'tooltip="If true, projection is only done for selected vertices"', '/>\n', ' <Param name="useangle"', 'value="%s"' % str(use_angle).lower(), 'description="use angle weight"', 'type="RichBool"', 'tooltip="If true, color contribution is weighted by pixel view angle"', '/>\n', ' <Param name="usedistance"', 'value="%s"' % str(use_distance).lower(), 'description="use distance weight"', 'type="RichBool"', 'tooltip="If true, color contribution is weighted by pixel view distance"', '/>\n', ' <Param name="useborders"', 'value="%s"' % str(use_borders).lower(), 'description="use image borders weight"', 'type="RichBool"', 'tooltip="If true, color contribution is weighted by pixel distance from image boundaries"', '/>\n', ' <Param name="usesilhouettes"', 'value="%s"' % str(use_silhouettes).lower(), 'description="use depth discontinuities weight"', 'type="RichBool"', 'tooltip="If true, color contribution is weighted by pixel distance from depth discontinuities (external and internal silhouettes)"', '/>\n', ' <Param name="usealpha"', 'value="%s"' % str(use_alpha).lower(), 'description="use image alpha weight"', 'type="RichBool"', 'tooltip="If true, alpha channel of the image is used as additional weight. In this way it is possible to mask-out parts of the images that should not be projected on the mesh. Please note this is not a transparency effect, but just influences the weighting between different images"', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
Set texture
def param_texture_from_rasters(script, textName="TEMP3D.png", texsize=1024, colorCorrection=True, colorCorrectionFilterSize=1, useDistanceWeight=True, useImgBorderWeight=True, useAlphaWeight=False, cleanIsolatedTriangles=True, stretchingAllowed=False, textureGutter=4): """Set texture """ filter_xml = ''.join([ ' <filter name="Parameterization + texturing from registered rasters">\n', ' <Param name="textureSize"', 'value="%d"' % texsize, 'description="Texture size"', 'type="RichInt"', 'tooltip="Specifies the dimension of the generated texture"', '/>\n', ' <Param name="textureName"', 'value="%s"' % textName, 'description="Texture name"', 'type="RichString"', 'tooltip="Specifies the name of the file into which the texture image will be saved"', '/>\n', ' <Param name="colorCorrection"', 'value="%s"' % str(colorCorrection).lower(), 'description="Color correction"', 'type="RichBool"', 'tooltip="If true, the final texture is corrected so as to ensure seamless transitions"', '/>\n', ' <Param name="colorCorrectionFilterSize"', 'value="%d"' % colorCorrectionFilterSize, 'description="Color correction filter"', 'type="RichInt"', 'tooltip="It is the radius (in pixel) of the kernel that is used to compute the difference between corresponding texels in different rasters. Default is 1 that generate a 3x3 kernel. Highest values increase the robustness of the color correction process in the case of strong image-to-geometry misalignments"', '/>\n', ' <Param name="useDistanceWeight"', 'value="%s"' % str(useDistanceWeight).lower(), 'description="Use distance weight"', 'type="RichBool"', 'tooltip="Includes a weight accounting for the distance to the camera during the computation of reference images"', '/>\n', ' <Param name="useImgBorderWeight"', 'value="%s"' % str(useImgBorderWeight).lower(), 'description="Use image border weight"', 'type="RichBool"', 'tooltip="Includes a weight accounting for the distance to the image border during the computation of reference images"', '/>\n', ' <Param name="useAlphaWeight"', 'value="%s"' % str(useAlphaWeight).lower(), 'description="Use image alpha weight"', 'type="RichBool"', 'tooltip="If true, alpha channel of the image is used as additional weight. In this way it is possible to mask-out parts of the images that should not be projected on the mesh. Please note this is not a transparency effect, but just influences the weigthing between different images"', '/>\n', ' <Param name="cleanIsolatedTriangles"', 'value="%s"' % str(cleanIsolatedTriangles).lower(), 'description="Clean isolated triangles"', 'type="RichBool"', 'tooltip="Remove all patches compound of a single triangle by aggregating them to adjacent patches"', '/>\n', ' <Param name="stretchingAllowed"', 'value="%s"' % str(stretchingAllowed).lower(), 'description="UV stretching"', 'type="RichBool"', 'tooltip="If true, texture coordinates are stretched so as to cover the full interval [0,1] for both directions"', '/>\n', ' <Param name="textureGutter"', 'value="%d"' % textureGutter, 'description="Texture gutter"', 'type="RichInt"', 'tooltip="Extra boundary to add to each patch before packing in texture space (in pixels)"', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
Set texture
def param_from_rasters(script, useDistanceWeight=True, useImgBorderWeight=True, useAlphaWeight=False, cleanIsolatedTriangles=True, stretchingAllowed=False, textureGutter=4): """Set texture """ filter_xml = ''.join([ ' <filter name="Parameterization from registered rasters">\n', ' <Param name="useDistanceWeight"', 'value="%s"' % str(useDistanceWeight).lower(), 'description="Use distance weight"', 'type="RichBool"', 'tooltip="Includes a weight accounting for the distance to the camera during the computation of reference images"', '/>\n', ' <Param name="useImgBorderWeight"', 'value="%s"' % str(useImgBorderWeight).lower(), 'description="Use image border weight"', 'type="RichBool"', 'tooltip="Includes a weight accounting for the distance to the image border during the computation of reference images"', '/>\n', ' <Param name="useAlphaWeight"', 'value="%s"' % str(useAlphaWeight).lower(), 'description="Use image alpha weight"', 'type="RichBool"', 'tooltip="If true, alpha channel of the image is used as additional weight. In this way it is possible to mask-out parts of the images that should not be projected on the mesh. Please note this is not a transparency effect, but just influences the weighting between different images"', '/>\n', ' <Param name="cleanIsolatedTriangles"', 'value="%s"' % str(cleanIsolatedTriangles).lower(), 'description="Clean isolated triangles"', 'type="RichBool"', 'tooltip="Remove all patches compound of a single triangle by aggregating them to adjacent patches"', '/>\n', ' <Param name="stretchingAllowed"', 'value="%s"' % str(stretchingAllowed).lower(), 'description="UV stretching"', 'type="RichBool"', 'tooltip="If true, texture coordinates are stretched so as to cover the full interval [0,1] for both directions"', '/>\n', ' <Param name="textureGutter"', 'value="%d"' % textureGutter, 'description="Texture gutter"', 'type="RichInt"', 'tooltip="Extra boundary to add to each patch before packing in texture space (in pixels)"', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
Compute the polyline representing a planar section ( a slice ) of a mesh.
def section(script, axis='z', offset=0.0, surface=False, custom_axis=None, planeref=2): """ Compute the polyline representing a planar section (a slice) of a mesh. If the resulting polyline is closed the result can be filled with a triangular mesh representing the section. Args: script: the mlx.FilterScript object or script filename to write the filter to. axis (str): The slicing plane is perpendicular to this axis. Accepted values are 'x', 'y', or 'z'; any other input will be interpreted as a custom axis (although using 'custom' is recommended for clarity). Upper or lowercase values are accepted. offset (float): Specify an offset of the cross-plane. The offset corresponds to the distance along 'axis' from the point specified in 'planeref'. surface (bool): If True, in addition to a layer with the section polyline, also a layer with a triangulated version of the section polyline will be created. This only works if the section polyline is closed. custom_axis (3 component list or tuple): Specify a custom axis as a 3 component vector (x, y, z); this is ignored unless 'axis' is set to 'custom'. planeref (int): Specify the reference from which the planes are shifted. Valid values are: 0 - Bounding box center 1 - Bounding box min 2 - Origin (default) Layer stack: Creates a new layer '{label}_sect_{axis_name}_{offset}', where 'axis_name' is one of [X, Y, Z, custom] and 'offest' is truncated 'offset' If surface is True, create a new layer '{label}_sect_{axis}_{offset}_mesh' Current layer is changed to the last (newly created) layer MeshLab versions: 2016.12 1.3.4BETA """ # Convert axis name into number if axis.lower() == 'x': axis_num = 0 axis_name = 'X' elif axis.lower() == 'y': axis_num = 1 axis_name = 'Y' elif axis.lower() == 'z': axis_num = 2 axis_name = 'Z' else: # custom axis axis_num = 3 axis_name = 'custom' if custom_axis is None: print('WARNING: a custom axis was selected, however', '"custom_axis" was not provided. Using default (Z).') if custom_axis is None: custom_axis = (0.0, 0.0, 1.0) filter_xml = ''.join([ ' <filter name="Compute Planar Section">\n', ' <Param name="planeAxis" ', 'value="{:d}" '.format(axis_num), 'description="Plane perpendicular to" ', 'enum_val0="X Axis" ', 'enum_val1="Y Axis" ', 'enum_val2="Z Axis" ', 'enum_val3="Custom Axis" ', 'enum_cardinality="4" ', 'type="RichEnum" ', '/>\n', ' <Param name="customAxis" ', 'x="{}" y="{}" z="{}" '.format(custom_axis[0], custom_axis[1], custom_axis[2]), 'description="Custom axis" ', 'type="RichPoint3f" ', '/>\n', ' <Param name="planeOffset" ', 'value="{}" '.format(offset), 'description="Cross plane offset" ', 'type="RichFloat" ', '/>\n', ' <Param name="relativeTo" ', 'value="{:d}" '.format(planeref), 'description="plane reference" ', 'enum_val0="Bounding box center" ', 'enum_val1="Bounding box min" ', 'enum_val2="Origin" ', 'enum_cardinality="3" ', 'type="RichEnum" ', '/>\n', ' <Param name="createSectionSurface" ', 'value="{}" '.format(str(surface).lower()), 'description="Create also section surface" ', 'type="RichBool" ', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) if isinstance(script, mlx.FilterScript): current_layer_label = script.layer_stack[script.current_layer()] script.add_layer('{}_sect_{}_{}'.format(current_layer_label, axis_name, int(offset))) if surface: script.add_layer('{}_sect_{}_{}_mesh'.format(current_layer_label, axis_name, int(offset))) return None
Compute a set of geometric measures of a mesh/ pointcloud.
def measure_geometry(script): """ Compute a set of geometric measures of a mesh/pointcloud. Bounding box extents and diagonal, principal axis, thin shell barycenter (mesh only), vertex barycenter and quality-weighted barycenter (pointcloud only), surface area (mesh only), volume (closed mesh) and Inertia tensor Matrix (closed mesh). Args: script: the mlx.FilterScript object or script filename to write the filter to. Layer stack: No impacts MeshLab versions: 2016.12 1.3.4BETA Bugs: Bounding box extents not computed correctly for some volumes """ filter_xml = ' <xmlfilter name="Compute Geometric Measures"/>\n' util.write_filter(script, filter_xml) if isinstance(script, mlx.FilterScript): script.parse_geometry = True return None
Compute a set of topological measures over a mesh
def measure_topology(script): """ Compute a set of topological measures over a mesh Args: script: the mlx.FilterScript object or script filename to write the filter to. Layer stack: No impacts MeshLab versions: 2016.12 1.3.4BETA """ filter_xml = ' <xmlfilter name="Compute Topological Measures"/>\n' util.write_filter(script, filter_xml) if isinstance(script, mlx.FilterScript): script.parse_topology = True return None
Parse the ml_log file generated by the measure_geometry function.
def parse_geometry(ml_log, log=None, ml_version='2016.12', print_output=False): """Parse the ml_log file generated by the measure_geometry function. Warnings: Not all keys may exist if mesh is not watertight or manifold Args: ml_log (str): MeshLab log file to parse log (str): filename to log output """ # TODO: read more than one occurrence per file. Record in list. aabb = {} geometry = {'aabb':aabb} with open(ml_log) as fread: for line in fread: if 'Mesh Bounding Box min' in line: #2016.12 geometry['aabb']['min'] = (line.split()[4:7]) geometry['aabb']['min'] = [util.to_float(val) for val in geometry['aabb']['min']] if 'Mesh Bounding Box max' in line: #2016.12 geometry['aabb']['max'] = (line.split()[4:7]) geometry['aabb']['max'] = [util.to_float(val) for val in geometry['aabb']['max']] if 'Mesh Bounding Box Size' in line: #2016.12 geometry['aabb']['size'] = (line.split()[4:7]) geometry['aabb']['size'] = [util.to_float(val) for val in geometry['aabb']['size']] if 'Mesh Bounding Box Diag' in line: #2016.12 geometry['aabb']['diagonal'] = util.to_float(line.split()[4]) if 'Mesh Volume' in line: geometry['volume_mm3'] = util.to_float(line.split()[3]) geometry['volume_cm3'] = geometry['volume_mm3'] * 0.001 if 'Mesh Surface' in line: if ml_version == '1.3.4BETA': geometry['area_mm2'] = util.to_float(line.split()[3]) else: geometry['area_mm2'] = util.to_float(line.split()[4]) geometry['area_cm2'] = geometry['area_mm2'] * 0.01 if 'Mesh Total Len of' in line: if 'including faux edges' in line: geometry['total_edge_length_incl_faux'] = util.to_float( line.split()[7]) else: geometry['total_edge_length'] = util.to_float( line.split()[7]) if 'Thin shell barycenter' in line: geometry['barycenter'] = (line.split()[3:6]) geometry['barycenter'] = [util.to_float(val) for val in geometry['barycenter']] if 'Thin shell (faces) barycenter' in line: #2016.12 geometry['barycenter'] = (line.split()[4:7]) geometry['barycenter'] = [util.to_float(val) for val in geometry['barycenter']] if 'Vertices barycenter' in line: #2016.12 geometry['vert_barycenter'] = (line.split()[2:5]) geometry['vert_barycenter'] = [util.to_float(val) for val in geometry['vert_barycenter']] if 'Center of Mass' in line: geometry['center_of_mass'] = (line.split()[4:7]) geometry['center_of_mass'] = [util.to_float(val) for val in geometry['center_of_mass']] if 'Inertia Tensor' in line: geometry['inertia_tensor'] = [] for val in range(3): row = (next(fread, val).split()[1:4]) row = [util.to_float(b) for b in row] geometry['inertia_tensor'].append(row) if 'Principal axes' in line: geometry['principal_axes'] = [] for val in range(3): row = (next(fread, val).split()[1:4]) row = [util.to_float(b) for b in row] geometry['principal_axes'].append(row) if 'axis momenta' in line: geometry['axis_momenta'] = (next(fread).split()[1:4]) geometry['axis_momenta'] = [util.to_float(val) for val in geometry['axis_momenta']] break # stop after we find the first match for key, value in geometry.items(): if log is not None: log_file = open(log, 'a') log_file.write('{:27} = {}\n'.format(key, value)) log_file.close() elif print_output: print('{:27} = {}'.format(key, value)) return geometry
Parse the ml_log file generated by the measure_topology function.
def parse_topology(ml_log, log=None, ml_version='1.3.4BETA', print_output=False): """Parse the ml_log file generated by the measure_topology function. Args: ml_log (str): MeshLab log file to parse log (str): filename to log output Returns: dict: dictionary with the following keys: vert_num (int): number of vertices edge_num (int): number of edges face_num (int): number of faces unref_vert_num (int): number or unreferenced vertices boundry_edge_num (int): number of boundary edges part_num (int): number of parts (components) in the mesh. manifold (bool): True if mesh is two-manifold, otherwise false. non_manifold_edge (int): number of non_manifold edges. non_manifold_vert (int): number of non-manifold verices genus (int or str): genus of the mesh, either a number or 'undefined' if the mesh is non-manifold. holes (int or str): number of holes in the mesh, either a number or 'undefined' if the mesh is non-manifold. """ topology = {'manifold': True, 'non_manifold_E': 0, 'non_manifold_V': 0} with open(ml_log) as fread: for line in fread: if 'V:' in line: vert_edge_face = line.replace('V:', ' ').replace('E:', ' ').replace('F:', ' ').split() topology['vert_num'] = int(vert_edge_face[0]) topology['edge_num'] = int(vert_edge_face[1]) topology['face_num'] = int(vert_edge_face[2]) if 'Unreferenced Vertices' in line: topology['unref_vert_num'] = int(line.split()[2]) if 'Boundary Edges' in line: topology['boundry_edge_num'] = int(line.split()[2]) if 'Mesh is composed by' in line: topology['part_num'] = int(line.split()[4]) if 'non 2-manifold mesh' in line: topology['manifold'] = False if 'non two manifold edges' in line: topology['non_manifold_edge'] = int(line.split()[2]) if 'non two manifold vertexes' in line: topology['non_manifold_vert'] = int(line.split()[2]) if 'Genus is' in line: # undefined or int topology['genus'] = line.split()[2] if topology['genus'] != 'undefined': topology['genus'] = int(topology['genus']) if 'holes' in line: topology['hole_num'] = line.split()[2] if topology['hole_num'] == 'a': topology['hole_num'] = 'undefined' else: topology['hole_num'] = int(topology['hole_num']) for key, value in topology.items(): if log is not None: log_file = open(log, 'a') log_file.write('{:16} = {}\n'.format(key, value)) log_file.close() elif print_output: print('{:16} = {}'.format(key, value)) return topology
Parse the ml_log file generated by the hausdorff_distance function.
def parse_hausdorff(ml_log, log=None, print_output=False): """Parse the ml_log file generated by the hausdorff_distance function. Args: ml_log (str): MeshLab log file to parse log (str): filename to log output Returns: dict: dictionary with the following keys: number_points (int): number of points in mesh min_distance (float): minimum hausdorff distance max_distance (float): maximum hausdorff distance mean_distance (float): mean hausdorff distance rms_distance (float): root mean square distance """ hausdorff_distance = {"min_distance": 0.0, "max_distance": 0.0, "mean_distance": 0.0, "rms_distance": 0.0, "number_points": 0} with open(ml_log) as fread: result = fread.readlines() data = "" for idx, line in enumerate(result): m = re.match(r"\s*Sampled (\d+) pts.*", line) if m is not None: hausdorff_distance["number_points"] = int(m.group(1)) if 'Hausdorff Distance computed' in line: data = result[idx + 2] m = re.match(r"\D+(\d+\.*\d*)\D+(\d+\.*\d*)\D+(\d+\.*\d*)\D+(\d+\.*\d*)", data) hausdorff_distance["min_distance"] = float(m.group(1)) hausdorff_distance["max_distance"] = float(m.group(2)) hausdorff_distance["mean_distance"] = float(m.group(3)) hausdorff_distance["rms_distance"] = float(m.group(4)) for key, value in hausdorff_distance.items(): if log is not None: log_file = open(log, 'a') log_file.write('{:16} = {}\n'.format(key, value)) log_file.close() elif print_output: print('{:16} = {}'.format(key, value)) return hausdorff_distance
Color function using muparser lib to generate new RGBA color for every vertex
def function(script, red=255, green=255, blue=255, alpha=255, color=None): """Color function using muparser lib to generate new RGBA color for every vertex Red, Green, Blue and Alpha channels may be defined by specifying a function for each. See help(mlx.muparser_ref) for muparser reference documentation. It's possible to use the following per-vertex variables in the expression: Variables (per vertex): x, y, z (coordinates) nx, ny, nz (normal) r, g, b, a (color) q (quality) rad (radius) vi (vertex index) vtu, vtv (texture coordinates) ti (texture index) vsel (is the vertex selected? 1 yes, 0 no) and all custom vertex attributes already defined by user. Args: script: the FilterScript object or script filename to write the filter to. red (str [0, 255]): function to generate red component green (str [0, 255]): function to generate green component blue (str [0, 255]): function to generate blue component alpha (str [0, 255]): function to generate alpha component color (str): name of one of the 140 HTML Color Names defined in CSS & SVG. Ref: https://en.wikipedia.org/wiki/Web_colors#X11_color_names If not None this will override the per component variables. Layer stack: No impacts MeshLab versions: 2016.12 1.3.4BETA """ # TODO: add options for HSV # https://www.cs.rit.edu/~ncs/color/t_convert.html if color is not None: red, green, blue, _ = color_name[color.lower()] filter_xml = ''.join([ ' <filter name="Per Vertex Color Function">\n', ' <Param name="x" ', 'value="{}" '.format(str(red).replace('&', '&amp;').replace('<', '&lt;')), 'description="func r = " ', 'type="RichString" ', '/>\n', ' <Param name="y" ', 'value="{}" '.format(str(green).replace('&', '&amp;').replace('<', '&lt;')), 'description="func g = " ', 'type="RichString" ', '/>\n', ' <Param name="z" ', 'value="{}" '.format(str(blue).replace('&', '&amp;').replace('<', '&lt;')), 'description="func b = " ', 'type="RichString" ', '/>\n', ' <Param name="a" ', 'value="{}" '.format(str(alpha).replace('&', '&amp;').replace('<', '&lt;')), 'description="func alpha = " ', 'type="RichString" ', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
Given a Mesh M and a Pointset P the filter projects each vertex of P over M and color M according to the geodesic distance from these projected points. Projection and coloring are done on a per vertex basis.
def voronoi(script, target_layer=0, source_layer=1, backward=True): """ Given a Mesh 'M' and a Pointset 'P', the filter projects each vertex of P over M and color M according to the geodesic distance from these projected points. Projection and coloring are done on a per vertex basis. Args: script: the FilterScript object or script filename to write the filter to. target_layer (int): The mesh layer whose surface is colored. For each vertex of this mesh we decide the color according to the following arguments. source_layer (int): The mesh layer whose vertexes are used as seed points for the color computation. These seeds point are projected onto the target_layer mesh. backward (bool): If True the mesh is colored according to the distance from the frontier of the voronoi diagram induced by the source_layer seeds. Layer stack: No impacts MeshLab versions: 2016.12 1.3.4BETA """ filter_xml = ''.join([ ' <filter name="Voronoi Vertex Coloring">\n', ' <Param name="ColoredMesh" ', 'value="{:d}" '.format(target_layer), 'description="To be Colored Mesh" ', 'type="RichMesh" ', '/>\n', ' <Param name="VertexMesh" ', 'value="{:d}" '.format(source_layer), 'description="Vertex Mesh" ', 'type="RichMesh" ', '/>\n', ' <Param name="backward" ', 'value="{}" '.format(str(backward).lower()), 'description="BackDistance" ', 'type="RichBool" ', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
Color mesh vertices in a repeating sinusiodal rainbow pattern
def cyclic_rainbow(script, direction='sphere', start_pt=(0, 0, 0), amplitude=255 / 2, center=255 / 2, freq=0.8, phase=(0, 120, 240, 0), alpha=False): """ Color mesh vertices in a repeating sinusiodal rainbow pattern Sine wave follows the following equation for each color channel (RGBA): channel = sin(freq*increment + phase)*amplitude + center Args: script: the FilterScript object or script filename to write the filter to. direction (str) = the direction that the sine wave will travel; this and the start_pt determine the 'increment' of the sine function. Valid values are: 'sphere' - radiate sine wave outward from start_pt (default) 'x' - sine wave travels along the X axis 'y' - sine wave travels along the Y axis 'z' - sine wave travels along the Z axis or define the increment directly using a muparser function, e.g. '2x + y'. In this case start_pt will not be used; include it in the function directly. start_pt (3 coordinate tuple or list): start point of the sine wave. For a sphere this is the center of the sphere. amplitude (float [0, 255], single value or 4 term tuple or list): amplitude of the sine wave, with range between 0-255. If a single value is specified it will be used for all channels, otherwise specify each channel individually. center (float [0, 255], single value or 4 term tuple or list): center of the sine wave, with range between 0-255. If a single value is specified it will be used for all channels, otherwise specify each channel individually. freq (float, single value or 4 term tuple or list): frequency of the sine wave. If a single value is specified it will be used for all channels, otherwise specifiy each channel individually. phase (float [0, 360], single value or 4 term tuple or list): phase of the sine wave in degrees, with range between 0-360. If a single value is specified it will be used for all channels, otherwise specify each channel individually. alpha (bool): if False the alpha channel will be set to 255 (full opacity). Layer stack: No impacts MeshLab versions: 2016.12 1.3.4BETA """ start_pt = util.make_list(start_pt, 3) amplitude = util.make_list(amplitude, 4) center = util.make_list(center, 4) freq = util.make_list(freq, 4) phase = util.make_list(phase, 4) if direction.lower() == 'sphere': increment = 'sqrt((x-{})^2+(y-{})^2+(z-{})^2)'.format( start_pt[0], start_pt[1], start_pt[2]) elif direction.lower() == 'x': increment = 'x - {}'.format(start_pt[0]) elif direction.lower() == 'y': increment = 'y - {}'.format(start_pt[1]) elif direction.lower() == 'z': increment = 'z - {}'.format(start_pt[2]) else: increment = direction red_func = '{a}*sin({f}*{i} + {p}) + {c}'.format( f=freq[0], i=increment, p=math.radians(phase[0]), a=amplitude[0], c=center[0]) green_func = '{a}*sin({f}*{i} + {p}) + {c}'.format( f=freq[1], i=increment, p=math.radians(phase[1]), a=amplitude[1], c=center[1]) blue_func = '{a}*sin({f}*{i} + {p}) + {c}'.format( f=freq[2], i=increment, p=math.radians(phase[2]), a=amplitude[2], c=center[2]) if alpha: alpha_func = '{a}*sin({f}*{i} + {p}) + {c}'.format( f=freq[3], i=increment, p=math.radians(phase[3]), a=amplitude[3], c=center[3]) else: alpha_func = 255 function(script, red=red_func, green=green_func, blue=blue_func, alpha=alpha_func) return None
muparser atan2 function
def mp_atan2(y, x): """muparser atan2 function Implements an atan2(y,x) function for older muparser versions (<2.1.0); atan2 was added as a built-in function in muparser 2.1.0 Args: y (str): y argument of the atan2(y,x) function x (str): x argument of the atan2(y,x) function Returns: A muparser string that calculates atan2(y,x) """ return 'if((x)>0, atan((y)/(x)), if(((x)<0) and ((y)>=0), atan((y)/(x))+pi, if(((x)<0) and ((y)<0), atan((y)/(x))-pi, if(((x)==0) and ((y)>0), pi/2, if(((x)==0) and ((y)<0), -pi/2, 0)))))'.replace( 'pi', str(math.pi)).replace('y', y).replace('x', x)
muparser cross product function
def v_cross(u, v): """muparser cross product function Compute the cross product of two 3x1 vectors Args: u (list or tuple of 3 strings): first vector v (list or tuple of 3 strings): second vector Returns: A list containing a muparser string of the cross product """ """ i = u[1]*v[2] - u[2]*v[1] j = u[2]*v[0] - u[0]*v[2] k = u[0]*v[1] - u[1]*v[0] """ i = '(({u1})*({v2}) - ({u2})*({v1}))'.format(u1=u[1], u2=u[2], v1=v[1], v2=v[2]) j = '(({u2})*({v0}) - ({u0})*({v2}))'.format(u0=u[0], u2=u[2], v0=v[0], v2=v[2]) k = '(({u0})*({v1}) - ({u1})*({v0}))'.format(u0=u[0], u1=u[1], v0=v[0], v1=v[1]) return [i, j, k]
Multiply vector by scalar
def v_multiply(scalar, v1): """ Multiply vector by scalar""" vector = [] for i, x in enumerate(v1): vector.append('(({})*({}))'.format(scalar, v1[i])) return vector
A tight ( small inner crossings ) ( p q ) torus knot parametric curve
def torus_knot(t, p=3, q=4, scale=1.0, radius=2.0): """ A tight (small inner crossings) (p,q) torus knot parametric curve Source (for trefoil): https://en.wikipedia.org/wiki/Trefoil_knot """ return ['{scale}*(sin({t}) + ({radius})*sin({p}*({t})))'.format(t=t, p=p, scale=scale, radius=radius), '{scale}*(cos({t}) - ({radius})*cos({p}*({t})))'.format(t=t, p=p, scale=scale, radius=radius), '{scale}*(-sin({q}*({t})))'.format(t=t, q=q, scale=scale)]
Add a new Per - Vertex scalar attribute to current mesh and fill it with the defined function.
def vert_attr(script, name='radius', function='x^2 + y^2'): """ Add a new Per-Vertex scalar attribute to current mesh and fill it with the defined function. The specified name can be used in other filter functions. It's possible to use parenthesis, per-vertex variables and boolean operator: (, ), and, or, <, >, = It's possible to use the following per-vertex variables in the expression: Variables: x, y, z (coordinates) nx, ny, nz (normal) r, g, b, a (color) q (quality) rad vi (vertex index) ?vtu, vtv (texture coordinates) ?ti (texture index) ?vsel (is the vertex selected? 1 yes, 0 no) and all custom vertex attributes already defined by user. Args: script: the FilterScript object or script filename to write the filter] to. name (str): the name of new attribute. You can access attribute in other filters through this name. function (str): function to calculate custom attribute value for each vertex Layer stack: No impacts MeshLab versions: 2016.12 1.3.4BETA """ filter_xml = ''.join([ ' <filter name="Define New Per Vertex Attribute">\n', ' <Param name="name" ', 'value="{}" '.format(name), 'description="Name" ', 'type="RichString" ', '/>\n', ' <Param name="expr" ', 'value="{}" '.format(str(function).replace('&', '&amp;').replace('<', '&lt;')), 'description="Function" ', 'type="RichString" ', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None