본문 바로가기
Revit/Revit API

CreateDimensions

by Crony 2014. 1. 24.

Application: CreateDimensions
Revit Platform: Structure
Revit Version: 2011.0
First Released For: 9.0
Programming Language: C#
Skill Level: Medium
Category: Annotation
Type: ExternalCommand

Subject: Create dimensions.
Summary:
This sample shows how to add a dimension to a selected structure wall from its start to its end.

샘플은 선택한 구조벽의 시작과 끝부분에 치수를 추가하는 방법을 보여줍니다.

 

Classes:

Autodesk.Revit.UI.IExternalCommand

Autodesk.Revit.DB.View

Autodesk.Revit.DB.Wall

Autodesk.Revit.DB.Dimension

Autodesk.Revit.DB.CategorySet

Autodesk.Revit.DB.Category

Autodesk.Revit.UI.Selection.SelElementSet

Autodesk.Revit.DB.Location

Autodesk.Revit.DB.LocationCurve

Autodesk.Revit.DB.Curve

Autodesk.Revit.DB.Line

Autodesk.Revit.DB.ReferenceArray

Autodesk.Revit.DB.Options

Autodesk.Revit.DB.Element

Autodesk.Revit.DB.GeometryObjectArray

Autodesk.Revit.DB.GeometryObject

 

Project Files:

Command.cs

It contains the class Command which implements interface IExternalCommand. It also provides the function of adding a dimension to a selected wall from its start point to its end point
Command.cs 외부명령을 구현하는 인터페이스를 포함하고 있으며 또한 선택한 벽의 시작과 끝부분에 치수를 추가하는 함수를 제공하다

 

Description:

This sample provides following functionalities.
샘플은 다음과 같은 기능을 제공합니다.

-     To get one element by using its Id, use Docment.Element(ElementId) method.
Docment.Element(ElementId) 메소드로 ID 이용하여 요소값을 얻기

-     Retrieve all the walls in the current project.
현재 프로젝트의 모든 벽을 검색합니다.

-     Loop to get every wall and perform following actions
모든 벽을 가지고 다음과 같은 작업 수행을 반복합니다.

-     Get the wall’s local curve and create a new bound line with its start point and end point

-    Loop the wall’s geometry elements and find the two upright lines beside the line   created in step 1. Create a reference array contains the references of the two lines

-    Create a new bound line which is close and parallel to the line in step 1

-    Create a dimension for the wall using the reference array as its bounds and the parallel line as its place

 

Instructions:

1.   Open Revit Structure.

2.   Draw some walls which have analytical model lines and select them

3.   Make sure that the active view is not a View3D or ViewSheet.

4.   Execute the external Command.



//
// (C) Copyright 2003-2013 by Autodesk, Inc.
//dsfsdf
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//

using System;
using System.IO;
using System.Collections;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Text;

using Autodesk;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB.Structure;


namespace Revit.SDK.Samples.CreateDimensions.CS
{
    /// 
    /// Implements the Revit add-in interface IExternalCommand
    /// 
    [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
    [Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)]
    [Autodesk.Revit.Attributes.Journaling(Autodesk.Revit.Attributes.JournalingMode.NoCommandData)]
    public class Command : IExternalCommand
    {
        ExternalCommandData m_revit = null;    //store external command
        string m_errorMessage = " ";           // store error message
        ArrayList m_walls = new ArrayList();   //store the wall of selected
        const double precision = 0.0000001;         //store the precision   

        /// 
        /// Implement this method as an external command for Revit.
        /// 
        /// An object that is passed to the external application 
        /// which contains data related to the command, 
        /// such as the application object and active view.
        /// A message that can be set by the external application 
        /// which will be displayed if a failure or cancellation is returned by 
        /// the external command.
        /// A set of elements to which the external application 
        /// can add elements that are to be highlighted in case of failure or cancellation.
        /// Return the status of the external command. 
        /// A result of Succeeded means that the API external method functioned as expected. 
        /// Cancelled can be used to signify that the user cancelled the external operation 
        /// at some point. Failure should be returned if the application is unable to proceed with 
        /// the operation.
        public Autodesk.Revit.UI.Result Execute(ExternalCommandData revit, ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            try
            {
                m_revit = revit;
                Autodesk.Revit.DB.View view = m_revit.Application.ActiveUIDocument.Document.ActiveView;
                View3D view3D = view as View3D;
                if (null != view3D)
                {
                    message += "Only create dimensions in 2D";
                    return Autodesk.Revit.UI.Result.Failed;
                }

                ViewSheet viewSheet = view as ViewSheet;
                if (null != viewSheet)
                {
                    message += "Only create dimensions in 2D";
                    return Autodesk.Revit.UI.Result.Failed;
                }

                //try too adds a dimension from the start of the wall to the end of the wall into the project
                if (!AddDimension())
                {
                    message = m_errorMessage;
                    return Autodesk.Revit.UI.Result.Failed;
                }
                return Autodesk.Revit.UI.Result.Succeeded;
            }
            catch (Exception e)
            {
                message = e.Message;
                return Autodesk.Revit.UI.Result.Failed;
            }
        }

        /// 
        /// find out the wall, insert it into a array list
        /// 
        bool initialize()
        {
            ElementSet selections = m_revit.Application.ActiveUIDocument.Selection.Elements;
            //nothing was selected
            if (0 == selections.Size)
            {
                m_errorMessage += "Please select Basic walls";
                return false;
            }

            //find out wall
            foreach (Autodesk.Revit.DB.Element e in selections)
            {
                Wall wall = e as Wall;
                if (null != wall)
                {
                    if ("Basic" != wall.WallType.Kind.ToString())
                    {
                        continue;
                    }
                    m_walls.Add(wall);
                }
            }

            //no wall was selected
            if (0 == m_walls.Count)
            {
                m_errorMessage += "Please select Basic walls";
                return false;
            }
            return true;
        }

        /// 
        /// find out every wall in the selection and add a dimension from the start of the wall to its end
        /// 
        /// if add successfully, true will be returned, else false will be returned
        public bool AddDimension()
        {
            if (!initialize())
            {
                return false;
            }

            Transaction transaction = new Transaction(m_revit.Application.ActiveUIDocument.Document, "Add Dimensions");
            transaction.Start();
            //get out all the walls in this array, and create a dimension from its start to its end
            for (int i = 0; i < m_walls.Count; i++)
            {
                Wall wallTemp = m_walls[i] as Wall;
                if (null == wallTemp)
                {
                    continue;
                }

                //get location curve
                Location location = wallTemp.Location;
                LocationCurve locationline = location as LocationCurve;
                if (null == locationline)
                {
                    continue;
                }

                //New Line

                Line newLine = null;

                //get reference
                ReferenceArray referenceArray = new ReferenceArray();

                AnalyticalModel analyticalModel = wallTemp.GetAnalyticalModel();
                IList activeCurveList = analyticalModel.GetCurves(AnalyticalCurveType.ActiveCurves);
                foreach (Curve aCurve in activeCurveList)
                {
                    // find non-vertical curve from analytical model
                    if (aCurve.GetEndPoint(0).Z == aCurve.GetEndPoint(1).Z)
                        newLine = aCurve as Line;
                    if (aCurve.GetEndPoint(0).Z != aCurve.GetEndPoint(1).Z)
                    {
                        AnalyticalModelSelector amSelector = new AnalyticalModelSelector(aCurve);
                        amSelector.CurveSelector = AnalyticalCurveSelector.StartPoint;
                        referenceArray.Append(analyticalModel.GetReference(amSelector));
                    }
                    if (2 == referenceArray.Size)
                        break;
                }
                if (referenceArray.Size != 2)
                {
                    m_errorMessage += "Did not find two references";
                    return false;
                }
                try
                {
                    //try to add new a dimension
                    Autodesk.Revit.UI.UIApplication app = m_revit.Application;
                    Document doc = app.ActiveUIDocument.Document;

                    Autodesk.Revit.DB.XYZ p1 = new XYZ(
                        newLine.GetEndPoint(0).X + 5,
                        newLine.GetEndPoint(0).Y + 5,
                        newLine.GetEndPoint(0).Z);
                    Autodesk.Revit.DB.XYZ p2 = new XYZ(
                        newLine.GetEndPoint(1).X + 5,
                        newLine.GetEndPoint(1).Y + 5,
                        newLine.GetEndPoint(1).Z);

                    Line newLine2 = Line.CreateBound(p1, p2);
                    Dimension newDimension = doc.Create.NewDimension(
                      doc.ActiveView, newLine2, referenceArray);
                }
                // catch the exceptions
                catch (Exception ex)
                {
                    m_errorMessage += ex.ToString();
                    return false;
                }
            }
            transaction.Commit();
            return true;
        }

    }
}