"""CC0 1.0 original FreeCAD native-history exercise, not a scanner reconstruction. Run with FreeCADCmd. Set SCANNER_NATIVE_OUTPUT to a fresh output directory. The script creates no input files to erase and never cleans prior results. """ import csv,hashlib,json,math,os,sys,shutil from pathlib import Path import FreeCAD as App import Part import Sketcher out=Path(os.environ['SCANNER_NATIVE_OUTPUT']).resolve() assert not out.exists(),'Use a fresh output directory; previous results are preserved' out.mkdir(parents=True);checks=[] doc=App.newDocument('ScannerMatchNativePlate') doc.License='CC0-1.0' doc.LicenseURL='https://creativecommons.org/publicdomain/zero/1.0/' body=doc.addObject('PartDesign::Body','PlateBody') profile=body.newObject('Sketcher::SketchObject','PlateProfile') points=[(-40,-25),(40,-25),(40,25),(-40,25)] for i in range(4): a=points[i];b=points[(i+1)%4] profile.addGeometry(Part.LineSegment(App.Vector(*a,0),App.Vector(*b,0)),False) for i in range(4):profile.addConstraint(Sketcher.Constraint('Coincident',i,2,(i+1)%4,1)) for i in [0,2]:profile.addConstraint(Sketcher.Constraint('Horizontal',i)) for i in [1,3]:profile.addConstraint(Sketcher.Constraint('Vertical',i)) for name,constraint in [('LeftX',Sketcher.Constraint('DistanceX',0,1,-40.0)),('BottomY',Sketcher.Constraint('DistanceY',0,1,-25.0)),('PlateWidth',Sketcher.Constraint('Distance',0,80.0)),('PlateHeight',Sketcher.Constraint('Distance',1,50.0))]: index=profile.addConstraint(constraint);profile.renameConstraint(index,name) doc.recompute();assert profile.FullyConstrained pad=body.newObject('PartDesign::Pad','PlatePad');pad.Profile=profile;pad.Length=6.0 doc.recompute();assert pad.Shape.isValid() and len(pad.Shape.Solids)==1 hole=body.newObject('Sketcher::SketchObject','HoleProfile') hole.setExpression('Placement.Base.z','PlatePad.Length') hole.addGeometry(Part.Circle(App.Vector(0,0,0),App.Vector(0,0,1),2.5),False) hole.addConstraint(Sketcher.Constraint('Coincident',0,3,-1,1)) hole_index=hole.addConstraint(Sketcher.Constraint('Diameter',0,5.0)) hole.renameConstraint(hole_index,'HoleDiameter') doc.recompute();assert hole.FullyConstrained pocket=body.newObject('PartDesign::Pocket','HolePocket');pocket.Profile=hole;pocket.Type=1 body.Tip=pocket;doc.recompute() def digest(path):return hashlib.sha256(path.read_bytes()).hexdigest() def bounds(shape):return [shape.BoundBox.XLength,shape.BoundBox.YLength,shape.BoundBox.ZLength] def check_shape(document,diameter,thickness,stage): document.recompute();feature=document.HolePocket;shape=feature.Shape expected=80*50*thickness-math.pi*(diameter/2)**2*thickness assert shape.isValid() and len(shape.Solids)==1 assert all(abs(a-b)<1e-7 for a,b in zip(bounds(shape),[80,50,thickness])) assert abs(shape.Volume-expected)<1e-6 assert document.PlateProfile.FullyConstrained and document.HoleProfile.FullyConstrained pocket_profile=document.HolePocket.Profile pad_profile=document.PlatePad.Profile if isinstance(pocket_profile,(tuple,list)):pocket_profile=pocket_profile[0] if isinstance(pad_profile,(tuple,list)):pad_profile=pad_profile[0] assert pocket_profile==document.HoleProfile and pad_profile==document.PlateProfile assert abs(document.HoleProfile.Placement.Base.z-thickness)<1e-7 assert document.PlateBody.Tip==document.HolePocket row={'stage':stage,'hole_diameter_mm':diameter,'plate_thickness_mm':thickness,'valid_solid':True,'solids':1,'bounds_mm':bounds(shape),'volume_mm3':shape.Volume,'expected_volume_mm3':expected,'both_sketches_fully_constrained':True,'dependent_hole_z_mm':document.HoleProfile.Placement.Base.z,'body_features':[o.Name for o in document.PlateBody.Group]} checks.append(row);return row files=[] for diameter in [5,7]: hole.setDatum(hole_index,App.Units.Quantity(str(diameter)+' mm')) row=check_shape(doc,diameter,6,'native_build_'+str(diameter)+'mm') native='plate-parametric-'+str(diameter)+'mm.FCStd';step='plate-parametric-'+str(diameter)+'mm.step' doc.saveAs(str(out/native));Part.export([pocket],str(out/step)) for filename in [native,step]:files.append({'file':filename,'bytes':(out/filename).stat().st_size,'sha256':digest(out/filename)}) shape=Part.Shape();shape.read(str(out/step));assert shape.isValid() and len(shape.Solids)==1 and abs(shape.Volume-row['volume_mm3'])<1e-6 and all(abs(a-b)<1e-7 for a,b in zip(bounds(shape),[80,50,6])) checks.append({'stage':'step_roundtrip_'+str(diameter)+'mm','file':step,'hole_diameter_mm':diameter,'plate_thickness_mm':6,'valid_solid':True,'solids':1,'bounds_mm':bounds(shape),'volume_mm3':shape.Volume,'expected_volume_mm3':row['expected_volume_mm3'],'native_history_transferred':False}) reopen_inputs=out/'retained-reopen-inputs';reopen_inputs.mkdir() reopened_documents=[] for diameter in [5,7]: native_name='plate-parametric-'+str(diameter)+'mm.FCStd' copied=reopen_inputs/('fresh-reopen-'+str(diameter)+'mm.FCStd') shutil.copy2(out/native_name,copied) assert digest(copied)==digest(out/native_name) reopened=App.openDocument(str(copied)) assert reopened.Name!=doc.Name and reopened.Name not in reopened_documents reopened_documents.append(reopened.Name) check_shape(reopened,diameter,6,'native_reopen_'+str(diameter)+'mm') changed=7 if diameter==5 else 9 reopened.HoleProfile.setDatum(hole_index,App.Units.Quantity(str(changed)+' mm')) check_shape(reopened,changed,6,'edit_hole_after_reopen_'+str(diameter)+'to'+str(changed)+'mm') reopened.PlatePad.Length=8.0 check_shape(reopened,changed,8,'edit_thickness_after_reopen_'+str(diameter)+'mm') # The reopened files remain unchanged on disk. Only in-memory parameters changed. assert digest(out/('plate-parametric-'+str(diameter)+'mm.FCStd'))==next(item['sha256'] for item in files if item['file']=='plate-parametric-'+str(diameter)+'mm.FCStd') report={'status':'PASS','application':'FreeCAD','version':App.Version(),'python':sys.version,'occt':getattr(Part,'OCC_VERSION','not exposed'),'performed_on':'2026-10-12','units':'mm','datum':{'plate_bounds_min_mm':[-40,-25,0],'plate_bounds_max_mm':[40,25,6],'hole_center_xy_mm':[0,0],'hole_axis':'global Z'},'history':['PlateProfile constrained rectangle','PlatePad 6 mm','HoleProfile named HoleDiameter + dependent placement','HolePocket through all'],'named_parameter':'HoleProfile.Constraints.HoleDiameter','native_reopen_inputs':'Byte-identical copies opened as two new documents; neither the build document nor the other reopened document was reused.','checks':checks,'files':files,'headless':True,'publisher_hardware_test':False,'real_scan_reconstruction':False,'gui_test':False,'independent_kernel_test':False,'limits':['Original synthetic native CAD, not reconstructed from a scan or STEP.','FCStd retains this authored feature history; STEP exports were checked as solids, not as native feature trees.','Only FreeCAD 1.1.4 headless operations were tested; other versions/applications/GUI behavior are not guaranteed.','FreeCAD uses OCCT, also used by the previous checks.']} (out/'file-check.json').write_text(json.dumps(report,indent=2),encoding='utf-8') with (out/'file-check.csv').open('w',newline='',encoding='utf-8') as file: writer=csv.writer(file);writer.writerow(['stage','hole_diameter_mm','thickness_mm','solids','volume_mm3','expected_volume_mm3','valid_solid']) for row in checks:writer.writerow([row['stage'],row['hole_diameter_mm'],row['plate_thickness_mm'],row['solids'],row['volume_mm3'],row['expected_volume_mm3'],row['valid_solid']]) print('NATIVE_HISTORY_RESULT '+json.dumps({'status':'PASS','checks':len(checks),'files':len(files),'version':App.Version(),'named_parameter':report['named_parameter']}),flush=True)