Beispiel #1
0
        public void Cmd_SelectUnNamed()
        {
            if (!LicensingAgent.Check())
            {
                return;
            }
            var acCurDoc = Application.DocumentManager.MdiActiveDocument;
            var acCurDb  = acCurDoc.Database;
            var acCurEd  = acCurDoc.Editor;

            var objIds  = acCurEd.GetAllSelection(false);
            var unNamed = new List <ObjectId>();

            using (var pWorker = new ProgressAgent("Finding Unnamed Parts: ", objIds.Length))
            {
                using (var acTrans = acCurDb.TransactionManager.StartTransaction())
                {
                    foreach (var obj in objIds)
                    {
                        if (!pWorker.Progress())
                        {
                            acTrans.Abort();
                            return;
                        }

                        var acEnt = acTrans.GetObject(obj, OpenMode.ForRead) as Entity;

                        if (acEnt == null)
                        {
                            continue;
                        }
                        if (string.IsNullOrEmpty(acEnt.GetPartName()))
                        {
                            unNamed.Add(obj);
                        }
                    }

                    if (unNamed.Count > 0)
                    {
                        acCurEd.SetImpliedSelection(unNamed.ToArray());
                        acCurEd.SelectImplied();
                    }
                    else
                    {
                        acCurEd.WriteMessage("\nAll selected parts have pre-defined names.");
                    }

                    acTrans.Commit();
                }
            }
        }
Beispiel #2
0
        public void Cmd_RcUpdate()
        {
            if (!LicensingAgent.Check())
            {
                return;
            }
            var acCurDoc = Application.DocumentManager.MdiActiveDocument;
            var acCurDb  = acCurDoc.Database;
            var acCurEd  = acCurDoc.Editor;

            using (var acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                var objIds = acCurEd.SelectAllOfType("3DSOLID", acTrans);

                using (var pWorker = new ProgressAgent("Updating Solids:", objIds.Length))
                {
                    foreach (var obj in objIds)
                    {
                        if (!pWorker.Progress())
                        {
                            acTrans.Abort();
                            return;
                        }

                        var acSol = acTrans.GetObject(obj, OpenMode.ForRead) as Solid3d;
                        if (acSol == null)
                        {
                            continue;
                        }

                        acSol.Update(acCurDb, acTrans);
                    }
                }

                acCurEd.WriteMessage($"\n{objIds.Length} objects updated.");
                acTrans.Commit();
            }

            RcLeader.UpdateMleaders();
        }
Beispiel #3
0
        public void Cmd_PartsGen()
        {
            var acCurDoc = Application.DocumentManager.MdiActiveDocument;

            if (acCurDoc == null)
            {
                return;
            }

            var acCurDb   = acCurDoc.Database;
            var acCurEd   = acCurDoc.Editor;
            var modelView = acCurEd.GetCurrentView().Clone() as ViewTableRecord;

            var objIds = acCurEd.GetFilteredSelection(Enums.DxfNameEnum._3Dsolid, false);

            if (objIds.Length <= 0)
            {
                return;
            }

            var splitNum = 8;
            var colCount = splitNum / 2;
            var rowCount = 2;

            var partList = new List <Solid3d>();

            using (var acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                foreach (var ob in objIds)
                {
                    var acSol = acTrans.GetObject(ob, OpenMode.ForRead) as Solid3d;
                    if (acSol == null)
                    {
                        continue;
                    }
                    partList.Add(acSol);
                }

                acTrans.Commit();
            }

            var sortedParts = partList.OrderBy(e => e.GetPartName()).ToList();

            var objChunks = sortedParts.ChunkBy(splitNum);

            var layName = "Model";

            var vPorts = new List <Viewport>();

            using (var pWorker = new ProgressAgent("Creating Part Views: ", sortedParts.Count))

                using (var acTrans = acCurDb.TransactionManager.StartTransaction())
                {
                    for (var i = 0; i < objChunks.Count; i++)
                    {
                        var curLayout = "PrtGen";
                        var id        = LayoutManager.Current.CreateAndMakeLayoutCurrentByAddition(curLayout);
                        // Open the created layout
                        var lay = (Layout)acTrans.GetObject(id, OpenMode.ForWrite);

                        // Open the Block table record Paper space for write
                        var acBlkTableRec = acTrans.GetObject(lay.BlockTableRecordId,
                                                              OpenMode.ForWrite) as BlockTableRecord;

                        // Make some settings on the layout and get its extents
                        lay.SetPlotSettings(
                            //"ISO_full_bleed_2A0_(1189.00_x_1682.00_MM)", // Try this big boy!
                            // "ANSI_B_(11.00_x_17.00_Inches)",
                            "ARCH_full_bleed_D_(36.00_x_24.00_Inches)",
                            "monochrome.ctb",
                            "AutoCAD PDF (High Quality Print).pc3"
                            );

                        if (acBlkTableRec != null)
                        {
                            foreach (var vpId in acBlkTableRec)
                            {
                                if (vpId == acCurDb.PaperSpaceVportId)
                                {
                                    continue;
                                }
                                var vp = acTrans.GetObject(vpId, OpenMode.ForRead) as Viewport;
                                if (vp != null)
                                {
                                    vPorts.Add(vp);
                                }
                            }

                            var layOutSize  = GetLayoutSize(lay);
                            var paperLength = layOutSize.Width;
                            var paperHeight = layOutSize.Height;

                            var dSpacing    = CalcUnit.GetProportion(1.5, 36, paperLength);
                            var dBorder     = CalcUnit.GetProportion(1.5, 36, paperLength);
                            var availWidth  = paperLength - dBorder * 2.5 - dSpacing * (colCount + 1);
                            var availHeight = paperHeight - dBorder * 2.25 - dSpacing * (rowCount + 1);

                            var dWidth  = availWidth / colCount;
                            var dWHalf  = dWidth / 2;
                            var dHeight = availHeight / rowCount;
                            var dhHalf  = dHeight / 2;

                            var col1 = dBorder + dWHalf + dSpacing;
                            var col2 = dBorder + dWHalf + dSpacing * 2 + dWidth;
                            var col3 = dBorder + dWHalf + dSpacing * 3 + dWidth * 2;
                            var col4 = dBorder + dWHalf + dSpacing * 4 + dWidth * 3;
                            //var col5 = dBorder + dWHalf + dSpacing * 5 + dWidth * 4;

                            var row1 = paperHeight - dhHalf - dBorder - dSpacing;
                            var row2 = paperHeight - dhHalf - dBorder - dSpacing * 2 - dHeight;
                            //row3 = paperHeight - dhHalf - dBorder - dSpacing * 3 - dHeight * 2;
                            //row4 = paperHeight - dhHalf - dBorder - dSpacing * 4 - dHeight * 3;

                            var positions = new[]
                            {
                                new Point2d(col1, row1),
                                new Point2d(col2, row1),
                                new Point2d(col3, row1),
                                new Point2d(col4, row1),
                                new Point2d(col1, row2),
                                new Point2d(col2, row2),
                                new Point2d(col3, row2),
                                new Point2d(col4, row2)
                            };

                            for (var j = 0; j < objChunks[i].Count; j++)
                            {
                                //Progress progress bar or exit if ESC has been pressed
                                if (!pWorker.Progress())
                                {
                                    acTrans.Abort();
                                    return;
                                }

                                var acSol = acTrans.GetObject(objChunks[i][j].ObjectId, OpenMode.ForWrite) as Solid3d;
                                if (acSol == null)
                                {
                                    continue;
                                }
                                var acExt   = acSol.GeometricExtents;
                                var acVport = new Viewport
                                {
                                    CenterPoint   = positions[j].Convert3D(),
                                    Width         = dWidth,
                                    Height        = dHeight,
                                    ViewDirection = ViewDirection.TopView
                                };

                                acCurDb.AppendEntity(acVport, acTrans);

                                acVport.FitContentToViewport(acExt);
                                acVport.FitViewportToContent(acExt);
                                acVport.CenterPoint = positions[j].Convert3D();
                                acVport.UpdateDisplay();
                                acVport.Layer = "Defpoints";
                                // Enable the viewport
                                acVport.Visible = true;
                                acVport.On      = true;

                                //acVport.CreateBaseViewFromVp(acSol.ObjectId, acCurEd, acCurDb, lay, acVport.CenterPoint);

                                System.Threading.Thread.Sleep(300);

                                vPorts.Add(acVport);

                                //Insert Part Tags
                                //Insert block to name the viewport
                                var insertMin = acVport.GeometricExtents.MinPoint;
                                var insertMax = acVport.GeometricExtents.MaxPoint;

                                var mid       = insertMin.GetMidPoint(insertMax);
                                var midInsert = new Point3d(mid.X, positions[j].Convert3D().Y - 1, 0);

                                // Open the Block table for read
                                var acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForWrite) as BlockTable;

                                if (!acBlkTbl.Has(SettingsInternal.TagName))
                                {
                                    MakeTag_Name(acBlkTbl, acTrans);
                                }

                                var blockName = SettingsInternal.TagName;

                                var acBlkRef = acBlkTableRec.InsertBlock(blockName, midInsert, acCurDb);

                                if (acBlkRef != null)
                                {
                                    UpdatePartViewSubs(acBlkRef, acSol, acCurDoc);
                                }
                            }
                        }

                        layName = lay.LayoutName;
                    }

                    //Save the new objects to the database
                    LayoutManager.Current.CurrentLayout = "MODEL";
                    using (var view = acCurEd.GetCurrentView())
                    {
                        view.CopyFrom(modelView);
                        acCurEd.SetCurrentView(view);
                    }
                    try
                    {
                        Thread.Sleep(300);
                        LayoutManager.Current.CurrentLayout = layName;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                    if (modelView != null)
                    {
                        modelView.Dispose();
                    }

                    // Zoom so that we can see our new layout, again with a little padding
                    acCurEd.Command("_.ZOOM", "_E");
                    acCurEd.Command("_.ZOOM", ".7X");
                    acCurEd.Regen();

                    // Commit the transaction
                    acTrans.Commit();
                }

            //using (var acTrans = acCurDb.TransactionManager.StartTransaction())
            //{
            //    foreach (var acVp in vPorts)
            //    {
            //        if (acVp.ObjectId == acCurDb.PaperSpaceVportId) continue;

            //        var delVp = acTrans.GetObject(acVp.ObjectId, OpenMode.ForWrite) as Viewport;
            //        delVp.Erase();
            //        delVp.Dispose();
            //    }

            //    acTrans.Commit();
            //}
        }
Beispiel #4
0
        internal static void Traverse(bool reselect = false)
        {
            var acCurDoc = Application.DocumentManager.MdiActiveDocument;
            var acCurDb  = acCurDoc.Database;
            var acCurEd  = acCurDoc.Editor;

            //Start a selection set
            SelectionSet acSet;

            //Check for pick-first selection -> if none, get selection
            if (!acCurEd.CheckForPickFirst(out acSet))
            {
                acSet = SelectionSet.FromObjectIds(acCurEd.GetFilteredSelection(Enums.DxfNameEnum._3Dsolid, false));
            }

            using (var acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                using (var pWorker = new ProgressAgent("Parsing Solids: ", acSet.Count))
                {
                    var parseCount = 1;

                    foreach (var objId in acSet.GetObjectIds())
                    {
                        //Progress progress bar or exit if ESC has been pressed
                        if (!pWorker.Progress())
                        {
                            acTrans.Abort();
                            return;
                        }

                        var acSol = acTrans.GetObject(objId, OpenMode.ForRead) as Solid3d;

                        if (acSol == null)
                        {
                            continue;
                        }

                        var entInfo = new EntInfo(acSol, acCurDb, acTrans);
                        acSol.AddXData(entInfo, acCurDb, acTrans);

                        if (!reselect)
                        {
                            acCurEd.WriteMessage("\n" + entInfo.PrintInfo(false, parseCount));
                        }

                        parseCount++;

                        #region Debug Testing

                        //acSol.UpdateXData("TestName", Enums.XDataCode.Name, acCurDb, acTrans); //1
                        //acSol.UpdateXData("TestInfo", Enums.XDataCode.Info, acCurDb, acTrans); //2
                        //acSol.UpdateXData(10, Enums.XDataCode.Length, acCurDb, acTrans); //3
                        //acSol.UpdateXData(20, Enums.XDataCode.Width, acCurDb, acTrans); //4
                        //acSol.UpdateXData(30, Enums.XDataCode.Thickness, acCurDb, acTrans); //5
                        //acSol.UpdateXData(40, Enums.XDataCode.Volume, acCurDb, acTrans); //6
                        //acSol.UpdateXData(50, Enums.XDataCode.MaxArea, acCurDb, acTrans); //7
                        //acSol.UpdateXData(60, Enums.XDataCode.MaxPerimeter, acCurDb, acTrans); //8
                        //acSol.UpdateXData(70, Enums.XDataCode.Asymmetry, acCurDb, acTrans); //9
                        //acSol.UpdateXData("AxymV", Enums.XDataCode.AsymmetryVector, acCurDb, acTrans); //10
                        //acSol.UpdateXData(1, Enums.XDataCode.PartOf, acCurDb, acTrans); //11
                        //acSol.UpdateXData(2, Enums.XDataCode.PartTotal, acCurDb, acTrans); //12
                        //acSol.UpdateXData(3, Enums.XDataCode.NumChanges, acCurDb, acTrans); //13
                        //acSol.UpdateXData(false, Enums.XDataCode.IsSweep, acCurDb, acTrans); //14
                        //acSol.UpdateXData(true, Enums.XDataCode.IsMirror, acCurDb, acTrans); //15
                        //acSol.UpdateXData(false, Enums.XDataCode.HasHoles, acCurDb, acTrans); //16
                        //acSol.UpdateXData(Enums.Texture.Across, Enums.XDataCode.Texture, acCurDb, acTrans); //17
                        //acSol.UpdateXData(Enums.Production.MillingTwoSide, Enums.XDataCode.Production, acCurDb, acTrans); //18
                        //acSol.UpdateXData(acSol.Handle, Enums.XDataCode.ParentObject, acCurDb, acTrans); //19
                        //acSol.UpdateXData(new List<Handle>() {acSol.Handle, acSol.Handle , acSol.Handle},
                        //Enums.XDataCode.ChildObjects, acCurDb, acTrans); //20

                        //acCurEd.WriteMessage("\n Testing XData Read");
                        //acCurEd.WriteMessage("\n" + acSol.GetAppName());
                        //acCurEd.WriteMessage("\n" + acSol.GetPartName());
                        //acCurEd.WriteMessage("\n" + acSol.GetPartInfo());
                        //acCurEd.WriteMessage("\n" + acSol.GetPartLength());
                        //acCurEd.WriteMessage("\n" + acSol.GetPartWidth());
                        //acCurEd.WriteMessage("\n" + acSol.GetPartThickness());
                        //acCurEd.WriteMessage("\n" + acSol.GetPartVolume());
                        //acCurEd.WriteMessage("\n" + acSol.GetPartArea());
                        //acCurEd.WriteMessage("\n" + acSol.GetPartPerimeter());
                        //acCurEd.WriteMessage("\n" + acSol.GetPartAsymmetry());
                        //acCurEd.WriteMessage("\n" + acSol.GetAsymVector());
                        //acCurEd.WriteMessage("\n" + acSol.GetQtyOf());
                        //acCurEd.WriteMessage("\n" + acSol.GetQtyTotal());
                        //acCurEd.WriteMessage("\n" + acSol.GetNumChanges());
                        //acCurEd.WriteMessage("\n" + acSol.GetIsSweep());
                        //acCurEd.WriteMessage("\n" + acSol.GetIsMirror());
                        //acCurEd.WriteMessage("\n" + acSol.GetHasHoles());
                        //acCurEd.WriteMessage("\n" + acSol.GetTextureDirection());
                        //acCurEd.WriteMessage("\n" + acSol.GetProductionType());
                        //acCurEd.WriteMessage("\n" + acSol.GetParent());
                        //acCurEd.WriteMessage("\n" + String.Join(",",acSol.GetChildren()));

                        #endregion
                    }

                    if (reselect)
                    {
                        acCurEd.SetImpliedSelection(acSet.GetObjectIds());
                    }
                }

                acTrans.Commit();
            }
        }
Beispiel #5
0
        public void Cmd_RCChop()
        {
            var acCurDoc = Application.DocumentManager.MdiActiveDocument;
            var acCurDb  = acCurDoc.Database;
            var acCurEd  = acCurDoc.Editor;

            //Call user to select a face
            var userSel = acCurEd.SelectSubentity(SubentityType.Face, "\nSelect a FACE to use as chopping criteria: ");

            if (userSel == null)
            {
                return;
            }
            if (userSel.Item1 == ObjectId.Null)
            {
                return;
            }
            if (userSel.Item2 == SubentityId.Null)
            {
                return;
            }

            var prSelOpts = new PromptDistanceOptions("\nEnter chop distance: ")
            {
                AllowNone     = false,
                AllowZero     = false,
                AllowNegative = false,
                DefaultValue  = SettingsUser.RcChopDepth
            };

            //Get the offset distance
            var prSelRes = acCurEd.GetDistance(prSelOpts);


            if (prSelRes.Status != PromptStatus.OK)
            {
                return;
            }

            SettingsUser.RcChopDepth = prSelRes.Value;

            // ReSharper disable once CompareOfFloatsByEqualityOperator
            if (SettingsUser.RcChopDepth == 0)
            {
                return;
            }
            var     sList    = new List <Surface>();
            Entity  faceEnt  = null;
            Surface tempSurf = null;

            try
            {
                //Open a transaction
                using (var acTrans = acCurDb.TransactionManager.StartTransaction())
                {
                    var acSol = acTrans.GetObject(userSel.Item1, OpenMode.ForWrite) as Solid3d;
                    if (acSol == null)
                    {
                        acTrans.Abort();
                        return;
                    }

                    faceEnt = acSol.GetSubentity(userSel.Item2);

                    using (tempSurf = faceEnt.CreateSurfaceFromFace(acCurDb, acTrans, false))
                    {
                        var canSlice   = true;
                        var multiplier = 1;

                        using (var pWorker = new ProgressAgent("Testing Chops: ", 100))
                        {
                            while (canSlice)
                            {
                                if (!pWorker.Progress())
                                {
                                    break;
                                }

                                var sliceSurf =
                                    Surface.CreateOffsetSurface(tempSurf,
                                                                -SettingsUser.RcChopDepth * multiplier) as Surface;

                                if (sliceSurf == null)
                                {
                                    break;
                                }

                                canSlice = CanSlice(acSol, sliceSurf);

                                if (!canSlice)
                                {
                                    sliceSurf.Dispose();
                                    continue;
                                }

                                sList.Add(sliceSurf);

                                multiplier++;
                            }

                            if (sList.Count > 0)
                            {
                                pWorker.SetTotalOperations(sList.Count);
                                pWorker.Reset("Chopping Solid: ");

                                foreach (var su in sList)
                                {
                                    if (!pWorker.Progress())
                                    {
                                        acTrans.Abort();
                                        break;
                                    }

                                    var obj = acSol.Slice(su, true);
                                    obj.SetPropertiesFrom(acSol);
                                    acCurDb.AppendEntity(obj);
                                }
                            }
                            else
                            {
                                acCurEd.WriteMessage("\nNo Chopping Criteria found!");
                            }
                        }
                    }

                    acTrans.Commit();
                }
            }
            catch (Exception e)
            {
                acCurEd.WriteMessage(e.Message);
            }
            finally
            {
                foreach (var suf in sList)
                {
                    suf.Dispose();
                }

                if (faceEnt != null)
                {
                    faceEnt.Dispose();
                }
                if (tempSurf != null)
                {
                    tempSurf.Dispose();
                }
            }
        }
Beispiel #6
0
        public void Cmd_NameParts()
        {
            if (!LicensingAgent.Check())
            {
                return;
            }
            var acCurDoc = Application.DocumentManager.MdiActiveDocument;
            var acCurDb  = acCurDoc.Database;
            var acCurEd  = acCurDoc.Editor;

            var keyList = new List <KeywordAgent>();

            var userResetPartCounter = SettingsUser.ResetPartCount;

            //Reset Part Number to 1 if specified in bool
            if (SettingsUser.ResetPartCount)
            {
                SortingAgent.CurrentPartNumber = 1;
            }

            var keyAgentName = new KeywordAgent(acCurEd, "NameFormat", "Enter naming format: ", TypeCode.String,
                                                SettingsUser.NamingConvention);
            var keyAgentNum = new KeywordAgent(acCurEd, "StartFrom", "Enter part number to start from: ",
                                               TypeCode.Int32, SortingAgent.CurrentPartNumber.ToString());

            keyList.Add(keyAgentName);
            keyList.Add(keyAgentNum);

            //Check for pick-first selection -> if none, get selection
            var acSet = SelectionSet.FromObjectIds(acCurEd.GetFilteredSelection(DxfNameEnum._3Dsolid, false, keyList));

            keyAgentName.Set(ref SettingsUser.NamingConvention);
            keyAgentNum.Set(ref SortingAgent.CurrentPartNumber);

            using (var acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                using (var pWorker = new ProgressAgent("Parsing Solids: ", acSet.Count))
                {
                    var eList = new List <EntInfo>();

                    foreach (var objId in acSet.GetObjectIds())
                    {
                        //Progress progress bar or exit if ESC has been pressed
                        if (!pWorker.Progress())
                        {
                            acTrans.Abort();
                            return;
                        }

                        var acSol = acTrans.GetObject(objId, OpenMode.ForRead) as Solid3d;

                        if (acSol == null)
                        {
                            continue;
                        }

                        eList.Add(new EntInfo(acSol, acCurDb, acTrans));
                    }

                    //eList.SortSolids();
                    eList.SortAndName(pWorker, acCurDb, acCurEd, acTrans);
                }

                acTrans.Commit();
            }

            SettingsUser.ResetPartCount = userResetPartCounter;
        }
Beispiel #7
0
        public void Cmd_RcMark()
        {
            if (!LicensingAgent.Check())
            {
                return;
            }
            var acCurDoc = Application.DocumentManager.MdiActiveDocument;
            var acCurDb  = acCurDoc.Database;
            var acCurEd  = acCurDoc.Editor;

            _ = AcVars.CmdEcho;
            AcVars.CmdEcho = Enums.CmdEcho.Off;

            // Set up our selection to only select 3D solids
            var pso = new PromptSelectionOptions {
                MessageForAdding = "\nSelect viewports to mark: "
            };
            var sf = new SelectionFilter(new[] { new TypedValue((int)DxfCode.Start, "VIEWPORT") });

            //Get the 3d Solid Selection
            var res = acCurEd.GetSelection(pso, sf);

            if (res.Status == PromptStatus.OK)
            {
                // extract the viewport points
                using (var acTrans = acCurDb.TransactionManager.StartTransaction())
                {
                    acCurDb.TransactionManager.QueueForGraphicsFlush();

                    using (
                        var pWorker = new ProgressAgent("Marking Viewports: ", res.Value.Count))
                    {
                        foreach (var objId in res.Value.GetObjectIds())
                        {
                            if (!pWorker.Progress())
                            {
                                acTrans.Abort();
                                return;
                            }

                            using (var psVp = acTrans.GetObject(objId, OpenMode.ForRead) as Viewport)
                            {
                                var pObjs = objId.GetPaperObjects();
                                var mObjs = objId.GetModelObjects();

                                if (pObjs.Count > 0 && SettingsUser.DeleteExistingMarks)
                                {
                                    foreach (ObjectId id in pObjs)
                                    {
                                        var acEnt = acTrans.GetObject(id, OpenMode.ForWrite) as Entity;
                                        if (acEnt == null)
                                        {
                                            continue;
                                        }

                                        if (!acEnt.HasXData())
                                        {
                                            continue;
                                        }
                                        var txt = acEnt.GetXData <string>(Enums.XDataCode.Info);

                                        if (txt != "RCMARK")
                                        {
                                            continue;
                                        }
                                        acEnt.Erase();
                                        acEnt.Dispose();
                                    }
                                }

                                if (mObjs.Count <= 0)
                                {
                                    continue;
                                }
                                {
                                    //Finished finding objects, now create tags
                                    var xform = psVp.Ms2Ps();

                                    foreach (ObjectId id in mObjs)
                                    {
                                        var dbObj = acTrans.GetObject(id, OpenMode.ForWrite);
                                        if (dbObj == null)
                                        {
                                            continue;
                                        }

                                        switch (dbObj)
                                        {
                                        case Solid3d acSol:
                                        {
                                            var solCen  = acSol.MassProperties.Centroid;
                                            var solName = acSol.GetPartName();
                                            var insPt   = solCen.TransformBy(xform).Flatten();

                                            using (var acText = new MText())
                                            {
                                                acText.TextHeight         = SettingsUser.MarkTextHeight;
                                                acText.Contents           = solName;
                                                acText.BackgroundFill     = true;
                                                acText.UseBackgroundColor = true;
                                                acText.ShowBorders        = true;
                                                acText.Location           = insPt;
                                                acText.Attachment         = AttachmentPoint.MiddleCenter;
                                                //acText.Layer = ;
                                                //acText.ColorIndex = ;

                                                //Append the text
                                                acCurDb.AppendEntity(acText, acTrans);
                                                acText.UpdateXData("RCMARK", Enums.XDataCode.Info, acCurDb, acTrans);
                                            }

                                            break;
                                        }

                                        case BlockReference bRef:
                                        {
                                            var ext = acTrans.GetExtents(new ObjectId[] { bRef.ObjectId }, acCurDb);
                                            var cen = ext.MinPoint.GetMidPoint(ext.MaxPoint);

                                            var bName = bRef.Name;
                                            var insPt = cen.TransformBy(xform).Flatten();

                                            using (var acText = new MText())
                                            {
                                                acText.TextHeight         = SettingsUser.MarkTextHeight;
                                                acText.Contents           = bName;
                                                acText.BackgroundFill     = true;
                                                acText.UseBackgroundColor = true;
                                                acText.ShowBorders        = true;
                                                acText.Location           = insPt;
                                                acText.Attachment         = AttachmentPoint.MiddleCenter;
                                                //acText.Layer = ;
                                                //acText.ColorIndex = ;

                                                //Append the text
                                                acCurDb.AppendEntity(acText, acTrans);
                                                acText.UpdateXData("RCMARK", Enums.XDataCode.Info, acCurDb, acTrans);
                                            }

                                            break;
                                        }
                                        }
                                    }
                                }
                            }
                        }

                        acTrans.Commit();
                    }
                }
            }
        }
Beispiel #8
0
        public void Cmd_LayParts()
        {
            if (!LicensingAgent.Check())
            {
                return;
            }
            var acCurDoc = Application.DocumentManager.MdiActiveDocument;
            var acCurDb  = acCurDoc.Database;
            var acCurEd  = acCurDoc.Editor;

            var keys = new List <KeywordAgent>();

            var keyFlatAssembly = new KeywordAgent(acCurEd, "FLatshot", "Flatten part to 2D lines? ", TypeCode.Boolean,
                                                   SettingsUser.LayFlatShot.ToSpecified());

            keys.Add(keyFlatAssembly);


            //Check for pick-first selection -> if none, get selection
            var acSet = SelectionSet.FromObjectIds(acCurEd.GetFilteredSelection(Enums.DxfNameEnum._3Dsolid, false, keys));

            if (acSet.Count <= 0)
            {
                return;
            }

            keyFlatAssembly.Set(ref SettingsUser.LayFlatShot);

            if (SettingsUser.LayFlatShot)
            {
                var layFlatShot = acCurEd.GetBool("\n Create flatshot for each side?");
                if (layFlatShot != null)
                {
                    SettingsUser.LayAllSidesFlatShot = layFlatShot.Value;
                }


                var retainHidden = acCurEd.GetBool("\n Retain hidden lines?");
                if (retainHidden != null)
                {
                    SettingsUser.RetainHiddenLines = retainHidden.Value;
                }
            }
            else
            {
                SettingsUser.LayAllSidesFlatShot = false;
            }

            //Set the UCS to World - save the user UCS
            var userCoordSystem = acCurEd.CurrentUserCoordinateSystem;

            acCurEd.CurrentUserCoordinateSystem = Matrix3d.Identity;

            //Set the Grid Mode to ON if it is not ON - Get the users current grid mode
            var userGridMode = AcVars.GridMode;

            if (AcVars.GridMode != Enums.GridMode.On)
            {
                AcVars.GridMode = Enums.GridMode.On;
            }

            acCurEd.Regen();

            var laypt = acCurEd.Get2DPoint("\nSelect point to lay parts at: ");

            // Return the Grid Mode to the Users Setting
            AcVars.GridMode = userGridMode;

            var multAmount = 1;

            if (SettingsUser.PromptForMultiplication)
            {
                multAmount = acCurEd.GetPositiveInteger("\nEnter number to multiply parts by: ", 1);
            }

            using (var acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                using (var pWorker = new ProgressAgent("Parsing Solids: ", acSet.Count))
                {
                    var eList = new List <EntInfo>();

                    foreach (var objId in acSet.GetObjectIds())
                    {
                        //Progress progress bar or exit if ESC has been pressed
                        if (!pWorker.Progress())
                        {
                            acTrans.Abort();
                            return;
                        }

                        var acSol = acTrans.GetObject(objId, OpenMode.ForRead) as Solid3d;

                        if (acSol == null)
                        {
                            continue;
                        }

                        eList.Add(new EntInfo(acSol, acCurDb, acTrans));
                    }

                    eList.SortAndLay(laypt, pWorker, acCurDb, acCurEd, acTrans, multAmount);
                }

                acTrans.Commit();
            }

            //Set the UCS back to the user UCS
            acCurEd.CurrentUserCoordinateSystem = userCoordSystem;
            acCurEd.Regen();
        }
Beispiel #9
0
        public void Cmd_GenDims()
        {
            var acCurDoc = Application.DocumentManager.MdiActiveDocument;
            var acCurDb  = acCurDoc.Database;
            var acCurEd  = acCurDoc.Editor;

            var objIds = acCurEd.GetAllSelection(false);

            if (objIds.Length <= 0)
            {
                return;
            }

            using (var pWorker = new ProgressAgent("Generating Dimension: ", objIds.Length))
            {
                using (var acTrans = acCurDb.TransactionManager.StartTransaction())
                {
                    foreach (var obj in objIds)
                    {
                        if (!pWorker.Progress())
                        {
                            acTrans.Abort();
                            return;
                        }

                        var acEnt = acTrans.GetObject(obj, OpenMode.ForRead) as Entity;
                        if (acEnt == null)
                        {
                            continue;
                        }

                        var extents = acEnt.GeometricExtents;

                        var minPt = extents.MinPoint;
                        var maxPt = extents.MaxPoint;

                        // Create the rotated dimension
                        using (var acXDim = new RotatedDimension())
                        {
                            acXDim.XLine1Point    = new Point3d(minPt.X, minPt.Y, 0);
                            acXDim.XLine2Point    = new Point3d(maxPt.X, minPt.Y, 0);
                            acXDim.DimLinePoint   = new Point3d(minPt.X, minPt.Y - SettingsUser.AnnoSpacing, 0);
                            acXDim.DimensionStyle = acCurDb.Dimstyle;

                            // Add the new object to Model space and the transaction
                            acCurDb.AppendEntity(acXDim);
                        }

                        // Create the rotated dimension
                        using (var acYDim = new RotatedDimension())
                        {
                            acYDim.XLine1Point    = new Point3d(minPt.X, minPt.Y, 0);
                            acYDim.XLine2Point    = new Point3d(minPt.X, maxPt.Y, 0);
                            acYDim.Rotation       = CalcUnit.ConvertToRadians(90);
                            acYDim.DimLinePoint   = new Point3d(minPt.X - SettingsUser.AnnoSpacing, minPt.Y, 0);
                            acYDim.DimensionStyle = acCurDb.Dimstyle;

                            // Add the new object to Model space and the transaction
                            acCurDb.AppendEntity(acYDim);
                        }
                    }

                    acTrans.Commit();
                }
            }
        }
Beispiel #10
0
        public void Cmd_RcJoint()
        {
            if (!LicensingAgent.Check())
            {
                return;
            }
            var acCurDoc = Application.DocumentManager.MdiActiveDocument;
            var acCurDb  = acCurDoc.Database;
            var acCurEd  = acCurDoc.Editor;

            //Prompt user to select solids to use as joint materials
            var userRes1 = acCurEd.GetFilteredSelection(Enums.DxfNameEnum._3Dsolid, false, null,
                                                        "\nSelect 3DSOLIDS to extend: ");

            if (userRes1.Length <= 0)
            {
                return;
            }

            var userRes2 = acCurEd.GetFilteredSelection(Enums.DxfNameEnum._3Dsolid, false, null,
                                                        "\nSelect 3DSOLIDS to cut joints into: ");

            if (userRes2.Length <= 0)
            {
                return;
            }

            //Get the Joint depth from the user
            var userDistOpt = new PromptDistanceOptions(string.Empty)
            {
                DefaultValue  = SettingsUser.RcJointDepth,
                Message       = "\n Enter joint depth: ",
                AllowNone     = false,
                AllowNegative = false,
                AllowZero     = false
            };

            //Set the join depth
            var distRes = acCurEd.GetDistance(userDistOpt);

            if (distRes.Status != PromptStatus.OK)
            {
                return;
            }

            SettingsUser.RcJointDepth = distRes.Value;

            //Create lists to hold solids
            var joinerSols  = new List <Solid3d>();
            var joinToSols  = new List <Solid3d>();
            var joinerGroup = new List <Tuple <Solid3d, List <SubentityId> > >();

            try
            {
                //Open a transaction
                using (var acTrans = acCurDb.TransactionManager.StartTransaction())
                {
                    //Get the object Ids of all of the selected solids
                    var joinerIds = userRes1;
                    var joinToIds = userRes2;

                    //Iterate through the joiner IDs
                    joinerSols.AddRange(
                        joinerIds.Select(joinId => acTrans.GetObject(joinId, OpenMode.ForWrite) as Solid3d));

                    //Iterate through the joiner IDs
                    joinToSols.AddRange(
                        joinToIds.Select(joinToId => acTrans.GetObject(joinToId, OpenMode.ForWrite) as Solid3d));
                    var joinToIds2 = joinToIds.ToList();

                    try
                    {
                        //Iterate through the joining solids and find if they touch the join to solids
                        foreach (var joinSol in joinerSols)
                        {
                            var subIds = new List <SubentityId>();

                            //Get Full Subentity Path
                            ObjectId[] objIds   = { joinSol.ObjectId };
                            var        fSubPath = new FullSubentityPath(objIds,
                                                                        new SubentityId(SubentityType.Null, IntPtr.Zero));

                            //Get BREP Subentities
                            using (var acBrep = new Brep(fSubPath))
                            {
                                var faceCollection = acBrep.Faces.ToList();

                                Debug.WriteLine(faceCollection.Count());

                                using (
                                    var pWorker = new ProgressAgent("Cutting Joints: ",
                                                                    faceCollection.Count()))
                                {
                                    //Offset each face and see if it interferes with a join to solid
                                    foreach (var jointFace in faceCollection)
                                    {
                                        //Progress progress bar or exit if ESC has been pressed
                                        if (!pWorker.Progress())
                                        {
                                            acTrans.Abort();
                                            return;
                                        }

                                        using (var tempTrans = new OpenCloseTransaction())
                                        {
                                            var checkJoiner =
                                                tempTrans.GetObject(joinSol.ObjectId, OpenMode.ForWrite) as Solid3d;

                                            SubentityId[] subentId =
                                            {
                                                checkJoiner.GetFsPath(jointFace.SubentityPath.SubentId).SubentId
                                            };
                                            checkJoiner?.OffsetFaces(subentId, 0.001);

                                            foreach (var checkSol in joinToSols)
                                            {
                                                var tempCheckSol =
                                                    tempTrans.GetObject(checkSol.ObjectId, OpenMode.ForRead) as Solid3d;
                                                if (checkJoiner != null && checkJoiner.CheckInterference(tempCheckSol))
                                                {
                                                    subIds.Add(subentId[0]);
                                                }
                                            }

                                            //Do not commit the transaction
                                            tempTrans.Abort();
                                        }
                                    }
                                }
                            }

                            //If touching faces found, add them to the group list
                            if (subIds.Count > 0)
                            {
                                joinerGroup.Add(Tuple.Create(joinSol, subIds));
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        acCurEd.WriteMessage(e.Message);
                        MailAgent.Report(e.Message);
                        acTrans.Abort();
                    }

                    var joinerIds2 = new List <ObjectId>();

                    //Offset all joiner faces
                    try
                    {
                        foreach (var group in joinerGroup)
                        {
                            if (!group.Item1.IsWriteEnabled)
                            {
                                group.Item1.UpgradeOpen();
                            }

                            try
                            {
                                group.Item1.OffsetFaces(group.Item2.ToArray(), SettingsUser.RcJointDepth);
                                joinerIds2.Add(group.Item1.ObjectId);
                            }
                            catch (Exception e)
                            {
                                acCurEd.WriteMessage(e.Message);
                                MailAgent.Report(e.Message);
                            }
                        }

                        //Open a transaction for subtracting solids
                        if (joinerIds2.Count > 0)
                        {
                            //Subtract the joint material from the join to parts
                            joinToIds2.ToArray().SolidSubtrahend(joinerIds2.ToArray(), acCurDb, acTrans, false);
                        }
                    }
                    catch (Exception e)
                    {
                        acCurEd.WriteMessage(e.Message);
                        MailAgent.Report(e.Message);
                        acTrans.Abort();
                    }

                    //Commit the transaction
                    acTrans.Commit();
                }
            }
            catch (Exception e)
            {
                acCurEd.WriteMessage(e.Message);
                MailAgent.Report(e.Message);
            }
        }
Beispiel #11
0
        public void Cmd_RcFlatten()
        {
            var acCurDoc = Application.DocumentManager.MdiActiveDocument;
            var acCurDb  = acCurDoc.Database;
            var acCurEd  = acCurDoc.Editor;

            var keys = new List <KeywordAgent>();

            var keyFlatAssembly = new KeywordAgent(acCurEd, "assemBly", "Flatten Assembly? ", TypeCode.Boolean,
                                                   SettingsUser.FlattenAssembly.ToSpecified());

            var keyFlatAllSides = new KeywordAgent(acCurEd, "allSides", "Flatten All Sides? ", TypeCode.Boolean,
                                                   SettingsUser.FlattenAllSides.ToSpecified());

            var keyRetainHidden = new KeywordAgent(acCurEd, "retainHidden", "Retain Hidden Lines? ", TypeCode.Boolean,
                                                   SettingsUser.RetainHiddenLines.ToSpecified());

            keys.Add(keyFlatAssembly);
            keys.Add(keyFlatAllSides);
            keys.Add(keyRetainHidden);

            var objIds =
                acCurEd.GetFilteredSelection(Enums.DxfNameEnum._3Dsolid, false, keys, "\nSelect solids to flatten: ");

            if (objIds.Length <= 0)
            {
                return;
            }

            keyFlatAssembly.Set(ref SettingsUser.FlattenAssembly);
            keyFlatAllSides.Set(ref SettingsUser.FlattenAllSides);
            keyRetainHidden.Set(ref SettingsUser.RetainHiddenLines);

            using (var pWorker = new ProgressAgent("Flattening Solids: ", objIds.Length))
            {
                using (var acTrans = acCurDb.TransactionManager.StartTransaction())
                {
                    //Set the UCS to World - save the user UCS
                    var userCoordSystem = acCurEd.CurrentUserCoordinateSystem;
                    acCurEd.CurrentUserCoordinateSystem = Matrix3d.Identity;

                    if (SettingsUser.FlattenAssembly || SettingsUser.FlattenAllSides)
                    {
                        var objId = objIds.SolidFusion(acTrans, acCurDb, true);
                        objIds = new[] { objId };
                    }

                    foreach (var obj in objIds)
                    {
                        if (!pWorker.Progress())
                        {
                            acTrans.Abort();
                        }

                        using (var acSol = acTrans.GetObject(obj, OpenMode.ForWrite) as Solid3d)
                        {
                            if (acSol != null)
                            {
                                if (SettingsUser.FlattenAllSides)
                                {
                                    acSol.FlattenAllSides(acCurDb, acCurEd, acTrans);
                                }
                                else
                                {
                                    acSol.Flatten(acTrans, acCurDb, acCurEd, true, false, true, userCoordSystem);
                                    if (SettingsUser.RetainHiddenLines)
                                    {
                                        acSol.Flatten(acTrans, acCurDb, acCurEd, false, true, true, userCoordSystem);
                                    }

                                    acSol.Erase();
                                    acSol.Dispose();
                                }
                            }
                        }
                    }

                    acCurEd.CurrentUserCoordinateSystem = userCoordSystem;
                    acTrans.Commit();
                }
            }
        }
Beispiel #12
0
        public void Cmd_CleanDirectory()
        {
            if (!LicensingAgent.Check())
            {
                return;
            }
            var acCurDoc = Application.DocumentManager.MdiActiveDocument;

            _ = acCurDoc.Database;
            var acCurEd = acCurDoc.Editor;

            var extensions = new HashSet <string>(StringComparer.InvariantCultureIgnoreCase)
            {
                ".bak", ".lck", ".dwl", ".dwl2", ".log"
            };

            //Tell the user we are going to open a dialog window to select a directory
            acCurEd.WriteMessage("\nSelect directory to clean");

            var dirSelected = false;

            // Get the directory to save to
            var fDirectory = string.Empty;

            //While user has not chosen a directory, or until user cancels - show a dialog window for directory selection
            while (dirSelected == false)
            {
                //Create the folder browser
                var fBrowser = new FolderBrowser();
                var result   = fBrowser.ShowDialog(new AcadMainWindow());

                //If the folder browser selection worked:
                if (result != DialogResult.OK)
                {
                    if (result == DialogResult.Cancel)
                    {
                        acCurEd.WriteMessage("\nOperation cancelled by user.");
                        return;
                    }

                    acCurEd.WriteMessage("\nError in selection - Aborting operation.");
                    return;
                }

                fDirectory  = fBrowser.DirectoryPath;
                dirSelected = true;
            }

            var files = new DirectoryInfo(fDirectory).GetFiles("*", SearchOption.AllDirectories);

            var deletableFiles = new List <FileInfo>();

            foreach (var file in files)
            {
                if (extensions.Contains(file.Extension))
                {
                    deletableFiles.Add(file);
                }

                if (file.FullName.Contains(".dwg") && file.FullName.Contains(".idw"))
                {
                    deletableFiles.Add(file);
                }
            }

            using (var pWorker = new ProgressAgent("Cleaning Directory: ", deletableFiles.Count()))
            {
                foreach (var file in deletableFiles)
                {
                    if (!pWorker.Progress())
                    {
                        return;
                    }

                    // try/catch if you really need, but I'd recommend catching a more
                    // specific exception
                    try
                    {
                        file.Attributes = FileAttributes.Normal;
                        File.Delete(file.FullName);
                        acCurEd.WriteMessage($"\nDeleting File: {file.Name}");
                    }
                    catch (Exception)
                    {
                        acCurEd.WriteMessage($"\nFile: {file.Name} could not be deleted!");
                    }
                }
            }
        }
Beispiel #13
0
        public void Cmd_SolDivide()
        {
            var acCurDoc = Application.DocumentManager.MdiActiveDocument;
            var acCurDb  = acCurDoc.Database;
            var acCurEd  = acCurDoc.Editor;

            //Call user to select an Edge
            var userSel = acCurEd.SelectSubentity(SubentityType.Edge, "\nSelect EDGE to use as division path: ");

            if (userSel == null)
            {
                return;
            }
            if (userSel.Item1 == ObjectId.Null)
            {
                return;
            }
            if (userSel.Item2 == SubentityId.Null)
            {
                return;
            }

            var divideAmt = acCurEd.GetPositiveInteger("\nEnter number of times to divide solid: ");

            if (divideAmt <= 1)
            {
                return;
            }

            //Open a transaction
            using (var acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                var acSol    = acTrans.GetObject(userSel.Item1, OpenMode.ForWrite) as Solid3d;
                var subEntId = userSel.Item2;

                //Creates entity path to generate Brep object from it

                var entityPath = new FullSubentityPath(
                    new[] { acSol.ObjectId },
                    new SubentityId(SubentityType.Null, IntPtr.Zero));

                using (var brep = new Brep(entityPath))
                {
                    using (var pworker = new ProgressAgent("Chopping Solid: ", divideAmt))
                    {
                        foreach (var edge in brep.Edges)
                        {
                            if (subEntId == edge.SubentityPath.SubentId)
                            {
                                if (!pworker.Progress())
                                {
                                    acTrans.Abort();
                                    return;
                                }

                                var c = acSol.GetSubentity(subEntId) as Curve;

                                var length = GetLength2(c, edge.Vertex1.Point, edge.Vertex2.Point);

                                var segment  = length / divideAmt;
                                var segments = segment;

                                var chopSol = acSol;

                                while (segments.RoundToTolerance() < length.RoundToTolerance())
                                {
                                    var p1    = c.GetPointAtDist(segments);
                                    var ang   = c.GetFirstDerivative(c.GetParameterAtPoint(p1));
                                    var plane = new Plane(p1, ang);

                                    var obj = chopSol.Slice(plane, true);
                                    obj.SetPropertiesFrom(acSol);
                                    acCurDb.AppendEntity(obj);


                                    segments += segment;
                                }
                            }
                        }
                    }

                    acTrans.Commit();
                }
            }
        }
Beispiel #14
0
        public void Cmd_RCBOM()
        {
            var acCurDoc = Application.DocumentManager.MdiActiveDocument;
            var acCurDb  = acCurDoc.Database;
            var acCurEd  = acCurDoc.Editor;

            //Check for pick-first selection -> if none, get selection
            var acSet = SelectionSet.FromObjectIds(acCurEd.GetFilteredSelection(Enums.DxfNameEnum._3Dsolid, false));

            var multAmount = 1;

            if (SettingsUser.PromptForMultiplication)
            {
                multAmount = acCurEd.GetPositiveInteger("\nEnter number to multiply parts by: ", 1);
            }

            using (var acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                //Get all Layouts in the Drawing
                var layoutList = new List <Layout>();
                var dbDict     = (DBDictionary)acTrans.GetObject(acCurDb.LayoutDictionaryId, OpenMode.ForRead);
                foreach (var curEntry in dbDict)
                {
                    var layout = (Layout)acTrans.GetObject(curEntry.Value, OpenMode.ForRead);
                    if (layout != null)
                    {
                        layoutList.Add(layout);
                    }
                }

                var pKeyOpts = new PromptKeywordOptions(string.Empty)
                {
                    Message             = "\nWhich layout would you like to insert the parts list in?",
                    AllowArbitraryInput = true
                };
                var iterator = 'A';
                var keyDict  = new Dictionary <string, string>();

                foreach (var layout in layoutList)
                {
                    keyDict.Add(layout.LayoutName, iterator.ToString());
                    pKeyOpts.Keywords.Add(iterator.ToString(), iterator.ToString(),
                                          iterator + ": " + layout.LayoutName.ToLower());
                    iterator++;
                }

                pKeyOpts.AllowNone = false;

                var pKeyRes = acCurEd.GetKeywords(pKeyOpts);

                if (pKeyRes.Status != PromptStatus.OK)
                {
                    return;
                }
                var returnIterator = pKeyRes.StringResult;

                ObjectId id;
                var      layoutName = string.Empty;

                foreach (var entry in keyDict)
                {
                    if (entry.Value == returnIterator)
                    {
                        layoutName = entry.Key;
                        break;
                    }
                }

                if (dbDict.Contains(layoutName))
                {
                    id = dbDict.GetAt(layoutName);
                }
                else
                {
                    acCurEd.WriteMessage("\nLayout not found. Cannot continue.");
                    acTrans.Abort();
                    return;
                }

                var chosenLayout = acTrans.GetObject(id, OpenMode.ForRead) as Layout;
                if (chosenLayout == null)
                {
                    return;
                }

                // Reference the Layout Manager
                var acLayoutMgr = LayoutManager.Current;
                // Set the layout current if it is not already
                if (chosenLayout.TabSelected == false)
                {
                    acLayoutMgr.CurrentLayout = chosenLayout.LayoutName;
                }

                if (chosenLayout.LayoutName != "Model")
                {
                    try
                    {
                        acCurEd.SwitchToPaperSpace();
                    }
                    catch (System.Exception e)
                    {
                        Console.WriteLine(e);
                    }
                }


                // Ask for the table insertion point
                var pr = acCurEd.GetPoint("\nEnter table insertion point: ");
                if (pr.Status == PromptStatus.OK)
                {
                    using (var pWorker = new ProgressAgent("Parsing Solids: ", acSet.Count))
                    {
                        var eList = new List <EntInfo>();

                        foreach (var objId in acSet.GetObjectIds())
                        {
                            //Progress progress bar or exit if ESC has been pressed
                            if (!pWorker.Progress())
                            {
                                acTrans.Abort();
                                return;
                            }

                            var acSol = acTrans.GetObject(objId, OpenMode.ForRead) as Solid3d;

                            if (acSol == null)
                            {
                                continue;
                            }

                            eList.Add(new EntInfo(acSol, acCurDb, acTrans));
                        }

                        var acTable = new Table();
                        acTable.Position   = pr.Value;
                        acTable.TableStyle = acCurDb.Tablestyle;

                        eList.SortToTable(pWorker, acCurDb, acCurEd, acTrans, acTable, multAmount);

                        acCurDb.AppendEntity(acTable, acTrans);

                        //Generate the layout
                        acTable.GenerateLayout();
                        acTrans.MoveToAttachment(acTable, SettingsUser.TableAttach, pr.Value, SettingsUser.TableXOffset,
                                                 SettingsUser.TableYOffset);
                    }
                }

                acTrans.Commit();
            }
        }
Beispiel #15
0
        public void Cmd_RcMark()
        {
            if (!LicensingAgent.Check())
            {
                return;
            }
            var acCurDoc = Application.DocumentManager.MdiActiveDocument;
            var acCurDb  = acCurDoc.Database;
            var acCurEd  = acCurDoc.Editor;

            _ = AcVars.CmdEcho;
            AcVars.CmdEcho = Enums.CmdEcho.Off;

            // Set up our selection to only select 3D solids
            var pso = new PromptSelectionOptions {
                MessageForAdding = "\nSelect viewports to shrink: "
            };
            var sf = new SelectionFilter(new[] { new TypedValue((int)DxfCode.Start, "VIEWPORT") });

            //Get the 3d Solid Selection
            var res = acCurEd.GetSelection(pso, sf);

            if (res.Status == PromptStatus.OK)
            {
                // extract the viewport points
                using (var acTrans = acCurDb.TransactionManager.StartTransaction())
                {
                    acCurDb.TransactionManager.QueueForGraphicsFlush();

                    using (
                        var pWorker = new ProgressAgent("Marking Viewports: ", res.Value.Count))
                    {
                        foreach (var objId in res.Value.GetObjectIds())
                        {
                            if (!pWorker.Progress())
                            {
                                acTrans.Abort();
                                return;
                            }

                            var largestPart = ObjectId.Null;
                            var cenView     = new Point2d();
                            var largestExt  = new Extents2d();

                            using (var psVp = acTrans.GetObject(objId, OpenMode.ForRead) as Viewport)
                            {
                                var mObjs = objId.GetModelObjects();

                                if (mObjs.Count <= 0)
                                {
                                    continue;
                                }
                                {
                                    //Finished finding objects, now create tags
                                    var xform = psVp.Ms2Ps();

                                    foreach (ObjectId id in mObjs)
                                    {
                                        var dbObj = acTrans.GetObject(id, OpenMode.ForWrite);
                                        if (dbObj == null)
                                        {
                                            continue;
                                        }

                                        switch (dbObj)
                                        {
                                        case Solid3d acSol:
                                        {
                                            var solCen = acSol.MassProperties.Centroid;
                                            var solExt = acSol.GeometricExtents;

                                            //TODO finish

                                            break;
                                        }

                                        case BlockReference bRef:
                                        {
                                            var ext = acTrans.GetExtents(new ObjectId[] { bRef.ObjectId }, acCurDb);
                                            var cen = ext.MinPoint.GetMidPoint(ext.MaxPoint);


                                            break;
                                        }
                                        }
                                    }
                                }
                            }
                        }

                        acTrans.Commit();
                    }
                }
            }
        }
Beispiel #16
0
        public void Cmd_RcFlip()
        {
            if (!LicensingAgent.Check())
            {
                return;
            }
            var acCurDoc = Application.DocumentManager.MdiActiveDocument;
            var acCurDb  = acCurDoc.Database;
            var acCurEd  = acCurDoc.Editor;

            //Prompt To Select Solids to perform Lay Command On
            var objIds = acCurEd.GetFilteredSelection(Enums.DxfNameEnum._3Dsolid, false, null,
                                                      "\nSelect 3DSOLIDS to flip on an axis: ");

            // Exit if selection error
            if (objIds.Length <= 0)
            {
                return;
            }

            // Prompt User to Select the Axis to flip on
            var flipAxisOpt = new PromptKeywordOptions("\nChoose axis to rotate around: ");

            flipAxisOpt.Keywords.Add("X");
            flipAxisOpt.Keywords.Add("Y");
            flipAxisOpt.Keywords.Add("Z");
            flipAxisOpt.AllowNone = false;

            var flipAxisRes = acCurEd.GetKeywords(flipAxisOpt);

            if (flipAxisRes.Status != PromptStatus.OK)
            {
                return;
            }

            // Prompt User to Select the Axis to flip on
            var flipDegOpt = new PromptKeywordOptions("\nChoose degree to rotate around axis: ");

            flipDegOpt.Keywords.Add("90");
            flipDegOpt.Keywords.Add("180");
            flipDegOpt.Keywords.Add("270");
            flipDegOpt.AllowNone = false;

            var flipDegRes = acCurEd.GetKeywords(flipDegOpt);

            if (flipDegRes.Status != PromptStatus.OK)
            {
                return;
            }

            // Get the selected keyword as a string
            var flipAxisKey = flipAxisRes.StringResult;
            var flipDegKey  = flipDegRes.StringResult;

            var parseCount = 1;

            // Set selection set to user selection
            var solObjIds = objIds;

            using (var acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                using (
                    var pWorker = new ProgressAgent("Flipping Solids:",
                                                    solObjIds.Count()))
                {
                    //Parse Data for each solid in the list
                    foreach (var acSolId in solObjIds)
                    {
                        //Progress progress bar or exit if ESC has been pressed
                        if (!pWorker.Progress())
                        {
                            acTrans.Abort();
                            return;
                        }

                        if (acSolId == ObjectId.Null)
                        {
                            continue;
                        }

                        // Get the Solid Information To Create a Lay Matrix
                        var acSol = acTrans.GetObject(acSolId, OpenMode.ForWrite) as Solid3d;

                        //Populate the solid
                        var eInfo = new EntInfo(acSol, acCurDb, acTrans);
                        parseCount++;

                        //Flip the solid
                        switch (flipAxisKey)
                        {
                        case "X":

                            switch (flipDegKey)
                            {
                            case "90":
                                acSol?.TransformBy(eInfo.X90);
                                break;

                            case "180":
                                acSol?.TransformBy(eInfo.X180);
                                break;

                            case "270":
                                acSol?.TransformBy(eInfo.X270);
                                break;
                            }

                            break;

                        case "Y":
                            switch (flipDegKey)
                            {
                            case "90":
                                acSol?.TransformBy(eInfo.Y90);
                                break;

                            case "180":
                                acSol?.TransformBy(eInfo.Y180);
                                break;

                            case "270":
                                acSol?.TransformBy(eInfo.Y270);
                                break;
                            }

                            break;

                        case "Z":
                            switch (flipDegKey)
                            {
                            case "90":
                                acSol?.TransformBy(eInfo.Z90);
                                break;

                            case "180":
                                acSol?.TransformBy(eInfo.Z180);
                                break;

                            case "270":
                                acSol?.TransformBy(eInfo.Z270);
                                break;
                            }

                            break;
                        }
                    }
                }

                acTrans.Commit();
            }
        }
Beispiel #17
0
        public void Cmd_OutputParts()
        {
            if (!LicensingAgent.Check())
            {
                return;
            }
            // Get the current document
            var acCurDoc = Application.DocumentManager.MdiActiveDocument;

            if (acCurDoc == null)
            {
                return;
            }

            using (acCurDoc.LockDocument())
            {
                //Get the current database and editor
                var acCurDb = acCurDoc.Database;
                var acCurEd = acCurDoc.Editor;

                var objIds = acCurEd.GetFilteredSelection(Enums.DxfNameEnum._3Dsolid, false, null,
                                                          "\nSelect 3D Solids to save out into separate files: ");
                if (objIds.Length <= 0)
                {
                    return;
                }


                //Tell the user we are going to open a dialog window to select a directory
                acCurEd.WriteMessage("\nSelect directory to export parts to");

                var dirSelected = false;

                // Get the directory to save to
                var fDirectory = string.Empty;

                //While user has not chosen a directory, or until user cancels - show a dialog window for directory selection
                while (dirSelected == false)
                {
                    //Create the folder browser
                    var fBrowser = new FolderBrowser();
                    var result   = fBrowser.ShowDialog(new AcadMainWindow());

                    //If the folder browser selection worked:
                    if (result != DialogResult.OK)
                    {
                        if (result == DialogResult.Cancel)
                        {
                            acCurEd.WriteMessage("\nOperation cancelled by user.");
                            return;
                        }

                        acCurEd.WriteMessage("\nError in selection - Aborting operation.");
                        return;
                    }

                    fDirectory  = fBrowser.DirectoryPath;
                    dirSelected = true;
                }

                #region Old File Handling

                if (!new PathFinder().IsDirectoryEmpty(fDirectory))
                {
                    var subPath = "\\_OldVersions" + DateTime.Now.ToString(" MM.dd [HH.mm.ss]");

                    var exists = Directory.Exists(fDirectory + subPath);

                    if (exists)
                    {
                        return;
                    }

                    try
                    {
                        // Ensure the source directory exists
                        if (Directory.Exists(fDirectory))
                        {
                            // Ensure the destination directory doesn't already exist
                            if (Directory.Exists(fDirectory + subPath) == false)
                            {
                                var destDir = fDirectory + subPath;

                                Directory.CreateDirectory(destDir);

                                var files = Directory.EnumerateFiles(fDirectory, "*")
                                            .Select(path => new FileInfo(path));

                                var folders = Directory.EnumerateDirectories(fDirectory, "*")
                                              .Select(path => new DirectoryInfo(path));

                                foreach (var file in files)
                                {
                                    try
                                    {
                                        file.MoveTo(Path.Combine(destDir, file.Name));
                                    }
                                    catch (Exception e)
                                    {
                                        MessageBox.Show("File " + file.Name +
                                                        " is currently in use and cannot be moved.");

                                        Console.WriteLine(e);
                                    }
                                }

                                foreach (var folder in folders)
                                {
                                    try
                                    {
                                        if (!folder.Name.Contains("OldVersions"))
                                        {
                                            folder.MoveTo(Path.Combine(destDir, folder.Name));
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        MessageBox.Show("Folder " + folder.Name +
                                                        " is currently in use and cannot be moved.");
                                        Console.WriteLine(e);
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message);
                        return;
                    }
                }

                #endregion

                acCurEd.WriteMessage("\nDirectory selected: " + fDirectory);
                var eList = new List <EntInfo>();

                var multAmount = 1;

                if (SettingsUser.PromptForMultiplication)
                {
                    multAmount = acCurEd.GetPositiveInteger("\nEnter number to multiply parts by: ", 1);
                }

                using (var pWorker = new ProgressAgent("Parsing Solids: ", objIds.Length))
                {
                    using (var acTrans = acCurDb.TransactionManager.StartTransaction())
                    {
                        foreach (var objId in objIds)
                        {
                            //Progress progress bar or exit if ESC has been pressed
                            if (!pWorker.Progress())
                            {
                                acTrans.Abort();
                                return;
                            }

                            var acSol = acTrans.GetObject(objId, OpenMode.ForRead) as Solid3d;

                            if (acSol == null)
                            {
                                continue;
                            }

                            eList.Add(new EntInfo(acSol, acCurDb, acTrans));
                        }

                        eList.SortAndExport(fDirectory, pWorker, acCurDb, acCurEd, acTrans, multAmount);

                        acTrans.Commit();
                    }
                }
            }
        }
Beispiel #18
0
        public void Cmd_VpToVb()
        {
            if (!LicensingAgent.Check())
            {
                return;
            }
            var acCurDoc = Application.DocumentManager.MdiActiveDocument;
            var acCurDb  = acCurDoc.Database;
            var acCurEd  = acCurDoc.Editor;

            var userCmdEcho = AcVars.CmdEcho;

            AcVars.CmdEcho = Enums.CmdEcho.Off;

            // Set up our selection to only select 3D solids
            var pso = new PromptSelectionOptions {
                MessageForAdding = "\nSelect viewports to convert: "
            };
            var sf = new SelectionFilter(new[] { new TypedValue((int)DxfCode.Start, "VIEWPORT") });

            //Get the 3d Solid Selection
            var res = acCurEd.GetSelection(pso, sf);

            if (res.Status == PromptStatus.OK)
            {
                // extract the viewport points
                using (var acTrans = acCurDb.TransactionManager.StartTransaction())
                {
                    acCurDb.TransactionManager.QueueForGraphicsFlush();

                    using (
                        var pWorker = new ProgressAgent("Converting Viewports: ", res.Value.Count))
                    {
                        var deleteVps = false;

                        foreach (var objId in res.Value.GetObjectIds())
                        {
                            if (!pWorker.Progress())
                            {
                                acTrans.Abort();
                                return;
                            }

                            var psVpPnts = new Point3dCollection();

                            using (var psVp = acTrans.GetObject(objId, OpenMode.ForWrite) as Viewport)
                            {
                                // get the vp number
                                if (psVp != null)
                                {
                                    // now extract the viewport geometry
                                    psVp.GetGripPoints(psVpPnts, new IntegerCollection(), new IntegerCollection());

                                    // let's assume a rectangular vport for now, make the cross-direction grips square
                                    var tmp = psVpPnts[2];
                                    psVpPnts[2] = psVpPnts[1];
                                    psVpPnts[1] = tmp;

                                    var msVpPnts = new Point3dCollection();
                                    foreach (Point3d pnt in psVpPnts)
                                    {
                                        var xform = psVp.Dcs2Wcs() * psVp.Psdcs2Dcs();
                                        // add the resulting point to the ms pnt array
                                        msVpPnts.Add(pnt.TransformBy(xform));
                                    }

                                    var layoutName = LayoutManager.Current.CurrentLayout;

                                    LayoutManager.Current.CurrentLayout = "Model";

                                    var extents = acCurDb.TileMode
                                        ? new Extents3d(acCurDb.Extmin, acCurDb.Extmax)
                                        : (int)Application.GetSystemVariable("CVPORT") == 1
                                            ? new Extents3d(acCurDb.Pextmin, acCurDb.Pextmax)
                                            : new Extents3d(acCurDb.Extmin, acCurDb.Extmax);

                                    using (var view = acCurEd.GetCurrentView())
                                    {
                                        var viewTransform =
                                            Matrix3d.PlaneToWorld(psVp.ViewDirection)
                                            .PreMultiplyBy(Matrix3d.Displacement(view.Target - Point3d.Origin))
                                            .PreMultiplyBy(Matrix3d.Rotation(-view.ViewTwist, view.ViewDirection,
                                                                             view.Target))
                                            .Inverse();

                                        extents.TransformBy(viewTransform);

                                        view.ViewDirection = psVp.ViewDirection;
                                        view.Width         = (extents.MaxPoint.X - extents.MinPoint.X) * 1.2;
                                        view.Height        = (extents.MaxPoint.Y - extents.MinPoint.Y) * 1.2;
                                        view.CenterPoint   = new Point2d(
                                            (extents.MinPoint.X + extents.MaxPoint.X) / 2.0,
                                            (extents.MinPoint.Y + extents.MaxPoint.Y) / 2.0);
                                        acCurEd.SetCurrentView(view);
                                    }

                                    // once switched, we can use the normal selection mode to select
                                    var selectionresult = acCurEd.SelectCrossingPolygon(msVpPnts);

                                    if (selectionresult.Status != PromptStatus.OK)
                                    {
                                        return;
                                    }

                                    var layout =
                                        (Layout)
                                        acTrans.GetObject(LayoutManager.Current.GetLayoutId(layoutName),
                                                          OpenMode.ForRead);

                                    LayoutManager.Current.CurrentLayout = layoutName;

                                    try
                                    {
                                        var ext   = acTrans.GetExtents(selectionresult.Value.GetObjectIds());
                                        var cenPt = Solid3DExtensions.GetBoxCenter(ext.MinPoint, ext.MaxPoint);
                                        var insPt = cenPt.TransformBy(psVp.Ms2Ps());

                                        CreateBaseViewFromVp(selectionresult, psVp, acCurEd, acCurDb, layout, insPt);

                                        deleteVps = true;
                                    }
                                    catch (Exception e)
                                    {
                                        deleteVps = false;
                                        acCurEd.WriteMessage(e.Message);
                                        MailAgent.Report(e.Message);
                                    }
                                }
                            }
                        }

                        if (deleteVps)
                        {
                            foreach (var objId in res.Value.GetObjectIds())
                            {
                                var vp = acTrans.GetObject(objId, OpenMode.ForWrite);
                                vp.Erase();
                                vp.Dispose();
                            }
                        }

                        acTrans.Commit();
                    }
                }
            }

            AcVars.CmdEcho = userCmdEcho;
        }