def getRhinoObjsOfSplitters(rhObjs, rhObj_withBrepFace):
    rdObj_withFace = rs.coercerhinoobject(rhObj_withBrepFace)

    rdObjs = []
    for rhObj in rhObjs:
        rdObj = rs.coercerhinoobject(rhObj)
        if isinstance(rdObj, (rd.BrepObject, rd.CurveObject)):
            if rdObj.Id == rdObj_withFace.Id:
                #print "Object to trim ({}) removed from trimming objects.".format(rdObj)
                continue
            rdObjs.append(rdObj)
    return rdObjs
Exemplo n.º 2
0
def bake(geo, doc):
    """
    Bakes geometry from Grasshopper

    :param geo: Geometry to bake
    :param doc: Grasshopper doc
    :return: Rhino ID
    """

    # we create or use some geometry
    geo_id = geo

    # we obtain the reference in the Rhino doc
    sc.doc = doc
    doc_object = rs.coercerhinoobject(geo_id)

    attributes = doc_object.Attributes
    geometry = doc_object.Geometry

    # we change the scriptcontext
    sc.doc = rc.RhinoDoc.ActiveDoc

    # we add both the geometry and the attributes to the Rhino doc
    rhino_line = sc.doc.Objects.Add(geometry, attributes)

    # we put back the original Grasshopper document as default
    sc.doc = doc
    return rhino_line
def SampleSerialization():
    
    # Select baseeobject
    base_id = rs.GetObject('Select object')
    base_obj = rs.coercerhinoobject(base_id)
    
    # Select object to embed
    id = rs.GetObject('Select object to embed')
    geometry = rs.coercegeometry(id)
    print(geometry)
    
    # Convert geometry to bytes
    bytes = GeometryBaseToBytes(geometry)
    print(bytes)
    
    # Add bytes to base object's dictionary
    key = 'test'
    base_obj.Attributes.UserDictionary.Set.Overloads[str,IEnumerable[System.Byte]](key ,bytes)
    
    # Get bytes from base object
    new_bytes = base_obj.Attributes.UserDictionary.GetBytes(key)
    print(new_bytes)

    # Convert bytes to geometry
    new_geometry = BytesToGeometryBase(new_bytes)
    print(new_geometry)
    
    # Add geometry to document
    new_id = sc.doc.Objects.Add(new_geometry)
    print(new_id)
    
    # Remove bytes from dictionary
    base_obj.Attributes.UserDictionary.Remove(key)
Exemplo n.º 4
0
def pre_process():
    # delete all previous user text
    all_objs = rs.AllObjects()
    for obj in all_objs:
        rh_obj = rs.coercerhinoobject(obj)
        rh_obj.Attributes.DeleteAllUserStrings()

    # remove all blocks
    for block in rs.BlockNames():
        rs.DeleteBlock(block)

    # set current layer
    rs.CurrentLayer(relevant_layers_dict["buildings"])

    # remove redundant layers
    for layer_name in rs.LayerNames():
        if layer_name not in relevant_layers_dict.values():
            rs.PurgeLayer(layer_name)

    # get all objects in building layer
    building_objs = rs.ObjectsByLayer(relevant_layers_dict["buildings"])

    for building_obj in building_objs:
        if rs.IsCurve(building_obj) and rs.IsCurveClosed(building_obj):

            # flatten curve to XY plane
            matrix = rs.XformPlanarProjection(rg.Plane.WorldXY)
            rs.TransformObject(building_obj, matrix, copy=False)

            # delete all object with a surface grater or smaller from MIN_BUILDING_AREA_SQ by TOLERANCE or just smaller than MIN_BUILDING_AREA_SQ
            TOLERANCE = 2
            if rs.CurveArea(building_obj)[0] < MIN_BUILDING_AREA_SQM or abs(
                    rs.CurveArea(building_obj)[0] -
                    MIN_BUILDING_AREA_SQM) < TOLERANCE:
                rs.DeleteObject(building_obj)
Exemplo n.º 5
0
def areaTag(pline):
    #get area
    area = rs.CurveArea(pline)[0]
    area = str((int(area * 100)) / 100) + "m2"
    print area

    #move area tag below name tag location
    offset = [0, -2.5, 0]

    #add text tag
    objID = pline
    text = '%<area("' + str(objID) + '")>%m2'

    pt = rs.AddPoint(rs.CurveAreaCentroid(pline)[0])
    rs.MoveObject(pt, offset)
    areaTag = rs.AddText(text, pt, 1, justification=131074)
    rs.DeleteObject(pt)

    parentLayer = rs.ParentLayer(rs.ObjectLayer(pline))
    hostLayer = rs.AddLayer("ANNO_AREA", (128, 128, 128), parent=parentLayer)
    rs.ObjectLayer(areaTag, hostLayer)

    te = rs.coercerhinoobject(areaTag, True, True)
    te.Geometry.TextFormula = text
    te.CommitChanges()
    sc.doc.Views.Redraw()
    return None
Exemplo n.º 6
0
def SortCurves(curves, torrent=0.001):
    """将多条曲线组成的闭合环线,按照首尾相连的顺序重新排列

    """
    newCurves = []
    newCurves.append(curves[0])
    crvs = curves[:]
    del crvs[0]
    startP0 = rs.CurveStartPoint(newCurves[-1])
    for i in range(len(curves) - 1):
        endP0 = rs.CurveEndPoint(newCurves[-1])
        # if (rs.Distance(startP0,endP0)<torrent):
        #    break
        flag = False
        for crv in crvs:
            sp = rs.CurveStartPoint(crv)
            ep = rs.CurveEndPoint(crv)
            if (rs.Distance(sp, endP0) < torrent):
                flag = True
                crvs.remove(crv)
                break
            if (rs.Distance(ep, endP0) < torrent):
                crvObj = rs.coercerhinoobject(crv).Geometry
                crvs.remove(crv)
                crv = ghc.FlipCurve(crvObj)[0]
                print('flip')
                flag = True
                break
        if not flag:
            print('erro:出现孤立的线')
            return None
        newCurves.append(crv)
    return newCurves
def objMatNameToLayer(guids):
    for guid in guids:
        obj = rs.coercerhinoobject(guid)

        #This gets the layers material index
        objLay = rs.ObjectLayer(obj)
        a = rs.LayerMaterialIndex(objLay)

        #This gets the 'By Object' Material Index
        material_index = obj.Attributes.MaterialIndex

        #Get material name from index
        rhino_material = sc.doc.Materials[
            a]  #<This is where you change the material to look up
        material_color = rhino_material.DiffuseColor
        material_name = rhino_material.Name

        print rhino_material.Name
        layer_index = sc.doc.Layers.Find(material_name, True)
        if layer_index >= 0:
            obj.Attributes.LayerIndex = layer_index
            obj.CommitChanges()
        else:
            new_layer_index = sc.doc.Layers.Add(material_name, material_color)
            obj.Attributes.LayerIndex = new_layer_index
            obj.CommitChanges()
Exemplo n.º 8
0
def RunCommand():
  objectIds = rs.GetObjects("Select objects to move")
  if objectIds is None: return

  gp = GetPoint()
  gp.SetCommandPrompt("Point to move from")
  gp.Get()
  if gp.CommandResult() != Result.Success:
    return gp.CommandResult()

  gt = GetTranslation()
  gt.SetCommandPrompt("Point to move to")
  gt.SetBasePoint(gp.Point(), True)
  gt.DrawLineFromPoint(gp.Point(), True)
  gt.GetXform()
  if gt.CommandResult() != Result.Success:
    return gt.CommandResult()

  list = Rhino.Collections.TransformObjectList()
  for id in objectIds:
      rhobj = rs.coercerhinoobject(id, True, True)
      list.Add(rhobj)
  gt.AddTransformObjects(list)

  xform = gt.CalculateTransform(gt.View().ActiveViewport, gt.Point())
  TransformObjects(list, xform, False, False)
  doc.Views.Redraw()
  return Result.Success
Exemplo n.º 9
0
def blkObjs(blkid):
    blockName = rs.BlockInstanceName(blkid)
    objref = rs.coercerhinoobject(blkid)
    idef = objref.InstanceDefinition
    idefIndex = idef.Index

    lvl = levels[rs.GetUserText(blkid, 'level')]
    height = float(lvl['height'])
    xform = rs.BlockInstanceXform(blkid)
    objects = rs.BlockObjects(blockName)
    # masses = map(lambda x: massFromSrf(x, height), objects)
    # newblk = rs.AddBlock(masses, (0,0,0), name=name, delete_input=True)

    # objects.extend(masses)

    newGeometry = []
    newAttributes = []
    for object in objects:
        newGeometry.append(rs.coercegeometry(object))
        ref = Rhino.DocObjects.ObjRef(object)
        attr = ref.Object().Attributes
        attr.SetUserString('blkname', blockName)
        newAttributes.append(attr)

    InstanceDefinitionTable = sc.doc.ActiveDoc.InstanceDefinitions
    InstanceDefinitionTable.ModifyGeometry(idefIndex, newGeometry,
                                           newAttributes)
    # rs.TransformObjects(masses, xform)
    rs.DeleteObjects(masses)
Exemplo n.º 10
0
def align_dims():
    if not sc.doc.Views.ActiveView.ActiveViewport.CameraZ == Rhino.Geometry.Plane.WorldXY.ZAxis:
        print "this works only in top view (world XY)"
        return
    """
    align vertical dimensions horizontally or horizontal dimensions vertically
    version 1.0
    www.studiogijs.nl
    """

    dims = rs.GetObjects("select dims to align", preselect=True, filter=512)
    if not dims:
        return
    p_ref = rs.GetPoint("set basepoint for the dimensions", in_plane=True)
    if not p_ref:
        return
    p_ref = rs.coerce3dpoint(p_ref)

    dims = [rs.coercerhinoobject(dim) for dim in dims]
    for dim in dims:

        vertical = False
        horizontal = False
        rc, e1, e2, a1, a2, dp, tp = dim.Geometry.Get3dPoints()
        if not rc:
            return
        #check arrow endpoints to see if dim is vertical or horizontal
        if a1.Y == a2.Y: horizontal = True
        if a1.X == a2.X: vertical = True

        if not (horizontal or vertical): continue  #next dimension

        #make sure all points are set relative to e1
        #for SetLocations method we need positions of dimension
        #extension lines and text position
        tp -= e1
        p_r = p_ref - e1
        e2 -= e1
        if horizontal:
            #make 2dpoints for setting the new location
            #sometimes dimension plane is inverted
            #depending on where the endpoints wer picked
            px = dim.Geometry.Plane.XAxis.X  #plane x-axis is (1,0,0) or (-1,0,0)
            py = dim.Geometry.Plane.YAxis.Y  #plane y-axis is (0,1,0) or (0,-1,0)
            dp_new = Rhino.Geometry.Point2d(tp.X * px, p_r.Y * py)
            e1_new = Rhino.Geometry.Point2d(0, 0)
            e2_new = Rhino.Geometry.Point2d(e2.X * px, e2.Y * py)
        elif vertical:
            #make 2dpoints for setting the new location
            #notice that vertical dimensions have their plane rotated 90 degrees
            #sometimes dimension plane is inverted
            px = dim.Geometry.Plane.XAxis.Y  #plane x-axis is (0,-1,0) or (0,1,0)
            py = dim.Geometry.Plane.YAxis.X  #plane y-axis is (1,0,0) or (-1,0,0)
            dp_new = Rhino.Geometry.Point2d(tp.Y * px, p_r.X * py)
            e1_new = Rhino.Geometry.Point2d(0, 0)
            e2_new = Rhino.Geometry.Point2d(e2.Y * px, e2.X * py)
        #perform the move
        dim.Geometry.SetLocations(e1_new, e2_new, dp_new)
        dim.CommitChanges()
Exemplo n.º 11
0
def SampleDescribeObject():
    obj_id = rs.GetObject(
        "Select object for displaying detailed object properties")
    if obj_id:
        obj = rs.coercerhinoobject(obj_id)
        log = Rhino.FileIO.TextLog()
        obj.Description(log)
        print log
Exemplo n.º 12
0
def surfaceToMesh(surfaces):
    meshes = []
    for s in surfaces:
        print s
        surfObj = rs.coercerhinoobject(s).Geometry
        m = ghc.MeshBrep(surfObj)
        meshes.append(m)
    mesh = ghc.MeshJoin(meshes)
    return mesh
def docText2Text(pt, section, entry):
    string = section + "\\" + entry
    text = entry + ': %<documenttext("'+ str(string) +'")>%'
    tag = rs.AddText(text, pt, 1, justification = 1)
    
    te = rs.coercerhinoobject(tag, True, True)
    te.Geometry.TextFormula = text
    te.CommitChanges()
    sc.doc.Views.Redraw()
def SampleObjectDescription(obj_id):
    if obj_id:
        obj = rs.coercerhinoobject(obj_id)
        if obj:
            log = Rhino.FileIO.TextLog()
            log.Print(obj.ShortDescription(False))
            obj.Description(log)
            Rhino.UI.Dialogs.ShowTextDialog(log.ToString(),
                                            'Object Description')
Exemplo n.º 15
0
 def UpdateScaleBar(self):
     stepSize = 90/self.numFrames
     self.progress = rs.coercerhinoobject(self.progressBarID).BrepGeometry
     bbox = self.progress.GetBoundingBox(rg.Plane.WorldXY)
     currLength = bbox.Max.X - bbox.Min.X
     xScale = (currLength + stepSize) / currLength
     xform = rg.Transform.Scale(self.plane, xScale, 1, 1)
     self.progress.Transform(xform)
     sc.doc.Objects.Replace(rs.coerceguid(self.progressBarID), self.progress)
Exemplo n.º 16
0
 def bake(self):
     doc_object = rs.coercerhinoobject(rs.CopyObject(self.shape), True,
                                       True)
     geometry = doc_object.Geometry
     attributes = doc_object.Attributes
     scriptcontext.doc = Rhino.RhinoDoc.ActiveDoc
     layer = self.set_layer()
     if not rs.IsLayer(layer):
         rs.AddLayer(layer)
     rhino_brep = scriptcontext.doc.Objects.Add(geometry, attributes)
     rs.ObjectLayer(rhino_brep, layer)
     scriptcontext.doc = ghdoc
Exemplo n.º 17
0
 def __init__(self, skNum, numFrames):
     self.numFrames = numFrames
     self.skNumID = r'9307b2df-e6e2-4c74-8671-b350783d5ff0'
     self.textID = r'7bd51e90-2a02-4532-ab53-563ec9ad6351'
     self.param1ID = r'806cc725-66fb-4d1e-b58e-399232a82585'
     self.param2ID = r'0f1272f2-e148-44e6-8aad-6c4df5ddd485'
     self.param3ID = r'b5089d05-07b4-460c-ae65-8ffcb8b3e8f7'
     self.skNum = rs.coercerhinoobject(self.skNumID)
     self.param1 = rs.coercerhinoobject(self.param1ID)
     self.param2 = rs.coercerhinoobject(self.param2ID)
     self.param3 = rs.coercerhinoobject(self.param3ID)
     self.text = rs.coercerhinoobject(self.textID)
     
     self.progressBarID = r'e0ac605f-ff4d-471d-a5eb-65e1f8b6be94'
     self.progress = rs.coercerhinoobject(self.progressBarID).BrepGeometry
     self.plane = rg.Plane.WorldXY
     self.plane.Origin = rg.Point3d(5,100,85.913)
     
     self.skNum.Geometry.Text = 'sk'+str(skNum)
     self.skNum.CommitChanges()
     self.param1.Geometry.Text = ' '
     self.param1.CommitChanges()
     self.param2.Geometry.Text = ' '
     self.param2.CommitChanges()
     self.param3.Geometry.Text = ' '
     self.param3.CommitChanges()
     
     bbox = self.progress.GetBoundingBox(rg.Plane.WorldXY)
     currLength = bbox.Max.X - bbox.Min.X
     xScale = 1 / currLength
     xform = rg.Transform.Scale(self.plane, xScale, 1, 1)
     self.progress.Transform(xform)
     sc.doc.Objects.Replace(rs.coerceguid(self.progressBarID), self.progress)
Exemplo n.º 18
0
def RemoveFromBlock():
    block = rs.GetObject("Select Block to extract objects from",
                         rs.filter.instance,
                         preselect=True)
    if not block: return

    blockName = rs.BlockInstanceName(block)
    objref = rs.coercerhinoobject(block)
    idef = objref.InstanceDefinition
    idefIndex = idef.Index

    XformBlock = rs.BlockInstanceXform(block)
    blockObjects = rs.BlockObjects(blockName)
    blockInstanceObjects = rs.TransformObjects(blockObjects, XformBlock, True)

    objs = rs.GetObjects("Select Objects to extract from Block",
                         objects=blockInstanceObjects)
    if not objs:
        rs.DeleteObjects(blockInstanceObjects)
        return

    keep = []  #List to keep in block
    delete = []  #list to delete from block and add to doc

    rs.EnableRedraw(False)

    for object in blockInstanceObjects:
        if object in objs: delete.append(object)
        else: keep.append(object)

    if rs.IsBlockReference(blockName):
        print "Block is referenced from file; unable to modify block"
        rs.DeleteObjects(keep)
        return

    rs.TransformObjects(keep, rs.XformInverse(XformBlock), False)

    newGeometry = []
    newAttributes = []
    for object in keep:
        newGeometry.append(rs.coercegeometry(object))
        ref = Rhino.DocObjects.ObjRef(object)
        attr = ref.Object().Attributes
        newAttributes.append(attr)

    InstanceDefinitionTable = sc.doc.ActiveDoc.InstanceDefinitions
    InstanceDefinitionTable.ModifyGeometry(idefIndex, newGeometry,
                                           newAttributes)

    rs.DeleteObjects(keep)
    rs.EnableRedraw(True)
Exemplo n.º 19
0
def BlockTxt(block, str = False, cstr = False, boolFlipHeb=True):
    if not block: return
    
    blockName = rs.BlockInstanceName(block)
    objref = rs.coercerhinoobject(block)
    idef = objref.InstanceDefinition
    idefIndex = idef.Index
    
    XformBlock = rs.BlockInstanceXform(block)
    blockObjects = rs.BlockObjects(blockName)
    
    txtobjs = False
    
    for obj in blockObjects:
        if rs.IsText(obj):
            if not str: txtobjs = True
            elif rs.TextObjectText(obj) == str: txtobjs = True
    
    if txtobjs:
        
        blockInstanceObjects = rs.TransformObjects(blockObjects, XformBlock, True)
        
        keep = []
        
        rs.EnableRedraw(False)
        
        for obj in blockInstanceObjects:
            if rs.IsText(obj):
                if not str and not cstr:
                    str = rs.TextObjectText(obj)
                    cstr = ConvTxt(str, boolFlipHeb)
                if not cstr == str:
                    rs.TextObjectText(obj, cstr)
                keep.append(obj)
            else: keep.append(obj)
        
        rs.TransformObjects(keep, rs.XformInverse(XformBlock), False)
        
        newGeometry = []
        newAttributes = []
        for object in keep:
            newGeometry.append(rs.coercegeometry(object))
            ref = Rhino.DocObjects.ObjRef(object)
            attr = ref.Object().Attributes
            newAttributes.append(attr)
        
        InstanceDefinitionTable = sc.doc.ActiveDoc.InstanceDefinitions
        InstanceDefinitionTable.ModifyGeometry(idefIndex, newGeometry, newAttributes)
        
        rs.DeleteObjects(keep)
Exemplo n.º 20
0
 def getSelctdObjsForSplitters(rhObjs_CurveOrBrep):
     rgCrvs_CrvObjs = []
     rgCrvs_Edges = []
     gBreps_ofEdges = []
     for o in rhObjs_CurveOrBrep:
         rdObj = rs.coercerhinoobject(
             o
         )  # coercecurve returns various rg.Curves, including rg.BrepEdge.
         if rdObj.ObjectType == rd.ObjectType.Curve:
             rgCrvs_CrvObjs.append(rdObj.Geometry)
         elif rdObj.ObjectType == rd.ObjectType.Brep:
             rgNEs = getNakedEdgesOfBrepObject(rdObj)
             for rgNE in rgNEs:
                 rgCrvs_Edges.append(rgNE.DuplicateCurve())
                 gBreps_ofEdges.append(rdObj.Id)
     return rgCrvs_CrvObjs, rgCrvs_Edges, gBreps_ofEdges
Exemplo n.º 21
0
def add_cutters_for_rivets():
    """
    This script adds cylinder objects (as a group named 'rivet-hole-cutters')
    at rivet block positions to easily cut holes into
    the sheet metal objects. 
    
    www.studiogijs.nl
    """
    depth = 12
    origin = Rhino.Geometry.Point3d(0.0, 0.0, -depth / 2)
    direction = Rhino.Geometry.Vector3d(0.0, 0.0, 1.0)
    plane = Rhino.Geometry.Plane(origin, direction)

    blocks = sc.doc.ActiveDoc.InstanceDefinitions

    blocknames = []

    for block in blocks:
        if block.Name != None:
            if block.Name.__contains__("rivet"):
                blocknames.append(block.Name)
    if len(blocknames) == 0:
        print "no rivet block items found in this document"
        return
    rivets = []
    for name in blocknames:
        instances = rs.BlockInstances(name, 0)
        for instance in instances:
            rivets.append(instance)
    cutters = []
    cutter_group = rs.AddGroup("rivet-hole-cutters")
    for rivet in rivets:
        radius = float(
            rs.coercerhinoobject(rivet).InstanceDefinition.Name[-5]) / 2 + 0.15
        circle = Rhino.Geometry.Circle(plane, radius).ToNurbsCurve()
        cyl = Rhino.Geometry.Extrusion.Create(circle, depth, True)
        xform = rs.BlockInstanceXform(rivet)
        trans = Rhino.Geometry.Transform(xform)
        cyl.Transform(trans)
        cutter = sc.doc.Objects.AddExtrusion(cyl)
        rs.AddObjectToGroup(cutter, "rivet-hole-cutters")

    sc.doc.Views.Redraw()
Exemplo n.º 22
0
def moveLight():
    """
    Use this script to move a light in the direction it is aimed.
    Positive values are in the direction it aimed at.
    Typically use this in a toolbar, where you can pass the distance directly.
    script by Gijs de Zwart
    www.studiogijs.nl
    """
    distance = rs.GetInteger(number=10)
    object = rs.GetObject("select light to move in normal direction",
                          preselect=True,
                          filter=256)
    if not object:
        return
    light = rs.coercerhinoobject(object)
    dir = light.LightGeometry.Direction
    dir.Unitize()
    trans = dir * distance
    rs.MoveObject(object, trans)
    rs.SelectObject(object)
Exemplo n.º 23
0
def AddToBlock():
    objects = rs.GetObjects("Choose Objects to Add to Block", preselect=True)
    if not objects: return

    block = rs.GetObject("Choose Block to Add Object to", rs.filter.instance)
    if not block: return

    rs.EnableRedraw(False)

    blockName = rs.BlockInstanceName(block)
    objref = rs.coercerhinoobject(block)
    idef = objref.InstanceDefinition
    idefIndex = idef.Index

    if rs.IsBlockReference(blockName):
        print "Block is referenced from file; unable to add object(s)"
        return

    blnCopy = False

    XformBlock = rs.BlockInstanceXform(block)

    rs.TransformObjects(objects, rs.XformInverse(XformBlock), blnCopy)

    objects.extend(rs.BlockObjects(blockName))

    newGeometry = []
    newAttributes = []
    for object in objects:
        newGeometry.append(rs.coercegeometry(object))
        ref = Rhino.DocObjects.ObjRef(object)
        attr = ref.Object().Attributes
        newAttributes.append(attr)

    InstanceDefinitionTable = sc.doc.ActiveDoc.InstanceDefinitions
    InstanceDefinitionTable.ModifyGeometry(idefIndex, newGeometry,
                                           newAttributes)

    rs.DeleteObjects(objects)

    rs.EnableRedraw(True)
Exemplo n.º 24
0
def SafeMatchObjectAttributes(target, source_id):
    """SafeMatchObjectAttributes(target, source_id)
    target (guid)
    source_id (guid)
    returns: None
    """
    source = rs.coercerhinoobject(source_id, True, True)
    newAttr = rc.DocObjects.ObjectAttributes()
    newAttr.LayerIndex = source.Attributes.LayerIndex
    newAttr.ObjectColor = source.Attributes.ObjectColor
    newAttr.ColorSource = source.Attributes.ColorSource
    newAttr.MaterialSource = source.Attributes.MaterialSource
    newAttr.MaterialIndex = source.Attributes.MaterialIndex
    newAttr.LinetypeSource = source.Attributes.LinetypeSource
    newAttr.LinetypeIndex = source.Attributes.LinetypeIndex
    newAttr.PlotWeight = source.Attributes.PlotWeight
    newAttr.PlotWeightSource = source.Attributes.PlotWeightSource
    newAttr.PlotColor = source.Attributes.PlotColor
    newAttr.PlotColorSource = source.Attributes.PlotColorSource

    sc.doc.Objects.ModifyAttributes(target, newAttr, True)
    sc.doc.Views.Redraw()
    def MeshObjects(self):
        ml_doc = []

        objects = [rs.coercerhinoobject(o) for o in self.objects_to_render]
        for o in objects:
            obj_ref = Rhino.DocObjects.ObjRef(o)
            attr = obj_ref.Object().Attributes

            if attr.MaterialSource == Rhino.DocObjects.ObjectMaterialSource.MaterialFromLayer:
                layer = sc.doc.Layers[attr.LayerIndex]
                material_index = layer.RenderMaterialIndex
            else:
                material_index = attr.MaterialIndex

            if material_index == -1:
                attr.MaterialSource = Rhino.DocObjects.ObjectMaterialSource.MaterialFromObject
                attr.MaterialIndex = self.materials[0]
                #attr.CommitChanges()
            elif material_index not in self.materials:
                self.materials.append(material_index)

            if rs.IsMesh(o):
                ml_doc.append(sc.doc.Objects.AddMesh(o.MeshGeometry, attr))
                continue

            p = o.GetRenderMeshParameters()
            obrefs = Rhino.DocObjects.RhinoObject.GetRenderMeshes([o], True,
                                                                  True)
            mainmesh = Rhino.Geometry.Mesh()
            for obref in obrefs:
                obm = obref.Mesh()
                mainmesh.Append(obm)

            ml_doc.append(sc.doc.Objects.AddMesh(mainmesh, attr))

        rs.SelectObjects(ml_doc)

        return ml_doc
Exemplo n.º 26
0
def add_detail_scale(detail):
    #set focus back to page
    pageview = sc.doc.Views.ActiveView
    pageview.SetPageAsActive()
    detail = rs.coercerhinoobject(detail)

    page_scale = pageview.ActiveViewport.GetUserString("page_scale")
    if page_scale == None:
        psh.change_page_scale()
    if detail.DetailGeometry.IsParallelProjection:
        ratio = detail.DetailGeometry.PageToModelRatio

        if ratio >= 1.0:
            text = str(int(ratio)) + ":1"
        else:
            text = "1:" + str(int(1 / ratio))
        if page_scale == text:
            print "At least one detail has the same scale as the page scale, no scale info to this detail was added."
            return
        else:
            pt = [0, 0, 0]
            pt[0] = detail.Geometry.GetBoundingBox(
                Rhino.Geometry.Plane.WorldXY).Min.X + 3
            pt[1] = detail.Geometry.GetBoundingBox(
                Rhino.Geometry.Plane.WorldXY).Min.Y + 3
            psh.set_detail_scale(detail, ratio)
            id = str(detail.Id)
            p = "%"
            scale = '%s<UserText("%s","detail_scale")>%s' % (p, id, p)

            text = "detail (scale " + scale + ")"

            sc.doc.Views.ActiveView = pageview
            rs.AddText(text,
                       pt,
                       height=2.0,
                       font='Courier new',
                       justification=65537)  #bottom left
Exemplo n.º 27
0
def main():
    """
    - sets a predefined scale from a list for selected detail(s), defaults to page scale
    
    version 0.2
    www.studiogijs.nl
    """
    pageview = sc.doc.Views.ActiveView
    if type(pageview) != Rhino.Display.RhinoPageView:
        print "This tool only works in layout space."
        return
    details = rs.GetObjects("select detail(s) to change scale",32768, preselect=True)
    if not details:
        return
    value = psh.select_scale()
    if not value:
        return
    scale = psh.get_scale(value)
    for detail in details:
        
        detail = rs.coercerhinoobject(detail)
        if not detail.DetailGeometry.IsParallelProjection:
            continue
        psh.set_detail_scale(detail, scale)
Exemplo n.º 28
0
def change_block_description():
    """
    change or set a block description
    
    version 1.0
    www.studiogijs.nl
    """

    block = rs.GetObject("select block to add or change description",
                         filter=4096,
                         preselect=True)
    if not block:
        return
    block = rs.coercerhinoobject(block).InstanceDefinition

    desc = rs.BlockDescription(block.Name)
    if desc == None:
        print "Current description not set"
    else:
        print "Current description: " + desc
    newdesc = rs.GetString(
        "Set new description, to use spaces enter description between \" \"")
    if newdesc:
        rs.BlockDescription(block.Name, newdesc)
def coerceannotation(object_id):
    annotation_object = rs.coercerhinoobject(object_id, True)
    if not isinstance(annotation_object, Rhino.DocObjects.AnnotationObjectBase):
        raise ValueError("object_id does not refer to an Annotation")
    return annotation_object
points30 = rs.DivideCurve(curve30, m + 1)
m = int(m)
n = int(n)
bpoints = points01 + points12 + points23 + points30
for i in range(n):
    icurve = rs.ShortPath(surface, points01[i + 1], points23[-(i + 2)])
    icurvesn.append(icurve)
count = 0
while (count < loop):
    icurvesm = []
    ipointssnm = []
    for icurve in icurvesn:
        ipoints = rs.DivideCurve(icurve, m + 1)
        ipointssnm.append(ipoints)
#    global surfObj
    surfObj = rs.coercerhinoobject(surface).Geometry
    print surfObj
    for i in range(m):
        ps = []
        puvs = []
        p = points30[-(i + 1) - 1]
        puv = ghc.SurfaceClosestPoint(p, surfObj)[1]
        puvs.append(puv)
        for j in range(n):
            #转换数据类型
            p = ipointssnm[j][i + 1]
            puv = ghc.SurfaceClosestPoint(p, surfObj)[1]
            ps.append(p)
            puvs.append(puv)
        p = points12[i + 1]
        puv = ghc.SurfaceClosestPoint(p, surfObj)[1]
Exemplo n.º 31
0
def ConnectPointss(surface, pointss, diagonalDirection, bRing, step):
    # print "bRing",bRing
    # 01
    if (rs.IsSurface(surface)):
        curves = []
        polylines = []
        step = int(step)
        # 11
        if not bRing:
            if diagonalDirection == 1:
                for i in range(len(pointss) - 1):
                    i = len(pointss) - i - 2
                    puvs = []
                    pls = []
                    surfObj = rs.coercerhinoobject(surface).Geometry
                    for j in range(len(pointss[0])):
                        if i + j >= len(pointss):
                            break
                        p = pointss[(i + j)][j]
                        pls.append(p)
                        puv = ghc.SurfaceClosestPoint(p, surfObj)[1]
                        puvs.append(puv)
                    crv = ghc.CurveOnSurface(surfObj, puvs, False)[0]
                    curves.append(crv)
                    polyline = rs.AddPolyline(pls)
                    polylines.append(polyline)
                for i in range(len(pointss[0]) - 1):
                    i = i + 1
                    puvs = []
                    pls = []
                    surfObj = rs.coercerhinoobject(surface).Geometry
                    for j in range(len(pointss)):
                        if i + j >= len(pointss[0]):
                            break
                        p = pointss[j][(i + j)]
                        pls.append(p)
                        puv = ghc.SurfaceClosestPoint(p, surfObj)[1]
                        puvs.append(puv)
                    crv = ghc.CurveOnSurface(surfObj, puvs, False)[0]
                    curves.append(crv)
                    polyline = rs.AddPolyline(pls)
                    polylines.append(polyline)
            if diagonalDirection == -1:
                for i in range(len(pointss) - 1):
                    i = len(pointss) - i - 2
                    puvs = []
                    pls = []
                    surfObj = rs.coercerhinoobject(surface).Geometry
                    for j in range(len(pointss[0])):
                        if i + j >= len(pointss):
                            break
                        p = pointss[(i + j)][len(pointss[0]) - j - 1]
                        pls.append(p)
                        puv = ghc.SurfaceClosestPoint(p, surfObj)[1]
                        puvs.append(puv)
                    crv = ghc.CurveOnSurface(surfObj, puvs, False)[0]
                    curves.append(crv)
                    polyline = rs.AddPolyline(pls)
                    polylines.append(polyline)
                for i in range(len(pointss[0]) - 1):
                    i = i + 1
                    puvs = []
                    pls = []
                    surfObj = rs.coercerhinoobject(surface).Geometry
                    for j in range(len(pointss)):
                        if i + j >= len(pointss[0]):
                            break
                        p = pointss[j][len(pointss[0]) - (i + j) - 1]
                        pls.append(p)
                        puv = ghc.SurfaceClosestPoint(p, surfObj)[1]
                        puvs.append(puv)
                    crv = ghc.CurveOnSurface(surfObj, puvs, False)[0]
                    curves.append(crv)
                    polyline = rs.AddPolyline(pls)
                    polylines.append(polyline)
            if diagonalDirection == 0:
                polylines = [rs.AddPolyline(pls) for pls in pointss]
        # 11 成环
        else:
            # print len(pointss)
            for i in range(int(len(pointss) / step)):
                puvs = []
                surfObj = rs.coercerhinoobject(surface).Geometry
                pls = []
                for j in range(len(pointss[0])):
                    # print  (i*step+j*diagonalDirection)%len(pointss)
                    p = pointss[(i * step + j * diagonalDirection) %
                                len(pointss)][j]
                    puv = ghc.SurfaceClosestPoint(p, surfObj)[1]
                    puvs.append(puv)
                    pls.append(p)
                crv = ghc.CurveOnSurface(surfObj, puvs, False)[0]
                curves.append(crv)
                polyline = rs.AddPolyline(pls)
                polylines.append(polyline)
    return curves