예제 #1
0
        /// <summary>
        /// Функция построения части лапы мотора
        /// </summary>
        /// <param name="database"> База данных</param>
        /// <param name="trans"> Транзакция</param>
        /// <param name="width"> Ширина части лапы</param>
        /// <param name="len"> Длина части лапы</param>
        /// <param name="coordinateX"> Позиция центра по координате Х </param>
        /// <param name="coordinateZ"> Позиция центра по координате Z</param>
        /// <param name="angle"> Угол вращения</param>
        private void BuildPawsBox(Database database, Transaction trans, double width, double len, double coordinateX, double coordinateZ, double angle)
        {
            double r     = _diameretBox / 2;
            double koord = (r * ((Math.Sqrt(2) - 1) / 2) + r) / Math.Sqrt(2);

            // Открываем таблицу блоков для чтения
            BlockTable blockTable = trans.GetObject(database.BlockTableId, OpenMode.ForRead) as BlockTable;

            // Открываем таблицу блоков модели для записи
            BlockTableRecord blockTableRecord = trans.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

            // Создать новую фигуру
            Solid3d paw = new Solid3d();

            paw.SetDatabaseDefaults();
            paw.CreateBox(width, len, 20);
            paw.ColorIndex = 7;

            // Позиция центра отрисовки фигуры
            paw.TransformBy(Matrix3d.Displacement(new Point3d(coordinateX, 0, coordinateZ) - Point3d.Origin));
            Vector3d vRotPaw = new Point3d(0, 0, 0).GetVectorTo(new Point3d(0, 1, 0));

            paw.TransformBy(Matrix3d.Rotation(angle, vRotPaw, new Point3d(coordinateX, 0, coordinateZ)));

            // Добавляем новый обьект в таблицу блоков и отправляем на транзакцию
            blockTableRecord.AppendEntity(paw);
            trans.AddNewlyCreatedDBObject(paw, true);
        }
예제 #2
0
파일: Strap.cs 프로젝트: 15831944/WatchCAD
        /// <summary>
        /// ремешок с перфорацие
        /// </summary>
        /// <param name="WatchData">информация о часах</param>
        /// <returns>Модель часов</returns>
        public Solid3d BuildStrapWithPerforations(WatchData WatchData)
        {
            //модель ремешка с перфор.
            Solid3d StrapWithPerforations = new Solid3d();

            StrapWithPerforations.CreateBox(Length / 2, Width, 3);

            //сглаживаем углы.
            Solid3d StrapSmoother = new Solid3d();

            StrapSmoother.CreateFrustum(Width, _params[ParNames.StrapTransformByY], _params[ParNames.StrapTransformByY], _params[ParNames.StrapTransformByY]);
            StrapSmoother.TransformBy(Matrix3d.Rotation(Math.PI / 2, new Vector3d(1, 0, 0), Point3d.Origin));
            StrapSmoother.TransformBy(Matrix3d.Displacement(new Vector3d(Length / 4, 0, 0)));
            StrapWithPerforations.BooleanOperation(BooleanOperationType.BoolUnite, StrapSmoother.Clone() as Solid3d);

            StrapSmoother.CreateFrustum(Width, _params[ParNames.StrapTransformByY], _params[ParNames.StrapTransformByY], _params[ParNames.StrapTransformByY]);
            StrapSmoother.TransformBy(Matrix3d.Rotation(Math.PI / 2, new Vector3d(1, 0, 0), Point3d.Origin));
            StrapSmoother.TransformBy(Matrix3d.Displacement(new Vector3d(-Length / 4, 0, 0)));
            StrapWithPerforations.BooleanOperation(BooleanOperationType.BoolUnite, StrapSmoother.Clone() as Solid3d);

            //проделываем перфорации
            Solid3d HoleMaker = new Solid3d();

            for (int i = 0; i < NumberOfPerforations; i++)
            {
                HoleMaker.CreateFrustum(3, PerforationRadius, PerforationRadius, PerforationRadius);
                HoleMaker.TransformBy(Matrix3d.Displacement(new Vector3d((Length / 4 - 10) - (Length / 3) / NumberOfPerforations * i, 0, 0)));
                StrapWithPerforations.BooleanOperation(BooleanOperationType.BoolSubtract, HoleMaker.Clone() as Solid3d);
            }

            StrapWithPerforations.TransformBy(Matrix3d.Displacement(new Vector3d(WatchData.BodyDiameter + WatchData.BootstrapLength + (Length / 4) - 0.5, 0, 0)));


            return(StrapWithPerforations);
        }
예제 #3
0
        public void DrawAndSaveAs2(Product product, IWorkbookSet bookSet)
        {
            if (File.Exists(filePath))
            { throw new Exception("已经存在temp.dwg,请保证已经删除"); }

            //TODO:Not here
            product.Parts.ForEach(it => it.CalculateLocationInfo(Point3d.Origin, 0));

            using (Database db = new Database())
            using (Transaction acTrans = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = (BlockTable)acTrans.GetObject(db.BlockTableId, OpenMode.ForRead);
                BlockTableRecord btr = (BlockTableRecord)acTrans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

                foreach (var part in product.Parts)
                {
                    Solid3d panel = new Solid3d();
                    panel.CreateBox(part.Length, part.Width, part.Thickness);

                    panel.TransformBy(Matrix3d.Rotation(part.XRotation * Math.PI / 180, Vector3d.XAxis, Point3d.Origin));
                    panel.TransformBy(Matrix3d.Rotation(part.YRotation * Math.PI / 180, Vector3d.YAxis, Point3d.Origin));
                    panel.TransformBy(Matrix3d.Rotation(part.ZRotation * Math.PI / 180, Vector3d.ZAxis, Point3d.Origin));

                    var moveVector = new Vector3d();
                    panel.TransformBy(Matrix3d.Displacement(part.CenterVector));

                    btr.AppendEntity(panel);
                    acTrans.AddNewlyCreatedDBObject(panel, true);
                }

                acTrans.Commit();

                db.SaveAs(filePath, DwgVersion.Newest);
            }
        }
예제 #4
0
        public void DrawAndSaveAs()
        {
            if (File.Exists(filePath))
            { throw new Exception("已经存在temp.dwg,请保证已经删除"); }

            using (Database db = new Database())
            using (Transaction acTrans = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = (BlockTable)acTrans.GetObject(db.BlockTableId, OpenMode.ForRead);
                BlockTableRecord btr = (BlockTableRecord)acTrans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

                Solid3d solid = new Solid3d();
                solid.CreateBox(width, depth, height);

                //Move the block to the left-behind origin
                solid.TransformBy(Matrix3d.Displacement(new Vector3d(width / 2, -depth / 2, height / 2)));

                btr.AppendEntity(solid);
                acTrans.AddNewlyCreatedDBObject(solid, true);

                acTrans.Commit();

                db.SaveAs(filePath, DwgVersion.Newest);
            }
        }
예제 #5
0
        /// <summary>
        /// 由底面中心点、半径和高度在UCS中创建圆柱体
        /// </summary>
        /// <param name="bottomCenPt">底面中心点</param>
        /// <param name="radius">底面半径</param>
        /// <param name="height">高度</param>
        /// <returns>返回创建的圆柱体的Id</returns>
        public static ObjectId AddCylinder(Point3d bottomCenPt, double radius, double height)
        {
            Database db = HostApplicationServices.WorkingDatabase;
            Editor   ed = Application.DocumentManager.MdiActiveDocument.Editor;

            if (radius < 0.00001 || Math.Abs(height) < 0.00001)
            {
                ed.WriteMessage("\n参数不当,创建圆柱体失败!");
                return(ObjectId.Null);
            }

            // 创建
            Solid3d ent = new Solid3d();

            ent.RecordHistory = true;
            ent.CreateFrustum(Math.Abs(height), radius, radius, radius);

            // 位置调整
            Point3d  cenPt = bottomCenPt + new Vector3d(0.0, 0.0, 0.5 * height);
            Matrix3d mt    = ed.CurrentUserCoordinateSystem;

            mt = mt * Matrix3d.Displacement(cenPt - Point3d.Origin);
            ent.TransformBy(mt);

            ObjectId entId = ObjectId.Null;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                entId = db.AddToModelSpace(ent);
                tr.Commit();
            }
            return(entId);
        }
예제 #6
0
        /// <summary>
        /// 由中心点和半径在UCS中创建球体
        /// </summary>
        /// <param name="cenPt">中心点</param>
        /// <param name="radius">半径</param>
        /// <returns>返回创建的球体的Id</returns>
        public static ObjectId AddSphere(Point3d cenPt, double radius)
        {
            Database db = HostApplicationServices.WorkingDatabase;
            Editor   ed = Application.DocumentManager.MdiActiveDocument.Editor;

            if (radius < 0.00001)
            {
                ed.WriteMessage("\n参数不当,创建球体失败!");
                return(ObjectId.Null);
            }

            // 创建
            Solid3d ent = new Solid3d();

            ent.RecordHistory = true;
            ent.CreateSphere(radius);

            // 位置调整
            Matrix3d mt = ed.CurrentUserCoordinateSystem;

            mt = mt * Matrix3d.Displacement(cenPt - Point3d.Origin);
            ent.TransformBy(mt);

            ObjectId entId = ObjectId.Null;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                entId = db.AddToModelSpace(ent);
                tr.Commit();
            }
            return(entId);
        }
        /// <summary>
        ///     Построить спинку
        /// </summary>
        private void BuildHeadboard()
        {
            var headboardDisplacement =
                new Point3d(
                    _parameters.ModelParameters[ParameterType.MainPartLength].Value / 2 +
                    _parameters.ModelParameters[ParameterType.HeadboardThickness]
                    .Value / 2, 0,
                    _parameters.ModelParameters[ParameterType.MainPartHeight].Value / 2) -
                Point3d.Origin;

            using (var transaction =
                       _database.TransactionManager.StartTransaction())
            {
                var blockTableRecord = GetBlockTableRecord(transaction);

                using (var headboardSolid3d = new Solid3d())
                {
                    headboardSolid3d.CreateBox(
                        _parameters.ModelParameters[ParameterType.HeadboardThickness]
                        .Value,
                        _parameters.ModelParameters[ParameterType.MainPartWidth].Value,
                        _parameters.ModelParameters[ParameterType.HeadboardHeight].Value);

                    headboardSolid3d.TransformBy(
                        Matrix3d.Displacement(headboardDisplacement));

                    blockTableRecord.AppendEntity(headboardSolid3d);
                    transaction.AddNewlyCreatedDBObject(headboardSolid3d, true);
                }

                transaction.Commit();
            }
        }
예제 #8
0
        public static void FindInterferenceBetweenSolids()
        {
            // 获取当前文档和数据库,启动事务
            var acDoc   = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument;
            var acCurDb = acDoc.Database;

            using (var acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                // 以读模式打开块表
                BlockTable acBlkTbl;
                acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
                                             OpenMode.ForRead) as BlockTable;

                // 以写模式打开块表记录模型空间
                BlockTableRecord acBlkTblRec;
                acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
                                                OpenMode.ForWrite) as BlockTableRecord;

                // 创建3D箱体
                var acSol3DBox = new Solid3d();
                acSol3DBox.CreateBox(5, 7, 10);
                acSol3DBox.ColorIndex = 7;

                // 3D实体的中心点放在(5,5,0)
                acSol3DBox.TransformBy(Matrix3d.Displacement(new Point3d(5, 5, 0) -
                                                             Point3d.Origin));

                // 将新对象添加到块表记录和事务
                acBlkTblRec.AppendEntity(acSol3DBox);
                acTrans.AddNewlyCreatedDBObject(acSol3DBox, true);

                // 创建3D圆柱体
                // 默认构造函数的中心点为(0,0,0)
                var acSol3DCyl = new Solid3d();
                acSol3DCyl.CreateFrustum(20, 5, 5, 5);
                acSol3DCyl.ColorIndex = 4;

                // 将新对象添加到块表记录和事务
                acBlkTblRec.AppendEntity(acSol3DCyl);
                acTrans.AddNewlyCreatedDBObject(acSol3DCyl, true);

                // 用箱体和圆柱体的干涉创建一个3D实体
                var acSol3DCopy = acSol3DCyl.Clone() as Solid3d;

                // 检查箱体和圆柱体是否有重叠部分
                if (acSol3DCopy.CheckInterference(acSol3DBox))
                {
                    acSol3DCopy.BooleanOperation(BooleanOperationType.BoolIntersect,
                                                 acSol3DBox.Clone() as Solid3d);
                    acSol3DCopy.ColorIndex = 1;
                }

                // 将新对象添加到块表记录和事务
                acBlkTblRec.AppendEntity(acSol3DCopy);
                acTrans.AddNewlyCreatedDBObject(acSol3DCopy, true);

                // 提交事务
                acTrans.Commit();
            }
        }
예제 #9
0
        /// <summary>
        /// Функция построения элементов радиаторной решетки
        /// </summary>
        /// <param name="database"> База данных</param>
        /// <param name="trans"> Транзакция</param>
        /// <param name="coordinateX"> Позиция центра по координате Х</param>
        /// <param name="coordinateZ"> Позиция центра по координате Z</param>
        private void BuildRadiator(Database database, Transaction trans, double coordinateX, double coordinateZ)
        {
            // Открываем таблицу блоков для чтения
            BlockTable blockTable = trans.GetObject(database.BlockTableId, OpenMode.ForRead) as BlockTable;

            // Открываем таблицу блоков модели для записи
            BlockTableRecord blockTableRecord = trans.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

            // Создать новую фигуру
            double sizeLenBox      = _lenBox * 0.7;
            double sizeDiameretBox = _diameretBox / 8;

            Solid3d paw = new Solid3d();

            paw.SetDatabaseDefaults();
            paw.CreateBox(sizeDiameretBox, sizeLenBox, 5);
            paw.ColorIndex = 3;

            // Позиция центра отрисовки фигуры
            double coordY = -0.1 * _lenBox;

            paw.TransformBy(Matrix3d.Displacement(new Point3d(coordinateX, coordY, coordinateZ) - Point3d.Origin));


            // Добавляем новый обьект в таблицу блоков и отправляем на транзакцию
            blockTableRecord.AppendEntity(paw);
            trans.AddNewlyCreatedDBObject(paw, true);
        }
예제 #10
0
        /// <summary>
        /// 由角点、长度、宽度和高度在UCS中创建楔体
        /// </summary>
        /// <param name="cornerPt">角点</param>
        /// <param name="lengthAlongX">长度</param>
        /// <param name="lengthAlongY">宽度</param>
        /// <param name="lengthAlongZ">高度</param>
        /// <returns>返回创建的楔体的Id</returns>
        public static ObjectId AddWedge(Point3d cornerPt, double lengthAlongX,
                                        double lengthAlongY, double lengthAlongZ)
        {
            Database db = HostApplicationServices.WorkingDatabase;
            Editor   ed = Application.DocumentManager.MdiActiveDocument.Editor;

            if (Math.Abs(lengthAlongX) < 0.00001 || Math.Abs(lengthAlongX) < 0.00001 || Math.Abs(lengthAlongX) < 0.00001)
            {
                ed.WriteMessage("\n参数不当,创建楔体失败!");
                return(ObjectId.Null);
            }

            Solid3d ent = new Solid3d();

            ent.RecordHistory = true;
            ent.CreateWedge(Math.Abs(lengthAlongX), Math.Abs(lengthAlongY), Math.Abs(lengthAlongZ));

            // 位置调整
            Point3d  cenPt = cornerPt + new Vector3d(0.5 * lengthAlongX, 0.5 * lengthAlongY, 0.5 * lengthAlongZ);
            Matrix3d mt    = ed.CurrentUserCoordinateSystem;

            mt = mt * Matrix3d.Displacement(cenPt - Point3d.Origin);
            ent.TransformBy(mt);

            ObjectId entId = ObjectId.Null;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                entId = db.AddToModelSpace(ent);
                tr.Commit();
            }
            return(entId);
        }
예제 #11
0
        public void DrawAndSaveAs()
        {
            if (File.Exists(filePath))
            {
                throw new Exception("已经存在temp.dwg,请保证已经删除");
            }

            using (Database db = new Database())
                using (Transaction acTrans = db.TransactionManager.StartTransaction())
                {
                    BlockTable       bt  = (BlockTable)acTrans.GetObject(db.BlockTableId, OpenMode.ForRead);
                    BlockTableRecord btr = (BlockTableRecord)acTrans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

                    Solid3d solid = new Solid3d();
                    solid.CreateBox(width, depth, height);

                    //Move the block to the left-behind origin
                    solid.TransformBy(Matrix3d.Displacement(new Vector3d(width / 2, -depth / 2, height / 2)));

                    btr.AppendEntity(solid);
                    acTrans.AddNewlyCreatedDBObject(solid, true);

                    acTrans.Commit();

                    db.SaveAs(filePath, DwgVersion.Newest);
                }
        }
예제 #12
0
파일: Rotor.cs 프로젝트: sanjaysy/ORSAPR
        /// <summary>
        /// Функция построения вала
        /// </summary>
        /// <param name="database">База данных</param>
        /// <param name="Trans">Транзакция</param>
        /// <param name="parameters">Класс с параметрами построения мотора</param>
        public void Build(Database database, Transaction trans, MotorParameters parameters)
        {
            int diameretRotor = _diameretRotor;
            int lenRotor      = _lenRotor;
            int lenPin        = _lenPin;

            int lenBox = parameters.LenBox;

            // Открываем таблицу блоков для чтения
            BlockTable blockTable = trans.GetObject(database.BlockTableId, OpenMode.ForRead) as BlockTable;

            // Открываем таблицу блоков модели для записи
            BlockTableRecord blockTableRecord = trans.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

            // Создам новый цилиндр
            Solid3d rotor = new Solid3d();

            rotor.SetDatabaseDefaults();
            rotor.CreateFrustum(lenRotor, diameretRotor / 2, diameretRotor / 2, diameretRotor / 2);
            rotor.ColorIndex = 4;

            // Позиция центра отрисовки обьекта
            rotor.TransformBy(Matrix3d.Displacement(new Point3d(0, -lenRotor / 2 - lenBox / 2, 0) - Point3d.Origin));

            double   angleRotate = Math.PI / 2;
            Vector3d vRotRotor   = new Point3d(0, 0, 0).GetVectorTo(new Point3d(1, 0, 0));

            rotor.TransformBy(Matrix3d.Rotation(angleRotate, vRotRotor, new Point3d(0, -lenRotor / 2 - lenBox / 2, 0)));

            // Добавляем новый обьект в таблицу блоков и отправляем на транзакцию
            blockTableRecord.AppendEntity(rotor);
            trans.AddNewlyCreatedDBObject(rotor, true);

            // Созать новую фигуру
            Solid3d pin = new Solid3d();

            pin.SetDatabaseDefaults();
            pin.CreateBox(diameretRotor / 10, lenPin, diameretRotor / 10);
            pin.ColorIndex = 7;

            // Позиция центра
            pin.TransformBy(Matrix3d.Displacement(new Point3d(0, -lenBox / 2 - lenRotor + lenPin / 2, diameretRotor / 2) - Point3d.Origin));

            // Добавляем новый обьект в таблицу блоков и отправляем на транзакцию
            blockTableRecord.AppendEntity(pin);
            trans.AddNewlyCreatedDBObject(pin, true);
        }
예제 #13
0
파일: Strap.cs 프로젝트: 15831944/WatchCAD
        /// <summary>
        /// ремешок с замком
        /// </summary>
        /// <param name="WatchData">информация о часах</param>
        /// <returns>модель ремешка</returns>
        public Solid3d BuildStrapWithLocker(WatchData WatchData)
        {
            //модель ремешка с замком
            Solid3d StrapWithLocker = new Solid3d();

            StrapWithLocker.CreateBox(Length / _params[ParNames.StrapTransformByX], Width, 3);

            //сглаживания ремешка
            Solid3d StrapSmoother = new Solid3d();

            StrapSmoother.CreateFrustum(Width, _params[ParNames.StrapTransformByY], _params[ParNames.StrapTransformByY], _params[ParNames.StrapTransformByY]);
            StrapSmoother.TransformBy(Matrix3d.Rotation(Math.PI / _params[ParNames.StrapTransformByX], new Vector3d(1, 0, 0), Point3d.Origin));
            StrapSmoother.TransformBy(Matrix3d.Displacement(new Vector3d(Length / 4, 0, 0)));
            StrapWithLocker.BooleanOperation(BooleanOperationType.BoolUnite, StrapSmoother.Clone() as Solid3d);

            StrapSmoother.CreateFrustum(Width, _params[ParNames.StrapTransformByY], _params[ParNames.StrapTransformByX], _params[ParNames.StrapTransformByY]);
            StrapSmoother.TransformBy(Matrix3d.Rotation(Math.PI / _params[ParNames.StrapTransformByX], new Vector3d(1, 0, 0), Point3d.Origin));
            StrapSmoother.TransformBy(Matrix3d.Displacement(new Vector3d(-Length / 4, 0, 0)));
            StrapWithLocker.BooleanOperation(BooleanOperationType.BoolUnite, StrapSmoother.Clone() as Solid3d);

            //замок ремешка
            Solid3d Locker = new Solid3d();

            Locker.CreateBox(20, Width + _params[ParNames.StrapTransformByX], 4);
            Solid3d LockerHole = new Solid3d();

            LockerHole.CreateBox(18, Width, 4);
            LockerHole.TransformBy(Matrix3d.Displacement(new Vector3d(4, 0, 0)));
            Locker.BooleanOperation(BooleanOperationType.BoolSubtract, LockerHole.Clone() as Solid3d);

            //Дерджатель на замке
            Solid3d LockerPin = new Solid3d();

            LockerPin.CreateBox(20, WatchData.StrapPerforationRadius, _params[ParNames.StrapTransformByX]);
            Locker.BooleanOperation(BooleanOperationType.BoolUnite, LockerPin.Clone() as Solid3d);

            //передвигаем ремешок
            Locker.TransformBy(Matrix3d.Displacement(new Vector3d((-Length / 4) - 5, 0, 0)));
            StrapWithLocker.BooleanOperation(BooleanOperationType.BoolUnite, Locker.Clone() as Solid3d);
            StrapWithLocker.TransformBy(Matrix3d.Displacement(new Vector3d(-(WatchData.BodyDiameter + WatchData.BootstrapLength + (Length / 4) - 0.5), 0, 0)));

            //возвращаем модель ремешка

            return(StrapWithLocker);
        }
예제 #14
0
        public static void Rotate_3DBox()
        {
            // 获取当前文档和数据库,启动事务
            var acDoc   = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument;
            var acCurDb = acDoc.Database;

            using (var acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                // 以读模式打开块表
                BlockTable acBlkTbl;
                acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
                                             OpenMode.ForRead) as BlockTable;

                // 以写模式打开块表记录模型空间
                BlockTableRecord acBlkTblRec;
                acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
                                                OpenMode.ForWrite) as BlockTableRecord;

                // 创建一个3D实体箱子
                var acSol3D = new Solid3d();
                acSol3D.CreateBox(5, 7, 10);

                // 3D实体的中心点放在(5,5,0)
                acSol3D.TransformBy(Matrix3d.Displacement(new Point3d(5, 5, 0) - Point3d.Origin));

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

                // 将3D箱体绕点(-3,4,0)和点(-3,-4,0)定义的轴旋转30度
                var vRot = new Point3d(-3, 4, 0).
                           GetVectorTo(new Point3d(-3, -4, 0));

                acSol3D.TransformBy(Matrix3d.Rotation(0.5236, vRot, new Point3d(-3, 4, 0)));

                // 将新对象添加到块表记录和事务
                acBlkTblRec.AppendEntity(acSol3D);
                acTrans.AddNewlyCreatedDBObject(acSol3D, true);

                // 提交事务
                acTrans.Commit();
            }
        }
예제 #15
0
        /// <summary>
        /// Построить 3д солид-модель
        /// </summary>
        /// <param name="WatchData">Параметры часов</param>
        /// <returns>3Д - солид модель</returns>
        public Solid3d BuildCrown(WatchData WatchData)
        {
            //заводная головка
            Solid3d CrownPart = new Solid3d();

            CrownPart.CreateFrustum(Height, Diameter, Diameter, Diameter);

            //низ заводной головки
            Solid3d CrownBottom = new Solid3d();

            CrownBottom.CreateFrustum(1, Diameter, Diameter, Diameter - _pararameters[ParNames.CrownBottomHeight]);
            CrownBottom.TransformBy(Matrix3d.Displacement(new Point3d(0, 0, Height / _pararameters[ParNames.CrownTransformByZ] + _pararameters[ParNames.CrownTopHeight]) - Point3d.Origin));
            CrownPart.BooleanOperation(BooleanOperationType.BoolUnite, CrownBottom.Clone() as Solid3d);

            //вверх зав.головки
            Solid3d CrownTop = new Solid3d();

            CrownBottom.CreateFrustum(_pararameters[ParNames.CrownTopHeight], Diameter - _pararameters[ParNames.CrownTopHeight], Diameter - _pararameters[ParNames.CrownTopHeight], Diameter);
            CrownBottom.TransformBy(Matrix3d.Displacement(new Point3d(0, 0, -Height / _pararameters[ParNames.CrownTransformByZ] - 0.25) - Point3d.Origin));
            CrownPart.BooleanOperation(BooleanOperationType.BoolUnite, CrownBottom.Clone() as Solid3d);

            CrownBottom.CreateFrustum(_pararameters[ParNames.CrownTopHeight], Diameter - _pararameters[ParNames.CrownTopHeight], Diameter - _pararameters[ParNames.CrownTopHeight], Diameter - 1);
            CrownBottom.TransformBy(Matrix3d.Displacement(new Point3d(0, 0, -Height / _pararameters[ParNames.CrownTransformByZ] - _pararameters[ParNames.CrownTopHeight]) - Point3d.Origin));
            CrownPart.BooleanOperation(BooleanOperationType.BoolSubtract, CrownBottom.Clone() as Solid3d);

            //вырезаем цилиндры по радиусу зав. головки
            Solid3d CrownCutter = new Solid3d();

            CrownCutter.CreateFrustum(Height + _pararameters[ParNames.CrownBottomHeight], Diameter / _pararameters[ParNames.CrownCutterCount], Diameter / _pararameters[ParNames.CrownCutterCount], Diameter / _pararameters[ParNames.CrownCutterCount]);

            for (int i = 0; i < _pararameters[ParNames.CrownCutterCylinder]; i++)
            {
                CrownCutter.TransformBy(Matrix3d.Displacement(new Vector3d(Diameter * Math.Cos(Math.PI / 12 * i), Diameter * Math.Sin(Math.PI / 12 * i), 0)));
                CrownPart.BooleanOperation(BooleanOperationType.BoolSubtract, CrownCutter.Clone() as Solid3d);
                CrownCutter.TransformBy(Matrix3d.Displacement(new Vector3d(-Diameter * Math.Cos(Math.PI / 12 * i), -Diameter * Math.Sin(Math.PI / 12 * i), 0)));
            }

            CrownPart.TransformBy(Matrix3d.Rotation(Math.PI / 2, new Vector3d(1, 0, 0), Point3d.Origin));
            CrownPart.TransformBy(Matrix3d.Displacement(new Vector3d(0, WatchData.BodyDiameter + Height / _pararameters[ParNames.CrownTransformByZ] + _pararameters[ParNames.CrownBottomHeight], 0)));
            return(CrownPart);
        }
예제 #16
0
        // 由中心点、长度、宽度和高度创建楔体的函数.
        public static ObjectId AddWedge(Point3d cenPt, double lengthAlongX, double lengthAlongY, double lengthAlongZ)
        {
            Solid3d ent = new Solid3d();

            ent.CreateWedge(lengthAlongX, lengthAlongY, lengthAlongZ);
            Matrix3d mt = Matrix3d.Displacement(cenPt - Point3d.Origin);

            ent.TransformBy(mt);
            ObjectId entId = AppendEntity(ent);

            return(entId);
        }
예제 #17
0
        // 由中心点、圆环半径和圆管半径创建圆环体的函数.
        public static ObjectId AddTorus(Point3d cenPt, double majorRadius, double minorRadius)
        {
            Solid3d ent = new Solid3d();

            ent.CreateTorus(majorRadius, minorRadius);
            Matrix3d mt = Matrix3d.Displacement(cenPt - Point3d.Origin);

            ent.TransformBy(mt);
            ObjectId entId = AppendEntity(ent);

            return(entId);
        }
예제 #18
0
        // 由中心点和半径创建球体的函数.
        public static ObjectId AddSphere(Point3d cenPt, double radius)
        {
            Solid3d ent = new Solid3d();

            ent.CreateSphere(radius);
            Matrix3d mt = Matrix3d.Displacement(cenPt - Point3d.Origin);

            ent.TransformBy(mt);
            ObjectId entId = AppendEntity(ent);

            return(entId);
        }
예제 #19
0
        // 由中心点、半径和高度创建圆锥体的函数.
        public static ObjectId AddCone(Point3d cenPt, double radius, double height)
        {
            Solid3d ent = new Solid3d();

            ent.CreateFrustum(height, radius, radius, 0);
            Matrix3d mt = Matrix3d.Displacement(cenPt - Point3d.Origin);

            ent.TransformBy(mt);
            ObjectId entId = AppendEntity(ent);

            return(entId);
        }
예제 #20
0
        private void _drawBeam()
        {
            const double angle = (Math.PI / 2);

            var solidBeam = new Solid3d();

            solidBeam.Extrude(Region, d, 0);

            // Rotate along flange
            solidBeam.TransformBy(Matrix3d.Rotation(angle, Vector3d.XAxis, Point3d.Origin));
            AutoCadHelper.AppendAndAddToTransaction(solidBeam);
        }
예제 #21
0
파일: Body.cs 프로젝트: 15831944/WatchCAD
        /// <summary>
        /// Строим стрелки
        /// </summary>
        /// <param name="WatchData">Информация о часах</param>
        /// <returns>модель стрелок</returns>
        private Solid3d BuildArrows(WatchData WatchData)
        {
            //стрелки
            Solid3d Arrows = new Solid3d();
            //база
            Solid3d Base = new Solid3d();

            //первая часть базы
            Base.CreateFrustum(_params[ParNames.BodyTransformByX] / 2, _params[ParNames.BodyTransformByZ], _params[ParNames.BodyTransformByZ], _params[ParNames.BodyTransformByZ]);
            Base.TransformBy(Matrix3d.Displacement(new Vector3d(0, 0, Height / 2 + _params[ParNames.BodyTransformByX] / 4)));
            Arrows.BooleanOperation(BooleanOperationType.BoolUnite, Base.Clone() as Solid3d);

            //вторая часть бызы
            Base.CreateFrustum(_params[ParNames.BodyTransformByX] / 2, _params[ParNames.BodyTransformByY], _params[ParNames.BodyTransformByY], _params[ParNames.BodyTransformByY]);
            Base.TransformBy(Matrix3d.Displacement(new Vector3d(0, 0, Height / 2 + _params[ParNames.BodyTransformByX] / 4 * 3)));
            Arrows.BooleanOperation(BooleanOperationType.BoolUnite, Base.Clone() as Solid3d);

            //часовая стрелка
            Solid3d Arrow = new Solid3d();

            Arrow.CreateBox(Diameter / 2, _params[ParNames.BodyTransformByY], _params[ParNames.BodyTransformByX] / 4);
            Arrow.TransformBy(Matrix3d.Displacement(new Vector3d(-(Diameter / 4), 0, Height / 2 + _params[ParNames.BodyTransformByX] / 4)));
            double TrueHour = System.DateTime.Now.Hour + ((double)System.DateTime.Now.Minute / 60);

            Arrow.TransformBy(Matrix3d.Rotation(-(Math.PI / 6 * TrueHour), new Vector3d(0, 0, 1), Point3d.Origin));
            Arrows.BooleanOperation(BooleanOperationType.BoolUnite, Arrow.Clone() as Solid3d);

            //минутная стрелка
            Arrow.CreateBox(Diameter / 2 + _params[ParNames.BodyTopTransformByY], _params[ParNames.BodyTransformByX] + _params[ParNames.BodyTransformByX] / 5, _params[ParNames.BodyTransformByX] / 5);
            Arrow.TransformBy(Matrix3d.Displacement(new Vector3d(-(Diameter / 4), 0, Height / 2 + _params[ParNames.BodyTransformByX] / 4 * 3)));
            Arrow.TransformBy(Matrix3d.Rotation(-(Math.PI / 30 * System.DateTime.Now.Minute), new Vector3d(0, 0, 1), Point3d.Origin));
            Arrows.BooleanOperation(BooleanOperationType.BoolUnite, Arrow.Clone() as Solid3d);
            //секундная стрелка
            Arrow.CreateBox(Diameter / 2 + _params[ParNames.BodyBottomHeight], _params[ParNames.BodyTransformByX] / 2, _params[ParNames.BodyTransformByX] / 5);
            Arrow.TransformBy(Matrix3d.Displacement(new Vector3d(-(Diameter / _params[ParNames.BodyTopTransformByX]), 0, Height / 2 + _params[ParNames.BodyTransformByX] + _params[ParNames.BodyTransformByX] / 10)));
            Arrow.TransformBy(Matrix3d.Rotation(-(Math.PI / 30 * System.DateTime.Now.Second), new Vector3d(0, 0, 1), Point3d.Origin));
            Arrows.BooleanOperation(BooleanOperationType.BoolUnite, Arrow.Clone() as Solid3d);

            return(Arrows);
        }
예제 #22
0
        public static void CreatePlane()
        {
            // Get the current document and database, and start a transaction
            Document acDoc   = Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;

            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                // Open the Block table record for read
                BlockTable acBlkTbl;
                acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
                                             OpenMode.ForRead) as BlockTable;

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

                // Create a 3D solid box
                using (Solid3d acSol3D = new Solid3d())
                {
                    acSol3D.CreateBox(5, 7, 10);

                    // Position the center of the 3D solid at (5,5,0)
                    acSol3D.TransformBy(Matrix3d.Displacement(new Point3d(5, 5, 0) -
                                                              Point3d.Origin));

                    // Add the new object to the block table record and the transaction
                    acBlkTblRec.AppendEntity(acSol3D);
                    acTrans.AddNewlyCreatedDBObject(acSol3D, true);

                    // Create a copy of the original 3D solid and change the color of the copy
                    Solid3d acSol3DCopy = acSol3D.Clone() as Solid3d;
                    acSol3DCopy.ColorIndex = 1;

                    // Define the mirror plane
                    Plane acPlane = new Plane(new Point3d(1.25, 0, 0),
                                              new Point3d(1.25, 2, 0),
                                              new Point3d(1.25, 2, 2));

                    // Mirror the 3D solid across the plane
                    acSol3DCopy.TransformBy(Matrix3d.Mirroring(acPlane));

                    // Add the new object to the block table record and the transaction
                    acBlkTblRec.AppendEntity(acSol3DCopy);
                    acTrans.AddNewlyCreatedDBObject(acSol3DCopy, true);
                }

                // Save the new objects to the database
                acTrans.Commit();
            }
        }
예제 #23
0
        public static void MirrorABox3D()
        {
            // 获取当前文档和数据库,启动事务
            var acDoc   = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument;
            var acCurDb = acDoc.Database;

            using (var acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                // 以读模式打开块表
                BlockTable acBlkTbl;
                acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
                                             OpenMode.ForRead) as BlockTable;

                // 以写模式打开块表记录模型空间
                BlockTableRecord acBlkTblRec;
                acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
                                                OpenMode.ForWrite) as BlockTableRecord;

                // 创建3D箱体
                var acSol3D = new Solid3d();
                acSol3D.CreateBox(5, 7, 10);

                // 3D实体的中心点放在(5,5,0)
                acSol3D.TransformBy(Matrix3d.Displacement(new Point3d(5, 5, 0) -
                                                          Point3d.Origin));

                // 将新对象添加到块表记录和事务
                acBlkTblRec.AppendEntity(acSol3D);
                acTrans.AddNewlyCreatedDBObject(acSol3D, true);

                // 创建原3D箱体的拷贝并修改颜色
                var acSol3DCopy = acSol3D.Clone() as Solid3d;
                acSol3DCopy.ColorIndex = 1;

                // 定义镜像平面
                var acPlane = new Plane(new Point3d(1.25, 0, 0),
                                        new Point3d(1.25, 2, 0),
                                        new Point3d(1.25, 2, 2));

                // 沿平面镜像3D实体
                acSol3DCopy.TransformBy(Matrix3d.Mirroring(acPlane));

                // 将新对象添加到块表记录和事务
                acBlkTblRec.AppendEntity(acSol3DCopy);
                acTrans.AddNewlyCreatedDBObject(acSol3DCopy, true);

                // 提交事务
                acTrans.Commit();
            }
        }
예제 #24
0
        public void DrawAndSaveAs2(Product product, IWorkbookSet bookSet)
        {
            if (File.Exists(filePath))
            {
                throw new Exception("已经存在temp.dwg,请保证已经删除");
            }

            //TODO:Not here
            product.Parts.ForEach(it => it.CalculateLocationInfo(Point3d.Origin, 0));

            using (Database db = new Database())
                using (Transaction acTrans = db.TransactionManager.StartTransaction())
                {
                    BlockTable       bt  = (BlockTable)acTrans.GetObject(db.BlockTableId, OpenMode.ForRead);
                    BlockTableRecord btr = (BlockTableRecord)acTrans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

                    foreach (var part in product.Parts)
                    {
                        Solid3d panel = new Solid3d();
                        panel.CreateBox(part.Length, part.Width, part.Thickness);

                        panel.TransformBy(Matrix3d.Rotation(part.XRotation * Math.PI / 180, Vector3d.XAxis, Point3d.Origin));
                        panel.TransformBy(Matrix3d.Rotation(part.YRotation * Math.PI / 180, Vector3d.YAxis, Point3d.Origin));
                        panel.TransformBy(Matrix3d.Rotation(part.ZRotation * Math.PI / 180, Vector3d.ZAxis, Point3d.Origin));

                        var moveVector = new Vector3d();
                        panel.TransformBy(Matrix3d.Displacement(part.CenterVector));

                        btr.AppendEntity(panel);
                        acTrans.AddNewlyCreatedDBObject(panel, true);
                    }

                    acTrans.Commit();

                    db.SaveAs(filePath, DwgVersion.Newest);
                }
        }
예제 #25
0
파일: Findings.cs 프로젝트: sanjaysy/ORSAPR
        /// <summary>
        /// Функция отрисовки портов вывода
        /// </summary>
        /// <param name="database">База данныйх</param>
        /// <param name="Trans">Транцакция</param>
        /// <param name="parameters">Класс с параметрами построения мотора</param>
        /// <param name="positionPort">Позиция отверстия</param>
        /// <param name="Figure">Обьект класса</param>
        /// <param name="x">Позиция центра по координате Х</param>
        /// <param name="y">Позиция центра по координате Y</param>
        /// <param name="z">Позиция центра по координате Z</param>
        private void Ports(Database database, Transaction trans, MotorParameters parameters, int positionPort, Solid3d figure, double x, double y, double z)
        {
            // Открываем таблицу блоков для чтения
            BlockTable blockTable = trans.GetObject(database.BlockTableId, OpenMode.ForRead) as BlockTable;

            // Открываем таблицу блоков модели для записи
            BlockTableRecord blockTableRecord = trans.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

            // Создаем 3D обьект - прямоугольник
            Solid3d port = new Solid3d();

            port.SetDatabaseDefaults();
            port.CreateFrustum(_widthFindings * (parameters.CountPorts - positionPort), _diameretPorts / 2, _diameretPorts / 2, _diameretPorts / 2);
            port.ColorIndex = 4;

            // Перемещение и и поворот
            port.TransformBy(Matrix3d.Displacement(new Point3d(x, y, z) - Point3d.Origin));
            Vector3d vRotPort = new Point3d(0, 0, 0).GetVectorTo(new Point3d(0, 1, 0));

            port.TransformBy(Matrix3d.Rotation(Math.PI / 2, vRotPort, new Point3d(x, y, z)));
            blockTableRecord.AppendEntity(port);
            trans.AddNewlyCreatedDBObject(port, true);
            figure.BooleanOperation(BooleanOperationType.BoolSubtract, port);
        }
예제 #26
0
        private Solid3d CreateSphere()
        {
            // create the sphere
            Solid3d sphere = new Solid3d();

            sphere.SetDatabaseDefaults();
            // let's create a random number generator for the sphere
            Random randomGenerator = new Random();
            double radius          = randomGenerator.NextDouble() * 50;

            // create the sphere
            sphere.CreateSphere(radius);
            // randomize the position using the randomizer!
            Matrix3d randomMover;
            double   xVec = randomGenerator.NextDouble() * 500;
            double   yVec = randomGenerator.NextDouble() * 400;
            double   zVec = randomGenerator.NextDouble() * 300;

            randomMover = Matrix3d.Displacement(new Vector3d(xVec, yVec, zVec));
            // now apply the the transform to the sphere
            sphere.TransformBy(randomMover);

            // set the material name
            const string matname = "Sitework.Paving - Surfacing.Riverstone.Mortared";

            using (DBDictionary matdict = mPreviewCtrl.mCurrentDwg.MaterialDictionaryId.Open(OpenMode.ForRead) as DBDictionary)
            {
                // if we have found the material, set it to the sphere
                if (matdict.Contains(matname))
                {
                    sphere.Material = matname;
                }
                else
                {
                    // get the editor object
                    Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
                    ed.WriteMessage("\nMaterial (" + matname + ") not found" + " - sphere will be rendered without it.", matname);
                }
            }

            return(sphere);
        }
예제 #27
0
        /// <summary>
        /// 由底面中心点、高度、棱数和底面外接圆半径创建棱锥
        /// </summary>
        /// <param name="bottomCenPt">底面中心点</param>
        /// <param name="height">高度</param>
        /// <param name="sides">棱数</param>
        /// <param name="radius">底面外接圆半径</param>
        /// <returns>返回创建的棱锥的Id</returns>
        public static ObjectId AddPyramid(Point3d bottomCenPt, double height, int sides, double radius)
        {
            Database db = HostApplicationServices.WorkingDatabase;
            Editor   ed = Application.DocumentManager.MdiActiveDocument.Editor;

            if (Math.Abs(height) < 0.00001 || radius < 0.00001 || sides < 3 || sides > 32)
            {
                ed.WriteMessage("\n参数不当,创建棱柱失败!");
                return(ObjectId.Null);
            }

            // 创建
            Solid3d ent = new Solid3d();

            ent.RecordHistory = true;
            ent.CreatePyramid(Math.Abs(height), sides, radius, 0);

            // 位置调整
            Point3d  cenPt = bottomCenPt + new Vector3d(0.0, 0.0, 0.5 * height);
            Matrix3d mt    = ed.CurrentUserCoordinateSystem;

            mt = mt * Matrix3d.Displacement(cenPt - Point3d.Origin);

            if (height < 0)
            {
                Plane miPlane = new Plane(bottomCenPt, bottomCenPt + new Vector3d(radius, 0.0, 0.0),
                                          bottomCenPt + new Vector3d(0.0, radius, 0.0));
                Matrix3d mtMirroring = Matrix3d.Mirroring(miPlane);
                mt = mt * Matrix3d.Mirroring(miPlane);
            }

            ent.TransformBy(mt);

            ObjectId entId = ObjectId.Null;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                entId = db.AddToModelSpace(ent);
                tr.Commit();
            }
            return(entId);
        }
예제 #28
0
        public static void CreateWedge()
        {
            // 获取当前文档和数据库,启动事务
            var acDoc   = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument;
            var acCurDb = acDoc.Database;

            using (var acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                // 以读模式打开块表
                BlockTable acBlkTbl;
                acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
                                             OpenMode.ForRead) as BlockTable;

                // 以写模式打开块表记录模型空间
                BlockTableRecord acBlkTblRec;
                acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
                                                OpenMode.ForWrite) as BlockTableRecord;

                //创建3D楔形实体wedge
                var acSol3D = new Solid3d();
                acSol3D.CreateWedge(10, 15, 20);

                // 3D实体的中心点放在(5,5,0)
                acSol3D.TransformBy(Matrix3d.Displacement(new Point3d(5, 5, 0) - Point3d.Origin));

                // 将新对象添加到块表记录和事务
                acBlkTblRec.AppendEntity(acSol3D);
                acTrans.AddNewlyCreatedDBObject(acSol3D, true);

                // 打开当前视口
                ViewportTableRecord acVportTblRec;
                acVportTblRec = acTrans.GetObject(acDoc.Editor.ActiveViewportId,
                                                  OpenMode.ForWrite) as ViewportTableRecord;

                // 旋转当前视口的观察方向
                acVportTblRec.ViewDirection = new Vector3d(-1, -1, 1);
                acDoc.Editor.UpdateTiledViewportsFromDatabase();

                // 提交事务
                acTrans.Commit();
            }
        }
예제 #29
0
        public static void UpdateSolid3D(ObjectId objectId, dynamic xb)
        {
            Editor   ed      = acApp.DocumentManager.MdiActiveDocument.Editor;
            Document acDoc   = acApp.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;

            Point3d p1 = new Point3d(Convert.ToDouble(xb.x1), Convert.ToDouble(xb.y1), Convert.ToDouble(xb.z1));
            Point3d p2 = new Point3d(Convert.ToDouble(xb.x2), Convert.ToDouble(xb.y2), Convert.ToDouble(xb.z2));

            //acCurDb.TryGetObjectId();
            // Start a transaction
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                Solid3d acSol3DBox = (Solid3d)acTrans.GetObject(objectId, OpenMode.ForWrite);
                acSol3DBox.CreateBox(Math.Abs(p2.X - p1.X), Math.Abs(p2.Y - p1.Y), Math.Abs(p2.Z - p1.Z));
                Point3d center = new Point3d(p1.X + ((p2.X - p1.X) / 2), p1.Y + ((p2.Y - p1.Y) / 2), p1.Z + ((p2.Z - p1.Z) / 2));
                acSol3DBox.TransformBy(Matrix3d.Displacement(center.GetAsVector()));
                acSol3DBox.Draw();
                acTrans.Commit();
                ed.UpdateScreen();
            }
        }
예제 #30
0
        public void cmdCreateBox()
        {
            var doc = AcApp.DocumentManager.MdiActiveDocument;
            var ed  = doc.Editor;
            var db  = doc.Database;

            using (var tr = db.TransactionManager.StartTransaction())
            {
                var bt  = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                var btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                var box = new Solid3d();
                box.CreateBox(100, 200, 300);

                var matrix = ed.CurrentUserCoordinateSystem;
                matrix = matrix * Matrix3d.Displacement(new Vector3d(111, 222, 333));
                box.TransformBy(matrix);

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

                tr.Commit();
            }
        }
예제 #31
0
        public static Solid3d GetBoundingBox(this Transaction acTrans, ObjectId[] ids, Database acCurDb)
        {
            var extents = acTrans.GetExtents(ids, acCurDb);

            //Get geom extents of all selected
            var minX = extents.MinPoint.X;
            var maxX = extents.MaxPoint.X;
            var minY = extents.MinPoint.Y;
            var maxY = extents.MaxPoint.Y;
            var minZ = extents.MinPoint.Z;
            var maxZ = extents.MaxPoint.Z;

            var sol = new Solid3d();

            var width  = Math.Abs(maxX - minX);
            var length = Math.Abs(maxY - minY);
            var height = Math.Abs(maxZ - minZ);

            sol.CreateBox(width, length, height);
            sol.TransformBy(
                Matrix3d.Displacement(sol.GeometricExtents.MinPoint.GetVectorTo(new Point3d(minX, minY, minZ))));

            return(sol);
        }
예제 #32
0
        protected override bool WorldDrawData(WorldDraw draw)
        {
            if (!base.WorldDrawData(draw))
            {
                return(false);
            }

            short origCol = draw.SubEntityTraits.Color;

            if (_resizing)
            {
                using (Solid3d cube = new Solid3d())
                {
                    try
                    {
                        if (switchm == 1)
                        {
                            cube.CreateFrustum(_profSide, _profSide, _profSide, 0.0);
                        }
                        else if (switchm == 0)
                        {
                            cube.CreateBox(_profSide, _profSide, _profSide);
                        }


                        if (cube != null)
                        {
                            cube.TransformBy(
                                Matrix3d.Displacement(
                                    _resizeLocation - Point3d.Origin
                                    )
                                );

                            // Draw the cursor

                            draw.SubEntityTraits.Color = ColorIndex;
                            cube.WorldDraw(draw);
                        }
                    }
                    catch (System.Exception ex)
                    {
                        _doc.Editor.WriteMessage(
                            "\nException: {0} - {1}", ex.Message, ex.InnerException
                            );
                    }
                    finally
                    {
                        draw.SubEntityTraits.Color = origCol;
                    }
                }



                return(true);
            }

            // If we're currently drawing...

            if (_drawing)
            {
                Solid3d sol = null;
                try
                {
                    // If we have vertices that haven't yet been drawn...

                    if (_vertices.Count > 1 //&&
                        //_vertices.Count - 1 > _lastDrawnVertex
                        )
                    {
                        // ... generate a tube

                        if (GenerateTube(_profSide, _vertices, out sol))
                        {
                            // We now need to break the pipe...

                            // If it was created, add it to our list to draw

                            _created.Add(sol);
                            sol = null;

                            // Clear all but the last vertex to draw from
                            // next time

                            ClearAllButLast(_vertices, 1);
                        }
                    }
                }
                catch
                {
                    // If the tube generation failed...

                    if (sol != null)
                    {
                        sol.Dispose();
                    }

                    // Loop, creating the most recent successful tube we can

                    bool succeeded = false;
                    int  n         = 1;

                    do
                    {
                        try
                        {
                            // Generate the previous, working tube using all
                            // but the last points (if it fails, one more is
                            // excluded per iteration, until we get a working
                            // tube)

                            GenerateTube(
                                _profSide, GetAllButLast(_vertices, n++), out sol
                                );

                            _created.Add(sol);
                            sol       = null;
                            succeeded = true;
                        }
                        catch { }
                    }while (!succeeded && n < _vertices.Count);

                    if (succeeded)
                    {
                        ClearAllButLast(_vertices, n - 1);

                        if (_vertices.Count > 1)
                        {
                            try
                            {
                                // And generate a tube for the remaining vertices

                                GenerateTube(_profSide, _vertices, out sol);
                            }
                            catch
                            {
                                succeeded = false;
                            }
                        }
                    }

                    if (!succeeded && sol != null)
                    {
                        sol.Dispose();
                        sol = null;
                    }
                }

                // Draw our solid(s)

                draw.SubEntityTraits.Color = ColorIndex;

                foreach (DBObject obj in _created)
                {
                    Entity ent = obj as Entity;
                    if (ent != null)
                    {
                        try
                        {
                            ent.WorldDraw(draw);
                        }
                        catch
                        { }
                    }
                }

                if (sol != null)
                {
                    try
                    {
                        sol.WorldDraw(draw);
                    }
                    catch
                    { }
                }

                if (_vertices.Count > 0)
                {
                    Point3d lastPt = _vertices[_vertices.Count - 1];

                    // Create a cursor sphere

                    using (Solid3d cursor = new Solid3d())
                    {
                        try
                        {
                            if (switchm == 1)
                            {
                                cursor.CreateFrustum(_profSide, _profSide, _profSide, 0.0);
                            }
                            else if (switchm == 0)
                            {
                                cursor.CreateBox(_profSide, _profSide, _profSide);
                            }
                            if (cursor != null)
                            {
                                cursor.TransformBy(
                                    Matrix3d.Displacement(lastPt - Point3d.Origin)
                                    );

                                // Draw the cursor

                                draw.SubEntityTraits.Color = 4;     // ColorIndex;

                                cursor.WorldDraw(draw);
                            }
                        }
                        catch { }
                    }
                }

                if (sol != null)
                {
                    sol.Dispose();
                }
            }

            draw.SubEntityTraits.Color = origCol;

            return(true);
        }
        public static ObjectId CreateExtrusion(Point2d[] pts, Point3d destPt, Vector3d normal, WoodGrainAlignment grain)
        {
            ObjectId entId = ObjectId.Null;

            Document activeDoc = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument;
            Database db = activeDoc.Database;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;

                BlockTableRecord btr = null;
                if (String.IsNullOrEmpty(blockName))
                    btr = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                else
                {
                    if (bt.Has(blockName))
                        btr = tr.GetObject(bt[blockName], OpenMode.ForWrite) as BlockTableRecord;
                    else
                    {
                        btr = new BlockTableRecord();
                        btr.Name = blockName;
                        bt.UpgradeOpen();
                        bt.Add(btr);
                        tr.AddNewlyCreatedDBObject(btr, true);
                    }
                }

                Solid3d extrudedSolid = new Solid3d();
                using (Autodesk.AutoCAD.DatabaseServices.Polyline outline = new Autodesk.AutoCAD.DatabaseServices.Polyline())
                {
                    outline.SetDatabaseDefaults();
                    outline.Normal = normal;

                    int cnt = 0;
                    foreach (Point2d pt in pts)
                    {
                        outline.AddVertexAt(cnt, pt, 0, 0, 0);
                        cnt++;
                    }
                    outline.Closed = true;

                    Extents3d exts = outline.GeometricExtents;
                    Point3d minPt = exts.MinPoint;
                    Point3d maxPt = exts.MaxPoint;

                    double p1 = maxPt.X - minPt.X;
                    double p2 = maxPt.Y - minPt.Y;
                    double p3 = maxPt.Z - minPt.Z;

                    double pmin = 0.0;
                    if (p1 == 0)
                    {
                        pmin = Math.Min(p2, p3);
                    }
                    if (p2 == 0)
                    {
                        pmin = Math.Min(p1, p3);
                    }
                    if (p3 == 0)
                    {
                        pmin = Math.Min(p1, p2);
                    }
                    double pmax = Math.Max(Math.Max(p1, p2), p3);

                    extrudedSolid.RecordHistory = true;

                    plyIndex++;

                    Vector3d heightVector = outline.Normal * t;

                    SweepOptions sweepOptions = new SweepOptions();

                    SweepOptionsBuilder builder = new SweepOptionsBuilder(sweepOptions);

                    extrudedSolid.CreateExtrudedSolid(outline, heightVector, sweepOptions);
                }

                entId = btr.AppendEntity(extrudedSolid);
                tr.AddNewlyCreatedDBObject(extrudedSolid, true);

                extrudedSolid.TransformBy(Matrix3d.Displacement(destPt.GetAsVector()));

                tr.Commit();
            }

            return entId;
        }
예제 #34
0
        protected override bool WorldDrawData(WorldDraw draw)
        {
            if (!base.WorldDrawData(draw))
                return false;

            short origCol = draw.SubEntityTraits.Color;

            if (_resizing)
            {
                using (Solid3d cylinder = new Solid3d())
                {
                    try
                    {
                        cylinder.CreateFrustum(_profSide, _profSide, _profSide,_profSide);

                        if (cylinder != null)
                        {
                            cylinder.TransformBy(
                              Matrix3d.Displacement(
                                _resizeLocation - Point3d.Origin
                              )
                            );

                            // Draw the cursor

                            draw.SubEntityTraits.Color = ColorIndex;
                            cylinder.WorldDraw(draw);
                        }
                    }
                    catch (System.Exception ex)
                    {
                        _doc.Editor.WriteMessage(
                          "\nException: {0} - {1}", ex.Message, ex.InnerException
                        );
                    }
                    finally
                    {
                        draw.SubEntityTraits.Color = origCol;
                    }
                }
                return true;
            }

            // If we're currently drawing...

            if (_drawing)
            {
                Solid3d sol = null;
                try
                {
                    // If we have vertices that haven't yet been drawn...

                    if (_vertices.Count > 1 //&&
                        //_vertices.Count - 1 > _lastDrawnVertex
                      )
                    {
                        // ... generate a tube

                        if (GenerateTube(_profSide, _vertices, out sol))
                        {
                            // We now need to break the pipe...

                            // If it was created, add it to our list to draw

                            _created.Add(sol);
                            sol = null;

                            // Clear all but the last vertex to draw from
                            // next time

                            ClearAllButLast(_vertices, 1);
                        }
                    }
                }
                catch
                {
                    // If the tube generation failed...

                    if (sol != null)
                    {
                        sol.Dispose();
                    }

                    // Loop, creating the most recent successful tube we can

                    bool succeeded = false;
                    int n = 1;

                    do
                    {
                        try
                        {
                            // Generate the previous, working tube using all
                            // but the last points (if it fails, one more is
                            // excluded per iteration, until we get a working
                            // tube)

                            GenerateTube(
                              _profSide, GetAllButLast(_vertices, n++), out sol
                            );

                            _created.Add(sol);
                            sol = null;
                            succeeded = true;
                        }
                        catch { }
                    }
                    while (!succeeded && n < _vertices.Count);

                    if (succeeded)
                    {
                        ClearAllButLast(_vertices, n - 1);

                        if (_vertices.Count > 1)
                        {
                            try
                            {
                                // And generate a tube for the remaining vertices

                                GenerateTube(_profSide, _vertices, out sol);
                            }
                            catch
                            {
                                succeeded = false;
                            }
                        }
                    }

                    if (!succeeded && sol != null)
                    {
                        sol.Dispose();
                        sol = null;
                    }
                }

                // Draw our solid(s)

                draw.SubEntityTraits.Color = ColorIndex;

                foreach (DBObject obj in _created)
                {
                    Entity ent = obj as Entity;
                    if (ent != null)
                    {
                        try
                        {
                            ent.WorldDraw(draw);
                        }
                        catch
                        { }
                    }
                }

                if (sol != null)
                {
                    try
                    {
                        sol.WorldDraw(draw);
                    }
                    catch
                    { }
                }

                if (_vertices.Count > 0)
                {
                    Point3d lastPt = _vertices[_vertices.Count - 1];

                    // Create a cursor sphere

                    using (Solid3d cursor = new Solid3d())
                    {
                        try
                        {
                            cursor.CreateFrustum(_profSide, _profSide, _profSide, _profSide );

                            if (cursor != null)
                            {
                                cursor.TransformBy(
                                  Matrix3d.Displacement(lastPt - Point3d.Origin)
                                );

                                // Draw the cursor

                                draw.SubEntityTraits.Color = 5; //ColorIndex;

                                cursor.WorldDraw(draw);
                            }
                        }
                        catch { }
                    }
                }

                if (sol != null)
                {
                    sol.Dispose();
                }
            }

            draw.SubEntityTraits.Color = origCol;

            return true;
        }
예제 #35
0
        protected override bool WorldDrawData(WorldDraw draw)
        {
            if (!base.WorldDrawData(draw))
                return false;

            short origCol = draw.SubEntityTraits.Color;

            if (_resizing)
            {
                //  using (Solid3d cube = new Solid3d())
                //{
                try
                {


                    //cube.CreateBox(0.5, 0.5, 0.5);
                    _firstdraw = _firstdraw + 1;


                    if (cube != null)
                    {
                        //int i = 20000;
                        bool chk = false;
                        //cube.TransformBy(
                        //  Matrix3d.Displacement(
                        //     _resizeLocation - Point3d.Origin
                        //  )
                        //  );

                        // Draw the cursor

                        draw.SubEntityTraits.Color = ColorIndex;
                        cube.WorldDraw(draw);
                        vRot = leftHand.GetVectorTo(rightHand); ;// new Point3d(-3, 4, 0).GetVectorTo(new Point3d(-3, -4, 0)); //rightHand.GetVectorTo(leftHand);

                        System.Threading.Thread.Sleep((int)System.TimeSpan.FromSeconds(0.2).TotalMilliseconds);

                        //chk = (leftHand.Z < leftHip.Z);

                        //while (true)
                        //{
                        //  if (chk)
                        //    break;
                        //Point3d pt1 = rightHand - leftHand;
                        cube.TransformBy(Matrix3d.Rotation(0.1, vRot, Point3d.Origin));
                        //}

                        /*if (chk)
                        {
                            cube.TransformBy(Matrix3d.Rotation(1.046, vRot, leftHand));
                            System.Threading.Thread.Sleep((int)System.TimeSpan.FromSeconds(2).TotalMilliseconds);
                        }  */

                        //cube.TransformBy(Matrix3d.Rotation(0.5236, vRot, leftHand));
                    }

                    // if(_changeaxis)

                    //            vRot = rightHand.GetVectorTo(leftHand);
                    //          cube.TransformBy(Matrix3d.Rotation(0.5236,vRot,leftHand));

                    //   if (leftHand.Z > leftHip.Z)
                    //     _isRotate = false;

                }
                catch (System.Exception ex)
                {

                    _doc.Editor.WriteMessage(
                      "\nException: {0} - {1}", ex.Message, ex.InnerException
                    );
                }
                finally
                {
                    draw.SubEntityTraits.Color = origCol;
                }
                // }
                return true;
            }

            if (_isRotate)
            {
                cube.WorldDraw(draw);
            }

            // If we're currently drawing...

            if (_drawing)
            {
                Solid3d sol = null;
                try
                {
                    // If we have vertices that haven't yet been drawn...

                    if (_vertices.Count > 1 //&&
                        //_vertices.Count - 1 > _lastDrawnVertex
                      )
                    {
                        // ... generate a tube

                        if (GenerateTube(_profSide, _vertices, out sol))
                        {
                            // We now need to break the pipe...

                            // If it was created, add it to our list to draw

                            _created.Add(sol);
                            sol = null;

                            // Clear all but the last vertex to draw from
                            // next time

                            ClearAllButLast(_vertices, 1);
                        }
                    }
                }
                catch
                {
                    // If the tube generation failed...

                    if (sol != null)
                    {
                        sol.Dispose();
                    }

                    // Loop, creating the most recent successful tube we can

                    bool succeeded = false;
                    int n = 1;

                    do
                    {
                        try
                        {
                            // Generate the previous, working tube using all
                            // but the last points (if it fails, one more is
                            // excluded per iteration, until we get a working
                            // tube)

                            GenerateTube(
                              _profSide, GetAllButLast(_vertices, n++), out sol
                            );

                            _created.Add(sol);
                            sol = null;
                            succeeded = true;
                        }
                        catch { }
                    }
                    while (!succeeded && n < _vertices.Count);

                    if (succeeded)
                    {
                        ClearAllButLast(_vertices, n - 1);

                        if (_vertices.Count > 1)
                        {
                            try
                            {
                                // And generate a tube for the remaining vertices

                                GenerateTube(_profSide, _vertices, out sol);
                            }
                            catch
                            {
                                succeeded = false;
                            }
                        }
                    }

                    if (!succeeded && sol != null)
                    {
                        sol.Dispose();
                        sol = null;
                    }
                }

                // Draw our solid(s)

                draw.SubEntityTraits.Color = ColorIndex;

                foreach (DBObject obj in _created)
                {
                    Entity ent = obj as Entity;
                    if (ent != null)
                    {
                        try
                        {
                            ent.WorldDraw(draw);
                        }
                        catch
                        { }
                    }
                }

                if (sol != null)
                {
                    try
                    {
                        sol.WorldDraw(draw);
                    }
                    catch
                    { }
                }

                if (_vertices.Count > 0)
                {
                    Point3d lastPt = _vertices[_vertices.Count - 1];

                    // Create a cursor sphere

                    using (Solid3d cursor = new Solid3d())
                    {
                        try
                        {
                            cursor.CreateBox(_profSide, _profSide, _profSide);

                            if (cursor != null)
                            {
                                cursor.TransformBy(
                                  Matrix3d.Displacement(lastPt - Point3d.Origin)
                                );

                                // Draw the cursor

                                draw.SubEntityTraits.Color = 4; // ColorIndex;

                                cursor.WorldDraw(draw);
                            }
                        }
                        catch { }
                    }
                }

                if (sol != null)
                {
                    sol.Dispose();
                }
            }

            draw.SubEntityTraits.Color = origCol;

            return true;
        }