Ejemplo n.º 1
0
 public static Vector3 Transform(Vector3 vector, Matrix3d matrix)
 {
     Matrix4d mat = Matrix4d.Identity;
     for (int i = 0; i < 2; i++)
     {
         for (int j = 0; j < 2; j++)
         {
             mat[i, j] = matrix[i, j];
         }
     }
     return (Vector3)Vector3d.Transform(new Vector3d(vector.X, vector.Y, vector.Z), mat);
 }
Ejemplo n.º 2
0
 /// <summary>
 /// Gets the transformation matrix from the current viewport Display Coordinate System (DCS)
 /// to the World Coordinate System (WCS).
 /// </summary>
 /// <param name="ed">The instance to which this method applies.</param>
 /// <returns>The DCS to WCS transformation matrix.</returns>
 public static Matrix3d DCS2WCS(this Editor ed)
 {
     Matrix3d retVal = new Matrix3d();
     bool tilemode = ed.Document.Database.TileMode;
     if (!tilemode)
         ed.SwitchToModelSpace();
     using (ViewTableRecord vtr = ed.GetCurrentView())
     {
         retVal =
             Matrix3d.Rotation(-vtr.ViewTwist, vtr.ViewDirection, vtr.Target) *
             Matrix3d.Displacement(vtr.Target - Point3d.Origin) *
             Matrix3d.PlaneToWorld(vtr.ViewDirection);
     }
     if (!tilemode)
         ed.SwitchToPaperSpace();
     return retVal;
 }
Ejemplo n.º 3
0
        public static void DrawSolidDescription(ObjectIdCollection OuterContours, Point3d origin, Point3d Xaxe, Point3d Yaxe, PromptPointResult target, bool bds)
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;  

            Vector3d vX, vY, vZ;
            ObjectId ID = OuterContours[OuterContours.Count - 1];
            Point3d centroid = new Point3d();
            string layer;
            ObjectId[] solids = { ID, ID, ID, ID, ID, ID, ID };
            using (Transaction acTrans = db.TransactionManager.StartTransaction())
            {
                BlockTable acBlkTbl = acTrans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                BlockTableRecord modelSpace = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                Entity ent = acTrans.GetObject(ID, OpenMode.ForRead) as Entity;

                #region check selection
                String[] str = ent.GetType().ToString().Split('.');
                if (str[str.Length - 1] != "Solid3d")//check for solid
                {
                    MessageBox.Show("No selected Solid !");
                    return;
                }

                Quaternion q1 = new Quaternion(Xaxe.X - origin.X, Xaxe.Y - origin.Y, Xaxe.Z - origin.Z, 0);
                Quaternion q2 = new Quaternion(Yaxe.X - origin.X, Yaxe.Y - origin.Y, Yaxe.Z - origin.Z, 0);

                if (q1.abs() < 10E-11)
                {
                    MessageBox.Show("origin = Xaxe !");
                    return;
                }

                if (q2.abs() < 10E-11)
                {
                    MessageBox.Show("origin = Xaxe !");
                    return;
                }


                q1 /= q1.abs();
                q2 /= q2.abs();

                Quaternion q = q2 / q1;
                q = new Quaternion(0, q.GetX(), q.GetY(), q.GetZ());
                if (q.norm() < 10E-14)
                {
                    MessageBox.Show("three points in one line !");
                    return;
                }
                #endregion

                Solid3d solid = acTrans.GetObject(ID, OpenMode.ForWrite) as Solid3d;
                layer = solid.Layer;
                solids[0] = solid.ObjectId;

                centroid = solid.MassProperties.Centroid;

                UCS UCS = new UCS(new Quaternion(0, origin.X, origin.Y, origin.Z), new Quaternion(0, Xaxe.X, Xaxe.Y, Xaxe.Z), new Quaternion(0, Yaxe.X, Yaxe.Y, Yaxe.Z));
                Quaternion ucsX = UCS.ToACS(new Quaternion(0, 1, 0, 0));
                Quaternion ucsY = UCS.ToACS(new Quaternion(0, 0, 1, 0));
                Quaternion ucsZ = UCS.ToACS(new Quaternion(0, 0, 0, 1));
                vX = origin.GetVectorTo(new Point3d(ucsX.GetX(), ucsX.GetY(), ucsX.GetZ()));
                vY = origin.GetVectorTo(new Point3d(ucsY.GetX(), ucsY.GetY(), ucsY.GetZ()));
                vZ = origin.GetVectorTo(new Point3d(ucsZ.GetX(), ucsZ.GetY(), ucsZ.GetZ()));

                _centroid = centroid;
                vO[0] = vX; vO[1] = vY; vO[2] = vZ;
                _target = target.Value;

                Matrix3d newMatrix = new Matrix3d();
                newMatrix = Matrix3d.AlignCoordinateSystem(centroid, vX, vY, vZ, centroid, Vector3d.XAxis, Vector3d.YAxis, Vector3d.ZAxis);
                solid.TransformBy(newMatrix);


                Point3d MIN = new Point3d(solid.GeometricExtents.MinPoint.X - centroid.X, solid.GeometricExtents.MinPoint.Y - centroid.Y, solid.GeometricExtents.MinPoint.Z - centroid.Z);
                Point3d MAX = new Point3d(solid.GeometricExtents.MaxPoint.X - centroid.X, solid.GeometricExtents.MaxPoint.Y - centroid.Y, solid.GeometricExtents.MaxPoint.Z - centroid.Z);

                double MaxX = (Math.Abs(MIN.X) > Math.Abs(MAX.X)) ? Math.Abs(MIN.X) : Math.Abs(MAX.X);
                double MaxY = (Math.Abs(MIN.Y) > Math.Abs(MAX.Y)) ? Math.Abs(MIN.Y) : Math.Abs(MAX.Y);
                double MaxZ = (Math.Abs(MIN.Z) > Math.Abs(MAX.Z)) ? Math.Abs(MIN.Z) : Math.Abs(MAX.Z);


                Solid3d[] solidARR = { solid.Clone() as Solid3d, solid.Clone() as Solid3d, solid.Clone() as Solid3d, solid.Clone() as Solid3d, solid.Clone() as Solid3d };

                for (int i = 0; i < 5; i++)
                {
                    modelSpace.AppendEntity(solidARR[i]);
                    acTrans.AddNewlyCreatedDBObject(solidARR[i], true);
                }

                Vector3d vRot1 = centroid.GetVectorTo(new Point3d(centroid.X, centroid.Y + 2.5 * Math.Abs(MAX.X), centroid.Z));
                Vector3d vRot2 = centroid.GetVectorTo(new Point3d(centroid.X + 2.5 * Math.Abs(MAX.X), centroid.Y, centroid.Z));
                Vector3d vRot3 = centroid.GetVectorTo(new Point3d(centroid.X, centroid.Y, centroid.Z + 2.5 * Math.Abs(MAX.Z)));


                if (bds)
                {
                    solidARR[0].TransformBy(Matrix3d.Rotation(-Math.PI / 2.0, vRot1, centroid));
                    solidARR[0].TransformBy(Matrix3d.Displacement(centroid.GetVectorTo(new Point3d(centroid.X - MaxZ - 1.5 * MaxX, centroid.Y, centroid.Z))));
                    solids[1] = solidARR[0].ObjectId;
                    solidARR[1].TransformBy(Matrix3d.Rotation(Math.PI / 2.0, vRot1, centroid));
                    solidARR[1].TransformBy(Matrix3d.Displacement(centroid.GetVectorTo(new Point3d(centroid.X + MaxZ + 1.5 * MaxX, centroid.Y, centroid.Z))));
                    solids[2] = solidARR[1].ObjectId;
                    solidARR[2].TransformBy(Matrix3d.Rotation(Math.PI, vRot1, centroid));
                    solidARR[2].TransformBy(Matrix3d.Displacement(centroid.GetVectorTo(new Point3d(centroid.X + 3 * MaxZ + 2.5 * MaxX, centroid.Y, centroid.Z))));
                    solids[3] = solidARR[2].ObjectId;
                    solidARR[3].TransformBy(Matrix3d.Rotation(Math.PI / 2, vRot2, centroid));
                    solidARR[3].TransformBy(Matrix3d.Displacement(centroid.GetVectorTo(new Point3d(centroid.X, centroid.Y - MaxZ - 1.5 * MaxY, centroid.Z))));
                    solids[4] = solidARR[3].ObjectId;
                    solidARR[4].TransformBy(Matrix3d.Rotation(-Math.PI / 2, vRot2, centroid));
                    solidARR[4].TransformBy(Matrix3d.Displacement(centroid.GetVectorTo(new Point3d(centroid.X, centroid.Y + MaxZ + 1.5 * MaxY, centroid.Z))));
                    solids[5] = solidARR[4].ObjectId;
                }
                else
                {
                    solidARR[0].TransformBy(Matrix3d.Rotation(-Math.PI / 2.0, vRot1, centroid));
                    solidARR[0].TransformBy(Matrix3d.Displacement(centroid.GetVectorTo(new Point3d(centroid.X + MaxZ + 1.5 * MaxX, centroid.Y, centroid.Z))));
                    solids[1] = solidARR[0].ObjectId;

                    solidARR[1].TransformBy(Matrix3d.Rotation(Math.PI / 2.0, vRot1, centroid));
                    solidARR[1].TransformBy(Matrix3d.Displacement(centroid.GetVectorTo(new Point3d(centroid.X - MaxZ - 1.5 * MaxX, centroid.Y, centroid.Z))));
                    solids[2] = solidARR[1].ObjectId;

                    solidARR[2].TransformBy(Matrix3d.Rotation(Math.PI, vRot1, centroid));
                    solidARR[2].TransformBy(Matrix3d.Displacement(centroid.GetVectorTo(new Point3d(centroid.X + 3 * MaxZ + 2.5 * MaxX, centroid.Y, centroid.Z))));
                    solids[3] = solidARR[2].ObjectId;
                    solidARR[3].TransformBy(Matrix3d.Rotation(Math.PI / 2, vRot2, centroid));
                    solidARR[3].TransformBy(Matrix3d.Displacement(centroid.GetVectorTo(new Point3d(centroid.X, centroid.Y + MaxZ + 1.5 * MaxY, centroid.Z))));
                    solids[4] = solidARR[3].ObjectId;
                    solidARR[4].TransformBy(Matrix3d.Rotation(-Math.PI / 2, vRot2, centroid));
                    solidARR[4].TransformBy(Matrix3d.Displacement(centroid.GetVectorTo(new Point3d(centroid.X, centroid.Y - MaxZ - 1.5 * MaxY, centroid.Z))));
                    solids[5] = solidARR[4].ObjectId;
                }

                Solid3d solid1 = solid.Clone() as Solid3d;
                modelSpace.AppendEntity(solid1);
                acTrans.AddNewlyCreatedDBObject(solid1, true);

                solids[6] = solid1.ObjectId;

                solid1.TransformBy(Matrix3d.Rotation(Math.PI / 4, vRot3, centroid));
                solid1.TransformBy(Matrix3d.Rotation(-Math.PI / 3.28854, vRot2, centroid));

                double dX = Math.Abs(solid1.GeometricExtents.MinPoint.X - centroid.X) + Math.Abs(solid.GeometricExtents.MaxPoint.X - centroid.X);
                double dY = Math.Abs(solid1.GeometricExtents.MinPoint.Y - centroid.Y) + Math.Abs(solid.GeometricExtents.MaxPoint.Y - centroid.Y);
                solid1.TransformBy(Matrix3d.Displacement(centroid.GetVectorTo(new Point3d(centroid.X + dX + 1.5 * MaxX, centroid.Y + dY + 1.5 * MaxY, 0))));

                acTrans.Commit();
            }

            for (int i = 0; i < 7; i++)
            {
                solids_buff[i] = solids[i];
            }


            doc.SendStringToExecute("-view\rO\rT\r", false, false, false);
            doc.SendStringToExecute("TILEMODE\r0\r", false, false, false);
            // Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("TILEMODE", 0);
            // Doc.Editor.SwitchToPaperSpace();
            doc.SendStringToExecute("MSPACE\r", false, false, false);
            doc.SendStringToExecute("SOLPROF\rall\r\rY\rY\rY\r", false, false, false);
            doc.SendStringToExecute("PSPACE\r", false, false, false);
            doc.SendStringToExecute("TILEMODE\r1\r", false, false, false);
            //Doc.SendStringToExecute("ZOOM\rE\r" , false , false , false);
            doc.SendStringToExecute("hideflat\r", false, false, false);

            if (target.Status == PromptStatus.OK)
            {
                string bs = centroid.X.ToString() + "," + centroid.Y.ToString();
                string ts = target.Value.X.ToString() + "," + target.Value.Y.ToString();

                doc.SendStringToExecute("move\rlast\r\r" + bs + "\r" + ts + "\r", false, false, false);
                doc.SendStringToExecute("ZOOM\rE\r", false, false, false);

            }

            doc.SendStringToExecute("eraseflat\r", false, false, false);
            doc.SendStringToExecute("finalflat\r", false, false, false);
            doc.SendStringToExecute("ZOOM\rE\r", false, false, false);
        }
Ejemplo n.º 4
0
 public void TransformBy(Matrix3d transform)
 {
     createInstance();
     BaseEntity.TransformBy(transform);
     tr.Dispose();
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Рекурсивное получение габаритного контейнера для выбранного примитива.
        /// </summary>
        /// <param name="en">Имя примитива</param>
        /// <param name="ext">Габаритный контейнер</param>
        /// <param name="mat">Матрица преобразования из системы координат блока в МСК.</param>
        private static Extents3d GetBlockExtents(Entity en, ref Matrix3d mat, Extents3d ext)
        {
            if (en is BlockReference)
            {
                var bref = en as BlockReference;
                Matrix3d matIns = mat * bref.BlockTransform;
                using (var btr = bref.BlockTableRecord.Open(OpenMode.ForRead) as BlockTableRecord)
                {
                    foreach (ObjectId id in btr)
                    {
                        // Пропускаем все тексты.
                        if (id.ObjectClass.IsDerivedFrom(DbTextRXClass) ||
                           id.ObjectClass.IsDerivedFrom(MTextRXClass) ||
                           id.ObjectClass.IsDerivedFrom(MLeaderRXClass) ||
                           id.ObjectClass.IsDerivedFrom(DimensionRXClass))
                        {
                            continue;
                        }
                        using (DBObject obj = id.Open(OpenMode.ForRead) as DBObject)
                        {
                            Entity enCur = obj as Entity;
                            if (enCur == null || enCur.Visible != true)
                                continue;
                            if (IsEmptyExt(ref ext))
                            {
                                ext.AddExtents(GetBlockExtents(enCur, ref matIns, ext));
                            }
                            else
                            {
                                ext = GetBlockExtents(enCur, ref matIns, ext);
                            }
                        }
                    }
                }
            }
            else
            {
                if (mat.IsUniscaledOrtho())
                {
                    using (Entity enTr = en.GetTransformedCopy(mat))
                    {
                        if (enTr is Dimension)
                            (enTr as Dimension).RecomputeDimensionBlock(true);
                        if (enTr is Table)
                            (enTr as Table).RecomputeTableBlock(true);

                        if (IsEmptyExt(ref ext))
                        {
                            try { ext = enTr.GeometricExtents; } catch { };
                        }
                        else
                        {
                            try { ext.AddExtents(enTr.GeometricExtents); } catch { };
                        }
                        return ext;
                    }
                }
                else
                {
                    try
                    {
                        Extents3d curExt = en.GeometricExtents;
                        curExt.TransformBy(mat);
                        if (IsEmptyExt(ref ext))
                            ext = curExt;
                        else
                            ext.AddExtents(curExt);
                    }
                    catch { }
                    return ext;
                }
            }
            return ext;
        }
Ejemplo n.º 6
0
        private void sizesCheek(bool doTrans, Matrix3d trans)
        {
            double xMinCheek = panelBase.PtsForBotDimCheek.First();
             Point3d ptDimLineCheek = new Point3d(xMinCheek, -165, 0);
             Point3d ptFirstCheek = new Point3d(xMinCheek, 0, 0);
             Point3d ptLastCheek = new Point3d(panelBase.PtsForBotDimCheek.Last(), 0, 0);

             if (panelBase.IsCheekLeft)
             {
            addCheekViewText(doTrans, trans, xMinCheek);
            addCheekViewBlock(doTrans, trans, xMinCheek+650, true);
             }
             if (panelBase.IsCheekRight)
             {
            addCheekViewText(doTrans, trans, xMinCheek);
            addCheekViewBlock(doTrans, trans, xMinCheek - 365, false);
             }

             Point3d ptPrevCheek = ptFirstCheek;
             foreach (var ptX in panelBase.PtsForBotDimCheek.Skip(1))
             {
            Point3d ptNextCheek = new Point3d(ptX, 0, 0);
            var dimCheek = CreateDim(ptPrevCheek, ptNextCheek, ptDimLineCheek, doTrans, trans);
            // Если размер маленький, то перемещение текста размера
            if (dimCheek.Measurement < 90)
            {
               double deltaX = panelBase.IsCheekLeft ? 70 : -70;
               Point3d ptText = new Point3d(ptPrevCheek.X + deltaX, ptDimLineCheek.Y - 100, 0);
               dimCheek.TextPosition = doTrans? ptText.TransformBy(trans) : ptText;
            }
            ptPrevCheek = ptNextCheek;
             }
             // Общий размер торца
             CreateDim(ptFirstCheek, ptLastCheek, new Point3d(0, ptDimLineCheek.Y - 150, 0), doTrans, trans);
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Transforms a point from a coordinate system to another one in the specified editor.
 /// </summary>
 /// <param name="pt">The instance to which the method applies.</param>
 /// <param name="ed">An instance of the Editor to which the method applies.</param>
 /// <param name="from">The origin coordinate system.</param>
 /// <param name="to">The target coordinate system.</param>
 /// <returns>The corresponding 3d point.</returns>
 /// <exception cref="Autodesk.AutoCAD.Runtime.Exception">
 /// eInvalidInput is thrown if CoordSystem.PSDCS is used with other than CoordSystem.DCS.</exception>
 public static Point3d Trans(this Point3d pt, Editor ed, CoordSystem from, CoordSystem to)
 {
     Matrix3d mat = new Matrix3d();
     switch (from)
     {
         case CoordSystem.WCS:
             switch (to)
             {
                 case CoordSystem.UCS:
                     mat = ed.WCS2UCS();
                     break;
                 case CoordSystem.DCS:
                     mat = ed.WCS2DCS();
                     break;
                 case CoordSystem.PSDCS:
                     throw new AcRx.Exception(
                         AcRx.ErrorStatus.InvalidInput,
                         "To be used only with DCS");
                 default:
                     mat = Matrix3d.Identity;
                     break;
             }
             break;
         case CoordSystem.UCS:
             switch (to)
             {
                 case CoordSystem.WCS:
                     mat = ed.UCS2WCS();
                     break;
                 case CoordSystem.DCS:
                     mat = ed.UCS2WCS() * ed.WCS2DCS();
                     break;
                 case CoordSystem.PSDCS:
                     throw new AcRx.Exception(
                         AcRx.ErrorStatus.InvalidInput,
                         "To be used only with DCS");
                 default:
                     mat = Matrix3d.Identity;
                     break;
             }
             break;
         case CoordSystem.DCS:
             switch (to)
             {
                 case CoordSystem.WCS:
                     mat = ed.DCS2WCS();
                     break;
                 case CoordSystem.UCS:
                     mat = ed.DCS2WCS() * ed.WCS2UCS();
                     break;
                 case CoordSystem.PSDCS:
                     mat = ed.DCS2PSDCS();
                     break;
                 default:
                     mat = Matrix3d.Identity;
                     break;
             }
             break;
         case CoordSystem.PSDCS:
             switch (to)
             {
                 case CoordSystem.WCS:
                     throw new AcRx.Exception(
                         AcRx.ErrorStatus.InvalidInput,
                         "To be used only with DCS");
                 case CoordSystem.UCS:
                     throw new AcRx.Exception(
                         AcRx.ErrorStatus.InvalidInput,
                         "To be used only with DCS");
                 case CoordSystem.DCS:
                     mat = ed.PSDCS2DCS();
                     break;
                 default:
                     mat = Matrix3d.Identity;
                     break;
             }
             break;
     }
     return pt.TransformBy(mat);
 }
Ejemplo n.º 8
0
        protected RotatedDimension CreateDim(Point3d ptPrev, Point3d ptNext, Point3d ptDimLine, 
                    bool doTrans, Matrix3d trans, int rangeSize = 0, double rotation = 0, bool interlineText = false)
        {
            if (doTrans)
             {
            ptPrev = ptPrev.TransformBy(trans);
            ptNext = ptNext.TransformBy(trans);
            ptDimLine = ptDimLine.TransformBy(trans);
             }

             var dim = new RotatedDimension(rotation.ToRadians(), ptPrev, ptNext, ptDimLine, "", panelBase.Service.Env.IdDimStyle);
             if (rangeSize>0)
             {
            dim.Suffix = getTextRange(dim.Measurement, rangeSize);
             }
             if (interlineText)
             {
            dim.Dimtmove = 0;
            dim.Dimtix = true;
             }
             dim.Dimscale = Settings.Default.SheetScale;
             btrDim.AppendEntity(dim);
             t.AddNewlyCreatedDBObject(dim, true);
             return dim;
        }
Ejemplo n.º 9
0
        protected void SizesRight(bool doTrans, Matrix3d trans)
        {
            double yWinMax=0;
             double yWinMin=0;
             var win = panelBase.Panel.windows?.window?.First();
             if (win == null)
             {
            var balc = panelBase.Panel.balconys?.balcony?.First();
            if (balc!=null)
            {
               yWinMax = balc.posi.Y + balc.height;
               yWinMin = balc.posi.Y;
            }
             }
             else
             {
            yWinMax = win.posi.Y + win.height;
            yWinMin = win.posi.Y;
             }

             var heightTile = Settings.Default.TileHeight + Settings.Default.TileSeam;
             // y последней плитки
             var countTile = Convert.ToInt32(panelBase.Height / heightTile);
             var yLastTile = (countTile * heightTile)-12;

             Point3d ptBotRight = new Point3d(panelBase.XMaxPanel, 0, 0);
             Point3d ptTopRight = new Point3d(ptBotRight.X, yLastTile, 0);

             bool hasIndentDim = yWinMax > 0;
             xDimLineRightMax = hasIndentDim ? ptBotRight.X+indentDimLineFromDraw+indentBetweenDimLine : ptBotRight.X + indentDimLineFromDraw;

             // Общий размер
             Point3d ptDimLineTotal = new Point3d(xDimLineRightMax, 0, 0);
             CreateDim(ptBotRight, ptTopRight, ptDimLineTotal, doTrans, trans, rangeSize: rangeSizeVertic, rotation: 90);
             // Промежуточные размеры
             if (hasIndentDim)
             {
            Point3d ptDimLineIndent = new Point3d(xDimLineRightMax - indentBetweenDimLine, 0, 0);
            Point3d ptMinWin= ptBotRight;
            if (yWinMin>0)
            {
               var countTileMinWin = Convert.ToInt32(yWinMin / heightTile);
               var yTilesMinWin = (countTileMinWin * heightTile) - 12;
               ptMinWin = new Point3d(ptBotRight.X, yTilesMinWin, 0);
               CreateDim(ptBotRight, ptMinWin, ptDimLineIndent, doTrans, trans, rangeSize: rangeSizeVertic, rotation: 90, interlineText:true);
               var ptMinWinSeam = new Point3d(ptMinWin.X, ptMinWin.Y+12, 0);
               var dimSeamMin= CreateDim(ptMinWin, ptMinWinSeam, ptDimLineIndent, doTrans, trans, rotation: 90);
               Point3d ptTextSeamMin = new Point3d(ptDimLineIndent.X, ptMinWinSeam.Y+65,0);
               dimSeamMin.TextPosition = doTrans? ptTextSeamMin.TransformBy(trans): ptTextSeamMin;
               ptMinWin = ptMinWinSeam;
            }
            var countTileMaxWin = Convert.ToInt32(yWinMax / heightTile);
            var yTilesMaxWin = (countTileMaxWin * heightTile) - 12;
            Point3d ptMaxWin = new Point3d(ptMinWin.X, yTilesMaxWin, 0);
            CreateDim(ptMinWin, ptMaxWin, ptDimLineIndent, doTrans, trans, rangeSize: rangeSizeVertic, rotation: 90, interlineText: true);
            Point3d ptMaxWinSeam = new Point3d(ptMaxWin.X, ptMaxWin.Y+12, 0);
            var dimSeamMax = CreateDim(ptMaxWin, ptMaxWinSeam, ptDimLineIndent, doTrans, trans, rotation: 90);
            Point3d ptTextSeamMax = new Point3d(ptDimLineIndent.X, ptMaxWin.Y - 65, 0);
            dimSeamMax.TextPosition = doTrans ? ptTextSeamMax.TransformBy(trans) : ptTextSeamMax;
            // размер до верха плиток
            CreateDim(ptMaxWinSeam, ptTopRight, ptDimLineIndent, doTrans, trans, rangeSize: rangeSizeVertic, rotation: 90, interlineText: true);
             }
        }
Ejemplo n.º 10
0
        public void SetupMatricesSolarSystem(bool forStars)
        {
            Lighting = Settings.Active.SolarSystemLighting;

            Space = false;
            if (SolarSystemTrack != SolarSystemObjects.Custom && SolarSystemTrack != SolarSystemObjects.Undefined)
            {
                ViewCamera.ViewTarget = Planets.GetPlanetTargetPoint(SolarSystemTrack, ViewCamera.Lat, ViewCamera.Lng, 0);
            }
            RenderTriangle.CullInside = false;


            double cameraDistance = SolarSystemCameraDistance;

            Matrix3d trackingMatrix = Matrix3d.Identity;

            cameraDistance -= 0.000001;

            bool activeTrackingFrame = false;

            if (SolarSystemTrack == SolarSystemObjects.Custom && !string.IsNullOrEmpty(TrackingFrame))
            {
                activeTrackingFrame = true;
                FrameTarget target = LayerManager.GetFrameTarget(this, TrackingFrame);
                ViewCamera.ViewTarget = target.Target;
                trackingMatrix        = target.Matrix;
            }
            else if (!string.IsNullOrEmpty(TrackingFrame))
            {
                TrackingFrame = "";
            }


            Vector3d center = ViewCamera.ViewTarget;
            //Vector3d lightPosition = -center;

            double   localZoom = ViewCamera.Zoom * 20;
            Vector3d lookAt    = new Vector3d();

            Matrix3d viewAdjust = Matrix3d.Identity;

            viewAdjust.Multiply(Matrix3d.RotationX(((-ViewCamera.Lat) / 180f * Math.PI)));
            viewAdjust.Multiply(Matrix3d.RotationY(((-ViewCamera.Lng) / 180f * Math.PI)));

            Matrix3d lookAtAdjust = Matrix3d.Identity;


            bool dome = false;

            Vector3d lookUp;


            if (useSolarSystemTilt && !SandboxMode)
            {
                double angle = ViewCamera.Angle;
                if (cameraDistance > 0.0008)
                {
                    angle = 0;
                }
                else if (cameraDistance > 0.00001)
                {
                    double val = Math.Min(1.903089987, Util.Log10(cameraDistance) + 5) / 1.903089987;

                    angle = angle * Math.Max(0, 1 - val);
                }



                CameraPosition = Vector3d.Create(
                    (Math.Sin(-ViewCamera.Rotation) * Math.Sin(angle) * cameraDistance),
                    (Math.Cos(-ViewCamera.Rotation) * Math.Sin(angle) * cameraDistance),
                    ((Math.Cos(angle) * cameraDistance)));
                lookUp = Vector3d.Create(Math.Sin(-ViewCamera.Rotation), Math.Cos(-ViewCamera.Rotation), 0.00001f);
            }
            else
            {
                CameraPosition = Vector3d.Create(0, 0, ((cameraDistance)));

                lookUp = Vector3d.Create(Math.Sin(-ViewCamera.Rotation), Math.Cos(-ViewCamera.Rotation), 0.0001f);
            }


            CameraPosition = viewAdjust.Transform(CameraPosition);

            cameraOffset = CameraPosition.Copy();

            Matrix3d tmp = trackingMatrix.Clone();

            tmp.Invert();
            cameraOffset = Vector3d.TransformCoordinate(cameraOffset, tmp);



            lookUp = viewAdjust.Transform(lookUp);


            World                = Matrix3d.Identity;
            WorldBase            = Matrix3d.Identity;
            WorldBaseNonRotating = Matrix3d.Identity;

            View = Matrix3d.MultiplyMatrix(Matrix3d.MultiplyMatrix(trackingMatrix, Matrix3d.LookAtLH(CameraPosition, lookAt, lookUp)), lookAtAdjust);


            ViewBase = View.Clone();


            Vector3d temp = Vector3d.SubtractVectors(lookAt, CameraPosition);

            temp.Normalize();
            temp = Vector3d.TransformCoordinate(temp, trackingMatrix);
            temp.Normalize();
            viewPoint = temp;



            //if (activeTrackingFrame)
            //{
            //    Vector3d atfCamPos = RenderContext11.CameraPosition;
            //    Vector3d atfLookAt = lookAt;
            //    Vector3d atfLookUp = lookUp;
            //    Matrix3d mat = trackingMatrix;
            //    mat.Invert();

            //    atfCamPos.TransformCoordinate(mat);
            //    atfLookAt.TransformCoordinate(mat);
            //    atfLookUp.TransformCoordinate(mat);
            //    atfLookAt.Normalize();
            //    atfLookUp.Normalize();

            //    CustomTrackingParams.Angle = 0;
            //    CustomTrackingParams.Rotation = 0;
            //    CustomTrackingParams.DomeAlt = viewCamera.DomeAlt;
            //    CustomTrackingParams.DomeAz = viewCamera.DomeAz;
            //    CustomTrackingParams.TargetReferenceFrame = "";
            //    CustomTrackingParams.ViewTarget = viewCamera.ViewTarget;
            //    CustomTrackingParams.Zoom = viewCamera.Zoom;
            //    CustomTrackingParams.Target = SolarSystemObjects.Custom;


            //    Vector3d atfLook = atfCamPos - atfLookAt;
            //    atfLook.Normalize();



            //    Coordinates latlng = Coordinates.CartesianToSpherical2(atfLook);
            //    CustomTrackingParams.Lat = latlng.Lat;
            //    CustomTrackingParams.Lng = latlng.Lng - 90;

            //    Vector3d up = Coordinates.GeoTo3dDouble(latlng.Lat + 90, latlng.Lng - 90);
            //    Vector3d left = Vector3d.Cross(atfLook, up);

            //    double dotU = Math.Acos(Vector3d.Dot(atfLookUp, up));
            //    double dotL = Math.Acos(Vector3d.Dot(atfLookUp, left));

            //    CustomTrackingParams.Rotation = dotU;// -Math.PI / 2;
            //}


            double radius = Planets.GetAdjustedPlanetRadius((int)SolarSystemTrack);


            if (cameraDistance < radius * 2.0 && !forStars)
            {
                nearPlane = cameraDistance * 0.03;

                //m_nearPlane = Math.Max(m_nearPlane, .000000000030);
                nearPlane = Math.Max(nearPlane, .00000000001);
                back      = 1900;
            }
            else
            {
                if (forStars)
                {
                    back      = 900056;
                    back      = cameraDistance > 900056 ? cameraDistance * 3 : 900056;
                    nearPlane = .00003f;

                    // m_nearPlane = cameraDistance * 0.03;

                    // back = 9937812653;
                    //  back = 21421655730;
                }
                else
                {
                    back = cameraDistance > 1900 ? cameraDistance + 200 : 1900;

                    // m_nearPlane = .0001f;
                    if (Settings.Active.SolarSystemScale < 13)
                    {
                        nearPlane = (float)Math.Min(cameraDistance * 0.03, 0.01);
                    }
                    else
                    {
                        nearPlane = .001f;
                    }
                }
            }


            Projection     = Matrix3d.PerspectiveFovLH((fovLocal), (double)Width / (double)Height, nearPlane, back);
            PerspectiveFov = fovLocal;
            fovAngle       = ((this.ViewCamera.Zoom) / FOVMULT) / Math.PI * 180;
            fovScale       = (fovAngle / Height) * 3600;

            SetMatrixes();
            MakeFrustum();
        }
Ejemplo n.º 11
0
        private ErrorStatus InsertDWGFile(System.Drawing.Point TempPt)
        {
            Editor       Ed         = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            DocumentLock DocLock    = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument();
            Database     CurrentDwg = Ed.Document.Database;
            Point3d      Position   = Ed.PointToWorld(TempPt, Ed.GetViewportNumber(TempPt));

            using (Transaction Trans = CurrentDwg.TransactionManager.StartTransaction())
            {
                if (!File.Exists(this.filePath))
                {
                    Ed.WriteMessage("插入失败,文件" + this.filePath + "未找到" + "\n");
                    return(ErrorStatus.FileNotFound);
                }
                string           EntinityName     = Path.GetFileNameWithoutExtension(this.filePath);
                BlockTable       TargetBlockTable = Trans.GetObject(CurrentDwg.BlockTableId, OpenMode.ForWrite) as BlockTable;
                BlockTableRecord ModelSpace       = (BlockTableRecord)SymbolUtilityServices.GetBlockModelSpaceId(CurrentDwg).GetObject(OpenMode.ForWrite);
                Database         SourceDB         = new Database(false, false);
                ErrorStatus      stat             = this.GetInsertDwgFile(ref SourceDB);
                string           FileName         = Path.GetFileNameWithoutExtension(this.filePath);
                if (stat != ErrorStatus.OK)
                {
                    return(stat);
                }
                try
                {
                    ObjectId       BlockId;
                    BlockReference BlockRef;
                    if (!TargetBlockTable.Has(FileName + "_^_" + InstanceNum))
                    {
                        try
                        {
                            InstanceNum++;
                            BlockId = CurrentDwg.Insert(FileName + "_^_" + InstanceNum, SourceDB, true);
                        }catch (Autodesk.AutoCAD.Runtime.Exception Ex)
                        {
                            Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(Ex.Message);
                            return(ErrorStatus.CantOpenFile);
                        }
                    }
                    else
                    {
                        BlockId = TargetBlockTable[FileName + "_^_" + InstanceNum];
                    }

                    BlockRef = new BlockReference(Position, BlockId);

                    if (BlockRef.Bounds != null)
                    {
                        Point3d MinPt1 = BlockRef.Bounds.Value.MinPoint;
                        Point3d MaxPt2 = BlockRef.Bounds.Value.MaxPoint;

                        Point3d CenterPt = new Point3d((MaxPt2.X + MinPt1.X) * 0.5, (MaxPt2.Y + MinPt1.Y) * 0.5, (MaxPt2.Z + MinPt1.Z) * 0.5);
                        BlockRef.TransformBy(Matrix3d.Displacement(Position - CenterPt));
                    }

                    ModelSpace.AppendEntity(BlockRef);

                    Trans.AddNewlyCreatedDBObject(BlockRef, true);
                    Trans.Commit();

                    if (DocLock != null)
                    {
                        DocLock.Dispose();
                    }
                    if (CurrentDwg != null)
                    {
                        CurrentDwg.Dispose();
                    }
                    SourceDB.Dispose();
                    return(ErrorStatus.OK);
                }
                catch (Autodesk.AutoCAD.Runtime.Exception ex)
                {
                    Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(ex.Message);
                    Trans.Commit();

                    if (DocLock != null)
                    {
                        DocLock.Dispose();
                    }
                    if (CurrentDwg != null)
                    {
                        CurrentDwg.Dispose();
                    }
                    SourceDB.Dispose();
                    return(ErrorStatus.CantOpenFile);
                }
            }
        }
Ejemplo n.º 12
0
 public override void GetObjectSnapPoints(Entity ent, ObjectSnapModes mode, IntPtr gsm, Point3d pick, Point3d last, Matrix3d view, Point3dCollection snaps, IntegerCollection geomIds, Matrix3d insertion)
 {
 }
Ejemplo n.º 13
0
        public void SetupMatricesSpace3d(double canvasWidth, double canvasHeight)
        {
            Lighting = false;
            if (!firstTimeInit)
            {
                galacticMatrix = Matrix3d.Identity;
                // -28.9361739586894, 17.7603329867975
                galacticMatrix.Multiply(Matrix3d.RotationY(-(270 - (17.7603329867975 * 15)) / 180.0 * Math.PI));
                galacticMatrix.Multiply(Matrix3d.RotationX(-((-28.9361739586894)) / 180.0 * Math.PI));
                galacticMatrix.Multiply(Matrix3d.RotationZ(((31.422052860102041270114993238783) - 90) / 180.0 * Math.PI));
                //galacticMatrix.Transpose();
                //galacticMatrix.Invert();
                firstTimeInit = true;
            }


            Space = true;
            RenderTriangle.CullInside = true;

            Matrix3d WorldMatrix = Matrix3d.Identity;

            if (Settings.Active.GalacticMode)
            {
                WorldMatrix.Multiply(galacticMatrix);
                WorldMatrix.Multiply(Matrix3d.RotationY(((az)) / 180.0 * Math.PI));
                WorldMatrix.Multiply(Matrix3d.RotationX(-((alt)) / 180.0 * Math.PI));
                double[] gPoint = Coordinates.GalactictoJ2000(az, alt);

                viewPoint        = Coordinates.RADecTo3dAu(gPoint[0] / 15, gPoint[1], 1.0);
                TargetCamera.Lng = this.RAtoViewLng(gPoint[0] / 15);
                TargetCamera.Lat = gPoint[1];
                ViewCamera.Lat   = TargetCamera.Lat;
                ViewCamera.Lng   = TargetCamera.Lng;
            }
            else
            {
                WorldMatrix.Multiply(Matrix3d.RotationY(-((ViewCamera.Lng - 90)) / 180.0 * Math.PI));
                WorldMatrix.Multiply(Matrix3d.RotationX(-((ViewCamera.Lat)) / 180.0 * Math.PI));
                viewPoint = Coordinates.RADecTo3dAu(RA, Dec, 1.0);
            }



            double camLocal = ((ViewCamera.Rotation /*+ 90*/));

            fovAngle = ((this.ViewCamera.Zoom) / FOVMULT) / Math.PI * 180;
            fovScale = (fovAngle / canvasHeight) * 3600;

            //Settings.Global.LocalHorizonMode = true;

            // altaz
            if (Settings.Active.LocalHorizonMode && backgroundImageset.DataSetType == ImageSetType.Sky)
            {
                Coordinates zenithAltAz = new Coordinates(0, 0);

                zenithAltAz.Az = 0;

                zenithAltAz.Alt = 0;

                Coordinates zenith = Coordinates.HorizonToEquitorial(zenithAltAz, SpaceTimeController.Location, SpaceTimeController.Now);
                //Coordinates zenith2 = Coordinates.HorizonToEquitorial(zenithAltAz, Coordinates.FromLatLng(1, 1), SpaceTimeController.Now);
                //Coordinates zenith3 = Coordinates.HorizonToEquitorial(zenithAltAz, Coordinates.FromLatLng(-1, 1), SpaceTimeController.Now);

                double raPart  = -((zenith.RA - 6) / 24.0 * (Math.PI * 2));
                double decPart = -(((zenith.Dec)) / 360.0 * (Math.PI * 2));
                string raText  = Coordinates.FormatDMS(zenith.RA);
                WorldMatrix = Matrix3d.RotationY(-raPart - Math.PI);
                WorldMatrix.Multiply(Matrix3d.RotationX(decPart));

                if (SpaceTimeController.Location.Lat < 0)
                {
                    WorldMatrix.Multiply(Matrix3d.RotationY(((az) / 180.0 * Math.PI)));

                    WorldMatrix.Multiply(Matrix3d.RotationX(((alt) / 180.0 * Math.PI)));
                    camLocal += Math.PI;
                }
                else
                {
                    WorldMatrix.Multiply(Matrix3d.RotationY(((-az) / 180.0 * Math.PI)));

                    WorldMatrix.Multiply(Matrix3d.RotationX(((-alt) / 180.0 * Math.PI)));
                }

                Coordinates currentRaDec = Coordinates.HorizonToEquitorial(Coordinates.FromLatLng(alt, az), SpaceTimeController.Location, SpaceTimeController.Now);

                ViewCamera.Lat = TargetCamera.Lat = currentRaDec.Dec;
                ViewCamera.Lng = TargetCamera.Lng = RAtoViewLng(currentRaDec.RA);
            }
            World     = WorldMatrix;
            WorldBase = WorldMatrix.Clone();
            // altaz



            double localZoomFactor = ViewCamera.Zoom;

            double FovAngle = ((localZoomFactor) / FOVMULT) / Math.PI * 180;

            CameraPosition = Vector3d.Create(0.0, 0.0, 0.0);
            // This is for distance Calculation. For space everything is the same distance, so camera target is key.

            View     = Matrix3d.LookAtLH(CameraPosition, Vector3d.Create(0.0, 0.0, -1.0), Vector3d.Create(Math.Sin(camLocal), Math.Cos(camLocal), 0.0));
            ViewBase = View.Clone();

            double m_nearPlane = .1;

            nearPlane  = .1f;
            Projection = Matrix3d.PerspectiveFovLH((localZoomFactor) / FOVMULT, (double)canvasWidth / (double)canvasHeight, .1, -2.0);


            SetMatrixes();

            MakeFrustum();
        }
 public Matrix3d GetMatrix3d()
 {
     Matrix3d result = new Matrix3d();
                 unsafe { Get(&result.XX, new Vector2i(3, 3), 1); }
                 return result;
 }
Ejemplo n.º 15
0
 public static void AddError(string msg, Entity ent, Matrix3d trans, Icon icon = null)
 {
     var err = new Error(msg, ent, trans, icon);
     Errors.Add(err);
 }
Ejemplo n.º 16
0
 public static void AddError(string msg, ObjectId idEnt, Matrix3d trans, Icon icon = null)
 {
     var err = new Error(msg, idEnt, trans, icon);
     Errors.Add(err);
 }
Ejemplo n.º 17
0
        public void KojtoCAD_3D_Get_Real_3D_Centroid()
        {
            Database db  = HostApplicationServices.WorkingDatabase;
            Editor   ed  = Application.DocumentManager.MdiActiveDocument.Editor;
            Matrix3d old = ed.CurrentUserCoordinateSystem;

            ed.CurrentUserCoordinateSystem = Matrix3d.Identity;

            try
            {
                Pair <double, PromptStatus> nodeDensityPair =
                    GlobalFunctions.GetDouble(ConstantsAndSettings.nodeDensity, "\nNodes Density: ");
                if (nodeDensityPair.Second == PromptStatus.OK)
                {
                    Pair <double, PromptStatus> bendDensityPair =
                        GlobalFunctions.GetDouble(ConstantsAndSettings.bendDensity, "\nBends Density: ");
                    if (bendDensityPair.Second == PromptStatus.OK)
                    {
                        Pair <double, PromptStatus> nozzleDensityPair =
                            GlobalFunctions.GetDouble(ConstantsAndSettings.nozzleDensity, "\nEnd of Bends (Nozzle) Density: ");

                        if (nozzleDensityPair.Second == PromptStatus.OK)
                        {
                            Pair <double, PromptStatus> glassDensityPair =
                                GlobalFunctions.GetDouble(ConstantsAndSettings.glassDensity, "\nGlass Density: ");

                            if (glassDensityPair.Second == PromptStatus.OK)
                            {
                                if ((container != null) && (container.Bends.Count > 0) && (container.Nodes.Count > 0) && (container.Triangles.Count > 0))
                                {
                                    PromptKeywordOptions pKeyOpts = new PromptKeywordOptions("");
                                    pKeyOpts.Message = "\nEnter an option ";
                                    pKeyOpts.Keywords.Add("All");
                                    pKeyOpts.Keywords.Add("Glass");
                                    pKeyOpts.Keywords.Add("Mesh");
                                    pKeyOpts.Keywords.Add("Triangles");
                                    pKeyOpts.Keywords.Add("Polygons");
                                    pKeyOpts.Keywords.Add("Bends");
                                    pKeyOpts.Keywords.Add("Nodes");
                                    pKeyOpts.Keywords.Default = "All";
                                    pKeyOpts.AllowNone        = true;

                                    PromptResult pKeyRes = Application.DocumentManager.MdiActiveDocument.Editor.GetKeywords(pKeyOpts);
                                    {
                                        switch (pKeyRes.StringResult)
                                        {
                                        case "All":
                                            #region All
                                            Triplet <int, double, quaternion> POL = GetPolygonsCentroid(ref container, glassDensityPair.First);
                                            Triplet <int, double, quaternion> TRI = GetTrianglesCentroid(ref container, glassDensityPair.First);
                                            Triplet <int, double, quaternion> NOD = GetNodesCentroid(ref container, nodeDensityPair.First);
                                            Triplet <int, double, quaternion> BEN = GetBendsCentroid(ref container, bendDensityPair.First, nozzleDensityPair.First);
                                            if ((POL.First > 0) || (TRI.First > 0) || (NOD.First > 0) || (BEN.First > 0))
                                            {
                                                quaternion TEMP_Q = POL.Second * POL.Third + TRI.Second * TRI.Third + NOD.Second * NOD.Third + BEN.Second * BEN.Third;
                                                double     TEMP_V = POL.Second + TRI.Second + NOD.Second + BEN.Second;
                                                TEMP_Q /= TEMP_V;

                                                string title = "\nCenter of gravity\n------------------\n\n";
                                                string mess  = string.Format("{0} total volume: {1} \n Coordinate: {2:f5},{3:f5},{4:f5}", title, TEMP_V,
                                                                             TEMP_Q.GetX(), TEMP_Q.GetY(), TEMP_Q.GetZ());
                                                ed.WriteMessage(mess);

                                                MessageBox.Show(mess, "Center of gravity", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                            }
                                            #endregion
                                            break;

                                        case "Glass":
                                            #region Glass
                                            Triplet <int, double, quaternion> pol = GetPolygonsCentroid(ref container, glassDensityPair.First);
                                            Triplet <int, double, quaternion> tri = GetTrianglesCentroid(ref container, glassDensityPair.First);
                                            if ((pol.First > 0) || (tri.First > 0))
                                            {
                                                quaternion tempQ = pol.Second * pol.Third + tri.Second * tri.Third;
                                                double     tempV = pol.Second + tri.Second;
                                                tempQ /= tempV;

                                                string title = "\nGlass center of gravity\n------------------\n\n";
                                                string mess  = string.Format("{0} total volume: {1} \n Coordinate: {2:f5},{3:f5},{4:f5}", title, tempV,
                                                                             tempQ.GetX(), tempQ.GetY(), tempQ.GetZ());
                                                ed.WriteMessage(mess);

                                                MessageBox.Show(mess, "Glass - center of gravity", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                            }
                                            #endregion
                                            break;

                                        case "Mesh":
                                            #region Mesh
                                            Triplet <int, double, quaternion> nod = GetNodesCentroid(ref container, nodeDensityPair.First);
                                            Triplet <int, double, quaternion> ben = GetBendsCentroid(ref container, bendDensityPair.First, nozzleDensityPair.First);

                                            if ((nod.First > 0) || (ben.First > 0))
                                            {
                                                quaternion tempQ = nod.Second * nod.Third + ben.Second * ben.Third;
                                                double     tempV = nod.Second + ben.Second;
                                                tempQ /= tempV;

                                                string title = "\nMesh center of gravity\n------------------\n\n";
                                                string mess  = string.Format("{0} total volume: {1} \n Coordinate: {2:f5},{3:f5},{4:f5}", title, tempV,
                                                                             tempQ.GetX(), tempQ.GetY(), tempQ.GetZ());
                                                ed.WriteMessage(mess);

                                                MessageBox.Show(mess, "Mesh - center of gravity", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                            }
                                            #endregion
                                            break;

                                        case "Polygons":
                                            #region Polygons
                                            Triplet <int, double, quaternion> pp = GetPolygonsCentroid(ref container, glassDensityPair.First);
                                            if (pp.First > 0)
                                            {
                                                string title = "\nPolygons center of gravity\n------------------\n\n";
                                                string mess  = string.Format("{0} total volume: {1} \n Coordinate: {2:f5},{3:f5},{4:f5}", title, pp.Second,
                                                                             pp.Third.GetX(), pp.Third.GetY(), pp.Third.GetZ());
                                                ed.WriteMessage(mess);

                                                MessageBox.Show(mess, "Polygons - center of gravity", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                            }
                                            #endregion
                                            break;

                                        case "Triangles":
                                            #region trianles
                                            Triplet <int, double, quaternion> ppp = GetTrianglesCentroid(ref container, glassDensityPair.First);
                                            if (ppp.First > 0)
                                            {
                                                string title = "\nTriangless center of gravity\n------------------\n\n";
                                                string mess  = string.Format("{0} total volume: {1} \n Coordinate: {2:f5},{3:f5},{4:f5}", title, ppp.Second,
                                                                             ppp.Third.GetX(), ppp.Third.GetY(), ppp.Third.GetZ());
                                                ed.WriteMessage(mess);

                                                MessageBox.Show(mess, "Triangles - center of gravity", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                            }
                                            #endregion
                                            break;

                                        case "Bends":
                                            #region bends
                                            Triplet <int, double, quaternion> trB = GetBendsCentroid(ref container, bendDensityPair.First, nozzleDensityPair.First);
                                            if (trB.First > 0)
                                            {
                                                string title = "\nBends center of gravity\n------------------\n\n";
                                                string mess  = string.Format("{0} total volume: {1} \n Coordinate: {2:f5},{3:f5},{4:f5}", title, trB.Second,
                                                                             trB.Third.GetX(), trB.Third.GetY(), trB.Third.GetZ());
                                                ed.WriteMessage(mess);

                                                MessageBox.Show(mess, "Bends - center of gravity", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                            }
                                            #endregion
                                            break;

                                        case "Nodes":
                                            #region nodes
                                            Triplet <int, double, quaternion> tr = GetNodesCentroid(ref container, nodeDensityPair.First);
                                            if (tr.First > 0)
                                            {
                                                string title = "\nNodes center of gravity\n------------------\n\n";
                                                string mess  = string.Format("{0} total volume: {1} \n Coordinate: {2:f5},{3:f5},{4:f5}", title, tr.Second,
                                                                             tr.Third.GetX(), tr.Third.GetY(), tr.Third.GetZ());
                                                ed.WriteMessage(mess);

                                                MessageBox.Show(mess, "Nodes - center of gravity", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                            }
                                            #endregion
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    MessageBox.Show("\nData Base Empty !\n", "Range Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                            }
                        }
                    }
                }//
            }
            catch { }
            finally { ed.CurrentUserCoordinateSystem = old; }
        }
Ejemplo n.º 18
0
        virtual public bool IsTileBigEnough(RenderContext renderContext)
        {
            if (Level > 1)
            {
                Matrix3d wvp = renderContext.WVP;


                //// Test for tile scale in view..
                //topLeftScreen = wvp.ProjectToScreen(TopLeft, renderContext.Width, renderContext.Height);
                //bottomRightScreen = wvp.ProjectToScreen(BottomRight, renderContext.Width, renderContext.Height);
                //topRightScreen = wvp.ProjectToScreen(TopRight, renderContext.Width, renderContext.Height);
                //bottomLeftScreen = wvp.ProjectToScreen(BottomLeft, renderContext.Width, renderContext.Height);

                //Vector3d top = topLeftScreen;
                //top.Subtract(topRightScreen);
                //double topLength = top.Length();

                //Vector3d bottom = bottomLeftScreen;
                //bottom.Subtract(bottomRightScreen);
                //double bottomLength = bottom.Length();

                //Vector3d left = bottomLeftScreen;
                //left.Subtract(topLeftScreen);
                //double leftLength = left.Length();

                //Vector3d right = bottomRightScreen;
                //right.Subtract(topRightScreen);
                //double rightLength = right.Length();

                // Test for tile scale in view..
                wvp.TransformTo(TopLeft, topLeftScreen);
                wvp.TransformTo(BottomRight, bottomRightScreen);
                wvp.TransformTo(TopRight, topRightScreen);
                wvp.TransformTo(BottomLeft, bottomLeftScreen);

                Vector3d top = topLeftScreen;
                top.Subtract(topRightScreen);
                double topLength = top.Length();

                Vector3d bottom = bottomLeftScreen;
                bottom.Subtract(bottomRightScreen);
                double bottomLength = bottom.Length();

                Vector3d left = bottomLeftScreen;
                left.Subtract(topLeftScreen);
                double leftLength = left.Length();

                Vector3d right = bottomRightScreen;
                right.Subtract(topRightScreen);
                double rightLength = right.Length();


                float lengthMax = Math.Max(Math.Max(rightLength, leftLength), Math.Max(bottomLength, topLength));
                if (lengthMax < 300) // was 220
                {
                    return(false);
                }
                else
                {
                    deepestLevel = Level > deepestLevel ? Level : deepestLevel;
                }
            }

            return(true);
        }
Ejemplo n.º 19
0
        public static Matrix4d PutTheMatrix4dtogether(this Matrix4d mat4d, Vector3d T, Matrix3d Rotation)
        {
            //put the 4d matrix together
            Matrix3d r3D      = Rotation.Clone();
            Matrix4d myMatrix = new Matrix4d(r3D);

            myMatrix[0, 3] = T.X;
            myMatrix[1, 3] = T.Y;
            myMatrix[2, 3] = T.Z;
            myMatrix[3, 3] = 1f;

            return(myMatrix);
        }
Ejemplo n.º 20
0
        protected void SizesRight(bool doTrans, Matrix3d trans)
        {
            double yWinMax = 0;
            double yWinMin = 0;
            var    win     = panelBase.Panel.windows?.window?.First();

            if (win == null)
            {
                var balc = panelBase.Panel.balconys?.balcony?.First();
                if (balc != null)
                {
                    yWinMax = balc.posi.Y + balc.height;
                    yWinMin = balc.posi.Y;
                }
            }
            else
            {
                yWinMax = win.posi.Y + win.height;
                yWinMin = win.posi.Y;
            }

            var heightTile = Settings.Default.TileHeight + Settings.Default.TileSeam;
            // y последней плитки
            var countTile = Convert.ToInt32(panelBase.Height / heightTile);
            var yLastTile = (countTile * heightTile) - 12;

            Point3d ptBotRight = new Point3d(panelBase.XMaxPanel, 0, 0);
            Point3d ptTopRight = new Point3d(ptBotRight.X, yLastTile, 0);

            bool hasIndentDim = yWinMax > 0;

            xDimLineRightMax = hasIndentDim ? ptBotRight.X + indentDimLineFromDraw + indentBetweenDimLine : ptBotRight.X + indentDimLineFromDraw;

            // Общий размер
            Point3d ptDimLineTotal = new Point3d(xDimLineRightMax, 0, 0);

            CreateDim(ptBotRight, ptTopRight, ptDimLineTotal, doTrans, trans, rangeSize: rangeSizeVertic, rotation: 90);
            // Промежуточные размеры
            if (hasIndentDim)
            {
                Point3d ptDimLineIndent = new Point3d(xDimLineRightMax - indentBetweenDimLine, 0, 0);
                Point3d ptMinWin        = ptBotRight;
                if (yWinMin > 0)
                {
                    var countTileMinWin = Convert.ToInt32(yWinMin / heightTile);
                    var yTilesMinWin    = (countTileMinWin * heightTile) - 12;
                    ptMinWin = new Point3d(ptBotRight.X, yTilesMinWin, 0);
                    CreateDim(ptBotRight, ptMinWin, ptDimLineIndent, doTrans, trans, rangeSize: rangeSizeVertic, rotation: 90, interlineText: true);
                    var     ptMinWinSeam  = new Point3d(ptMinWin.X, ptMinWin.Y + 12, 0);
                    var     dimSeamMin    = CreateDim(ptMinWin, ptMinWinSeam, ptDimLineIndent, doTrans, trans, rotation: 90);
                    Point3d ptTextSeamMin = new Point3d(ptDimLineIndent.X, ptMinWinSeam.Y + 65, 0);
                    dimSeamMin.TextPosition = doTrans? ptTextSeamMin.TransformBy(trans): ptTextSeamMin;
                    ptMinWin = ptMinWinSeam;
                }
                var     countTileMaxWin = Convert.ToInt32(yWinMax / heightTile);
                var     yTilesMaxWin    = (countTileMaxWin * heightTile) - 12;
                Point3d ptMaxWin        = new Point3d(ptMinWin.X, yTilesMaxWin, 0);
                CreateDim(ptMinWin, ptMaxWin, ptDimLineIndent, doTrans, trans, rangeSize: rangeSizeVertic, rotation: 90, interlineText: true);
                Point3d ptMaxWinSeam  = new Point3d(ptMaxWin.X, ptMaxWin.Y + 12, 0);
                var     dimSeamMax    = CreateDim(ptMaxWin, ptMaxWinSeam, ptDimLineIndent, doTrans, trans, rotation: 90);
                Point3d ptTextSeamMax = new Point3d(ptDimLineIndent.X, ptMaxWin.Y - 65, 0);
                dimSeamMax.TextPosition = doTrans ? ptTextSeamMax.TransformBy(trans) : ptTextSeamMax;
                // размер до верха плиток
                CreateDim(ptMaxWinSeam, ptTopRight, ptDimLineIndent, doTrans, trans, rangeSize: rangeSizeVertic, rotation: 90, interlineText: true);
            }
        }
Ejemplo n.º 21
0
        protected void SizesBot(bool doTrans, Matrix3d trans)
        {
            // Общий размер
             Point3d ptBotLeft = new Point3d(panelBase.XMinContour, 0, 0);
             Point3d ptBotRight = new Point3d(panelBase.XMaxContour, 0, 0);
             yDimLineBotMin = -indentDimLineFromDraw -indentBetweenDimLine;
             Point3d ptDimLineTotal = new Point3d(0, yDimLineBotMin, 0);
             CreateDim(ptBotLeft, ptBotRight, ptDimLineTotal, doTrans, trans);
             // Промежуточный размер
             Point3d ptDimLineInter = new Point3d(0, yDimLineBotMin + indentBetweenDimLine, 0);
             var ptNext = new Point3d(ptBotRight.X - 288, 0, 0);
             var dim = CreateDim(ptBotLeft, ptNext, ptDimLineInter, doTrans, trans);
             var lenTile = Settings.Default.TileLenght + Settings.Default.TileSeam;
             var count = Convert.ToInt32(dim.Measurement / lenTile);
             dim.Prefix = $"({Settings.Default.TileLenght}+{Settings.Default.TileSeam})x{count}=";

             CreateDim(ptNext, ptBotRight, ptDimLineInter, doTrans, trans);

             // Торец
             if (panelBase.IsCheekRight || panelBase.IsCheekLeft)
             {
            sizesCheek(doTrans, trans);
             }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Вставка блока профиля и стрелок к местам установки профиля на стыке плиток в торце панели
        /// </summary>
        protected void addProfileTile(bool doTrans, Matrix3d trans)
        {
            double xPtProfile     = 0;
            double yPtProfile     = 0;
            double xPtArrowDirect = 0;

            if (panelBase.IsCheekLeft)
            {
                // Для торца слева - профиль вставляется в одну и туже точку (-400,-600)
                xPtProfile         = -400;
                yPtProfile         = -600;
                ptPosArrowToHorSec = ptPosHorizontalPanelSection;
            }
            else if (panelBase.IsCheekRight)
            {
                // Для торца справа - на раст (400,600) от нижнего правого края последней плитки
                xPtProfile         = panelBase.XMaxContour + 400;
                yPtProfile         = -600;
                xPtArrowDirect     = panelBase.XMaxContour;
                ptPosArrowToHorSec = new Point3d(panelBase.XMaxContour, ptPosHorizontalPanelSection.Y, 0);
            }
            else
            {
                // Не нужен профиль для панелей без торцов (Cheek)
                return;
            }

            // Поиск блока профиля в инвентаре
            BlockInfo biProfile = panelBase.Service.Env.BlocksInFacade.FirstOrDefault(b => b.BlName.Equals(Settings.Default.BlockProfileTile));

            if (biProfile == null)
            {
                return;
            }

            ObjectId idBtrProfile = biProfile.IdBtr;

            // Точка вставки блока профиля
            ptPosProfile = new Point3d(xPtProfile, yPtProfile, 0);
            Point3d ptBlrefProfile = ptPosProfile;

            if (doTrans)
            {
                ptBlrefProfile = ptPosProfile.TransformBy(trans);
            }

            // Вставка блока профиля - название и марка
            var blRefProfile = CreateBlRefInBtrDim(ptBlrefProfile, idBtrProfile, Settings.Default.SheetScale);

            if (blRefProfile == null)
            {
                return;
            }

            // Добавление атрибутов Названия и марки
            // Атрибут Названия - из вхождения атрибута
            var atrRefName = biProfile.AttrsRef.FirstOrDefault(a => a.Tag.Equals("НАЗВАНИЕ"));

            if (atrRefName != null)
            {
                // определение атрибута
                var atrDefName = biProfile.AttrsDef.FirstOrDefault(a => a.Tag.Equals("НАЗВАНИЕ"));
                if (atrDefName != null)
                {
                    AddAttrToBlockRef(blRefProfile, atrDefName.IdAtr, atrRefName.Text);
                }
            }
            // Атрибут Марки - из вхождения атрибута
            var atrRefMark = biProfile.AttrsRef.FirstOrDefault(a => a.Tag.Equals("МАРКА"));

            if (atrRefMark != null)
            {
                // определение атрибута
                var atrDefMark = biProfile.AttrsDef.FirstOrDefault(a => a.Tag.Equals("МАРКА"));
                if (atrDefMark != null)
                {
                    AddAttrToBlockRef(blRefProfile, atrDefMark.IdAtr, atrRefMark.Text);
                }
            }

            // Вставка стрелки до угла панели
            Point3d ptArrowPos    = new Point3d(xPtProfile, yPtProfile + 4 * Settings.Default.SheetScale, 0);
            Point3d ptArrowDirect = new Point3d(xPtArrowDirect, 0, 0);

            InsertArrowBlRef(ptArrowPos, ptArrowDirect, doTrans, trans);
        }
Ejemplo n.º 23
0
        private void addCheekViewBlock(bool doTrans, Matrix3d trans, double xPosView, bool isLeft)
        {
            // Добавление блока вида.
             // Если блока нет, то выход.
             if (panelBase.Service.Env.IdBtrView.IsNull)
             {
            return;
             }

             Point3d ptBlView = new Point3d(xPosView, 860, 0);
             if (doTrans)
             {
            ptBlView = ptBlView.TransformBy(trans);
             }
             BlockReference blRefView = CreateBlRefInBtrDim(ptBlView, panelBase.Service.Env.IdBtrView, Settings.Default.SheetScale);
             if (blRefView == null)
             {
            return;
             }

             // атрибут Вида
             if (!panelBase.Service.Env.IdAttrDefView.IsNull)
             {
            using (var attrDefView = panelBase.Service.Env.IdAttrDefView.GetObject(OpenMode.ForRead, false, true) as AttributeDefinition)
            {
               var attrRefView = new AttributeReference();
               attrRefView.SetAttributeFromBlock(attrDefView, blRefView.BlockTransform);
               attrRefView.TextString = "А";

               blRefView.AttributeCollection.AppendAttribute(attrRefView);
               t.AddNewlyCreatedDBObject(attrRefView, true);

               if ((!isLeft || doTrans) && !(!isLeft && doTrans))
               {
                  attrRefView.TransformBy(Matrix3d.Mirroring(
                     new Line3d(attrRefView.AlignmentPoint, new Point3d(attrRefView.AlignmentPoint.X, 0, 0))));
               }
            }
             }

             if ((!isLeft || doTrans) && !(!isLeft && doTrans))
             {
            blRefView.TransformBy(Matrix3d.Mirroring(new Line3d(ptBlView, new Point3d(ptBlView.X, 0, 0))));
             }
        }
Ejemplo n.º 24
0
 protected void InsertArrowBlRef(Point3d ptArrowBlPos, Point3d ptArrowDirect, bool doTrans, Matrix3d trans)
 {
     // Вставка стрелки и направление ее на указанную точку
     if (!panelBase.Service.Env.IdBtrArrow.IsNull)
     {
         if (doTrans)
         {
             ptArrowBlPos  = ptArrowBlPos.TransformBy(trans);
             ptArrowDirect = ptArrowDirect.TransformBy(trans);
         }
         // вставка блока стрелки
         var blRefArrow = CreateBlRefInBtrDim(ptArrowBlPos, panelBase.Service.Env.IdBtrArrow, Settings.Default.SheetScale);
         if (blRefArrow == null)
         {
             return;
         }
         // поворот стрелки и установка длины
         Vector2d vecArrow = ptArrowDirect.Convert2d() - ptArrowBlPos.Convert2d();
         blRefArrow.Rotation = vecArrow.Angle;
         // длина стрелки
         setDynParam(blRefArrow, "Длина", vecArrow.Length);
     }
 }
Ejemplo n.º 25
0
        public static void Transform(Matrix3d matrix, ObjectId entId)
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            Database dwg = Application.DocumentManager.MdiActiveDocument.Database;
            using (Transaction tr = dwg.TransactionManager.StartTransaction())
            {
                try
                {
                    Entity ent = entId.GetObject(OpenMode.ForWrite) as Entity;

                    ent.TransformBy(matrix);
                    tr.Commit();
                }
                catch (Exception exc)
                {
                    ed.WriteMessage(exc.Message);
                    tr.Abort();
                }
            }
        }
Ejemplo n.º 26
0
        protected override SamplerStatus Sampler(JigPrompts prompts)
        {
            int           num;
            SamplerStatus samplerStatus;
            int           num7;
            object        obj;

            try
            {
IL_01:
                ProjectData.ClearProjectError();
                num = -2;
IL_09:
                int num2 = 2;
                JigPromptPointOptions jigPromptPointOptions = new JigPromptPointOptions("\r\n请指定插入点:");
IL_16:
                num2 = 3;
                jigPromptPointOptions.UserInputControls = 2;
IL_1F:
                num2 = 4;
                jigPromptPointOptions.Cursor = 3;
IL_28:
                num2 = 5;
                jigPromptPointOptions.BasePoint = this.point3d_0;
IL_36:
                num2 = 6;
                jigPromptPointOptions.UseBasePoint = true;
IL_3F:
                num2 = 7;
                PromptPointResult promptPointResult = prompts.AcquirePoint(jigPromptPointOptions);
IL_4A:
                num2 = 8;
                if (promptPointResult.Status != -5002)
                {
                    goto IL_61;
                }
IL_5C:
                goto IL_1DC;
IL_61:
                num2 = 11;
IL_64:
                num2           = 12;
                this.point3d_1 = promptPointResult.Value;
IL_74:
                num2 = 13;
                if (!(this.point3d_2 != this.point3d_1))
                {
                    goto IL_113;
                }
IL_8D:
                num2 = 14;
                Matrix3d matrix3d = Matrix3d.Displacement(this.point3d_1 - this.point3d_2);
IL_A8:
                num2 = 15;
                int num3 = 0;
                checked
                {
                    int num4 = this.objectIdCollection_0.Count - 1;
                    this.int_0 = num3;
                    for (;;)
                    {
                        int num5 = this.int_0;
                        int num6 = num4;
                        if (num5 > num6)
                        {
                            break;
                        }
IL_C3:
                        num2 = 16;
                        this.entity_0[this.int_0].TransformBy(matrix3d);
IL_DA:
                        num2 = 17;
                        this.int_0++;
                    }
IL_F9:
                    num2           = 18;
                    this.point3d_2 = this.point3d_1;
IL_108:
                    num2          = 19;
                    samplerStatus = 0;
                    goto IL_1DC;
IL_113:
                    num2 = 21;
IL_116:
                    num2          = 22;
                    samplerStatus = 1;
                    goto IL_1DC;
IL_121:
                    goto IL_1E8;
IL_126:
                    num7 = num2;
                    if (num <= -2)
                    {
                        goto IL_140;
                    }
                    @switch(ICSharpCode.Decompiler.ILAst.ILLabel[], num);
IL_13B:
                    goto IL_1E8;
                    IL_140 :;
                }
                int num8 = num7 + 1;
                num7 = 0;
                @switch(ICSharpCode.Decompiler.ILAst.ILLabel[], num8);
                goto IL_121;
                IL_1B7 :;
            }
            catch when(endfilter(obj is Exception & num != 0 & num7 == 0))
            {
                Exception ex = (Exception)obj2;

                goto IL_126;
            }
IL_1DC:
            SamplerStatus result = samplerStatus;

            if (num7 != 0)
            {
                ProjectData.ClearProjectError();
            }
            return(result);

IL_1E8:
            throw ProjectData.CreateProjectError(-2146828237);
        }
Ejemplo n.º 27
0
 public FullSubentityPath[] GetSubentityPathsAtGraphicsMarker(SubentityType type, long gsMark, Point3d pickPoint, Matrix3d viewTransform, int numInserts, ObjectId[] entityAndInsertStack)
 {
     createInstance();
     FullSubentityPath[] GetSubentityPathsAtG = BaseEntity.GetSubentityPathsAtGraphicsMarker(type, gsMark, pickPoint, viewTransform, numInserts, entityAndInsertStack);
     tr.Dispose();
     return GetSubentityPathsAtG;
 }
Ejemplo n.º 28
0
        public override void ToMachining(double AssociatedDist, ToolFile toolFile)
        {
            //由于这个指令是指定了板件的1-8个点进行定位的,所以要把空间的绝对坐标换算回机加工原点的相对坐标
            //matrix1负责把所在点的坐标转换为板件中心的坐标
            //matrix2负责把板件中心的坐标,再转换为MP中心的坐标
            Point3d  pt      = Part.GetPartPointByNumber(EdgeNumber.ToString());
            Matrix3d matrix1 = Matrix3d.AlignCoordinateSystem(
                Point3d.Origin,
                Vector3d.XAxis,
                Vector3d.YAxis,
                Vector3d.ZAxis,
                pt,
                (Part.MachinePoint.IsRotated) ? this.GetPointYAxis(EdgeNumber) : this.GetPointXAxis(EdgeNumber),
                (Part.MachinePoint.IsRotated) ? this.GetPointXAxis(EdgeNumber) : this.GetPointYAxis(EdgeNumber),
                Vector3d.ZAxis);
            Matrix3d matrix2 = Matrix3d.AlignCoordinateSystem(
                Part.MPPoint,
                Part.MPXAxis,
                Part.MPYAxis,
                Part.MPZAxis,
                Point3d.Origin,
                Vector3d.XAxis,
                Vector3d.YAxis,
                Vector3d.ZAxis);

            if (LeadIn > 0)
            {
                double  rRadius  = LeadIn;
                Point3d firstPt  = new Point3d(Radius + rRadius, -rRadius, Depth);
                Point3d secondPt = new Point3d(Radius, 0, Depth);
                Point3d thirdPt  = new Point3d(0, Radius, Depth);
                Point3d forthPt  = new Point3d(-rRadius, Radius + rRadius, Depth);

                firstPt  = firstPt.TransformBy(matrix1).TransformBy(matrix2);
                secondPt = secondPt.TransformBy(matrix1).TransformBy(matrix2);
                thirdPt  = thirdPt.TransformBy(matrix1).TransformBy(matrix2);
                forthPt  = forthPt.TransformBy(matrix1).TransformBy(matrix2);

                double   firstBulge = -0.414214;
                ToolComp comp       = ToolComp.None;

                if (firstPt.X >= thirdPt.X && firstPt.Y >= thirdPt.Y)
                {
                    comp        = ToolComp.Left;
                    firstBulge *= -1;
                }
                else if (firstPt.X >= thirdPt.X && firstPt.Y < thirdPt.Y)
                {
                    comp = ToolComp.Right;
                }
                else if (firstPt.X < thirdPt.X && firstPt.Y < thirdPt.Y)
                {
                    comp        = ToolComp.Left;
                    firstBulge *= -1;
                }
                else if (firstPt.X < thirdPt.X && firstPt.Y >= thirdPt.Y)
                {
                    comp = ToolComp.Right;
                }

                Machinings.Routing route = new Machinings.Routing();
                route.ToolName = ToolName;
                route.Points   = new List <Point3d>()
                {
                    firstPt, secondPt, thirdPt, forthPt
                };
                route.Part     = Part;
                route.ToolComp = comp;
                route.Bulges   = (new double[] { 0, firstBulge, 0, 0 }).ToList();
                if (FaceNumber == 5)
                {
                    route.OnFace5 = true;
                }
                else
                {
                    route.OnFace5 = false;
                }

                Part.Routings.Add(route);
            }
        }
Ejemplo n.º 29
0
 public static void UniformMatrix3(int location, bool transpose, ref Matrix3d matrix)
 {
     unsafe
     {
         fixed (double* matrix_ptr = &matrix.Row0.X)
         {
             GL.UniformMatrix3(location, 1, transpose, matrix_ptr);
         }
     }
 }
Ejemplo n.º 30
0
        static void Zoom(Point3d pMin, Point3d pMax, Point3d pCenter, double dFactor)
        {
            // Get the current document and database
            Document acDoc   = Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;

            int nCurVport = System.Convert.ToInt32(Application.GetSystemVariable("CVPORT"));

            // Get the extents of the current space no points
            // or only a center point is provided
            // Check to see if Model space is current
            if (acCurDb.TileMode == true)
            {
                if (pMin.Equals(new Point3d()) == true &&
                    pMax.Equals(new Point3d()) == true)
                {
                    pMin = acCurDb.Extmin;
                    pMax = acCurDb.Extmax;
                }
            }
            else
            {
                // Check to see if Paper space is current
                if (nCurVport == 1)
                {
                    // Get the extents of Paper space
                    if (pMin.Equals(new Point3d()) == true &&
                        pMax.Equals(new Point3d()) == true)
                    {
                        pMin = acCurDb.Pextmin;
                        pMax = acCurDb.Pextmax;
                    }
                }
                else
                {
                    // Get the extents of Model space
                    if (pMin.Equals(new Point3d()) == true &&
                        pMax.Equals(new Point3d()) == true)
                    {
                        pMin = acCurDb.Extmin;
                        pMax = acCurDb.Extmax;
                    }
                }
            }

            // Start a transaction
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                // Get the current view
                using (ViewTableRecord acView = acDoc.Editor.GetCurrentView())
                {
                    Extents3d eExtents;

                    // Translate WCS coordinates to DCS
                    Matrix3d matWCS2DCS;
                    matWCS2DCS = Matrix3d.PlaneToWorld(acView.ViewDirection);
                    matWCS2DCS = Matrix3d.Displacement(acView.Target - Point3d.Origin) * matWCS2DCS;
                    matWCS2DCS = Matrix3d.Rotation(-acView.ViewTwist,
                                                   acView.ViewDirection,
                                                   acView.Target) * matWCS2DCS;

                    // If a center point is specified, define the min and max
                    // point of the extents
                    // for Center and Scale modes
                    if (pCenter.DistanceTo(Point3d.Origin) != 0)
                    {
                        pMin = new Point3d(pCenter.X - (acView.Width / 2),
                                           pCenter.Y - (acView.Height / 2), 0);

                        pMax = new Point3d((acView.Width / 2) + pCenter.X,
                                           (acView.Height / 2) + pCenter.Y, 0);
                    }

                    // Create an extents object using a line
                    using (Line acLine = new Line(pMin, pMax))
                    {
                        eExtents = new Extents3d(acLine.Bounds.Value.MinPoint,
                                                 acLine.Bounds.Value.MaxPoint);
                    }

                    // Calculate the ratio between the width and height of the current view
                    double dViewRatio;
                    dViewRatio = (acView.Width / acView.Height);

                    // Tranform the extents of the view
                    matWCS2DCS = matWCS2DCS.Inverse();
                    eExtents.TransformBy(matWCS2DCS);

                    double  dWidth;
                    double  dHeight;
                    Point2d pNewCentPt;

                    // Check to see if a center point was provided (Center and Scale modes)
                    if (pCenter.DistanceTo(Point3d.Origin) != 0)
                    {
                        dWidth  = acView.Width;
                        dHeight = acView.Height;

                        if (dFactor == 0)
                        {
                            pCenter = pCenter.TransformBy(matWCS2DCS);
                        }

                        pNewCentPt = new Point2d(pCenter.X, pCenter.Y);
                    }
                    else // Working in Window, Extents and Limits mode
                    {
                        // Calculate the new width and height of the current view
                        dWidth  = eExtents.MaxPoint.X - eExtents.MinPoint.X;
                        dHeight = eExtents.MaxPoint.Y - eExtents.MinPoint.Y;

                        // Get the center of the view
                        pNewCentPt = new Point2d(((eExtents.MaxPoint.X + eExtents.MinPoint.X) * 0.5),
                                                 ((eExtents.MaxPoint.Y + eExtents.MinPoint.Y) * 0.5));
                    }

                    // Check to see if the new width fits in current window
                    if (dWidth > (dHeight * dViewRatio))
                    {
                        dHeight = dWidth / dViewRatio;
                    }

                    // Resize and scale the view
                    if (dFactor != 0)
                    {
                        acView.Height = dHeight * dFactor;
                        acView.Width  = dWidth * dFactor;
                    }

                    // Set the center of the view
                    acView.CenterPoint = pNewCentPt;

                    // Set the current view
                    acDoc.Editor.SetCurrentView(acView);
                }

                // Commit the changes
                acTrans.Commit();
            }
        }
Ejemplo n.º 31
0
        public static void TagFoundations(List <Curve> lines, Plot p)
        {
            Database acCurDb;

            acCurDb = Application.DocumentManager.MdiActiveDocument.Database;
            ObjectContextCollection occ = acCurDb.ObjectContextManager.GetContextCollection("ACDB_ANNOTATIONSCALES");

            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                LayerTable acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId, OpenMode.ForRead) as LayerTable;
                ObjectId   current  = acCurDb.Clayer;
                acCurDb.Clayer = acLyrTbl[Main.FoundationTextLayer];

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

                ObjectId blkRecId = ObjectId.Null;

                if (!acBlkTbl.Has("FormationTag"))
                {
                    Main.LoadBlocks();
                }

                foreach (Curve c in lines)
                {
                    Matrix3d           curUCSMatrix = Application.DocumentManager.MdiActiveDocument.Editor.CurrentUserCoordinateSystem;
                    CoordinateSystem3d curUCS       = curUCSMatrix.CoordinateSystem3d;

                    //Get lable point
                    Point3d labelPoint3d = c.GetPointAtDist(c.GetDistanceAtParameter(c.EndParam) / 2);
                    Point3d labelPoint   = new Point3d(labelPoint3d.X, labelPoint3d.Y, 0);

                    // Insert the block into the current space
                    using (BlockReference acBlkRef = new BlockReference(labelPoint, acBlkTbl["FormationTag"]))
                    {
                        //Calculate Line Angle
                        double y     = c.EndPoint.Y - c.StartPoint.Y;
                        double x     = c.EndPoint.X - c.StartPoint.X;
                        double angle = Math.Atan(Math.Abs(y) / Math.Abs(x));
                        if (angle >= Math.PI / 2)
                        {
                            acBlkRef.TransformBy(Matrix3d.Rotation(0, curUCS.Zaxis, labelPoint));
                        }
                        else
                        {
                            acBlkRef.TransformBy(Matrix3d.Rotation(Math.PI / 2, curUCS.Zaxis, labelPoint));
                        }
                        acBlkRef.AddContext(occ.GetContext("10:1"));

                        //Set value
                        AttributeCollection attCol = acBlkRef.AttributeCollection;
                        foreach (ObjectId attId in attCol)
                        {
                            AttributeReference att = acTrans.GetObject(attId, OpenMode.ForRead, false) as AttributeReference;
                            if (att.Tag == "LEVEL")
                            {
                                att.UpgradeOpen();
                                att.TextString = p.FormationLevel.ToString();
                            }
                        }

                        BlockTableRecord acCurSpaceBlkTblRec;
                        acCurSpaceBlkTblRec = acTrans.GetObject(acCurDb.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;

                        acCurSpaceBlkTblRec.AppendEntity(acBlkRef);
                        acTrans.AddNewlyCreatedDBObject(acBlkRef, true);
                    }
                }

                acCurDb.Clayer = current;

                acTrans.Commit();
            }
        }
Ejemplo n.º 32
0
        public void AddGlyphPoints(List <PositionTexture> pointList, Vector2d size, Rectangle position, Rectangle uv)
        {
            PositionTexture[] points = new PositionTexture[6];

            for (int i = 0; i < 6; i++)
            {
                points[i] = new PositionTexture();
            }



            Vector3d left  = Vector3d.Cross(center, up);
            Vector3d right = Vector3d.Cross(up, center);

            left.Normalize();
            right.Normalize();
            up.Normalize();

            Vector3d upTan = Vector3d.Cross(center, right);

            upTan.Normalize();

            if (alignment == Alignment.Center)
            {
                left.Multiply(width - position.Left * 2);
                right.Multiply(width - ((width * 2) - position.Right * 2));
            }
            else if (alignment == Alignment.Left)
            {
                left.Multiply(-position.Left * 2);
                right.Multiply(position.Right * 2);
            }

            Vector3d top    = upTan.Copy();
            Vector3d bottom = Vector3d.SubtractVectors(Vector3d.Empty, upTan);

            top.Multiply(height - position.Top * 2);
            bottom.Multiply(height - ((height * 2) - position.Bottom * 2));
            Vector3d ul = center.Copy();

            ul.Add(top);
            if (sky)
            {
                ul.Add(left);
            }
            else
            {
                ul.Subtract(left);
            }
            Vector3d ur = center.Copy();

            ur.Add(top);
            if (sky)
            {
                ur.Add(right);
            }
            else
            {
                ur.Subtract(right);
            }
            Vector3d ll = center.Copy();

            if (sky)
            {
                ll.Add(left);
            }
            else
            {
                ll.Subtract(left);
            }

            ll.Add(bottom);

            Vector3d lr = center.Copy();

            if (sky)
            {
                lr.Add(right);
            }
            else
            {
                lr.Subtract(right);
            }
            lr.Add(bottom);

            points[0].Position = ul.Copy();
            points[0].Tu       = uv.Left;
            points[0].Tv       = uv.Top;
            //     points[0].Color = Color;

            points[2].Tu       = uv.Left;
            points[2].Tv       = uv.Bottom;
            points[2].Position = ll.Copy();
            //      points[2].Color = Color;

            points[1].Tu       = uv.Right;
            points[1].Tv       = uv.Top;
            points[1].Position = ur.Copy();
            //      points[1].Color = Color;

            points[3].Tu       = uv.Right;
            points[3].Tv       = uv.Bottom;
            points[3].Position = lr.Copy();
            //      points[3].Color = Color;

            points[5].Tu       = uv.Right;
            points[5].Tv       = uv.Top;
            points[5].Position = ur.Copy();
            //     points[5].Color = Color;

            points[4].Tu       = uv.Left;
            points[4].Tv       = uv.Bottom;
            points[4].Position = ll.Copy();
            //     points[4].Color = Color;

            if (Rotation != 0 || Tilt != 0 || Bank != 0)
            {
                if (!matInit)
                {
                    Matrix3d lookAt    = Matrix3d.LookAtLH(center, new Vector3d(), up);
                    Matrix3d lookAtInv = lookAt.Clone();
                    lookAtInv.Invert();

                    rtbMat = Matrix3d.MultiplyMatrix(Matrix3d.MultiplyMatrix(Matrix3d.MultiplyMatrix(Matrix3d.MultiplyMatrix(lookAt, Matrix3d.RotationZ(-Rotation / 180 * Math.PI)), Matrix3d.RotationX(-Tilt / 180 * Math.PI)), Matrix3d.RotationY(-Bank / 180 * Math.PI)), lookAtInv);
                    //todo make this true after debug
                    matInit = true;
                }
                for (int i = 0; i < 6; i++)
                {
                    points[i].Position = Vector3d.TransformCoordinate(points[i].Position, rtbMat);
                }
            }

            pointList.AddRange(points);
        }
Ejemplo n.º 33
0
        public void KojtoCAD_3D_Get_Teoretical_Bends_Centroid()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            Editor   ed = Application.DocumentManager.MdiActiveDocument.Editor;

            Matrix3d old = ed.CurrentUserCoordinateSystem;

            ed.CurrentUserCoordinateSystem = Matrix3d.Identity;

            try
            {
                PromptKeywordOptions pop = new PromptKeywordOptions("");
                pop.AppendKeywordsToMessage = true;
                pop.AllowNone = false;
                pop.Keywords.Add("Run");
                pop.Keywords.Add("Help");
                pop.Keywords.Default = "Run";
                PromptResult res = ed.GetKeywords(pop);
                //_AcAp.Application.ShowAlertDialog(res.ToString());
                if (res.Status == PromptStatus.OK)
                {
                    switch (res.StringResult)
                    {
                    case "Run":
                        if ((container != null) && (container.Bends.Count > 0))
                        {
                            quaternion qSum_Bends_Teor = new quaternion();
                            double     mass            = 0.0;
                            foreach (WorkClasses.Bend bend in container.Bends)
                            {
                                if (!bend.IsFictive())
                                {
                                    qSum_Bends_Teor += (bend.MidPoint * bend.Length);
                                    mass            += bend.Length;
                                }
                            }
                            if (mass > 0)
                            {
                                qSum_Bends_Teor /= mass;
                                //UtilityClasses.GlobalFunctions.DrawLine(new Point3d(1000, 1000, 0), (Point3d)qSum_Bends_Real, 3);
                                string title = "\nTeoretical Mesh Bends center of gravity\n------------------\n\n";
                                string mess  = string.Format("{0} total length: {1} \n Coordinate: {2:f5},{3:f5},{4:f5}", title, mass,
                                                             qSum_Bends_Teor.GetX(), qSum_Bends_Teor.GetY(), qSum_Bends_Teor.GetZ());
                                ed.WriteMessage(mess);

                                MessageBox.Show(mess, "Bends - teoretical mesh center of gravity", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                        }
                        else
                        {
                            MessageBox.Show("\nData Base Empty !\n\nMissing Bends !", "Range Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        break;

                    case "Help":
                        GlobalFunctions.OpenHelpHTML("http://3dsoft.blob.core.windows.net/kojtocad/html/MESH_CENTROID.htm");
                        break;
                    }
                }
            }
            catch (System.Exception ex)
            {
                Application.ShowAlertDialog(
                    string.Format("\nError: {0}\nStackTrace: {1}", ex.Message, ex.StackTrace));
            }
            finally { ed.CurrentUserCoordinateSystem = old; }
        }
Ejemplo n.º 34
0
            private void UpdateBlock()
            {
                Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                Autodesk.AutoCAD.DatabaseServices.Database    db  = doc.Database;

                Matrix3d ucs2wcs    = AcadUtility.AcadGraphics.UcsToWcs;
                Point3d  pBaseWorld = mpBase.TransformBy(ucs2wcs);
                Point3d  pTextWorld = mpText.TransformBy(ucs2wcs);

                BlockReference bref = Entity as BlockReference;

                bref.TransformBy(lastTransform.Inverse());
                for (int i = 0; i < bref.AttributeCollection.Count; i++)
                {
                    AttributeReference attRef = bref.AttributeCollection[i].GetObject(OpenMode.ForWrite) as AttributeReference;
                    string             text   = attRef.TextString;
                    attRef.SetAttributeFromBlock(mAttDict[attRef], bref.BlockTransform);
                    attRef.TextString = text;
                    attRef.AdjustAlignment(db);
                }

                bref.Position = pTextWorld;
                double scale = Math.Abs(bref.ScaleFactors[0]);

                // Mirror block if text is to the left of base point
                if (mpText.X < mpBase.X)
                {
                    using (Line3d mirrorLine = new Line3d(bref.Position, bref.Position + ucs2wcs.CoordinateSystem3d.Yaxis))
                    {
                        Matrix3d mirroring = Matrix3d.Mirroring(mirrorLine);
                        bref.TransformBy(mirroring);
                        lastTransform = mirroring;
                    }
                    for (int i = 0; i < bref.AttributeCollection.Count; i++)
                    {
                        AttributeReference attRef = bref.AttributeCollection[i].GetObject(OpenMode.ForWrite) as AttributeReference;
                        string             text   = attRef.TextString;
                        attRef.SetAttributeFromBlock(mAttDict[attRef], bref.BlockTransform);
                        attRef.TextString = text;
                        Extents3d ex       = attRef.GeometricExtents;
                        Point3d   midPoint = new Point3d((ex.MinPoint.X + ex.MaxPoint.X) / 2, (ex.MinPoint.Y + ex.MaxPoint.Y) / 2, (ex.MinPoint.Z + ex.MaxPoint.Z) / 2);
                        using (Line3d mirrorLine = new Line3d(midPoint, midPoint + ucs2wcs.CoordinateSystem3d.Yaxis))
                        {
                            Matrix3d mirroring = Matrix3d.Mirroring(mirrorLine);
                            attRef.TransformBy(mirroring);
                        }
                        attRef.AdjustAlignment(db);
                    }
                }
                else
                {
                    lastTransform = Matrix3d.Identity;
                }

                IntegerCollection vpNumbers = AcadUtility.AcadGraphics.GetActiveViewportNumbers();

                if (line == null)
                {
                    line = new Line();
                    TransientManager.CurrentTransientManager.AddTransient(line, TransientDrawingMode.DirectShortTerm, 0, vpNumbers);
                }
                line.StartPoint = pBaseWorld;
                line.EndPoint   = pTextWorld;
                TransientManager.CurrentTransientManager.UpdateTransient(line, vpNumbers);
            }
Ejemplo n.º 35
0
        public void KojtoCAD_3D_Get_Glass_Conturs_Centroid()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            Editor   ed = Application.DocumentManager.MdiActiveDocument.Editor;

            Matrix3d old = ed.CurrentUserCoordinateSystem;

            ed.CurrentUserCoordinateSystem = Matrix3d.Identity;

            try
            {
                PromptKeywordOptions pop = new PromptKeywordOptions("");
                pop.AppendKeywordsToMessage = true;
                pop.AllowNone = false;
                pop.Keywords.Add("Run");
                pop.Keywords.Add("Help");
                pop.Keywords.Default = "Run";
                PromptResult res = ed.GetKeywords(pop);
                //_AcAp.Application.ShowAlertDialog(res.ToString());
                if (res.Status == PromptStatus.OK)
                {
                    switch (res.StringResult)
                    {
                    case "Run":
                        if ((container != null) && (container.Bends.Count > 0) && (container.Nodes.Count > 0) && (container.Triangles.Count > 0))
                        {
                            double     area = 0.0;
                            quaternion cen  = new quaternion();
                            foreach (WorkClasses.Triangle TR in container.Triangles)
                            {
                                Triplet <quaternion, quaternion, quaternion> pr = container.GetInnererTriangle(TR.Numer, true);

                                double ar = Math.Abs(GlobalFunctions.GetArea(pr));

                                area += ar;
                                quaternion centroid = new quaternion();
                                centroid  = (pr.First + pr.Second) / 2.0;
                                centroid  = centroid - pr.Third;
                                centroid *= (2.0 / 3.0);
                                centroid  = pr.Third + centroid;
                                centroid *= ar;
                                cen      += centroid;
                            }
                            if (area > 0.0)
                            {
                                cen /= area;
                                string title = "\nTeoretical Mesh Glass Conturs center of gravity\n------------------\n\n";
                                string mess  = string.Format("{0} total area: {1} \n Coordinate: {2:f5},{3:f5},{4:f5}", title, area,
                                                             cen.GetX(), cen.GetY(), cen.GetZ());
                                ed.WriteMessage(mess);

                                MessageBox.Show(mess, "Glass Conturs - teoretical mesh center of gravity", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                        }
                        else
                        {
                            MessageBox.Show("\nData Base Empty !\n", "Range Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        break;

                    case "Help":
                        GlobalFunctions.OpenHelpHTML("http://3dsoft.blob.core.windows.net/kojtocad/html/SPOTS_CENTROID.htm");
                        break;
                    }
                }
            }
            catch (System.Exception ex)
            {
                Application.ShowAlertDialog(
                    string.Format("\nError: {0}\nStackTrace: {1}", ex.Message, ex.StackTrace));
            }
            finally { ed.CurrentUserCoordinateSystem = old; }
        }
Ejemplo n.º 36
0
        public void LevelLabel()
        {
            if (!CheckLicense.Check())
            {
                return;
            }

            if (!init)
            {
                if (!ShowSettings())
                {
                    return;
                }
            }

            while (true)
            {
                PromptPointOptions ptOpts = new PromptPointOptions("\nKot noktası: [Reset/Güncelle]", "Reset Update");
                PromptPointResult  ptRes  = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetPoint(ptOpts);
                if (ptRes.Status == PromptStatus.Cancel)
                {
                    return;
                }
                else if (ptRes.Status == PromptStatus.Keyword && ptRes.StringResult == "Reset")
                {
                    Reset();
                    return;
                }
                else if (ptRes.Status == PromptStatus.Keyword && ptRes.StringResult == "Update")
                {
                    PromptSelectionResult selRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetSelection();
                    if (selRes.Status != PromptStatus.OK)
                    {
                        return;
                    }

                    UpdateLevelBlocks(selRes.Value.GetObjectIds());
                    return;
                }
                else
                {
                    Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                    Autodesk.AutoCAD.DatabaseServices.Database    db  = doc.Database;

                    ObjectId blockId = ObjectId.Null;
                    using (Transaction tr = db.TransactionManager.StartTransaction())
                        using (BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead))
                        {
                            if (bt.Has(BlockName))
                            {
                                blockId = bt[BlockName];
                            }
                            tr.Commit();
                        }
                    if (blockId.IsNull)
                    {
                        MessageBox.Show("Kot bloğu '" + BlockName + "' bulunamadı.", "Level", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    string level = GetLevel(ptRes.Value);

                    Matrix3d ucs2wcs  = AcadUtility.AcadGraphics.UcsToWcs;
                    Point3d  ptWorld  = ptRes.Value.TransformBy(ucs2wcs);
                    double   rotation = Math.Atan2(ucs2wcs.CoordinateSystem3d.Xaxis.Y, ucs2wcs.CoordinateSystem3d.Xaxis.X);

                    using (Transaction tr = db.TransactionManager.StartTransaction())
                        using (BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite))
                        {
                            BlockReference bref = new BlockReference(ptWorld, blockId);
                            bref.Rotation     = rotation;
                            bref.ScaleFactors = new Scale3d(BlockScale);

                            btr.AppendEntity(bref);
                            tr.AddNewlyCreatedDBObject(bref, true);

                            Dictionary <AttributeReference, AttributeDefinition> dict = new Dictionary <AttributeReference, AttributeDefinition>();

                            BlockTableRecord blockDef = tr.GetObject(blockId, OpenMode.ForRead) as BlockTableRecord;
                            foreach (ObjectId id in blockDef)
                            {
                                AttributeDefinition attDef = tr.GetObject(id, OpenMode.ForRead) as AttributeDefinition;
                                if ((attDef != null) && (!attDef.Constant))
                                {
                                    // Create a new AttributeReference
                                    AttributeReference attRef = new AttributeReference();
                                    dict.Add(attRef, attDef);
                                    attRef.SetAttributeFromBlock(attDef, bref.BlockTransform);
                                    attRef.TextString = level;
                                    bref.AttributeCollection.AppendAttribute(attRef);
                                    tr.AddNewlyCreatedDBObject(attRef, true);
                                }
                            }

                            if (LevelJig.Jig(ptRes.Value, bref, dict))
                            {
                                Line line = new Line();
                                line.StartPoint = ptWorld;
                                line.EndPoint   = bref.Position;

                                btr.AppendEntity(line);
                                tr.AddNewlyCreatedDBObject(line, true);

                                tr.Commit();
                            }
                            else
                            {
                                bref.Dispose();
                                tr.Abort();
                                return;
                            }
                        }
                }
            }
        }
Ejemplo n.º 37
0
 // 按照参照线 镜像实体
 public static void mirrorByLine3d(this Entity entity,Line3d line3d) {
     Matrix3d mt = Matrix3d.Mirroring(line3d);
     entity.TransformBy(mt);
 }
Ejemplo n.º 38
0
        private void ComputeOrbital(RenderContext11 renderContext)
        {
            CAAEllipticalObjectElements ee = Elements;
            Vector3d point = CAAElliptical.CalculateRectangular(SpaceTimeController.JNow, ee, out MeanAnomoly);

            Vector3d pointInstantLater = CAAElliptical.CalculateRectangular(ee, MeanAnomoly + .001);

            Vector3d direction = point - pointInstantLater;

            direction.Normalize();
            Vector3d up = point;

            up.Normalize();
            direction.Normalize();

            double dist        = point.Length();
            double scaleFactor = 1.0;

            switch (SemiMajorAxisUnits)
            {
            case AltUnits.Meters:
                scaleFactor = 1.0;
                break;

            case AltUnits.Feet:
                scaleFactor = 1.0 / 3.2808399;
                break;

            case AltUnits.Inches:
                scaleFactor = (1.0 / 3.2808399) / 12;
                break;

            case AltUnits.Miles:
                scaleFactor = 1609.344;
                break;

            case AltUnits.Kilometers:
                scaleFactor = 1000;
                break;

            case AltUnits.AstronomicalUnits:
                scaleFactor = UiTools.KilometersPerAu * 1000;
                break;

            case AltUnits.LightYears:
                scaleFactor = UiTools.AuPerLightYear * UiTools.KilometersPerAu * 1000;
                break;

            case AltUnits.Parsecs:
                scaleFactor = UiTools.AuPerParsec * UiTools.KilometersPerAu * 1000;
                break;

            case AltUnits.MegaParsecs:
                scaleFactor = UiTools.AuPerParsec * UiTools.KilometersPerAu * 1000 * 1000000;
                break;

            case AltUnits.Custom:
                scaleFactor = 1;
                break;

            default:
                break;
            }
            scaleFactor *= 1 / renderContext.NominalRadius;


            Matrix3d look = Matrix3d.LookAtLH(new Vector3d(0, 0, 0), direction, up);

            look.Invert();

            WorldMatrix = Matrix3d.Identity;
            WorldMatrix.Translate(Translation);


            double localScale = (1 / renderContext.NominalRadius) * Scale * MeanRadius;

            WorldMatrix.Scale(new Vector3d(localScale, localScale, localScale));
            WorldMatrix.Rotate(Quaternion.RotationYawPitchRoll((float)((Heading) / 180.0 * Math.PI), (float)(Pitch / 180.0 * Math.PI), (float)(Roll / 180.0 * Math.PI)));
            if (RotationalPeriod != 0)
            {
                double rotationCurrent = (((SpaceTimeController.JNow - this.ZeroRotationDate) / RotationalPeriod) * Math.PI * 2) % (Math.PI * 2);
                WorldMatrix.Multiply(Matrix3d.RotationX(-rotationCurrent));
            }

            point = Vector3d.Scale(point, scaleFactor);

            WorldMatrix.Translate(point);

            if (StationKeeping)
            {
                WorldMatrix = look * WorldMatrix;
            }
        }
Ejemplo n.º 39
0
 protected void InsertArrowBlRef(Point3d ptArrowBlPos, Point3d ptArrowDirect, bool doTrans, Matrix3d trans)
 {
     // Вставка стрелки и направление ее на указанную точку
      if (!panelBase.Service.Env.IdBtrArrow.IsNull)
      {
     if (doTrans)
     {
        ptArrowBlPos = ptArrowBlPos.TransformBy(trans);
        ptArrowDirect = ptArrowDirect.TransformBy(trans);
     }
     // вставка блока стрелки
     var blRefArrow = CreateBlRefInBtrDim(ptArrowBlPos, panelBase.Service.Env.IdBtrArrow, Settings.Default.SheetScale);
     if (blRefArrow == null) return;
     // поворот стрелки и установка длины
     Vector2d vecArrow = ptArrowDirect.Convert2d() - ptArrowBlPos.Convert2d();
     blRefArrow.Rotation = vecArrow.Angle;
     // длина стрелки
     setDynParam(blRefArrow, "Длина", vecArrow.Length);
      }
 }
Ejemplo n.º 40
0
        /// <summary>
        /// 视图缩放
        /// </summary>
        /// <param name="ed">命令行对象</param>
        /// <param name="ptMin">要显示区域的左下角点</param>
        /// <param name="ptMax">要显示区域的右上角点</param>
        /// <param name="ptCenter">要显示区域的中心点</param>
        /// <param name="factor">缩放比例</param>
        public static void Zoom(this Editor ed, Point3d ptMin, Point3d ptMax, Point3d ptCenter, double factor)
        {
            Extents3d extents;
            Document  doc    = ed.Document;
            Database  db     = doc.Database;
            int       cvport = Convert.ToInt32(Application.GetSystemVariable("CVPORT"));

            if (db.TileMode == true)
            {
                if (ptMin.Equals(Point3d.Origin) == true && ptMax.Equals(Point3d.Origin) == true)
                {
                    ptMin = db.Extmin;
                    ptMax = db.Extmax;
                }
            }
            else
            {
                if (cvport == 1)
                {
                    if (ptMin.Equals(Point3d.Origin) == true && ptMax.Equals(Point3d.Origin) == true)
                    {
                        ptMin = db.Pextmin;
                        ptMax = db.Pextmax;
                    }
                }
                else
                {
                    if (ptMin.Equals(Point3d.Origin) == true && ptMax.Equals(Point3d.Origin) == true)
                    {
                        ptMin = db.Extmin;
                        ptMax = db.Extmax;
                    }
                }
            }
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                ViewTableRecord view       = ed.GetCurrentView();
                Matrix3d        matWCS2DCS = view.Wcs2Dcs();
                if (ptCenter.DistanceTo(Point3d.Origin) != 0)
                {
                    ptMin = new Point3d(ptCenter.X - view.Width / 2, ptCenter.Y - view.Height / 2, 0);
                    ptMax = new Point3d(ptCenter.X + view.Width / 2, ptCenter.Y + view.Height / 2, 0);
                }
                using (Line line = new Line(ptMin, ptMax))
                {
                    extents = new Extents3d(line.GeometricExtents.MinPoint, line.GeometricExtents.MaxPoint);
                }
                double viewRatio = view.Width / view.Height;
                extents.TransformBy(matWCS2DCS);
                double  width, height;
                Point2d newCenter;
                if (ptCenter.DistanceTo(Point3d.Origin) != 0)
                {
                    width  = view.Width;
                    height = view.Height;
                    if (factor == 0)
                    {
                        ptCenter = ptCenter.TransformBy(matWCS2DCS);
                    }
                    newCenter = new Point2d(ptCenter.X, ptCenter.Y);
                }
                else
                {
                    width     = extents.MaxPoint.X - extents.MinPoint.X;
                    height    = extents.MaxPoint.Y - extents.MinPoint.Y;
                    newCenter = new Point2d((extents.MaxPoint.X + extents.MinPoint.X) * 0.5, (extents.MaxPoint.Y + extents.MinPoint.Y) * 0.5);
                }
                if (width > height * viewRatio)
                {
                    height = width / viewRatio;
                }
                if (factor != 0)
                {
                    view.Height = height * factor;
                    view.Width  = width * factor;
                }
                view.CenterPoint = newCenter;
                ed.SetCurrentView(view);
                trans.Commit();
            }
        }
Ejemplo n.º 41
0
        protected void SizesLeft(bool doTrans, Matrix3d trans)
        {
            var heightTile = Settings.Default.TileHeight + Settings.Default.TileSeam;
             // y последней плитки
             var countTile = Convert.ToInt32((panelBase.Height - heightTile) / heightTile);
             var yLastTile = countTile * heightTile;

             Point3d ptBotLeft = new Point3d(panelBase.XMinPanel, 0, 0);
             Point3d ptTopLeft = new Point3d(ptBotLeft.X, yLastTile, 0);

             xDimLineLeftMin = ptBotLeft.X-indentDimLineFromDraw;
             Point3d ptDimLine = new Point3d(xDimLineLeftMin, 0, 0);

             var dim= CreateDim(ptBotLeft, ptTopLeft, ptDimLine, doTrans, trans, rotation: 90);
             dim.Prefix = $"({Settings.Default.TileHeight}+{Settings.Default.TileSeam})x{countTile}=";

             Point3d ptLastTile = new Point3d(ptTopLeft.X, ptTopLeft.Y + Settings.Default.TileHeight, 0);
             dim = CreateDim(ptTopLeft, ptLastTile, ptDimLine, doTrans, trans, rotation:90);
             Point3d ptText = new Point3d(ptDimLine.X, ptTopLeft.Y - 65, 0);
             dim.TextPosition = doTrans? ptText.TransformBy(trans): ptText;
        }
Ejemplo n.º 42
0
        public void GeneratePlan(Point3d location)
        {
            Standard.Apply(this);

            var pLines  = new List <Polyline>();
            var acDoc   = Application.DocumentManager.MdiActiveDocument;
            var acCurDb = acDoc.Database;

            //Sort pipe connections for ease of drawing
            var sortedPipes = IncomingPipes.OrderBy(p => p.Angle).ToList();

            using (var tr = acCurDb.TransactionManager.StartTransaction())
            {
                var offset = location.GetAsVector().Subtract(IntersectionPoint.GetAsVector());

                //Calculate alternate connection point
                Circle   slopeCircle    = new Circle(location, Vector3d.ZAxis, 450);
                Vector3d slopeIntersect = location.GetVectorTo(OutgoingConnection.Location.Add(offset));
                slopeIntersect = slopeIntersect * 450 / slopeIntersect.Length;
                Point2d slopePoint2D = new Point2d(location.Add(slopeIntersect).X, location.Add(slopeIntersect).Y);

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

                // Open the Block table record Model space for write
                BlockTableRecord acBlkTblRec;
                acBlkTblRec = tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                acCurDb.RegisterLayer(Constants.LAYER_PIPE_WALLS_NAME, Constants.LAYER_PIPE_WALLS_COLOR);
                acCurDb.RegisterLayer(Constants.LAYER_PIPE_CENTRE_LINE_NAME, Constants.LAYER_PIPE_CENTRE_LINE_COLOR, Constants.LAYER_PIPE_CENTRE_LINE_TYPE);
                acCurDb.RegisterLayer(Constants.LAYER_MANHOLE_WALL_NAME, Constants.LAYER_MANHOLE_WALL_COLOR);
                acCurDb.RegisterLayer(Constants.LAYER_MANHOLE_FURNITURE_NAME, Constants.LAYER_MANHOLE_FURNITURE_COLOR);

                Circle pipeIntrusion = new Circle(location, Vector3d.ZAxis, (double)(Diameter / 2) - 150f);

                //Outgoing line
                Polyline outgoingLine = new Polyline();
                outgoingLine.AddVertexAt(0, new Point2d(location.X, location.Y), 0, 0, 0);
                outgoingLine.AddVertexAt(1, new Point2d(OutgoingConnection.Location.Add(offset).X, OutgoingConnection.Location.Add(offset).Y), 0, 0, 0);
                outgoingLine.Layer = Constants.LAYER_PIPE_CENTRE_LINE_NAME;

                Polyline outgoingoffsetPlus = outgoingLine.GetOffsetCurves(OutgoingConnection.Diameter / 2)[0] as Polyline;
                outgoingoffsetPlus.Layer = Constants.LAYER_PIPE_WALLS_NAME;
                Polyline outgoingoffsetMinus = outgoingLine.GetOffsetCurves(-OutgoingConnection.Diameter / 2)[0] as Polyline;
                outgoingoffsetMinus.Layer = Constants.LAYER_PIPE_WALLS_NAME;

                //Add descriptive text
                var outLabel = new MText
                {
                    Location   = new Point3d(OutgoingConnection.Location.Add(offset).X, OutgoingConnection.Location.Add(offset).Y, 0),
                    Contents   = OutgoingConnection.Code + "\\P" + OutgoingConnection.Diameter + "%%C",
                    TextHeight = 40
                };

                outLabel.AlignTo(outgoingLine);
                acBlkTblRec.AppendEntity(outLabel);
                tr.AddNewlyCreatedDBObject(outLabel, true);

                //Pipe walls
                Polyline outouteroffsetPlus = outgoingLine.GetOffsetCurves(OutgoingConnection.Diameter / 2 + 20f)[0] as Polyline;
                outouteroffsetPlus.Layer = Constants.LAYER_PIPE_WALLS_NAME;
                Point3dCollection intersection = new Point3dCollection();
                outouteroffsetPlus.IntersectWith(pipeIntrusion, Intersect.ExtendArgument, intersection, IntPtr.Zero, IntPtr.Zero);
                outouteroffsetPlus.AddVertexAt(0, new Point2d(intersection[0].X, intersection[0].Y), 0, 0, 0);
                outouteroffsetPlus.RemoveVertexAt(1);

                Polyline outouteroffsetMinus = outgoingLine.GetOffsetCurves(-OutgoingConnection.Diameter / 2 - 20f)[0] as Polyline;
                outouteroffsetMinus.Layer = Constants.LAYER_PIPE_WALLS_NAME;
                intersection = new Point3dCollection();
                outouteroffsetMinus.IntersectWith(pipeIntrusion, Intersect.ExtendArgument, intersection, IntPtr.Zero, IntPtr.Zero);
                outouteroffsetMinus.AddVertexAt(0, new Point2d(intersection[0].X, intersection[0].Y), 0, 0, 0);
                outouteroffsetMinus.RemoveVertexAt(1);

                Polyline outcloseWall = new Polyline();
                outcloseWall.AddVertexAt(0, new Point2d(outouteroffsetMinus.StartPoint.X, outouteroffsetMinus.StartPoint.Y), 0, 0, 0);
                outcloseWall.AddVertexAt(0, new Point2d(outouteroffsetPlus.StartPoint.X, outouteroffsetPlus.StartPoint.Y), 0, 0, 0);
                outcloseWall.Layer = Constants.LAYER_PIPE_WALLS_NAME;

                acBlkTblRec.AppendEntity(outgoingLine);
                tr.AddNewlyCreatedDBObject(outgoingLine, true);

                acBlkTblRec.AppendEntity(outouteroffsetMinus);
                tr.AddNewlyCreatedDBObject(outouteroffsetMinus, true);
                acBlkTblRec.AppendEntity(outouteroffsetPlus);
                tr.AddNewlyCreatedDBObject(outouteroffsetPlus, true);
                acBlkTblRec.AppendEntity(outcloseWall);
                tr.AddNewlyCreatedDBObject(outcloseWall, true);

                Polyline lastLine = outgoingoffsetPlus;

                for (int i = 0; i < sortedPipes.Count(); i++)
                {
                    PipeConnection pipeConnection = sortedPipes.ToArray()[i];

                    //Create centreline
                    Polyline newLine = new Polyline();//location, pipeConnection.Location.Add(offset)
                    newLine.AddVertexAt(0, new Point2d(location.X, location.Y), 0, 0, 0);
                    newLine.AddVertexAt(1, new Point2d(pipeConnection.Location.Add(offset).X, pipeConnection.Location.Add(offset).Y), 0, 0, 0);
                    newLine.Layer = Constants.LAYER_PIPE_CENTRE_LINE_NAME;

                    //Add descriptive text
                    var label = new MText
                    {
                        Location = new Point3d(pipeConnection.Location.Add(offset).X, pipeConnection.Location.Add(offset).Y, 0),
                        Contents = pipeConnection.Code + "\\P" + pipeConnection.Diameter + "%%C"
                    };


                    acBlkTblRec.AppendEntity(label);
                    tr.AddNewlyCreatedDBObject(label, true);

                    label.TextHeight = 40;
                    label.AlignTo(newLine);

                    //Pipe walls
                    Polyline outeroffsetPlus = newLine.GetOffsetCurves(pipeConnection.Diameter / 2 + 20f)[0] as Polyline;
                    outeroffsetPlus.Layer = Constants.LAYER_PIPE_WALLS_NAME;
                    intersection          = new Point3dCollection();
                    outeroffsetPlus.IntersectWith(pipeIntrusion, Intersect.ExtendArgument, intersection, IntPtr.Zero, IntPtr.Zero);
                    outeroffsetPlus.AddVertexAt(0, new Point2d(intersection[0].X, intersection[0].Y), 0, 0, 0);
                    outeroffsetPlus.RemoveVertexAt(1);

                    Polyline outeroffsetMinus = newLine.GetOffsetCurves(-pipeConnection.Diameter / 2 - 20f)[0] as Polyline;
                    outeroffsetMinus.Layer = Constants.LAYER_PIPE_WALLS_NAME;
                    intersection           = new Point3dCollection();
                    outeroffsetMinus.IntersectWith(pipeIntrusion, Intersect.ExtendArgument, intersection, IntPtr.Zero, IntPtr.Zero);
                    outeroffsetMinus.AddVertexAt(0, new Point2d(intersection[0].X, intersection[0].Y), 0, 0, 0);
                    outeroffsetMinus.RemoveVertexAt(1);

                    Polyline closeWall = new Polyline();
                    closeWall.AddVertexAt(0, new Point2d(outeroffsetMinus.StartPoint.X, outeroffsetMinus.StartPoint.Y), 0, 0, 0);
                    closeWall.AddVertexAt(0, new Point2d(outeroffsetPlus.StartPoint.X, outeroffsetPlus.StartPoint.Y), 0, 0, 0);
                    closeWall.Layer = Constants.LAYER_PIPE_WALLS_NAME;


                    //Check that angle is ok
                    //Skip the check if this is the only incoming pipe
                    if (sortedPipes.Count() > 1)
                    {
                        if (pipeConnection.Angle < 135 || pipeConnection.Angle > 225)
                        {
                            //Angle exceeds 45° so change
                            Point3dCollection slopeIntersectCollection = new Point3dCollection();
                            newLine.IntersectWith(slopeCircle, Intersect.ExtendArgument, slopeIntersectCollection, IntPtr.Zero, IntPtr.Zero);
                            Point3d circleIntersectPoint = slopeIntersectCollection[0];
                            newLine.AddVertexAt(1, new Point2d(circleIntersectPoint.X, circleIntersectPoint.Y), 0, 0, 0);

                            newLine.SetPointAt(0, slopePoint2D);
                        }
                    }

                    Polyline offsetPlus = newLine.GetOffsetCurves(pipeConnection.Diameter / 2)[0] as Polyline;
                    offsetPlus.Layer = Constants.LAYER_PIPE_WALLS_NAME;
                    Polyline offsetMinus = newLine.GetOffsetCurves(-pipeConnection.Diameter / 2)[0] as Polyline;
                    offsetMinus.Layer = Constants.LAYER_PIPE_WALLS_NAME;

                    //Fillet
                    Point3dCollection collection = new Point3dCollection();
                    offsetMinus.IntersectWith(lastLine, Intersect.ExtendBoth, collection, IntPtr.Zero, IntPtr.Zero);

                    //Check that the lines do intersect, may not if small pipe to large when parallel
                    if (collection.Count > 0)
                    {
                        var inter = collection[0];
                        lastLine.SetPointAt(0, new Point2d(inter.X, inter.Y));
                        offsetMinus.SetPointAt(0, new Point2d(inter.X, inter.Y));
                    }

                    acBlkTblRec.AppendEntity(newLine);
                    tr.AddNewlyCreatedDBObject(newLine, true);

                    lastLine.JoinEntity(offsetMinus);
                    pLines.Add(lastLine);

                    acBlkTblRec.AppendEntity(outeroffsetMinus);
                    tr.AddNewlyCreatedDBObject(outeroffsetMinus, true);
                    acBlkTblRec.AppendEntity(outeroffsetPlus);
                    tr.AddNewlyCreatedDBObject(outeroffsetPlus, true);

                    acBlkTblRec.AppendEntity(closeWall);
                    tr.AddNewlyCreatedDBObject(closeWall, true);

                    lastLine = offsetPlus;
                }

                Point3dCollection lastCollection = new Point3dCollection();
                outgoingoffsetMinus.IntersectWith(lastLine, Intersect.ExtendBoth, lastCollection, IntPtr.Zero, IntPtr.Zero);

                if (lastCollection.Count > 0)
                {
                    Point3d lastIntersection = lastCollection[0]; //No intersection throwing error???
                    lastLine.SetPointAt(0, new Point2d(lastIntersection.X, lastIntersection.Y));
                    outgoingoffsetMinus.SetPointAt(0, new Point2d(lastIntersection.X, lastIntersection.Y));
                }

                lastLine.JoinEntity(outgoingoffsetMinus);
                pLines.Add(lastLine);

                foreach (var line in pLines)
                {
                    line.FilletAll();
                    acBlkTblRec.AppendEntity(line);
                    tr.AddNewlyCreatedDBObject(line, true);
                }

                //Create rings
                var innerManhole = new Circle(location, Vector3d.ZAxis, Diameter / 2)
                {
                    Layer = Constants.LAYER_MANHOLE_WALL_NAME
                };
                acBlkTblRec.AppendEntity(innerManhole);
                tr.AddNewlyCreatedDBObject(innerManhole, true);

                //Calculate best location for steps and check minimum benching
                double maxAngle   = 0;
                int    maxSegment = 0;

                double minAngle   = double.MaxValue;
                int    minSegment = 0;

                double previousAngle = 0;
                for (int i = 0; i < sortedPipes.Count(); i++)
                {
                    PipeConnection pc = sortedPipes.ToArray()[i];

                    double anglebetween = pc.Angle - previousAngle;
                    previousAngle += pc.Angle;

                    if (anglebetween > maxAngle)
                    {
                        maxAngle   = anglebetween;
                        maxSegment = i;
                    }

                    if (anglebetween < maxAngle)
                    {
                        maxAngle   = anglebetween;
                        maxSegment = i;
                    }
                }

                PipeConnection edgeSegment = sortedPipes.ToArray()[maxSegment];
                double         stepCenter  = edgeSegment.Angle - maxAngle / 2;

                //check the last segment is not better
                PipeConnection endSegment = sortedPipes.ToArray().Last();
                double         lastAngle  = 360 - endSegment.Angle;
                if (lastAngle > maxAngle)
                {
                    stepCenter = 360 - lastAngle / 2;
                }

                Polyline stepCenterLine = new Polyline();
                stepCenterLine.AddVertexAt(0, new Point2d(outgoingLine.StartPoint.X, outgoingLine.StartPoint.Y), 0, 0, 0);
                stepCenterLine.AddVertexAt(1, new Point2d(outgoingLine.EndPoint.X, outgoingLine.EndPoint.Y), 0, 0, 0);

                Matrix3d           curUCSMatrix = acDoc.Editor.CurrentUserCoordinateSystem;
                CoordinateSystem3d curUCS       = curUCSMatrix.CoordinateSystem3d;

                // Rotate the polyline 45 degrees, around the Z-axis of the current UCS
                // using a base point of (4,4.25,0)
                stepCenterLine.TransformBy(Matrix3d.Rotation(stepCenter * Math.PI / 180, -curUCS.Zaxis, stepCenterLine.StartPoint));

                /*acBlkTblRec.AppendEntity(stepCenterLine);
                 * tr.AddNewlyCreatedDBObject(stepCenterLine, true);*/


                //TODO: Needs reviewing - as it need to be kept?
                //TODO: Make sure this works and allow for pipe widths not centre lines

                /*//Calculate both intersection points
                 * (Vector3d majorBenching, Vector3d minorBenching) = CalculateBenching(stepCenterLine, innerManhole);
                 *
                 *
                 * if (minorBenching.Length < MinimumMinorBenching)
                 * {
                 *  Vector3d adjustment = minorBenching * (MinimumMinorBenching / minorBenching.Length);
                 *  innerManhole.Center = innerManhole.Center.Add(adjustment);
                 *  (majorBenching, minorBenching) = CalculateBenching(stepCenterLine, innerManhole);
                 * }
                 *
                 * if (majorBenching.Length < MinimumMajorBenching)
                 * {
                 *  if (minorBenching.Length > MinimumMinorBenching)
                 *  {
                 *      Vector3d adjustment = minorBenching * (MinimumMinorBenching / minorBenching.Length);
                 *      innerManhole.Center = innerManhole.Center.Add(adjustment);
                 *      (majorBenching, minorBenching) = CalculateBenching(stepCenterLine, innerManhole);
                 *
                 *      if (majorBenching.Length < MinimumMajorBenching)
                 *      {
                 *          throw new ArgumentException("Major benching does not meet minimum distances");
                 *      }
                 *  }
                 *
                 *  throw new ArgumentException("Major benching does not meet minimum distances");
                 * }*/

                //Create rings now offset is fixed
                var outerManhole = new Circle(location, Vector3d.ZAxis, Diameter / 2 + WallThickness)
                {
                    Layer = Constants.LAYER_MANHOLE_WALL_NAME
                };
                acBlkTblRec.AppendEntity(outerManhole);
                tr.AddNewlyCreatedDBObject(outerManhole, true);

                var outerSurround = new Circle(location, Vector3d.ZAxis, Diameter / 2 + WallThickness + 100f)
                {
                    Layer = Constants.LAYER_MANHOLE_WALL_NAME
                };
                acBlkTblRec.AppendEntity(outerSurround);
                tr.AddNewlyCreatedDBObject(outerSurround, true);


                //Generate manhole cover
                var cover = GenerateManholeCover(stepCenterLine, innerManhole);
                cover.Layer = Constants.LAYER_MANHOLE_FURNITURE_NAME;
                acBlkTblRec.AppendEntity(cover);
                tr.AddNewlyCreatedDBObject(cover, true);

                //Generate manhole step
                var step = GenerateManholeStep(stepCenterLine, innerManhole);
                foreach (var entity in step)
                {
                    entity.Layer = Constants.LAYER_MANHOLE_FURNITURE_NAME;
                    acBlkTblRec.AppendEntity(entity);
                    tr.AddNewlyCreatedDBObject(entity, true);
                }

                //Generate benching
                var bench = GenerateBenching(stepCenterLine, innerManhole, pLines);
                foreach (var entity in bench)
                {
                    entity.Layer = Constants.LAYER_MANHOLE_FURNITURE_NAME;
                    acBlkTblRec.AppendEntity(entity);
                    tr.AddNewlyCreatedDBObject(entity, true);
                }

                //Add safety features
                if (SafetyChain)
                {
                    throw new NotImplementedException();
                }
                if (SafetyRail)
                {
                    throw new NotImplementedException();
                }

                //Generate Table
                var tbLocation = new Point3d(location.X + (1800 * 1.1), location.Y + 450, 0);
                var tb         = GenerateTable(this, tbLocation);
                acBlkTblRec.AppendEntity(tb);
                tr.AddNewlyCreatedDBObject(tb, true);

                var height = outgoingLine.Length * 2;
                var width  = outgoingLine.Length + tb.Width + (tbLocation.X - location.X);
                LayoutHeight = height * SCALE * 1.1;
                LayoutWidth  = width * SCALE * 1.1;
                var shift = (width / 2) - outgoingLine.Length;
                Centre = new Point3d(location.X + shift, location.Y, 0);
                //Finalize
                tr.Commit();
            }
        }
Ejemplo n.º 43
0
        protected void SizesTop(bool doTrans, Matrix3d trans)
        {
            bool hasInterDim = panelBase.PtsForTopDim.Count > 0 || panelBase.XMinPanel < 0 || panelBase.XMaxPanel > panelBase.Length;

             // Общий размер
             Point3d ptTopLeft = new Point3d(panelBase.XMinContour, panelBase.Height, 0);
             Point3d ptTopRight = new Point3d(panelBase.XMaxContour, panelBase.Height, 0);
             yDimLineTopMax = hasInterDim ? panelBase.Height + indentBetweenDimLine + indentDimLineFromDraw : panelBase.Height + indentDimLineFromDraw;
             Point3d ptDimLineTotal = new Point3d(0, yDimLineTopMax, 0);
             CreateDim(ptTopLeft, ptTopRight, ptDimLineTotal, doTrans, trans, rangeSize: rangeSizeHor);
             // добавление промежуточных размеров
             if (hasInterDim)
             {
            panelBase.PtsForTopDim.Sort();
            AcadLib.Comparers.DoubleEqualityComparer comparer = new AcadLib.Comparers.DoubleEqualityComparer(4);
            var ptsX = panelBase.PtsForTopDim.GroupBy(p => p, comparer).Select(g => g.First());

            Point3d ptPrev = ptTopLeft;
            Point3d ptDimLineInter = new Point3d(0, yDimLineTopMax - indentBetweenDimLine, 0);
            foreach (var x in ptsX)
            {
               Point3d ptNext = new Point3d(x, ptPrev.Y, 0);
               CreateDim(ptPrev, ptNext, ptDimLineInter, doTrans, trans, rangeSize: rangeSizeHor);
               ptPrev = ptNext;
            }
            // Замыкающий размер
            CreateDim(ptPrev, ptTopRight, ptDimLineInter, doTrans, trans, rangeSize: rangeSizeHor);

            //если есть пустые области Outsides, то добавление промежеточных размеров.
            if (Math.Abs(panelBase.XMinPanel - panelBase.XMinContour)>100)
            {
               CreateDim(new Point3d(panelBase.XMinPanel, ptPrev.Y, 0),
                         new Point3d(panelBase.XMinContour, ptPrev.Y, 0), ptDimLineInter, doTrans, trans);
            }
            if (Math.Abs(panelBase.XMaxPanel - panelBase.XMaxContour) > 100)
            {
               CreateDim(new Point3d(panelBase.XMaxContour, ptPrev.Y, 0),
                         new Point3d(panelBase.XMaxPanel, ptPrev.Y, 0), ptDimLineInter, doTrans, trans);
            }
             }
        }
Ejemplo n.º 44
0
        public void drawSpring()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            //??ask about gauge of spring back vs seat
            //seat 8 gauge .1285"
            //back 12 gauge .0808"

            #region get ends of spring to get total distance
            //ask user for points for spring to exist
            PromptPointOptions ppo = new PromptPointOptions("First end of spring:");
            PromptPointResult  ppr = ed.GetPoint(ppo);
            if (ppr.Status != PromptStatus.OK)
            {
                return;
            }
            Point3d startPoint = ppr.Value;

            ppo.Message = "Second end of spring";
            ppr         = ed.GetPoint(ppo);
            if (ppr.Status != PromptStatus.OK)
            {
                return;
            }

            //calculate distance from chosen points
            #endregion
            double totalLength = startPoint.DistanceTo(ppr.Value);

            #region get spring Type (length)
            //given total length, calculate ideal spring length which is total minus some percentage
            double theorySpgLength = (Math.Round(.9 * totalLength * 2)) / 2;
            //find the nearest spring length that is less than or equal to total length(springs tend to come in 1/2" increments)
            //compare to list of spring lengths in stock **(eventually get springs from SQL)

            //present any springs withen an accaptable margin of diviation (maybe 8%)??
            //if none are easily exceptable but might work within a special circumstance, present that with warning (10%)??
            //if none are accaptable at all, then give different warning and end command (user will need to move spring rail or order diff springs)

            //**idealy replace with a user dialoge to choose from springs in system
            //ask user for spring length desired(may prompt with options from list) based on orignal distance
            PromptDoubleOptions pdo = new PromptDoubleOptions("Enter spring length:");
            //needs to pull these dynamically***************
            pdo.Keywords.Add(theorySpgLength.ToString());
            pdo.Keywords.Add((theorySpgLength - .5).ToString());
            PromptDoubleResult pdr = ed.GetDouble(pdo);
            if (pdr.Status != PromptStatus.OK)
            {
                return;
            }
            #endregion
            double springLength = pdr.Value;

            #region Create top view of spring
            //1 Calculate rungs
            //spring length / average gap
            int    rungCount = Convert.ToInt32(springLength / .875);//guessing at the avg rung gap for starters
            double rungGap   = totalLength / rungCount;
            double rungWidth = 2 - rungGap;
            //springs tend to be approx 2" wide
            //rung widths are 2" - rung gap (the two radii of bends)

            //add all parts to object collection then convert to polyline
            DBObjectCollection springParts = new DBObjectCollection();
            //construct first rung (has hooked end)
            springParts = createEnd(springParts, startPoint, rungGap, rungWidth, true, true);

            //construct rungs/bends in middle
            //and bends on alternating runs
            for (int i = 0; i < rungCount; i++)
            {
                Line rung = new Line(
                    new Point3d(startPoint.X - rungWidth / 2, startPoint.Y + i * rungGap, startPoint.Z),
                    new Point3d(startPoint.X + rungWidth / 2, startPoint.Y + i * rungGap, startPoint.Z));
                //add rungs except for either end
                if (i != 0 && i != rungCount)
                {
                    springParts.Add(rung);
                }

                //add bends to either side depending on if it is an even or odd rung
                if (i % 2 == 0)
                {
                    //even
                    Arc leftBend = new Arc(new Point3d(startPoint.X - 1 + rungGap / 2, startPoint.Y + rungGap * i + rungGap / 2, startPoint.Z), rungGap / 2, Math.PI / 2, 3 * Math.PI / 2);
                    springParts.Add(leftBend);
                }
                else
                {
                    //odd
                    Arc rightBend = new Arc(new Point3d(startPoint.X + 1 - rungGap / 2, startPoint.Y + rungGap * i + rungGap / 2, startPoint.Z), rungGap / 2, 3 * Math.PI / 2, Math.PI / 2);
                    springParts.Add(rightBend);
                }
            }

            //construct end
            //if rungCount is even it opens same as first
            bool secondOpen = true;
            if (rungCount % 2 == 0)
            {
                secondOpen = false;
            }
            springParts = createEnd(springParts, new Point3d(startPoint.X, startPoint.Y + totalLength, startPoint.Z), rungGap, rungWidth, secondOpen, false);

            ////just for testing **
            //using (Transaction trans = db.TransactionManager.StartTransaction())
            //{
            //    BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable;
            //    BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
            //    foreach (DBObject dbo in springParts)
            //    {
            //        Entity ent = dbo as Entity;
            //        btr.AppendEntity(ent);
            //        trans.AddNewlyCreatedDBObject(ent, true);
            //    }

            //    trans.Commit();
            //}

            Polyline pLine = BuildPLine.drawPolyLine(springParts);

            //move spring polyline to the correct Z coordinate, converting to a polyline cuts off z coords leaving it at 0****
            //***************************
            #endregion

            #region create side view (crown)
            //need to account for creating arc along different plane
            //arc is start point, and then total length vertical from first point (same plane) *we'll rotate later
            //for now all springs will use same crown, need a formula later and need an element that accounts for flat vs curly springs
            //create arc flat along same plane as spring polyline, then rotate it??
            Arc     crown    = new Arc();
            Point3d startArc = new Point3d(startPoint.X - 2, startPoint.Y, startPoint.Z);
            Point3d endArc   = new Point3d(startArc.X, startArc.Y + totalLength, startArc.Z);
            Point3d arcMid   = new Point3d(startArc.X - 1.5, startArc.Y + (totalLength / 2), startArc.Z);

            //assuming crown is 1.5 until we derive a diff system
            //radius = height/2 + width^2/height(8)
            crown.Radius = .75 + (Math.Pow(startArc.DistanceTo(endArc), 2) / 12);

            //given that we always will have our arc aligned vertically center is easter to calculate
            crown.Center = new Point3d(arcMid.X + crown.Radius, arcMid.Y, arcMid.Z);

            Matrix3d ocs2wcs = Matrix3d.PlaneToWorld(crown.Normal);
            Plane    plane   = new Plane(ocs2wcs.CoordinateSystem3d.Origin, ocs2wcs.CoordinateSystem3d.Xaxis, ocs2wcs.CoordinateSystem3d.Yaxis);

            //need start and end angles
            //double startAngle = tanAngle(arcCenter, startArc);
            //double endAngle = tanAngle(arcCenter, endArc);
            crown.EndAngle   = (startArc - crown.Center).AngleOnPlane(plane);
            crown.StartAngle = (endArc - crown.Center).AngleOnPlane(plane);

            //Arc crown = new Arc(arcCenter,radius,startAngle,endAngle);

            // Rotate the 3D solid 30 degrees around the axis that is defined by the points
            Vector3d turnArc = crown.StartPoint.GetVectorTo(crown.EndPoint);
            crown.TransformBy(Matrix3d.Rotation(3 * (Math.PI / 2), turnArc, crown.StartPoint));

            #endregion

            //convert collection to polyline
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTable       bt  = tr.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable;
                BlockTableRecord btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                //Have to have both views inserted to turn into extruded surface
                btr.AppendEntity(pLine);
                tr.AddNewlyCreatedDBObject(pLine, true);
                btr.AppendEntity(crown);
                tr.AddNewlyCreatedDBObject(crown, true);

                #region Extrude surfaces from open curves, polylines
                //extrude two shapes
                Profile3d    profileCrown  = new Profile3d(crown);
                Profile3d    profileSpring = new Profile3d(pLine);
                Vector3d     polylineDir   = new Vector3d(0, 0, 4);
                Vector3d     crownDir      = (crown.StartPoint).GetVectorTo(new Point3d(crown.StartPoint.X + 4, crown.StartPoint.Y, crown.StartPoint.Z));
                SweepOptions sweepOp       = new SweepOptions();

                //need a different vector for crown
                ObjectId surfaceId = Autodesk.AutoCAD.DatabaseServices.Surface.CreateExtrudedSurface(
                    profileCrown, crownDir, sweepOp, true);
                ObjectId surfaceSpringId = Autodesk.AutoCAD.DatabaseServices.Surface.CreateExtrudedSurface(
                    profileSpring, polylineDir, sweepOp, true);

                //remove original lines
                pLine.Erase(true);
                crown.Erase(true);
                #endregion

                //intersect both regions(observe how extrusions work with ucs)
                Autodesk.AutoCAD.DatabaseServices.Surface crownEnt  = tr.GetObject(surfaceId, OpenMode.ForWrite) as Autodesk.AutoCAD.DatabaseServices.Surface;
                Autodesk.AutoCAD.DatabaseServices.Surface springEnt = tr.GetObject(surfaceSpringId, OpenMode.ForWrite) as Autodesk.AutoCAD.DatabaseServices.Surface;
                //convert both surfaces to nurbs
                //the polyline extrusion creates many surfaces in nurb form, loop through intersections creating splines and lines
                springParts = Intersect_Surfaces.IntersectSurf(crownEnt, springEnt);
                //delete surfaces
                crownEnt.Erase(true);
                springEnt.Erase(true);

                //join intersection pieces as spline (maynot be possible)
                //convert collection of splines/lines to single 3Dspline
                Spline springSpline = Intersect_Surfaces.mergeSpline(springParts);
                btr.AppendEntity(springSpline);
                tr.AddNewlyCreatedDBObject(springSpline, true);

                //loft along spline
                try
                {
                    //create circle to to sweep
                    Circle wireGauge = new Circle();
                    wireGauge.Center = springSpline.StartPoint;
                    wireGauge.Radius = .06425;//diameter .1285
                    //Entity sweepEnt = tr.GetObject();

                    Curve pathEnt = tr.GetObject(springSpline.Id, OpenMode.ForRead) as Curve;
                    //Curve pathEnt = tr.GetObject(pLine.Id, OpenMode.ForRead) as Curve;
                    if (wireGauge == null || pathEnt == null)
                    {
                        ed.WriteMessage("\nProblem getting spline made");
                        return;
                    }

                    //builder object to create sweepoptions
                    SweepOptionsBuilder sob = new SweepOptionsBuilder();

                    //align the entity to sweep to the path
                    sob.Align = SweepOptionsAlignOption.AlignSweepEntityToPath;

                    //the base point is the start of the path
                    sob.BasePoint = pathEnt.StartPoint;

                    //the profile will rotate to follow the path
                    sob.Bank = true;

                    Entity  ent;
                    Solid3d sol = new Solid3d();
                    sol.CreateSweptSolid(wireGauge, pathEnt, sob.ToSweepOptions());
                    ent = sol;

                    //and add it to the modelspace
                    btr.AppendEntity(ent);
                    tr.AddNewlyCreatedDBObject(ent, true);
                }
                catch { }

                //re-align spring to first points chosen by user
                tr.Commit();
            }
        }
Ejemplo n.º 45
0
 private void addCheekViewText(bool doTrans, Matrix3d trans, double xMinCheek)
 {
     // Текст с именем вида
      DBText textView = new DBText();
      textView.TextString = "Вид А";
      textView.Height = 75;
      Point3d ptTextPos = new Point3d(xMinCheek, panelBase.Height + 170, 0);
      if (doTrans)
      {
     ptTextPos = ptTextPos.TransformBy(trans);
     ptTextPos = new Point3d(ptTextPos.X - 290, ptTextPos.Y, 0);
      }
      textView.Position = ptTextPos;
      btrDim.AppendEntity(textView);
      t.AddNewlyCreatedDBObject(textView, true);
 }
Ejemplo n.º 46
0
        /// <summary>
        /// 绘制平立面
        /// </summary>
        /// <param name="db"></param>
        /// <param name="AnchorPoint"></param>
        public double PlotA(Database db, Point2d AnchorPoint, int ScaleA = 0)
        {
            Transaction      tr       = db.TransactionManager.StartTransaction();
            BlockTable       blockTbl = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
            BlockTableRecord ms       = tr.GetObject(blockTbl[BlockTableRecord.ModelSpace],
                                                     OpenMode.ForWrite) as BlockTableRecord;
            DimStyleTable dst = (DimStyleTable)tr.GetObject(db.DimStyleTableId, OpenMode.ForRead);

            if (ScaleA == 0)
            {
                ScaleA = GetScaleA();
            }
            double dy = ScaleA * -50;

            // 立面图
            ObjectId blkRecId = blockTbl["T321-1"];
            ObjectId HLJJ     = blockTbl["T321-HLJJ"];
            ObjectId QMB      = blockTbl["T321-QMB"];
            ObjectId HL       = blockTbl["T321-HL-C" + Columns.ToString()];
            ObjectId T321PM   = blockTbl["T321-2"];
            ObjectId XZ       = blockTbl["T321-XZ"];
            ObjectId QZC1     = blockTbl["T321-QZ-C1"];
            ObjectId QZC1R    = blockTbl["T321-QZ-C1R"];
            ObjectId QZC2     = blockTbl["T321-QZ-C2"];
            ObjectId QZC2R    = blockTbl["T321-QZ-C2R"];
            ObjectId ZBC1     = blockTbl["T321-ZB-C1"];
            ObjectId ZBC2     = blockTbl["T321-ZB-C2"];
            ObjectId ZBC3     = blockTbl["T321-ZB-C3"];
            ObjectId ZBC3L    = blockTbl["T321-ZB-C3L"];
            ObjectId ZCJ      = blockTbl["T321-ZCJ-2"];
            ObjectId KFLG     = blockTbl["T321-KFLG"];
            ObjectId QMB2     = blockTbl["T321-QMB-2"];
            ObjectId JQXG     = blockTbl["T321-JQXG"];

            // 立面桁架
            for (int i = 0; i < Pieces; i++)
            {
                for (int j = 0; j < Layers; j++)
                {
                    using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(0 + i * 3000, 0 + j * 1500), blkRecId))
                    {
                        ms.AppendEntity(acBlkRef);
                        tr.AddNewlyCreatedDBObject(acBlkRef, true);
                    }
                    if (IsEnhence && i != 0 && i != (Pieces - 1))
                    {
                        if (j == 0)
                        {
                            using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(0 + i * 3000, 0 + j * 1500 - 100), JQXG))
                            {
                                ms.AppendEntity(acBlkRef);
                                tr.AddNewlyCreatedDBObject(acBlkRef, true);
                            }
                        }
                        else if (j == Layers - 1)
                        {
                            using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(0 + i * 3000, 0 + j * 1500 + 1500), JQXG))
                            {
                                ms.AppendEntity(acBlkRef);
                                tr.AddNewlyCreatedDBObject(acBlkRef, true);
                            }
                        }
                    }



                    if (j == 0)
                    {
                        using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(1413 + i * 3000, 328), HLJJ))
                        {
                            ms.AppendEntity(acBlkRef);
                            tr.AddNewlyCreatedDBObject(acBlkRef, true);
                        }
                        using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(1413 + i * 3000, dy), HL))
                        {
                            ms.AppendEntity(acBlkRef);
                            tr.AddNewlyCreatedDBObject(acBlkRef, true);
                        }
                        using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(1413 + 1410 + i * 3000, 328), HLJJ))
                        {
                            ms.AppendEntity(acBlkRef);
                            tr.AddNewlyCreatedDBObject(acBlkRef, true);
                        }
                        using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(1413 + 1410 + i * 3000, dy), HL))
                        {
                            ms.AppendEntity(acBlkRef);
                            tr.AddNewlyCreatedDBObject(acBlkRef, true);
                        }
                        using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(1323 + i * 3000, 553), QMB))
                        {
                            ms.AppendEntity(acBlkRef);
                            tr.AddNewlyCreatedDBObject(acBlkRef, true);
                        }
                    }
                }
            }
            blkRecId = blockTbl["T321-ZCJ-1"];
            double offsetZCJ = 0.0;

            if (Columns != 1)
            {
                for (int i = 0; i < Pieces; i++)
                {
                    if (IsEnhence)
                    {
                        if (i == 0 || i == (Pieces - 1))
                        {
                            offsetZCJ = 0;
                        }
                        else
                        {
                            offsetZCJ = 100;
                        }
                    }
                    using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(910 + i * 3000, (Layers) * 1500 - 70 + offsetZCJ), blkRecId))
                    {
                        ms.AppendEntity(acBlkRef);
                        tr.AddNewlyCreatedDBObject(acBlkRef, true);
                    }
                }
            }

            blkRecId = blockTbl["T321-YTDZ"];
            using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(), blkRecId))
            {
                ms.AppendEntity(acBlkRef);
                tr.AddNewlyCreatedDBObject(acBlkRef, true);
            }
            blkRecId = blockTbl["T321-HL-1"];
            using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(-157, 58), blkRecId))
            {
                ms.AppendEntity(acBlkRef);
                tr.AddNewlyCreatedDBObject(acBlkRef, true);
            }
            using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(-157, dy), HL))
            {
                ms.AppendEntity(acBlkRef);
                tr.AddNewlyCreatedDBObject(acBlkRef, true);
            }



            blkRecId = blockTbl["T321-ITDZ"];
            using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(Pieces * 3000.0), blkRecId))
            {
                ms.AppendEntity(acBlkRef);
                tr.AddNewlyCreatedDBObject(acBlkRef, true);
            }
            blkRecId = blockTbl["T321-QZ"];
            using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(Pieces * 3000.0 + 37, -145), blkRecId))
            {
                ms.AppendEntity(acBlkRef);
                tr.AddNewlyCreatedDBObject(acBlkRef, true);
            }
            using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(-37, -145), blkRecId))
            {
                ms.AppendEntity(acBlkRef);
                tr.AddNewlyCreatedDBObject(acBlkRef, true);
            }
            blkRecId = blockTbl["T321-ZB"];
            using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(Pieces * 3000.0 + 37, -297), blkRecId))
            {
                ms.AppendEntity(acBlkRef);
                tr.AddNewlyCreatedDBObject(acBlkRef, true);
            }
            using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(-37, -297), blkRecId))
            {
                ms.AppendEntity(acBlkRef);
                tr.AddNewlyCreatedDBObject(acBlkRef, true);
            }


            // 平面桁架
            for (int k = 0; k < 2; k++)
            {
                double sidey = (-4200) * k;
                int    dir   = k == 0 ? 1 : -1;
                for (int i = 0; i < Columns; i++)
                {
                    double cy;
                    if (i == 0)
                    {
                        cy = 0;
                    }
                    else if (i == 1)
                    {
                        cy = dir * 450;
                    }
                    else
                    {
                        cy = (450 + 250) * dir;
                    }

                    for (int j = 0; j < Pieces; j++)
                    {
                        using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(j * 3000, dy - 825 + sidey + cy), T321PM))
                        {
                            ms.AppendEntity(acBlkRef);
                            tr.AddNewlyCreatedDBObject(acBlkRef, true);
                        }
                        if (j != 0)
                        {
                            using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(j * 3000, dy - 825 + sidey + cy - 75.3), XZ))
                            {
                                ms.AppendEntity(acBlkRef);
                                tr.AddNewlyCreatedDBObject(acBlkRef, true);
                            }
                        }
                        if (i == 0)
                        {
                            if (Columns != 1)
                            {
                                using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(j * 3000 + 910, dy - 825 + sidey + dir * 450), ZCJ))
                                {
                                    if (dir == -1)
                                    {
                                        acBlkRef.TransformBy(Matrix3d.Mirroring(new Line3d(
                                                                                    AnchorPoint.Convert3D(j * 3000 + 910, dy - 825 + sidey + dir * 450),
                                                                                    AnchorPoint.Convert3D(j * 3000 + 910 + 100, dy - 825 + sidey + dir * 450)
                                                                                    )));
                                    }
                                    ms.AppendEntity(acBlkRef);
                                    tr.AddNewlyCreatedDBObject(acBlkRef, true);
                                }
                            }
                            if (k == 0)
                            {
                                if (j < 0.5 * Pieces)
                                {
                                    using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(j * 3000 + 329, dy - 825 + sidey), KFLG))
                                    {
                                        ms.AppendEntity(acBlkRef);
                                        tr.AddNewlyCreatedDBObject(acBlkRef, true);
                                    }
                                }
                                else
                                {
                                    using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(j * 3000 + 2821, dy - 825 + sidey - 180), QMB2))
                                    {
                                        ms.AppendEntity(acBlkRef);
                                        tr.AddNewlyCreatedDBObject(acBlkRef, true);
                                    }
                                }
                            }
                        }
                    }
                }

                if (Columns == 1)
                {
                    using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(-37, dy - 825 + sidey), QZC1))
                    {
                        ms.AppendEntity(acBlkRef);
                        tr.AddNewlyCreatedDBObject(acBlkRef, true);
                    }
                    using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(Pieces * 3000 + 37, dy - 825 + sidey), QZC1R))
                    {
                        ms.AppendEntity(acBlkRef);
                        tr.AddNewlyCreatedDBObject(acBlkRef, true);
                    }
                    using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(-37, dy - 825 + sidey), ZBC1))
                    {
                        acBlkRef.TransformBy(Matrix3d.Mirroring(new Line3d(
                                                                    AnchorPoint.Convert3D(-37, dy - 825 + sidey),
                                                                    AnchorPoint.Convert3D(-37, dy - 825 + sidey + 100)
                                                                    )));
                        ms.AppendEntity(acBlkRef);
                        tr.AddNewlyCreatedDBObject(acBlkRef, true);
                    }
                    using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(37 + Pieces * 3000, dy - 825 + sidey), ZBC1))
                    {
                        ms.AppendEntity(acBlkRef);
                        tr.AddNewlyCreatedDBObject(acBlkRef, true);
                    }
                }

                else if (Columns == 2)
                {
                    using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(-37, dy - 825 + sidey), QZC1))
                    {
                        ms.AppendEntity(acBlkRef);
                        tr.AddNewlyCreatedDBObject(acBlkRef, true);
                    }
                    using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(-37, dy - 825 + sidey + dir * 450), QZC1))
                    {
                        ms.AppendEntity(acBlkRef);
                        tr.AddNewlyCreatedDBObject(acBlkRef, true);
                    }
                    using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(Pieces * 3000 + 37, dy - 825 + sidey), QZC1R))
                    {
                        ms.AppendEntity(acBlkRef);
                        tr.AddNewlyCreatedDBObject(acBlkRef, true);
                    }
                    using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(Pieces * 3000 + 37, dy - 825 + sidey + dir * 450), QZC1R))
                    {
                        ms.AppendEntity(acBlkRef);
                        tr.AddNewlyCreatedDBObject(acBlkRef, true);
                    }
                    using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(Pieces * 3000 + 37, dy - 825 + sidey + dir * 225), ZBC2))
                    {
                        ms.AppendEntity(acBlkRef);
                        tr.AddNewlyCreatedDBObject(acBlkRef, true);
                    }
                    using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(-37, dy - 825 + sidey + dir * 225), ZBC2))
                    {
                        acBlkRef.TransformBy(Matrix3d.Mirroring(new Line3d(AnchorPoint.Convert3D(-37, dy - 825 + sidey + dir * 225), AnchorPoint.Convert3D(-37, dy - 825 + sidey + dir * 225 + 100))));
                        ms.AppendEntity(acBlkRef);
                        tr.AddNewlyCreatedDBObject(acBlkRef, true);
                    }
                }
                else
                {
                    using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(-37, dy - 825 + sidey), QZC1))
                    {
                        ms.AppendEntity(acBlkRef);
                        tr.AddNewlyCreatedDBObject(acBlkRef, true);
                    }
                    using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(-37, dy - 825 + sidey + dir * (450 + 125)), QZC2))
                    {
                        ms.AppendEntity(acBlkRef);
                        tr.AddNewlyCreatedDBObject(acBlkRef, true);
                    }
                    using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(Pieces * 3000 + 37, dy - 825 + sidey), QZC1R))
                    {
                        ms.AppendEntity(acBlkRef);
                        tr.AddNewlyCreatedDBObject(acBlkRef, true);
                    }
                    using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(Pieces * 3000 + 37, dy - 825 + sidey + dir * (450 + 125)), QZC2R))
                    {
                        ms.AppendEntity(acBlkRef);
                        tr.AddNewlyCreatedDBObject(acBlkRef, true);
                    }

                    using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(Pieces * 3000 + 37, dy - 825 + sidey + dir * 350), ZBC3))
                    {
                        ms.AppendEntity(acBlkRef);
                        tr.AddNewlyCreatedDBObject(acBlkRef, true);
                    }

                    using (BlockReference acBlkRef = new BlockReference(AnchorPoint.Convert3D(-37, dy - 825 + sidey + dir * 350), ZBC3))
                    {
                        acBlkRef.TransformBy(Matrix3d.Mirroring(new Line3d(
                                                                    AnchorPoint.Convert3D(-37, dy - 825 + sidey + dir * 350),
                                                                    AnchorPoint.Convert3D(-37, dy - 825 + sidey + dir * 350 + 100)
                                                                    )));
                        if (dir == -1)
                        {
                            acBlkRef.TransformBy(Matrix3d.Mirroring(new Line3d(
                                                                        AnchorPoint.Convert3D(-37, dy - 825 + sidey + dir * 350),
                                                                        AnchorPoint.Convert3D(-37 + 100, dy - 825 + sidey + dir * 350)
                                                                        )));
                        }
                        ms.AppendEntity(acBlkRef);
                        tr.AddNewlyCreatedDBObject(acBlkRef, true);
                    }
                }
            }
            tr.Commit();
            tr.Dispose();

            // 标注


            var     DimStyleID = dst["1-" + ScaleA.ToString()];
            Point3d SW         = AnchorPoint.Convert3D();
            Point3d SE         = AnchorPoint.Convert3D(Pieces * 3000.0);
            Point3d NW         = SW.Convert3D(0, Layers * 1400 + (Layers - 1) * 100);
            Point3d NE         = SE.Convert3D(0, Layers * 1400 + (Layers - 1) * 100);
            Point3d CT         = NW.Convert3D(0.5 * Pieces * 3000.0);

            Point3d pNW = SW.Convert3D(0, dy - 825);
            Point3d pNE = SE.Convert3D(0, dy - 825);
            Point3d pSW = pNW.Convert3D(0, -4200);
            Point3d pSE = pNE.Convert3D(0, -4200);
            Point3d pCT = pNW.Convert3D(0.5 * Pieces * 3000.0);

            string stmp = string.Format("{0}×3000=<>", Pieces);

            DimPloter.Dim0(db, NW, NE, NE.Convert3D(0, 10 * ScaleA), DimStyleID, 0, stmp);
            DimPloter.Dim0(db, SW, NW, NW.Convert3D(-10 * ScaleA), DimStyleID, 0.5 * Math.PI);
            DimPloter.Dim0(db, SE, SE.Convert3D(0, 1400), SE.Convert3D(8 * ScaleA), DimStyleID, 0.5 * Math.PI);
            for (int i = 0; i < Layers - 1; i++)
            {
                DimPloter.Dim0(db, SE.Convert3D(0, 1500 * (i + 1) - 100), SE.Convert3D(0, 1500 * (i + 1)), SE.Convert3D(8 * ScaleA), DimStyleID, 0.5 * Math.PI);
                DimPloter.Dim0(db, SE.Convert3D(0, 1500 * (i + 1)), SE.Convert3D(0, 1500 * (i + 1) + 1400), SE.Convert3D(8 * ScaleA), DimStyleID, 0.5 * Math.PI);
            }
            DimPloter.Dim0(db, pSW, pSE, pSW.Convert3D(0, -15 * ScaleA), DimStyleID);
            DimPloter.Dim0(db, pSW, pNW, pNW.Convert3D(-10 * ScaleA), DimStyleID, 0.5 * Math.PI);

            double ymin = pSW.Convert3D(0, -15 * ScaleA).Y;

            // 图名

            TextPloter.PrintTitle(db, "立 面", CT.Convert2D(0, 25 * ScaleA), ScaleA);
            TextPloter.PrintTitle(db, "平 面", pCT.Convert2D(0, 20 * ScaleA), ScaleA);
            double ymax = CT.Convert2D(0, 25 * ScaleA).Y;

            return(ymax - AnchorPoint.Y);
        }
Ejemplo n.º 47
0
        /// <summary>
        /// Вставка блока профиля и стрелок к местам установки профиля на стыке плиток в торце панели
        /// </summary>
        protected void addProfileTile(bool doTrans, Matrix3d trans)
        {
            double xPtProfile = 0;
             double yPtProfile = 0;
             double xPtArrowDirect = 0;
             if (panelBase.IsCheekLeft)
             {
            // Для торца слева - профиль вставляется в одну и туже точку (-400,-600)
            xPtProfile = -400;
            yPtProfile = -600;
            ptPosArrowToHorSec = ptPosHorizontalPanelSection;
             }
             else if (panelBase.IsCheekRight)
             {
            // Для торца справа - на раст (400,600) от нижнего правого края последней плитки
            xPtProfile = panelBase.XMaxContour + 400;
            yPtProfile = -600;
            xPtArrowDirect = panelBase.XMaxContour;
            ptPosArrowToHorSec = new Point3d(panelBase.XMaxContour, ptPosHorizontalPanelSection.Y, 0);
             }
             else
             {
            // Не нужен профиль для панелей без торцов (Cheek)
            return;
             }

             // Поиск блока профиля в инвентаре
             BlockInfo biProfile = panelBase.Service.Env.BlocksInFacade.FirstOrDefault(b => b.BlName.Equals(Settings.Default.BlockProfileTile));
             if (biProfile == null)
             {
            return;
             }

             ObjectId idBtrProfile = biProfile.IdBtr;
             // Точка вставки блока профиля
             ptPosProfile = new Point3d(xPtProfile, yPtProfile, 0);
             Point3d ptBlrefProfile = ptPosProfile;
             if (doTrans)
             {
            ptBlrefProfile = ptPosProfile.TransformBy(trans);
             }

             // Вставка блока профиля - название и марка
             var blRefProfile = CreateBlRefInBtrDim(ptBlrefProfile, idBtrProfile, Settings.Default.SheetScale);
             if (blRefProfile == null) return;

             // Добавление атрибутов Названия и марки
             // Атрибут Названия - из вхождения атрибута
             var atrRefName = biProfile.AttrsRef.FirstOrDefault(a => a.Tag.Equals("НАЗВАНИЕ"));
             if (atrRefName != null)
             {
            // определение атрибута
            var atrDefName = biProfile.AttrsDef.FirstOrDefault(a => a.Tag.Equals("НАЗВАНИЕ"));
            if (atrDefName != null)
            {
               AddAttrToBlockRef(blRefProfile, atrDefName.IdAtr, atrRefName.Text);
            }
             }
             // Атрибут Марки - из вхождения атрибута
             var atrRefMark = biProfile.AttrsRef.FirstOrDefault(a => a.Tag.Equals("МАРКА"));
             if (atrRefMark != null)
             {
            // определение атрибута
            var atrDefMark = biProfile.AttrsDef.FirstOrDefault(a => a.Tag.Equals("МАРКА"));
            if (atrDefMark != null)
            {
               AddAttrToBlockRef(blRefProfile, atrDefMark.IdAtr, atrRefMark.Text);
            }
             }

             // Вставка стрелки до угла панели
             Point3d ptArrowPos = new Point3d(xPtProfile, yPtProfile + 4 * Settings.Default.SheetScale, 0);
             Point3d ptArrowDirect = new Point3d(xPtArrowDirect, 0, 0);
             InsertArrowBlRef(ptArrowPos, ptArrowDirect, doTrans, trans);
        }
Ejemplo n.º 48
0
        /// <summary>
        ///     TODO
        /// </summary>
        /// <param name="face"></param>
        /// <returns></returns>
        public static Matrix3d GetLayMatrix(this Face face)
        {
            Matrix3d layMat;
            double   x;
            double   y;
            Vector3d yVector;
            Vector3d zVector;
            Matrix3d matX;
            Vector3d matY;

            if (face.IsNull)
            {
                layMat = new Matrix3d();
                return(layMat);
            }

            try
            {
                using (var surface = face.Surface)
                {
                    if (surface == null || !(surface is ExternalBoundedSurface))
                    {
                        layMat = new Matrix3d();
                    }
                    else
                    {
                        var externalBoundedSurface = surface as ExternalBoundedSurface;
                        var envelope    = externalBoundedSurface.GetEnvelope();
                        var lowerBound  = envelope[0].LowerBound;
                        var lowerBound1 = envelope[1].LowerBound;
                        var point2D     = new Point2d(lowerBound, lowerBound1);
                        using (var pointOnSurface = new PointOnSurface(externalBoundedSurface, point2D))
                        {
                            var uDerivative = pointOnSurface.GetNormal();
                            var point       = pointOnSurface.GetPoint();
                            x = !externalBoundedSurface.IsClosedInU(CalcTol.CadTolerance)
                                ? envelope[0].UpperBound
                                : (envelope[0].LowerBound + envelope[0].UpperBound) / 2;
                            y = !externalBoundedSurface.IsClosedInV(CalcTol.CadTolerance)
                                ? envelope[1].UpperBound
                                : (envelope[1].LowerBound + envelope[1].UpperBound) / 2;
                            var point3D   = pointOnSurface.GetPoint(new Point2d(x, lowerBound1));
                            var vectorTo  = point.GetVectorTo(point3D);
                            var point1    = pointOnSurface.GetPoint(new Point2d(lowerBound, y));
                            var vectorTo1 = point.GetVectorTo(point1);
                            if (vectorTo.Length < SettingsUser.TolPoint)
                            {
                                if (vectorTo1.Length >= SettingsUser.TolPoint)
                                {
                                    vectorTo  = vectorTo1;
                                    vectorTo1 = new Vector3d();
                                }
                                else
                                {
                                    matX   = new Matrix3d();
                                    layMat = matX;
                                    return(layMat);
                                }
                            }

                            if (vectorTo.Length < vectorTo1.Length)
                            {
                                var vector3D2 = vectorTo;
                                vectorTo  = vectorTo1;
                                vectorTo1 = vector3D2;
                            }

                            var angleTo = vectorTo.GetAngleTo(uDerivative);
                            if (angleTo < SettingsInternal.TolVector || Math.PI - angleTo < SettingsInternal.TolVector)
                            {
                                uDerivative = pointOnSurface.GetUDerivative(1, point2D);
                            }
                            var xVec = vectorTo.GetNormal();
                            if (uDerivative.Length >= SettingsUser.TolPoint)
                            {
                                zVector = uDerivative.GetNormal();
                                matY    = uDerivative.CrossProduct(vectorTo);
                                yVector = matY.GetNormal();
                                matY    = xVec.CrossProduct(yVector);
                                zVector = matY.GetNormal();
                            }
                            else if (vectorTo1.Length >= SettingsUser.TolPoint)
                            {
                                var angleTo1 = vectorTo.GetAngleTo(uDerivative);
                                if (angleTo1 < SettingsInternal.TolVector ||
                                    Math.PI - angleTo1 < SettingsInternal.TolVector)
                                {
                                    matX   = new Matrix3d();
                                    layMat = matX;
                                    return(layMat);
                                }

                                yVector = vectorTo1.GetNormal();
                                matY    = vectorTo.CrossProduct(vectorTo1);
                                zVector = matY.GetNormal();
                                matY    = zVector.CrossProduct(xVec);
                                yVector = matY.GetNormal();
                            }
                            else
                            {
                                matX   = new Matrix3d();
                                layMat = matX;
                                return(layMat);
                            }

                            layMat = Matrix3d.AlignCoordinateSystem(point, xVec, yVector, zVector, Point3d.Origin,
                                                                    Vector3d.XAxis, Vector3d.YAxis, Vector3d.ZAxis);
                        }
                    }
                }
            }
            catch
            {
                matX   = new Matrix3d();
                layMat = matX;
            }

            return(layMat);
        }
Ejemplo n.º 49
0
 public void XDataTransformBy(Matrix3d transform)
 {
     createInstance();
     BaseDBObject.XDataTransformBy(transform);
     tr.Dispose();
 }
Ejemplo n.º 50
0
            protected override bool WorldDraw(Autodesk.AutoCAD.GraphicsInterface.WorldDraw draw)
            {
                //throw new System.Exception("The method or operation is not implemented.");

                Entitied.Clear();
                Entity enti = null;

                if (PartOneIsActive)
                {
                    //CenterPoint02 = new Point3d(CenterPoint01.X + 40, CenterPoint01.Y, CenterPoint01.Z);
                    //Matrix3d trans1 = Matrix3d.Scaling(MyScale, new Point3d(CenterPoint01.X, CenterPoint01.Y, 0));
                    //Matrix3d trans2 = Matrix3d.Scaling(MyScale, new Point3d(CenterPoint02.X, CenterPoint02.Y, 0));

                    //enti = DrawConsol(CenterPoint01, 10, 10);
                    //enti.TransformBy(trans1);
                    //Entitied.Add(enti);

                    //Entitied.Add(DrawLine(CenterPoint01, CenterPoint02));

                    //enti = DrawRod(CenterPoint02, 6, 6);
                    //enti.TransformBy(trans2);
                    //Entitied.Add(enti);

                    //enti = DrawTriangle(CenterPoint02);
                    //enti.TransformBy(trans2);
                    //Entitied.Add(enti);
                }
                else
                {
                    Line     l        = new Line(CenterPoint01, CenterPoint02);
                    double   newAngle = l.Angle;
                    Matrix3d trans1   = Matrix3d.Scaling(MyScale, new Point3d(CenterPoint01.X, CenterPoint01.Y, 0));
                    Matrix3d trans2   = Matrix3d.Scaling(MyScale, new Point3d(CenterPoint02.X, CenterPoint02.Y, 0));

                    //enti = DrawConsol(CenterPoint01, 10, 10);
                    //enti.TransformBy(trans1);
                    //Entitied.Add(enti);

                    Entitied.Add(DrawLine(CenterPoint01, CenterPoint02));

                    enti = DrawCircle(CenterPoint02, 6);
                    enti.TransformBy(trans2);
                    Entitied.Add(enti);

                    //enti = DrawTriangle(CenterPoint02);
                    //enti.TransformBy(trans2);
                    //Entitied.Add(enti);
                }

                ////~~~~~~~~ SCALE ~~~~~~~~~~

                //Matrix3d trans1 = Matrix3d.Scaling(MyScale, new Point3d(CenterPoint01.X, CenterPoint01.Y, 0));
                //foreach (Entity en in Entitied)
                //{
                //    en.TransformBy(trans1);
                //}

                ////~~~~~~~~~~~~~~~~~~~~~~~~~


                foreach (Entity ent in Entitied)
                {
                    draw.Geometry.Draw(ent);
                }


                return(true);
            }
Ejemplo n.º 51
0
 public void GetObjectSnapPoints(ObjectSnapModes snapMode, int gsSelectionMark, Point3d pickPoint, Point3d lastPoint, Matrix3d viewTransform, Point3dCollection snapPoints, IntegerCollection geometryIds, Matrix3d insertionMat)
 {
     createInstance();
     BaseEntity.GetObjectSnapPoints(snapMode, gsSelectionMark, pickPoint, lastPoint, viewTransform, snapPoints, geometryIds, insertionMat);
     tr.Dispose();
 }
Ejemplo n.º 52
0
        public static void RotateLight(double LastAngleDegree, double NewAngleDegree, ObjectId PoleOI, ObjectId LightOI, Point3d CenterPoint)
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;

            using (DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument())
            {
                Database db = Application.DocumentManager.MdiActiveDocument.Database;
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    ObjectIdCollection LightSub = Atend.Global.Acad.UAcad.GetGroupSubEntities(LightOI);

                    foreach (ObjectId oi in LightSub)
                    {
                        //Atend.Base.Acad.AT_INFO KhazanSubInfo = Atend.Base.Acad.AT_INFO.SelectBySelectedObjectId(oi);
                        //if (KhazanSubInfo.ParentCode != "NONE" && KhazanSubInfo.NodeType == (int)Atend.Control.Enum.PLightuctType.ConsolElse)
                        //{
                        Entity ent = tr.GetObject(oi, OpenMode.ForWrite) as Entity;
                        if (ent != null)
                        {
                            ////Polyline LineEntity = ent as Polyline;
                            ////if (LineEntity != null)
                            ////{
                            //ed.WriteMessage("khazan entity found \n");
                            //KhazanOI = oi;
                            //Atend.Acad.AcadMove.LastCenterPoint = Atend.Global.Acad.UAcad.CenterOfEntity(Atend.Global.Acad.UAcad.GetEntityByObjectID(oi));
                            Matrix3d trans = Matrix3d.Rotation(((LastAngleDegree * Math.PI) / 180) * -1, ed.CurrentUserCoordinateSystem.CoordinateSystem3d.Zaxis, CenterPoint);
                            ent.TransformBy(trans);

                            trans = Matrix3d.Rotation(((NewAngleDegree * Math.PI) / 180), ed.CurrentUserCoordinateSystem.CoordinateSystem3d.Zaxis, CenterPoint);
                            ent.TransformBy(trans);

                            //Matrix3d m = new Matrix3d();
                            //Atend.Acad.AcadMove.ConsolOI = ConsolOI;
                            //Atend.Acad.AcadMove.isMoveConsolOnly = true;

                            ////}
                        }
                        //}
                    }

                    //ObjectId id = Atend.Global.Acad.UAcad.GetEntityGroup(LightOI);
                    //Atend.Base.Acad.AT_SUB EntityS = Atend.Base.Acad.AT_SUB.SelectBySelectedObjectId(id);
                    //foreach (ObjectId oisb in EntityS.SubIdCollection)
                    //{
                    //    Atend.Base.Acad.AT_INFO _Info = Atend.Base.Acad.AT_INFO.SelectBySelectedObjectId(oisb);
                    //    if (_Info.ParentCode != "NONE" && _Info.NodeType == (int)Atend.Control.Enum.ProductType.Comment)
                    //    {
                    //        Entity ent = tr.GetObject(oisb, OpenMode.ForWrite) as Entity;
                    //        if (ent != null)
                    //        {
                    //            Matrix3d trans = Matrix3d.Rotation(((LastAngleDegree * Math.PI) / 180) * -1, ed.CurrentUserCoordinateSystem.CoordinateSystem3d.Zaxis, CenterPoint);
                    //            ent.TransformBy(trans);
                    //            trans = Matrix3d.Rotation(((NewAngleDegree * Math.PI) / 180), ed.CurrentUserCoordinateSystem.CoordinateSystem3d.Zaxis, CenterPoint);
                    //            ent.TransformBy(trans);
                    //        }
                    //    }
                    //}
                    tr.Commit();
                    //Atend.Global.Acad.AcadMove.LightOI  = LightOI;
                    //Atend.Global.Acad.AcadMove.AllowToMove = true;
                    //Atend.Global.Acad.AcadMove.MoveLight(LightOI);
                }
            }
        }
Ejemplo n.º 53
0
 public Entity GetTransformedCopy(Matrix3d transform)
 {
     createInstance();
     Entity GetTransformedC = BaseEntity.GetTransformedCopy(transform);
     tr.Dispose();
     return GetTransformedC;
 }
Ejemplo n.º 54
0
 public void MakeMatrixes()
 {
     if (Fov + Aspect + OffsetX + OffsetY + Pitch + Heading + Roll + X + Y + Z + RadialAmountX + RadialAmountY + RadialCenterX + RadialCenterY != lastVals)
     {
         if (projectionType != ProjectionType.FishEye)
         {
             ProjMatrix = MakeProjection(near, far, Fov, Aspect, OffsetX, OffsetY);
         }
         TranMatrix = MakeTransform(Pitch, Heading, Roll, X, Y, Z);
         if (projectionType != ProjectionType.FishEye)
         {
             CamMatrix = TranMatrix * ProjMatrix;
         }
         lastVals = Fov + Aspect + OffsetX + OffsetY + Pitch + Heading + Roll + X + Y + Z + RadialAmountX + RadialAmountY + RadialCenterX + RadialCenterY;
     }
 }
Ejemplo n.º 55
0
 public void TransformSubentityPathsBy(FullSubentityPath[] subPaths, Matrix3d transform)
 {
     createInstance();
     BaseEntity.TransformSubentityPathsBy(subPaths, transform);
     tr.Dispose();
 }
Ejemplo n.º 56
0
 public AffineMatrix4d(Matrix3d mat, Vector3d vec)
 {
     this.a = mat[0];
     this.b = mat[1];
     this.c = mat[2];
     this.d = mat[3];
     this.e = mat[4];
     this.f = mat[5];
     this.g = mat[6];
     this.h = mat[7];
     this.i = mat[8];
     this.x = vec.x;
     this.y = vec.y;
     this.z = vec.z;
 }
        /// <summary>
        /// Transforms a point from a coordinate system to another one in the specified editor.
        /// </summary>
        /// <param name="pt">The instance to which the method applies.</param>
        /// <param name="ed">An instance of the Editor to which the method applies.</param>
        /// <param name="from">The origin coordinate system.</param>
        /// <param name="to">The target coordinate system.</param>
        /// <returns>The corresponding 3d point.</returns>
        /// <exception cref="Autodesk.AutoCAD.Runtime.Exception">
        /// eInvalidInput is thrown if CoordSystem.PSDCS is used with other than CoordSystem.DCS.</exception>
        public static Point3d Trans(this Point3d pt, Editor ed, CoordSystem from, CoordSystem to)
        {
            Matrix3d mat = new Matrix3d();

            switch (from)
            {
            case CoordSystem.WCS:
                switch (to)
                {
                case CoordSystem.UCS:
                    mat = ed.WCS2UCS();
                    break;

                case CoordSystem.DCS:
                    mat = ed.WCS2DCS();
                    break;

                case CoordSystem.PSDCS:
                    throw new AcRx.Exception(
                              AcRx.ErrorStatus.InvalidInput,
                              "To be used only with DCS");

                default:
                    mat = Matrix3d.Identity;
                    break;
                }
                break;

            case CoordSystem.UCS:
                switch (to)
                {
                case CoordSystem.WCS:
                    mat = ed.UCS2WCS();
                    break;

                case CoordSystem.DCS:
                    mat = ed.UCS2WCS() * ed.WCS2DCS();
                    break;

                case CoordSystem.PSDCS:
                    throw new AcRx.Exception(
                              AcRx.ErrorStatus.InvalidInput,
                              "To be used only with DCS");

                default:
                    mat = Matrix3d.Identity;
                    break;
                }
                break;

            case CoordSystem.DCS:
                switch (to)
                {
                case CoordSystem.WCS:
                    mat = ed.DCS2WCS();
                    break;

                case CoordSystem.UCS:
                    mat = ed.DCS2WCS() * ed.WCS2UCS();
                    break;

                case CoordSystem.PSDCS:
                    mat = ed.DCS2PSDCS();
                    break;

                default:
                    mat = Matrix3d.Identity;
                    break;
                }
                break;

            case CoordSystem.PSDCS:
                switch (to)
                {
                case CoordSystem.WCS:
                    throw new AcRx.Exception(
                              AcRx.ErrorStatus.InvalidInput,
                              "To be used only with DCS");

                case CoordSystem.UCS:
                    throw new AcRx.Exception(
                              AcRx.ErrorStatus.InvalidInput,
                              "To be used only with DCS");

                case CoordSystem.DCS:
                    mat = ed.PSDCS2DCS();
                    break;

                default:
                    mat = Matrix3d.Identity;
                    break;
                }
                break;
            }
            return(pt.TransformBy(mat));
        }
Ejemplo n.º 58
0
        public Result Define(IEnumerable ids, Matrix3d transToModel)
        {
            TransToModel = transToModel;
            Rooms = new List<Room>();

            List<View> views;
            List<Number> numbers;
            IterateEnt(ids, out views, out numbers);

            // Определение принадлежности видов помещениям
            ViewsOwner(views);

            // Определение принадлежности номеров помещениям
            NumbersOwner(numbers);

            CalcRolls();

            return Result.Ok();
        }
Ejemplo n.º 59
0
        public void ChangeBasePoint()
        {
            // Вставка блока
            var blRefId = AcadLib.Blocks.BlockInsert.Insert(OldName);

            Document doc = Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Database db = doc.Database;

            // Выбор новой базовой точки
            var ptInput = ed.GetPointWCS("\nВыбор новой базовой точки блока:");

            using (var t = db.TransactionManager.StartTransaction())
            {
                var blRef = blRefId.GetObject(OpenMode.ForRead, false, true) as BlockReference;
                var ptNewBase = ptInput- blRef.Position;
                // Вектор смещения базовой точки вхождения блока
                var ptBaseInBtr = ptNewBase.TransformBy(blRef.BlockTransform);
                var vec = new Vector3d(ptBaseInBtr.ToArray());
                // Вектор смещения объектов в блоке
                var vecBtr = vec.Negate();

                // Перемещение всех объектов блока на заданные вектор
                var matInBtr = Matrix3d.Displacement(vecBtr);
                var btr = IdBtr.GetObject(OpenMode.ForRead) as BlockTableRecord;
                foreach (var idEnt in btr)
                {
                    var ent = idEnt.GetObject(OpenMode.ForWrite, false, true) as Entity;
                    ent.TransformBy(matInBtr);
                }

                // Перемещение всех вхождений блока
                MatChangeBasePoint = Matrix3d.Displacement(vec);
                var refs = btr.GetBlockReferenceIds(true, false);
                foreach (ObjectId itemBlRefId in refs)
                {
                    var itemBlRef = itemBlRefId.GetObject( OpenMode.ForWrite, false, true) as BlockReference;
                    itemBlRef.TransformBy(MatChangeBasePoint);
                }

                if (IsDynamic)
                {
                    btr.UpdateAnonymousBlocks();
                    var anonyms = btr.GetAnonymousBlockIds();
                    foreach (ObjectId idAnonymBtr in anonyms)
                    {
                        var anonymBtr = idAnonymBtr.GetObject(OpenMode.ForRead) as BlockTableRecord;
                        var refsAnonym = anonymBtr.GetBlockReferenceIds(true, false);
                        foreach (ObjectId idBlRefAnonym in refsAnonym)
                        {
                            var blRefAnonym = idBlRefAnonym.GetObject( OpenMode.ForWrite, false, true) as BlockReference;
                            blRefAnonym.TransformBy(MatChangeBasePoint);
                        }
                    }
                }
                t.Commit();
            }
            IsChangeBasePoint = true;
        }
Ejemplo n.º 60
0
        public override void ToMachining(double AssociatedDist, ToolFile toolFile)
        {
            FindAssociatedFaces(AssociatedDist + this.GapDist);

            PartFace pf = this.Part.GetPartFaceByNumber(FaceNumber);

            if (pf.AssociatedPartFaces.Count != 0)//数量不为0,说明有关联的板件
            {
                double totolDist = DistToBottom + DistToTop;
                int    number    = (int)(totolDist / DistBetweenTwoHoles);
                for (int i = 0; i < number; i++)
                {
                    foreach (PartFace f in pf.AssociatedPartFaces)
                    {
                        if (f.IsHorizontalFace)//不对水平面处理
                        {
                            continue;
                        }


                        //TODO:关于生成的孔的排列

                        /*
                         * 1、无论层板如何旋转,计算上下时总是按未位移旋转时的下平面为基准
                         * 2、排列时,无论本身如何旋转,在加工板件上总是竖直平行于板件的一边
                         * 3、平行的难点:是平行于长边,还是平行于短边?
                         *
                         */


                        double firstPointX = GetFirstPointX();
                        double firstPointY = GetFirstPointY();
                        double firstPointZ = DistToBottom - i * DistBetweenTwoHoles;
                        //firstPointZ = -Part.Thickness - DistToBottom + i * DistBetweenTwoHoles;
                        Point3d holeposition = new Point3d(firstPointX, firstPointY, firstPointZ);

                        holeposition = holeposition.TransformBy(Matrix3d.AlignCoordinateSystem(new Point3d(),
                                                                                               Vector3d.XAxis,
                                                                                               Vector3d.YAxis,
                                                                                               Vector3d.ZAxis,
                                                                                               Part.MPPoint,
                                                                                               Part.MPXAxis,
                                                                                               Part.MPYAxis,
                                                                                               Part.MPZAxis));
                        holeposition = Math.MathHelper.GetRotatedAndMovedPoint(holeposition, Part.TXRotation, Part.YRotation, Part.ZRotation, Part.CenterVector);
                        holeposition = holeposition.TransformBy(Matrix3d.AlignCoordinateSystem(f.Part.MovedMPPoint,
                                                                                               f.Part.MovedMPXAxis,
                                                                                               f.Part.MovedMPYAxis,
                                                                                               f.Part.MovedMPZAxis,
                                                                                               new Point3d(),
                                                                                               Vector3d.XAxis,
                                                                                               Vector3d.YAxis,
                                                                                               Vector3d.ZAxis));
                        double dimx = holeposition.X;
                        double dimy = holeposition.Y;

                        VDrilling vdrill = new VDrilling(f.FaceNumber, dimx, dimy, this.FaceHoleDiameter, this.FaceHoleDepth, f.Part);
                        f.Part.VDrillings.Add(vdrill);
                    }
                }
            }
        }