Ejemplo n.º 1
0
def get_reference_vector(b_obj):
	"""pick a reference vector for deciding surface category.
	note that we can't pick [0,1,0] because the brep might be on a 45deg angle."""
	base_ref_vect = rs.VectorCreate([0,1,0],[0,0,0])
	up = rs.coerce3dvector([0,0,1])
	down = rs.coerce3dvector([0,0,-1])
	epsilon = 0.5
	
	faces = b_obj.Faces
	print faces.Count
	
	ref_faces = []
	ref_angle_rotation = 90
	for k in faces:
		v = k.NormalAt(0.5,0.5) #top and botom of extrusion have IsSurface = False (why?)
		if not (v.EpsilonEquals(up,epsilon) or v.EpsilonEquals(down,epsilon)):
			ref_faces.append(k)
			angle = rs.VectorAngle(v,base_ref_vect)
			angle = angle%90
			print angle
			ref_angle_rotation = min(ref_angle_rotation,angle)
	
	new_ref_vector = rs.VectorRotate(base_ref_vect,ref_angle_rotation,[0,0,1])
	#debug: verify this angle is good
#	for k in faces:
#		v = k.NormalAt(0.5,0.5) #top and botom of extrusion have IsSurface = False (why?)
#		if not (v.EpsilonEquals(up,epsilon) or v.EpsilonEquals(down,epsilon)):
#			ref_faces.append(k)
#			angle = rs.VectorAngle(v,new_ref_vector)
#			angle = angle%180
#			print angle
	
	return new_ref_vector
Ejemplo n.º 2
0
 def MoveWithVector (treeIn, profPointTreeIn, vectorTreeIn, thicknessIn, angleIn, treeOut):
     
     profMax = GridCornerBig (profPointTreeIn)
     profMin = GridCornerSmall (profPointTreeIn)
     
     max =  GridCornerBig (treeIn)
     
     
     for i in range(treeIn.BranchCount):
         treeBranch = treeIn.Branch(i)
         treePath = treeIn.Path(i)
         
         profBranch = profPointTreeIn.Branch(i)
         vectorBranch = vectorTreeIn.Branch(i)
         thicknessBranch = thicknessIn.Branch(i)
         angleBranch = angleIn.Branch(i)
         
         for j in range(treeBranch.Count):
             elem = treeBranch[j]
             profPoint = profBranch [j]
             vector = vectorBranch [j]
             v = thicknessBranch [j]
             angle = angleBranch [j]
             
             
             if type != 0:
                 elemLapos = rs.AddPoint (elem.X,elem.Y,0)
                 elemLapos = rs.coerce3dvector (elemLapos)
                 
                 #angle = rs.VectorAngle ([1,0,0], elemLapos)
                 betaRad = math.radians (beta)
                 
                 gammaRad = math.radians (angle)
                 
                 if gammaRad > betaRad/2:
                     gammaRad = gammaRad - betaRad/2
                 else:
                     gammaRad = betaRad/2 - gammaRad
                 
                 v = (math.cos (betaRad/2)) / (math.cos (gammaRad)) *v
             
             vec = rs.coerce3dpoint (vector)
             rotVecX = vec.X
             rotVecZ = vec.Y
             rotVecY = vec.Z
             rotVec = rs.AddPoint (rotVecX, rotVecY, rotVecZ)
             rotVec = rs.coerce3dpoint (rotVec)
             ORIGO = rs.AddPoint (0,0,0)
             ORIGO = rs.coerce3dpoint (ORIGO)
             VECTOR = rs.RotateObject(rotVec, ORIGO, angle, [0,0,1])
             
             vector = rs.coerce3dvector (VECTOR)
             vector = vector * v
             
             elem = rs.coerce3dpoint (elem)
             
             MovePoint = rs.MoveObject (elem, vector)
             MovePoint = rs.coerce3dpoint (MovePoint)
             
             treeOut.Add (elem, treePath)
Ejemplo n.º 3
0
def VectorInternalDivision(vector1, vector2, ratio1, ratio2):
    vector1 = rs.coerce3dvector(vector1)
    vector2 = rs.coerce3dvector(vector2)

    return rs.VectorDivide(
        rs.VectorAdd(rs.VectorScale(vector1, ratio2),
                     rs.VectorScale(vector2, ratio1)), ratio1 + ratio2)
Ejemplo n.º 4
0
def Orthogonal(vecIn):
    vecIn = rs.VectorUnitize(vecIn)

    # Pick any vector which isn't aligned to the input
    otherVec = rs.coerce3dvector((1.0, 0.0, 0.0))
    if abs(rs.VectorDotProduct(vecIn, otherVec)) > 0.99:
        otherVec = rs.coerce3dvector((0.0, 1.0, 0.0))

    # Create a unit length orthogonal to both the other one, and the original one
    return rs.VectorUnitize(rs.VectorCrossProduct(vecIn, otherVec))
Ejemplo n.º 5
0
def MakePlan(elevation, viewDepthZ, geos):
    objs = rs.CopyObjects(geos)
    rs.HideObjects(geos)

    ############################################################################
    print "Cutting Plan"
    allCrvs = []

    #Make plane
    plane = Rhino.Geometry.Plane(rs.coerce3dpoint((0, 0, elevation)),
                                 rs.coerce3dvector((0, 0, 1)))
    planeNeg = Rhino.Geometry.Plane(rs.coerce3dpoint((0, 0, viewDepthZ)),
                                    rs.coerce3dvector((0, 0, 1)))

    ############################################################################
    #Partition the geometry

    partitionedObjs = PartitionGeometry(objs, elevation, viewDepthZ)

    ############################################################################
    #Intersection Curves

    #interCrvs = IntersectGeos(partitionedObjs[1], plane)

    ############################################################################
    #Split Geometry
    #Get the bottom half of intersecting objs
    belowObjs = SplitGeometry(partitionedObjs[1], plane)
    print "A"

    #Get the top half of that previous geometry
    visibleObjs = SplitGeometry(partitionedObjs[0] + belowObjs, planeNeg, -1)

    rs.SelectObjects(visibleObjs)
    objs2del = rs.InvertSelectedObjects()
    rs.DeleteObjects(objs2del)
    print "A"
    ############################################################################
    #Make 2D
    allCrvs += ProjectPlan(visibleObjs, plane)

    rs.DeleteObjects(visibleObjs)

    print "Plan Cut"
    rs.ShowObjects(geos)
    rs.HideObjects(allCrvs)
    return allCrvs
Ejemplo n.º 6
0
def get_face_category(f,v):
	"""pick category:
	0: side srfs that get extended
	1: side srfs that get shortened
	2: top surfaces"""
	normal = f.NormalAt(0.5,0.5)
	epsilon = 0.5
	up = rs.coerce3dvector([0,0,1])
	down = rs.coerce3dvector([0,0,-1])
	compare_angle = min(rs.VectorAngle(normal,v),rs.VectorAngle(normal,rs.VectorReverse(v)))
	
	if normal.EpsilonEquals(up,epsilon) or normal.EpsilonEquals(down,epsilon):
		return 2
	elif 88 < compare_angle < 92:
		return 1
	else:
		return 0
Ejemplo n.º 7
0
def IntersectGeo(obj, level):
    tolerance = rs.UnitAbsoluteTolerance()
    plane = rc.Geometry.Plane(rs.coerce3dpoint((0, 0, level)),
                              rs.coerce3dvector((0, 0, 1)))
    finalCurves = []
    #BLOCKS
    if rs.IsBlockInstance(obj):
        matrix = rs.BlockInstanceXform(obj)
        blockObjs = rs.BlockObjects(rs.BlockInstanceName(obj))
        for eachBlockObj in blockObjs:
            newCopy = rs.CopyObject(eachBlockObj)
            xformedObj = rs.TransformObject(newCopy, matrix)

            #EXTRUSIONS
            if isinstance(xformedObj, rc.Geometry.Extrusion):
                temp = sc.doc.Objects.AddBrep(xformedObj.ToBrep(False))
                xformedObj = rs.coercebrep(temp)
                rs.DeleteObject(temp)

            #BREPS IN BLOCK
            result = IntersectBrepPlane(xformedObj, plane)
            if result is None: continue
            for each in result:
                if each is not None:
                    finalCurves.append(each)
            rs.DeleteObject(xformedObj)

            #MESHES IN BLOCK <---This code might not be necessary
            result = IntersectMeshPlane(xformedObj, plane)
            if result is None: continue
            for each in result:
                if each is not None:
                    finalCurves.append(each)
            rs.DeleteObject(xformedObj)

    #BREPS
    elif rs.IsBrep(obj):
        result = IntersectBrepPlane(obj, plane)
        if result is None: return None
        for each in result:
            if each is not None:
                finalCurves.append(each)

    #MESHES
    elif rs.IsMesh(obj):
        result = IntersectMeshPlane(obj, plane)
        if result is None: return None
        for each in result:
            if each is not None:
                finalCurves.append(each)
    return finalCurves
Ejemplo n.º 8
0
def get_surface_outline(b_geo):
    """get the surface outline and project to the surface's baseplane."""
    initial_boundary_guids = []
    initial_boundary_crv = []
    bb = rs.BoundingBox(b_geo)
    proj_plane = Rhino.Geometry.Plane.WorldXY
    proj_plane.Translate(rs.coerce3dvector([0, 0, bb[0].Z]))
    for e in b_geo.Edges:
        initial_boundary_crv.append(
            Rhino.Geometry.Curve.ProjectToPlane(e.EdgeCurve, proj_plane))
    joined_boundary_crv = Rhino.Geometry.Curve.JoinCurves(
        initial_boundary_crv, D_TOL)
    if len(joined_boundary_crv) == 1:
        return joined_boundary_crv
    else:
        print "Script Error: more than one surface boundary outline. Please save this file and report error."
        return None
Ejemplo n.º 9
0
def ImportLighthouseSensorsFromJSON(filename):
    print "Reading", filename
    contents = file(filename).read()
    if "{" not in contents:
        raise Exception("Malformed JSON")
    header = contents[0:contents.find('{')]
    print header

    try:
        layername = os.path.splitext(os.path.basename(filename))[0].lower()
    except:
        layername = "sensors"

    jsonstr = contents[contents.find('{'):]
    data = json.loads(jsonstr)

    originalLayer = rs.CurrentLayer()
    layername = rs.AddLayer(layername)
    rs.CurrentLayer(layername)
    rs.LayerColor(layername, RandomSaturatedColor())

    groupName = rs.AddGroup(layername)

    SENSOR_RADIUS_MM = 3.0
    SENSOR_NORMAL_LENGTH_MM = 8.0

    for point, normal in zip(data['modelPoints'], data['modelNormals']):
        position = rs.coerce3dvector([x * 1000.0 for x in point])
        normal = rs.VectorUnitize(normal)
        normalOrthoA = Orthogonal(normal)
        normalOrthoB = rs.VectorCrossProduct(normalOrthoA, normal)

        objID = rs.AddCircle3Pt(position + SENSOR_RADIUS_MM * normalOrthoA,
                                position - SENSOR_RADIUS_MM * normalOrthoA,
                                position + SENSOR_RADIUS_MM * normalOrthoB)
        rs.AddObjectToGroup(objID, groupName)

        objID = rs.AddLine(position,
                           position + SENSOR_NORMAL_LENGTH_MM * normal)
        rs.AddObjectToGroup(objID, groupName)

    rs.CurrentLayer(originalLayer)
Ejemplo n.º 10
0
def get_building_footprints(building_breps, planes):
    """extract the footprints from the buildings"""
    #rs.EnableRedraw()
    plane_sections = []
    slice_depth = []
    for b in building_breps:
        for i, p in enumerate(planes):
            s = get_section(rs.coercebrep(b), p)
            if s:
                plane_sections.append(s[0])
                slice_depth.append(i)
                break

    for section, d in zip(plane_sections, slice_depth):
        k = wrh.add_curve_to_layer(section, 1)
        #rs.ObjectLayer(k,"Default")
        #print section
    m = zip(plane_sections, slice_depth)
    new_boolean_list = []
    for item in m:
        if item[1] > 0:
            transformation = Rhino.Geometry.Transform.Translation(
                rs.coerce3dvector([0, 0, -THICKNESS]))
            new_crv = item[0].Transform(transformation)
            new_level = item[1] - 1
            new_boolean_list.append((new_crv, new_level))
        else:
            new_boolean_list.append(item)

    a, b = zip(*new_boolean_list)
    #for section,d in zip(a,b):
    #	print section, d

    #rs.Redraw()
    #rs.EnableRedraw(False)
    return
Ejemplo n.º 11
0
 def ProfileCurveThings (treeIn, profCrv, profPointTreeOut, vectorTreeOut, vectorLineTree, tOut):
     
     MaxCoord = GridCornerBig (treeIn)
     x_max = MaxCoord.X
     y_max = MaxCoord.Y
     z_max = MaxCoord.Z
     
     profPointList = []
     profVecDirection = []
     vectorList = []
     curvatureTree = datatree [sys.Object] ()
     directionTree = datatree [sys.Object] ()
     
     
     Crv = rs.coercecurve (profCrv)
     start = rs.CurveStartPoint (Crv)
     end = rs.CurveEndPoint (Crv)
     
     if start.Y > end.Y :
         Crv = rh.Geometry.Curve.Reverse (Crv)
     
     for i in range(treeIn.BranchCount):
         treeBranch = treeIn.Branch(i)
         treePath = treeIn.Path(i)
         
         for j in range(treeBranch.Count):
             
             elem = treeBranch[j]
             x = elem.X
             y = elem.Y
             z = elem.Z
             
             Yarany = y / y_max
             crvPoint = rh.Geometry.Curve.PointAtNormalizedLength(profCrv, Yarany)
             crvPoint = rs.coerce3dpoint (crvPoint)
             
             
             t = rs.CurveClosestPoint (profCrv, crvPoint)
             
             curvature = rs.CurveCurvature(profCrv, t)[4]
             tangent = rs.CurveCurvature(profCrv, t)[1]
             angle1 = rs.VectorAngle ([0,1,0], curvature)
             angle2 = rs.VectorAngle ([0,1,0], tangent)
             
             curvatureRot = curvature
             curvatureRot = rs.coerce3dpoint (curvatureRot)
             
             rs.RotateObject (curvatureRot, [0,0,0], 90, [0,0,1])
             curvatureRot = rs.coerce3dvector (curvatureRot)
             
             angle = rs.VectorAngle (curvatureRot, tangent)
             curvature = rs.coerce3dpoint(curvature)
             
             
             if 179.99 < angle <180.01:
                 angleDirect = 0
             else:
                 angleDirect = 1
             
             profPointList.append (crvPoint)
             profVecDirection.append (angleDirect)
             vectorList.append (curvature)
             
             curvatureTree.Add (curvature, treePath)
             profPointTreeOut.Add (crvPoint, treePath)
             directionTree.Add (angleDirect, treePath)
             tOut.Add (Yarany, treePath)
     
     profPoint_x_List = []
     for i in range (profPointList.Count):
         profPoint = profPointList [i]
         profPoint_x = profPoint.X
         profPoint_x_List.append (profPoint_x)
     
     a = 0
     for i in range (profPoint_x_List.Count):
         x = profPoint_x_List [i]
         Xabs = math.fabs (x)
         if Xabs > a:
             b = i
             a = Xabs
             c = x
         
     directByMax = profVecDirection [b]
     
     vectorByMax = vectorList [b]
     pointByMax = profPointList [b]
     stableByMax = pointByMax
     pointX = math.fabs (stableByMax.X)
     moveByMax = pointByMax
     unitVecByMax = rs.VectorUnitize (vectorByMax)
     rs.MoveObject (moveByMax, 5* unitVecByMax)
     moveX = math.fabs (moveByMax.X)
     
     
     if moveX > pointX:
         mirror = 1
     else:
         mirror = 0
     
     
     for i in range(curvatureTree.BranchCount):
         treeBranch = curvatureTree.Branch(i)
         treePath = curvatureTree.Path(i)
         pointBranch = profPointTreeOut.Branch(i)
         directionBranch = directionTree.Branch(i)
         
         for j in range(treeBranch.Count):
             curvature = treeBranch [j]
             crvPoint = pointBranch [j]
             direction = directionBranch [j]
             
             curvature = rs.coerce3dpoint(curvature)
             
             if mirror == 0:
                 if direction != directByMax:
                     rs.RotateObject (curvature, [0,0,0], 180, [0,0,1])
             
             if mirror == 1:
                 if direction == directByMax:
                     rs.RotateObject (curvature, [0,0,0], 180, [0,0,1])
             
             
             curvature = rs.coerce3dvector(curvature)
             unitCrvVec = rs.VectorUnitize (curvature)
             
             
             if c < 0:
                 unitCrvVec2 = - unitCrvVec
             else:
                 unitCrvVec2 = unitCrvVec
             
             unitCrvVec = rs.coerce3dvector (unitCrvVec)
             unitCrvVec2 = rs.coerce3dvector (unitCrvVec2)
             
             moveCrvPoint = crvPoint + (unitCrvVec*5)
             
             moveCrvPoint = rs.coerce3dpoint (moveCrvPoint)
             vectorLine = rs.AddLine (crvPoint, moveCrvPoint)
             vectorTreeOut.Add (unitCrvVec2, treePath)
             vectorLineTree.Add (vectorLine, treePath)
def FixedFractureGen(n, aspect_ratio=None, sides=None):
    """
    A function to add a fixed number of circles in a cube. It also writes data 
    to fracture data text file for regenerating fracture networks.
    """
    if fracture_shape == 'circle':
        # initialize a to store fractures
        fracture_list = []
        # a loop to insert the fixed number of fractures
        for i in range(n):
            #layer name for the frcature
            layer_name = "FRACTURE_" + str(i + 1)
            #create an istance of Fracture class
            frac = Fracture()
            #store fracture name
            frac.fracture_name = layer_name
            #generate origin for fracture
            origin = GeneratePoint(boxlength)
            #store farcture center
            frac.fracture_center = origin
            #convert the origin to a plane
            plane = InclinePlane(origin)
            #add layer and color
            rs.AddLayer(layer_name, rs.CreateColor(0, 255, 0))
            #make current layer
            rs.CurrentLayer(layer_name)
            #insert the fracture in the domain
            my_circle = rs.AddCircle(plane, radius)
            #circle_list.append(my_circle)
            surf = rs.AddPlanarSrf(my_circle)
            #delete initial fracture drawn which is a curve
            rs.DeleteObject(my_circle)
            #save fracture's GUID
            frac.fracture_GUID = surf[0]
            #append fracture into fracture list
            fracture_list.append(frac)

    elif fracture_shape == 'ellipse':
        #list to store fracture surface GUIDs
        fracture_list = []
        for i in range(n):
            #layer name for the frcature
            layer_name = "FRACTURE_" + str(i + 1)
            #create an istance of Fracture class
            frac = Fracture()
            frac.fracture_name = layer_name
            #generate fracture origin
            origin = GeneratePoint(boxlength)
            frac.fracture_center = origin
            #plane for fracture
            plane = InclinePlane(origin)
            #calculate r_y
            ry = radius / aspect_ratio
            #create layer for fracture
            rs.AddLayer(layer_name, rs.CreateColor(0, 255, 0))
            rs.CurrentLayer(layer_name)
            #draw ellipse
            fracture = rs.AddEllipse(plane, radius, ry)
            # write the plane, r_x and r_y to file for re-plotting
            ##file.write("\n" + str(plane[0]) + "," +  str(plane[1]) + "," +  str(plane[2]) + "," + str(radius) + ","+ str(ry))
            #make fracture a surface
            frac_surf = rs.AddPlanarSrf(fracture)
            #delete initial fracture drawn which is a curve
            rs.DeleteObject(fracture)
            #append surface GUID to list of fracture surfaces
            frac.fracture_GUID = frac_surf[0]
            fracture_list.append(frac)

    elif fracture_shape == 'polygon':
        #list to store fracture surface GUIDs
        fracture_list = []
        #write the shape type
        ##file.write('\npolygon\n')
        for i in range(n):
            layer_name = "FRACTURE_" + str(i + 1)
            frac = Fracture()
            frac.fracture_name = layer_name
            #theta in radian
            theta_rad = (2 * math.pi) / sides
            #theta in degree (interior angles)
            theta_deg = theta_rad * (180 / math.pi)
            #generate origin
            origin = GeneratePoint(boxlength)
            frac.fracture_center = origin
            #create a 3D point object which isn't visible to the rhino document
            pt_01 = rs.coerce3dvector(
                [radius + origin[0], origin[1], origin[2]])
            #empty list to store all points
            points = []
            #a rotation axis
            ax = rs.coerce3dvector([0, 0, 1])
            #loop to generate points for polygon vertices
            #file.write("\n")
            for j in range(sides):
                #rotation transform with rotation from the origin
                trans = rs.XformRotation2(theta_deg * j, ax, origin)
                #transform the original 3D point and append to list
                points.append(rs.PointTransform(pt_01, trans))
            # append the initial point to close the polygon
            points.append(pt_01)
            # create layer for fracture
            # layer_name = "FRACTURE_" + str(i+1)
            rs.AddLayer(layer_name, rs.CreateColor(0, 255, 0))
            rs.CurrentLayer(layer_name)
            # get GUID of created polygon
            polygon = rs.AddPolyline(points)
            # polygon = rs.AddPolyline(points)
            plane = InclinePlane(origin, boxlength)
            cob = rs.XformChangeBasis(rs.WorldXYPlane(), plane)
            shear2d = rs.XformIdentity()
            shear2d[0, 2] = math.tan(math.radians(45.0))
            cob_inverse = rs.XformChangeBasis(plane, rs.WorldXYPlane())
            temp = rs.XformMultiply(shear2d, cob)
            xform = rs.XformMultiply(cob_inverse, temp)
            fracture = rs.TransformObjects(polygon, xform, False)
            # make fracture a surface
            frac_surf = rs.AddPlanarSrf(fracture)
            # delete initial fracture drawn which is a curve
            rs.DeleteObject(fracture)
            frac.fracture_GUID = frac_surf[0]
            fracture_list.append(frac)
    return fracture_list
Ejemplo n.º 13
0
def RandomFractureGen(frac_min,
                      frac_max,
                      radius_min,
                      radius_max,
                      aspect_min=None,
                      aspect_max=None,
                      polysize_min=None,
                      polysize_max=None):
    """
    Funtions to generate fractures of random number and sizes
    
    Parameters
    ----------
    frac_min: int
        minimum number of fractures to generate
    frac_max: int
        maximum number of fractures to generate
    radius_min: float
        minimum size of fractures
    radius_max: float
        maximum number of fractures to generate
    aspect_min: float
        minimum aspect ratio fpr ellipses (Default:None)
    aspect_max: float
        maximum aspect ratio fpr ellipses (Default:None)
    polysize_min: int
        minimum size of polygon (Default:None)
    polysize_max: int
        maximum size of polygon (Default:None)
    """
    # randomly determine the number of fractures to generate
    num_frac = random.randint(frac_min, frac_max)
    # open file and append to it
    file = open(path, 'a')
    if fracture_shape == 'circle':
        # write the shape type
        file.write('\ncircle')
        # initialize list to store fractures
        fracture_list = []
        # loop to generate fractures
        for i in range(num_frac):
            # name the layer
            layer_name = "FRACTURE_" + str(i + 1)
            # an instance of fracture object
            frac = Fracture()
            # get fracture name
            frac.fracture_name = layer_name
            # generate fracture center
            origin = GeneratePoint(boxlength)
            # store fracture center
            frac.fracture_center = origin
            # convert the origin to a plane
            plane = InclinePlane(origin, boxlength)
            # add layer and create color for it
            rs.AddLayer(layer_name, rs.CreateColor(0, 255, 0))
            # make layer current layer
            rs.CurrentLayer(layer_name)
            # generate fracture size
            radius = FractureSize(size_dist, radius_min, radius_max)
            # insert the circle in the domain
            my_circle = rs.AddCircle(plane, radius)
            # write the plane and radius to file for re-plotting
            file.write("\n" + str(plane[0]) + "," + str(plane[1]) + "," +
                       str(plane[2]) + "," + str(radius))
            surf = rs.AddPlanarSrf(my_circle)
            # delete initial fracture drawn which is a curve
            rs.DeleteObject(my_circle)
            # set fracture guid into its object
            frac.fracture_GUID = surf[0]
            fracture_list.append(frac)

    elif fracture_shape == 'ellipse':
        # initialize list to store fractures
        fracture_list = []
        # write the shape type
        file.write('\nellipse')
        for i in range(num_frac):
            # name the layer
            layer_name = "FRACTURE_" + str(i + 1)
            # an instance of fracture object
            frac = Fracture()
            # get fracture name
            frac.fracture_name = layer_name
            # generate fracture center
            origin = GeneratePoint(boxlength)
            # store fracture center
            frac.fracture_center = origin
            # plane for fracture
            plane = InclinePlane(origin, boxlength)
            # randomly generate radius(rx)
            radius = FractureSize(size_dist, radius_min, radius_max)
            # randomly generate aspect ratio
            aspect_ratio = random.randint(aspect_min, aspect_max)
            # calculate r_y
            ry = radius / aspect_ratio
            # add layer with color
            rs.AddLayer(layer_name, rs.CreateColor(0, 255, 0))
            # make current layer
            rs.CurrentLayer(layer_name)
            # draw fracture
            fracture = rs.AddEllipse(plane, radius, ry)
            # write the plane, r_x and r_y to file for re-plotting
            file.write("\n" + str(plane[0]) + "," + str(plane[1]) + "," +
                       str(plane[2]) + "," + str(radius) + "," + str(ry))
            # make fracture a surface
            frac_surf = rs.AddPlanarSrf(fracture)
            # delete initial fracture drawn which is a curve
            rs.DeleteObject(fracture)
            # set fracture guid into its object
            frac.fracture_GUID = frac_surf[0]
            # append fracture guid to list
            fracture_list.append(frac)

    elif fracture_shape == 'polygon':
        # initialize list to store fractures
        fracture_list = []
        # write the shape type
        file.write('\npolygon\n')
        for i in range(num_frac):
            # name the layer
            layer_name = "FRACTURE" + str(i + 1)
            # an instance of fracture class
            frac = Fracture()
            # get farcture name
            frac.fracture_name = layer_name
            # randomly determine the sides of the polygon
            sides = random.randint(polysize_min, polysize_max)
            # theta in radian
            theta_rad = (2 * math.pi) / sides
            # theta in degree (interior angles)
            theta_deg = theta_rad * (180 / math.pi)
            # generate origin
            origin = GeneratePoint(boxlength)
            # save fracture center
            frac.fracture_center = origin
            # randomly generate radius(rx)
            radius = FractureSize(size_dist, radius_min, radius_max)
            # create a 3D point object which isn't visible to the rhino document
            pt_01 = rs.coerce3dvector(
                [radius + origin[0], origin[1], origin[2]])
            # empty list to store all points
            points = []
            # a rotation axis
            ax = rs.coerce3dvector([0, 0, 1])
            # loop to generate points for polygon vertices
            for j in range(sides):
                # rotation transform with rotation from the origin
                trans = rs.XformRotation2(theta_deg * j, ax, origin)
                # transform the original 3D point and append to list
                points.append(rs.PointTransform(pt_01, trans))
                if j == 0:
                    file.write(
                        str(rs.PointTransform(pt_01, trans)[0]) + "," +
                        str(rs.PointTransform(pt_01, trans)[1]) + "," +
                        str(rs.PointTransform(pt_01, trans)[2]) + ",")
                if j != 0:
                    file.write(
                        str(rs.PointTransform(pt_01, trans)[0]) + "," +
                        str(rs.PointTransform(pt_01, trans)[1]) + "," +
                        str(rs.PointTransform(pt_01, trans)[2]) + ",")
            # append the initial point to close the polygon
            points.append(pt_01)
            file.write(
                str(pt_01[0]) + "," + str(pt_01[1]) + "," + str(pt_01[2]) +
                ",")
            # create layer for fracture
            layer_name = "FRACTURE_" + str(i + 1)
            rs.AddLayer(layer_name, rs.CreateColor(0, 255, 0))
            rs.CurrentLayer(layer_name)
            # get GUID of created polygon
            polygon = rs.AddPolyline(points)
            # get the plane
            plane = InclinePlane(origin, boxlength)
            # transform the polygon to the plane
            cob = rs.XformChangeBasis(rs.WorldXYPlane(), plane)
            shear2d = rs.XformIdentity()
            shear2d[0, 2] = math.tan(math.radians(45.0))
            cob_inverse = rs.XformChangeBasis(plane, rs.WorldXYPlane())
            temp = rs.XformMultiply(shear2d, cob)
            xform = rs.XformMultiply(cob_inverse, temp)
            fracture = rs.TransformObjects(polygon, xform, False)
            # write to file
            #file.write(str(origin[0]) + "," + str(origin[1]) + "," + str(origin[2])+ "," )
            file.write(
                str(plane[0]) + "," + str(plane[1]) + "," + str(plane[2]) +
                "," + str(sides) + "\n")
            # make fracture a surface
            frac_surf = rs.AddPlanarSrf(fracture)
            # delete initial fracture drawn which is a curve
            rs.DeleteObject(fracture)
            # set fracture guid into its objects
            frac.fracture_GUID = frac_surf[0]
            # append fracture guid to list
            fracture_list.append(frac)
    # close file
    file.close()
    return fracture_list
Ejemplo n.º 14
0
    1, 1, 1)  #(non uniform scale can throw error someimtes(ex.cirles))
rotationZ = 0
isTilable = False
isTrimmed = False
dblWindowVoidDepth = 0
customSystem = None

#check for object type : Brep or dynamicGeometry instance
if _geometry and _geometry[0]:
    if type(_geometry[0]) == rc.Geometry.Brep:
        newCustomGeometry = _geometry
    elif str(type(_geometry[0])) == "<type 'instance'>":
        newCustomGeometry = _geometry[0]

    if numInputs > 1 and upAxisVector <> None:
        vecUpAxis = rs.coerce3dvector(upAxisVector)
    if numInputs > 2 and placementVector <> None:
        vecPlacement = rs.coerce3dvector(placementVector)
    if numInputs > 3 and scaleVector <> None:
        vecScaleFactor = rs.coerce3dvector(scaleVector)
    if numInputs > 4 and rotation <> None: rotationZ = eval(str(rotation))
    if numInputs > 5 and tilable <> None: isTilable = tilable
    if numInputs > 6 and trimToPanelSize <> None: isTrimmed = trimToPanelSize
    if numInputs > 7 and windowVoidDepth <> None:
        dblWindowVoidDepth = windowVoidDepth

    customSystem = [
        newCustomGeometry, vecPlacement, vecScaleFactor, vecUpAxis, isTilable,
        rotationZ, dblWindowVoidDepth, isTrimmed
    ]
else:
Ejemplo n.º 15
0
def rc_cut_plan(boundary_brep, cut_heights, floor_guids, use_epsilon):

    bb = rs.BoundingBox(boundary_brep)
    max_z = bb[4].Z
    min_z = bb[0].Z
    crv_list, layer_list, refpt_list, bdims_list = [[], [], [], []]

    for i, guids in enumerate(floor_guids):
        if not (min_z < cut_heights[i] < max_z): continue
        outline_crv, internals, refpt, bdims = process_floor(
            guids, boundary_brep, cut_heights[i])

        mp = Rhino.Geometry.AreaMassProperties.Compute(outline_crv)
        outline_crv_centroid = mp.Centroid
        corner_style = Rhino.Geometry.CurveOffsetCornerStyle.Sharp
        offset_crv = outline_crv.Offset(outline_crv_centroid,
                                        rs.coerce3dvector([0, 0, 1]),
                                        THICKNESS, D_TOL, corner_style)
        offset_crv_geometry = offset_crv[0]

        crv_list.append([[offset_crv_geometry], internals])
        layer_list.append([LCUT_INDICES[1], LCUT_INDICES[2]])
        refpt_list.append(refpt)
        bdims_list.append(bdims)
    #...brep conversion may be necessary

    if len(crv_list) == 0:
        print "Error: Cut planes do not intersect the envelope brep"
        return None

    #set base for output.
    xbase = 0
    ybase = 0
    #set the amount to move up from the bottom of the brep for cutting the lower outline.
    #this should be replaced by a projection of the bottom face of the brep.
    epsilon = D_TOL * 2

    select_items = []

    increment = max(d.X for d in bdims_list) + GAP_SIZE * 1
    dplane_list = get_drawing_planes(bdims_list, rs.WorldXYPlane(), GAP_SIZE)
    refplane_list = [rs.MovePlane(rs.WorldXYPlane(), pt) for pt in refpt_list]

    for i, floor in enumerate(crv_list):
        t = Rhino.Geometry.Transform.ChangeBasis(dplane_list[i],
                                                 refplane_list[i])

        for j, layer_crvs in enumerate(floor):
            for c in layer_crvs:
                c.Transform(t)
            select_items.extend(
                wru.add_curves_to_layer(layer_crvs, layer_list[i][j]))

        labelpt = (bdims_list[i].X / 2 + dplane_list[i].Origin.X,
                   bdims_list[i].Y / 2 + dplane_list[i].OriginY, 0)
        td = rs.AddTextDot(str(i + 1), labelpt)
        rs.ObjectLayer(td, "XXX_LCUT_00-GUIDES")
        select_items.append(td)

    rs.UnselectAllObjects()
    rs.SelectObjects(select_items)
    rs.Redraw()
    rs.EnableRedraw(True)
Ejemplo n.º 16
0
if not openStudioIsReady:
    print "Problem loading OSM. Have you let HB fly?"

else:
    osm = ops.Model()

    # BREP
    for i in range(len(breps)):
        brep = breps[i]

        osm_space = ops.Space(osm)
        osm_space.setName("space_{}".format(i))

        # ghlib methods
        faces = ghlib.components.DeconstructBrep(rs.coercebrep(brep))[0]
        brep_vec = rs.coerce3dvector(ghlib.components.Area(brep)[1])

        # SURFACES
        for j in range(len(faces)):

            face = faces[j]

            edges = ghlib.components.DeconstructBrep(face)[1]

            face_curve = rc.Geometry.Curve.JoinCurves(edges, TOL)[0]
            nc = face_curve.ToNurbsCurve()
            points = [nc.Points[i_].Location for i_ in xrange(nc.Points.Count)]
            points.pop()

            # Sort the face normals of your space
            ndist, rndist = get_norm_dist(face_curve, points, brep_vec)