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

R7 Problems exporting stl using rhinoscript/python

$
0
0

hi there,

i am often exporting via python- /rhinoscript a lot of breps automaticaly as stl due to a necessary Workflow. Since R7 i kind of can not prevent Rhino from asking me this Dialog:

Choose STL option ( ExportFileAs=Binary ExportUnfinishedObjects=Yes UseSimpleDialog=No )

I tried to deactivate it by telling Rhino always to use the same options but it keeps on asking me this for each geometry. Am i missing something ?

Here`s my code:

            mid = sc.doc.Objects.AddMesh(mobj)
            rs.UnselectAllObjects()
            rs.SelectObjects(mid)
            cmd = '_-Export "{}" _enter'.format(file_path)
            rs.Command(cmd)
            sc.doc.Objects.Delete(mid,True)

Thanks for the help

4 posts - 2 participants

Read full topic


Delete points in the middle of straight edges of a surface

$
0
0

Hi all,
I am generating different geometries starting from squared cells. Once I find the cells and I join them to get the shape I want, I would like to get right of the points between my corners. I am looking for a way to do this in rhinocommon and python if possible. This is what I get, you can see the midpoints on the edges due to the generation from smaller cells:

For now, I was just able to do get rid of those points using the Discontinuity component. So, I implemented it in my code like this after picking the cells:

import Rhino.Geometry as rg
import ghpythonlib.components as gh
joinedCells = rg.Brep.JoinBreps(cells, 0.01)[0] # put [0] to get one brep, otherwise it is an Array[Brep]
# use three lines to delete inner edges and keep only countour curve and create surface from that
nakedEdges = joinedCells.DuplicateNakedEdgeCurves(True, False)
curveFromEdges = rg.Curve.JoinCurves(nakedEdges, 0.01, True)[0]
curveNoMidPoints = gh.PolyLine(gh.Discontinuity(curveFromEdges, 1)[0], True) # this line to avoid having points in the middle of a straight line
surfaceFromCurve = rg.Brep.CreatePlanarBreps(curveNoMidPoints , 0.01)[0]

As you can see from the picture below I don’t have those points anymore. But I would like to solve this issue by using rhinocommon.

5 posts - 2 participants

Read full topic

My script is flawed both logically and programatically, extra eyes needed

$
0
0

i’ve got a script that i have hacked away at. it originally might have been @Helvetosaur or @pascal script.

what i’m looking to do is find layers that have hidden objects in them, select from a list the layers that have hidden objects, show the hidden objects isolated with the option to either keep that isolated display state or revert back to the original display state pre script.

first, if i hit cancel on the layer list that comes up, it’s not reverting to it’s original state, it’s keeping the state with all the layers turned on and i can’t remember exactly why i had to turn them all on at the start but i’m missing something and it’s probably obvious.

second, i’m using a lot of hacks with Rhino.Command i think there maybe a better way to go about the saving and reverting layer states. is this the best way to do this? are there any improvements i could make?

thank you

sorry it isn’t that readable, for some reason it is double spacing my copy paste :frowning:

IsolateHiddenObjects.rvb (2.2 KB)

' https://developer.rhino3d.com/api/rhinoscript/layer_state_methods/layer_state_methods.htm

Option Explicit

'Call IsolateHiddenObjects()

Sub IsolateHiddenObjects()

    ' turn off refresh

    'Call Rhino.EnableRedraw(False)

    ' enable LayerTools

    Dim objPlugIn

    On Error Resume Next

    Set objPlugIn = Rhino.GetPluginObject("Rhino Bonus Tools")

    If Err Then

        MsgBox Err.Description

        Exit Sub

    End If

    

    ' save current layer state

    Call objPlugIn.SaveLayerState("temp")

    ' turn all layers on

    Dim strLayer

    Dim arrLayers: arrLayers = Rhino.LayerNames

    If IsArray(arrLayers) Then

        For Each strLayer In arrLayers

            If Rhino.LayerVisible(strLayer) = False Then

                Rhino.LayerVisible strLayer, True

            End If

        Next

    End If

        

    ' check for hidden

    Dim aHid : aHid = Rhino.HiddenObjects

    If Not IsArray(aHid) Then

        Rhino.Print "There are no hidden objects in this file."

        Rhino.EnableRedraw(True)

        Exit Sub

    End If

    ' prepare for dialog display

    Dim sHid, n

    Dim aLayers()

    n = 0

    For Each sHid In aHid

        ReDim Preserve aLayers(n)

        aLayers(n) = Rhino.ObjectLayer(sHid)

        n = n + 1

    Next

    Dim aCull: aCull = Rhino.CullDuplicateStrings(aLayers)

    n = 0

    Dim sLayer

    For Each slayer In aCull:

        ReDim Preserve aStates(n)

        aStates(n) = False

        n = n + 1

    Next

    
    

    ' display checklist

    Dim ShowLayers : Showlayers = Rhino.CheckListBox(aCull, aStates, "Select layers to show objects", "Layers with hidden objects")

    If Not IsArray(ShowLayers) Then Exit Sub

    Dim Id

    For n = 0 To UBound(aCull)

        If ShowLayers(n) = True Then

            For Each ID In Rhino.ObjectsByLayer(aCull(n))

                Rhino.ShowObject(Id)

            Next

        End If

    Next

    

    ' display results

    Call Rhino.SelectObjects(aHid)

    Dim hObjects : hObjects = rhino.UnselectedObjects

    Call rhino.HideObjects(hObjects)

    Call rhino.UnselectObjects(aHid)

    ' turn refresh back on

    'Call rhino.EnableRedraw(True)

    

    ' restore or not?

    Dim question : question = Rhino.MessageBox("Restore previous state?", 1)

    If (question = 1) Then

        ' restore to pre command

        Call rhino.HideObjects(aHid)

        Call objPlugIn.RestoreLayerState("temp", 2)

        Call rhino.ShowObjects(hObjects)

        Call objPlugIn.DeleteLayerState("temp")

        Exit Sub

    End If

    

    Call objPlugIn.DeleteLayerState("temp")

    

End Sub

2 posts - 2 participants

Read full topic

Python toolbar update

$
0
0

Hello , i have a problem with closing and reopen and showing a toolbar ( like an update of him ), the code it’s attached at this post , what i m missing?

import rhinoscriptsyntax as rs
import Rhino

def updatetools():
update = 1 #0 = no update // 1 = ready for update

if update == 0:
    
    rs.MessageBox("Everything is up to date")
    exit()

else:

    s = rs.ToolbarCollectionNames()
    rs.HideToolbar("CPE_TOOLBAR","CPE_TOOLBAR")
    rs.CloseToolbarCollection("CPE_TOOLBAR",False)
    toolbar =rs.OpenToolbarCollection("P:\_Development\Rihno Python Scripts\CPE-RHINO\CPE_TOOLBAR.rui")
    if toolbar:
        test = rs.ShowToolbar("CPE_TOOLBAR","CPE_TOOLBAR")
        if rs.IsToolbarVisible("CPE_TOOLBAR", "CPE_TOOLBAR"): print "The Layer toolbar is visible."
        else: print "The Layer toolbar is not visible."


updatetools()

1 post - 1 participant

Read full topic

Trim with Closed Polysurface Multiple Objects

$
0
0

Is there a way to trim multiple objects using as cutting object a closed polysrf so that all surfaces that standing outside of a closed polysrf are removed?
I have attached an example. The blue color is the cutting object and with red are the surfaces that i would like to trim.
Thanks in advance!

trim_outside object.3dm (197.0 KB)

2 posts - 2 participants

Read full topic

How to find the genus (number of "handles") of a closed surface?

$
0
0

Hello,

I would like to know if there is a way to determine the genus (number of “handles or holes”) of a closed surface by scripting?

That would be used to find if there was a problem with text engraving punching holes through thin parts of my closed 3D surface. My original closed surface is topologically equivalent to a sphere and punching holes in it would make it equivalent to a torus (genus 1) or higher degree genus surface (see images above).

Regards,

Bruno

2 posts - 2 participants

Read full topic

Partition List line

$
0
0

This Python code is an perfect number that I wrote (an perfect number is a number whose sum divisible by it is equal to the number itself)
The first question is why that Partition List line does not work on the last line of code
The second question is how to write c # code with maximum execution speed?
perfect number
perfect number.gh (11.4 KB)

import rhinoscriptsyntax as rs
import ghpythonlib.components as gh

b=[]
t=[]
a=[]
w=[]
h=[]
for i in range(3,n):
    for j in range(2,i+1,1):
        if i%j==0:
            b.append(i//j)
            x.append(i//j)
    c=sum(b)
    if c==i:
      t.append(c)
    b=[]
print len(t)
for k in range(0,len(t),1):
    v=t[k]
    for j in range(2,v+1,1):
        if v%j==0:
            a.append(v//j)
            h.append(v//j)
            g=len(h)
    w.append(g)
    h=[]
m=gh.PartitionList(a,w)

2 posts - 2 participants

Read full topic

Default export igs, 3dm, stl

$
0
0

Hi everybody,
This code uses to default import igs, stl ,3dm
anyone can edit it to export code ??

-runscript
(Sub import

Dim strFolder1,strFilename1
Dim objFso,objStream,FileDate,FlieExist
Dim zs,zt,zn

strFolder1 = Rhino.ExeFolder
Set objFSO = CreateObject(“Scripting.FileSystemObject”)

Dim strFolder,typed
Dim Filename,f,fc,strFilename

Typed=Rhino.GetString (“Type: 1, Iges ; 2, Stl ; 3, 3dm”,1)

If typed=1 Then
fc=Rhino.OpenFileNames(“Import”, “Igs Files (.igs)|.igs|3dm(.3dm)|.3dm|All Files (.)|.||”)
If Not IsArray(fc) Then Exit Sub
ElseIf typed=2 Then
fc=Rhino.OpenFileNames(“Import”, “Stl Files (.stl)|.stl|3dm(.3dm)|.3dm|All Files (.)|.||”)
ElseIf typed=3 Then
fc=Rhino.OpenFileNames(“Import”, “3dm Files (.3dm)|.3dm|3dm(.3dm)|.3dm|All Files (.)|.||”)

End If

For Each strFilename In fc

If Not IsNull(strFilename) Then

Rhino.Command “_-import " & “””" & strFilename & “”"",vbFalse
End If

filename=UCase(OBJfso.getbasename(strFilename))

Dim arrobjects,currcentlayer
Dim arrLayers, strLayer
Dim llayer
arrObjects = Rhino.SelectedObjects
currcentlayer=Rhino.CurrentLayer
arrLayers = Rhino.LayerNames

If IsArray(arrLayers) Then
For Each strLayer In arrLayers

If strlayer=Filename Then
filename=filename&"-2"
Else
filename=filename
End If

Rhino.AddLayer(Filename)
Rhino.Layercolor (Filename),RGB(127,255,191)
Rhino.ObjectLayer arrObjects ,Filename

If Rhino.IsLayerEmpty(strLayer)And strlayer<>currcentlayer Then

Rhino.DeleteLayer (strLayer)

End If

Next

Rhino.command"noecho sellast group pause"
Rhino.command"_SetView _World _Perspective _Zoom _Extents"

End If

Set arrObjects = Nothing

Rhino.UnselectAllObjects

Next

Set objFSO=Nothing

End Sub
import
)

1 post - 1 participant

Read full topic


Rhinoscript: evaluation points from surface do not take the shape of the surface

$
0
0

I am trying to extract point from a surface that was created from separated curves. The problem is the outcome points are regular grid of points although the surface shape is irregular. Is there a command to extract points from a surface of the exact shape? if not, is there a way to delete the points outside the surface, thank you for your help

3 posts - 2 participants

Read full topic

Morph Control Box, Access Points

$
0
0

Hi,

MorphControl has a Surface and Curve property, both set to degrees of zero presumably because the box form is the exception that isn’t described in this way.

Image the top slice in a 4x4x4 cage cube. On that top slice, i want to move the central 4 up in Z by a fixed amount. I can access the grips fine (index 20, 24, 36 and 40). But because there isn’t a location property which i can set to Z to +5, +10 or whatever, I’m stuck.

Given that I can get the selection already, I just have to transform with the gumball. But wondering if I can get the script to transform the points too.

xform_this.3dm (761.8 KB)


cages = rs.GetObjects( "select cages to manipulate" )
cage_objects = []

for cage in cages:
    cage_objects.append(rs.coercegeometry(cage))
"""
for cage_object in cage_objects:
    cage_object.
"""
rs.EnableRedraw(False)
for cage in cages:
    rs.EnableObjectGrips(cage)
    rs.SelectObjectGrip( cage, 20)
    rs.SelectObjectGrip( cage, 24)
    rs.SelectObjectGrip( cage, 36)
    rs.SelectObjectGrip( cage, 40)

rs.EnableRedraw(True) ```

1 post - 1 participant

Read full topic

Rhinocommon and rhinoscriptsyntax object color methods result in different outcome?

$
0
0
print sc.doc.Objects.Find(objID).Attributes.ObjectColor
print rs.ObjectColor(objID)

Result:

Color [Black]
Color [White]

White is correct.

2 posts - 2 participants

Read full topic

Default export igs, 3dm, stl

$
0
0

Hi everybody,
This code uses to default import igs, stl ,3dm
anyone can edit it to export code ??

-runscript
(Sub import

Dim strFolder1,strFilename1
Dim objFso,objStream,FileDate,FlieExist
Dim zs,zt,zn

strFolder1 = Rhino.ExeFolder
Set objFSO = CreateObject(“Scripting.FileSystemObject”)

Dim strFolder,typed
Dim Filename,f,fc,strFilename

Typed=Rhino.GetString (“Type: 1, Iges ; 2, Stl ; 3, 3dm”,1)

If typed=1 Then
fc=Rhino.OpenFileNames(“Import”, “Igs Files ( *.igs)|* .igs|3dm( *.3dm)|* .3dm|All Files ( *.* )| *.* ||”)
If Not IsArray(fc) Then Exit Sub
ElseIf typed=2 Then
fc=Rhino.OpenFileNames(“Import”, “Stl Files ( *.stl)|* .stl|3dm( *.3dm)|* .3dm|All Files ( *.* )| *.* ||”)
ElseIf typed=3 Then
fc=Rhino.OpenFileNames(“Import”, “3dm Files ( *.3dm)|* .3dm|3dm( *.3dm)|* .3dm|All Files ( *.* )| *.* ||”)

End If

For Each strFilename In fc

If Not IsNull(strFilename) Then

Rhino.Command “_-import " & “””" & strFilename & “”"",vbFalse
End If

filename=UCase(OBJfso.getbasename(strFilename))

Dim arrobjects,currcentlayer
Dim arrLayers, strLayer
Dim llayer
arrObjects = Rhino.SelectedObjects
currcentlayer=Rhino.CurrentLayer
arrLayers = Rhino.LayerNames

If IsArray(arrLayers) Then
For Each strLayer In arrLayers

If strlayer=Filename Then
filename=filename&"-2"
Else
filename=filename
End If

Rhino.AddLayer(Filename)
Rhino.Layercolor (Filename),RGB(127,255,191)
Rhino.ObjectLayer arrObjects ,Filename

If Rhino.IsLayerEmpty(strLayer)And strlayer<>currcentlayer Then

Rhino.DeleteLayer (strLayer)

End If

Next

Rhino.command"noecho sellast group pause"
Rhino.command"_SetView _World _Perspective _Zoom _Extents"

End If

Set arrObjects = Nothing

Rhino.UnselectAllObjects

Next

Set objFSO=Nothing

End Sub
import
)

1 post - 1 participant

Read full topic

Rhinoscript: spread rectangle pattern along irregular surface

$
0
0


As you see in the image, I am trying to spread rectangles along an irregular surface that was formed by more than 4 curves (lines). The problem is I can spread rectangles in a small area and not through all the surface.
My script is:
# construct rectangle pattern on a floor 2D plan
# Nabil Mohareb
import rhinoscriptsyntax as rs

def startPattern(surface, pattU, pattV):
    # dictionary of the points
    ptMTX = {}
    # get domain of the surface
    udomain = rs.SurfaceDomain(surface,0) 
    vdomain = rs.SurfaceDomain(surface,1)
    # calculate the steps ofr U (X) & V (Y), distance of the grid
    stepU = (udomain [1] - udomain [0])/pattU
    stepV = (vdomain [1] - vdomain [0])/pattV
    
    #plot points on surface
    for i in range (pattU+1):
        for j in range (pattV+1):
            #define u & v in terms of steps values, i, j
            u = udomain[0] + stepU*i
            v = vdomain[0] + stepV*j
            # diviede the surface and draw points on surfaces 
            point = rs.EvaluateSurface (surface, u, v)
            if rs.IsPointOnSurface(surface, point) != False:
                rs.AddPoint(point)
                # write the points in the dictionary 
                ptMTX [(i,j)] = point
    #loop to create geometry 
    for i in range (6,12):    #(6,12) # this is the problem, what range should I use?
        for j in range (6,12):# the numbers are just playing around, but I think this is the problem
            if i>0 and j>0:
                curverec= rs.AddPolyline((ptMTX[(i,j)], ptMTX[(i-1,j)],ptMTX[(i-1,j-1)], ptMTX[(i,j-1)], ptMTX[(i,j)]))
                #add surface to the small rectangles
                smlSurf= rs.AddPlanarSrf(curverec)
                # find the center of the small rectangle and add point to it
                center = rs.SurfaceAreaCentroid(smlSurf)
                rs.AddPoint( center[0] )

def main():
    #select the plan lines
    plane = rs.GetObjects('select curves please', rs.filter.curve)
    pattU = rs.GetInteger('write U (x) value', 12)
    pattV = rs.GetInteger('write V (y) value', 12)
    #join the plan lines
    planeJoined= rs.JoinCurves(plane)
    #convert plane to surface
    surface =rs.AddPlanarSrf(planeJoined)
    
    # call the function
    startPattern(surface, pattU, pattV)

main ()

1 post - 1 participant

Read full topic

Move Lines until it touches the curve

$
0
0

Hi,

I would like to move all the blocks until it touches the curve ( Upper block to upper curve, lower blocks to lower curves), is there any way to do that in rhino, maybe using grasshopper?p.3dm (69.5 KB)

3 posts - 2 participants

Read full topic

OrientOnSrf

$
0
0

Hello.
sorry for the stupid question. I’m a newbie.
OrientOnSrf
how to add turn on a Scale?
(is it possible to add hotkeys? to scale + 0.1 - 0.1 from 1)
how to add turn on a Copy?
how to add turn on a live Views.?
is it possible and how to download a 3dm file from a folder and add a # Select objects to orient?
thanks for the answer. :sunglasses:
OrientOnSrf.py (2.6 KB)

1 post - 1 participant

Read full topic


Unrolling reverses the additional geometry order

$
0
0

Hello,

I have two surfaces: one flat, one curved, with the similar UV direction.
I would like to unroll them, and unrolled the points on them as well:

For the curved surface, after unrolling, the point order remains the same:

However, for the flat surface, the order of the points gets reversed:

What is causing the difference between these two?

I get the same result in both Rhino 6 SR30, and Rhino 7 Beta (7.0.20301.12003)

Attached is an example code, and both surfaces.
If this is expected Rhino behavior I can always check if the surfaces are curved or not.
I still want to know if it is intentionally set up like this.
unroll flat, curved srfs.3dm (43.8 KB)


import rhinoscriptsyntax as rs
import Rhino.Geometry as rg
import Rhino


# a) inputs
id = rs.GetObject("select brep to unroll")
brep = rs.coercegeometry(id)



# for flat 'brep'
pt_L = [
        rg.Point3d(161.381105, -4.70594, 13.736569),
        rg.Point3d(171.388057, -4.691688, 18.407002),
        rg.Point3d(181.024381, -4.677964, 22.802705)]
"""
# for curved 'brep'
pt_L = [
        rg.Point3d(212.118075, -8.081183, 3.022045),
        rg.Point3d(219.292585, -12.429482, 12.362912),
        rg.Point3d(230.643013, -13.730152, 21.154316)]
"""






# b) perform unroll
unroller = rg.Unroller(brep)

# add addtional geometry to the unroller
for pt in pt_L:
    unroller.AddFollowingGeometry(pt)

unrolledGeom = unroller.PerformUnroll()
brep_unrolled = unrolledGeom[0][0]
pt_L_unrolled = unrolledGeom[2]
Rhino.RhinoDoc.ActiveDoc.Objects.Add(brep_unrolled)






# c) label
# label pt_L before unrolling
for i in range(pt_L.Count):
    rs.AddTextDot(str(i), pt_L[i])

# label pt_L after unrolling
for i in range(pt_L_unrolled.Count):
    rs.AddTextDot(str(i), pt_L_unrolled[i])

4 posts - 2 participants

Read full topic

Load cluster in my Python code

$
0
0

Hello i created a cluster with C # if I want to load this cluster in my Python code? Is it possible?
I wrote such a line, but it got an error and the cluster was not found at all(for example this "extrudemesh "components )

import Grasshopper.Folders as fo
    fo.ClusterFolders.Add.#my_cluster(extrudeMeshc#)

photo_2020-11-23_12-12-50

2 posts - 2 participants

Read full topic

Script to export drawings to dxf - color error (converts black lines to white)

$
0
0

I have written a c# script that exports a bunch of geometries on assigned layers to separate dxf files for fabrication. Key is to have specifi geos on specific layers with assigned colours.

All works fine, but not one layer that is meant to be black. When i open exported dxf files, all black lines are white. Which is weird, because other layers - like yellow or green ones - work fine.

Does anyone knows why is that?

6 posts - 4 participants

Read full topic

Workflow for testing when using VS Code?

$
0
0

Hello everyone,

I am wondering if anyone has a good workflow for doing Unit-Tests on Python modules which are used by GHPython components when I am creating those modules in VS Code or similar external IDE?


For example:

I can create components in Grasshopper which import and use my custom modules - that all works great:

and I can write those modules outside Rhino/GH (I’m using VS Code at the moment) and that is all working fine as well. Though I am not able to make the ‘stubs’ work unfortunately, so I am still not getting any autocomplete. But that’s not the end of the world, and when I run everything in Grasshopper it all works just fine.


So the only issue I run into is if I try and create any Unit-Tests which import my custom module(s). If my module includes Rhino / Grasshopper module imports (which they almost all do), I get an error when I try and run the tests:

So I wonder if there is good workflow / process that I should be using for something like this? I can do UnitTests for the functions inside Grasshopper using the process outlined here, so that is helpful, but I’d like to be able to integrate more testing into my modules as well? Do I need to setup VS Code in some particular fashion to allow my to access those Rhino/GH modules somehow? Is there some other preferred method I should be using to do tests on GHPython modules?

any advice or recommendations are much appreciated!
thanks so much.
@ed.p.may

1 post - 1 participant

Read full topic

Radial symmetry (Reflect) need а macro

$
0
0

Hello!
I am trying to automate the process a bit.
I have a model with 3-sided symmetry.
The model is in the center of coordinates.
After making some minor adjustments, I use Reflect
And I make symmetry 3 times along the outer corners of 120 degrees.

Can anyone help with writing a macro?

Thanks

4 posts - 2 participants

Read full topic

Viewing all 5823 articles
Browse latest View live