Download tools/export_fitout.py from dellweb3/build3d: direct link, hf CLI and curl.
- Browser
- Download file 6.92 kB
-
https://huggingface.co/spaces/dellweb3/build3d/resolve/main/tools/export_fitout.py
- Command line
-
hf download hf://spaces/dellweb3/build3d/tools/export_fitout.py
-
curl -L -o export_fitout.py https://huggingface.co/spaces/dellweb3/build3d/resolve/main/tools/export_fitout.py
6.92 kB
| """Export matching structural/finished 3DM models with editable native solids.""" | |
| import json,sys,math,shutil | |
| from pathlib import Path | |
| ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'.local/runtime/python'));sys.path.insert(0,str(ROOT/'app')) | |
| import rhino3dm as rh | |
| from geometry_mesh import surface_mesh | |
| from interior_spec import compile_scene | |
| def geometry(item): | |
| kind=item['shape'];sx,sy,sz=[v*1000 for v in item['size']] | |
| if kind=='polygon': | |
| points=[] | |
| for p in item['polygon']: | |
| if not points or p!=points[-1]:points.append(p) | |
| if points[0]!=points[-1]:points.append(points[0]) | |
| curve=rh.PolylineCurve([rh.Point3d(x*1000,y*1000,0) for x,y in points]);g=rh.Extrusion.Create(curve,item['height']*1000,True) | |
| elif kind=='box': | |
| pts=[(-sx/2,-sy/2),(sx/2,-sy/2),(sx/2,sy/2),(-sx/2,sy/2),(-sx/2,-sy/2)] | |
| g=rh.Extrusion.Create(rh.PolylineCurve([rh.Point3d(x,y,-sz/2) for x,y in pts]),sz,True) | |
| elif kind in ('cylinder','rod'): | |
| if kind=='rod': | |
| a,b=item['a'],item['b'];axis=rh.Vector3d(*[b[i]-a[i] for i in range(3)]);axis.Unitize();plane=rh.Plane(rh.Point3d(*[v*1000 for v in a]),axis) | |
| circle=rh.Circle(sx/2);circle.Plane=plane | |
| return rh.Cylinder(circle,math.dist(a,b)*1000).ToBrep(True,True) | |
| circle=rh.Circle(sx/2);circle.Plane=rh.Plane(rh.Point3d(0,0,-sz/2),rh.Vector3d(0,0,1)) | |
| g=rh.Cylinder(circle,sz).ToBrep(True,True) | |
| elif kind=='ellipsoid': | |
| g=rh.Sphere(rh.Point3d(0,0,0),1).ToBrep();g.Transform(rh.Transform.Scale(rh.Plane.WorldXY(),sx/2,sy/2,sz/2)) | |
| elif kind in ('bowl','ring','prism','lathe','tube','cad-basin'): | |
| vertices,faces=surface_mesh(item);g=rh.Mesh() | |
| for v in vertices:g.Vertices.Add(*[p*1000 for p in v]) | |
| for f in faces:g.Faces.AddFace(*f) | |
| g.Normals.ComputeNormals();g.Compact() | |
| else:raise ValueError('Unsupported geometry '+kind) | |
| if g is None or not g.IsValid:raise ValueError('Invalid geometry '+item['id']) | |
| for angle,axis in zip(item.get('rotation',[0,0,0]),[rh.Vector3d(1,0,0),rh.Vector3d(0,1,0),rh.Vector3d(0,0,1)]): | |
| if angle:g.Transform(rh.Transform.Rotation(angle,axis,rh.Point3d(0,0,0))) | |
| g.Transform(rh.Transform.Translation(*[v*1000 for v in item['position']])) | |
| return g | |
| def export(source,project,out): | |
| source=Path(source);project=Path(project);out=Path(out);scene=compile_scene(json.loads(source.read_text(encoding='utf-8'))) | |
| node=project/'inputs/20240426壁龛节点-1.3dm';reports={} | |
| for variant in ('structural','finished'): | |
| model=rh.File3dm.Read(str(node)) if node.exists() else rh.File3dm();original=len(model.Objects) | |
| if original: | |
| parent=rh.Layer();parent.Name='参考节点(原坐标,隐藏)';parent.Visible=False;pi=model.Layers.Add(parent) | |
| for layer in list(model.Layers)[:pi]: | |
| if str(layer.ParentLayerId)=='00000000-0000-0000-0000-000000000000':layer.ParentLayerId=model.Layers[pi].Id | |
| layer.Visible=False | |
| def layer(name,parent=None): | |
| l=rh.Layer();l.Name=name | |
| if parent is not None:l.ParentLayerId=model.Layers[parent].Id | |
| return model.Layers.Add(l) | |
| root=layer('土建模型' if variant=='structural' else '精装模型');rooms={};categories={};material_layers={};mats={} | |
| for room in scene['rooms']:rooms[room['id']]=layer(room['name'],root) | |
| for item in scene['materials']: | |
| mat=rh.Material();mat.Name=item['id']+' '+item['name'];mat.DiffuseColor=(200,189,170,255) | |
| if item.get('texture'): | |
| from PIL import Image | |
| p=(project/item['texture']).resolve() | |
| if not p.is_relative_to(project.resolve()):raise ValueError('Invalid texture path') | |
| if p.exists():mat.DiffuseColor=(*Image.open(p).convert('RGB').resize((1,1)).getpixel((0,0)),255) | |
| mats[item['id']]=model.Materials.Add(mat) | |
| count=0;solids=0 | |
| for item in scene['components']: | |
| if item['variant'] not in ('both',variant):continue | |
| key=(item['room'],item['category']) | |
| if key not in categories:categories[key]=layer(item['category'],rooms.get(item['room'],root)) | |
| material_key=(*key,item['material']) | |
| if material_key not in material_layers:material_layers[material_key]=layer(item['material'],categories[key]) | |
| geom=geometry(item) | |
| if not geom.IsValid:raise ValueError('Invalid transformed geometry '+item['id']) | |
| attr=rh.ObjectAttributes();attr.Name=item['name']+' · '+item['id'];attr.LayerIndex=material_layers[material_key] | |
| for k in ('id','room','category','material','source','verification','elevation'):attr.SetUserString(k,str(item.get(k,''))) | |
| attr.SetUserString('size_m',json.dumps(item['size']));attr.SetUserString('variant',item['variant']) | |
| if item['material'] in mats:attr.MaterialIndex=mats[item['material']];attr.MaterialSource=rh.ObjectMaterialSource.MaterialFromObject | |
| else:attr.ColorSource=rh.ObjectColorSource.ColorFromObject;attr.ObjectColor=(175,180,183,255) if variant=='structural' else (228,225,219,255) | |
| model.Objects.Add(geom,attr);count+=1 | |
| if isinstance(geom,(rh.Brep,rh.Extrusion)) and geom.IsSolid:solids+=1 | |
| model.Settings.ModelUnitSystem=rh.UnitSystem.Millimeters;model.Settings.ModelAbsoluteTolerance=.1 | |
| model.Strings['dimension_comparison']=json.dumps(scene['dimensionComparison'],ensure_ascii=False) | |
| model.Strings['elevation_index']=json.dumps(scene['elevations'],ensure_ascii=False) | |
| model.Strings['model_status']='图纸与节点驱动的参数化模型;产品未注厂家细部与反算基层仍需核审' | |
| model.Strings['texture_note']='材料编码与样板平均色;完整贴图在同版本GLB/Blender' | |
| path=out/f'model-{variant}.3dm' | |
| if not model.Write(str(path),8):raise ValueError('3DM write failed') | |
| checked=rh.File3dm.Read(str(path));invalid=sum(not o.Geometry.IsValid for o in checked.Objects) | |
| if invalid:raise ValueError('Invalid 3DM objects') | |
| reports[variant]=dict(objects=len(checked.Objects),components=count,newSolids=solids,invalidObjects=invalid,sourceObjects=original,layers=len(checked.Layers)) | |
| shutil.copy2(out/'model-finished.3dm',out/'model.3dm') | |
| report=dict(units='mm',variants=reports,newSolids=reports['finished']['newSolids'],invalidObjects=0,referenceNodeEmbedded=bool(reports['finished']['sourceObjects']),sourceObjects=reports['finished']['sourceObjects'],objects=reports['finished']['objects'],layers=reports['finished']['layers']) | |
| (out/'rhino-report.json').write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8');print(json.dumps(report,ensure_ascii=False)) | |
| if __name__=='__main__':export(*sys.argv[1:4]) | |