如何在Rhino Python中正确引用网格执行布尔差集操作?
问题解决:Rhino Python 网格布尔差集脚本修正
错误原因分析
- 对象类型不匹配:
RhinoGet.GetOneObject返回的是ObjRef(对象引用),而非直接的Mesh几何对象,不能直接传入布尔运算函数。 - 参数格式错误:
Mesh.CreateBooleanDifference要求传入Mesh集合(IEnumerable) ,而非单个Mesh对象。 - 结果未添加到文档:原代码未将布尔运算生成的网格添加到Rhino文档,即使运算成功也无法看到结果。
修正后的代码
def BooleanDifference(): # 仅允许选择网格对象,避免误选其他类型 filter = Rhino.DocObjects.ObjectType.Mesh # 选择被减的网格 rc, mesh_ref1 = Rhino.Input.RhinoGet.GetOneObject("Select mesh to subtract from", False, filter) if rc != Rhino.Commands.Result.Success: return rc mesh1 = mesh_ref1.Geometry if not isinstance(mesh1, Rhino.Geometry.Mesh): return Rhino.Commands.Result.Failure # 选择要减去的网格 rc, mesh_ref2 = Rhino.Input.RhinoGet.GetOneObject("Select mesh to subtract", False, filter) if rc != Rhino.Commands.Result.Success: return rc mesh2 = mesh_ref2.Geometry if not isinstance(mesh2, Rhino.Geometry.Mesh): return Rhino.Commands.Result.Failure tolerance = scriptcontext.doc.ModelAbsoluteTolerance # 将单个Mesh包装为列表(满足IEnumerable参数要求),执行布尔差集 rc, result_meshes = Rhino.Geometry.Mesh.CreateBooleanDifference([mesh1], [mesh2], tolerance) if rc != Rhino.Commands.Result.Success: return rc if not result_meshes: return Rhino.Commands.Result.Failure # 将运算结果添加到Rhino文档 for mesh in result_meshes: scriptcontext.doc.Objects.AddMesh(mesh) scriptcontext.doc.Views.Redraw() return Rhino.Commands.Result.Success
关键修改点说明
- 过滤网格类型:将
ObjectType.AnyObject改为ObjectType.Mesh,确保仅能选中网格对象,减少类型错误。 - 提取几何对象:通过
mesh_ref.Geometry从ObjRef中获取实际的Mesh实例,而非直接使用对象引用。 - 包装集合参数:把单个Mesh放入列表
[mesh1]、[mesh2],满足函数对IEnumerable参数的要求。 - 添加结果到文档:遍历运算返回的网格数组,用
Objects.AddMesh将结果添加到Rhino文档,确保可见。 - 类型校验:增加
isinstance判断,确保提取的对象确实是Mesh类型,避免无效输入。
内容的提问来源于stack exchange,提问作者C.K
相关产品推荐
相关产品推荐

