Hello everyone, I need some help.
I am trying to get a XY plane that cuts through a brep and seperates the brep in two parts equally.
Code as below. It fails by the “while” loop. How do I refine the code?
Thanks in advance.
import rhinoscriptsyntax as rs
import Rhino.Geometry as rg
# Variable "Brep" is a closed brep input.
Vol=rg.Brep.GetVolume(Brep)
BB=rs.BoundingBox(Brep)
# Returns the height of the input brep in Z direction.
Height=rs.Distance(BB[0],BB[4])
# Define a function that returns a volume cut by a XY plane at certain height.
def vol_split(Brep_in,para_h):
point_z=rs.AddPoint(0,0,para_h)
base_plane=rs.WorldXYPlane()
cutter=rs.MovePlane(base_plane,point_z)
Btm=rg.Brep.Trim(Brep_in,cutter,0.001)
Btm=rg.Brep.CapPlanarHoles(Btm[0],0.001)
para_v=abs(rg.Brep.GetVolume(Btm))
return Btm, para_v
# Target is half of the volume.
Tar=Vol/2
# Giving an accuracy.
Acc=100
# Using dichotomy by "while" loop.
max = Height*0.99
min = Height*0.01
h = (max+min)/2
while abs(Tar-vol_split(Brep,h)[1])>Acc:
if vol_split(Brep,h)[1]-Tar>0:
max=h
h=(max+min)/2
elif vol_split(Brep,h)[1]-Tar<0:
min=h
h=(max+min)/2
# Out put.
a=h
b=vol_split(Brep,h)[0]
Edit: I didn’t notice you had commented out the offending bits of code (using """" some code """ will highlight properly). Looks like you’re never meeting a condition that will end the while loop (i.e. you enter an infinite loop and crash Rhino). You can prevent this by explicitly breaking the loop after N iterations, enabling you to debug why. In this case, your volume variable never drops below 5550:
Hi Anders. Thanks for your help. I’m happy to tell you that I’ve solved the problem with your debug method.
But I cann’t upload the gh file by network issues this time. (Try serval times but still happens.)
Will reuploaded it when the network is available.
Can’t wait to share with you so I will explain below.
The reason is that the varaible “Btm” (surface) in function “vol_split” is flipped unexpectedly. As a result, the variable “Vol” and “Tar” turn to be negative numbers, which makes the while loop doesn’t work.
One of the solution is to change " Tar = Vol/2 " to " Tar = abs (Vol/2) "
With this change, the while loop works well (no need the break condition).