SetFactory("OpenCASCADE");

Include "magnets_common.pro";

mm = 1.e-3;
SetFactory("OpenCASCADE");


// set some global Gmsh options
Mesh.Algorithm= 5;

VolWires[] = {};
VolMagnets[] = {};
For i In {1:NumMagnets}
  iLabel = newv;
  Cylinder(iLabel) = { X~{i}, Y~{i}-L~{i}/2, Z~{i}, 0, L~{i}, 0, R~{i}+AG~{i} };
  Cylinder(iLabel+1) = { X~{i}, Y~{i}-L~{i}/2, Z~{i}, 0, L~{i}, 0, R~{i}+AG~{i}+WT~{i}  };
  BooleanDifference(iLabel+2)={Volume{iLabel+1}; Delete;}{Volume{iLabel}; Delete;};
 
  Physical Volume(Sprintf("Wires_%g",i),iLabel+2) = { iLabel+2 };
  skin~{iLabel+2}[] = CombinedBoundary{ Volume{ iLabel+2 }; };
  Physical Surface(Sprintf("SkinWire_%g",i),iLabel+2) = -skin~{iLabel+2}[];
  VolWires[] += {iLabel+2};
  Cylinder(iLabel+3) = { X~{i}, Y~{i}-L~{i}/2, Z~{i}, 0, L~{i}, 0, R~{i} };
  Physical Volume(Sprintf("Magnet_%g",i),i+3) = { iLabel+3 };
  skinm~{iLabel+3}[] = CombinedBoundary{ Volume{iLabel+3 }; };
  Physical Surface(Sprintf("SkinMagnet_%g",i),iLabel+3) = -skinm~{iLabel+3}[]; // magnet skin
  VolMagnets[] += { iLabel+3 };
  iLabel=iLabel+4;
EndFor

Include "InfiniteBox.geo";
// The overall dimensions of the model have been calculated in InfiniteBox.geo
// So we use to characteristic length set for the infinite box for the whole mesh.

AirBox[] = BooleanDifference{ 
  Volume{ InteriorInfBox }; Delete;
}{ 
  Volume{ VolMagnets[],VolWires[] };
};

Physical Volume("AirBox",400000) = { AirBox[] };

Volumes[] = { VolInf[], VolMagnets[], VolWires[], AirBox[] };

vv[] = BooleanFragments{
  Volume { Volumes[] }; Delete; }{};

If( #vv[] > #Volumes[] )
  Error("Overlapping magnets");
  Abort;
EndIf

Printf("Check whether BooleanFragments has preserved volume numbering:");
For num In {0:#vv()-1}
   Printf("Fragment %10g -> %g", Volumes[num], vv(num));
EndFor

Outer[] = CombinedBoundary{ Volume{ Volumes[] }; };
Physical Surface("OuterSurface", 50000) = { Outer[]  };
