public void ConvertDWGtoModelLines() { //set current document Document curDoc = this.Application.ActiveUIDocument.Document; //set linestyle name string linestyleName = "Thin Lines"; //prompt user to select DWG file ImportInstance curDWG = null; curDWG = SelectDWG(curDoc); //check if selected element is importinstanct - if so then run command if (curDWG != null) { int counter = 0; counter = ConvertDWG(curDoc, curDWG, "model", linestyleName); if (counter > 0) { TaskDialog.Show("Complete", "Converted " + counter + " elements to model lines."); } } else { TaskDialog.Show("Error", "Please select a DWG import or link."); } }
public List <GeometryObject> GetLinkedDWGCurves(ImportInstance curLink, Document curDoc) { // returns list of curves for linked DWG file List <GeometryObject> curveList = new List <GeometryObject>(); Options curOptions = new Options(); GeometryElement geoElement; GeometryInstance geoInstance; GeometryElement geoElem2; // get geometry from current link geoElement = curLink.get_Geometry(curOptions); foreach (GeometryObject geoObject in geoElement) { // convert geoObject to geometry instance geoInstance = (GeometryInstance)geoObject; geoElem2 = geoInstance.GetInstanceGeometry(); foreach (GeometryObject curObj in geoElem2) { // add object to list curveList.Add(curObj); } } // return list of geometry return(curveList); }
/// <summary> /// Get the absolute path of the linked DWG file (ver.2010 or below) /// </summary> public static string GetCADPath(UIDocument uidoc, ImportInstance import) { Document doc = uidoc.Document; //Element ele = import as ImportInstance; CADLinkType cadLinkType = doc.GetElement(import.GetTypeId()) as CADLinkType; return(ModelPathUtils.ConvertModelPathToUserVisiblePath(cadLinkType.GetExternalFileReference().GetAbsolutePath())); }
public void ProcessMultipleSAT() { List <ElementId> importIds = new List <ElementId>(); // create and set new SAT options SATImportOptions satOptions = new SATImportOptions(); satOptions.Placement = ImportPlacement.Origin; satOptions.ColorMode = ImportColorMode.BlackAndWhite; satOptions.Unit = ImportUnit.Millimeter; using (Transaction trans = new Transaction(m_doc, "UpdateSAT")) { trans.Start(); List <GeometryObject> geoObjList = new List <GeometryObject>(); DirectShape ds = null; ElementId currentId; try { currentId = m_doc.Import(@"B:\Rhino\OpenNURBS\v5_example_file.sat", satOptions, m_doc.ActiveView); importIds.Add(currentId); } catch (Exception) { currentId = ElementId.InvalidElementId; } // extract geometry from import instance ImportInstance ii = m_doc.GetElement(currentId) as ImportInstance; Options gOptions = new Options(); gOptions.ComputeReferences = true; GeometryElement geoElement = ii.get_Geometry(gOptions); // get solids from geometry element List <GeometryObject> tempGeoList = FindElementGeometry(geoElement); foreach (GeometryObject go in tempGeoList) { geoObjList.Add(go); } ds = DirectShape.CreateElement(m_doc, new ElementId((int)BuiltInCategory.OST_GenericModel)); ds.SetShape(geoObjList); // set the Direct Shape options DirectShapeOptions dsOptions = ds.GetOptions(); dsOptions.ReferencingOption = DirectShapeReferencingOption.Referenceable; ds.SetOptions(dsOptions); trans.Commit(); trans.Start("Delete Elements"); // clean up imported solids m_doc.Delete(importIds); trans.Commit(); } }
public static void CreateOnViewDrafting(ViewDrafting view, ElementId linkId) { Document doc = view.Document; ImportInstance instance = doc.GetElement(linkId) as ImportInstance; GeometryElement geometryElement = instance.get_Geometry(new Options()); foreach (GeometryObject go in geometryElement) { GeometryInstance ginstance = go as GeometryInstance; if (null != ginstance) { CreatePrimitives(view, ginstance.SymbolGeometry); } } }
private ImportInstance SelectDWG(UIDocument uidoc) { Document doc = uidoc.Document; Reference reference = uidoc.Selection.PickObject(ObjectType.Element); Element el = uidoc.Document.GetElement(reference); if (el.GetType().FullName == "Autodesk.Revit.DB.ImportInstance") { ImportInstance curLink = el as ImportInstance; return(curLink); } else { return(null); } }
public void getBlock() { UIDocument uiDoc = this.ActiveUIDocument; Document doc = uiDoc.Document; Reference myRef = uiDoc.Selection.PickObject(ObjectType.Element, "Select an Import Instance"); ImportInstance myImportInstance = doc.GetElement(myRef) as ImportInstance; Element e = doc.GetElement(myRef); XYZ originInstance = myImportInstance.GetTransform().Origin; GeometryElement myGeoElem = e.get_Geometry(new Options()); foreach (GeometryObject GeoOj in myGeoElem) { GeometryInstance instance = GeoOj as GeometryInstance; if (instance != null) { foreach (GeometryObject instObj in instance.SymbolGeometry) { if (instObj is GeometryInstance) { GeometryInstance blockInstance = instObj as GeometryInstance; string name = blockInstance.Symbol.Name; if (name == "test.dwg.*U26") { Transform transform = blockInstance.Transform; XYZ origin = transform.Origin; XYZ vectorTran = transform.OfVector(transform.BasisX.Normalize()); double rot = transform.BasisX.AngleOnPlaneTo(vectorTran, transform.BasisZ.Normalize()); // radians rot = rot * (180 / Math.PI); // degrees } } } } } //TaskDialog.Show("GeometryInstance Symbol Geometry", "Curve Count: " + curveCounter + "polylineCount: " + polylineCounter); }
/// <summary> /// Shatter geometry objects to curves /// </summary> /// <param name="uidoc"></param> /// <param name="import"></param> /// <param name="layer"></param> /// <param name="tolerance"></param> /// <returns></returns> public static List <Curve> ShatterCADGeometry(UIDocument uidoc, ImportInstance import, string layer, double tolerance) { List <Curve> shatteredCrvs = new List <Curve>(); //List<Arc> arcs = new List<Arc>(); List <GeometryObject> dwg_geos = TeighaGeometry.ExtractElement(uidoc, import, layer); if (dwg_geos.Count > 0) { foreach (var obj in dwg_geos) { if (obj.GetType().ToString() == "Autodesk.Revit.DB.Arc") { Arc arc = obj as Arc; Debug.Print("An arc detected"); shatteredCrvs.Add(arc); continue; } Curve crv = obj as Curve; PolyLine poly = obj as PolyLine; if (null != crv) { shatteredCrvs.Add(crv); } if (null != poly) { var vertices = poly.GetCoordinates(); for (int i = 0; i < vertices.Count() - 1; i++) { if ((vertices[i + 1] - vertices[i]).GetLength() >= tolerance) { shatteredCrvs.Add(Line.CreateBound(vertices[i], vertices[i + 1]) as Curve); } else { continue; } } } } } return(shatteredCrvs); }
private ImportInstance SelectDWG(Document curDoc) { //prompt user to select DWG file ElementId curElemID = null; curElemID = this.Application.ActiveUIDocument.Selection.PickObject(ObjectType.Element, "Select DWG file").ElementId; //check that selected element is DWG file Element curElem = curDoc.GetElement(curElemID); //check that selected element is DWG if (curElem.GetType() == typeof(Autodesk.Revit.DB.ImportInstance)) { ImportInstance curLink = (ImportInstance)curElem; return(curLink); } return(null); }
public void ConvertDWGtoDetailLines(UIDocument uidoc) { Document doc = uidoc.Document; ImportInstance currentDWG = SelectDWG(uidoc); if (currentDWG != null) { int counter = ConvertDWG(doc, currentDWG); if (counter > 0) { String stringToShow = "Converted " + counter.ToString() + " elements to detail lines."; App.thisApp.p_MyForm.EndOfConversion(stringToShow); } else { TaskDialog.Show("Error", "Please select a DWG import or link."); } } }
private void DeleteCADImports(Document doc) { var collector = new FilteredElementCollector(doc).OfClass(typeof(ImportInstance)).ToElementIds(); if (collector.Count != 0) { foreach (ElementId id in collector) { if (doc.GetElement(id) != null) { ImportInstance cad = doc.GetElement(id) as ImportInstance; if (!cad.IsLinked) { doc.Delete(id); } } } } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; Selection selection = uidoc.Selection; Reference reff = selection.PickObject(ObjectType.PointOnElement); Element elem = doc.GetElement(reff); ImportInstance instance = elem as ImportInstance; GeometryObject geo = instance.GetGeometryObjectFromReference(reff) as GeometryObject; Category targetCategory = null; if (geo.GraphicsStyleId != ElementId.InvalidElementId) { GraphicsStyle gs = doc.GetElement(geo.GraphicsStyleId) as GraphicsStyle; if (gs != null) { targetCategory = gs.GraphicsStyleCategory; } } using (Transaction ts = new Transaction(doc, "hide layer")) { ts.Start(); doc.ActiveView.SetVisibility(targetCategory, false); ts.Commit(); } GeometryElement geoElement = elem.get_Geometry(new Options()); if (geoElement == null || geo.GraphicsStyleId == null) { message += "几何元素或者Id不存在"; return(Result.Failed); } // List<CADModel> curveArrayList= return(Result.Succeeded); }
/// <summary> /// Try To Get The Text From CAD But Failure /// </summary> /// <param name="revitDoc"></param> private void GetCADTest(Document revitDoc) { Document doc = uidoc.Document; View active_view = doc.ActiveView; List <GeometryObject> visible_dwg_geo = new List <GeometryObject>(); // Pick Import Instance Reference r = uidoc.Selection.PickObject(ObjectType.Element, new JtElementsOfClassSelectionFilter <ImportInstance>()); ImportInstance dwg = doc.GetElement(r) as ImportInstance; FilteredElementCollector col = new FilteredElementCollector(doc).OfClass(typeof(ImportInstance)); foreach (GeometryObject geometryObj in dwg.get_Geometry(new Options())) { if (geometryObj is GeometryInstance) // This will be the whole thing { GeometryInstance dwgInstance = geometryObj as GeometryInstance; var test = dwgInstance.Symbol; foreach (GeometryObject blockObject in dwgInstance.SymbolGeometry) { if (blockObject is GeometryInstance) // This could be a block { //get the object name and coordinates and rotation and //load into my own class GeometryInstance blockInstance = blockObject as GeometryInstance; string name = blockInstance.Symbol.Name; Transform transform = blockInstance.Transform; XYZ origin = transform.Origin; XYZ vectorTran = transform.OfVector(transform.BasisX.Normalize()); double rot = transform.BasisX.AngleOnPlaneTo(vectorTran, transform.BasisZ.Normalize()); // radians rot = rot * (180 / Math.PI); // degrees } } } } }
// Function public List <CegImportInstanceInfor> GetImportInsntaceInfors(Document doc) { List <CegImportInstanceInfor> importInsntaces = new List <CegImportInstanceInfor>(); FilteredElementCollector collector = new FilteredElementCollector(doc); IList <Element> elements = collector.OfClass(typeof(ImportInstance)).ToElements(); Dictionary <ElementId, ElementId> viewSheetDict = ViewSheetDict(doc); foreach (Element element in elements) { ImportInstance importInstance = element as ImportInstance; if (importInstance == null) { continue; } CegImportInstanceInfor importInsntaceInfor = new CegImportInstanceInfor(); string name = importInstance.Category.Name; importInsntaceInfor.Name = name; importInsntaceInfor.Id = element.Id; View view = doc.GetElement(importInstance.OwnerViewId) as View; if (view == null) { continue; } importInsntaceInfor.ViewId = view.Id; importInsntaceInfor.ViewName = view.ViewName; if (viewSheetDict.ContainsKey(view.Id)) { ViewSheet viewSheet = doc.GetElement(viewSheetDict[view.Id]) as ViewSheet; if (viewSheet != null) { importInsntaceInfor.SheetId = viewSheet.Id; importInsntaceInfor.SheetName = viewSheet.Name; importInsntaceInfor.SheetNumber = viewSheet.SheetNumber; } } importInsntaces.Add(importInsntaceInfor); } return(importInsntaces); }
public static List <bool> IsLinked([DefaultArgument("{}")] IList elements) { List <bool> value = new List <bool>(); foreach (var ins in elements) { var ce = (Proto.Element)ins; Element element = ce.InternalElement; ImportInstance instance = element as ImportInstance; if (instance == null) { TaskDialog.Show("Error", "Expecting Impored Instance"); return(value); } else { value.Add(instance.IsLinked); } } return(value); }
private List <GeometryObject> GetLinkedDWGCurves(ImportInstance currentDWG) { List <GeometryObject> curvelist = new List <GeometryObject>(); Options curOptions = new Options(); GeometryElement geoElement; GeometryElement geoElement2; GeometryInstance geoInstance; geoElement = currentDWG.get_Geometry(curOptions); foreach (GeometryObject geoObject in geoElement) { //convert geoObject to geoInstance geoInstance = geoObject as GeometryInstance; geoElement2 = geoInstance.GetInstanceGeometry(); foreach (GeometryObject curObject in geoElement2) { curvelist.Add(curObject); } } return(curvelist); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { uidoc = commandData.Application.ActiveUIDocument; Document doc = uidoc.Document; Selection sel = uidoc.Selection; try { IList <FamilyWithImage> allColumnsType = getAllColumnFamilies(); if (allColumnsType.Count == 0) { message = Properties.Messages.BeamsFromCAD_NoColumnFamilyLoaded; return(Result.Failed); } IList <Element> allLevels = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Levels).OfClass(typeof(Level)).OrderBy(l => (l as Level).Elevation).ToList(); Element selElem = doc.GetElement(sel.PickObject(ObjectType.Element, new CADSelectionFilter(), Properties.Messages.BeamsFromCAD_SelectCADInstance)); ImportInstance importInstance = selElem as ImportInstance; Transform instanceTransform = importInstance.GetTotalTransform(); GeometryElement geoElem = selElem.get_Geometry(new Options() { DetailLevel = ViewDetailLevel.Coarse, ComputeReferences = false, IncludeNonVisibleObjects = false }); string selectedLayerItem = ""; //Gather information the layers of the ImportedInstance IList <DwgLayerInfo> layerInfo = GetLayerInfo(geoElem); if (layerInfo.Count < 1) { message = Properties.Messages.BeamsFromCAD_NoValidCADElements; return(Result.Failed); } ColumnsFromDwgUI columnsFromDwgWindow = new ColumnsFromDwgUI(layerInfo); if (columnsFromDwgWindow.ShowDialog() == false) { return(Result.Cancelled); } else { selectedLayerItem = columnsFromDwgWindow.GetSelectedLayerName(); } using (TransactionGroup tGroup = new TransactionGroup(doc, Properties.Messages.BeamsFromCAD_Transaction)) { tGroup.Start(); IList <ColumnsTobeRotated> fInnstances = new List <ColumnsTobeRotated>(); CreateInstances(geoElem, doc, selectedLayerItem, allLevels, fInnstances); using (Transaction tRotate = new Transaction(doc, Properties.Messages.BeamsFromCAD_RotateTransaction)) { tRotate.Start(); foreach (ColumnsTobeRotated fi in fInnstances) { RotateInstance(doc, fi.currentInstance, fi.currentAngle); } tRotate.Commit(); } tGroup.Assimilate(); } } catch (Exception excep) { ExceptionManager eManager = new ExceptionManager(excep); if (excep is OperationCanceledException) { return(Result.Cancelled); } else { return(Result.Failed); } } return(Result.Succeeded);; }
internal static IList <XYZ> GetDwgGeometryMidPoints(DwgGeometryType targetGeometryType, ImportInstance targetImportedInstance, string targetLayerName) { GeometryElement geoElem = targetImportedInstance.get_Geometry(new Options() { DetailLevel = ViewDetailLevel.Coarse, ComputeReferences = false, IncludeNonVisibleObjects = true }); IList <XYZ> midPoints = new List <XYZ>(); foreach (GeometryObject geoObj in geoElem) { if (geoObj is GeometryInstance) { GeometryInstance geoInstance = geoObj as GeometryInstance; GeometryElement geo = geoInstance.GetInstanceGeometry(); foreach (var currentGeo in geo) { #region if Poly Line if ((currentGeo is PolyLine) && (targetGeometryType == DwgGeometryType.Rectangle)) { PolyLine currentPolyLine = currentGeo as PolyLine; int numCoordinates = currentPolyLine.NumberOfCoordinates; if (numCoordinates == 5) { if (targetLayerName != null) { if ((((targetImportedInstance.Document.GetElement(currentPolyLine.GraphicsStyleId) as GraphicsStyle).GraphicsStyleCategory).Name) != targetLayerName) { continue; } } IList <XYZ> coordinates = currentPolyLine.GetCoordinates(); IList <XYZ> first3Points = new List <XYZ>(); for (int i = 0; i < 3; i++) { first3Points.Add(coordinates.ElementAt(i)); } double maxDist = double.NegativeInfinity; XYZ point1 = new XYZ(); XYZ point2 = new XYZ(); foreach (XYZ currentPoint1 in first3Points) { foreach (XYZ currentPoint2 in first3Points) { double currentDist = currentPoint1.DistanceTo(currentPoint2); if (currentDist > maxDist) { maxDist = currentDist; point1 = currentPoint1; point2 = currentPoint2; } } } XYZ currentMidPoint = Utils.GetPoint.getMidPoint(point1, point2); //We need to check if there`s point already near this one (or in the same place) //If so, we cant create a duplicate point or a point almost equal to another bool theresPointNear = false; foreach (XYZ currentPoint in midPoints) { if (currentMidPoint.DistanceTo(currentPoint) < 0.3) { theresPointNear = true; } } if (theresPointNear == false) { midPoints.Add(currentMidPoint); } } } #endregion #region if Arc - Circle if ((currentGeo is Arc) && (targetGeometryType == DwgGeometryType.Circle)) { Arc currentArc = currentGeo as Arc; if ((currentArc.IsCyclic == false) || (currentArc.IsBound == true)) { continue; } if (targetLayerName != null) { if ((((targetImportedInstance.Document.GetElement(currentArc.GraphicsStyleId) as GraphicsStyle).GraphicsStyleCategory).Name) != targetLayerName) { continue; } } XYZ currentMidPoint = currentArc.Center; //We need to check if there`s point already near this one (or in the same place) //If so, we cant create a duplicate point or a point almost equal to another bool theresPointNear = false; foreach (XYZ currentPoint in midPoints) { if (currentMidPoint.DistanceTo(currentPoint) < 0.3) { theresPointNear = true; } } if (theresPointNear == false) { midPoints.Add(currentMidPoint); } } } #endregion } } return(midPoints); }
private int ConvertDWG(Document curDoc, ImportInstance curLink, string convertType, string linestyleName) { //check if family doc or project doc string docType = null; if (curDoc.IsFamilyDocument == true) { docType = "family"; } else { docType = "project"; } //set line counter int counter = 0; //get geometry curves from selected file List <GeometryObject> curGeomList = new List <GeometryObject>(); curGeomList = GetLinkedDWGCurves(curLink, curDoc); //confirm linestyle exists if (doesLinestyleExist(curDoc, linestyleName) == false) { TaskDialog.Show("error", "The specified linestyle ( " + linestyleName + " ) does not exist in the current project file."); return(counter); } //create transaction using (Transaction curTrans = new Transaction(curDoc, "Convert lines")) { if (curTrans.Start() == TransactionStatus.Started) { if (curGeomList.Count != 0) { //create detail lines for elements in geometry list foreach (GeometryObject curGeom in curGeomList) { if (curGeom.GetType() == typeof(Autodesk.Revit.DB.PolyLine)) { //figure out what to do with polylines PolyLine curPolyline = (PolyLine)curGeom; //get polyline coordinate points IList <XYZ> ptsList = curPolyline.GetCoordinates(); //create lines from coordinates for (int i = 0; i <= ptsList.Count - 2; i++) { //create curve from polyline coordinates try { if (docType == "project") { //project if (convertType == "detail") { //detail line DetailCurve newLine = null; newLine = curDoc.Create.NewDetailCurve(curDoc.ActiveView, Line.CreateBound(ptsList[i], ptsList[i + 1])); //set new line style newLine.LineStyle = (Element)getLinestyleByName(curDoc, linestyleName); } else { //model line ModelCurve newLine = null; //get current sketchplane from view SketchPlane curSketchplane = null; curSketchplane = SketchPlane.Create(curDoc, curLink.LevelId); //create line newLine = curDoc.Create.NewModelCurve(Line.CreateBound(ptsList[i], ptsList[i + 1]), curSketchplane); //set new line style newLine.LineStyle = (Element)getLinestyleByName(curDoc, linestyleName); } } else { //family if (convertType == "detail") { //detail line DetailCurve newLine = null; try { //create line newLine = curDoc.FamilyCreate.NewDetailCurve(curDoc.ActiveView, Line.CreateBound(ptsList[i], ptsList[i + 1])); } catch (Exception ex) { TaskDialog.Show("Error", "Cannot create detail lines in this type of family."); return(0); } //set new line style newLine.LineStyle = (Element)getLinestyleByName(curDoc, linestyleName); } else { //model line ModelCurve newLine = null; try { //get current sketchplane from view SketchPlane curSketchplane = null; curSketchplane = SketchPlane.Create(curDoc, curLink.LevelId); //create line newLine = curDoc.FamilyCreate.NewModelCurve(Line.CreateBound(ptsList[i], ptsList[i + 1]), curSketchplane); } catch (Exception ex) { TaskDialog.Show("Error", "Cannot create model lines in this type of family."); return(0); } //set new line style newLine.LineStyle = (Element)getLinestyleByName(curDoc, linestyleName); } } } catch (Exception ex) { Debug.Print("could not create polyline"); } //increment counter counter = counter + 1; } } else { try { //create line in current view if (docType == "project") { //project if (convertType == "detail") { //detail line DetailCurve newLine = null; newLine = curDoc.Create.NewDetailCurve(curDoc.ActiveView, (Curve)curGeom); //set new line style newLine.LineStyle = (Element)getLinestyleByName(curDoc, linestyleName); } else { //model line ModelCurve newLine = null; //get current sketchplane from view SketchPlane curSketchplane = null; curSketchplane = SketchPlane.Create(curDoc, curLink.LevelId); //create line newLine = curDoc.Create.NewModelCurve((Curve)curGeom, curSketchplane); //set new line style newLine.LineStyle = (Element)getLinestyleByName(curDoc, linestyleName); } } else { //family if (convertType == "detail") { //detail line DetailCurve newLine = null; try { //create line newLine = curDoc.FamilyCreate.NewDetailCurve(curDoc.ActiveView, (Curve)curGeom); } catch (Exception ex) { TaskDialog.Show("Error", "Cannot create detail lines in this type of family."); return(0); } //set new line style newLine.LineStyle = (Element)getLinestyleByName(curDoc, linestyleName); } else { //model line ModelCurve newLine = null; try { //get current sketchplane from view SketchPlane curSketchplane = null; curSketchplane = SketchPlane.Create(curDoc, curLink.LevelId); //create line newLine = curDoc.FamilyCreate.NewModelCurve((Curve)curGeom, curSketchplane); } catch (Exception ex) { TaskDialog.Show("Error", "Cannot create model lines in this type of family."); return(0); } //set new line style newLine.LineStyle = (Element)getLinestyleByName(curDoc, linestyleName); } } //increment counter counter = counter + 1; } catch (Exception ex) { Debug.Print("could not create line"); } } } } } //commit changes curTrans.Commit(); } return(counter); }
/// <summary> /// Pick a DWG import/linked instance (ver.2010 or below), extract all visible elements or /// ones within specific Layer(LineType) if the type(GeometryObjectType) is assigned. /// </summary> public static List <GeometryObject> ExtractElement(UIDocument uidoc, ImportInstance import, string layer = "*", string type = "*") { Document doc = uidoc.Document; View active_view = doc.ActiveView; List <GeometryObject> visible_dwg_geo = new List <GeometryObject>(); // Get Geometry var geoElem = import.get_Geometry(new Options()); Debug.Print("Found elements altogether: " + geoElem.Count().ToString()); foreach (var geoObj in geoElem) { if (geoObj is GeometryInstance) { var geoIns = geoObj as GeometryInstance; // This may contain child GeometryInstance, so... // If fully explosion is need, recrusive function is needed here var ge2 = geoIns.GetInstanceGeometry(); if (ge2 != null) { foreach (var obj in ge2) { // Use the GraphicsStyle to get the DWG layer linked to the Category for visibility. var gStyle = doc.GetElement(obj.GraphicsStyleId) as GraphicsStyle; // If an object does not have a GraphicsStyle just skip it if (gStyle == null) { continue; } //Debug.Print(obj.GetType().Name); // Check if the layer is visible in the view. if (!active_view.GetCategoryHidden(gStyle.GraphicsStyleCategory.Id)) { if (layer == "*") { if (type == "*") { visible_dwg_geo.Add(obj); } else if (obj.GetType().Name == type) { visible_dwg_geo.Add(obj); } } // Select a certain Linetype(Layername/StyleCategory) else if (gStyle.GraphicsStyleCategory.Name == layer) { if (type == "*") { visible_dwg_geo.Add(obj); } else if (obj.GetType().Name == type) { visible_dwg_geo.Add(obj); } } } } } } } Debug.Print("Geometry collected: " + visible_dwg_geo.Count().ToString()); return(visible_dwg_geo); }
private void Stream( ArrayList data, ImportInstance impInst ) { data.Add( new Snoop.Data.ClassSeparator( typeof( ImportInstance ) ) ); data.Add( new Snoop.Data.Bool( "Pinned", impInst.Pinned ) ); data.Add( new Snoop.Data.Object( "Visibility", impInst.GetVisibility() ) ); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; Application app = uiapp.Application; Document doc = uiapp.ActiveUIDocument.Document; Dictionary <string, string> dict = GetFilePaths(app, true); IList <Element> links = GetLinkedFiles(doc).ToElements(); int n = links.Count; Debug.Print( "There {0} {1} linked Revit model{2}.", (1 == n ? "is" : "are"), n, Util.PluralSuffix(n)); string name; char[] sep = new char[] { ':' }; string[] a; foreach (Element link in links) { name = link.Name; a = name.Split(sep); name = a[0].Trim(); Debug.Print( "Link '{0}' full path is '{1}'.", name, dict[name]); #region Explore Location Location loc = link.Location; // unknown content in here LocationPoint lp = loc as LocationPoint; if (null != lp) { XYZ p = lp.Point; } GeometryElement e = link.get_Geometry(new Options()); if (null != e) // no geometry defined { //GeometryObjectArray objects = e.Objects; // 2012 //n = objects.Size; // 2012 n = e.Count <GeometryObject>(); // 2013 } #endregion // Explore Location #region Explore Pinning if (link is ImportInstance) // nope, this never happens ... { ImportInstance i = link as ImportInstance; string s = i.Pinned ? "" : "not "; Debug.Print("{1}pinned", s); i.Pinned = !i.Pinned; } #endregion // Explore Pinning } return(Result.Succeeded); }
public Result Execute(ExternalCommandData commandData, ref string messages, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; Selection sel = uidoc.Selection; Transaction trans = new Transaction(doc, "ExComm"); trans.Start(); DWGExportOptions options = new DWGExportOptions(); //SUPPORT.PARAMETER.PARAMETER Para = new SUPPORT.PARAMETER.PARAMETER(); View view = doc.ActiveView; ElementId eleid = view.Id; ICollection <ElementId> views = new List <ElementId>(); FilteredElementCollector filter = new FilteredElementCollector(doc); FilteredElementCollector Filter = filter.OfCategory(BuiltInCategory.OST_Views).WhereElementIsNotElementType(); IList <Element> list = Filter.ToElements(); IList <Element> lishname = new List <Element>(); ViewDrafting drafting = null; ElementId newlegend = null; string currentview = doc.ActiveView.ViewName; string test = "Zz_" + currentview + "##"; ElementId id = null; View viewlegend = null; foreach (var ele1 in list) { Parameter parameter = ele1.get_Parameter(BuiltInParameter.VIEW_NAME); string viewname = parameter.AsString(); ViewFamilyType vd = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)).Cast <ViewFamilyType>() .FirstOrDefault(q => q.ViewFamily == ViewFamily.Drafting); views.Add(doc.ActiveView.Id); doc.Export(@"C:\Autodesk", "exportdwg.dwg", views, options); drafting = ViewDrafting.Create(doc, vd.Id); doc.Regenerate(); DWGImportOptions importOptions = new DWGImportOptions(); importOptions.ColorMode = ImportColorMode.BlackAndWhite; doc.Import(@"C:\Autodesk\\exportdwg.dwg", importOptions, drafting, out id); try { drafting.Name = test; trans.Commit(); commandData.Application.ActiveUIDocument.ActiveView = drafting; } catch { TaskDialog.Show("ERROR", "SECTION NÀY ĐÃ ĐƯỢC TẠO FROZEN"); trans.RollBack(); break; } break; } using (Transaction tx = new Transaction(doc)) { tx.Start("Transaction Name"); Element curElem = doc.GetElement(id); ImportInstance curLink = (ImportInstance)curElem; List <GeometryObject> curveobject = GetLinkedDWGCurves(curLink, doc); foreach (GeometryObject curGeom in curveobject) { if (curGeom.GetType() == typeof(PolyLine)) { // create polyline in current view PolyLine curPolyline = (PolyLine)curGeom; // get polyline coordinate points IList <XYZ> ptsList = curPolyline.GetCoordinates(); for (var i = 0; i <= ptsList.Count - 2; i++) { // create detail curve from polyline coordinates try { DetailCurve newDetailLine = doc.Create.NewDetailCurve(doc.ActiveView, Line.CreateBound(ptsList[i], ptsList[i + 1])); } catch { } } } else { try { DetailCurve newDetailLine = doc.Create.NewDetailCurve(doc.ActiveView, (Curve)curGeom); } catch { } } } FilteredElementCollector legCollector = new FilteredElementCollector(doc).OfClass(typeof(View)).WhereElementIsNotElementType(); List <View> alllegends = new List <View>(); foreach (ElementId eid in legCollector.ToElementIds()) { View v = doc.GetElement(eid) as View; if (v.ViewType == ViewType.Legend) { alllegends.Add(v); } } newlegend = alllegends.Last().Duplicate(ViewDuplicateOption.WithDetailing); viewlegend = doc.GetElement(newlegend) as View; tx.Commit(); } using (Form_FrozenSection form = new Form_FrozenSection(doc, uiapp)) { form.ShowDialog(); if (form.DialogResult == System.Windows.Forms.DialogResult.Cancel) { return(Result.Cancelled); } if (form.DialogResult == System.Windows.Forms.DialogResult.OK) { using (Transaction tx1 = new Transaction(doc)) { tx1.Start("Transaction Name"); tx1.Commit(); uiapp.ActiveUIDocument.ActiveView = form.vsheet(); } } using (Transaction tx2 = new Transaction(doc)) { tx2.Start("Transaction Name"); XYZ pos = uidoc.Selection.PickPoint(ObjectSnapTypes.None, "Chon diem dat legend"); Viewport.Create(doc, form.vsheet().Id, newlegend, pos); FilteredElementCollector allElementsInView = new FilteredElementCollector(doc, viewlegend.Id).WhereElementIsNotElementType(); ICollection <ElementId> elementsInView = allElementsInView.WhereElementIsNotElementType().Where(x => x.Category != null).Select(x => x.Id).ToList(); doc.Delete(elementsInView); FilteredElementCollector detailine = new FilteredElementCollector(doc, drafting.Id); IList <ElementId> listdetailine = detailine.OfCategory(BuiltInCategory.OST_Lines).WhereElementIsNotElementType().ToElementIds().ToList(); Transform tranform = ElementTransformUtils.GetTransformFromViewToView(viewlegend, doc.ActiveView); ElementTransformUtils.CopyElements(drafting, listdetailine, viewlegend, tranform, new CopyPasteOptions()); viewlegend.Scale = 16; Parameter viewname = viewlegend.LookupParameter("View Name"); string name = form.Viewname(); viewname.Set(name); doc.Delete(drafting.Id); tx2.Commit(); } } return(Result.Succeeded); }
public void placeFamilyByBlockOneAngle() { UIDocument uiDoc = this.ActiveUIDocument; Document doc = uiDoc.Document; //Select ImportInstance Reference myRef = uiDoc.Selection.PickObject(ObjectType.Element, "Select Import DWG..."); Element dwgImportElement = doc.GetElement(myRef); string myTextClipBoard = Clipboard.GetText(); Dictionary <XYZ, double> myDicCoorAndRot = getOriginAndRotByBlock(dwgImportElement, myTextClipBoard); if (myDicCoorAndRot.Keys.Count < 1) { TaskDialog.Show("Error!!", "CLipboard không có dữ liệu, hoặc file .DWG không chứa block có tên như trong clipboard"); return; } Reference myRefFamily = uiDoc.Selection.PickObject(ObjectType.Element, "Select Instance Family..."); ImportInstance myImportInstance = doc.GetElement(myRef) as ImportInstance; Element myFamilyElement = doc.GetElement(myRefFamily); LocationPoint myLocPoint = myFamilyElement.Location as LocationPoint; double myAngleFamily = myLocPoint.Rotation; XYZ originInstance = myImportInstance.GetTransform().Origin; LocationCurve locCurve = myFamilyElement.Location as LocationCurve; if (null == locCurve) { XYZ pointRef = ((LocationPoint)myFamilyElement.Location).Point; XYZ deltaXYZ = new XYZ(); List <ElementId> myElemIdCopiedColTotal = new List <ElementId>(); foreach (XYZ myXYZ in myDicCoorAndRot.Keys) { List <ElementId> myElemIdCopiedCol = new List <ElementId>(); //Copy Element if (Math.Round(myAngleFamily, 3) == Math.Round(myDicCoorAndRot[myXYZ], 3)) { using (Transaction myTrans = new Transaction(doc, "Copy Element")) { myTrans.Start(); deltaXYZ = originInstance + myXYZ - pointRef; myElemIdCopiedCol = ElementTransformUtils.CopyElement(doc, myFamilyElement.Id, deltaXYZ).ToList(); myTrans.Commit(); } } foreach (ElementId myIdEleCopied in myElemIdCopiedCol) { myElemIdCopiedColTotal.Add(myIdEleCopied); } } // Make group From element Cp=opied using (Transaction trans = new Transaction(doc, "Make group from Copied Element")) { trans.Start(); if (myElemIdCopiedColTotal.Count > 0) { Group myGroupRebar = doc.Create.NewGroup(myElemIdCopiedColTotal); // myGroupRebar.GroupType.Name = rebarGroupName; } else { TaskDialog.Show("Warning!", "No rebar was hosted by this element, so no any group was created!"); } trans.Commit(); } } }
public void copyAndPlaceFamilyAtDwgBlock(UIDocument uiDoc) { Document doc = uiDoc.Document; //Select ImportInstance //List<string> myListImportDwg = new List<string>() {"Import Symbol"}; Reference myRefImportDWG = uiDoc.Selection.PickObject(ObjectType.Element, "Pick a Import DWG..."); ImportInstance myImportInstance = doc.GetElement(myRefImportDWG) as ImportInstance; Element dwgImportElement = doc.GetElement(myRefImportDWG); string myTextClipBoard = Clipboard.GetText(); Dictionary <XYZ, double> myDicCoorAndRot = getOriginAndRotByBlock(dwgImportElement, myTextClipBoard); if (myDicCoorAndRot.Keys.Count < 1) { TaskDialog.Show("Error!!", "CLipboard không có dữ liệu, hoặc file .DWG không chứa block có tên như trong clipboard"); return; } Reference myRefFamily = uiDoc.Selection.PickObject(ObjectType.Element, "Select Instance Family..."); Element myFamilyElement = doc.GetElement(myRefFamily); XYZ originInstance = myImportInstance.GetTransform().Origin; LocationCurve locCurve = myFamilyElement.Location as LocationCurve; if (null == locCurve) { XYZ pointRef = ((LocationPoint)myFamilyElement.Location).Point; XYZ deltaXYZ = new XYZ(); List <ElementId> myElemIdCopiedColTotal = new List <ElementId>(); foreach (XYZ myXYZ in myDicCoorAndRot.Keys) { List <ElementId> myElemIdCopiedCol = new List <ElementId>(); //Copy Element using (Transaction myTrans = new Transaction(doc, "Copy Element")) { myTrans.Start(); deltaXYZ = originInstance + myXYZ - pointRef; myElemIdCopiedCol = ElementTransformUtils.CopyElement(doc, myFamilyElement.Id, deltaXYZ).ToList(); myTrans.Commit(); } using (Transaction myTrans = new Transaction(doc, "RotateElement Location Point")) { myTrans.Start(); // Code here //ElementTransformUtils.RotateElement(doc, myEle.Id, axis, DegreesToRadians(degrees)); foreach (ElementId myIdEleCopied in myElemIdCopiedCol) { Element myElemCopied = doc.GetElement(myIdEleCopied); XYZ point = ((LocationPoint)myElemCopied.Location).Point; XYZ point2 = point.Add(XYZ.BasisZ); Line axis = Line.CreateBound(point, point2); ElementTransformUtils.RotateElement(doc, myIdEleCopied, axis, myDicCoorAndRot[myXYZ]); myElemIdCopiedColTotal.Add(myIdEleCopied); } myTrans.Commit(); } } // Make group From element Cp=opied using (Transaction trans = new Transaction(doc, "Make group from Copied Element")) { trans.Start(); if (myElemIdCopiedColTotal.Count > 0) { Group myGroupRebar = doc.Create.NewGroup(myElemIdCopiedColTotal); // myGroupRebar.GroupType.Name = rebarGroupName; } else { TaskDialog.Show("Warning!", "No rebar was hosted by this element, so no any group was created!"); } trans.Commit(); } } }
public RevitImportInstanceStringer(ImportInstance revitImportInstance, Document doc) { revitImport = revitImportInstance; stringerText = doc.GetElement(revitImport.GetTypeId()).Name; }
void OnDocumentChanged(object sender, DocumentChangedEventArgs args) { var elementDoc = args.GetDocument(); var modifiedElementsId = args.GetModifiedElementIds(); // Кэширование данных (маркеры изменения координат) ProjectLocation projectLocation = null; SiteLocation siteLocation = null; RevitLinkInstance rvtPositionProvider = null; ImportInstance dwgPositionProvider = null; foreach (var elementId in modifiedElementsId) { var element = elementDoc.GetElement(elementId); // Пропускаем элементы, не относящиеся к данному файлу if (element.Document.Title != Globals.ActiveDocumentTitle) { continue; } // Проверяем категорию изменённого элемента на принадлежность к маркерам изменения общих координат switch (element) { case ProjectLocation loc: projectLocation = loc.Document.ActiveProjectLocation; break; case RevitLinkInstance link: rvtPositionProvider = link; break; case ImportInstance link: dwgPositionProvider = link; break; case SiteLocation site: siteLocation = site; break; } } // Фильтруем события, не относящиеся к изменению площадок if (projectLocation == null) { return; } // ИВЕНТ ПРИНЯТИЯ КООРДИНАТ ИЗ СВЯЗИ if (siteLocation != null && (rvtPositionProvider != null || dwgPositionProvider != null)) { // не самый рабочий вариант, т.к. некрасивый и в случае с dwg - не предоставляет имя площадки провайдера var positionProviderName = dwgPositionProvider != null?dwgPositionProvider.get_Parameter(BuiltInParameter.ELEM_TYPE_PARAM).AsValueString() : rvtPositionProvider.Name; // Извлечение имени площадки файла-провайдера string extractedSiteName = null; var providerSiteName = positionProviderName.Split(':'); if (providerSiteName.Count() > 1) { var providerFileName = providerSiteName.Last().Trim(); var spaceIdx = providerFileName.IndexOf(" ", StringComparison.Ordinal) + 1; extractedSiteName = providerFileName.Substring(spaceIdx); } var logging = $"ProviderFileName: {positionProviderName}" + $"SiteName: {projectLocation.Name}" + $"ParentFile: {Globals.ActiveDocumentTitle}" + $"ProviderSiteName: {extractedSiteName}"; } // ИВЕНТ ИЗМЕНЕНИЯ КООРДИНАТ В ПРОЕКТЕ if (siteLocation == null) { var logging = $"ProviderFileName: {Globals.ActiveDocumentTitle}" + $"SiteName: {projectLocation.Name}" + $"ParentFile: {Globals.ActiveDocumentTitle}"; } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; double tolerance = app.ShortCurveTolerance; // Check if the families are ready if (Properties.Settings.Default.name_columnRect == null || Properties.Settings.Default.name_columnRound == null) { System.Windows.MessageBox.Show("Please select the column type in settings", "Tips"); return(Result.Cancelled); } //if (!File.Exists(Properties.Settings.Default.url_column)) //{ // System.Windows.MessageBox.Show("Please check the family path is solid", "Tips"); // return Result.Cancelled; //} //Family fColumn; //using (Transaction tx = new Transaction(doc, "Load necessary families")) //{ // tx.Start(); // doc.LoadFamily(Properties.Settings.Default.url_column, new Util.SampleFamilyLoadOptions(), out fColumn); // tx.Commit(); //} // Pick Import Instance ImportInstance import = null; try { Reference r = uidoc.Selection.PickObject(ObjectType.Element, new Util.ElementsOfClassSelectionFilter <ImportInstance>()); import = doc.GetElement(r) as ImportInstance; } catch { return(Result.Cancelled); } if (import == null) { System.Windows.MessageBox.Show("CAD not found", "Tips"); return(Result.Cancelled); } // Fetch baselines List <Curve> columnCrvs = new List <Curve>(); var columnLayers = Misc.GetLayerNames(Properties.Settings.Default.layerColumn); try { foreach (string columnLayer in columnLayers) { columnCrvs.AddRange(Util.TeighaGeometry.ShatterCADGeometry(uidoc, import, columnLayer, tolerance)); } } catch (Exception e) { System.Windows.MessageBox.Show(e.Message, "Tips"); return(Result.Cancelled); } if (columnCrvs == null || columnCrvs.Count == 0) { System.Windows.MessageBox.Show("Baseline not found", "Tips"); return(Result.Cancelled); } // Grab the current building level FilteredElementCollector docLevels = new FilteredElementCollector(doc) .WhereElementIsNotElementType() .OfCategory(BuiltInCategory.INVALID) .OfClass(typeof(Level)); ICollection <Element> levels = docLevels.OfClass(typeof(Level)).ToElements(); Level defaultLevel = null; foreach (Level level in levels) { if (level.Id == import.LevelId) { defaultLevel = level; } } if (defaultLevel == null) { System.Windows.MessageBox.Show("Please make sure there's a base level in current view", "Tips"); return(Result.Cancelled); } // Start batching TransactionGroup tg = new TransactionGroup(doc, "Create columns"); try { tg.Start(); CreateColumn.Execute(app, doc, columnCrvs, Properties.Settings.Default.name_columnRect, Properties.Settings.Default.name_columnRound, defaultLevel, false); tg.Assimilate(); } catch (Exception e) { System.Windows.MessageBox.Show(e.Message); tg.RollBack(); return(Result.Cancelled); } return(Result.Succeeded); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; View active_view = doc.ActiveView; double tolerance = app.ShortCurveTolerance; // Pick Import Instance ImportInstance import = null; try { Reference r = uidoc.Selection.PickObject(ObjectType.Element, new Util.ElementsOfClassSelectionFilter <ImportInstance>()); import = doc.GetElement(r) as ImportInstance; } catch { return(Result.Cancelled); } if (import == null) { System.Windows.MessageBox.Show("CAD not found", "Tips"); return(Result.Cancelled); } List <GeometryObject> dwg_geos = Util.TeighaGeometry.ExtractElement(uidoc, import); //List<GeometryObject> dwg_geos = CADGeoUtil.ExtractElement(uidoc, import, "WALL", "Line"); //Debug.Print("Number of geos is " + dwg_geos.Count().ToString()); // Create ModelCurve for all GeometryElement in DWG // Directly by exposed RevitAPI methods if (dwg_geos.Count > 0) { using (var t = new Transaction(doc)) { t.Start("Extract Geos"); // Visualize model lines for debugging (needs SketchPlane) Plane Geomplane = Plane.CreateByNormalAndOrigin(XYZ.BasisZ, XYZ.Zero); SketchPlane sketch = SketchPlane.Create(doc, Geomplane); foreach (var obj in dwg_geos) { // The variable will be null if the implicit cast fails, thus... // This will sort the curve(line) and polyline into two categories automatically Curve crv = obj as Curve; PolyLine poly = obj as PolyLine; // Draw a ModelCurve in case the object is a Curve if (null != crv) { ModelCurve modelline = doc.Create.NewModelCurve(crv, sketch) as ModelCurve; } // Draw shattered lines in case the object is a PolyLine if (null != poly) { var vertices = poly.GetCoordinates(); CurveArray shatters = new CurveArray(); for (int i = 0; i < vertices.Count() - 1; i++) { if ((vertices[i + 1] - vertices[i]).GetLength() >= tolerance) { shatters.Append(Line.CreateBound(vertices[i], vertices[i + 1]) as Curve); } else { continue; } } foreach (Curve shatter in shatters) { ModelCurve modelline = doc.Create.NewModelCurve(shatter, sketch) as ModelCurve; } } } t.Commit(); } } // Convert texts info into TextNote by Teigha // Revit does not expose any API to parse text info string path = Util.TeighaText.GetCADPath(uidoc, import); List <Util.TeighaText.CADTextModel> texts = Util.TeighaText.GetCADText(path); Debug.Print("The path of linked DWG file is: " + path); Debug.Print("Texts.Count: " + texts.Count.ToString()); if (texts.Count > 0) { using (var t = new Transaction(doc)) { t.Start("Extracting Text"); // Visualize the text notes just for reference // Do not use NewModelText that only works for family document but not project TextNoteType tnt = new FilteredElementCollector(doc) .OfClass(typeof(TextNoteType)).First() as TextNoteType; foreach (var textmodel in texts) { TextNote txNote = TextNote.Create(doc, active_view.Id, textmodel.Location, textmodel.Text, tnt.Id); } t.Commit(); } } return(Result.Succeeded); }
private int ConvertDWG(Document doc, ImportInstance currentDWG) { string docType; if (doc.IsFamilyDocument == true) { docType = "family"; } else { docType = "project"; } string lineStyleToUse; int counter = 0; List <GeometryObject> curGeometryList = GetLinkedDWGCurves(currentDWG); //Check and set linestyletouse if (doesLinestyleExist(doc, "*Solid (02-Thin)") == true) { lineStyleToUse = "*Solid (02-Thin)"; } else { lineStyleToUse = "Thin Lines"; } using (Transaction tx = new Transaction(doc)) { tx.Start("Convert DWG to Lines"); if (curGeometryList.Count != 0) { //create detail lines for elements in geometry list foreach (GeometryObject curGeom in curGeometryList) { if (curGeom.GetType().FullName == "Autodesk.Revit.DB.PolyLine") { //Since Revit can't handle polylines PolyLine curPolyLine = curGeom as PolyLine; IList <XYZ> ptsList = curPolyLine.GetCoordinates(); for (int i = 0; i <= ptsList.Count - 2; i++) { try { if (docType == "project") { //project file DetailCurve newLine = doc.Create.NewDetailCurve(doc.ActiveView, Line.CreateBound(ptsList[i], ptsList[i + 1])); newLine.LineStyle = getLinestyleByName(doc, lineStyleToUse) as Element; } else { //family file try { DetailCurve newLine = doc.FamilyCreate.NewDetailCurve(doc.ActiveView, Line.CreateBound(ptsList[i], ptsList[i + 1])); newLine.LineStyle = getLinestyleByName(doc, lineStyleToUse) as Element; } catch { TaskDialog.Show("Error", " Cannot create detail line in this type of family."); return(0); } } } catch { //Debug.Print("Could not create polyline"); } counter = counter + 1; } } else { //create a line in the current view try { if (docType == "project") { DetailCurve newLine = doc.Create.NewDetailCurve(doc.ActiveView, curGeom as Curve); newLine.LineStyle = getLinestyleByName(doc, lineStyleToUse) as Element; } else { try { DetailCurve newLine = doc.FamilyCreate.NewDetailCurve(doc.ActiveView, curGeom as Curve); newLine.LineStyle = getLinestyleByName(doc, lineStyleToUse) as Element; } catch { TaskDialog.Show("Error", " Cannot create detail line in this type of family."); return(0); } } counter = counter + 1; } catch { //Debug.Print("Could not create polyline"); } } } } tx.Commit(); } return(counter); }
// Main execution public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.AssemblyResolve += new ResolveEventHandler(Misc.LoadFromSameFolder); UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; View view = doc.ActiveView; Selection sel = uidoc.Selection; double tolerance = app.ShortCurveTolerance; // Check if the families are ready if (Properties.Settings.Default.name_door == null || Properties.Settings.Default.name_window == null) { System.Windows.MessageBox.Show("Please select the door/window type in settings", "Tips"); return(Result.Cancelled); } //if (!File.Exists(Properties.Settings.Default.url_door) && File.Exists(Properties.Settings.Default.url_window)) //{ // System.Windows.MessageBox.Show("Please check the family path is solid", "Tips"); // return Result.Cancelled; //} //Family fDoor, fWindow = null; //using (Transaction tx = new Transaction(doc, "Load necessary families")) //{ // tx.Start(); // if (!doc.LoadFamily(Properties.Settings.Default.url_door, out fDoor) || // !doc.LoadFamily(Properties.Settings.Default.url_window, out fWindow)) // { // System.Windows.MessageBox.Show("Loading family failed", "Tips"); // return Result.Cancelled; // } // tx.Commit(); //} // Pick Import Instance ImportInstance import = null; try { Reference r = uidoc.Selection.PickObject(ObjectType.Element, new Util.ElementsOfClassSelectionFilter <ImportInstance>()); import = doc.GetElement(r) as ImportInstance; } catch { return(Result.Cancelled); } if (import == null) { System.Windows.MessageBox.Show("CAD not found", "Tips"); return(Result.Cancelled); } // Fetch baselines List <Curve> doorCrvs = new List <Curve>(); List <Curve> windowCrvs = new List <Curve>(); List <Curve> wallCrvs = new List <Curve>(); var wallLayers = Misc.GetLayerNames(Properties.Settings.Default.layerWall); var doorLayers = Misc.GetLayerNames(Properties.Settings.Default.layerDoor); var windowLayers = Misc.GetLayerNames(Properties.Settings.Default.layerWindow); try { foreach (string doorLayer in doorLayers) { doorCrvs.AddRange(Util.TeighaGeometry.ShatterCADGeometry(uidoc, import, doorLayer, tolerance)); } foreach (string windowLayer in windowLayers) { windowCrvs.AddRange(Util.TeighaGeometry.ShatterCADGeometry(uidoc, import, windowLayer, tolerance)); } foreach (string wallLayer in wallLayers) { wallCrvs.AddRange(Util.TeighaGeometry.ShatterCADGeometry(uidoc, import, wallLayer, tolerance)); } } catch (Exception e) { System.Windows.MessageBox.Show(e.Message, "Tips"); return(Result.Cancelled); } if (doorCrvs == null || windowCrvs == null || wallCrvs == null || doorCrvs.Count * windowCrvs.Count * wallCrvs.Count == 0) { System.Windows.MessageBox.Show("Baselines not found", "Tips"); return(Result.Cancelled); } // Grab the current building level FilteredElementCollector docLevels = new FilteredElementCollector(doc) .WhereElementIsNotElementType() .OfCategory(BuiltInCategory.INVALID) .OfClass(typeof(Level)); ICollection <Element> levels = docLevels.OfClass(typeof(Level)).ToElements(); Level defaultLevel = null; foreach (Level level in levels) { if (level.Id == import.LevelId) { defaultLevel = level; } } if (defaultLevel == null) { System.Windows.MessageBox.Show("Please make sure there's a base level in current view", "Tips"); return(Result.Cancelled); } // Convert texts info into TextNote by Teigha // Revit does not expose any API to parse text info string path = Util.TeighaText.GetCADPath(uidoc, import); List <Util.TeighaText.CADTextModel> labels = Util.TeighaText.GetCADText(path); /* * List<UtilGetCADText.CADTextModel> labels = new List<UtilGetCADText.CADTextModel>(); * foreach (UtilGetCADText.CADTextModel text in UtilGetCADText.GetCADText(path)) * { * if (UtilGetCADText.IsLabel(text.Text, out string label)) * { * labels.Add(text); * } * } */ Debug.Print("The path of linked DWG file is: " + path); Debug.Print("Lables in total: " + labels.Count.ToString()); foreach (Util.TeighaText.CADTextModel label in labels) { Debug.Print(label.Text); } /* * // LineStyle filter * CurveElementFilter filter = new CurveElementFilter(CurveElementType.ModelCurve); * FilteredElementCollector collector = new FilteredElementCollector(doc); * ICollection<Element> founds = collector.WherePasses(filter).ToElements(); * List<CurveElement> importCurves = new List<CurveElement>(); * * foreach (CurveElement ce in founds) * { * importCurves.Add(ce); * } * * var doorCurves = importCurves.Where(x => x.LineStyle.Name == "DOOR").ToList(); * List<Curve> doorCrvs = new List<Curve>(); // The door block has one arc at least * foreach (CurveElement ce in doorCurves) * { * doorCrvs.Add(ce.GeometryCurve as Curve); * } * * var wallCurves = importCurves.Where(x => x.LineStyle.Name == "WALL").ToList(); * List<Line> wallLines = new List<Line>(); // Algorithm only support walls of line type * foreach (CurveElement ce in wallCurves) * { * wallLines.Add(ce.GeometryCurve as Line); * } * var windowCurves = importCurves.Where(x => x.LineStyle.Name == "WINDOW").ToList(); * List<Curve> windowCrvs = new List<Curve>(); * foreach (CurveElement ce in windowCurves) * { * windowCrvs.Add(ce.GeometryCurve as Curve); * } */ TransactionGroup tg = new TransactionGroup(doc, "Create openings"); try { tg.Start(); CreateOpening.Execute(doc, doorCrvs, windowCrvs, wallCrvs, labels, Properties.Settings.Default.name_door, Properties.Settings.Default.name_window, defaultLevel, false); tg.Assimilate(); } catch (Exception e) { System.Windows.MessageBox.Show(e.Message); tg.RollBack(); return(Result.Cancelled); } return(Result.Succeeded); }