Exemplo n.º 1
0
def CaptureDisplayModesToFile():
    try:
        displayModeNames = []
        displayModeBool = []
        displayModesChecked = []

        ########
        #Get current display mode
        originalDisplayMode = rc.RhinoDoc.ActiveDoc.Views.ActiveView.ActiveViewport.DisplayMode.LocalName

        ########
        #Get default display mode selection
        if 'CaptureDisplayModes-DisplayModes' in sc.sticky:
            dict = sc.sticky['CaptureDisplayModes-DisplayModes']
            for each in rc.Display.DisplayModeDescription.GetDisplayModes():
                displayModeNames.append(each.EnglishName)
                if each.EnglishName in dict:
                    displayModeBool.append(dict[each.EnglishName])
                else:
                    displayModeBool.append(False)
        else:
            for each in rc.Display.DisplayModeDescription.GetDisplayModes():
                displayModeNames.append(each.EnglishName)
                displayModeBool.append(False)

        results = rs.CheckListBox(zip(displayModeNames, displayModeBool), 'Select Display Modes', 'Capture Display Modes To File')
        if results is None: return

        ########
        #Save display modes to sticky
        resultDict = {}
        for each in results:
            resultDict[each[0]] = each[1]
        sc.sticky['CaptureDisplayModes-DisplayModes'] = resultDict

        for each in results:
            if each[1]:
                displayModesChecked.append(each[0])

        ########
        #Get default filename
        date = utils.GetDatePrefix()
        activeView = sc.doc.Views.ActiveView.ActiveViewport.Name
        if activeView is None: activeView = 'VIEW'
        path = rs.SaveFileName('Export All Display Modes', "PNG (*.png)|*.png||", filename = date+'_'+activeView)
        if path is None: return

        ########
        #Get sizes from sticky
        if 'catpureDisplays-width' in sc.sticky:
            widthDefault = sc.sticky['catpureDisplays-width']
        else:
            widthDefault = 5100

        if 'catpureDisplays-height' in sc.sticky:
            heightDefault = sc.sticky['catpureDisplays-height']
        else:
            heightDefault = 3300

        width = rs.GetInteger('Image Width', number = widthDefault, minimum = 200, maximum = 20000)
        height = rs.GetInteger('Image Height', number = heightDefault, minimum = 200, maximum = 20000)

        ########
        #Save sizes to sticky
        sc.sticky['catpureDisplays-width'] = width
        sc.sticky['catpureDisplays-height'] = height

        #######################################################################
        #Export the images
        count = 0
        for name in displayModesChecked:
            try:
                rs.ViewDisplayMode(mode = name)
                exportImage(path, name, width, height)
                count += 1
            except:
                pass
        print "{} Images saved to {}".format(count , os.path.abspath(os.path.join(path, os.pardir)))
        result = True
    except:
        result = False
    ########
    #Restore original display mode
    if originalDisplayMode is not None:
        rs.ViewDisplayMode(mode = originalDisplayMode)

    ########
    #Save analytics
    try:
        utils.SaveFunctionData('IO-Capture Display Modes', [__version__, str(displayModesChecked), width, height, result])
    except: print "Failed to save function data"
    return result
Exemplo n.º 2
0
import rhinoscriptsyntax as rs

rs.EnableRedraw(False)
#Get Kerf parameters for bending
obj_0 = rs.GetObject("Select the bottom line", 4)
obj_1 = rs.GetObject("Select the left line", 4)
l = rs.GetInteger("Segments length [mm]")
dis = rs.GetInteger("Distance x from the segments [mm]")
sp = rs.GetInteger("Distance y from the segments [mm]")
# Set the length of the segment
L = rs.CurveLength(obj_0)
x = (L/(l+dis))
xint = int(x+0.5)
d = L/xint-l

L_2 = rs.CurveLength(obj_1)
x_2 = (L_2/sp)
xint_2 = int(x_2+0.5)
s = L_2/xint_2


#----------Generate pattern A----------#
joins = []
a = rs.AddPoint(rs.CurveStartPoint (obj_0))
joins.append(a)
p = rs.CopyObject(a,[(l/2),0,0])
joins.append(p)

for i in range (1, (xint)):
    c = rs.CopyObject(p,[d,0,0])
    joins.append(c)
#2D Point Grid with Circles generated with an Attractor Point
#This script will create a 2D grid of points and circle centered on each point.
#Circle radius is driven by the distance from the attractor to the point defining the center of the circle.

import rhinoscriptsyntax as rs

#spacing variable sets distance between points
spacing = 3

#Dictionary to hold points
pts = {}

#Prompt user to set X and Y extents, default of 20
iMax = rs.GetInteger("Please enter max number of points in x", 20)
jMax = rs.GetInteger("Please enter max number of points in y", 20)

#select an attractor pt.  This will drive the size of the circles
attPt = rs.GetObject("Select attractor point", 1)

#nested For loops for X and Y Domains
for i in range(iMax):
    for j in range(jMax):

        #define x,y,(z)
        x = i * spacing
        y = j * spacing
        #z will always be 0 for a 2D Grid
        z = 0

        #Store the points in the dictionary using the iterators as the reference keys
        pts[(i, j)] = [x, y, z]
Exemplo n.º 4
0
def outline_region():
	
	
	go = Rhino.Input.Custom.GetObject()
	go.GeometryFilter = Rhino.DocObjects.ObjectType.Curve
	
	default_length = sc.sticky["length"] if sc.sticky.has_key("length") else 100
	default_delete = sc.sticky["delete"] if sc.sticky.has_key("delete") else True
	
	opt_delete = Rhino.Input.Custom.OptionToggle(default_delete,"No","Yes")
	go.SetCommandPrompt("Select Curves")
	go.AddOptionToggle("DeleteInput", opt_delete)

	go.GroupSelect = True
	go.SubObjectSelect = False
	go.AcceptEnterWhenDone(True)
	go.AcceptNothing(True)
	go.EnableClearObjectsOnEntry(False)
	go.GroupSelect = True
	go.SubObjectSelect = False
	go.DeselectAllBeforePostSelect = False
	
	res = None
	bHavePreselectedObjects = False
	while True:
		res = go.GetMultiple(1,0)
		if res == Rhino.Input.GetResult.Option:
			#print res
			go.EnablePreSelect(False, True)
			continue
		#If not correct
		elif res != Rhino.Input.GetResult.Object:
			print "No curves selected!"
			return Rhino.Commands.Result.Cancel
		if go.ObjectsWerePreselected:
			bHavePreselectedObjects = True
			go.EnablePreSelect(False, True)
			continue
		break
	
	input_curves = []
	for i in xrange(go.ObjectCount):
		b_obj = go.Object(i).Object()
		input_curves.append(b_obj.Id)
	
	#Get length
	extension_length = rs.GetInteger(message="Enter Extension Length",number=default_length)
	if not extension_length:
		rs.EnableRedraw(True)
		print "No Extension Length entered."
		return False

	arr_preview_geom = get_preview_geometry(input_curves)
	for indCrv in arr_preview_geom:
		rs.ExtendCurveLength(indCrv,0,2,extension_length)
	
	rs.EnableRedraw(False)
	#Get curveboolean and display it
	region_was_created = True
	rs.UnselectAllObjects()
	rs.SelectObjects(arr_preview_geom)
	
	rs.Command("_-CurveBoolean _AllRegions _Enter")
	
	pcurve_outline = rs.LastCreatedObjects()
	
	if isinstance(pcurve_outline,list):
		preview_srf = rs.AddPlanarSrf(pcurve_outline)
		rs.LockObjects(arr_preview_geom)
		rs.LockObjects(preview_srf)
	else:
		region_was_created = False
		rs.LockObjects(arr_preview_geom)
		preview_srf = []

	rs.EnableRedraw(True)
	rs.Redraw()

	#Set up input object
	go = Rhino.Input.Custom.GetOption()
	optint = Rhino.Input.Custom.OptionDouble(extension_length)

	prompt = "Press Enter to accept"
	warning = "Insufficient overlap length. "
	s = prompt if region_was_created else warning+prompt
	go.SetCommandPrompt(s)
	go.AddOptionDouble("ExtensionLength", optint)
	go.AddOptionToggle("DeleteInput", opt_delete)
	go.AcceptEnterWhenDone(True)
	go.AcceptNothing(True)

	#control flow: can distinguish between inserting an option, cancelling, and pressing enter
	res = None
	while True:
		res = go.Get()
		rs.EnableRedraw(False)
		region_was_created = True
		
		#If new option entered, redraw a possible result
		if res == Rhino.Input.GetResult.Option:
			#Delete old preview
			rs.UnlockObjects(preview_srf+arr_preview_geom)
			rs.DeleteObjects(preview_srf+arr_preview_geom)
			if isinstance(pcurve_outline,list):
				rs.DeleteObjects(pcurve_outline)
			rs.SelectObjects(input_curves)
			
			#Draw new preview
			arr_preview_geom = get_preview_geometry(input_curves)
			if not extension_length: return False
			
			for indCrv in arr_preview_geom:
				rs.ExtendCurveLength(indCrv,0,2,optint.CurrentValue)
			
			rs.UnselectAllObjects()
			rs.SelectObjects(arr_preview_geom)
			rs.Command("_-CurveBoolean _AllRegions _Enter")
			pcurve_outline = rs.LastCreatedObjects()
			
			if isinstance(pcurve_outline,list):
				preview_srf = rs.AddPlanarSrf(pcurve_outline)
				rs.LockObjects(arr_preview_geom)
				rs.LockObjects(preview_srf)
			else:
				rs.LockObjects(arr_preview_geom)
				preview_srf = []
				region_was_created = False
			rs.EnableRedraw(True)
			
			s = prompt if region_was_created else warning+prompt
			go.SetCommandPrompt(s)
			
			continue

		#If accepted, leave loop
		elif res == Rhino.Input.GetResult.Nothing:
			break
		
		#If cancelled, delete working geometry
		elif res != Rhino.Input.GetResult.Option:
			rs.UnlockObjects(preview_srf)
			rs.UnlockObjects(arr_preview_geom)
			rs.DeleteObjects(preview_srf)
			rs.DeleteObjects(arr_preview_geom)
			rs.DeleteObjects(pcurve_outline)
			rs.EnableRedraw(True)
			return Rhino.Commands.Result.Cancel
	

	#Clean up if successful
	if opt_delete.CurrentValue == True: rs.DeleteObjects(input_curves)
	rs.UnlockObjects(preview_srf)
	rs.UnlockObjects(arr_preview_geom)
	rs.DeleteObjects(preview_srf)
	rs.DeleteObjects(arr_preview_geom)
	if isinstance(pcurve_outline,list):
		rs.SelectObjects(pcurve_outline)
	
	sc.sticky["length"] = optint.CurrentValue
	sc.sticky["delete"] = opt_delete.CurrentValue
	
	rs.EnableRedraw(True)
Exemplo n.º 5
0

def GetAllLayerNames():
    allLayerNames = []
    layerNums = []

    setupVariables()

    global csvPath
    layerData = GetLayerData(csvPath)
    for i in range(0, 10000, 1000):
        layerNumsSet = GetChildNumbers(i, layerData)
        layerNumsSet.sort()
        layerNums = layerNums + layerNumsSet

    for each in layerNums:
        allLayerNames.append(GetLayerNameByNumber(each))
    return allLayerNames


if __name__ == "__main__" and utils.IsAuthorized():
    setupVariables()
    layerNumRequested = rs.GetInteger(
        "Enter layer number to add to the document",
        number=10000,
        minimum=0,
        maximum=10000)
    AddLayerByNumber(layerNumRequested)
    utils.SaveToAnalytics('layers-' + str(layerNumRequested))
    #print GetLayerNameByNumber(layerNumRequested)
Exemplo n.º 6
0
def ScatterBlocks():
    try:
        ################################################################################
        #                             GET OBJECTS AND VARIABLE                         #
        ################################################################################

        obj = rs.GetObject(message="Select surface to scatter on", filter=8 | 16 |
                           32, preselect=False, select=False, custom_filter=None, subobjects=False)
        if not obj:
            return
        blocks = rs.GetObjects(message="Select blocks to scatter", filter=4096, group=True, preselect=False,
                               select=False, objects=None, minimum_count=1, maximum_count=0, custom_filter=None)
        if not blocks:
            return
        scatterNum = rs.GetInteger(
            message="Enter scatter amount", number=100, minimum=1, maximum=10000)
        if not scatterNum:
            return
        userScale = rs.GetReal(
            "enter scale multiplyer (0 for no scaling)", number=0, minimum=None, maximum=None)

        userRotation = rs.GetBoolean(
            "random rotation of blocks?", ("Rotation", "No", "Yes"), (True))
        if not userRotation:
            return

        isMesh = rs.IsMesh(obj)
        ptBucket = 0
        pointList = []
        blockList = []
        worldZVector = (rs.WorldXYPlane()).ZAxis

        rs.EnableRedraw(False)

        def MeshBrep(brep_id, params):
            brep = rs.coercebrep(brep_id)
            if brep:
                mesh = Rhino.Geometry.Mesh()
                mesh_parts = Rhino.Geometry.Mesh.CreateFromBrep(brep, params)
                for mesh_part in mesh_parts:
                    mesh.Append(mesh_part)
                mesh.Compact()
                return mesh

        def TestMeshBrep():
            mesh_params = Rhino.Geometry.MeshingParameters.Coarse
            mesh_brep = MeshBrep(obj, mesh_params)
            if mesh_brep:
                mesh = sc.doc.Objects.AddMesh(mesh_brep)
            return mesh

        def chunks(lst, n):  # list split generator
            for i in xrange(0, len(lst), n):
                yield lst[i:i + n]

        if isMesh == False:
            mesh = TestMeshBrep()
        else:
            mesh = obj

        # Get and format vertex points in mesh, format from point3d object to float list
        meshVerts = rs.MeshFaces(mesh, face_type=False)
        totalArea = rs.MeshArea(mesh)
        meshFaceCount = rs.MeshFaceCount(mesh)

        PT01 = meshVerts[0::3]
        PT01S = []
        for i in PT01:
            i = (i.X, i.Y, i.Z)
            PT01S.append(i)

        PT02 = meshVerts[1::3]
        PT02S = []
        for i in PT02:
            i = (i.X, i.Y, i.Z)
            PT02S.append(i)

        PT03 = meshVerts[2::3]
        PT03S = []
        for i in PT03:
            i = (i.X, i.Y, i.Z)
            PT03S.append(i)

        # format list together in order to loop through
        triangleList = zip(PT01S, PT02S, PT03S)

        ################################################################################
        #                             POINT SCATTER LOOP                               #
        ################################################################################

        # loop through the three vertexes forming individual triangles
        for i in triangleList:
            a = i[0]  # triangle vert 1
            b = i[1]  # triangle vert 2
            c = i[2]  # triangle vert 3

        # Find area of triangle
            dist01 = rs.Distance(a, b)
            dist02 = rs.Distance(a, c)
            dist03 = rs.Distance(b, c)
            # Herons formula to find area of triangle by sides
            s = (dist01 + dist02 + dist03) / 2
            tArea = math.sqrt(s*(s-dist01)*(s-dist02)*(s-dist03))

        # assign portion of points base on area of triangle, if assignment of points is lower then one, add that to the next assignment
            numPtsPerUnit = totalArea[1] / scatterNum
            ptAllocation = tArea / numPtsPerUnit
            ptBucket = ptBucket + ptAllocation

            if ptBucket < 1:
                continue
            else:
                pointShare = int(math.floor(ptBucket))
                ptBucket = 0

        # Vectors from origin to either corner of triangle
            ac = rs.VectorCreate(c, a)
            ab = rs.VectorCreate(b, a)
            originVector = rs.VectorCreate(a, (0, 0, 0))

        # Generate random numbers between 0,1. Random scatter onto triangle
            for i in range(pointShare):
                r1 = random.random()
                r2 = random.random()
                if r1 + r2 < 1:
                    p = r1 * ac + r2 * ab
                else:
                    p = (1 - r1) * ac + (1 - r2) * ab

                points = rs.AddPoint(p)
                pointList.append(points)
                rs.MoveObjects(points, originVector)

        ################################################################################
        #                 MOVE BLOCKS TO POINTS WITH ROTATION / SCALE                  #
        ################################################################################

        # shuffle point list then split list by the number of blocks to scatter. Copy blocks to split lists
        random.shuffle(pointList)
        ptDivision = int(len(pointList) / len(blocks))
        genList = chunks(pointList, ptDivision)
        blockIndex = 0

        for pts in genList:  # looping through split point list and blocks and copying blocks to scatter
            blockPt = rs.BlockInstanceInsertPoint(blocks[blockIndex])
            for pt in pts:
                vector = rs.VectorCreate(pt, blockPt)
                newBlock = rs.CopyObject(blocks[blockIndex], vector)
                # create list of blocks for later modification
                blockList.append(newBlock)
            if blockIndex < (len(blocks) - 1):
                blockIndex += 1

        # apply random scaling and rotation to blocks
        if userRotation[0] == True:
            for block in blockList:
                centerPt = rs.BlockInstanceInsertPoint(block)
                angle = random.randint(0, 360)
                rs.RotateObject(block, centerPt, angle, worldZVector)

        for block in blockList:
            centerPt = rs.BlockInstanceInsertPoint(block)
            scale = random.uniform((userScale/4), userScale)
            rs.ScaleObject(block, centerPt, (scale, scale, scale))

        # If a mesh was created, delete it, general cleanup
        if isMesh == False:
            rs.DeleteObject(mesh)
        rs.DeleteObjects(pointList)

        rs.EnableRedraw(True)

    except:
        print("Failed to execute")
        rs.EnableRedraw(True)
        return
Exemplo n.º 7
0
import rhinoscriptsyntax as rs

# this pulls in all of rhino's native commands into python,
# so from here on out we can just say rs.[whatever] to access rhino's stuff
# a list of rhino python commands is here: http://www.rhino3d.com/5/ironpython/index.html
# first, we need some information from the user:
numberOfPoints = rs.GetInteger("how many data points?") # do the same for the number of data points
radius = rs.GetReal("what's the radius of your sun-sphere?") # get a radius for the sphere the sun's going to rotate around

rs.AddLayer("sun sphere", [0,0,255]) # make a new layer for the sphere itself, and color it blue
rs.AddLayer("sun rays", [255,0,0]) # make a new layer for the rays shooting inwards from the sun, color it red
rs.CurrentLayer("sun sphere") # go to the sun sphere layer

sunSphere = rs.AddSphere([0,0,0], radius) # draw the sun sphere at the origin with a radius of whatever is in the variable "radius" (and store it in a variable called sunSphere)



# saying if(something) is a boolean test - checks to see whether the statements are true.
# it just checks to see whether there's anything positive in these variables
if ((numberOfPoints > 0) and (radius > 0)):

    dayName = rs.GetString("which day is this? (no spaces!)") # ask for a label (text blocks are called 'strings') for the eventual curve object
    print "current day = ", dayName # print it to the command line, just to make sure it worked
    rs.AddLayer(dayName, [255,255,255]) # make a new layer for each day - make everything on them white, just to distinguish
    # (you can change [255,255,255] to any color, or delete that part)
    rs.CurrentLayer(dayName) # go to that layer
    
    listOfPoints = [] # setup a list (empty at this point) to hold all the points for the curve
    rs.AddPoint([0,radius,0]) # put down one point at x=0, y= the radius of the sun-sphere, z=0
    starterPt = rs.FirstObject() # FirstObject grabs the last thing created, in this case that point we just made - let's name that 'starterPt'
    
Exemplo n.º 8
0
import rhinoscriptsyntax as rs


### rs.GetInteger(msg, defalut, min, max)
tmp_num_0 = rs.GetInteger("Please Enter an Integer-A", 10, 0, 100)
tmp_num_1 = rs.GetInteger("Please Enter an Integer-B", 2)

print "Integer-A + Interger-B =", tmp_num_0 + tmp_num_1



### rs.GetString(msg, defalut)
tmp_txt = rs.GetString("Please Enter Your Name", "aaa")

print "Hello,", tmp_txt
Exemplo n.º 9
0
def start():
    from compas.geometry.algorithms.smoothing import mesh_smooth_centroid
    from compas.geometry.algorithms.smoothing import mesh_smooth_area

    from compas_pattern.algorithms.smoothing import define_constraints
    from compas_pattern.algorithms.smoothing import apply_constraints

    guid = rs.GetObject('get mesh')
    dense_mesh = RhinoGeometry.from_guid(guid)
    vertices, faces = dense_mesh.get_vertices_and_faces()
    dense_mesh = Mesh.from_vertices_and_faces(vertices, faces)

    #lines = rs.GetObjects('lines', filter = 4)
    #edges = [[rs.CurveStartPoint(line), rs.CurveEndPoint(line)] for line in lines]
    #dense_mesh = Mesh.from_lines(edges)

    #faces = list(dense_mesh.faces())
    #for fkey in faces:
    #    if len(dense_mesh.face_vertices(fkey)) > 10:
    #        delete_face(dense_mesh, fkey)
    #        print '-1 face'

    #dense_mesh = conway_ambo(dense_mesh)
    #dense_mesh = conway_dual(dense_mesh)
    #dense_mesh = conway_gyro(dense_mesh)
    #dense_mesh = conway_dual(dense_mesh)
    #dense_mesh = conway_gyro(dense_mesh)
    #dense_mesh = conway_kis(dense_mesh)

    #rs.EnableRedraw(False)
    #draw_mesh(dense_mesh)
    #rs.EnableRedraw(True)
    #return

    surface_guid = rs.GetSurfaceObject('surface constraint')[0]

    smooth_mesh = dense_mesh.copy()

    smoothing_iterations = rs.GetInteger('number of iterations for smoothing',
                                         number=20)
    damping_value = rs.GetReal('damping value for smoothing', number=.5)

    rs.EnableRedraw(False)

    #constraints, surface_boundaries = custom_constraints(smooth_mesh, surface_guid)
    constraints, surface_boundaries = define_constraints(
        smooth_mesh, surface_guid)

    rs.EnableRedraw(False)
    fixed_vertices = [
        vkey for vkey, constraint in constraints.items()
        if constraint[0] == 'fixed'
    ]
    mesh_smooth_area(smooth_mesh,
                     fixed=fixed_vertices,
                     kmax=smoothing_iterations,
                     damping=damping_value,
                     callback=apply_constraints,
                     callback_args=[smooth_mesh, constraints])

    smooth_mesh_guid = draw_mesh(smooth_mesh)

    #layer = 'smooth_mesh'
    #rs.AddLayer(layer)
    #rs.ObjectLayer(smooth_mesh_guid, layer = layer)

    rs.EnableRedraw(True)
Exemplo n.º 10
0

class GhcompService(rpyc.ClassicService):
    def on_connect(self, conn):
        print('Incoming connection.')
        super(GhcompService, self).on_connect(conn)
        import ghpythonlib.components as ghcomp
        self.ghcomp = ghcomp

    def on_disconnect(self, conn):
        print('Disconnected.')

    def get_component(self, component_name, is_cluster_component=False):
        component = getattr(self.ghcomp, component_name)
        if is_cluster_component:
            component = getattr(
                component, component_name
            )  # TODO: improve ghcomp to get clusters the same way we get compiled components, thus removing the need for a custom getter
        return component


if __name__ == '__main__':
    import rhinoscriptsyntax as rs
    port = rs.GetInteger("Server bind port", 18871, 1023, 65535)

    server = OneShotServer(GhcompService,
                           hostname='localhost',
                           port=port,
                           listener_timeout=None)
    server.start()
Exemplo n.º 11
0
            new_keys = []
            for key in keys:
                point = mesh_obj.vertex_coordinates(key)
                x, y, z = add_vectors(point, vec)
                new_keys.append(mesh_obj.add_vertex(x=x, y=y, z=z))

            mesh_obj.delete_face(fkey)

            mesh_obj.add_face(new_keys)

            for i, key in enumerate(keys):
                mesh_obj.add_face(
                    [keys[i - 1], keys[i], new_keys[i], new_keys[i - 1]])

        if selection == "steps":
            steps = rs.GetInteger("Subdivision steps", steps, 1, 5)
#        mesh_obj.draw(name="control",
#                     layer="SD_mesh",
#                     clear=False,
#                     redraw=True,
#                     show_faces=False,  # rename to display_faces?
#                     show_vertices=False,  # rename to display_vertices?
#                     show_edges=False,  # rename to display_edges?
#                     vertex_color=None,
#                     edge_color=None,
#                     face_color=None,
#                     show_faces_mesh=True)
#        print mesh_obj
#        break

        if break_flag:
Exemplo n.º 12
0
"""
SHL Architects 07-02-2019
Sean Lamb (Developer)
[email protected]
"""
import rhinoscriptsyntax as rs
import shl_toolbox_lib.util as wut
reload(wut)

num = rs.GetInteger("Enter number of layers")
prefix = rs.GetString("Enter layer name prefix")

colors = wut.equidistant_hsv_color(num, 0.4)

for i in xrange(num):
    rs.AddLayer(prefix + "-" + str(i), colors[i])
Exemplo n.º 13
0
import rhinoscriptsyntax as rs

numberofpoints = rs.GetInteger("how many points?")
radius = rs.GetReal("what's the radius?")

rs.AddLayer("Sphere", [255, 0, 0])
rs.CurrentLayer("Sphere")

Sunsphere = rs.AddSphere([0, 0, 0], radius)

if ((numberofpoints > 0) and (radius > 0)):
    #stuff if true
    print "we're good"

    dayname = rs.GetString("what day is this?")
    print "the entered day name is:", dayname

    rs.AddLayer(dayname, [0, 0, 255])
    rs.CurrentLayer(dayname)

    listofpoints = []

    startpoint = rs.AddPoint([0, radius, 0])

    for i in range(numberofpoints):
        elevation = rs.GetReal("what's the elevation?")
        azimuth = rs.GetReal("what's the azimuth?")
        azimuth *= -1
        rs.RotateObject(startpoint, [0, 0, 0],
                        elevation,
                        axis=[1, 0, 0],
Exemplo n.º 14
0
def BatchCapture():
    try:
        namedViews = rs.NamedViews()
        if len(namedViews) < 1:
            print "There are no Named Views in this file."
            return None

        #Prepare checklis
        items = []
        for view in namedViews:
            items.append([view, False])

        #Checklist
        returnedVals = rs.CheckListBox(items, "Select Views to Export", "Batch Capture")
        if returnedVals is None: return

        chosenViews = []
        for val in returnedVals:
            if val[1]:
                chosenViews.append(val[0])
        if len(chosenViews) < 1: return

        defaultFilename = utils.GetDatePrefix() + '_FILENAME'
        #path = rs.SaveFileName('Batch Capture', "PNG (*.png)|*.png||", filename = date+'_FILENAME')
        path = rs.SaveFileName('Save view location', "PNG (*.png)|*.png|JPEG (*.jpeg)|*.jpeg||", filename = defaultFilename, extension = ".png")
        if path is None: return

        #Check if in stick
        if 'batchCapture-width' in sc.sticky:
            defaultWidth = sc.sticky['batchCapture-width']
        else:
            defaultWidth = 5100
        if 'batchCapture-height' in sc.sticky:
            defaultHeight = sc.sticky['batchCapture-height']
        else:
            defaultHeight = 3300

        #Get output width
        width =  rs.GetInteger('Width', defaultWidth, 200, 10000 )
        if width is None: return
        sc.sticky['batchCapture-width'] = width

        #Get output height
        height = rs.GetInteger('Height', defaultHeight, 200, 10000 )
        if height is None: return
        sc.sticky['batchCapture-height'] = height

        rs.AddNamedView("temp")

        baseName = os.path.splitext(path)[0]
        for eachView in chosenViews:
            rs.RestoreNamedView(eachView)

            splitPath = path.Split(".")
            if splitPath[-1] == "png":
                filePath = baseName + "_" + eachView + ".png"
                result = SafeCapture_PNG(filePath, width, height)
            else:
                filePath = baseName + "_" + eachView + ".jpg"
                result = SafeCapture_JPG(filePath, width, height)

        #return to original view
        rs.RestoreNamedView("temp")
        rs.DeleteNamedView("temp")


        result = True
    except:
        result = False
    utils.SaveFunctionData('IO-BatchCapture', [__version__] + chosenViews)
    return result
Exemplo n.º 15
0
                                            targetFolderUserObjects)
        result = True
    except:
        print "FAIL-----Could not copy dependencies. You must have Grasshopper open. Close and reopen Rhino, then run this again."
        result = False

    utils.SaveFunctionData(
        'Standards-PCPA GH Dependencies',
        [numberOfLibraryObjects, numberOfUserObjects, result])


if __name__ == "__main__" and utils.IsAuthorized():
    PreloadCheck()

    standardsRequested = rs.GetInteger("Standards to import",
                                       number=0,
                                       minimum=0,
                                       maximum=10000)
    fileLocations = config.GetDict()
    if standardsRequested == 0:
        LoadPCPAMaterials(fileLocations['Material File'])
    elif standardsRequested == 1:
        SetTemplateFolder(fileLocations['Template Folder'])
        SetTemplateFile(fileLocations['Template File'])
        utils.SaveToAnalytics('standards-Set Template')
    elif standardsRequested == 2:
        LoadPCPAComponents(fileLocations['PCPA GH Components'])
        LoadGHDependencies(fileLocations)
        utils.SaveToAnalytics('standards-Load GH Components')
    elif standardsRequested == 3:
        LoadAcadSchemes(fileLocations['ACAD Scheme Folder'])
        utils.SaveToAnalytics('standards-Load ACADSchemes')
Exemplo n.º 16
0
def CA():
   
    # input
    gridSizeX = rs.GetInteger("grid size X", 10)
    gridSizeY = rs.GetInteger("grid size Y", 10)
    steps = rs.GetInteger("how many steps", 20)
   
    listCells = [None]*gridSizeX
    # make first generation
    for x in range(gridSizeX):
        cells = [None]*gridSizeY
        for y in range(gridSizeY):
            if rnd.random() > 0.5:
                cells[y] = 1
            else:
                cells[y] = 0
        listCells[x] = cells
       
    # iterate through generations - steps
    for i in range(steps):
        rs.EnableRedraw(False)
        # loop x
        for x in range(gridSizeX):
            # loop y
            for y in range(gridSizeY):
                # torus space
                xMinus = x-1
                if x==0:
                    xMinus = gridSizeX-1
                xPlus = x+1
                if x==gridSizeX-1:
                    xPlus = 0
                yMinus = y-1
                if y==0:
                    yMinus = gridSizeY-1
                yPlus = y+1
                if y==gridSizeY-1:
                    yPlus = 0
               
                # sum neighbors
                sum = 0
                sum = sum + listCells[xMinus][yMinus]
                sum = sum + listCells[x][yMinus]
                sum = sum + listCells[xPlus][yMinus]
                sum = sum + listCells[xMinus][y]
                sum = sum + listCells[xPlus][y]
                sum = sum + listCells[xMinus][yPlus]
                sum = sum + listCells[x][yPlus]
                sum = sum + listCells[xPlus][yPlus]
               
                # rules
                # if alive and < 2 neighbors - dies = 0
                # if alive and == 2 or == 3 neighbors - alive = 1
                # if alive and > 3 neighbors - dies = 0
                # if dead and ==3 neighbors - alive = 1
                if listCells[x][y] == 1:
                    if sum < 2:
                        listCells[x][y] = 0
                    if sum == 2 or sum == 3:
                        listCells[x][y] = 0
                    if sum > 3:
                        listCells[x][y] = 1
                else:
                    if sum == 3:
                        listCells[x][y] = 0
               
                # render
                if listCells[x][y] == 1:
                    rs.AddPoint([x,y,i])
                    #rs.AddBox([ [x,y,i], [x+1,y,i], [x+1,y+1,i], [x,y+1,i], [x,y,i+1], [x+1,y,i+1], [x+1,y+1,i+1], [x,y+1,i+1]])
        rs.EnableRedraw(True)
Exemplo n.º 17
0
#Python Workshop Lesson:14
#http://www.designalyze.com/int2pythonscripting13_NotSoSimpleRecursion

import rhinoscriptsyntax as rs
 
def RecursiveScale(objID,scalePt,scaleFact, scaleVect, num):
    if num == 0:
        return 0
    else:
        sc = (1.0 / scaleFact)
        scaleVect = [x - sc for x in scaleVect]
        rs.ScaleObject(objID, scalePt, scaleVect, True)
        return RecursiveScale(objID, scalePt, scaleFact, scaleVect, num-1)
 
 
objID = rs.GetObject()
scalePt = rs.GetPoint("Pick Scale Center")
scaleFact = rs.GetReal("Enter a scale Factor", 10, 0)
scaleVect = [1.0, 1.0, 1.0]
num = rs.GetInteger("Enter a the number of iterations", 10, 1)
 
RecursiveScale(objID, scalePt, scaleFact, scaleVect, num)
Exemplo n.º 18
0
#of objects and functions in Rhino
import rhinoscriptsyntax as rs

#Let's work in 2D first (in Rhino, only look at Top window).

#Points in 2D can be represented by a list of numbers [x, y, 0]
p1 = [1, 12, 0]
p2 = [-2, 2, 0]

#and drawn to the canvas by using a built-in function
rs.AddPoint(p1)
rs.AddPoint(p2)

#we can draw a collection of points, such as this zig-zag,
#based on user-inputted data
count = rs.GetInteger("Number of points")
height = rs.GetInteger("Height of zig-zag")

if count:
    for i in range(count):
        x = i
        if (i % (2 * height) < height):
            y = i % height
        else:
            y = height - (i % height)
        rs.AddPoint([x, y, 0])

#this is a collecton of points along a 'curve' defined by a
#mathematical function, y = |x|sin(5x),  for a specified range
#and a fixed stepsize in x (representing angle in degrees).
#For fixed intervals, the built-in function frange is very useful
Exemplo n.º 19
0
"""
Author: Angel Linares Garcia.
Date: 150821
Description: This scripts takes one
selected curve and creates N offsets
at D distance.
"""
##############################

import rhinoscriptsyntax as rs

strCrv0 = rs.GetCurveObject("Select curve", True)
intTimes = rs.GetInteger("Number of repetitions")
dblDist = rs.GetReal("Distance between curves")
pt0 = rs.GetPoint("Selec offset side")
rs.EnableRedraw(False)

for i in range(intTimes):

    newCurve = rs.OffsetCurve(strCrv0[0], pt0, dblDist * (i + 1))
    strCrv = newCurve

rs.EnableRedraw(True)
Exemplo n.º 20
0
# use rhinoscriptsyntax to get all the functions in one shot
import rhinoscriptsyntax as rs
import random
import time
import math
import Rhino

numCyls = rs.GetInteger("Number of sticks")
spread = rs.GetInteger("spread")

seed = rs.GetPoint("seed point")
print "seed point: ", seed[0], " / ", seed[1], " / ", seed[2]

pi = math.pi

if numCyls and spread and seed:

    for a in range(numCyls):
        x = seed[0]
        y = seed[1]
        z = seed[2]
        # points.append([seed[0], seed[1], seed[2]])
        offset = random.random() * spread
        stick = rs.AddCylinder([x + offset, y, z],
                               random.random() * 10,
                               random.random() * 0.5, True)
        rs.RotateObject(stick, seed, random.random() * 360)

    rs.ZoomExtents(view=None, all=True)
Exemplo n.º 21
0
    def __init__(self):
        rs.AddLayer("garbage", visible=False)
        self.max = 500
        self.fsr = 3
        self.loc_pts = []
        self.res_obj = []
        self.num_copies = 1
        self.site_crv = rs.GetObject('pick site boundary')
        self.site_copy = []
        FileName = "input.csv"
        FilePath = rs.GetString(
            "Enter the working directory for the program : ")
        if (FilePath == ""):
            FilePath = 'c:/nir_dev/temp/output_1'
        try:
            os.stat(FilePath)
        except:
            print('folder does not exist')
            return
        os.chdir(FilePath)
        req_fsr = 3.0
        """
        # since total area for each function is given, fsr required is not applicable
        try:
            self.fsr=float(rs.GetString("Enter FSR required"))
        except:
            print('this is incorrect data type default value of fsr=3.0 assumed')
        """
        n = rs.GetInteger('Enter number of variations required')
        if (n == 0 or n == None):
            n = 1
        a = int(math.sqrt(n))
        b = int(math.sqrt(n))
        self.num_copies = n
        self.max = self.getMax()
        req_str_li = []
        k = 0
        rs.ClearCommandHistory()
        print('processing...')
        rs.EnableRedraw(False)

        # this is the correct field
        for i in range(0, a, 1):
            for j in range(0, b, 1):
                print('iteration %s in RunProc()' % (k))
                temp_site_crv = rs.CopyObject(self.site_crv,
                                              [self.max * i, self.max * j, 0])
                self.site_copy.append(temp_site_crv)
                m = main(FileName, self.fsr, temp_site_crv)
                r = m.getInpObj()
                self.res_obj.append(r)
                m.genFuncObj_Site()
                s = m.retResult()
                req_str_li.append(s)
                pt = rs.CurveAreaCentroid(temp_site_crv)[0]
                self.loc_pts.append(pt)
                self.addLabel(k, temp_site_crv)
                k += 1
        try:
            self.writeToCsv(k, req_str_li)
        except:
            pass
        # end of correct code block

        # start of revised code block
        """
        for i in range(0,a,1):
            for j in range(0,b,1):
                print('iteration %s in RunProc()'%(k))
                temp_site_crv=self.site_crv#rs.CopyObject(self.site_crv,[self.max*i,self.max*j,0])
                self.site_copy.append(temp_site_crv)
                m=main(FileName,self.fsr,temp_site_crv)
                r=m.getInpObj()
                self.res_obj.append(r)
                m.genFuncObj_Site()
                s=m.retResult()
                req_str_li.append(s)
                pt=rs.CurveAreaCentroid(temp_site_crv)[0]
                self.loc_pts.append(pt)
                self.addLabel(k,temp_site_crv)
                rs.RenderColor(1,(255,255,255))
                str_img=str(k+1)+'.png'
                rs.Redraw()
                #rs.Command("_ViewCaptureToFile",tr_img)
                rs.CreatePreviewImage(str_img, "Perspective", (1200,1024), 4, False)
                print('img created')
                m.delResult()
                k+=1
        self.writeToCsvPcp(k,req_str_li)
        """
        #end of revised code block

        rs.EnableRedraw(True)
Exemplo n.º 22
0
import rhinoscriptsyntax as rs
import createBox
import exportObjs

xNum = rs.GetInteger("X number", 5, 1)
yNum = rs.GetInteger("Y number", 5, 1)
boxes = createBox.Run(xNum, yNum)
if boxes is None or len(boxes) == 0:
    rs.MessageBox("No objects to export")
else:
    dir = rs.BrowseForFolder(None, "Select a folder to save files")
    exportObjs.Run(boxes, dir, "3dm")
clr.AddReference('System.Core')
clr.AddReference('RhinoInside.Revit')
clr.AddReference('RevitAPI')
clr.AddReference('RevitAPIUI')

from System.Linq import Enumerable
from Autodesk.Revit.DB import *
import Rhino as rh
from RhinoInside.Revit import Revit, Convert
import ghpythonlib as gh
import scriptcontext as sc
import rhinoscriptsyntax as rs

# Select polylines from rhino
obj = rs.GetObjects("Please select multiple polyline curves", 0, True, True)
bool2 = rs.GetInteger("Press 0 to generate areas and 1 to generate rooms")
input_curves = []
for o in obj:
    input_curves.append(rs.coercecurve(o))

doc = Revit.ActiveDBDocument
tol = sc.doc.ModelAbsoluteTolerance
_t = 100000000

# Filter out various revit elements
levels = FilteredElementCollector(doc).OfClass(Level)
rooms = FilteredElementCollector(doc).OfClass(SpatialElement).OfCategory(
    BuiltInCategory.OST_Rooms).ToElements()
areas = FilteredElementCollector(doc).OfClass(SpatialElement).OfCategory(
    BuiltInCategory.OST_Areas).ToElements()
views = FilteredElementCollector(doc).OfClass(ViewPlan).ToElements()
Exemplo n.º 24
0

def getVertexString(point):
    return "v " + str(point[0]) + " " + str(point[1]) + " " + str(
        point[2]) + "\n"


def getFaceString(indexes):
    faceString = "f"
    for index in indexes:
        faceString = faceString + " " + str(index)
    return faceString + "\n"


polysurfaces = rs.GetObjects('select polysurfaces', 16)
nU = rs.GetInteger("u", 1)
nV = rs.GetInteger("v", 1)
filename = rs.SaveFileName()
vertices = {}
vI = 1
# file = open("testPythonexport.obj", "w")
file = open(filename, "w")
for polysurface in polysurfaces:
    surfaces = rs.ExplodePolysurfaces(polysurface)
    for surface in surfaces:
        domainU = rs.SurfaceDomain(surface, 0)
        dU = (domainU[1] - domainU[0]) / nU
        domainV = rs.SurfaceDomain(surface, 1)
        dV = (domainV[1] - domainV[0]) / nV
        for i in range(nU):
            for j in range(nV):
Exemplo n.º 25
0
            else:
                # print "Cool"
                centroid = rs.CurveAreaCentroid(pl)
                centpt = rs.AddPoint(centroid[0])
                curves = rs.ExplodeCurves(pl)
                for crv in curves:
                    # print crv
                    pt1 = rs.CurveStartPoint(crv)
                    pt2 = rs.CurveEndPoint(crv)
                    pts = []
                    pts.append(pt1)
                    pts.append(pt2)
                    pts.append(centpt)
                    pts.append(pt1)
                    newpl = rs.AddPolyline(pts)
                    pls.append(newpl)
                    rs.DeleteObject(crv)
                cleanup = []
                cleanup.append(centpt)
                # cleanup.append(curves)
                rs.DeleteObjects(cleanup)
        count = count - 1
        return crackpolygon(pls, count)


count = rs.GetInteger("How many iterations would you like to do?", 3)
pl = rs.GetCurveObject("pick a closed curve to crack")
plguid = pl[0]
polygons = []
polygons.append(plguid)
crackpolygon(polygons, count)
Exemplo n.º 26
0
# This script can be used to generate shipflow offsets from rhino surface
# ---------------------------
#|                          |
#|                          |
#AP-------------------------FP

#x2_________________________x1
# the points x1 and x2 should be below the base line

#x1 should be the foreend of the hull surface
#x2 Aft End

x1 = rs.GetPoint("Pick start point")
x2 = rs.GetPoint("Pick end point")
h = rs.GetPoint("Pick a point above deck")
n = rs.GetInteger("Number of stations", 30, 0)
dx = rs.Distance(x1, x2) / n

#  file for saving shf file
surface = rs.GetObject("Select surface to project onto", rs.filter.surface)
filter = "Text File (*.shf)|*.shf|All Files (*.*)|*.*||"
filename = rs.SaveFileName("Save point coordinates as", filter)
###

file = open(filename, "w")
file.write("hull \n")

for i in range(1, n):
    flg_stn = 1
    c1 = (x1[0] - i * dx, x1[1], x1[2])
    c2 = (x1[0] - i * dx, x1[1], h[2])
import rhinoscriptsyntax as rs

idSurface = rs.GetObject("Surface to frame", 8, True, True)
faces = []

intCount = rs.GetInteger("Number of iterations per direction", 20, 2)

uDomain = rs.SurfaceDomain(idSurface, 0)
vDomain = rs.SurfaceDomain(idSurface, 1)
uStep = int((uDomain[1] - uDomain[0]) / intCount)
vStep = int((vDomain[1] - vDomain[0]) / intCount)

rs.EnableRedraw(False)
for u in range(int(uDomain[0]), int(uDomain[1]), int(uStep)):
    for v in range(int(vDomain[0]), int(vDomain[1]), int(vStep)):
        pt = rs.EvaluateSurface(idSurface, u, v)
        srfFrame = rs.SurfaceFrame(idSurface, [u, v])
        rs.AddPlaneSurface(srfFrame, 2.0, 2.0)
        #rs.AddEllipse(srfFrame, 1.0, 3.0)
        component = rs.GetObject("component to populate", rs.filter.mesh)
        faces = rs.MeshFaces(component, False)
        rs.AddMesh(faces, srfFrame)

rs.EnableRedraw(True)
Exemplo n.º 28
0
# use rhinoscriptsyntax to get all the functions in one shot
import rhinoscriptsyntax as rs
import random
import time
import Rhino

count = rs.GetInteger("Number of points")

points = []
if count:
    x = 0
    y = 0
    z = 0

    xadd = 0
    yadd = 0

    rmin = 1
    rmax = 20
    toggle = 1

    rs.AddPoint([x, y, z])
    points.append([x, y, z])

    for i in range(count):
        #         time.sleep(0.001)

        xadd = random.randint(rmin, rmax)
        yadd = random.randint(rmin, rmax)

        if (i % 2 == 0):
from System.Drawing import Color
'''
What it does is exporting drawings uniformly arranged on the plan to each .dwg file
'''

#This part defines start position of drawings
X_ST = 0
Y_ST = 0

#Change the girdsize based on your project
X_Step = 9000
Y_Step = 10000

#Define the prefix of each file
Sail_Name = rs.GetString("Input Sail Number")
x = rs.GetInteger("Number of Drawings in X direction")
y = rs.GetInteger("Number of Drawings in Y direction")
direct = rs.BrowseForFolder(None, "Choose a folder", None)

#Define color to exort geometry to DWG cause cannot see black in DWG
Black = Color.Black
White = Color.White

#Change black color to white
layers = rs.LayerIds()
for layer in layers:
    print rs.LayerColor(layer)
    if rs.LayerColor(layer) == Black:
        rs.LayerColor(layer, White)

#Select the drawings which are in grid and export.
Exemplo n.º 30
0
                filePath = baseName + "_" + eachView + ".jpg"
                result = SafeCapture_JPG(filePath, width, height)

        #return to original view
        rs.RestoreNamedView("temp")
        rs.DeleteNamedView("temp")


        result = True
    except:
        result = False
    utils.SaveFunctionData('IO-BatchCapture', [__version__] + chosenViews)
    return result

if __name__ == "__main__" and utils.IsAuthorized():
    func = rs.GetInteger("Function to run", number = 0)
    if func == 0:
        result = importCAD_Button()
        if result: utils.SaveToAnalytics('IO-Import CAD')
    elif func == 1:
        result = exportToRenderDWG()
        if result: utils.SaveToAnalytics('IO-Export To Render DWG')
    elif func == 2:
        result = exportToRenderSKP()
        if result: utils.SaveToAnalytics('IO-Export To Render SKP')
    elif func == 3:
        result = CaptureDisplayModesToFile()
        if result: utils.SaveToAnalytics('IO-Capture Display Modes')
    elif func == 4:
        result = SafeCaptureButton()
        if result: utils.SaveToAnalytics('IO-Safe Capture')