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); } }
/// <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); }
/// <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); }
/// <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(); } }
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(); } }
/// <summary> /// 由角点、长度、宽度和高度在UCS中创建长方体 /// </summary> /// <param name="cornerPt">角点</param> /// <param name="lengthX">长度</param> /// <param name="lengthY">宽度</param> /// <param name="lengthZ">高度</param> /// <returns>返回创建的长方体的Id</returns> public static ObjectId AddBox(Point3d cornerPt, double lengthX, double lengthY, double lengthZ) { Database db = HostApplicationServices.WorkingDatabase; Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; if (Math.Abs(lengthX) < 0.00001 || Math.Abs(lengthY) < 0.00001 || Math.Abs(lengthZ) < 0.00001) { ed.WriteMessage("\n参数不当,创建长方体失败!"); return(ObjectId.Null); } // 创建 Solid3d ent = new Solid3d(); ent.RecordHistory = true; ent.CreateBox(Math.Abs(lengthX), Math.Abs(lengthY), Math.Abs(lengthZ)); // 位置调整 Point3d cenPt = cornerPt + new Vector3d(0.5 * lengthX, 0.5 * lengthY, 0.5 * lengthZ); 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); }
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); } }
public void cmdImportTxtForAcCoreConsole() { var doc = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument; var ed = doc.Editor; var db = doc.Database; var fileName = @"InputFile.txt"; var folderPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var filePath = Path.Combine(folderPath, fileName); var lines = File.ReadAllLines(filePath); 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; foreach (var line in lines) { var parts = line.Split(','); var xLength = double.Parse(parts[0]); var yLength = double.Parse(parts[1]); var zLength = double.Parse(parts[2]); var box = new Solid3d(); box.CreateBox(xLength, yLength, zLength); btr.AppendEntity(box); tr.AddNewlyCreatedDBObject(box, true); } tr.Commit(); } db.SaveAs(Path.Combine(folderPath, @"Generated.dwg"), DwgVersion.Current); }
/// <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); }
public void CreateBoolSolid() { // 在内存中创建旋转截面对象. Solid3d ent1 = new Solid3d(); Solid3d ent2 = new Solid3d(); ent1.CreateBox(100, 60, 40); ent2.CreateFrustum(90, 20, 20, 20); // 差集操作. ent1.BooleanOperation(BooleanOperationType.BoolSubtract, ent2); ModelSpace.AppendEntity(ent1); }
// 由中心点、长度、宽度和高度创建长方体的函数. public static ObjectId AddBox(Point3d cenPt, double lengthAlongX, double lengthAlongY, double lengthAlongZ) { Solid3d ent = new Solid3d(); ent.CreateBox(lengthAlongX, lengthAlongY, lengthAlongZ); Matrix3d mt = Matrix3d.Displacement(cenPt - Point3d.Origin); ent.TransformBy(mt); ObjectId entId = AppendEntity(ent); return(entId); }
/// <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); }
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(); } }
private Solid3d NewBox(Point3d centerPoint, double h, double df) { double num1 = 0.15 * (df - 10.0) / 5.0; double num2 = 0.15 * (df - 10.0) / 2.0; double num3 = h; Solid3d solid3d = new Solid3d(); solid3d.CreateBox(num1, num2, num3); // ISSUE: explicit reference operation // ISSUE: explicit reference operation // ISSUE: explicit reference operation ((Entity)solid3d).TransformBy(Matrix3d.Displacement(Vector3d.op_Addition(new Vector3d(0.15 * (df - 10.0), 0.0, h / 2.0), new Vector3d(((Point3d)@centerPoint).get_X(), ((Point3d)@centerPoint).get_Y(), ((Point3d)@centerPoint).get_Z())))); return(solid3d); }
public void Cmd_DEBUGBOXES() { if (!LicensingAgent.Check()) { return; } var acCurDoc = Application.DocumentManager.MdiActiveDocument; var acCurDb = acCurDoc.Database; _ = acCurDoc.Editor; var boxCount = 500; var maxSize = 40; var minSize = 5; var minX = -500; var minY = -500; var minZ = -500; var maxX = 500; var maxY = 500; var maxZ = 500; var random = new Random(); using (var acTrans = acCurDb.TransactionManager.StartTransaction()) { for (var i = 0; i < boxCount; i++) { var acSol = new Solid3d(); var length = random.Next(minSize, maxSize); var width = random.Next(minSize, maxSize); var height = random.Next(minSize, maxSize); acSol.CreateBox(length, width, height); var insertPoint = new Point3d(random.Next(minX, maxX), random.Next(minY, maxY), random.Next(minZ, maxZ)); acCurDb.AppendEntity(acSol); acSol.Move(acSol.GetBoxCenter(), insertPoint); acSol.CleanBody(); } acTrans.Commit(); } }
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(); } }
/// <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); }
/// <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); }
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(); } }
/// <summary> /// Построить основную часть /// </summary> private void BuildMainPart() { using (var transaction = _database.TransactionManager.StartTransaction()) { var blockTableRecord = GetBlockTableRecord(transaction); using (var mainPartSolid3d = new Solid3d()) { mainPartSolid3d.CreateBox( _parameters.ModelParameters[ParameterType.MainPartLength].Value, _parameters.ModelParameters[ParameterType.MainPartWidth].Value, _parameters.ModelParameters[ParameterType.MainPartHeight].Value); blockTableRecord.AppendEntity(mainPartSolid3d); transaction.AddNewlyCreatedDBObject(mainPartSolid3d, true); } transaction.Commit(); } }
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(); } }
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(); } }
public KinectrotateCubesJig( Document doc, Transaction tr, double profSide, double factor ) { // Initialise the various members _doc = doc; _tr = tr; _vertices = new Point3dCollection(); _lastDrawnVertex = -1; _resizing = false; _resizebool = 0; _drawing = false; leftHand = new Point3d(); rightHand = new Point3d(); leftHip = new Point3d(); _isRotate = false; vRot = new Vector3d(); _changeaxis = false; _firstdraw = 0; ct = 0; _created = new DBObjectCollection(); _profSide = profSide; _segFactor = factor; cube = new Solid3d(); cube.CreateBox(0.5, 0.5, 0.5); Words.Add("red"); Words.Add("green"); Words.Add("blue"); Words.Add("yellow"); Words.Add("pink"); Words.Add("magenta"); Words.Add("cyan"); }
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); }
/// <summary> /// Функция построения коробки выводов /// </summary> /// <param name="database">База данный объектов </param> /// <param name="Trans">Транзакции</param> /// <param name="parameters">Класс с параметрами построения мотора</param> public void Build(Database database, Transaction trans, MotorParameters parameters) { int widthFindings = _widthFindings; int lenFindings = _lenFindings; int heightFindings = _heightFindings; int countPorts = _countPorts; int diameretPorts = _diameretPorts; int lenBox = parameters.LenBox; int diameretBox = parameters.DiameretBox; // Коэффициенты трансформации double transformationFactorLen = 1.2; double transformationFactorHeight = 0.1; // Открываем таблицу блоков для чтения BlockTable blockTable = trans.GetObject(database.BlockTableId, OpenMode.ForRead) as BlockTable; // Открываем таблицу блоков модели для записи BlockTableRecord blockTableRecord = trans.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; // Создаем 3D обьект - прямоугольник Solid3d findings = new Solid3d(); findings.SetDatabaseDefaults(); findings.CreateBox(widthFindings, lenFindings, heightFindings); findings.ColorIndex = 7; // Задаем позицию центра 3D обьекта findings.TransformBy(Matrix3d.Displacement(new Point3d(0, -lenBox / 2 + transformationFactorLen * lenFindings / 2, diameretBox / 2 + heightFindings / 2 - transformationFactorHeight * heightFindings) - Point3d.Origin)); // Добавляем новый обьект в таблицу блоков и отправляем на транзакцию blockTableRecord.AppendEntity(findings); trans.AddNewlyCreatedDBObject(findings, true); // Параметры double cavityWidth = widthFindings * 0.8; double cavityLen = lenFindings * 0.9; double cavityHeight = heightFindings * 0.8; // Создать новую фигуру Solid3d cavity = new Solid3d(); cavity.SetDatabaseDefaults(); cavity.CreateBox(cavityWidth, cavityLen, cavityHeight); cavity.TransformBy(Matrix3d.Displacement(new Point3d(0, -lenBox / 2 + transformationFactorLen * lenFindings / 2, diameretBox / 2 + heightFindings / 2 - transformationFactorHeight * heightFindings) - Point3d.Origin)); // Добавляем новый обьект в таблицу блоков и отправляем на транзакцию blockTableRecord.AppendEntity(cavity); trans.AddNewlyCreatedDBObject(cavity, true); findings.BooleanOperation(BooleanOperationType.BoolSubtract, cavity); double coordZ = diameretBox / 2 + heightFindings / 2 - transformationFactorHeight * heightFindings; double coordX = widthFindings / 3; if (countPorts >= 1) { double y1 = -lenBox / 2 + (transformationFactorLen * lenFindings / 2 + lenFindings / 3); Ports(database, trans, parameters, 0, findings, coordX, y1, coordZ); } if (countPorts > 2) { double y2 = -lenBox / 2 + (transformationFactorLen * lenFindings / 2); Ports(database, trans, parameters, 2, findings, coordX, y2, coordZ); } if (countPorts > 4) { double y3 = -lenBox / 2 + (transformationFactorLen * lenFindings / 2 - lenFindings / 3); Ports(database, trans, parameters, 4, findings, -coordX, y3, coordZ); } }
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); }
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); }
/// <summary> /// Построить модель корпуса /// </summary> /// <param name="WatchData">параметры часов</param> /// <returns>3д модель корпуса</returns> private Solid3d BuildBody(WatchData WatchData) { //корпус часов Solid3d Body = new Solid3d(); Body.CreateFrustum(Height, Diameter, Diameter, Diameter); //Верхняя часть корпуса Solid3d BodyTop = new Solid3d(); BodyTop.CreateFrustum(_params[ParNames.BodyTransformByY], Diameter, Diameter, Diameter - _params[ParNames.BodyTransformByZ]); BodyTop.TransformBy(Matrix3d.Displacement(new Point3d(0, 0, Height / _params[ParNames.BodyTransformByY] + _params[ParNames.BodyTransformByX]) - Point3d.Origin)); Body.BooleanOperation(BooleanOperationType.BoolUnite, BodyTop.Clone() as Solid3d); //Нижняя часть корпуса Solid3d BodyBottom = new Solid3d(); BodyBottom.CreateFrustum(_params[ParNames.BodyTransformByX], Diameter - _params[ParNames.BodyTopTransformByY], Diameter - _params[ParNames.BodyTopTransformByY], Diameter - _params[ParNames.BodyTransformByY]); BodyBottom.TransformBy(Matrix3d.Displacement(new Point3d(0, 0, -(Height / 2 + _params[ParNames.BodyTransformByX] / 2)) - Point3d.Origin)); Body.BooleanOperation(BooleanOperationType.BoolUnite, BodyBottom.Clone() as Solid3d); //Вырез на корпусе, сверху BodyTop = new Solid3d(); BodyTop.CreateFrustum(_params[ParNames.BodyTransformByY], Diameter - _params[ParNames.BodyBottomTransformByX], Diameter - _params[ParNames.BodyBottomTransformByX], Diameter - _params[ParNames.BodyTopTransformByY]); BodyTop.TransformBy(Matrix3d.Displacement(new Point3d(0, 0, Height / _params[ParNames.BodyTransformByY] + _params[ParNames.BodyTransformByX]) - Point3d.Origin)); Body.BooleanOperation(BooleanOperationType.BoolSubtract, BodyTop.Clone() as Solid3d); //ушки на корпусе Solid3d Bootstrap = new Solid3d(); Bootstrap.CreateBox(BootstrapLength * _params[ParNames.BodyTransformByY] + Diameter * _params[ParNames.BodyTransformByY], _params[ParNames.BodyTopTransformByY], _params[ParNames.BodyTopTransformByY]); Vector3d BootsrapPosition; Solid3d ArcPart = new Solid3d(); ArcPart.CreateFrustum(_params[ParNames.BodyTopTransformByY], _params[ParNames.BodyTopTransformByY] / 2, _params[ParNames.BodyTopTransformByY] / 2, _params[ParNames.BodyTopTransformByY] / 2); ArcPart.TransformBy(Matrix3d.Rotation(Math.PI / 2, new Vector3d(1, 0, 0), Point3d.Origin)); ArcPart.TransformBy(Matrix3d.Displacement(new Vector3d(Diameter + BootstrapLength, 0, 0))); //Держатели на ушках Solid3d StrapHolder = new Solid3d(); StrapHolder.CreateFrustum(WatchData.StrapWidth + _params[ParNames.BodyTopTransformByX], _params[ParNames.BodyTransformByX] / _params[ParNames.BodyTransformByY], _params[ParNames.BodyTransformByX] / _params[ParNames.BodyTransformByY], _params[ParNames.BodyTransformByX] / _params[ParNames.BodyTransformByY]); StrapHolder.TransformBy(Matrix3d.Rotation(Math.PI / _params[ParNames.BodyTransformByY], new Vector3d(1, 0, 0), Point3d.Origin)); StrapHolder.TransformBy(Matrix3d.Displacement(new Vector3d(Diameter + BootstrapLength, -WatchData.StrapWidth / 2 - _params[ParNames.BodyTransformByY], 0))); ArcPart.BooleanOperation(BooleanOperationType.BoolUnite, StrapHolder.Clone() as Solid3d); Bootstrap.BooleanOperation(BooleanOperationType.BoolUnite, ArcPart.Clone() as Solid3d); //сглаженные углы на ушках ArcPart.CreateFrustum(_params[ParNames.BodyTopTransformByY], _params[ParNames.BodyTopTransformByY] / _params[ParNames.BodyTransformByY], _params[ParNames.BodyTopTransformByY] / 2, _params[ParNames.BodyTopTransformByY] / 2); ArcPart.TransformBy(Matrix3d.Rotation(Math.PI / _params[ParNames.BodyTransformByY], new Vector3d(1, 0, 0), Point3d.Origin)); ArcPart.TransformBy(Matrix3d.Displacement(new Vector3d(-(Diameter + BootstrapLength), 0, 0))); StrapHolder.CreateFrustum(WatchData.StrapWidth + _params[ParNames.BodyTopTransformByX], _params[ParNames.BodyTransformByX] / 2, _params[ParNames.BodyTransformByX] / 2, _params[ParNames.BodyTransformByX] / 2); StrapHolder.TransformBy(Matrix3d.Rotation(Math.PI / 2, new Vector3d(1, 0, 0), Point3d.Origin)); StrapHolder.TransformBy(Matrix3d.Displacement(new Vector3d(-(Diameter + BootstrapLength), -WatchData.StrapWidth / 2 - _params[ParNames.BodyTransformByY], 0))); ArcPart.BooleanOperation(BooleanOperationType.BoolUnite, StrapHolder.Clone() as Solid3d); Bootstrap.BooleanOperation(BooleanOperationType.BoolUnite, ArcPart.Clone() as Solid3d); BootsrapPosition = new Vector3d(0, WatchData.StrapWidth / _params[ParNames.BodyTransformByY] + _params[ParNames.BodyTransformByZ], 0); Bootstrap.TransformBy(Matrix3d.Displacement(BootsrapPosition)); Body.BooleanOperation(BooleanOperationType.BoolUnite, Bootstrap.Clone() as Solid3d); Bootstrap = new Solid3d(); Bootstrap.CreateBox(BootstrapLength * _params[ParNames.BodyTransformByY] + Diameter * _params[ParNames.BodyTransformByY], _params[ParNames.BodyTopTransformByY], _params[ParNames.BodyTopTransformByY]); ArcPart = new Solid3d(); ArcPart.CreateFrustum(_params[ParNames.BodyTopTransformByY], _params[ParNames.BodyTopTransformByY] / 2, _params[ParNames.BodyTopTransformByY] / _params[ParNames.BodyTransformByY], _params[ParNames.BodyTopTransformByY] / _params[ParNames.BodyTransformByY]); ArcPart.TransformBy(Matrix3d.Rotation(Math.PI / _params[ParNames.BodyTransformByY], new Vector3d(1, 0, 0), Point3d.Origin)); ArcPart.TransformBy(Matrix3d.Displacement(new Vector3d(Diameter + BootstrapLength, 0, 0))); Bootstrap.BooleanOperation(BooleanOperationType.BoolUnite, ArcPart.Clone() as Solid3d); ArcPart.CreateFrustum(_params[ParNames.BodyTopTransformByY], _params[ParNames.BodyTopTransformByY] / _params[ParNames.BodyTransformByY], _params[ParNames.BodyTopTransformByY] / 2, _params[ParNames.BodyTopTransformByY] / _params[ParNames.BodyTransformByY]); ArcPart.TransformBy(Matrix3d.Rotation(Math.PI / _params[ParNames.BodyTransformByY], new Vector3d(1, 0, 0), Point3d.Origin)); ArcPart.TransformBy(Matrix3d.Displacement(new Vector3d(-(Diameter + BootstrapLength), 0, 0))); Bootstrap.BooleanOperation(BooleanOperationType.BoolUnite, ArcPart.Clone() as Solid3d); BootsrapPosition = new Vector3d(0, -(WatchData.StrapWidth / _params[ParNames.BodyTransformByY] + _params[ParNames.BodyTransformByZ]), 0); Bootstrap.TransformBy(Matrix3d.Displacement(BootsrapPosition)); //соеденяем все вместе Body.BooleanOperation(BooleanOperationType.BoolUnite, Bootstrap.Clone() as Solid3d); //если есть хронограф, то выполняем if (HasChronograph) { //первая кнопка хронографа Solid3d ChronoButtonTop = new Solid3d(); ChronoButtonTop.CreateFrustum(_params[ParNames.BodyTopTransformByX], _params[ParNames.BodyTopTransformByX], _params[ParNames.BodyTopTransformByX], _params[ParNames.BodyTopTransformByX]); ChronoButtonTop.TransformBy(Matrix3d.Rotation(Math.PI / 2, new Vector3d(1, 0, 0), Point3d.Origin)); ChronoButtonTop.TransformBy(Matrix3d.Displacement(new Vector3d(0, Diameter, 0))); ChronoButtonTop.TransformBy(Matrix3d.Rotation(Math.PI / 6, new Vector3d(0, 0, 1), Point3d.Origin)); Body.BooleanOperation(BooleanOperationType.BoolUnite, ChronoButtonTop.Clone() as Solid3d); //вторая кнопка хронографа Solid3d ChronoButtonBottom = new Solid3d(); ChronoButtonBottom.CreateFrustum(_params[ParNames.BodyTopTransformByY], _params[ParNames.BodyTopTransformByY], _params[ParNames.BodyTopTransformByY], _params[ParNames.BodyTopTransformByY]); ChronoButtonBottom.TransformBy(Matrix3d.Rotation(Math.PI / 2, new Vector3d(1, 0, 0), Point3d.Origin)); ChronoButtonBottom.TransformBy(Matrix3d.Displacement(new Vector3d(0, Diameter, 0))); ChronoButtonBottom.TransformBy(Matrix3d.Rotation(-Math.PI / 6, new Vector3d(0, 0, 1), Point3d.Origin)); Body.BooleanOperation(BooleanOperationType.BoolUnite, ChronoButtonBottom.Clone() as Solid3d); } return(Body); }
public void interferenceSolids() { Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; using (Transaction trans = db.TransactionManager.StartTransaction()) { try { BlockTable blkTable = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; if (blkTable == null) { trans.Abort(); return; } BlockTableRecord blkTableRecord = trans.GetObject(blkTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; if (blkTableRecord == null) { return; } using (Solid3d solid3DBox = new Solid3d()) { // 3D Solid Box. solid3DBox.CreateBox(5, 7, 10); solid3DBox.ColorIndex = 7; // Position of the center of solid3DBox at (5, 5, 0) solid3DBox.TransformBy(Matrix3d.Displacement(new Point3d(5, 5, 0) - Point3d.Origin)); //blkTableRecord.AppendEntity(solid3DBox); //trans.AddNewlyCreatedDBObject(solid3DBox, true); // 3D Solid Cylinder. using (Solid3d solid3DCylinder = new Solid3d()) { solid3DCylinder.CreateFrustum(20, 5, 5, 5); solid3DCylinder.ColorIndex = 4; //blkTableRecord.AppendEntity(solid3DCylinder); //trans.AddNewlyCreatedDBObject(solid3DCylinder, true); // Create 3D solid from the interference of the box and cylinder. //Solid3d solid3dCopy = solid3DCylinder.Clone() as Solid3d; //if (solid3dCopy.CheckInterference(solid3DBox) == true) //{ // solid3dCopy.BooleanOperation(BooleanOperationType.BoolSubtract, solid3DBox.Clone() as Solid3d); // solid3dCopy.ColorIndex = 1; //} //// add solid3dCopy to the block table record. //blkTableRecord.AppendEntity(solid3dCopy); //trans.AddNewlyCreatedDBObject(solid3dCopy, true); Solid3d solid3dCopyCylinder = solid3DCylinder.Clone() as Solid3d; if (solid3dCopyCylinder.CheckInterference(solid3DBox) == true) { solid3dCopyCylinder.BooleanOperation(BooleanOperationType.BoolIntersect, solid3DBox); solid3dCopyCylinder.ColorIndex = 3; } blkTableRecord.AppendEntity(solid3dCopyCylinder); trans.AddNewlyCreatedDBObject(solid3dCopyCylinder, true); } } trans.Commit(); } catch (System.Exception) { trans.Abort(); throw; } } }
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 void Test() { Document acDoc = Application.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; Editor acEd = acDoc.Editor; using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { var blkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; var mdlSpc = acTrans.GetObject(blkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; /* var ent3dArray = Enumerable.Range(0, 8).Select(i => new Solid3d()).ToArray(); * var box = ent3dArray[0]; * box.CreateBox(1, 2, 3); * //圆锥/圆柱 * var fru = ent3dArray[1]; * fru.CreateFrustum(3, 1, 1, 0); * * //台体 * var pyr = ent3dArray[2]; * pyr.CreatePyramid(3, 5, 2, 1); * * var sph = ent3dArray[3]; * sph.CreateSphere(2); * * var tor = ent3dArray[4]; * tor.CreateTorus(2, 0.5); * * var wdg = ent3dArray[5]; * wdg.CreateWedge(1, 2, 3); * * var poly = new Polyline(); * * poly.AddVertexAt(poly.NumberOfVertices, Point2d.Origin - Vector2d.XAxis, 0, 0, 0); * poly.AddVertexAt(poly.NumberOfVertices, Point2d.Origin + Vector2d.XAxis, 0, 0, 0); * poly.AddVertexAt(poly.NumberOfVertices, Point2d.Origin + Vector2d.YAxis, 0, 0, 0); * poly.Closed = true; * * var reg=Region.CreateFromCurves(new DBObjectCollection() { poly })[0] as Region; * * var ext1 = ent3dArray[6]; * ext1.Extrude(reg, 6, 0); * * var ext2 = ent3dArray[7]; * ext2.Revolve(reg, Point3d.Origin + Vector3d.XAxis, Vector3d.YAxis, Math.PI * 2); * * foreach (var i in Enumerable.Range(0,8)) * { * * var ent3d = ent3dArray[i]; * * ent3d.TransformBy(Matrix3d.Displacement((Vector3d.XAxis * 10).RotateBy(i * Math.PI / 4, Vector3d.ZAxis))); * * mdlSpc.AppendEntity(ent3d); * acTrans.AddNewlyCreatedDBObject(ent3d, true); * * * }*/ var unit0 = new Solid3d(); unit0.CreateBox(2, 2, 0.2); unit0.TransformBy(Matrix3d.Displacement(Vector3d.ZAxis * 0.1)); using (var unit1 = new Solid3d()) { unit1.CreateFrustum(3, 0.9, 0.9, 0); unit1.TransformBy(Matrix3d.Displacement(Vector3d.ZAxis * 1.7)); unit0.BooleanOperation(BooleanOperationType.BoolUnite, unit1); } using (var unit2 = new Solid3d()) { unit2.CreateFrustum(3, 0.9, 0.9, 0); unit2.TransformBy(Matrix3d.Displacement(Vector3d.ZAxis * 1.5)); unit0.BooleanOperation(BooleanOperationType.BoolSubtract, unit2); } using (var unit3 = new Solid3d()) { unit3.CreateFrustum(2, 0.6, 0.6, 0); unit3.TransformBy(Matrix3d.Displacement(Vector3d.ZAxis * 1)); unit0.BooleanOperation(BooleanOperationType.BoolUnite, unit3); } var brep = new Brep(unit0); acEd.WriteMessage(string.Join("\n", new[] { $"Complex:{brep.Complexes.Count()}", $"Shell:{brep.Shells.Count()}", $"Face:{brep.Faces.Count()}", $"Edged:{brep.Edges.Count()}", $"Vertex:{brep.Vertices.Count()}" } )); mdlSpc.AppendEntity(unit0); acTrans.AddNewlyCreatedDBObject(unit0, true); acTrans.Commit(); } }
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; }
public KinectextrudeCubesJig( Document doc, Transaction tr, double profSide, double factor ) { // Initialise the various members _doc = doc; _tr = tr; _vertices = new Point3dCollection(); _lastDrawnVertex = -1; _resizing = false; _resizebool = 0; _drawing = false; leftHand = new Point3d(); rightHand = new Point3d(); leftHip = new Point3d(); _isExtrude = false; vRot = new Vector3d(); _changeaxis = false; _firstdraw = 0; ct = 0; _created = new DBObjectCollection(); _profSide = profSide; _segFactor = factor; cube = new Solid3d(); cube.CreateBox(0.5, 0.5, 0.5); Words.Add("red"); Words.Add("green"); Words.Add("blue"); Words.Add("yellow"); Words.Add("pink"); Words.Add("magenta"); Words.Add("cyan"); }