.NET
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Autocad 2013, plane cut solid3d, to get region, access region, autocad crash

12 REPLIES 12
Reply
Message 1 of 13
hongmei
1651 Views, 12 Replies

Autocad 2013, plane cut solid3d, to get region, access region, autocad crash

 
12 REPLIES 12
Message 2 of 13
Alexander.Rivilis
in reply to: hongmei

Maybe you post yours code?

Відповідь корисна? Клікніть на "ВПОДОБАЙКУ" цім повідомленням! | Do you find the posts helpful? "LIKE" these posts!
Находите сообщения полезными? Поставьте "НРАВИТСЯ" этим сообщениям!
На ваше запитання відповіли? Натисніть кнопку "ПРИЙНЯТИ РІШЕННЯ" | Have your question been answered successfully? Click "ACCEPT SOLUTION" button.
На ваш вопрос успешно ответили? Нажмите кнопку "УТВЕРДИТЬ РЕШЕНИЕ"


Alexander Rivilis / Александр Ривилис / Олександр Рівіліс
Programmer & Teacher & Helper / Программист - Учитель - Помощник / Програміст - вчитель - помічник
Facebook | Twitter | LinkedIn
Expert Elite Member

Message 3 of 13
hongmei
in reply to: Alexander.Rivilis

using

System;

using

System.Collections.Generic;

using

System.Linq;

using

System.Text;

using

Autodesk.AutoCAD.Runtime;

using

Autodesk.AutoCAD.ApplicationServices;

using

Autodesk.AutoCAD.DatabaseServices;

using

Autodesk.AutoCAD.EditorInput;

using

Autodesk.AutoCAD.Geometry;

using

acadAPP = Autodesk.AutoCAD.ApplicationServices.Application;

namespace

Solid3dCut2013

{

publicclassClass1

{

[

CommandMethod("ACut_Solid3d")]

 

publicstaticvoidACut_Solid3d()

{

Document doc=acadAPP.DocumentManager .MdiActiveDocument ;

 

try

{

ObjectIdsolId;

 

Planepln;

 

ObjectIdCollectionobjIds;

pickSolid3d (doc,

out solId ,out pln ,outobjIds);

 

if (solId ==ObjectId .Null || pln ==null ) return;

 

using (DocumentLockdlock=doc.LockDocument ())

{

using (Transactiontrans=doc.TransactionManager .StartTransaction ())

{

foreach (ObjectId objId inobjIds)

{

CutSolid(doc, trans, objId , pln);

}

trans .Commit ();

}

}

}

catch (System.Exceptionex)

{

doc.Editor .WriteMessage (ex.Message +

"\n");

}

}

publicstaticvoid pickSolid3d(Document doc, outObjectId solId, outPlane pln,outObjectIdCollectionobjIds)

{

solId =

ObjectId.Null;

pln =

null;

objIds =

null;

 

PromptSelectionResultpsr= doc.Editor.SelectAll();

objIds =

newObjectIdCollection( psr.Value.GetObjectIds());

 

PromptEntityOptions peo = newPromptEntityOptions("pick solid3d: ");

peo.SetRejectMessage(

"solid3d only \n");

peo.AddAllowedClass(

typeof(Solid3d), true);

 

PromptEntityResultper = doc.Editor.GetEntity(peo);

 

while (true)

{

if (per.Status == PromptStatus.Cancel) return;

 

if (per.Status != PromptStatus.OK) continue;

solId =per.ObjectId ;

Point3dpt=per.PickedPoint ;

 

using (DocumentLockdlock=doc.LockDocument ())

{

using (Transactiontrans=doc.TransactionManager .StartTransaction ())

{

Solid3d sol=(Solid3d ) trans .GetObject (solId ,OpenMode.ForRead );

 

doublez= (sol.GeometricExtents .MinPoint.Z +sol .GeometricExtents .MaxPoint .Z ) /2;

pt=

newPoint3d(pt.X,pt.Y ,z);

pln=

newPlane (pt,newVector3d(1,1,1).GetNormal () );

trans .Commit ();

}

}

return;

}

}

staticpublicvoid CutSolid(Document doc, Transaction tr, ObjectId solId, Planepln)

{

Entity ent = (Entity)(tr.GetObject(solId, OpenMode.ForRead));

 

if (ent == null)

 

return;

 

if (ent.GetType() != typeof(Solid3d))

 

return;

 

Solid3d sol = (Solid3d)ent;

 

sol.Highlight();

doc.Editor.WriteMessage(

"objId: "+solId .ToString ()+"\n");

 

PromptStringOptions pso = newPromptStringOptions("continu...");

doc.Editor.GetString(pso);

sol.Unhighlight();

 

Region reg = null;

 

try

{

reg = sol.GetSection(pln);

}

catch (Autodesk.AutoCAD.Runtime.Exceptionex)

{

doc.Editor.WriteMessage(ex.Message +

"\n");

 

return;

}

catch (System.Exceptione)

{

//MessageBox.Show(e.Message);

doc.Editor .WriteMessage (e.Message +

"\n");

 

return;

}

try

{

if (reg==null || reg.IsNull) //add region to DB, otherwise 2013 crash return;

}

catch (System.AccessViolationExceptionex)

{

doc.Editor.WriteMessage(ex.Message +

"\n"); // MessageBox.Show(ex.Message);return;

}

catch (System.Exceptionex2)

{

doc.Editor.WriteMessage(ex2.Message +

"\n"); //MessageBox.Show(ex2.Message);

}

DBObjectCollection entCol = newDBObjectCollection();

reg.Explode(entCol);

////add region to DB

BlockTable bt = (BlockTable)(tr.GetObject(doc.Database.BlockTableId, OpenMode.ForWrite));

 

BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

btr.AppendEntity(reg);

tr.AddNewlyCreatedDBObject(reg,

true);

reg.Erase();

if (entCol != null&& entCol.Count != 0)

{

foreach (DBObject obj inentCol)

{

if (!(obj isEntity)) continue;

 

Entity ent1 = (Entity)obj;

ent1.ColorIndex = 6;

//pink

btr.AppendEntity(ent1);

tr.AddNewlyCreatedDBObject(obj,

true);

}

}

}

}

}

 

 

For some solid3d (not all),  can pass region=solid.getsection();

but when run to the yellow line, all region's properties can't access, can't catch, just cause autocad 2013 crash, ACAD2011 is ok, only ACAD2013

 

 

Thank you very much

Message 4 of 13
Alexander.Rivilis
in reply to: hongmei

1. First of all your code is not readable. Many of keywords are concatenated and if you try copy code from forum to VS and compile it then you get errors. In order to post code please use Insert Code button:

01-03-2013 15-59-28.png

2. I did not see any yellow line although I'm not color blind.

Відповідь корисна? Клікніть на "ВПОДОБАЙКУ" цім повідомленням! | Do you find the posts helpful? "LIKE" these posts!
Находите сообщения полезными? Поставьте "НРАВИТСЯ" этим сообщениям!
На ваше запитання відповіли? Натисніть кнопку "ПРИЙНЯТИ РІШЕННЯ" | Have your question been answered successfully? Click "ACCEPT SOLUTION" button.
На ваш вопрос успешно ответили? Нажмите кнопку "УТВЕРДИТЬ РЕШЕНИЕ"


Alexander Rivilis / Александр Ривилис / Олександр Рівіліс
Programmer & Teacher & Helper / Программист - Учитель - Помощник / Програміст - вчитель - помічник
Facebook | Twitter | LinkedIn
Expert Elite Member

Message 5 of 13
hongmei
in reply to: Alexander.Rivilis

pink , sorry, I colored it yellow, then I realized yellow is not bright enough, so I changed it to pink, when I wrote the message, I still think the yellow color

Message 6 of 13
Alexander.Rivilis
in reply to: hongmei

Sorry but in any case, I can not read this code ... Maybe someone else ...

Відповідь корисна? Клікніть на "ВПОДОБАЙКУ" цім повідомленням! | Do you find the posts helpful? "LIKE" these posts!
Находите сообщения полезными? Поставьте "НРАВИТСЯ" этим сообщениям!
На ваше запитання відповіли? Натисніть кнопку "ПРИЙНЯТИ РІШЕННЯ" | Have your question been answered successfully? Click "ACCEPT SOLUTION" button.
На ваш вопрос успешно ответили? Нажмите кнопку "УТВЕРДИТЬ РЕШЕНИЕ"


Alexander Rivilis / Александр Ривилис / Олександр Рівіліс
Programmer & Teacher & Helper / Программист - Учитель - Помощник / Програміст - вчитель - помічник
Facebook | Twitter | LinkedIn
Expert Elite Member

Message 7 of 13
hongmei
in reply to: hongmei

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;

using acadAPP = Autodesk.AutoCAD.ApplicationServices.Application;
namespace Solid3dCut2013
{
    public class Class1
    {
        [CommandMethod("ACut_Solid3d")]
        public static void ACut_Solid3d()
        {
            Document doc=acadAPP .DocumentManager .MdiActiveDocument ;
            try
            {
                ObjectId solId;
                Plane pln;
                ObjectIdCollection objIds;

                pickSolid3d (doc,out solId ,out pln ,out   objIds);
                if (solId ==ObjectId .Null || pln ==null )  return ;
                using (DocumentLock dlock=doc.LockDocument ())
                {
                    using (Transaction trans=doc.TransactionManager .StartTransaction ())
                    {
                        foreach (ObjectId objId in objIds)
                        {
                            CutSolid(doc, trans, objId , pln);
                        }
                        trans .Commit ();
                    }
                }
            }
            catch (System.Exception ex)
            {
                doc.Editor .WriteMessage (ex.Message +"\n");
            }
        }
        public static void pickSolid3d(Document doc, out ObjectId solId, out Plane pln,out ObjectIdCollection objIds)
        {
            solId = ObjectId.Null;
            pln = null;
            objIds = null;
            
            PromptSelectionResult psr= doc.Editor.SelectAll();
            objIds =new ObjectIdCollection ( psr.Value.GetObjectIds());

            PromptEntityOptions peo = new PromptEntityOptions("pick solid3d: ");
            peo.SetRejectMessage("solid3d only \n");
            peo.AddAllowedClass(typeof(Solid3d), true);
            

            PromptEntityResult per = doc.Editor.GetEntity(peo);
            while (true)
            {
                if (per.Status == PromptStatus.Cancel) return ;
                if (per.Status != PromptStatus.OK) continue;

                solId =per.ObjectId ;
                Point3d pt=per.PickedPoint ;
                using (DocumentLock dlock=doc.LockDocument ())
                {
                    using (Transaction trans=doc.TransactionManager .StartTransaction ())
                    {
                        Solid3d sol=(Solid3d ) trans .GetObject (solId ,OpenMode .ForRead );
                        double z= (sol.GeometricExtents .MinPoint.Z +sol .GeometricExtents .MaxPoint .Z ) /2;
                        pt=new Point3d (pt.X,pt.Y ,z);
                        pln=new Plane (pt,new Vector3d (1,1,1).GetNormal ()  );
                        trans .Commit ();
                    }
                }
                return ;
            }

        }
        static public void CutSolid(Document doc, Transaction tr, ObjectId solId, Plane pln)
        {
            Entity ent = (Entity)(tr.GetObject(solId, OpenMode.ForRead));
            if (ent == null)
                return;
            if (ent.GetType() != typeof(Solid3d))
                return;
            Solid3d sol = (Solid3d)ent;
            
            sol.Highlight();

            doc.Editor.WriteMessage("objId: "+solId .ToString ()+"\n");
            PromptStringOptions pso = new PromptStringOptions("continu...");
            doc.Editor.GetString(pso);
            sol.Unhighlight();


            Region reg = null;
            try
            {
                reg = sol.GetSection(pln);
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                doc.Editor.WriteMessage(ex.Message + "\n");
                return;
            }
            catch (System.Exception e)
            {
                //MessageBox.Show(e.Message);
                doc.Editor .WriteMessage (e.Message +"\n");
                return;
            }
            

            try
            {
                if (reg==null || reg.IsNull)  //add region to DB, otherwise 2013 crash                
                    return;
            }
            catch (System.AccessViolationException ex)
            {
                doc.Editor.WriteMessage(ex.Message + "\n"); // MessageBox.Show(ex.Message);
                
                return;
            }
            catch (System.Exception ex2)
            {
                doc.Editor.WriteMessage(ex2.Message + "\n"); //MessageBox.Show(ex2.Message);
            }

            DBObjectCollection entCol = new DBObjectCollection();
            reg.Explode(entCol);

////add  region to DB
            BlockTable bt = (BlockTable)(tr.GetObject(doc.Database.BlockTableId, OpenMode.ForWrite));
            BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
            btr.AppendEntity(reg);
            tr.AddNewlyCreatedDBObject(reg, true);
            reg.Erase();

            
            if (entCol != null && entCol.Count != 0)
            {
                foreach (DBObject obj in entCol)
                {
                    if (!(obj is Entity)) continue;
                    
                    Entity ent1 = (Entity)obj;
                    ent1.ColorIndex = 6;  //pink
                    btr.AppendEntity(ent1);
                    tr.AddNewlyCreatedDBObject(obj, true);                    
                }
            }
        }

    }
}

 

Message 8 of 13
Alexander.Rivilis
in reply to: hongmei

I have to your code so many questions that do not even know where to start.

 

1. Function pickSolid3d:

a) if user not select Solid3d (missed) then infinite loop and AutoCAD hang because you do not change per inside the while loop.

b) you really need such cutting plane:

            pln = new Plane(pt, new Vector3d(1, 1, 1).GetNormal());

or you need horizontal cutting plane?

 

2. Function CutSolid:

a) why you open BlockTabe forwrite?

b) what entities you can try add to BlockTableRecord - Region or exploded Region?

c) why you add Region to BlockTableRecord and once it is erased?

 

This is just what I saw quickly viewing your code.

Відповідь корисна? Клікніть на "ВПОДОБАЙКУ" цім повідомленням! | Do you find the posts helpful? "LIKE" these posts!
Находите сообщения полезными? Поставьте "НРАВИТСЯ" этим сообщениям!
На ваше запитання відповіли? Натисніть кнопку "ПРИЙНЯТИ РІШЕННЯ" | Have your question been answered successfully? Click "ACCEPT SOLUTION" button.
На ваш вопрос успешно ответили? Нажмите кнопку "УТВЕРДИТЬ РЕШЕНИЕ"


Alexander Rivilis / Александр Ривилис / Олександр Рівіліс
Programmer & Teacher & Helper / Программист - Учитель - Помощник / Програміст - вчитель - помічник
Facebook | Twitter | LinkedIn
Expert Elite Member

Message 9 of 13
hongmei
in reply to: Alexander.Rivilis

Thank you for your patience,

 

I was about to ask ADN support this question, but for some reason, I can't access ADN my account

 

This piece of code is I made up temporary to raise the error, it is full of mistakes if you set a high standard.

my purpose is to make the problem appear, on this line, reg.isNull || reg==null , cause autocad2013 crash, which I couldn't catch

 

your question

1. picksolid3d

  a.my purpose is to pick a solid, I have a drawing which has all solid3d

  b. my cut plane can be any, I just make up this one to make the error appear, horizontal plane can't make the error

 

2. cutsolid

  a.blockTable open for write, not necessary

  b.entities add to model space are entites after explode the region,

  c. region is created tempary, if I don't do anything , it will cause memory leak, if I delete it directly will cause error 'not in database'. so I need to add it to model splace, add to transaction, then I can delete it safely and no memery leak

 

 

Thanks

 

Message 10 of 13
Alexander.Rivilis
in reply to: hongmei


hongmei wrote:

...I was about to ask ADN support this question, but for some reason, I can't access ADN my account...


Are you ADN member? If yes why you can not access DevHelp? Maybe you have to e-mail ADN administrator? If you have not his e-mail then PM me.


@hongmei wrote:
...my purpose is to make the problem appear, on this line, reg.isNull || reg==null , cause autocad2013 crash, which I couldn't catch

I can reproduce this behavior. Maybe it's a bug, maybe no...  If cutting plane has not intersection with Solid3d then calling reg.isNull produce exception.


@hongmei wrote:
...  c. region is created tempary, if I don't do anything , it will cause memory leak, if I delete it directly will cause error 'not in database'. so I need to add it to model splace, add to transaction, then I can delete it safely and no memery leak

As usually enough to call reg.Dispose() in order to free its memory.

Відповідь корисна? Клікніть на "ВПОДОБАЙКУ" цім повідомленням! | Do you find the posts helpful? "LIKE" these posts!
Находите сообщения полезными? Поставьте "НРАВИТСЯ" этим сообщениям!
На ваше запитання відповіли? Натисніть кнопку "ПРИЙНЯТИ РІШЕННЯ" | Have your question been answered successfully? Click "ACCEPT SOLUTION" button.
На ваш вопрос успешно ответили? Нажмите кнопку "УТВЕРДИТЬ РЕШЕНИЕ"


Alexander Rivilis / Александр Ривилис / Олександр Рівіліс
Programmer & Teacher & Helper / Программист - Учитель - Помощник / Програміст - вчитель - помічник
Facebook | Twitter | LinkedIn
Expert Elite Member

Message 11 of 13
hongmei
in reply to: Alexander.Rivilis

I am ADN member, they fixed my account today, I already post the question to them.

 

so, you found the problem, Thank you very much, sorry for confusing you by my bad code

 

how to get around this, not causing ACAD2013 crash, I don't mind ignore cutting some objects.

 

I will call obj.Dispose(),

Message 12 of 13
hongmei
in reply to: hongmei

hello,

 

I wonder if you can help.

 

nobody can reproduce this error from Autodesk, you are the only one.

 

strange thing for me:

if I set breakpt in reg=sol.GetSection(pln) , 

run step by step, it won't crash, just throw exception here, and catch in here.

 

if no breakpt set, it will crash,

 

if set breakpt if (reg==null || reg.IsNull) , I can see the reg properties are not valid

 

 

not all the ACAD2013 behave the same. 

I have ACAD2013 on my virtual machine works fine. I tried to add all my other addins, still works

 

ACAD2013 on my real machine crashes, I removed all my other addins, still crashes

 

I need to find the reason, or find a solution to get around this, I can ignore cutting some objects

 

 

appreciate any help

 

 

Message 13 of 13
hongmei
in reply to: Alexander.Rivilis

hello, Alex

 

I wonder if you can help.

 

nobody can reproduce this error from Autodesk, you are the only one.

 

strange thing for me:

if I set breakpt in reg=sol.GetSection(pln) ,

run step by step, it won't crash, just throw exception here, and catch in here.

 

if no breakpt set, it will crash,

 

if set breakpt if (reg==null || reg.IsNull) , I can see the reg properties are not valid

 

 

not all the ACAD2013 behave the same.

I have ACAD2013 on my virtual machine works fine. I tried to add all my other addins, still works

 

ACAD2013 on my real machine crashes, I removed all my other addins, still crashes

 

I need to find the reason, or find a solution to get around this, I can ignore cutting some objects

 

 

appreciate any help

Can't find what you're looking for? Ask the community or share your knowledge.

Post to forums  

Autodesk DevCon in Munich May 28-29th


Autodesk Design & Make Report

”Boost