Quantcast
Channel: Scripting - McNeel Forum
Viewing all 4125 articles
Browse latest View live

DisplayConduit and point editing

$
0
0

Clement wrote:

I´m drawing points, curves and meshes in a display conduit based on geometry existing in the rhino document. The display is performed permanently and saved in sticky. With a different script i disable the conduit.

How can i make my dynamic displayed objects follow point edits and and transforms (eg. on a surface in the document) ? Is there an example preferably in python ?

thank you in advance,
c.

Posts: 1

Participants: 1

Read full topic


Selecting same radius circles

$
0
0

Peter Hennessey wrote:

Hi,

here is simple script to select all the circles of a certain radius. It should be pretty straight forward. However, when I run it I find it only finds SOME of the circles of that radius. When I look at the ones it doesn't select, they seem to have an identical radius to the ones it did select.

rs.UnselectAllObjects()
diam = rs.GetReal("Diameter to search", 5.0 )
srchrad = diam/2.0
objs = rs.ObjectsByType (4, select=False)
info = 0
for object_id in objs:
	if rs.IsCircle(object_id):
		if rs.CircleRadius(object_id) == (srchrad):
			rs.SelectObject(object_id)
			info += 1
print str(info) + " objects selected"

I'm wondering if it has something to do with rounding, or if the object has been scaled or moved or copied or something. Any suggestions?

Thanks
Peter

Posts: 11

Participants: 7

Read full topic

Strange Fillet Surface problem

$
0
0

Filip Rooms wrote:

Dear community,

I encountered a strange surface fillet problem today... The Rhino 3dm file contains three planes, which need to be filleted. The bottom and right plane work, the bottom and left plane don't, not when I try to fillet after the fillet right, and not even when I try to fillet the left plane first... Trying it manually on the command line and manually selecting the surfaces works fine however, just not in the script... Anything special with the left side plane?

Anyone an idea? Many thanks in advance...

PlanesFillet.3dm (37.2 KB)

I tried the following script:

    Sub Main()
	Dim idPlaneLeft, idPlaneRight, idPlaneBottom, arrTemp

	If Not isnull(rhino.allobjects) Then
		rhino.DeleteObjects rhino.allobjects
	End If

	'import and assign objects; adjust path to refer to the file above
	Rhino.Command "_Import D:\UserData\PlanesFillet.3dm"
	arrTemp = rhino.allobjects

	idPlaneLeft = arrTemp(0)
	idPlaneRight = arrTemp(2)
	idPlaneBottom = arrTemp(1)

	'fillet right and bottom plane
	Rhino.Command "_SelNone"
	Rhino.Command "_FilletSrf _R 45 _SelID " & idPlaneRight & " _SelID " & idPlaneBottom

	arrTemp = Rhino.LastCreatedObjects 

	'fillet left and bottom plane
	Rhino.ObjectColor idPlaneLeft, RGB(255, 255, 0)
	Rhino.ObjectColor arrTemp(0), RGB(255, 255, 0)

	Rhino.Command "_SelNone"
	Rhino.Command "_FilletSrf _R 45 _SelID " & idPlaneLeft & " _SelID " & arrTemp(0)
End Sub

Kind regards,

Filip

Posts: 2

Participants: 2

Read full topic

Leap motion + rhino python

$
0
0

Guido Maciocci wrote:

Hi all,

I have been toying around with the Leap Motion controller and it's API in Python.

My goal is to write some scripts in Rhino Python which leverage the data acquired from the Leap controller. I thought I'd share my findings so that others may benefit but also to ask questions relating to the stability of running Leap within Rhino Python.

The setup process to access the Leap libraries from within Rhino Python is as follows:
Created a rhino python script called leapTst.py in a folder
To the folder I added the relevant files from the Leap SDK Dev Kit. The files in the folder are the following, including the leapTst.py test script:
Leap.dll
Leap.py
Leap.pyc
LeapCSharp.dll
LeapCSharp.NET4.0.dll
leapTst.py

At the beginning of the leapTst.py script I use clr.AddReferenceToFileAndPath and point it to the LeapCSharp.NET4.0.dll assembly inside the folder.

Also in the script, the path to the Leap SDK x64 libraries folder is appended to sys.path to reference the correct libraries.

I then adapted the Sample.py file from the Leap SDK samples folder in Rhino Python to create a custom SampleListener which retrieves frame data from the Leap controller and prints it to the Rhino console.

I noticed that while using the listener callback function and the OnFrame() method to retrieve frame data, Rhino would crash as soon as the listener began 'listening' to the incoming stream of data. In order to debug the script I customized the SampleListener class so that it would just return the Frame ID and Timestamp of the current frame from the Leap controller. This is very stable and Rhino does not crash.

As soon as I make the OnFrame method retrun any other frame data, such as the Fingers.TipPosition or HandSphereRadius, then the script crashes Rhino.

Reading the Leap API, there is a note on using the listener callback functions to retrieve frame data that mentions the process is multithreaded and therefore one must ensure that it is run in a threadsafe manner. Could this be the reason why Rhino crashes?

What other methods could be used in Rhino Python (considering that Rhino itself has no inherent application frame rate) to poll the controller for frame data? Timer? Event based polling?

Any help on this would be greatly appreciated. Following is the test script code:

import sys
import clr
import scriptcontext
import rhinoscriptsyntax as rs
import Rhino
import time

clr.AddReferenceToFileAndPath("C:\Users\GMAC\Desktop\leap RHINO test\LeapCSharp.NET4.0.dll")

pathsToLibs = ["C:\\Users\\GMAC\\Documents\\PROJECTS\\CODING\\LEAP MOTION\\LeapDeveloperKit\\LeapDeveloperKit\\LeapSDK\\lib\\x64"]

for path in pathsToLibs:
    sys.path.append(path)

print sys.path

import Leap

from Leap import CircleGesture, KeyTapGesture, ScreenTapGesture, SwipeGesture

class SampleListener(Leap.Listener):
    def OnInit(self, controller):
        print "Initialized"

    def OnConnect(self, controller):
        print "Connected"

    def OnDisconnect(self, controller):
        # Note: not dispatched when running in a debugger.
        print "Disconnected"

    def OnExit(self, controller):
        print "Exited"

    def OnFrame(self, controller):
        # Get the most recent frame and report some basic information
        print "This is a frame"
        frame = controller.Frame()
        print frame

        hands = frame.Hands
        if hands.Count > 0:
            print "Found {} hands".format(hands.Count)
            if hands.Count == 1:
                hand = hands[0]
                Leap.Hand.SphereRadius
                handSphereRadius = hand.SphereRadius
                handSphereCentre = hand.SphereCentre
                print handSphereRadius
                print handSphereCentre



def main():
    # Create a sample listener and controller
    listener = SampleListener()
    controller = Leap.Controller()

    # Have the sample listener receive events from the controller
    controller.AddListener(listener)

    # Keep this process running until Enter is pressed
    print "Press ESCape to quit..."
    running = True
    while running:
        escape = scriptcontext.escape_test(False)
        if escape:
            running = False
    # Remove the sample listener when done
    print "Shutting down"
    controller.RemoveListener(listener)


if __name__ == "__main__":

    main()

Posts: 2

Participants: 1

Read full topic

Work around for ObjectTopGroup

$
0
0

Peter Hennessey wrote:

Hi,

I'm wondering if anyone has a quick workaround for ObjectTopGroup which is apparently not implemented in Python yet...

My first guess is the count the members in all the groups an object is attached to and go with the one that has the most members, but I'm sure there is a more foolproof/better way...

I got such a great response to my last question, I thought I'd keep asking smilecheers peter

Posts: 1

Participants: 1

Read full topic

GetBoundingBox Aligned to Plane

$
0
0

Ryan Gathmann wrote:

I am trying to get the bounding box of a curve aligned to a plane. If I use GetBoundingBox(True), the boxes show up in the correct location. However if I use GetBoundingBox(plane) or GetBoundingBox(transform). The bounding box is always in the wrong place.Do I need to transform the bounding box after it is created?

Thanks!

Posts: 3

Participants: 2

Read full topic

Scaling Objects in Fractal Shape Generation (Script Broken)

$
0
0

Ryanyde wrote:

Hi guys,

I'm new this semester both to Rhino and programming--I am making my way through David Rutten's Rhino101 and finally decided to edit my script for a final project in a class I am taking. Unfortunately, the script that I edited that once worked is now broken, and I'm literally breaking it more trying to debug it.

The script is designed to make a set of rotated pentagons that branch each generation into 2 more pentagons. The original (working) script is here so you can see how I've broken it:
http://www.giuliopiacentino.com/tree-and-lake/

The idea was to:
1) Change the shapes to pentagons
2) Scale each object by a random amount (between .9 and 1.1) so that the final shapes could be booleaned together (this is where a lot of the trouble comes).

I would be really grateful for any help--since additional work I do seems to make the problem worse, rather than better.

Thanks again!
Ryan

    Sub makeGrowingTree
	Rhino.AddLayer("Algorithm Tester")
	Rhino.CurrentLayer("AlgorithmTester")
	Dim originPoint, arrPlane, arrPentagonOrigin, arr3dX, arr3dY, arr3dZ, advanceBy
	'Shapes changed from circles to Pentagons, but any shape may be used
	Dim pentagon, rotatedPentagon
	'Declaring variables with the name of the shape helps understand, make sure to change these
	Dim angleX:angleX = 15
	Dim angleZ:angleZ = 25
	'Sets Rotation Angle, in this case only rotating in the X and Z axis
	originPoint = Array(0, 0, 0)
	'Sets the origin
	advanceBy = Array(0, 0, 10)
	'Number of units you will increase in each generation.  This is fixed
	Dim generations:generations = 3
	'Number of times the script will run
	Dim listGenerations()
	ReDim listGenerations(generations,4^generations-1)
	'Each time you are increasing the number of times you run the script by 4^n-1
	Dim cumulativeRotations()
	ReDim cumulativeRotations(4^generations-1)


	Dim generationNum, childNum, colsToFill, startToFill, fillingChild

	'draw the pentagon
	arrPentagonOrigin = Array(0, 0, 0)
	arr3dX = Array(1, 0, 0)
	arr3dY = Array(0, 1, 0)
	arr3dZ = Array(0, 0, 1)
	arrPlane = Array(arrPentagonOrigin, arr3dX, arr3dY, arr3dZ)
	'dimension of the pentagon 
	pentagon = Rhino.addPolygon(arrPlane, 5, 5)
	'Change the number of sides and size of the polygon.  First 5 is the radius, the second 5 is the number of sides
	For childNum = 0 To 2 ^ generations - 1
		cumulativeRotations(childNum) = 0
		listGenerations(0, childNum) = pentagon
	Next

	For generationNum = 1 To generations
		For childNum = 0 To 4 ^ generationNum - 1

			colsToFill = 4 ^ (generations - generationNum)
			startToFill = childNum * colsToFill

			For fillingChild=0 To colsToFill - 1
				If (childNum Mod 2) = 0 Then
					cumulativeRotations(fillingChild + startToFill) = cumulativeRotations(fillingChild + startToFill) + angleX
				Else
					cumulativeRotations(fillingChild + startToFill) = cumulativeRotations(fillingChild + startToFill) - angleX
				End If                 
			Next

			Dim dblLow:dblLow = 0.90
			Dim dblHigh:dblHigh = 1.10
			Randomize
			Dim Random:Random = Rnd * (dblHigh - dblLow) + dblLow
			Dim arrRand:arrRand = (Random,Random, Random)
			arrPentagonOrigin = Rhino.CurveMidPoint(listGenerations(generationNum - 1, startToFill))
			'CurveMidPoint replace Circle Center
			'MsgBox generationNum 

			'the new circle is copied and repositioned 
			rotatedPentagon = Rhino.scaleObject(listGenerations(generationNum - 1, startToFill), arrPentagonOrigin, Array(0.8, 0.8, 0.8), True)          
			Rhino.MoveObject rotatedPentagon, originPoint, advanceBy
			Rhino.RotateObject rotatedPentagon, originPoint, cumulativeRotations(startToFill), arr3dX, False
			Rhino.RotateObject rotatedPentagon, originPoint, angleZ * Sqr(generationNum), arr3dZ, False
			Rhino.ScaleObject(rotatedPentagon, arrPentagonOrigin, arrRand, False)

			'MsgBox "Generation is " & generationNum & "." & Chr(13) & "Columns to fill are " & colsToFill & ". Start filling at " & startToFill & "."


			For fillingChild=0 To colsToFill - 1
				listGenerations(generationNum, fillingChild + startToFill) = rotatedPentagon              
			Next
		Next  
	Next


	'Prepare the 2-dimension array to a 1-dimension and loft
	Dim arrCurves(), i
	ReDim arrCurves(UBound(listGenerations,1))

	For childNum=0 To UBound(listGenerations, 2)

		For i=0 To UBound(listGenerations, 1)
			arrCurves(i) = listGenerations(i, childNum)
		Next



		Rhino.AddLoftSrf arrCurves  'normal
		'Rhino.AddLoftSrf arrCurves, , , 1  'loose
		'Rhino.AddLoftSrf arrCurves, , , 2  'tight

	Next


End Sub

Rhino.EnableRedraw False
Call makeGrowingTree
Rhino.EnableRedraw True

Posts: 1

Participants: 1

Read full topic

A Python strategy to iterate through objects?

$
0
0

Dan Bayn wrote:

I seem to be stuck on what is probably a basic concept. I have attached a file that shows 5 items. There appears to be 3 because 2 of the items are "duplicates" of the others, although not in a strict enough sense to let the SelDup command find them.

Is there a strategy using Python to iterate through the details and find those that match, perhaps by volume in the case of a closed polysurface? It's the iteration part that I need guidance on.

Thanks,

Dan

Objects.3dm (163.9 KB)

Posts: 6

Participants: 3

Read full topic


ViewCaptureToFile via Python Script

Scripting changes via Python, Rhino won't exit if I take a screenshot

$
0
0

Marcus Rademacher wrote:

I'm having trouble with a Python script I wrote to modify some parameters in GH, update the geometry, and then exit. I'd like a screentshot of the updated geometry, and when I include that command the exit is ignored and Rhino stays open waiting for user input. Here's my script:

import clr
clr.AddReferenceByName("Grasshopper")

import System
import Rhino
import Grasshopper
from Rhino import RhinoApp, RhinoDoc
from Rhino.Geometry import *
import rhinoscript as rs

radius = 5.5
height = 8.5

gh = RhinoApp.GetPlugInObject("Grasshopper")
gh.LoadEditor()
gh.CloseAllDocuments()
gh.ShowEditor()
gh.OpenDocument("definedvolume.ghx")

docServer = Grasshopper.GH_InstanceServer.DocumentServer
doc = docServer[0] # first opened document

def FindBatteryByNickname(docObjects, name):
if docObjects is None: return None
for obj in docObjects:
attr = obj.Attributes
if attr.PathName == name:
return obj
raise Exception(name + " was not found in document")

radiusSlider = FindBatteryByNickname(doc.Objects, "Radius")
heightSlider = FindBatteryByNickname(doc.Objects, "Height")

radiusSlider.SetSliderValue(radius)
heightSlider.SetSliderValue(height)

gh.RunSolver(False)

volumeObj = FindBatteryByNickname(doc.Objects, "VolumeOutput")
stringOut = volumeObj.InstanceDescription.decode('unicode_escape').encode('ascii','ignore')
vol = stringOut.split('\n')[1]
outputFile = open('volume.txt', 'w')
outputFile.write('Volume\n')
outputFile.write(vol)
outputFile.close()

path = "C:\Temp\"

rs.application.Command("-ScreenCaptureToFile " + path + "cyl.jpg")
gh.CloseAllDocuments()
rs.application.Command("
Exit")

I tried two different screenshot commands. Both generate a screenshot, but neither will exit. If I comment out the screenshot command it exits as expected. I'd appreciate any help figuring out how to get it to do both the screenshot and exit.

As a secondary question, it doesn't appear that Rhino has a background execution. The screenshot also will grab whatever's on the screen where the perspective viewport is, resulting in screenshots of folders or other applications if I run this and look at something else on that screen. Anyone have a solution to that?

Thanks,
Marcus

Posts: 3

Participants: 2

Read full topic

Run Rhino in background with scripting

$
0
0

Marcus Rademacher wrote:

Is there a way to run Rhino with a script in the background? Right now I call

"C:/Program Files/Rhinoceros 5 (64-bit)/System/Rhino.exe" /nosplash /runscript="! _-RunPythonScript script.py"

...but this opens Rhino in the standard interactive mode while executing the script. It'd be better if it was possible to have it run in the background so it doesn't pop up in the user's face while the script is executing.

Posts: 2

Participants: 2

Read full topic

Script to rotate objects 90 degrees around their center

$
0
0

Cosmas Demetriou wrote:

To the scripting world:

I have a feeling there is a script for this, but I am looking for a way to select an object, say in an ortho view (or even in perspective mode) and with an alias have it rotate 90 degrees either vertically or horizontally around it's center. There would be four aliases: Turn right or left around a vertical axis through its center and turn up or down around a horizontal axis through its center.

Is this doable?

Thank you.

Posts: 10

Participants: 3

Read full topic

RS JoinSurfaces

$
0
0

Don Lewis wrote:

JoinSurfaces does not appear to work, I can replace it with "Rhino.Command ("Join") and that works. (Yes, they are surfaces)

If lcase(extspec) = "igs" Then
  igsSelect = Rhino.LastCreatedObjects(True)
  Call Rhino.ObjectLayer(igsSelect, ParLayer)
  Call Rhino.JoinSurfaces(igsSelect,True)
  Call Rhino.UnselectAllObjects()
End If

Thanks,
Don

Posts: 3

Participants: 3

Read full topic

HtmlBox Icon Customization

$
0
0

gfr wrote:

I use the HtmlBox command in RhinoScript quite often and I've tried in the past to customize the HtmlBox icon without any luck. Anyone know how to customize the HtmlBox icon? Thanks.

Posts: 2

Participants: 2

Read full topic

Graph mapper in Python?

$
0
0

Tingwei D wrote:

hi ,everyone, I was trying to implement graph mapper in python via
the latest ghpythonlib , however, I could not find the functions in the
library , so I wondering where I could find it or any extra library I need to add.
the current solution I have is : I have to go through the graph mapper component in
grasshopper, and give it a predefined amount of values which will be used for later calculation in
my scripting component. the shortage is when it comes to a situation with random amount,
this method would never work, it only works with fixed amount of values.
thank you all for help!!!!!!

Posts: 1

Participants: 1

Read full topic


Understanding scriptcontext vs ghdoc

$
0
0

Mathias Gmachl wrote:

Hi,

I am familiar with GH, but new to Python. I found a Python script that I'd like to 'port' to a GH context. It uses scriptcontext a lot (to reference geometry in the open document).

https://github.com/jlopezbi/DLA_heatSink

I understand that I can reference geometry and parameters easily from the GH definition. Is it the right approach to remove all instance of scriptcontext and find more GH native solutions?

Thanks for you insights.

Posts: 1

Participants: 1

Read full topic

Python Snap method doesn't work

$
0
0

Dan Bayn wrote:

I tried running the sample script in the help file, and Snap doesn't seem to be working.

import rhinoscriptsyntax as rs
if not rs.Snap(): rs.Snap(True)

If I turn it on manually and go the other way (attempt to shut it off) it still doesn't work.

import rhinoscriptsyntax as rs
if rs.Snap(): rs.Snap(False)

Thanks,

Dan

Posts: 3

Participants: 2

Read full topic

ViewCaptureToFile saves the wrong mode

$
0
0

Jeff Thompson wrote:

I'm trying to create a bulk renderer using Python on Rhino for Mac.

  1. I set the view to rendered using -SetDisplayMode Viewport=Active Mode=Rendered _Enter which works.
  2. I render the view to file using -ViewCaptureToFile "output.png" _Enter which also works...

But the rendered view isn't in Rendered mode, it's in whatever was previously chosen!

Here's the full code, in case I've missed something obvious:

rs.Command('_SetDisplayMode _Viewport=_Active _Mode=_Rendered _Enter')

rs.Command('-ViewCaptureToFile "thumbnails/' + filename[0:-4] + '.png" Width=' + str(width) + ' Height=' + str(height) + ' TransparentBackground=Yes _Enter')

Posts: 8

Participants: 4

Read full topic

User interface in OSX

$
0
0

Peter Hennessey wrote:

Hi,

I'm not sure if this should go to Mac Rhino or Scripting, but...

Obviously in the move from VB to Python and into OSX user interface dialog box stuff is going to be the hardest, as it is os specific. This list of UI methods that don't work on Mac are pretty long but you can work around them with a series of GetStrings and MessageBox calls but its pretty clunky.

However, the standard install of IronPython comes with a bunch of built-in user interface modules such as tkinter and EasyDialogs (for example) that allow pretty extensive UI coding. These seem to have been stripped out of the Mac Rhino IronPython install that I have installed. (They are there in OSX's native Python install, which lives somewhere else.)

Is this right? Would it be possible or sensible to add those modules in to my install? How would I do that? Or is there a good reason not to use them?

Obviously I would prefer a more 'native' Rhino UI, like the tool options that come up when you type _Box but I can't see that being a short term priority for a busy development team smile

thanks
Peter

Posts: 2

Participants: 2

Read full topic

IronPython is 2.7, will I be able to update for Python 3.4?

$
0
0

Stephan Park wrote:

Hi guys, I'm an old time Rhino user since it was a public beta.
I noticed that Rhino is using IronPython 2.7. Unfortunately, I recently finished up a Python 3.x instruction so I'm wondering if there is a way to update IronPython separately, if not will I have to start learning Python 2..x vs. 3.x differences.

Posts: 2

Participants: 2

Read full topic

Viewing all 4125 articles
Browse latest View live