Ejemplo n.º 1
0
		public void Render(View3D view)
		{
			Matrix model = Matrix.RotationQuaternion(m_Rotation) * Matrix.Translation(m_Location);

			Effect.Render(view, model, m_DiffuseTextureView, m_DiffuseLightMapTextureView, m_SpecularLightMapTextureView, m_Vertices, m_Indices, m_IndexCount, m_CubeBindings);
			//Effect.RenderImposter(m_OverlayType, m_DiffuseTextureView); 
		}
Ejemplo n.º 2
0
		public override void WriteVisibleElements(View3D view,
													RectangleF ClientBounds, ref RectangleF RemainingBounds,
													SlimDX.DataStream LineVerts, ref int LineVertsCount, 
													SlimDX.DataStream LinesIndices, ref int LinesIndicesCount, 
													SlimDX.DataStream TriangleVerts, ref int TriangleVertsCount, 
													SlimDX.DataStream TriangleIndices, ref int TriangleIndicesCount)
		{
			float x, y, w, h;

			m_Bounds = UiStyleHelper.LayoutControlBounds(RemainingBounds, Location, Size, Anchor, Docking, out RemainingBounds);

			UiStyleHelper.CovertToVertCoords(m_Bounds, view.WindowSize, view.PixelSize, out x, out y, out w, out h);

			if (m_ShowBorder == true)
			{
				Color4 lineColor = UiStyleHelper.GetControlLineColor(this);

				WriteLinesForBounds(x, y, w, h, lineColor, LineVerts, ref LineVertsCount, LinesIndices, ref LinesIndicesCount);
			}

			if (m_ShowBackground == true)
			{
				Color4 backColor = UiStyleHelper.GetControlBackColor(this, m_ControlStyle);

				WriteTrianglesForBounds(x, y, w, h, backColor, TriangleVerts, ref TriangleVertsCount, TriangleIndices, ref TriangleIndicesCount);
			}
		}
Ejemplo n.º 3
0
		public override void WriteVisibleElements(View3D view, RectangleF ClientBounds, ref RectangleF RemainingBounds, SlimDX.DataStream LineVerts, ref int LineVertsCount, SlimDX.DataStream LinesIndices, ref int LinesIndicesCount, SlimDX.DataStream TriangleVerts, ref int TriangleVertsCount, SlimDX.DataStream TriangleIndices, ref int TriangleIndicesCount)
		{
			SizeF stringSize = TextRenderHelper.MessureString(m_Text, m_FontType, view, 1f);

			if (m_FixedSize == false)
			{
				this.Size = new System.Drawing.Size(m_Padding.Horizontal + (int)stringSize.Width, m_Padding.Vertical + (int)stringSize.Height);
			}

			m_Bounds = UiStyleHelper.LayoutControlBounds(RemainingBounds, Location, Size, Anchor, Docking, out RemainingBounds);

			float x, y;
			float px = view.PixelSize.X;
			float py = view.PixelSize.Y;

			PointF textLocation = UiStyleHelper.LayoutTextBounds(Bounds, stringSize, TextAlign, Padding);

			UiStyleHelper.CovertToVertCoords_Relitive(textLocation, view.PixelSize, out x, out y);	

			Color4 textColor; 

			if (TextColorOverride == true)
			{
				textColor = m_TextColor;
			}
			else
			{
				textColor = UiStyleHelper.GetControlTextColor(this, DisplayMode.Auto);
			}

			TextRenderHelper.WriteString(view, Bounds,
											m_Text, m_FontType, new Vector3(x, y, ZIndexForLines_Float), 1f, textColor,
											TriangleVerts, ref TriangleVertsCount,
											TriangleIndices, ref TriangleIndicesCount);
		}
Ejemplo n.º 4
0
		public override void WriteVisibleElements(View3D view,
													RectangleF ClientBounds, ref RectangleF RemainingBounds,
													SlimDX.DataStream LineVerts, ref int LineVertsCount, 
													SlimDX.DataStream LinesIndices, ref int LinesIndicesCount, 
													SlimDX.DataStream TriangleVerts, ref int TriangleVertsCount, 
													SlimDX.DataStream TriangleIndices, ref int TriangleIndicesCount)
		{
			base.WriteVisibleElements(view, ClientBounds, ref RemainingBounds,
									LineVerts, ref LineVertsCount, 
									LinesIndices, ref LinesIndicesCount, 
									TriangleVerts, ref TriangleVertsCount, 
									TriangleIndices, ref TriangleIndicesCount);

			RectangleF innerBounds = Bounds; 

			foreach (UiControl ctrl in Controls)
			{
				if (ctrl.IsVisible == false)
				{
					continue; 
				}

				ctrl.WriteVisibleElements(view, ClientBounds, ref innerBounds,
											LineVerts, ref LineVertsCount,
											LinesIndices, ref LinesIndicesCount,
											TriangleVerts, ref TriangleVertsCount,
											TriangleIndices, ref TriangleIndicesCount);
			}
		}
Ejemplo n.º 5
0
 //class constructor
 public Revit_View_ThreeD(View3D view)
 {
     vView3D = view;
     vCameraPosition=vView3D.EyePosition;
     vCameraViewDirection = vView3D.ViewDirection;
     vCameraUp = vView3D.UpDirection;
 }
Ejemplo n.º 6
0
		public override void WriteVisibleElements(View3D view, RectangleF ClientBounds, ref RectangleF RemainingBounds, SlimDX.DataStream LineVerts, ref int LineVertsCount, SlimDX.DataStream LinesIndices, ref int LinesIndicesCount, SlimDX.DataStream TriangleVerts, ref int TriangleVertsCount, SlimDX.DataStream TriangleIndices, ref int TriangleIndicesCount)
		{
			base.WriteVisibleElements(view, ClientBounds,ref RemainingBounds, LineVerts, ref LineVertsCount, LinesIndices, ref LinesIndicesCount, TriangleVerts, ref TriangleVertsCount, TriangleIndices, ref TriangleIndicesCount);

			RectangleF inner = Bounds; 
			foreach (MenuBarItem item in Items)
			{
				item.WriteVisibleElements(view, ClientBounds, ref inner, LineVerts, ref LineVertsCount, LinesIndices, ref LinesIndicesCount, TriangleVerts, ref TriangleVertsCount, TriangleIndices, ref TriangleIndicesCount);
			}
		}
Ejemplo n.º 7
0
		public override void WriteVisibleElements(View3D view, RectangleF ClientBounds, ref RectangleF RemainingBounds, SlimDX.DataStream LineVerts, ref int LineVertsCount, SlimDX.DataStream LinesIndices, ref int LinesIndicesCount, SlimDX.DataStream TriangleVerts, ref int TriangleVertsCount, SlimDX.DataStream TriangleIndices, ref int TriangleIndicesCount)
		{
			if (FixedSize == false)
			{ 
				SizeF stringSize = TextRenderHelper.MessureString(m_MaxLength, m_FontType, view, 1f);

				this.Size = new System.Drawing.Size(m_Padding.Horizontal + (int)stringSize.Width, m_Padding.Vertical + (int)stringSize.Height);
			}

			m_Bounds = UiStyleHelper.LayoutControlBounds(RemainingBounds, Location, Size, Anchor, Docking, out RemainingBounds);
		}
    void SetWhiteRenderBackground( View3D view )
    {
      RenderingSettings rs = view.GetRenderingSettings();
      rs.BackgroundStyle = BackgroundStyle.Color;

      ColorBackgroundSettings cbs
        = (ColorBackgroundSettings) rs
          .GetBackgroundSettings();

      cbs.Color = new Color( 255, 0, 0 );
      rs.SetBackgroundSettings( cbs );
      view.SetRenderingSettings( rs );
    }
Ejemplo n.º 9
0
 /// <summary>
 /// Constructor, initialize all the fields.
 /// </summary>
 /// <param name="rvtDoc">Revit Document</param>
 public Detector(Document rvtDoc)
 {
     m_rvtDoc = rvtDoc;
     FilteredElementCollector collector = new FilteredElementCollector(m_rvtDoc);
     FilteredElementIterator iter = collector.OfClass(typeof(View3D)).GetElementIterator();
     iter.Reset();
     while(iter.MoveNext())
     {
         m_view3d = iter.Current as View3D;
         if (null != m_view3d && !m_view3d.IsTemplate)
             break;
     }
 }
Ejemplo n.º 10
0
		public static SizeF MessureString(int maxLength, FontType fontType, View3D view, float scale)
		{
			float width = 0, height = 0;

			Rectangle charSize = Effect.TextFont[fontType];

			height = (float)charSize.Height;
			width = (float)charSize.Width * maxLength; 

			width *= scale;
			height *= scale;

			return new SizeF(width, height);
		}
Ejemplo n.º 11
0
        public Result Execute(
          ExternalCommandData commandData,
          ref string message,
          ElementSet elements)
        {
            #if !VERSION2014
            Debug.Print("Version 2013");
            #else
            Debug.Print("Version 2014");
            #endif // VERSION2014
            UIApplication uiapp = commandData.Application;
            UIDocument uidoc = uiapp.ActiveUIDocument;
            Application app = uiapp.Application;
            Document doc = uidoc.Document;

            bool isNavisAvailable = OptionalFunctionalityUtils.IsNavisworksExporterAvailable();
            if (isNavisAvailable)
            {

                _default3dView = new FilteredElementCollector(doc).OfClass(typeof(View3D)).FirstElement() as View3D;

                NavisworksExportOptions neo = new NavisworksExportOptions();
                m_neo = neo;
                m_neo.ExportScope = NavisworksExportScope.View;
                m_neo.FindMissingMaterials = false;

                Form1 formDialog = new Form1(doc, m_neo);
                System.Windows.Forms.DialogResult dr = formDialog.ShowDialog();

                if (dr == System.Windows.Forms.DialogResult.OK)
                {
                    return Result.Succeeded;
                }
                else
                    return Result.Cancelled;
            }
            else
            {
                TaskDialog.Show("Error", "No Compatible Navisworks plugins found. Please install a compatible Navisworks exporter to use with Revit.");
                return Result.Failed;
            }
        }
Ejemplo n.º 12
0
		public static SizeF MessureString(string str, FontType fontType, View3D view, float scale)
		{
			float width = 0, height = 0;

			foreach (char @char in str)
			{
				RectangleF rect = Effect.TextFont[fontType, @char];

				if (rect.Height > height)
				{
					height = rect.Height; 
				}

				width += rect.Width; 
			}

			width *= Effect.TextFont.TextureSize * scale;
			height *= Effect.TextFont.TextureSize * scale;

			return new SizeF(width, height);
		}
Ejemplo n.º 13
0
		public void WriteDynamicElements(View3D view, SlimDX.DataStream LineVerts, ref int LineVertsCount, SlimDX.DataStream LinesIndices, ref int LinesIndicesCount, SlimDX.DataStream TriangleVerts, ref int TriangleVertsCount, SlimDX.DataStream TriangleIndices, ref int TriangleIndicesCount)
		{
			string text = m_Text;
			
			if (text == null)
			{
				text = ""; 
			}
			else if (text.Length > m_MaxLength)
			{
				text = text.Substring(0, m_MaxLength);
			}

			SizeF stringSize = TextRenderHelper.MessureString(text, m_FontType, view, 1f);
			
			float x, y;
			float px = view.PixelSize.X;
			float py = view.PixelSize.Y;

			PointF textLocation = UiStyleHelper.LayoutTextBounds(Bounds, stringSize, TextAlign, Padding);

			UiStyleHelper.CovertToVertCoords_Relitive(textLocation, view.PixelSize, out x, out y);			

			Color4 textColor;

			if (m_ForeColor == new Color4())
			{
				textColor = UiStyleHelper.GetControlTextColor(this, DisplayMode.Auto);
			}
			else
			{
				textColor = m_ForeColor; 
			}

			TextRenderHelper.WriteString(view, Bounds,
											text, m_FontType, new Vector3(x, y, ZIndexForLines_Float), 1f, textColor,
											TriangleVerts, ref TriangleVertsCount,
											TriangleIndices, ref TriangleIndicesCount);
		}
Ejemplo n.º 14
0
		public static void WriteString(View3D view,
											RectangleF RemainingBounds,
											string str, FontType fontType, ref float px, ref float py, float z, float scale, Color4 color,
											SlimDX.DataStream TriangleVerts, ref int TriangleVertsCount,
											SlimDX.DataStream TriangleIndices, ref int TriangleIndicesCount)
		{
			float x, y, w, h;
			float pw, ph; 

			//UiStyleHelper.CovertToVertCoords(px, py, view.WindowSize, view.PixelSize, out x, out y);
			UiStyleHelper.CovertToVertCoords(RemainingBounds, view.WindowSize, view.PixelSize, out x, out y, out w, out h);

			x += px;
			y += py; 

			foreach (char @char in str)
			{
				RectangleF rect = Effect.TextFont[fontType, @char];

				//pw = rect.Width * Effect.TextFont.TextureSize * scale;
				//ph = rect.Height * Effect.TextFont.TextureSize * scale;

				w = rect.Width * Effect.TextFont.TextureSize * view.PixelSize.X * scale;
				h = rect.Height * Effect.TextFont.TextureSize * view.PixelSize.Y * scale;

				TriangleVerts.WriteRange(new UIVertex[] { 
					new UIVertex() { Color = color, Position = new Vector3(x, y, z), TextureCoords = new Vector2(rect.Left, rect.Top) },
					new UIVertex() { Color = color, Position = new Vector3(x + w, y, z), TextureCoords = new Vector2(rect.Right, rect.Top) },
					new UIVertex() { Color = color, Position = new Vector3(x, y - h, z), TextureCoords = new Vector2(rect.Left, rect.Bottom) },
					new UIVertex() { Color = color, Position = new Vector3(x + w, y - h, z), TextureCoords = new Vector2(rect.Right, rect.Bottom) }
				});

				int i = TriangleVertsCount;

				TriangleIndices.WriteRange(new int[] { 
					i + 0, i + 1, i + 2,
					i + 1, i + 3, i + 2
				});

				TriangleVertsCount += 4;
				TriangleIndicesCount += 6;

				x += w;
				px += w;
			}
		}
        public override Result OnExecute(ExternalCommandData InCommandData, ref string OutCommandMessage, ElementSet OutElements)
        {
            UIDocument UIDoc      = InCommandData.Application.ActiveUIDocument;
            Document   Doc        = UIDoc.Document;
            View3D     ActiveView = Doc.ActiveView as View3D;

            if (ActiveView == null)
            {
                string Message = "You must be in a 3D view to export.";
                MessageBox.Show(Message, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(Result.Cancelled);
            }

            if (ActiveView.IsTemplate || !ActiveView.CanBePrinted)
            {
                string Message = "The active 3D view cannot be exported.";
                MessageBox.Show(Message, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(Result.Cancelled);
            }

            Debug.Assert(FDirectLink.Get() != null);

            // Holding ctrl will force full sync.
            if (FDirectLink.Get().SyncCount > 0 && (System.Windows.Forms.Control.ModifierKeys & Keys.Control) == Keys.Control)
            {
                FDirectLink.DestroyInstance(FDirectLink.Get(), InCommandData.Application.Application);
                FDirectLink.ActivateInstance(Doc);
            }

            FDatasmithRevitExportContext ExportContext = new FDatasmithRevitExportContext(
                InCommandData.Application.Application,
                Doc,
                null,
                new DatasmithRevitExportOptions(Doc),
                FDirectLink.Get());

            // Export the active 3D View to the given Unreal Datasmith file.
            using (CustomExporter Exporter = new CustomExporter(Doc, ExportContext))
            {
                try
                {
                    // The export process will exclude output of geometric objects such as faces and curves,
                    // but the context needs to receive the calls related to Faces or Curves to gather data.
                    // The context always receive their tessellated geometry in form of polymeshes or lines.
                    Exporter.IncludeGeometricObjects = true;

                    // The export process should stop in case an error occurs during any of the exporting methods.
                    Exporter.ShouldStopOnError = true;

#if REVIT_API_2020
                    Exporter.Export(ActiveView as Autodesk.Revit.DB.View);
#else
                    Exporter.Export(ActiveView);
#endif
                }
                catch (System.Exception exception)
                {
                    OutCommandMessage = string.Format("Cannot export the 3D view:\n\n{0}\n\n{1}", exception.Message, exception.StackTrace);
                    MessageBox.Show(OutCommandMessage, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return(Result.Failed);
                }
                finally
                {
                    if (ExportContext.GetMessages().Count > 0)
                    {
                        string Messages = string.Join($"{System.Environment.NewLine}", ExportContext.GetMessages());
                        DatasmithRevitApplication.SetExportMessages(Messages);
                    }
                }
            }

            return(Result.Succeeded);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Export a given 3D view to JSON using
        /// our custom exporter context.
        /// </summary>
        void ExportView3D( View3D view3d, string filename )
        {
            AppDomain.CurrentDomain.AssemblyResolve
            += CurrentDomain_AssemblyResolve;

              Document doc = view3d.Document;

              Va3cExportContext context
            = new Va3cExportContext( doc, filename );

              CustomExporter exporter = new CustomExporter(
            doc, context );

              // Note: Excluding faces just suppresses the
              // OnFaceBegin calls, not the actual processing
              // of face tessellation. Meshes of the faces
              // will still be received by the context.

              exporter.IncludeFaces = false;

              exporter.ShouldStopOnError = false;

              exporter.Export( view3d );
        }
Ejemplo n.º 17
0
        private bool Create3DView()
        {
            bool result = false;

            try
            {
                BoundingBoxXYZ            boundingBox       = null;
                Dictionary <int, Element> elementDictionary = new Dictionary <int, Element>();
                foreach (ListViewItem item in listViewComponents.Items)
                {
                    if (null != item.Tag)
                    {
                        Element element = item.Tag as Element;
                        if (null != element.get_BoundingBox(null) && !elementDictionary.ContainsKey(element.Id.IntegerValue))
                        {
                            elementDictionary.Add(element.Id.IntegerValue, element);
                        }
                    }
                }

                boundingBox = elementDictionary[elementDictionary.Keys.First()].get_BoundingBox(null);

                double maxX = boundingBox.Max.X;
                double maxY = boundingBox.Max.Y;
                double maxZ = boundingBox.Max.Z;
                double minX = boundingBox.Min.X;
                double minY = boundingBox.Min.Y;
                double minZ = boundingBox.Min.Z;

                foreach (int eId in elementDictionary.Keys)
                {
                    Element element = elementDictionary[eId];
                    boundingBox = element.get_BoundingBox(null);
                    if (null != boundingBox)
                    {
                        if (boundingBox.Max.X > maxX)
                        {
                            maxX = boundingBox.Max.X;
                        }
                        if (boundingBox.Max.Y > maxY)
                        {
                            maxY = boundingBox.Max.Y;
                        }
                        if (boundingBox.Max.Z > maxZ)
                        {
                            maxZ = boundingBox.Max.Z;
                        }
                        if (boundingBox.Min.X < minX)
                        {
                            minX = boundingBox.Min.X;
                        }
                        if (boundingBox.Min.Y < minY)
                        {
                            minY = boundingBox.Min.Y;
                        }
                        if (boundingBox.Min.Z < minZ)
                        {
                            minZ = boundingBox.Min.Z;
                        }
                    }
                }

                XYZ xyzMax = new XYZ(maxX, maxY, maxZ);
                XYZ xyzMin = new XYZ(minX, minY, minZ);

                boundingBox.Max = xyzMax;
                boundingBox.Min = xyzMin;
                using (Transaction trans = new Transaction(m_doc))
                {
                    trans.Start("Create a 3DView");
                    View3D view3d = View3D.CreateIsometric(m_doc, view3dFamilyType.Id);
#if RELEASE2013
                    view3d.SectionBox = boundingBox;
#else
                    view3d.SetSectionBox(boundingBox);
                    view3d.GetSectionBox().Enabled = true;
#endif

                    view3d.Name = selectedView;

#if RELEASE2014 || RELEASE2015 || RELEASE2016 || RELEASE2017
                    SetElementTransparency(view3d, elementDictionary);
#endif

                    if (!view3dDictionary.ContainsKey(view3d.Name))
                    {
                        view3dDictionary.Add(view3d.Name, view3d);
                    }
                    trans.Commit();
                }
                result = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to create a 3DView named " + selectedView + "\n" + ex.Message, "CommandForm:Create3DView", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                result = false;
            }
            return(result);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Generate Viewpoint
        /// </summary>
        /// <param name="elemCheck"></param>
        /// <returns></returns>
        public VisualizationInfo generateViewpoint(int elemCheck)
        {
            try
            {
                UIDocument uidoc = uiapp.ActiveUIDocument;
                Document   doc   = uidoc.Document;

                VisualizationInfo v = new VisualizationInfo();

                XYZ    centerIMP = new XYZ();
                string type      = "";
                double zoomValue = 1;

                if (uidoc.ActiveView.ViewType != ViewType.ThreeD) //is a 2D view
                {
                    XYZ TL = uidoc.GetOpenUIViews()[0].GetZoomCorners()[0];
                    XYZ BR = uidoc.GetOpenUIViews()[0].GetZoomCorners()[1];
                    v.SheetCamera             = new SheetCamera();
                    v.SheetCamera.SheetID     = uidoc.ActiveView.Id.IntegerValue;
                    v.SheetCamera.TopLeft     = new IssueTracker.Classes.BCF2.Point(TL.X, TL.Y, TL.Z);
                    v.SheetCamera.BottomRight = new IssueTracker.Classes.BCF2.Point(BR.X, BR.Y, BR.Z);
                }
                else
                {
                    View3D view3D = (View3D)uidoc.ActiveView;
                    if (!view3D.IsPerspective) //IS ORTHO
                    {
                        XYZ TL = uidoc.GetOpenUIViews()[0].GetZoomCorners()[0];
                        XYZ BR = uidoc.GetOpenUIViews()[0].GetZoomCorners()[1];

                        double xO = (TL.X + BR.X) / 2;
                        double yO = (TL.Y + BR.Y) / 2;
                        double zO = (TL.Z + BR.Z) / 2;
                        //converto to METERS
                        centerIMP = new XYZ(xO, yO, zO);
                        double dist       = TL.DistanceTo(BR) / 2; //custom sectet value to get solibri zoom value from Corners of Revit UiView
                        XYZ    diagVector = TL.Subtract(BR);
                        // **** CUSTOM VALUE FOR TEKLA **** //
                        //zoomValue = UnitUtils.ConvertFromInternalUnits(dist * Math.Sin(diagVector.AngleTo(view3D.RightDirection)), DisplayUnitType.DUT_METERS);
                        // **** CUSTOM VALUE FOR TEKLA **** //
                        double customZoomValue = (MyProjectSettings.Get("useDefaultZoom", doc.PathName) == "1") ? 1 : 2.5;

                        zoomValue = UnitUtils.ConvertFromInternalUnits(dist * Math.Sin(diagVector.AngleTo(view3D.RightDirection)), DisplayUnitType.DUT_METERS) * customZoomValue;
                        type      = "OrthogonalCamera";
                    }
                    else // it is a perspective view
                    {
                        centerIMP = uidoc.ActiveView.Origin;
                        type      = "PerspectiveCamera";
                        zoomValue = 45;
                    }
                    ViewOrientation3D t = ConvertBasePoint(centerIMP, uidoc.ActiveView.ViewDirection, uidoc.ActiveView.UpDirection, false);
                    //ViewOrientation3D t = new ViewOrientation3D(centerIMP, uidoc.ActiveView.UpDirection, uidoc.ActiveView.ViewDirection);
                    XYZ c  = t.EyePosition;
                    XYZ vi = t.ForwardDirection;
                    XYZ up = t.UpDirection;

                    if (type == "OrthogonalCamera")
                    {
                        v.OrthogonalCamera = new OrthogonalCamera();
                        v.OrthogonalCamera.CameraViewPoint.X = UnitUtils.ConvertFromInternalUnits(c.X, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraViewPoint.Y = UnitUtils.ConvertFromInternalUnits(c.Y, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraViewPoint.Z = UnitUtils.ConvertFromInternalUnits(c.Z, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraUpVector.X  = UnitUtils.ConvertFromInternalUnits(up.X, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraUpVector.Y  = UnitUtils.ConvertFromInternalUnits(up.Y, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraUpVector.Z  = UnitUtils.ConvertFromInternalUnits(up.Z, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraDirection.X = UnitUtils.ConvertFromInternalUnits(vi.X, DisplayUnitType.DUT_METERS) * -1;
                        v.OrthogonalCamera.CameraDirection.Y = UnitUtils.ConvertFromInternalUnits(vi.Y, DisplayUnitType.DUT_METERS) * -1;
                        v.OrthogonalCamera.CameraDirection.Z = UnitUtils.ConvertFromInternalUnits(vi.Z, DisplayUnitType.DUT_METERS) * -1;
                        v.OrthogonalCamera.ViewToWorldScale  = zoomValue;
                    }
                    else
                    {
                        v.PerspectiveCamera = new PerspectiveCamera();
                        v.PerspectiveCamera.CameraViewPoint.X = UnitUtils.ConvertFromInternalUnits(c.X, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraViewPoint.Y = UnitUtils.ConvertFromInternalUnits(c.Y, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraViewPoint.Z = UnitUtils.ConvertFromInternalUnits(c.Z, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraUpVector.X  = UnitUtils.ConvertFromInternalUnits(up.X, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraUpVector.Y  = UnitUtils.ConvertFromInternalUnits(up.Y, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraUpVector.Z  = UnitUtils.ConvertFromInternalUnits(up.Z, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraDirection.X = UnitUtils.ConvertFromInternalUnits(vi.X, DisplayUnitType.DUT_METERS) * -1;
                        v.PerspectiveCamera.CameraDirection.Y = UnitUtils.ConvertFromInternalUnits(vi.Y, DisplayUnitType.DUT_METERS) * -1;
                        v.PerspectiveCamera.CameraDirection.Z = UnitUtils.ConvertFromInternalUnits(vi.Z, DisplayUnitType.DUT_METERS) * -1;
                        v.PerspectiveCamera.FieldOfView       = zoomValue;
                    }


                    // handle section box if enabled
                    if (view3D.IsSectionBoxActive)
                    {
                        BoundingBoxXYZ sectionBox = view3D.GetSectionBox();

                        // Note that the section box can be rotated and transformed.
                        // So the min/max corners coordinates relative to the model must be computed via the transform.
                        Transform trf = sectionBox.Transform;

                        XYZ max = sectionBox.Max; //Maximum coordinates (upper-right-front corner of the box before transform is applied).
                        XYZ min = sectionBox.Min; //Minimum coordinates (lower-left-rear corner of the box before transform is applied).

                        // Transform the min and max to model coordinates
                        XYZ maxInModelCoords = trf.OfPoint(max);
                        XYZ minInModelCoords = trf.OfPoint(min);

                        // Convert to shared coordinates
                        maxInModelCoords = ARUP.IssueTracker.Revit.Classes.Utils.ConvertToFromSharedCoordinate(doc, maxInModelCoords, false);
                        minInModelCoords = ARUP.IssueTracker.Revit.Classes.Utils.ConvertToFromSharedCoordinate(doc, minInModelCoords, false);

                        // Convert to project unit
                        DisplayUnitType lengthUnitType = DisplayUnitType.DUT_METERS;
                        maxInModelCoords = new XYZ(UnitUtils.ConvertFromInternalUnits(maxInModelCoords.X, lengthUnitType),
                                                   UnitUtils.ConvertFromInternalUnits(maxInModelCoords.Y, lengthUnitType),
                                                   UnitUtils.ConvertFromInternalUnits(maxInModelCoords.Z, lengthUnitType));
                        minInModelCoords = new XYZ(UnitUtils.ConvertFromInternalUnits(minInModelCoords.X, lengthUnitType),
                                                   UnitUtils.ConvertFromInternalUnits(minInModelCoords.Y, lengthUnitType),
                                                   UnitUtils.ConvertFromInternalUnits(minInModelCoords.Z, lengthUnitType));

                        // Add to BCF clipping planes
                        v.ClippingPlanes = ARUP.IssueTracker.Revit.Classes.Utils.GetClippingPlanesFromBoundingBox(maxInModelCoords, minInModelCoords, trf, doc);
                    }
                }


                //COMPONENTS PART
                FilteredElementCollector collector = new FilteredElementCollector(doc, doc.ActiveView.Id).WhereElementIsNotElementType();
                System.Collections.Generic.ICollection <ElementId> collection = null;

                if (elemCheck == 0)
                {
                    collection = collector.ToElementIds();
                }
                else if (elemCheck == 1)
                {
                    collection = uidoc.Selection.GetElementIds();
                }

                if (null != collection && collection.Any())
                {
                    v.Components = new List <IssueTracker.Classes.BCF2.Component>();
                    foreach (var eId in collection)
                    {
                        Guid   guid    = ExportUtils.GetExportId(doc, eId);
                        string ifcguid = IfcGuid.ToIfcGuid(guid).ToString();
                        v.Components.Add(new ARUP.IssueTracker.Classes.BCF2.Component(doc.Application.VersionName, eId.ToString(), ifcguid));
                    }
                }

                return(v);
            }
            catch (System.Exception ex1)
            {
                TaskDialog.Show("Error!", "exception: " + ex1);
            }
            return(null);
        }
Ejemplo n.º 19
0
		public override void WriteVisibleElements(View3D view, RectangleF ClientBounds, ref RectangleF RemainingBounds, SlimDX.DataStream LineVerts, ref int LineVertsCount, SlimDX.DataStream LinesIndices, ref int LinesIndicesCount, SlimDX.DataStream TriangleVerts, ref int TriangleVertsCount, SlimDX.DataStream TriangleIndices, ref int TriangleIndicesCount)
		{
			float x, y, w, h;

			SizeF lineSize = TextRenderHelper.MessureString(m_EmptyLine, FontType.Monospaced, view, 1f);

			Size = new System.Drawing.Size((int)lineSize.Width + m_Padding.Horizontal, (int)(lineSize.Height * m_NumberOfLines) + m_Padding.Vertical);

			m_Bounds = UiStyleHelper.LayoutControlBounds(RemainingBounds, Location, Size, Anchor, Docking, out RemainingBounds);

			m_Bounds = new RectangleF(m_Bounds.X, m_Bounds.Y, m_Bounds.Width, m_Bounds.Height - 1f);

			UiStyleHelper.CovertToVertCoords(m_Bounds, view.WindowSize, view.PixelSize, out x, out y, out w, out h);

			Color4 lineColor = UiStyleHelper.GetControlLineColor(this);

			WriteLinesForBounds(x, y, w, h, lineColor, LineVerts, ref LineVertsCount, LinesIndices, ref LinesIndicesCount);

			Color4 backColor = UiStyleHelper.GetControlBackColor(this, DisplayMode.Normal);

			WriteTrianglesForBounds(x, y, w, h, backColor, TriangleVerts, ref TriangleVertsCount, TriangleIndices, ref TriangleIndicesCount);
		}
Ejemplo n.º 20
0
		public void OnMouseUp(View3D view, Vector2 mousePosition, System.Windows.Forms.MouseButtons mouseButtons, out bool shouldUpdate)
		{
			Vector2 mousePositionCorrected = mousePosition + view.ViewportOffset; // new Vector2(view.Viewport.X, view.Viewport.Y);

			shouldUpdate = false;

			if (m_Focused != null)
			{
				if (m_Focused is UiSubScene)
				{
					bool shouldSubUpdate;

					(m_Focused as UiSubScene).OnMouseUp(view, mousePosition, mouseButtons, out shouldSubUpdate);
					
					m_MouseState = MouseState.Hovering;

					m_Control_ClickStart = null;
				}
				else
				{
					if (m_MouseState == MouseState.Dragging ||
						m_MouseState == MouseState.DragStart)
					{
						m_MouseState = MouseState.DragEnd;

						m_Focused.DoMouseInteraction(m_MouseState, m_MouseButtons, mousePositionCorrected, out shouldUpdate);

						m_Control_ClickStart = null;
					}
					else if (m_MouseState == MouseState.ClickStart)
					{
						m_MouseState = MouseState.ClickEnd;

						m_Focused.DoMouseInteraction(m_MouseState, m_MouseButtons, mousePositionCorrected, out shouldUpdate);
						
						m_Control_ClickStart = null;
					}
					else
					{
						m_MouseState = MouseState.Hovering;

						m_Control_ClickStart = null;
					}
				}
			}
			else
			{
				m_MouseState = MouseState.None;

				m_Control_ClickStart = null;
			}
		}
Ejemplo n.º 21
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="app"></param>
 /// <param name="view3D"></param>
 /// <returns></returns>
 private static Revit.Element CloneElement( Autodesk.Revit.UI.UIApplication app, View3D view3D )
 {
     XYZ viewDir = view3D.ViewDirection;
       View3D view3DClone = View3D.CreateIsometric( app.ActiveUIDocument.Document, view3D.GetTypeId() );
       Utils.ParamUtil.SetParameters( view3DClone.Parameters, view3D.Parameters );
       return view3DClone;
 }
        // Implement the interface to execute the command.
        public override Result OnExecute(ExternalCommandData InCommandData, ref string OutCommandMessage, ElementSet OutElements)
        {
            UIDocument UIDoc = InCommandData.Application.ActiveUIDocument;
            Document   Doc   = UIDoc.Document;

            string DocumentPath = Doc.PathName;

            if (string.IsNullOrWhiteSpace(DocumentPath))
            {
                string message = "Your document must be saved on disk before exporting.";
                MessageBox.Show(message, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(Result.Cancelled);
            }

            bool ExportActiveViewOnly = true;

            // Retrieve the Unreal Datasmith export options.
            DatasmithRevitExportOptions ExportOptions = new DatasmithRevitExportOptions(Doc);

            if ((System.Windows.Forms.Control.ModifierKeys & Keys.Control) == Keys.Control)
            {
                if (ExportOptions.ShowDialog() != DialogResult.OK)
                {
                    return(Result.Cancelled);
                }
                ExportActiveViewOnly = false;
            }

            // Generate file path for each view.
            Dictionary <ElementId, string> FilePaths = new Dictionary <ElementId, string>();
            List <View3D> ViewsToExport = new List <View3D>();

            if (ExportActiveViewOnly)
            {
                View3D ActiveView = Doc.ActiveView as View3D;

                if (ActiveView == null)
                {
                    string Message = "You must be in a 3D view to export.";
                    MessageBox.Show(Message, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return(Result.Cancelled);
                }

                if (ActiveView.IsTemplate || !ActiveView.CanBePrinted)
                {
                    string Message = "The active 3D view cannot be exported.";
                    MessageBox.Show(Message, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return(Result.Cancelled);
                }

                string ViewFamilyName = ActiveView.get_Parameter(BuiltInParameter.ELEM_FAMILY_PARAM).AsValueString().Replace(" ", "");
                string FileName       = Regex.Replace($"{Path.GetFileNameWithoutExtension(DocumentPath)}-{ViewFamilyName}-{ActiveView.Name}.udatasmith", @"\s+", "_");

                SaveFileDialog Dialog = new SaveFileDialog();

                Dialog.Title            = DIALOG_CAPTION;
                Dialog.InitialDirectory = Path.GetDirectoryName(DocumentPath);
                Dialog.FileName         = FileName;
                Dialog.DefaultExt       = "udatasmith";
                Dialog.Filter           = "Unreal Datasmith|*.udatasmith";
                Dialog.CheckFileExists  = false;
                Dialog.CheckPathExists  = true;
                Dialog.AddExtension     = true;
                Dialog.OverwritePrompt  = true;

                if (Dialog.ShowDialog() != DialogResult.OK)
                {
                    return(Result.Cancelled);
                }

                string FilePath = Dialog.FileName;

                if (string.IsNullOrWhiteSpace(FilePath))
                {
                    string message = "The given Unreal Datasmith file name is blank.";
                    MessageBox.Show(message, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return(Result.Cancelled);
                }

                FilePaths.Add(ActiveView.Id, FilePath);
                ViewsToExport.Add(ActiveView);
            }
            else
            {
                string SavePath;
                using (var FBD = new FolderBrowserDialog())
                {
                    FBD.ShowNewFolderButton = true;
                    DialogResult result = FBD.ShowDialog();

                    if (result != DialogResult.OK || string.IsNullOrWhiteSpace(FBD.SelectedPath))
                    {
                        return(Result.Cancelled);
                    }

                    SavePath = FBD.SelectedPath;
                }

                foreach (var View in ExportOptions.Selected3DViews)
                {
                    string ViewFamilyName = View.get_Parameter(BuiltInParameter.ELEM_FAMILY_PARAM).AsValueString().Replace(" ", "");
                    string FileName       = Regex.Replace($"{Path.GetFileNameWithoutExtension(DocumentPath)}-{ViewFamilyName}-{View.Name}.udatasmith", @"\s+", "_");
                    FilePaths.Add(View.Id, Path.Combine(SavePath, FileName));
                    ViewsToExport.Add(View);
                }
            }

            // Prevent user interaction with the active 3D view to avoid the termination of the custom export,
            // without Revit providing any kind of internal or external feedback.
            EnableViewWindow(InCommandData.Application, false);

            // Create a custom export context for command Export to Unreal Datasmith.
            FDatasmithRevitExportContext ExportContext = new FDatasmithRevitExportContext(
                InCommandData.Application.Application,
                Doc,
                FilePaths,
                ExportOptions,
                null);

            // Export the active 3D View to the given Unreal Datasmith file.
            using (CustomExporter Exporter = new CustomExporter(Doc, ExportContext))
            {
                // Add a progress bar callback.
                // application.ProgressChanged += exportContext.HandleProgressChanged;

                try
                {
                    // The export process will exclude output of geometric objects such as faces and curves,
                    // but the context needs to receive the calls related to Faces or Curves to gather data.
                    // The context always receive their tessellated geometry in form of polymeshes or lines.
                    Exporter.IncludeGeometricObjects = true;

                    // The export process should stop in case an error occurs during any of the exporting methods.
                    Exporter.ShouldStopOnError = true;

                    // Initiate the export process for all 3D views.
                    foreach (var view in ViewsToExport)
                    {
#if REVIT_API_2020
                        Exporter.Export(view as Autodesk.Revit.DB.View);
#else
                        Exporter.Export(view);
#endif
                    }
                }
                catch (System.Exception exception)
                {
                    OutCommandMessage = string.Format("Cannot export the 3D view:\n\n{0}\n\n{1}", exception.Message, exception.StackTrace);
                    MessageBox.Show(OutCommandMessage, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return(Result.Failed);
                }
                finally
                {
                    // Remove the progress bar callback.
                    // application.ProgressChanged -= exportContext.HandleProgressChanged;

                    // Restore user interaction with the active 3D view.
                    EnableViewWindow(InCommandData.Application, true);

                    if (ExportContext.GetMessages().Count > 0)
                    {
                        string Messages = string.Join($"{System.Environment.NewLine}", ExportContext.GetMessages());
                        DatasmithRevitApplication.SetExportMessages(Messages);
                    }
                }
            }

            return(Result.Succeeded);
        }
Ejemplo n.º 23
0
		public void Render(View3D view)
		{					
			if (HasBeenInvalidated)
			{
				UpdateStaticBuffers(view);

				m_HasBeenInvalidated = false;
			}

			Effect.Render(m_StaticBuffer);

			UpdateBuffers(view);

			Effect.Render(m_DynamicBuffer);

			foreach (UiSubScene scene in SubScenes)
			{
				if (scene.IsVisible == false)
				{
					continue;
				}

				if (scene.IsParentVisible == false)
				{
					continue;
				}

				scene.Render(view);
			}
		}
Ejemplo n.º 24
0
        /// <summary>
        /// The top level command.
        /// </summary>
        /// <param name="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.</param>
        /// <param name="message">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.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>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.</returns>
        public Result Execute(ExternalCommandData revit, ref string message, ElementSet elements)
        {
            m_app = revit.Application.Application;
            m_doc = revit.Application.ActiveUIDocument.Document;

            Transaction trans = new Transaction(m_doc, "Revit.SDK.Samples.MeasureHeight");

            trans.Start();
            // Find a 3D view to use for the ray tracing operation
            FilteredElementCollector collector     = new FilteredElementCollector(m_doc);
            Func <View3D, bool>      isNotTemplate = v3 => !(v3.IsTemplate);

            m_view3D = collector.OfClass(typeof(View3D)).Cast <View3D>().First <View3D>(isNotTemplate);

            Autodesk.Revit.UI.Selection.Selection selection = revit.Application.ActiveUIDocument.Selection;

            // If skylight is selected, process it.
            m_skylight = null;
            if (selection.GetElementIds().Count == 1)
            {
                foreach (ElementId eId in selection.GetElementIds())
                {
                    Element e = revit.Application.ActiveUIDocument.Document.GetElement(eId);
                    if (e is FamilyInstance)
                    {
                        FamilyInstance instance       = e as FamilyInstance;
                        bool           isWindow       = (instance.Category.Id.IntegerValue == (int)BuiltInCategory.OST_Windows);
                        bool           isHostedByRoof = (instance.Host.Category.Id.IntegerValue == (int)BuiltInCategory.OST_Roofs);

                        if (isWindow && isHostedByRoof)
                        {
                            m_skylight = instance;
                        }
                    }
                }
            }

            if (m_skylight == null)
            {
                message = "This tool requires exactly one skylight to be selected.";
                trans.RollBack();
                return(Result.Cancelled);
            }

            // Find the floor to use for the measurement (hardcoded)
            ElementId id = new ElementId(150314);

            m_floor = m_doc.GetElement(id) as Floor;

            // Calculate the height
            Line line = CalculateLineAboveFloor();

            // Create a model curve to show the distance
            Plane       plane       = Plane.CreateByNormalAndOrigin(new XYZ(1, 0, 0), line.GetEndPoint(0));
            SketchPlane sketchPlane = SketchPlane.Create(m_doc, plane);

            ModelCurve curve = m_doc.Create.NewModelCurve(line, sketchPlane);

            // Show a message with the length value
            TaskDialog.Show("Distance", "Distance to floor: " + String.Format("{0:f2}", line.Length));

            trans.Commit();
            return(Result.Succeeded);
        }
        // Implement the interface to execute the command.
        public Result Execute(
            ExternalCommandData in_commandData,                 // contains reference to Application and View
            ref string out_commandMessage,                      // error message to display in the failure dialog when the command returns "Failed"
            ElementSet out_elements                             // set of problem elements to display in the failure dialog when the command returns "Failed"
            )
        {
            Autodesk.Revit.ApplicationServices.Application application = in_commandData.Application.Application;

            if (string.Compare(application.VersionNumber, "2018", StringComparison.Ordinal) == 0 && string.Compare(application.SubVersionNumber, "2018.3", StringComparison.Ordinal) < 0)
            {
                string message = string.Format("The running Revit is not supported.\nYou must use Revit 2018.3 or further updates to export.");
                MessageBox.Show(message, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(Result.Cancelled);
            }

            if (!CustomExporter.IsRenderingSupported())
            {
                string message = "3D view rendering is not supported in the running Revit.";
                MessageBox.Show(message, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(Result.Cancelled);
            }

            UIDocument uiDocument = in_commandData.Application.ActiveUIDocument;

            if (uiDocument == null)
            {
                string message = "You must be in a document to export.";
                MessageBox.Show(message, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(Result.Cancelled);
            }

            Document document = uiDocument.Document;

            View3D activeView = document.ActiveView as View3D;

            if (activeView == null)
            {
                string message = "You must be in a 3D view to export.";
                MessageBox.Show(message, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(Result.Cancelled);
            }

            if (activeView.IsTemplate || !activeView.CanBePrinted)
            {
                string message = "The active 3D view cannot be exported.";
                MessageBox.Show(message, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(Result.Cancelled);
            }

            string documentPath = document.PathName;

            if (string.IsNullOrWhiteSpace(documentPath))
            {
                string message = "Your document must be saved on disk before exporting.";
                MessageBox.Show(message, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(Result.Cancelled);
            }

            string ViewFamilyName = activeView.get_Parameter(BuiltInParameter.ELEM_FAMILY_PARAM).AsValueString().Replace(" ", "");
            string FileName       = Regex.Replace($"{Path.GetFileNameWithoutExtension(documentPath)}-{ViewFamilyName}-{activeView.Name}.udatasmith", @"\s+", "_");

            SaveFileDialog dialog = new SaveFileDialog();

            dialog.Title            = DIALOG_CAPTION;
            dialog.InitialDirectory = Path.GetDirectoryName(documentPath);
            dialog.FileName         = FileName;
            dialog.DefaultExt       = "udatasmith";
            dialog.Filter           = "Unreal Datasmith|*.udatasmith";
            dialog.CheckFileExists  = false;
            dialog.CheckPathExists  = true;
            dialog.AddExtension     = true;
            dialog.OverwritePrompt  = true;

            if (dialog.ShowDialog() != DialogResult.OK)
            {
                return(Result.Cancelled);
            }

            string filePath = dialog.FileName;

            if (string.IsNullOrWhiteSpace(filePath))
            {
                string message = "The given Unreal Datasmith file name is blank.";
                MessageBox.Show(message, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(Result.Cancelled);
            }

            // Retrieve the Unreal Datasmith export options.
            DatasmithRevitExportOptions exportOptions = new DatasmithRevitExportOptions();

            if ((System.Windows.Forms.Control.ModifierKeys & Keys.Control) == Keys.Control)
            {
                if (exportOptions.ShowDialog() != DialogResult.OK)
                {
                    return(Result.Cancelled);
                }
            }

            // Prevent user interaction with the active 3D view to avoid the termination of the custom export,
            // without Revit providing any kind of internal or external feedback.
            EnableViewWindow(in_commandData.Application, false);

            // Create a custom export context for command Export to Unreal Datasmith.
            FDatasmithRevitExportContext exportContext = new FDatasmithRevitExportContext(in_commandData.Application.Application, document, filePath, exportOptions);

            // Export the active 3D View to the given Unreal Datasmith file.
            using (CustomExporter customExporter = new CustomExporter(document, exportContext))
            {
                // Add a progress bar callback.
                // application.ProgressChanged += exportContext.HandleProgressChanged;

                try
                {
                    // The export process will exclude output of geometric objects such as faces and curves,
                    // but the context needs to receive the calls related to Faces or Curves to gather data.
                    // The context always receive their tessellated geometry in form of polymeshes or lines.
                    customExporter.IncludeGeometricObjects = true;

                    // The export process should stop in case an error occurs during any of the exporting methods.
                    customExporter.ShouldStopOnError = true;

                    // Initiate the export process for the active 3D View.
                                        #if REVIT_API_2020
                    customExporter.Export(activeView as Autodesk.Revit.DB.View);
                                        #else
                    customExporter.Export(activeView);
                                        #endif
                }
                catch (System.Exception exception)
                {
                    out_commandMessage = string.Format("Cannot export the active 3D view:\n\n{0}\n\n{1}", exception.Message, exception.StackTrace);
                    MessageBox.Show(out_commandMessage, DIALOG_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return(Result.Failed);
                }
                finally
                {
                    // Remove the progress bar callback.
                    // application.ProgressChanged -= exportContext.HandleProgressChanged;

                    // Restore user interaction with the active 3D view.
                    EnableViewWindow(in_commandData.Application, true);

                    if (exportContext.GetMessages().Count > 0)
                    {
                        string Messages = string.Join($"{System.Environment.NewLine}", exportContext.GetMessages());
                        DatasmithRevitApplication.ShowExportMessages(Messages);
                    }
                }
            }

            return(Result.Succeeded);
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            // Select two walls and the dimension line point:

            Selection      sel  = uidoc.Selection;
            ReferenceArray refs = new ReferenceArray();

            try
            {
                //WallSelectionFilter f
                //  = new WallSelectionFilter();

                ISelectionFilter f
                    = new JtElementsOfClassSelectionFilter <Wall>();

                refs.Append(sel.PickObject(
                                ObjectType.Element, f,
                                "Please select first wall"));

                refs.Append(sel.PickObject(
                                ObjectType.Element, f,
                                "Please pick dimension line "
                                + "point on second wall"));

                //rFace = sel.PickObject( ObjectType.Face,
                //  "Please select face on second wall at dimension line point" );
                //
                //rPoint = sel.PickObject( ObjectType.PointOnElement,
                //  "Please select point on first wall" );
            }
            catch (Autodesk.Revit.Exceptions.OperationCanceledException)
            {
                message = "No two walls selected";
                return(Result.Failed);
            }

            // Ensure the two selected walls are straight and
            // parallel; determine their mutual normal vector
            // and a point on each wall for distance
            // calculations:

            Wall[]     walls = new Wall[2];
            List <int> ids   = new List <int>(2);

            XYZ[]              pts   = new XYZ[2];
            Line[]             lines = new Line[2];
            IntersectionResult ir;
            XYZ normal = null;
            int i      = 0;

            foreach (Reference r in refs)
            {
                // 'Autodesk.Revit.DB.Reference.Element' is
                // obsolete: Property will be removed. Use
                // Document.GetElement(Reference) instead.
                //Wall wall = r.Element as Wall; // 2011

                Wall wall = doc.GetElement(r) as Wall; // 2012

                walls[i] = wall;
                ids.Add(wall.Id.IntegerValue);

                // Obtain location curve and
                // check that it is straight:

                LocationCurve lc = wall.Location
                                   as LocationCurve;

                Curve curve = lc.Curve;
                lines[i] = curve as Line;

                if (null == lines[i])
                {
                    message = _prompt;
                    return(Result.Failed);
                }

                // Obtain normal vectors
                // and ensure that they are equal,
                // i.e. walls are parallel:

                if (null == normal)
                {
                    normal = Util.Normal(lines[i]);
                }
                else
                {
                    if (!Util.IsParallel(normal,
                                         Util.Normal(lines[i])))
                    {
                        message = _prompt;
                        return(Result.Failed);
                    }
                }

                // Obtain pick points and project
                // onto wall location lines:

                XYZ p = r.GlobalPoint;
                ir = lines[i].Project(p);

                if (null == ir)
                {
                    message = string.Format(
                        "Unable to project pick point {0} "
                        + "onto wall location line.",
                        i);

                    return(Result.Failed);
                }

                pts[i] = ir.XYZPoint;

                Debug.Print(
                    "Wall {0} id {1} at {2}, {3} --> point {4}",
                    i, wall.Id.IntegerValue,
                    Util.PointString(lines[i].GetEndPoint(0)),
                    Util.PointString(lines[i].GetEndPoint(1)),
                    Util.PointString(pts[i]));

                if (0 < i)
                {
                    // Project dimension point selected on second wall
                    // back onto first wall, and ensure that normal
                    // points from second wall to first:

                    ir = lines[0].Project(pts[1]);
                    if (null == ir)
                    {
                        message = string.Format(
                            "Unable to project selected dimension "
                            + "line point {0} on second wall onto "
                            + "first wall's location line.",
                            Util.PointString(pts[1]));

                        return(Result.Failed);
                    }
                    pts[0] = ir.XYZPoint;
                }

                ++i;
            }

            XYZ v = pts[0] - pts[1];

            if (0 > v.DotProduct(normal))
            {
                normal = -normal;
            }

            // Shoot a ray back from the second
            // picked wall towards first:

            Debug.Print(
                "Shooting ray from {0} in direction {1}",
                Util.PointString(pts[1]),
                Util.PointString(normal));

            View3D view = Get3DView(doc);

            if (null == view)
            {
                message = "No 3D view named '{3D}' found; "
                          + "run the View > 3D View command once "
                          + "to generate it.";

                return(Result.Failed);
            }

            //refs = doc.FindReferencesByDirection(
            //  pts[1], normal, view ); // 2011

            //IList<ReferenceWithContext> refs2
            //  = doc.FindReferencesWithContextByDirection(
            //    pts[1], normal, view ); // 2012

            // In the Revit 2014 API, the call to
            // FindReferencesWithContextByDirection causes a
            // warning saying:
            // "FindReferencesWithContextByDirection is obsolete:
            // This method is deprecated in Revit 2014.
            // Use the ReferenceIntersector class instead."

            ReferenceIntersector ri
                = new ReferenceIntersector(
                      walls[0].Id, FindReferenceTarget.Element, view);

            ReferenceWithContext ref2
                = ri.FindNearest(pts[1], normal);

            if (null == ref2)
            {
                message = "ReferenceIntersector.FindNearest"
                          + " returned null!";

                return(Result.Failed);
            }

            #region Obsolete code to determine the closest reference
#if NEED_TO_DETERMINE_CLOSEST_REFERENCE
            // Store the references to the wall surfaces:

            Reference[] surfrefs = new Reference[2] {
                null, null
            };

            // Find the two closest intersection
            // points on each of the two walls:

            double[] minDistance = new double[2] {
                double.MaxValue,
                double.MaxValue
            };

            //foreach( Reference r in refs )
            foreach (ReferenceWithContext rc in refs2)
            {
                // 'Autodesk.Revit.DB.Reference.Element' is
                // obsolete: Property will be removed. Use
                // Document.GetElement(Reference) instead.
                //Element e = r.Element; // 2011

                Reference r = rc.GetReference();
                Element   e = doc.GetElement(r); // 2012

                if (e is Wall)
                {
                    i = ids.IndexOf(e.Id.IntegerValue);

                    if (-1 < i &&
                        ElementReferenceType.REFERENCE_TYPE_SURFACE
                        == r.ElementReferenceType)
                    {
                        //GeometryObject g = r.GeometryObject; // 2011
                        GeometryObject g = e.GetGeometryObjectFromReference(r); // 2012

                        if (g is PlanarFace)
                        {
                            PlanarFace face = g as PlanarFace;

                            Line line = (e.Location as LocationCurve)
                                        .Curve as Line;

                            Debug.Print(
                                "Wall {0} at {1}, {2} surface {3} "
                                + "normal {4} proximity {5}",
                                e.Id.IntegerValue,
                                Util.PointString(line.GetEndPoint(0)),
                                Util.PointString(line.GetEndPoint(1)),
                                Util.PointString(face.Origin),
                                Util.PointString(face.Normal),
                                rc.Proximity);

                            // First reference: assert it is a face on this wall
                            // and the distance is half the wall thickness.
                            // Second reference: the first reference on the other
                            // wall; assert the distance between the two references
                            // equals the distance between the wall location lines
                            // minus half of the sum of the two wall thicknesses.

                            if (rc.Proximity < minDistance[i])
                            {
                                surfrefs[i]    = r;
                                minDistance[i] = rc.Proximity;
                            }
                        }
                    }
                }
            }

            if (null == surfrefs[0])
            {
                message = "No suitable face intersection "
                          + "points found on first wall.";

                return(Result.Failed);
            }

            if (null == surfrefs[1])
            {
                message = "No suitable face intersection "
                          + "points found on second wall.";

                return(Result.Failed);
            }

            CmdDimensionWallsIterateFaces
            .CreateDimensionElement(doc.ActiveView,
                                    pts[0], surfrefs[0], pts[1], surfrefs[1]);
#endif // NEED_TO_DETERMINE_CLOSEST_REFERENCE
            #endregion // Obsolete code to determine the closest reference

            CmdDimensionWallsIterateFaces
            .CreateDimensionElement(doc.ActiveView,
                                    pts[0], ref2.GetReference(), pts[1], refs.get_Item(1));

            return(Result.Succeeded);
        }
        public void SetSectionBox(UIApplication app, int offset)
        {
            var     doc         = app.ActiveUIDocument.Document;
            Element currentView = app.ActiveUIDocument.ActiveView;
            View3D  view3D      = null;
            var     userName    = Environment.UserName;

            var list3D = new FilteredElementCollector(doc).OfClass(typeof(View3D)).ToList();

            if (currentView is View3D)
            {
                view3D = currentView as View3D;
            }
            else
            {
                if (list3D.Any())
                {
                    var my3D = list3D.Where(x => x.Name.ToUpper().Contains(userName.ToUpper())).ToList();
                    if (my3D.Count != 0)
                    {
                        view3D = my3D[0] as View3D;
                    }
                }
            }

            if (view3D == null)
            {
                using (var tr = new Transaction(doc, "Create 3D view"))
                {
                    tr.Start();
                    if (list3D.Any() && list3D[0].GetTypeId().IntegerValue == -1)
                    {
                        var threeD =
                            new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType))
                            .Cast <ViewFamilyType>()
                            .FirstOrDefault(x => x.ViewFamily == ViewFamily.ThreeDimensional);
                        view3D = View3D.CreateIsometric(doc, threeD?.Id);
                    }
                    else
                    {
                        if (list3D.Any())
                        {
                            view3D = View3D.CreateIsometric(doc, list3D[0].GetTypeId());
                        }
                        else
                        {
                            var threeD =
                                new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType))
                                .Cast <ViewFamilyType>()
                                .FirstOrDefault(x => x.ViewFamily == ViewFamily.ThreeDimensional);
                            view3D = View3D.CreateIsometric(doc, threeD?.Id);
                        }
                    }
#if R2017 || R2018
                    view3D.ViewName = "3D - " + userName;
#else
                    view3D.Name = "3D - " + userName;
#endif
                    tr.Commit();
                }
            }

            app.ActiveUIDocument.ActiveView = view3D;
            var elements = app.ActiveUIDocument.Selection.GetElementIds()
                           .Select(id => doc.GetElement(id)).Where(el => el.Category.Id.IntegerValue != (int)BuiltInCategory.OST_SectionBox).ToList();

            var points = GetBoundingBoxXYZ(elements, doc);
            var box    = new BoundingBoxXYZ();
            box.Max = new XYZ(points[0].X + offset, points[0].Y + offset, points[0].Z + offset);
            box.Min = new XYZ(points[1].X - offset, points[1].Y - offset, points[1].Z - offset);
            using (var tr = new Transaction(doc, "Create 3D section"))
            {
                tr.Start();
                try
                {
                    view3D.SetSectionBox(box);
                    if (ExternalCommands.ScrollerWin.IsSectionView)
                    {
                        app.ActiveUIDocument.ShowElements(app.ActiveUIDocument.Selection.GetElementIds());
                    }
                }
                catch
                {
                    // ignored
                }

                tr.Commit();
            }
        }
Ejemplo n.º 28
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;

            // Get the current Document
            Document curDoc = uiapp.ActiveUIDocument.Document;

            //Get the current View
            View curView = uidoc.Document.ActiveView;

            BoundingBoxXYZ curViewBoundary = curView.CropBox;


            FilteredElementCollector viewCollector = new FilteredElementCollector(curDoc);

            viewCollector.OfClass(typeof(View3D));
            List <View3D> view3dList = viewCollector.ToElements().Cast <View3D>().Where(x => x.IsTemplate == false).ToList();

            //TaskDialog.Show("test", view3dList.First().ViewName.ToString());


            //Build eyeLevel and eyeLevel sketchplane
            double eyeLevel  = 5;
            XYZ    eyeNormal = new XYZ(0, 0, 1);
            XYZ    xAxis     = new XYZ(1, 0, 0);
            XYZ    yAxis     = new XYZ(0, 1, 0);

            //Isovist variables
            int    numRays       = 600;
            double isoRadius     = 300;
            double isoStartAngle = 0;
            double isoEndAngle   = 360;

            //Convert to radians
            double radIsoStartAngle = (Math.PI / 180) * isoStartAngle;
            double radIsoEndAngle   = (Math.PI / 180) * isoEndAngle;


            //Get all walls
            FilteredElementCollector wallCollector = new FilteredElementCollector(curDoc, curView.Id);

            wallCollector.OfCategory(BuiltInCategory.OST_Walls);


            //Get all stacked walls
            FilteredElementCollector stackedWallCollector = new FilteredElementCollector(curDoc, curView.Id);

            stackedWallCollector.OfCategory(BuiltInCategory.OST_StackedWalls);

            stackedWallCollector.UnionWith(wallCollector).WhereElementIsNotElementType();


            //TaskDialog.Show("Test", stackedWallCollector.Count().ToString() + " Walls");


            List <Face>  wallFaces  = new List <Face>();
            double       totalArea  = 0;
            List <Solid> wallSolids = new List <Solid>();

            foreach (Element curWall in stackedWallCollector)
            {
                Options         opt      = new Options();
                GeometryElement geomElem = curWall.get_Geometry(opt);


                foreach (GeometryObject geomObj in geomElem)
                {
                    Solid geomSolid = geomObj as Solid;
                    wallSolids.Add(geomSolid);


                    if (null != geomSolid)
                    {
                        foreach (Face geomFace in geomSolid.Faces)
                        {
                            totalArea += geomFace.Area;
                            wallFaces.Add(geomFace);
                        }
                    }
                }
            }

            //TaskDialog.Show("test", wallFaces.Count().ToString() + "  Faces");



            //Determine All Defaults for stuff later
            ElementId defaultView3d = curDoc.GetDefaultElementTypeId(ElementTypeGroup.ViewType3D);

            ElementId defaultTxtId = curDoc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType);
            ElementId defaultFRId  = curDoc.GetDefaultElementTypeId(ElementTypeGroup.FilledRegionType);



            //Create View Boundary filter for roomCollector

            Outline outline = new Outline(new XYZ(curViewBoundary.Min.X, curViewBoundary.Min.Y, -100), new XYZ(curViewBoundary.Max.X, curViewBoundary.Max.Y, 100));
            BoundingBoxIsInsideFilter bbFilter = new BoundingBoxIsInsideFilter(outline);

            //FilteredElementCollector roomList = roomCollector.WherePasses(bbFilter);


            // Get all rooms; Divide into point grid; Return points in curPointList
            RoomFilter filter = new RoomFilter();

            FilteredElementCollector roomCollector = new FilteredElementCollector(curDoc, curView.Id);

            roomCollector.WherePasses(filter).WherePasses(bbFilter);

            TaskDialog.Show("Magic View Region Drawing Machine", "Be sure to set the crop region around the rooms you would like to test, encompassing at least one exterior wall and all bounding elements." +
                            "Only rooms located fully within the bounds of the view range will be calculated.");
            TaskDialog.Show("Magic View Region Drawing Machine", roomCollector.Count().ToString() + " rooms fully visible in current view. The more rooms you run, the longer this will take!");

            Transaction t = new Transaction(curDoc, "Draw Some Lines");

            t.Start();

            View3D curView3d = View3D.CreateIsometric(curDoc, defaultView3d);

            IEnumerable <Element> extWalls = GetExteriorWalls(curDoc, curView);

            //TaskDialog.Show("test", extWalls.Count().ToString() +"  Exterior Walls");

            List <XYZ> somePoints = new List <XYZ>();

            foreach (Element wall in extWalls)
            {
                List <XYZ> pointsList = new List <XYZ>();


                pointsList = GetWallOpenings(wall, eyeLevel, curView3d);

                somePoints.AddRange(pointsList);
            }

            //TaskDialog.Show("test", somePoints.Count.ToString()+" points");


            List <List <Curve> > viewCones = new List <List <Curve> >();



            foreach (XYZ curPoint in somePoints)
            {
                Plane       eyePlane       = Plane.CreateByNormalAndOrigin(eyeNormal, curPoint);
                SketchPlane eyeSketchPlane = SketchPlane.Create(curDoc, eyePlane);

                //Arc arc = Arc.Create(curPoint, 2, 0, 360, xAxis, yAxis);
                //ModelCurve newArc = curDoc.Create.NewModelCurve(arc, eyeSketchPlane);



                List <Curve> outLineList = createIsovist(curPoint, numRays, isoRadius, radIsoStartAngle, radIsoEndAngle, curView, curDoc, eyeSketchPlane, wallFaces, defaultFRId);


                viewCones.Add(outLineList);
            }

            //Convert to polygons in int values
            Polygons polys = GetBoundaryLoops(viewCones);
            //TaskDialog.Show("test", polys.Count.ToString()+ " Polygons");


            //Calculate Intersection
            Polygons union = new Polygons();

            Clipper c = new Clipper();

            c.AddPath(polys[0], PolyType.ptSubject, true);

            for (int i = 1; i < polys.Count - 1; i++)
            {
                c.AddPath(polys[i], PolyType.ptClip, true);
            }

            c.Execute(ClipType.ctUnion, union, PolyFillType.pftPositive);

            /*
             *
             *          TaskDialog.Show("test", union.Count.ToString()+ " Polygons");
             *
             *          if (0 < union.Count)
             *          {
             *                  List<CurveLoop>regionLoops = new List<CurveLoop>();
             *
             *                  for (int p = 0; p < union.Count -1; p++)
             *                  {
             *                          List<Curve> unionLineList = new List<Curve>();
             *                          Polygon poly = union[p];
             *
             *                          for (int i = 1; i <= poly.Count-1; i++)
             *                          {
             *                                  unionLineList.Add(Line.CreateBound(GetXyzPoint(poly[i-1]), GetXyzPoint(poly[i])));
             *
             *                          }
             *                          unionLineList.Add(Line.CreateBound(GetXyzPoint(poly[poly.Count-1]), GetXyzPoint(poly[0])));
             *
             *                          CurveLoop regionLoop = CurveLoop.Create(unionLineList);
             *
             *                          regionLoops.Add(regionLoop);
             *
             *                  }
             *
             *                  FilledRegion region = FilledRegion.Create(curDoc, defaultFRId, curView.Id, regionLoops);
             *
             *
             *          }
             */


            foreach (Room curRoom in roomCollector)
            {
                SpatialElementBoundaryOptions bo = new SpatialElementBoundaryOptions();

                List <Curve> roomCurves = new List <Curve>();
                foreach (List <BoundarySegment> lstBs in curRoom.GetBoundarySegments(bo))
                {
                    foreach (BoundarySegment bs in lstBs)
                    {
                        roomCurves.Add(bs.GetCurve());
                    }
                }

                XYZ sketchPoint = new XYZ(0, 0, 0);

                Plane       eyePlane       = Plane.CreateByNormalAndOrigin(eyeNormal, sketchPoint);
                SketchPlane eyeSketchPlane = SketchPlane.Create(curDoc, eyePlane);


                List <List <Curve> > roomLoops = new List <List <Curve> >();

                roomLoops.Add(roomCurves);

                //Convert to polygon in int values
                Polygon roomPoly = GetBoundaryLoop(roomCurves);


                //Calculate Intersection
                Polygons intersection = new Polygons();

                Clipper c2 = new Clipper();

                c2.AddPath(roomPoly, PolyType.ptClip, true);
                c2.AddPaths(union, PolyType.ptSubject, true);

                c2.Execute(ClipType.ctIntersection, intersection, PolyFillType.pftPositive);

                //TaskDialog.Show("test", intersection.Count.ToString());


                if (0 < intersection.Count)
                {
                    List <CurveLoop> regionLoops          = new List <CurveLoop>();
                    List <Curve>     intersectionLineList = new List <Curve>();
                    Polygon          poly = intersection[0];

                    IntPoint?p0 = null;
                    IntPoint?p  = null;

                    foreach (IntPoint q in poly)
                    {
                        if (null == p0)
                        {
                            p0 = q;
                        }
                        if (null != p)
                        {
                            intersectionLineList.Add(Line.CreateBound(GetXyzPoint(p.Value), GetXyzPoint(q)));
                        }
                        p = q;
                    }

                    intersectionLineList.Add(Line.CreateBound(GetXyzPoint(poly[poly.Count - 1]), GetXyzPoint(poly[0])));

                    foreach (Curve cur in intersectionLineList)
                    {
                        //ModelCurve newArc = curDoc.Create.NewModelCurve(cur, eyeSketchPlane);
                    }


                    CurveLoop regionLoop = CurveLoop.Create(intersectionLineList);

                    regionLoops.Add(regionLoop);


                    //TaskDialog.Show("test", intersectionLineList.Count.ToString());



                    FilledRegion region = FilledRegion.Create(curDoc, defaultFRId, curView.Id, regionLoops);
                }
            }

            t.Commit();



            TaskDialog.Show("Magic View Region Drawing Machine", "Always double check the results, sometimes walls are missed. Tip: Curtain wall is prone to gliches and watch your door openings... Enjoy!");

            return(Result.Succeeded);
        }
Ejemplo n.º 29
0
		protected void UpdateStaticBuffers(View3D view)
		{
			if (m_Disposed == true)
			{
				return;
			}

			int LineVerts = 0;
			int LinesIndices = 0;
			int TriangleVerts = 0;
			int TriangleIndices = 0;

			DataStream LineVertsStream;
			DataStream LinesIndicesStream;
			DataStream TriangleVertsStream;
			DataStream TriangleIndicesStream;

			try
			{
				foreach (UiControl control in Controls)
				{
					control.GetTotalElementCounts(ref LineVerts, ref LinesIndices, ref TriangleVerts, ref TriangleIndices);
				}

				m_StaticBuffer.Resize(LineVerts, LinesIndices, TriangleVerts, TriangleIndices);

				LineVerts = 0;
				LinesIndices = 0;
				TriangleVerts = 0;
				TriangleIndices = 0;

				m_StaticBuffer.MapStreams(MapMode.WriteDiscard, out LineVertsStream, out LinesIndicesStream, out TriangleVertsStream, out TriangleIndicesStream);

				RectangleF rect = new RectangleF(view.Viewport.X + view.ViewportOffset.X, view.Viewport.Y + view.ViewportOffset.Y, view.Viewport.Width, view.Viewport.Height);
				RectangleF clientBounds = rect;

				foreach (UiControl control in Controls)
				{
					if (control.IsVisible == true)
					{
						control.WriteVisibleElements(view, clientBounds, ref rect, LineVertsStream, ref LineVerts, LinesIndicesStream, ref LinesIndices, TriangleVertsStream, ref TriangleVerts, TriangleIndicesStream, ref TriangleIndices);
					}
				}
			}
			finally
			{
				m_StaticBuffer.UnmapStreams(LineVerts, LinesIndices, TriangleVerts, TriangleIndices);
			}
		}
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;
            Selection     sel   = uidoc.Selection;

            // Retrieve all floors from the model

            var floors
                = new FilteredElementCollector(doc)
                  .OfClass(typeof(Floor))
                  .ToElements()
                  .Cast <Floor>()
                  .ToList();

            if (2 != floors.Count)
            {
                message = "Please create two intersected floors";
                return(Result.Failed);
            }

            // Retrieve the floor solids

            Options opt = new Options();

            var geometry1 = floors[0].get_Geometry(opt);
            var geometry2 = floors[1].get_Geometry(opt);

            var solid1 = geometry1.FirstOrDefault() as Solid;
            var solid2 = geometry2.FirstOrDefault() as Solid;

            // Calculate the intersection solid

            var intersectedSolid = BooleanOperationsUtils
                                   .ExecuteBooleanOperation(solid1, solid2,
                                                            BooleanOperationsType.Intersect);

            // Search for the metric mass family template file

            string template_path = DirSearch(
                app.FamilyTemplatePath,
                "Metric Mass.rft");

            // Create a new temporary family

            var family_doc = app.NewFamilyDocument(
                template_path);

            // Create a free form element
            // from the intersection solid

            using (var t = new Transaction(family_doc))
            {
                t.Start("Add Free Form Element");

                var freeFormElement = FreeFormElement.Create(
                    family_doc, intersectedSolid);

                t.Commit();
            }

            string dir = Path.GetTempPath();

            string filepath = Path.Combine(dir,
                                           "floor_intersection_family.rfa");

            SaveAsOptions sao = new SaveAsOptions()
            {
                OverwriteExistingFile = true
            };

            family_doc.SaveAs(filepath, sao);

            // Create 3D View

            var viewFamilyType
                = new FilteredElementCollector(family_doc)
                  .OfClass(typeof(ViewFamilyType))
                  .OfType <ViewFamilyType>()
                  .FirstOrDefault(x =>
                                  x.ViewFamily == ViewFamily.ThreeDimensional);

            View3D threeDView;

            using (var t = new Transaction(family_doc))
            {
                t.Start("Create 3D View");

                threeDView = View3D.CreateIsometric(
                    family_doc, viewFamilyType.Id);

                t.Commit();
            }

            // Export to SAT

            var viewSet = new List <ElementId>()
            {
                threeDView.Id
            };

            SATExportOptions exportOptions
                = new SATExportOptions();

            var res = family_doc.Export(dir,
                                        "SolidFile.sat", viewSet, exportOptions);

            return(Result.Succeeded);
        }
Ejemplo n.º 31
0
        public void TotalSectionBox(UIDocument uidoc)
        {
            Document        doc              = uidoc.Document;
            Element         activeView       = uidoc.ActiveView as Element;
            IList <Element> RVTLinkInstances = new FilteredElementCollector(doc).OfClass(typeof(RevitLinkInstance)).ToElements().ToList <Element>();
            var             doclist          = new List <Document>();

            for (int i = 0; i < RVTLinkInstances.Count; i++)
            {
                RevitLinkInstance l1 = RVTLinkInstances[i] as RevitLinkInstance;
                Document          d1 = l1.GetLinkDocument();
                doclist.Add(d1);
            }

            try
            {
                Reference pickedElement = uidoc.Selection.PickObject(ObjectType.LinkedElement);
                ElementId lEleID        = pickedElement.LinkedElementId;

                /* debug task dialog
                 * TaskDialog kk = new TaskDialog("kjk");
                 * kk.MainContent = doc.ActiveView.UniqueId+ "\n"+ uidoc.ActiveView.UniqueId;
                 * kk.Show();
                 */

                if (activeView.GetType().ToString() != "Autodesk.Revit.DB.View3D")
                {
                    var dddTypes = new List <ViewFamilyType>();
                    FilteredElementCollector collector      = new FilteredElementCollector(doc);
                    ICollection <Element>    viewTypesInDoc = collector.OfClass(typeof(ViewFamilyType)).ToElements();
                    foreach (ViewFamilyType v in viewTypesInDoc)
                    {
                        if (v.ViewFamily == ViewFamily.ThreeDimensional)
                        {
                            dddTypes.Add(v);
                        }
                    }
                    Transaction newDDD = new Transaction(doc, "newDDD");
                    newDDD.Start();
                    View3D new3D = View3D.CreateIsometric(doc, dddTypes.First <ViewFamilyType>().Id);
                    newDDD.Commit();
                    uidoc.ActiveView = new3D;
                    activeView       = new3D;
                }

                Transaction newSectionBox = new Transaction(doc, "newSectionBox");
                newSectionBox.Start();
                foreach (Document lDoc in doclist)
                {
                    if (lDoc.IsLinked)
                    {
                        try
                        {
                            BoundingBoxXYZ lEleBbox = lDoc.GetElement(lEleID).get_BoundingBox(activeView as View3D);
                            (activeView as View3D).SetSectionBox(lEleBbox);
                            newSectionBox.Commit();
                        }
                        catch
                        {
                        }
                    }
                }
            }
            catch
            {
            }
        }
Ejemplo n.º 32
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="app"></param>
        /// <param name="element"></param>
        /// <returns></returns>
        public static Revit.Element CloneElement(Application app, Revit.Element element)
        {
            Opening opening = element as Opening;

            if (opening != null)
            {
                return(CloneElement(app, opening));
            }

            BoundaryConditions boundaryConditions = element as BoundaryConditions;

            if (boundaryConditions != null)
            {
                return(CloneElement(app, boundaryConditions));
            }

            AreaLoad areaLoad = element as AreaLoad;

            if (areaLoad != null)
            {
                return(CloneElement(app, areaLoad));
            }

            AreaReinforcement areaReinforcement = element as AreaReinforcement;

            if (areaReinforcement != null)
            {
                return(CloneElement(app, areaReinforcement));
            }

            BeamSystem beamSystem = element as BeamSystem;

            if (beamSystem != null)
            {
                return(CloneElement(app, beamSystem));
            }

            Dimension dimension = element as Dimension;

            if (dimension != null)
            {
                return(CloneElement(app, dimension));
            }

            FamilyInstance familyInstance = element as FamilyInstance;

            if (familyInstance != null)
            {
                return(CloneElement(app, familyInstance));
            }

            Floor floor = element as Floor;

            if (floor != null)
            {
                return(CloneElement(app, floor));
            }

            Grid grid = element as Grid;

            if (grid != null)
            {
                return(CloneElement(app, grid));
            }

            Group group = element as Group;

            if (group != null)
            {
                return(CloneElement(app, group));
            }

            Level level = element as Level;

            if (floor != null)
            {
                return(CloneElement(app, floor));
            }

            LineLoad lineLoad = element as LineLoad;

            if (lineLoad != null)
            {
                return(CloneElement(app, lineLoad));
            }

            LoadCase loadCase = element as LoadCase;

            if (loadCase != null)
            {
                return(CloneElement(app, loadCase));
            }

            LoadCombination loadCombination = element as LoadCombination;

            if (loadCombination != null)
            {
                return(CloneElement(app, loadCombination));
            }

            LoadNature loadNature = element as LoadNature;

            if (loadNature != null)
            {
                return(CloneElement(app, loadNature));
            }

            LoadUsage loadUsage = element as LoadUsage;

            if (loadUsage != null)
            {
                return(CloneElement(app, loadUsage));
            }

            ModelCurve modelCurve = element as ModelCurve;

            if (modelCurve != null)
            {
                return(CloneElement(app, modelCurve));
            }

            PointLoad pointLoad = element as PointLoad;

            if (pointLoad != null)
            {
                return(CloneElement(app, pointLoad));
            }

            Rebar rebar = element as Rebar;

            if (rebar != null)
            {
                return(CloneElement(app, rebar));
            }

            ReferencePlane referencePlane = element as ReferencePlane;

            if (referencePlane != null)
            {
                return(CloneElement(app, referencePlane));
            }

            Room room = element as Room;

            if (room != null)
            {
                return(CloneElement(app, room));
            }

            RoomTag roomTag = element as RoomTag;

            if (roomTag != null)
            {
                return(CloneElement(app, roomTag));
            }

            SketchPlane sketchPlane = element as SketchPlane;

            if (sketchPlane != null)
            {
                return(CloneElement(app, sketchPlane));
            }

            View3D view3D = element as View3D;

            if (view3D != null)
            {
                return(CloneElement(app, view3D));
            }

            ViewDrafting viewDrafting = element as ViewDrafting;

            if (viewDrafting != null)
            {
                return(CloneElement(app, viewDrafting));
            }

            ViewSection viewSection = element as ViewSection;

            if (viewSection != null)
            {
                return(CloneElement(app, viewSection));
            }

            ViewSheet viewSheet = element as ViewSheet;

            if (viewSheet != null)
            {
                return(CloneElement(app, viewSheet));
            }

            Wall wall = element as Wall;

            if (wall != null)
            {
                return(CloneElement(app, wall));
            }

            // this element has not yet been exposed in the Creation Document class
            //Debug.Assert(false);

            return(null);
        }
Ejemplo n.º 33
0
        /// <summary>
        /// External Event Implementation
        /// </summary>
        /// <param name="app"></param>
        public void Execute(UIApplication app)
        {
            try
            {
                UIDocument uidoc = app.ActiveUIDocument;
                Document   doc   = uidoc.Document;
                //Selection m_elementsToHide = uidoc.Selection; //SelElementSet.Create();

                List <ElementId> elementsToBeIsolated = new List <ElementId>();
                List <ElementId> elementsToBeHidden   = new List <ElementId>();
                List <ElementId> elementsToBeSelected = new List <ElementId>();



                // IS ORTHOGONAL
                if (v.OrthogonalCamera != null)
                {
                    if (v.OrthogonalCamera.ViewToWorldScale == null || v.OrthogonalCamera.CameraViewPoint == null || v.OrthogonalCamera.CameraUpVector == null || v.OrthogonalCamera.CameraDirection == null)
                    {
                        return;
                    }
                    //type = "OrthogonalCamera";
                    var zoom            = UnitUtils.ConvertToInternalUnits(v.OrthogonalCamera.ViewToWorldScale, DisplayUnitType.DUT_METERS);
                    var CameraDirection = ARUP.IssueTracker.Revit.Classes.Utils.GetXYZ(v.OrthogonalCamera.CameraDirection.X, v.OrthogonalCamera.CameraDirection.Y, v.OrthogonalCamera.CameraDirection.Z);
                    var CameraUpVector  = ARUP.IssueTracker.Revit.Classes.Utils.GetXYZ(v.OrthogonalCamera.CameraUpVector.X, v.OrthogonalCamera.CameraUpVector.Y, v.OrthogonalCamera.CameraUpVector.Z);
                    var CameraViewPoint = ARUP.IssueTracker.Revit.Classes.Utils.GetXYZ(v.OrthogonalCamera.CameraViewPoint.X, v.OrthogonalCamera.CameraViewPoint.Y, v.OrthogonalCamera.CameraViewPoint.Z);
                    var orient3d        = ARUP.IssueTracker.Revit.Classes.Utils.ConvertBasePoint(doc, CameraViewPoint, CameraDirection, CameraUpVector, true);


                    View3D orthoView = null;
                    //if active view is 3d ortho use it
                    if (doc.ActiveView.ViewType == ViewType.ThreeD)
                    {
                        View3D ActiveView3D = doc.ActiveView as View3D;
                        if (!ActiveView3D.IsPerspective)
                        {
                            orthoView = ActiveView3D;
                        }
                    }
                    if (orthoView == null)
                    {
                        IEnumerable <View3D> viewcollector3D = get3DViews(doc);
                        //try to use default 3D view
                        if (viewcollector3D.Any() && viewcollector3D.Where(o => o.Name == "{3D}" || o.Name == "BCFortho").Any())
                        {
                            orthoView = viewcollector3D.Where(o => o.Name == "{3D}" || o.Name == "BCFortho").First();
                        }
                    }
                    using (Transaction trans = new Transaction(uidoc.Document))
                    {
                        if (trans.Start("Open orthogonal view") == TransactionStatus.Started)
                        {
                            //create a new 3d ortho view
                            if (orthoView == null)
                            {
                                orthoView      = View3D.CreateIsometric(doc, getFamilyViews(doc).First().Id);
                                orthoView.Name = "BCFortho";
                            }

                            orthoView.DisableTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate);
                            orthoView.SetOrientation(orient3d);
                            trans.Commit();
                        }
                    }
                    uidoc.ActiveView = orthoView;
                    //adjust view rectangle

                    // **** CUSTOM VALUE FOR TEKLA **** //
                    // double x = touple.Item2
                    // **** CUSTOM VALUE FOR TEKLA **** //
                    double customZoomValue = (MyProjectSettings.Get("useDefaultZoom", doc.PathName) == "1") ? 1 : 2.5;
                    double x       = zoom / customZoomValue;
                    XYZ    m_xyzTl = uidoc.ActiveView.Origin.Add(uidoc.ActiveView.UpDirection.Multiply(x)).Subtract(uidoc.ActiveView.RightDirection.Multiply(x));
                    XYZ    m_xyzBr = uidoc.ActiveView.Origin.Subtract(uidoc.ActiveView.UpDirection.Multiply(x)).Add(uidoc.ActiveView.RightDirection.Multiply(x));
                    uidoc.GetOpenUIViews().First().ZoomAndCenterRectangle(m_xyzTl, m_xyzBr);
                }

                else if (v.PerspectiveCamera != null)
                {
                    if (v.PerspectiveCamera.FieldOfView == null || v.PerspectiveCamera.CameraViewPoint == null || v.PerspectiveCamera.CameraUpVector == null || v.PerspectiveCamera.CameraDirection == null)
                    {
                        return;
                    }

                    var    zoom   = v.PerspectiveCamera.FieldOfView;
                    double z1     = 18 / Math.Tan(zoom / 2 * Math.PI / 180); //focale 1
                    double z      = 18 / Math.Tan(25 / 2 * Math.PI / 180);   //focale, da controllare il 18, vedi PDF
                    double factor = z1 - z;

                    var CameraDirection = ARUP.IssueTracker.Revit.Classes.Utils.GetXYZ(v.PerspectiveCamera.CameraDirection.X, v.PerspectiveCamera.CameraDirection.Y, v.PerspectiveCamera.CameraDirection.Z);
                    var CameraUpVector  = ARUP.IssueTracker.Revit.Classes.Utils.GetXYZ(v.PerspectiveCamera.CameraUpVector.X, v.PerspectiveCamera.CameraUpVector.Y, v.PerspectiveCamera.CameraUpVector.Z);
                    XYZ oldO            = ARUP.IssueTracker.Revit.Classes.Utils.GetXYZ(v.PerspectiveCamera.CameraViewPoint.X, v.PerspectiveCamera.CameraViewPoint.Y, v.PerspectiveCamera.CameraViewPoint.Z);
                    var CameraViewPoint = (oldO.Subtract(CameraDirection.Divide(factor)));
                    var orient3d        = ARUP.IssueTracker.Revit.Classes.Utils.ConvertBasePoint(doc, CameraViewPoint, CameraDirection, CameraUpVector, true);



                    View3D perspView = null;

                    IEnumerable <View3D> viewcollector3D = get3DViews(doc);
                    if (viewcollector3D.Any() && viewcollector3D.Where(o => o.Name == "BCFpersp").Any())
                    {
                        perspView = viewcollector3D.Where(o => o.Name == "BCFpersp").First();
                    }
                    using (Transaction trans = new Transaction(uidoc.Document))
                    {
                        if (trans.Start("Open perspective view") == TransactionStatus.Started)
                        {
                            if (null == perspView)
                            {
                                perspView      = View3D.CreatePerspective(doc, getFamilyViews(doc).First().Id);
                                perspView.Name = "BCFpersp";
                            }

                            perspView.DisableTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate);
                            perspView.SetOrientation(orient3d);

                            // turn on the far clip plane with standard parameter API
                            if (perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR).HasValue)
                            {
                                Parameter m_farClip = perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR);
                                m_farClip.Set(1);
                            }
                            // reset far clip offset
                            if (perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_OFFSET_FAR).HasValue)
                            {
                                Parameter m_farClipOffset = perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_OFFSET_FAR);
                                m_farClipOffset.SetValueString("35");
                            }
                            // turn off the far clip plane with standard parameter API
                            if (perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR).HasValue)
                            {
                                Parameter m_farClip = perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR);
                                m_farClip.Set(0);
                            }
                            perspView.CropBoxActive  = true;
                            perspView.CropBoxVisible = true;

                            trans.Commit();
                        }
                    }
                    uidoc.ActiveView = perspView;
                }
                else if (v.SheetCamera != null)//sheet
                {
                    //using (Transaction trans = new Transaction(uidoc.Document))
                    //{
                    //    if (trans.Start("Open sheet view") == TransactionStatus.Started)
                    //    {
                    IEnumerable <View> viewcollectorSheet = getSheets(doc, v.SheetCamera.SheetID);
                    if (!viewcollectorSheet.Any())
                    {
                        MessageBox.Show("No Sheet with Id=" + v.SheetCamera.SheetID + " found.");
                        return;
                    }
                    uidoc.ActiveView = viewcollectorSheet.First();
                    uidoc.ActiveView.DisableTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate);
                    uidoc.RefreshActiveView();

                    //        trans.Commit();
                    //    }
                    //}
                    XYZ m_xyzTl = new XYZ(v.SheetCamera.TopLeft.X, v.SheetCamera.TopLeft.Y,
                                          v.SheetCamera.TopLeft.Z);
                    XYZ m_xyzBr = new XYZ(v.SheetCamera.BottomRight.X, v.SheetCamera.BottomRight.Y,
                                          v.SheetCamera.BottomRight.Z);
                    uidoc.GetOpenUIViews().First().ZoomAndCenterRectangle(m_xyzTl, m_xyzBr);
                }
                else
                {
                    return;
                }

                //apply BCF clipping planes to Revit section box
                View3D view3D = doc.ActiveView as View3D;
                if (view3D != null)
                {
                    if (v.ClippingPlanes != null)
                    {
                        if (v.ClippingPlanes.Count() > 0)
                        {
                            var result = getBoundingBoxFromClippingPlanes(doc, v.ClippingPlanes);

                            if (result != null)
                            {
                                BoundingBoxXYZ computedBox = result.Item1;
                                Transform      rotate      = result.Item2;

                                using (Transaction trans = new Transaction(uidoc.Document))
                                {
                                    if (trans.Start("Apply Section Box") == TransactionStatus.Started)
                                    {
                                        view3D.IsSectionBoxActive = true;
                                        view3D.SetSectionBox(computedBox);

                                        if (rotate != null)
                                        {
                                            // Transform the View3D's section box with the rotation transform
                                            computedBox.Transform = computedBox.Transform.Multiply(rotate);

                                            // Set the section box back to the view (requires an open transaction)
                                            view3D.SetSectionBox(computedBox);
                                        }
                                    }
                                    trans.Commit();
                                }
                            }
                        }
                    }
                }

                //select/hide elements
                if (v.Components != null && v.Components.Any())
                {
                    if (v.Components.Count > 100)
                    {
                        var result = MessageBox.Show("Too many elements attached. It may take for a while to isolate/select them. Do you want to continue?", "Warning", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                        if (result == MessageBoxResult.No)
                        {
                            uidoc.RefreshActiveView();
                            return;
                        }
                    }

                    FilteredElementCollector collector = new FilteredElementCollector(doc, doc.ActiveView.Id).WhereElementIsNotElementType();
                    System.Collections.Generic.ICollection <ElementId> collection = collector.ToElementIds();
                    foreach (var e in v.Components)
                    {
                        var bcfguid         = IfcGuid.FromIfcGUID(e.IfcGuid);
                        int authoringToolId = string.IsNullOrWhiteSpace(e.AuthoringToolId) ? -1 : int.Parse(e.AuthoringToolId);
                        var ids             = collection.Where(o => bcfguid == ExportUtils.GetExportId(doc, o) | authoringToolId == Convert.ToInt32(doc.GetElement(o).UniqueId.Substring(37), 16));
                        if (ids.Any())
                        {
                            // handle visibility
                            if (e.Visible)
                            {
                                elementsToBeIsolated.Add(ids.First());
                            }
                            else
                            {
                                elementsToBeHidden.Add(ids.First());
                            }

                            // handle selection
                            if (e.Selected)
                            {
                                elementsToBeSelected.Add(ids.First());
                            }
                        }
                    }

                    if (elementsToBeHidden.Count > 0)
                    {
                        using (Transaction trans = new Transaction(uidoc.Document))
                        {
                            if (trans.Start("Hide Elements") == TransactionStatus.Started)
                            {
                                uidoc.ActiveView.HideElementsTemporary(elementsToBeHidden);
                            }
                            trans.Commit();
                        }
                    }
                    else if (elementsToBeIsolated.Count > 0)
                    {
                        using (Transaction trans = new Transaction(uidoc.Document))
                        {
                            if (trans.Start("Isolate Elements") == TransactionStatus.Started)
                            {
                                uidoc.ActiveView.IsolateElementsTemporary(elementsToBeIsolated);
                            }
                            trans.Commit();
                        }
                    }

                    if (elementsToBeSelected.Count > 0)
                    {
                        using (Transaction trans = new Transaction(uidoc.Document))
                        {
                            if (trans.Start("Select Elements") == TransactionStatus.Started)
                            {
                                uidoc.Selection.SetElementIds(elementsToBeSelected);
                            }
                            trans.Commit();
                        }
                    }
                }

                uidoc.RefreshActiveView();
            }
            catch (Exception ex)
            {
                TaskDialog.Show("Error!", "exception: " + ex);
            }
        }
Ejemplo n.º 34
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="app"></param>
        /// <param name="view3D"></param>
        /// <returns></returns>
        private static Revit.Element CloneElement(Autodesk.Revit.UI.UIApplication app, View3D view3D)
        {
            XYZ    viewDir     = view3D.ViewDirection;
            View3D view3DClone = View3D.CreateIsometric(app.ActiveUIDocument.Document, view3D.GetTypeId());

            Utils.ParamUtil.SetParameters(view3DClone.Parameters, view3D.Parameters);
            return(view3DClone);
        }
        public void test(UIDocument uidoc)
        {
            Document doc = uidoc.Document;

            ReferenceArray refs = new ReferenceArray();

            Reference myRef = uidoc.Selection.PickObject(
                ObjectType.Element,
                new MySelectionFilter("Walls"),
                "Select a wall");

            Wall wall = doc.GetElement(myRef) as Wall;

            // Creates an element e from the selected object
            // reference -- this will be the wall element
            Element e = doc.GetElement(myRef);

            // Creates a selection filter to dump objects
            // in for later selection
            ICollection <ElementId> selSet = new List <ElementId>();

            // Gets the bounding box of the selected wall
            // element picked above
            BoundingBoxXYZ bb = e.get_BoundingBox(doc.ActiveView);

            // adds a buffer to the bounding box to ensure
            // all elements are contained within the box
            XYZ buffer = new XYZ(0.1, 0.1, 0.1);

            // creates an ouline based on the boundingbox
            // corners of the panel and adds the buffer
            Outline outline = new Outline(
                bb.Min - buffer, bb.Max + buffer);

            // filters the selection by the bounding box of the selected object
            // the "true" statement inverts the selection and selects all other objects
            BoundingBoxIsInsideFilter bbfilter
                = new BoundingBoxIsInsideFilter(outline, false);

            ICollection <BuiltInCategory> bcat
                = new List <BuiltInCategory>();

            //creates a new filtered element collector that
            // filters by the active view settings
            FilteredElementCollector collector
                = new FilteredElementCollector(
                      doc, doc.ActiveView.Id);

            //collects all objects that pass through the
            // requirements of the bbfilter
            collector.WherePasses(bbfilter);

            //add all levels and grids to filter -- these
            // are filtered out by the viewtemplate, but
            // are nice to have
            bcat.Add(BuiltInCategory.OST_StructConnections);

            //create new multi category filter
            ElementMulticategoryFilter multiCatFilter
                = new ElementMulticategoryFilter(bcat);

            //create new filtered element collector, add the
            // passing levels and grids, then remove them
            // from the selection
            foreach (Element el in collector.WherePasses(
                         multiCatFilter))
            {
                if (el.Name.Equals("EMBEDS"))
                {
                    selSet.Add(el.Id);
                }
            }

            XYZ[] pts = new XYZ[99];

            //View3D view = doc.ActiveView as View3D;
            View3D view = Get3dView(doc);

            // THIS IS WHERE IT RETURNS THE WALL OPENING REFERENCES.
            // HOWEVER THEY ONLY ARE ABLE TO BE USED FOR DIMENSIONS
            // IF THE OPENING IS CREATED USING A FAMILY SUCH AS A
            // WINDOW OR DOOR. OPENING BY FACE/WALL DOES NOT WORK,
            // EVEN THOUGH IT RETURNS PROPER REFERENCES

            List <Reference> openings = GetWallOpenings(e as Wall, view);

            foreach (Reference reference in openings)
            {
                refs.Append(reference);
            }

            TaskDialog.Show("REFERE", refs.Size.ToString());

            Curve wallLocation = (wall.Location as LocationCurve).Curve;

            int i = 0;

            foreach (ElementId ele in selSet)
            {
                FamilyInstance fi = doc.GetElement(ele) as FamilyInstance;
                Reference      reference
                    = ScottWilsonVoodooMagic.GetSpecialFamilyReference(
                          fi, ScottWilsonVoodooMagic.SpecialReferenceType.CenterLR,
                          doc);

                refs.Append(reference);

                pts[i] = (fi.Location as LocationPoint).Point;
                i++;
            }

            XYZ offset = new XYZ(0, 0, 4);

            Line line = Line.CreateBound(
                pts[0] + offset, pts[1] + offset);

            using (Transaction t = new Transaction(doc))
            {
                t.Start("dimension embeds");

                Dimension dim = doc.Create.NewDimension(doc.ActiveView, line, refs);

                t.Commit();
            }
        }
Ejemplo n.º 36
0
        /// <summary>
        /// Retrieve all wall openings,
        /// including at start and end of wall.
        /// </summary>
        List <WallOpening2d> GetWallOpenings(
            Wall wall,
            View3D view)
        {
            Document doc           = wall.Document;
            Level    level         = doc.GetElement(wall.LevelId) as Level;
            double   elevation     = level.Elevation;
            Curve    c             = (wall.Location as LocationCurve).Curve;
            XYZ      wallOrigin    = c.GetEndPoint(0);
            XYZ      wallEndPoint  = c.GetEndPoint(1);
            XYZ      wallDirection = wallEndPoint - wallOrigin;
            double   wallLength    = wallDirection.GetLength();

            wallDirection = wallDirection.Normalize();
            UV offsetOut = _offset * new UV(wallDirection.X, wallDirection.Y);

            XYZ rayStart = new XYZ(wallOrigin.X - offsetOut.U,
                                   wallOrigin.Y - offsetOut.V, elevation + _offset);

            ReferenceIntersector intersector
                = new ReferenceIntersector(wall.Id,
                                           FindReferenceTarget.Face, view);

            IList <ReferenceWithContext> refs
                = intersector.Find(rayStart, wallDirection);

            // Extract the intersection points:
            // - only surfaces
            // - within wall length plus offset at each end
            // - sorted by proximity
            // - eliminating duplicates

            List <XYZ> pointList = new List <XYZ>(refs
                                                  .Where <ReferenceWithContext>(r => IsSurface(
                                                                                    r.GetReference()))
                                                  .Where <ReferenceWithContext>(r => r.Proximity
                                                                                < wallLength + _offset + _offset)
                                                  .OrderBy <ReferenceWithContext, double>(
                                                      r => r.Proximity)
                                                  .Select <ReferenceWithContext, XYZ>(r
                                                                                      => r.GetReference().GlobalPoint)
                                                  .Distinct <XYZ>(new XyzEqualityComparer()));

            // Check if first point is at the wall start.
            // If so, the wall does not begin with an opening,
            // so that point can be removed. Else, add it.

            XYZ q = wallOrigin + _offset * XYZ.BasisZ;

            bool wallHasFaceAtStart = Util.IsEqual(
                pointList[0], q);

            if (wallHasFaceAtStart)
            {
                pointList.RemoveAll(p
                                    //=> _eps > p.DistanceTo( q ) );
                                    => Util.IsEqual(p, q));
            }
            else
            {
                pointList.Insert(0, wallOrigin);
            }

            // Check if last point is at the wall end.
            // If so, the wall does not end with an opening,
            // so that point can be removed. Else, add it.

            q = wallEndPoint + _offset * XYZ.BasisZ;

            bool wallHasFaceAtEnd = Util.IsEqual(
                pointList.Last(), q);

            if (wallHasFaceAtEnd)
            {
                pointList.RemoveAll(p
                                    //=> _eps > p.DistanceTo( q ) );
                                    => Util.IsEqual(p, q));
            }
            else
            {
                pointList.Add(wallEndPoint);
            }

            int n = pointList.Count;

            Debug.Assert(IsEven(n),
                         "expected an even number of opening sides");

            var wallOpenings = new List <WallOpening2d>(
                n / 2);

            for (int i = 0; i < n; i += 2)
            {
                wallOpenings.Add(new WallOpening2d
                {
                    Start = pointList[i],
                    End   = pointList[i + 1]
                });
            }
            return(wallOpenings);
        }
Ejemplo n.º 37
0
		public void WriteDynamicElements(View3D view, SlimDX.DataStream LineVerts, ref int LineVertsCount, SlimDX.DataStream LinesIndices, ref int LinesIndicesCount, SlimDX.DataStream TriangleVerts, ref int TriangleVertsCount, SlimDX.DataStream TriangleIndices, ref int TriangleIndicesCount)
		{
			SizeF lineSize = TextRenderHelper.MessureString(m_EmptyLine, FontType.Monospaced, view, 1f);

			float x, y;
			float px = view.PixelSize.X;
			float py = view.PixelSize.Y;

			PointF textLocation = UiStyleHelper.LayoutTextBounds(Bounds, lineSize, ContentAlignment.TopLeft, m_Padding);

			long top = m_TopVisibleLine;

			if (top < m_ConsoleBuffer.TopLine)
			{
				top = m_ConsoleBuffer.TopLine; 
			}

			List<string> lines = m_ConsoleBuffer.GetLines(top, m_NumberOfLines);

			foreach (string line in lines)
			{
				UiStyleHelper.CovertToVertCoords_Relitive(textLocation, view.PixelSize, out x, out y);

				Color4 textColor = UiStyleHelper.GetControlTextColor(this, DisplayMode.Normal);

				TextRenderHelper.WriteInterpreted(view,
													Bounds, lineSize, m_ConsoleBuffer.BufferWidth,
													line, FontType.Monospaced, new Vector3(x, y, ZIndexForLines_Float), 1f,
													ConsoleColorExt.White, m_ColorLookup,
													TriangleVerts, ref TriangleVertsCount,
													TriangleIndices, ref TriangleIndicesCount);

				textLocation.Y = textLocation.Y + lineSize.Height; 
			} 
		}
Ejemplo n.º 38
0
        private void DeleteViewsAndSheets(Document doc, bool onsheet, bool notonsheets, bool sheets, bool templates)
        {
            List <ElementId> delete = new List <ElementId>();

            var allsheets = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Sheets).ToElementIds();

            var allviews = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views).ToElements().Cast <View>().Where(x => x.IsTemplate != true && x.CanBePrinted).ToList();

            if (onsheet)
            {
                if (allsheets.Count > 0)
                {
                    foreach (ElementId id in allsheets)
                    {
                        ViewSheet sheet = doc.GetElement(id) as ViewSheet;

                        ISet <ElementId> views = sheet.GetAllPlacedViews();

                        foreach (ElementId view in views)
                        {
                            if (doc.GetElement(view) != null)
                            {
                                doc.Delete(view);
                            }
                        }
                    }

                    allviews = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views).ToElements().Cast <View>().Where(x => x.IsTemplate != true && x.CanBePrinted).ToList();
                }
            }

            if (sheets)
            {
                foreach (ElementId sheet in allsheets)
                {
                    if (doc.GetElement(sheet) != null)
                    {
                        doc.Delete(sheet);
                    }
                }
                allsheets = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Sheets).ToElementIds();
            }

            if (notonsheets)
            {
                List <ElementId> viewsonsheets = new List <ElementId>();

                if (allsheets.Count > 0)
                {
                    foreach (ElementId id in allsheets)
                    {
                        ViewSheet sheet = doc.GetElement(id) as ViewSheet;

                        viewsonsheets.AddRange(sheet.GetAllPlacedViews());
                    }
                }

                if (viewsonsheets.Count > 0)
                {
                    allviews = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views).Excluding(viewsonsheets).ToElements().Cast <View>().Where(x => x.IsTemplate != true && x.CanBePrinted).ToList();
                }
                else
                {
                    allviews = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views).ToElements().Cast <View>().Where(x => x.IsTemplate != true && x.CanBePrinted).ToList();
                }

                foreach (View view in allviews)
                {
                    if (view.IsValidObject)
                    {
                        if (doc.GetElement(view.Id) != null)
                        {
                            if (view.GetDependentViewIds().Count == 0)
                            {
                                doc.Delete(view.Id);
                            }
                        }
                    }
                }

                if (viewsonsheets.Count > 0)
                {
                    allviews = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views).Excluding(viewsonsheets).ToElements().Cast <View>().Where(x => x.IsTemplate != true && x.CanBePrinted).ToList();
                }
                else
                {
                    allviews = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views).ToElements().Cast <View>().Where(x => x.IsTemplate != true && x.CanBePrinted).ToList();
                }

                foreach (View view in allviews)
                {
                    if (view.IsValidObject)
                    {
                        if (doc.GetElement(view.Id) != null)
                        {
                            if (view.GetDependentViewIds().Count == 0)
                            {
                                doc.Delete(view.Id);
                            }
                        }
                    }
                }
            }

            if (templates)
            {
                var alltemplates = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views).ToElements().Cast <View>().Where(x => x.IsTemplate == true);

                foreach (View template in alltemplates)
                {
                    if (doc.GetElement(template.Id) != null)
                    {
                        doc.Delete(template.Id);
                    }
                }
            }

            allviews = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views).ToElements().Cast <View>().Where(x => x.IsTemplate != true && x.CanBePrinted).ToList();

            if (allviews.Count() == 0)
            {
                var viewFamilyType = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)).Cast <ViewFamilyType>().FirstOrDefault(x => x.ViewFamily == ViewFamily.ThreeDimensional);

                var view3D = View3D.CreateIsometric(doc, viewFamilyType.Id);
            }
        }
Ejemplo n.º 39
0
        /// <summary>
        /// Paint a solid in a new named view
        /// </summary>
        /// <param name="s">solid</param>
        /// <param name="viewName">Given the name of view</param>
        public void PaintSolid(Solid s, String viewName)
        {
            View view;

            if (!viewNameList.Contains(viewName))
            {
                IList <Element> viewFamilyTypes = new FilteredElementCollector(m_doc).OfClass(typeof(ViewFamilyType)).ToElements();
                ElementId       View3DId        = new ElementId(-1);
                foreach (Element e in viewFamilyTypes)
                {
                    if (e.Name == "3D View")
                    {
                        View3DId = e.Id;
                    }
                }

                //view = m_doc.Create.NewView3D(new XYZ(1, 1, 1));
                view = View3D.CreateIsometric(m_doc, View3DId);
                ViewOrientation3D viewOrientation3D = new ViewOrientation3D(new XYZ(1, -1, -1), new XYZ(1, 1, 1), new XYZ(1, 1, -2));
                (view as View3D).SetOrientation(viewOrientation3D);
                (view as View3D).SaveOrientation();
                view.Name = viewName;
                viewNameList.Add(viewName);
            }
            else
            {
                view = (((new FilteredElementCollector(m_doc).
                          OfClass(typeof(View))).Cast <View>()).
                        Where(e => e.Name == viewName)).First <View>();
            }

            SpatialFieldManager sfm = SpatialFieldManager.GetSpatialFieldManager(view);

            if (sfm == null)
            {
                sfm = SpatialFieldManager.CreateSpatialFieldManager(view, 1);
            }

            if (SchemaId != -1)
            {
                IList <int> results = sfm.GetRegisteredResults();

                if (!results.Contains(SchemaId))
                {
                    SchemaId = -1;
                }
            }

            if (SchemaId == -1)
            {
                AnalysisResultSchema resultSchema1 = new AnalysisResultSchema("PaintedSolid" + viewName, "Description");

                AnalysisDisplayStyle displayStyle = AnalysisDisplayStyle.CreateAnalysisDisplayStyle(
                    m_doc,
                    "Real_Color_Surface" + viewName,
                    new AnalysisDisplayColoredSurfaceSettings(),
                    new AnalysisDisplayColorSettings(),
                    new AnalysisDisplayLegendSettings());

                resultSchema1.AnalysisDisplayStyleId = displayStyle.Id;

                SchemaId = sfm.RegisterResult(resultSchema1);
            }

            FaceArray faces = s.Faces;
            Transform trf   = Transform.Identity;

            foreach (Face face in faces)
            {
                int idx = sfm.AddSpatialFieldPrimitive(face, trf);

                IList <UV>           uvPts   = null;
                IList <ValueAtPoint> valList = null;
                ComputeValueAtPointForFace(face, out uvPts, out valList, 1);

                FieldDomainPointsByUV pnts = new FieldDomainPointsByUV(uvPts);

                FieldValues vals = new FieldValues(valList);

                sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, SchemaId);
            }
        }
Ejemplo n.º 40
0
        public override Value Evaluate(FSharpList <Value> args)
        {
            View3D view    = null;
            var    eye     = (XYZ)((Value.Container)args[0]).Item;
            var    target  = (XYZ)((Value.Container)args[1]).Item;
            var    name    = ((Value.String)args[2]).Item;
            var    extents = ((Value.Container)args[3]).Item;
            var    isolate = Convert.ToBoolean(((Value.Number)args[4]).Item);

            var globalUp  = XYZ.BasisZ;
            var direction = target.Subtract(eye);
            var up        = direction.CrossProduct(globalUp).CrossProduct(direction);
            var orient    = new ViewOrientation3D(eye, up, direction);

            if (this.Elements.Any())
            {
                if (dynUtils.TryGetElement(this.Elements[0], out view))
                {
                    if (!view.ViewDirection.IsAlmostEqualTo(direction) || !view.Origin.IsAlmostEqualTo(eye))
                    {
                        view.Unlock();
                        view.SetOrientation(orient);
                        view.SaveOrientationAndLock();
                    }

                    if (!view.Name.Equals(name))
                    {
                        view.Name = ViewBase.CreateUniqueViewName(name);
                    }
                }
                else
                {
                    //create a new view
                    view        = ViewBase.Create3DView(orient, name, isPerspective);
                    Elements[0] = view.Id;
                }
            }
            else
            {
                view = Create3DView(orient, name, isPerspective);
                Elements.Add(view.Id);
            }

            var fec = dynRevitUtils.SetupFilters(dynRevitSettings.Doc.Document);

            if (isolate)
            {
                view.CropBoxActive = true;

                var element = extents as Element;
                if (element != null)
                {
                    var e = element;

                    var all    = fec.ToElements();
                    var toHide =
                        fec.ToElements().Where(x => !x.IsHidden(view) && x.CanBeHidden(view) && x.Id != e.Id).Select(x => x.Id).ToList();

                    if (toHide.Count > 0)
                    {
                        view.HideElements(toHide);
                    }

                    dynRevitSettings.Doc.Document.Regenerate();

                    Debug.WriteLine(string.Format("Eye:{0},Origin{1}, BBox_Origin{2}, Element{3}",
                                                  eye.ToString(), view.Origin.ToString(), view.CropBox.Transform.Origin.ToString(), (element.Location as LocationPoint).Point.ToString()));

                    //http://wikihelp.autodesk.com/Revit/fra/2013/Help/0000-API_Deve0/0039-Basic_In39/0067-Views67/0069-The_View69
                    if (isPerspective)
                    {
                        var farClip = view.get_Parameter("Far Clip Active");
                        farClip.Set(0);
                    }
                    else
                    {
                        //http://adndevblog.typepad.com/aec/2012/05/set-crop-box-of-3d-view-that-exactly-fits-an-element.html
                        var pts = new List <XYZ>();

                        ParseElementGeometry(element, pts);

                        var bounding     = view.CropBox;
                        var transInverse = bounding.Transform.Inverse;
                        var transPts     = pts.Select(transInverse.OfPoint).ToList();

                        //ingore the Z coordindates and find
                        //the max X ,Y and Min X, Y in 3d view.
                        double dMaxX = 0, dMaxY = 0, dMinX = 0, dMinY = 0;

                        //geom.XYZ ptMaxX, ptMaxY, ptMinX,ptMInY;
                        //coorresponding point.
                        bool bFirstPt = true;
                        foreach (var pt1 in transPts)
                        {
                            if (true == bFirstPt)
                            {
                                dMaxX    = pt1.X;
                                dMaxY    = pt1.Y;
                                dMinX    = pt1.X;
                                dMinY    = pt1.Y;
                                bFirstPt = false;
                            }
                            else
                            {
                                if (dMaxX < pt1.X)
                                {
                                    dMaxX = pt1.X;
                                }
                                if (dMaxY < pt1.Y)
                                {
                                    dMaxY = pt1.Y;
                                }
                                if (dMinX > pt1.X)
                                {
                                    dMinX = pt1.X;
                                }
                                if (dMinY > pt1.Y)
                                {
                                    dMinY = pt1.Y;
                                }
                            }
                        }

                        bounding.Max = new XYZ(dMaxX, dMaxY, bounding.Max.Z);
                        bounding.Min = new XYZ(dMinX, dMinY, bounding.Min.Z);
                        view.CropBox = bounding;
                    }
                }
                else
                {
                    var xyz = extents as BoundingBoxXYZ;
                    if (xyz != null)
                    {
                        view.CropBox = xyz;
                    }
                }

                view.CropBoxVisible = false;
            }
            else
            {
                view.UnhideElements(fec.ToElementIds());
                view.CropBoxActive = false;
            }

            return(Value.NewContainer(view));
        }
Ejemplo n.º 41
0
        void IExportControl.Init(UIDocument uidoc, View3D view, AppConfig config, Dictionary <int, bool> elementIds)
        {
            _UIDocument  = uidoc;
            _View        = view;
            _Config      = config;
            _LocalConfig = _Config.Svf;
            _ElementIds  = elementIds;
            _ViewIds     = null;

            _Features = new List <FeatureInfo>
            {
                new FeatureInfo(FeatureType.ExcludeProperties, Strings.FeatureNameExcludeProperties, Strings.FeatureDescriptionExcludeProperties),
                new FeatureInfo(FeatureType.ExcludeTexture, Strings.FeatureNameExcludeTexture, Strings.FeatureDescriptionExcludeTexture, true, false),
                new FeatureInfo(FeatureType.ExcludeLines, Strings.FeatureNameExcludeLines, Strings.FeatureDescriptionExcludeLines),
                new FeatureInfo(FeatureType.ExcludePoints, Strings.FeatureNameExcludePoints, Strings.FeatureDescriptionExcludePoints, true, false),
                new FeatureInfo(FeatureType.UseLevelCategory, Strings.FeatureNameUseLevelCategory, Strings.FeatureDescriptionUseLevelCategory),
                new FeatureInfo(FeatureType.UseNwLevelCategory, Strings.FeatureNameUseNwLevelCategory, Strings.FeatureDescriptionUseNwLevelCategory),
                new FeatureInfo(FeatureType.UseBoundLevelCategory, Strings.FeatureNameUseBoundLevelCategory, Strings.FeatureDescriptionUseBoundLevelCategory),
                new FeatureInfo(FeatureType.OnlySelected, Strings.FeatureNameOnlySelected, Strings.FeatureDescriptionOnlySelected),
                new FeatureInfo(FeatureType.GenerateElementData, Strings.FeatureNameGenerateElementData, Strings.FeatureDescriptionGenerateElementData),
                new FeatureInfo(FeatureType.ExportGrids, Strings.FeatureNameExportGrids, Strings.FeatureDescriptionExportGrids),
                new FeatureInfo(FeatureType.ExportRooms, Strings.FeatureNameExportRooms, Strings.FeatureDescriptionExportRooms),
                new FeatureInfo(FeatureType.ConsolidateGroup, Strings.FeatureNameConsolidateGroup, Strings.FeatureDescriptionConsolidateGroup),
                new FeatureInfo(FeatureType.ConsolidateAssembly, Strings.FeatureNameConsolidateAssembly, Strings.FeatureDescriptionConsolidateAssembly),
                new FeatureInfo(FeatureType.Wireframe, Strings.FeatureNameWireframe, Strings.FeatureDescriptionWireframe, true, false),
                new FeatureInfo(FeatureType.Gray, Strings.FeatureNameGray, Strings.FeatureDescriptionGray, true, false),
                new FeatureInfo(FeatureType.GenerateModelsDb, Strings.FeatureNameGenerateModelsDb, Strings.FeatureDescriptionGenerateModelsDb),
                new FeatureInfo(FeatureType.GenerateThumbnail, Strings.FeatureNameGenerateThumbnail, Strings.FeatureDescriptionGenerateThumbnail),
                new FeatureInfo(FeatureType.UseCurrentViewport, Strings.FeatureNameUseCurrentViewport, Strings.FeatureDescriptionUseCurrentViewport),
                new FeatureInfo(FeatureType.UseViewOverrideGraphic, Strings.FeatureNameUseViewOverrideGraphic, Strings.FeatureDescriptionUseViewOverrideGraphic, true, false),
                new FeatureInfo(FeatureType.UseBasicRenderColor, string.Empty, string.Empty, true, false),
                new FeatureInfo(FeatureType.Export2DViewOnlySheet, Strings.FeatureNameExport2DViewOnlySheet, Strings.FeatureDescriptionExport2DViewOnlySheet),
                new FeatureInfo(FeatureType.Export2DViewAll, Strings.FeatureNameExport2DViewAll, Strings.FeatureDescriptionExport2DViewAll),
                new FeatureInfo(FeatureType.GenerateLeaflet, Strings.FeatureNameGenerateLeaflet, Strings.FeatureDescriptionGenerateLeaflet),
                new FeatureInfo(FeatureType.GenerateDwgDrawing, Strings.FeatureNameGenerateDwgDrawing, Strings.FeatureDescriptionGenerateDwgDrawing),
                new FeatureInfo(FeatureType.Force2DViewUseWireframe, Strings.FeatureNameForce2DViewUseWireframe, Strings.FeatureDescriptionForce2DViewUseWireframe),
                new FeatureInfo(FeatureType.RegroupForLink, Strings.FeatureNameRegroupForLink, Strings.FeatureDescriptionRegroupForLink),
            };

            _VisualStyles = new List <VisualStyleInfo>();
            _VisualStyles.Add(new VisualStyleInfo(@"Wireframe", Strings.VisualStyleWireframe, new Dictionary <FeatureType, bool>
            {
                { FeatureType.ExcludeTexture, true },
                { FeatureType.Wireframe, true },
                { FeatureType.UseViewOverrideGraphic, false },
                { FeatureType.UseBasicRenderColor, false },
                { FeatureType.Gray, false }
            }));
            _VisualStyles.Add(new VisualStyleInfo(@"Gray", Strings.VisualStyleGray, new Dictionary <FeatureType, bool>
            {
                { FeatureType.ExcludeTexture, true },
                { FeatureType.Wireframe, false },
                { FeatureType.UseViewOverrideGraphic, false },
                { FeatureType.UseBasicRenderColor, false },
                { FeatureType.Gray, true }
            }));
            _VisualStyles.Add(new VisualStyleInfo(@"Colored", Strings.VisualStyleColored, new Dictionary <FeatureType, bool>
            {
                { FeatureType.ExcludeTexture, true },
                { FeatureType.Wireframe, false },
                { FeatureType.UseViewOverrideGraphic, true },
                { FeatureType.UseBasicRenderColor, false },
                { FeatureType.Gray, false }
            }));
            _VisualStyles.Add(new VisualStyleInfo(@"Textured", Strings.VisualStyleTextured + $@"({Strings.TextDefault})", new Dictionary <FeatureType, bool>
            {
                { FeatureType.ExcludeTexture, false },
                { FeatureType.Wireframe, false },
                { FeatureType.UseViewOverrideGraphic, false },
                { FeatureType.UseBasicRenderColor, true },
                { FeatureType.Gray, false }
            }));
            _VisualStyles.Add(new VisualStyleInfo(@"Realistic", Strings.VisualStyleRealistic, new Dictionary <FeatureType, bool>
            {
                { FeatureType.ExcludeTexture, false },
                { FeatureType.Wireframe, false },
                { FeatureType.UseViewOverrideGraphic, false },
                { FeatureType.UseBasicRenderColor, false },
                { FeatureType.Gray, false }
            }));
            _VisualStyleDefault = _VisualStyles.First(x => x.Key == @"Textured");

            _LevelOfDetails = new List <ComboItemInfo>();
            _LevelOfDetails.Add(new ComboItemInfo(-1, Strings.TextAuto));
            for (var i = 0; i <= 15; i++)
            {
                string text;
                switch (i)
                {
                case 0:
                    text = $@"{i} ({Strings.TextLowest})";
                    break;

                case 8:
                    text = $@"{i} ({Strings.TextNormal})";
                    break;

                case 15:
                    text = $@"{i} ({Strings.TextHighest})";
                    break;

                default:
                    text = i.ToString();
                    break;
                }

                _LevelOfDetails.Add(new ComboItemInfo(i, text));
            }
            _LevelOfDetailDefault = _LevelOfDetails.Find(x => x.Value == -1);

            cbVisualStyle.Items.Clear();
            cbVisualStyle.Items.AddRange(_VisualStyles.Select(x => (object)x).ToArray());

            cbLevelOfDetail.Items.Clear();
            cbLevelOfDetail.Items.AddRange(_LevelOfDetails.Select(x => (object)x).ToArray());
        }
Ejemplo n.º 42
0
        void Focus(UIApplication uiapp, Document doc, Element_Change item)
        {
            try
            {
                BoundingBoxXYZ boundingBoxXYZ = new BoundingBoxXYZ();
                ResetView(uiapp, doc);
                double a = 2;
                if (item.element != null && item.element_link != null)
                {
                    BoundingBoxXYZ boundingbox_1 = item.element.get_BoundingBox(null);
                    BoundingBoxXYZ boundingbox_2 = item.element_link.get_BoundingBox(null);

                    var x_1_min = boundingbox_1.Min.X;
                    var y_1_min = boundingbox_1.Min.Y;
                    var z_1_min = boundingbox_1.Min.Z;

                    var x_2_min = boundingbox_2.Min.X;
                    var y_2_min = boundingbox_2.Min.Y;
                    var z_2_min = boundingbox_2.Min.Z;

                    XYZ min = new XYZ(Math.Max(x_1_min, x_2_min) - a, Math.Max(y_1_min, y_2_min) - a, Math.Max(z_1_min, z_2_min) - a);

                    var x_1_max = boundingbox_1.Max.X;
                    var y_1_max = boundingbox_1.Max.Y;
                    var z_1_max = boundingbox_1.Max.Z;

                    var x_2_max = boundingbox_2.Max.X;
                    var y_2_max = boundingbox_2.Max.Y;
                    var z_2_max = boundingbox_2.Max.Z;

                    XYZ max = new XYZ(Math.Min(x_1_max, x_2_max) + a, Math.Min(y_1_max, y_2_max) + a, Math.Min(z_1_max, z_2_max) + a);

                    boundingBoxXYZ.Min = min;
                    boundingBoxXYZ.Max = max;
                }
                else if (item.element != null && item.element_link == null)
                {
                    BoundingBoxXYZ boundingbox_1 = item.element.get_BoundingBox(null);

                    XYZ min = new XYZ(boundingbox_1.Min.X - a, boundingbox_1.Min.Y - a, boundingbox_1.Min.Z - a);
                    XYZ max = new XYZ(boundingbox_1.Max.X + a, boundingbox_1.Max.Y + a, boundingbox_1.Max.Z + a);

                    boundingBoxXYZ.Min = min;
                    boundingBoxXYZ.Max = max;
                }
                else if (item.element == null && item.element_link != null)
                {
                    BoundingBoxXYZ boundingbox_1 = item.element_link.get_BoundingBox(null);

                    XYZ min = new XYZ(boundingbox_1.Min.X - a, boundingbox_1.Min.Y - a, boundingbox_1.Min.Z - a);
                    XYZ max = new XYZ(boundingbox_1.Max.X + a, boundingbox_1.Max.Y + a, boundingbox_1.Max.Z + a);

                    boundingBoxXYZ.Min = min;
                    boundingBoxXYZ.Max = max;
                }

                View3D view = doc.ActiveView as View3D;
                view.SetSectionBox(boundingBoxXYZ);

                var UIView = uiapp.ActiveUIDocument.GetOpenUIViews();
                foreach (var view1 in UIView)
                {
                    if (view1.ViewId == view.Id)
                    {
                        view1.ZoomAndCenterRectangle(boundingBoxXYZ.Min, boundingBoxXYZ.Max);
                    }
                }

                Selection select = uiapp.ActiveUIDocument.Selection;
                if (item.element != null)
                {
                    select.SetElementIds(new List <ElementId>()
                    {
                        item.element.Id
                    });
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Ejemplo n.º 43
0
		public static void WriteInterpreted(View3D view,
											RectangleF RemainingBounds, SizeF lineSize, int maxWidth, 
											string buffer, FontType fontType, Vector3 start, float scale, 
											ConsoleColorExt foregroundColor, Color4[] colorLookup,
											SlimDX.DataStream TriangleVerts, ref int TriangleVertsCount,
											SlimDX.DataStream TriangleIndices, ref int TriangleIndicesCount)
		{
			string prefix = ""; 
			int lastIndex = 0;
			Stack<ConsoleColorExt> stack = new Stack<ConsoleColorExt>();

			ConsoleColorExt activeForegroundColor = foregroundColor;

			float x = start.X, y = start.Y; 

			foreach (Match match in ConsoleFormatter.FormatRegex.Matches(buffer))
			{
				if (match.Groups["Tag"].Success)
				{
					// start tag 
					// parse the tags inner value
					// e.g. c:# (where # is the name or ID of the colour to use (From ConsoleColourExt) 
					// add the parsed colour to the stack 

					ConsoleColorExt col = ConsoleFormatter.ParseColour(match.Groups["Inner"].Value, RC.Theme);

					stack.Push(activeForegroundColor);

					activeForegroundColor = col;
				}
				else if (match.Groups["EndTag"].Success)
				{
					// end tag 
					// handle stack changes
					if (stack.Count >= 0)
					{
						activeForegroundColor = stack.Pop();
					}
					else
					{
						throw new Exception(string.Format("Unexpected end tag at index {0}", match.Index));
					}
				}
				else if (match.Groups["Text"].Success)
				{
					string wholeMessage = ConsoleFormatter.UnescapeString(match.Value);

					List<string> lines = ConsoleFormatter.SplitLinebreaks(wholeMessage);

					foreach (string line in lines)
					{
						string str = line;

						if (str == "\n" || str == Environment.NewLine)
						{
							//BufferWriteLine("");
							x = start.X;
							y += lineSize.Height; 

							lastIndex = 0;
						}
						else
						{
							while (str.Length > 0)
							{
								if (lastIndex + str.Length > maxWidth)
								{
									int lastWord = str.LastIndexOf(' ', maxWidth - lastIndex, maxWidth - lastIndex);

									if (lastWord <= 0)
									{
										lastWord = maxWidth - lastIndex;
									}

									string toRender;

									if (lastIndex > 0)
									{
										toRender = str.Substring(0, lastWord);
									}
									else
									{
										toRender = prefix + str.Substring(0, lastWord);
									}

									if (maxWidth == lastIndex + toRender.Length)
									{
										WriteString(view,
													RemainingBounds,
													toRender, fontType, ref x, ref y, start.Z, scale, colorLookup[(int)activeForegroundColor],
													TriangleVerts, ref TriangleVertsCount,
													TriangleIndices, ref TriangleIndicesCount);
										
										//BufferWrite(toRender);
									}
									else
									{
										WriteString(view,
													RemainingBounds,
													toRender, fontType, ref x, ref y, start.Z, scale, colorLookup[(int)activeForegroundColor],
													TriangleVerts, ref TriangleVertsCount,
													TriangleIndices, ref TriangleIndicesCount);

//										BufferWriteLine(toRender);
										
										x = start.X;
										y += lineSize.Height; 
									}

									str = str.Substring(lastWord + 1);

									lastIndex = 0;
								}
								else
								{
									string toRender = str;

									if (lastIndex <= 0)
									{
										toRender = prefix + str;
									}

									//BufferWrite(toRender);
									WriteString(view,
													RemainingBounds,
													toRender, fontType, ref x, ref y, start.Z, scale, colorLookup[(int)activeForegroundColor],
													TriangleVerts, ref TriangleVertsCount,
													TriangleIndices, ref TriangleIndicesCount);
										
									lastIndex += str.Length;

									str = "";
								}
							}
						}
					}
				}
			}
		}
Ejemplo n.º 44
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {

            Application app = commandData.Application.Application;
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document doc = uidoc.Document;
            View view1 = doc.ActiveView;
            const double mmTofeet = 1.0 / 304.8;

            //Check if the view is a 3D view, and if it is locked:
            if (view1.ViewType == ViewType.ThreeD)
            {
                View3D view3D1 = (View3D)view1;
                if (!view3D1.IsLocked)
                {
                    TaskDialog.Show("Error", "3D-view must be locked to place tags");
                    return Result.Cancelled;
                }
            }

            //Check if the view has a usable sketchplane active, create and set one if not.
            if (view1.SketchPlane != null)
            {
                XYZ existingSPdir = view1.SketchPlane.GetPlane().Normal;
                if (Math.Abs(view1.ViewDirection.AngleTo(existingSPdir)) > 000.1)
                {
                    SetWorkPlane(view1, doc);
                }
            }
            else SetWorkPlane(view1, doc);

            //Get the rebar host: Use selected element if exactly one is selected, else ask user to pick a element that is host for rebar.
            Element host1 = null;
            XYZ topPt1 = new XYZ();
            try
            {
                ICollection<ElementId> selectedElementIds = uidoc.Selection.GetElementIds();
                if (selectedElementIds.Count == 1)
                {
                    host1 = doc.GetElement(selectedElementIds.First());
                }
                else host1 = doc.GetElement(uidoc.Selection.PickObject(ObjectType.Element, new RebarHostSelectionFilter(), "Pick a rebar host").ElementId);

                //ui: Pick a point where the top tag should be placed (host tag)
                topPt1 = uidoc.Selection.PickPoint("Pick a point to place tags");
            }

            catch (Autodesk.Revit.Exceptions.OperationCanceledException)
            {
                return Result.Cancelled;
            }
            /*
            //Select all rebars and get their hostId, pick the ones with hostId==host1.Id
            FilteredElementCollector fec1 = new FilteredElementCollector(doc, view1.Id).OfCategory(BuiltInCategory.OST_Rebar);
            List<Autodesk.Revit.DB.Structure.Rebar> rebarList = fec1.Cast<Autodesk.Revit.DB.Structure.Rebar>().Where(e => e.GetHostId() == host1.Id).ToList();
            */
            
            //Get rebars in host:
            IList<Autodesk.Revit.DB.Structure.Rebar> rebarList = RebarHostData.GetRebarHostData(host1).GetRebarsInHost();

            //Get View Scale and updirection from active view
            double scale1 = System.Convert.ToDouble(view1.get_Parameter(BuiltInParameter.VIEW_SCALE).AsInteger());
            XYZ viewDirUp1 = view1.UpDirection;
            double tagSize1 = 3.5 * mmTofeet;
            double spacing1 = tagSize1 + (2.0 * mmTofeet);
            XYZ deltaVec = viewDirUp1.Normalize().Multiply(spacing1 * scale1);



            //Calculate the spacing of the tags
            int numberOfTags = rebarList.Count();
            XYZ tempPt = topPt1;
            List<XYZ> ptList = new List<XYZ>();
            for (int i = 0; i < numberOfTags; i++)
            {
                tempPt = tempPt.Subtract(deltaVec);
                ptList.Add(tempPt);
            }


            using (Transaction t2 = new Transaction(doc, "Create tag"))
            {
                t2.Start();
#if RVT2017
                doc.Create.NewTag(view1, host1, false, TagMode.TM_ADDBY_CATEGORY, TagOrientation.Horizontal, topPt1);
#else
                IndependentTag.Create(doc, view1.Id, new Reference(host1), false, TagMode.TM_ADDBY_CATEGORY, TagOrientation.Horizontal, topPt1);
#endif
                for (int i = 0; i < numberOfTags; i++)
                {
#if RVT2017 
                    doc.Create.NewTag(view1, rebarList[i], false, TagMode.TM_ADDBY_CATEGORY, TagOrientation.Horizontal, ptList[i]);
#else
                    IndependentTag.Create(doc, view1.Id, new Reference(rebarList[i]), false, TagMode.TM_ADDBY_CATEGORY, TagOrientation.Horizontal, ptList[i]);
#endif
                }

                t2.Commit();
            }

            //The external command requres a return.
            return Result.Succeeded;
        }
Ejemplo n.º 45
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app    = commandData.Application;
            Document      doc    = app.ActiveUIDocument.Document;
            View3D        view3d = doc.ActiveView as View3D;

            if (null == view3d)
            {
                message = "Please activate a 3D view"
                          + " before running this command.";

                return(Result.Failed);
            }

            // get the 3d view crop box:

            BoundingBoxXYZ bb = view3d.CropBox;

            // get the transform from the current view
            // to the 3D model:

            Transform transform = bb.Transform;

            // get the transform from the 3D model
            // to the current view:

            Transform transformInverse = transform.Inverse;

            // get all rooms in the model:

            FilteredElementCollector collector
                = new FilteredElementCollector(doc);

            collector.OfClass(typeof(Room));
            IList <Element> rooms = collector.ToElements();
            int             n     = rooms.Count;

            Room room = (0 < n)
        ? rooms[BumpRoomIndex(n)] as Room
        : null;

            if (null == room)
            {
                message = "No room element found in project.";
                return(Result.Failed);
            }

            // Collect all vertices of room closed shell
            // to determine its extents:

            GeometryElement e        = room.ClosedShell;
            List <XYZ>      vertices = new List <XYZ>();

            //foreach( GeometryObject o in e.Objects ) // 2012

            foreach (GeometryObject o in e) // 2013
            {
                if (o is Solid)
                {
                    // Iterate over all the edges of all solids:

                    Solid solid = o as Solid;

                    foreach (Edge edge in solid.Edges)
                    {
                        foreach (XYZ p in edge.Tessellate())
                        {
                            // Collect all vertices,
                            // including duplicates:

                            vertices.Add(p);
                        }
                    }
                }
            }

            List <XYZ> verticesIn3dView = new List <XYZ>();

            foreach (XYZ p in vertices)
            {
                verticesIn3dView.Add(
                    transformInverse.OfPoint(p));
            }

            // Ignore the Z coorindates and find the
            // min and max X and Y in the 3d view:

            double xMin = 0, yMin = 0, xMax = 0, yMax = 0;

            bool first = true;

            foreach (XYZ p in verticesIn3dView)
            {
                if (first)
                {
                    xMin  = p.X;
                    yMin  = p.Y;
                    xMax  = p.X;
                    yMax  = p.Y;
                    first = false;
                }
                else
                {
                    if (xMin > p.X)
                    {
                        xMin = p.X;
                    }
                    if (yMin > p.Y)
                    {
                        yMin = p.Y;
                    }
                    if (xMax < p.X)
                    {
                        xMax = p.X;
                    }
                    if (yMax < p.Y)
                    {
                        yMax = p.Y;
                    }
                }
            }

            // Grow the crop box by one twentieth of its
            // size to include the walls of the room:

            double d = 0.05 * (xMax - xMin);

            xMin = xMin - d;
            xMax = xMax + d;

            d    = 0.05 * (yMax - yMin);
            yMin = yMin - d;
            yMax = yMax + d;

            bb.Max = new XYZ(xMax, yMax, bb.Max.Z);
            bb.Min = new XYZ(xMin, yMin, bb.Min.Z);

            view3d.CropBox = bb;

            // Change the crop view setting manually or
            // programmatically to see the result:

            view3d.CropBoxActive  = true;
            view3d.CropBoxVisible = true;

            return(Result.Succeeded);
        }
Ejemplo n.º 46
0
        private void TreatUnsupportedWalls(IList <Level> strLevels)
        {
            // Create ref 3D view to get outline of the selected wall
            ViewFamilyType viewFamilyType =
                (from v in new FilteredElementCollector(_doc)
                 .OfClass(typeof(ViewFamilyType))
                 .Cast <ViewFamilyType>()
                 where v.ViewFamily == ViewFamily.ThreeDimensional
                 select v).First();
            Transaction t = new Transaction(_doc);

            t.Start("Create auxiliary 3D View to get the size of the building");
            _auxiliary3DView = View3D.CreateIsometric(_doc, viewFamilyType.Id);
            t.Commit();

            List <Wall> toCheckWallList =
                new FilteredElementCollector(_doc)
                .OfClass(typeof(Wall))
                .Cast <Wall>()
                .ToList();

            List <Wall> unsupportedWallList = new List <Wall>();

            foreach (Wall toCheckdWall in toCheckWallList)
            {
                Line selectedWallAxeLine = (toCheckdWall.Location as LocationCurve).Curve as Line;

                Level selectedWallLevel = _doc.GetElement(toCheckdWall.LevelId) as Level;

                Level wallStructLevel = (from Level l in strLevels
                                         where l.Id == selectedWallLevel.Id
                                         select l).FirstOrDefault();

                int wallLevelInd = strLevels.IndexOf(wallStructLevel);

                ElementId lowerLevelId = wallLevelInd == 0 ?
                                         ElementId.InvalidElementId : strLevels[wallLevelInd - 1].Id;

                // Get all the beams who are parallel with the selected wall
                // and at the same level of the wall
                List <Element> beamList =
                    (from FamilyInstance beam in new FilteredElementCollector(_doc)
                     .OfCategory(BuiltInCategory.OST_StructuralFraming)
                     .OfClass(typeof(FamilyInstance))
                     .Cast <FamilyInstance>()
                     where beam.Host != null && beam.Host.Name.Equals(selectedWallLevel.Name) &&
                     IsCollinear(selectedWallAxeLine, (beam.Location as LocationCurve).Curve as Line)
                     select beam as Element)
                    .ToList();

                //TaskDialog.Show("Revit", $"{beamList.Count} beams as supporter");

                // Get all the walls who are parallel with the selected wall
                // and at the lower level of the wall
                List <Element> wallList =
                    (from Wall wall in new FilteredElementCollector(_doc)
                     .OfClass(typeof(Wall))
                     .Cast <Wall>()
                     where wall.LevelId == lowerLevelId &&
                     IsCollinear(selectedWallAxeLine, (wall.Location as LocationCurve).Curve as Line)
                     select wall as Element)
                    .ToList();

                //TaskDialog.Show("Revit", $"{wallList.Count} walls as supporter");

                // List of beams & walls to loop
                List <Element> supporterList = new List <Element>();
                supporterList.AddRange(beamList);
                supporterList.AddRange(wallList);

                // Check the support situation
                bool wallIsEntirelySupported = false;

                if (supporterList.Count != 0)
                {
                    Element        originalSupporter = supporterList.First();
                    List <Element> loopSupporterList = supporterList;
                    for (int i = 0; i < supporterList.Count; i++)
                    {
                        wallIsEntirelySupported = FinalOutlinContainseRefOutline(
                            toCheckdWall, originalSupporter, loopSupporterList,
                            out List <Element> remainList);

                        if (wallIsEntirelySupported || remainList.Count == 0)
                        {
                            break;
                        }

                        originalSupporter = remainList.First();
                        loopSupporterList = remainList;
                    }
                }

                if (!wallIsEntirelySupported)
                {
                    unsupportedWallList.Add(toCheckdWall);
                }
            }

            if (unsupportedWallList.Count != 0)
            {
                AddWallListToTable(unsupportedWallList, _form.UnsupportedWallDataTable);
            }

            // Delete the ref 3D view
            t.Start("Delete the auxiliary 3D View");
            _doc.Delete(_auxiliary3DView.Id);
            t.Commit();
        }
Ejemplo n.º 47
0
		protected void UpdateBuffers(View3D view)
		{
			if (m_Disposed == true)
			{
				return;
			}

			int LineVerts = 0;
			int LinesIndices = 0;
			int TriangleVerts = 0;
			int TriangleIndices = 0;

			DataStream LineVertsStream;
			DataStream LinesIndicesStream;
			DataStream TriangleVertsStream;
			DataStream TriangleIndicesStream;

			try
			{
				m_DynamicBuffer.MapStreams(MapMode.WriteDiscard, out LineVertsStream, out LinesIndicesStream, out TriangleVertsStream, out TriangleIndicesStream);

				foreach (IDynamicUiControl control in DynamicControls)
				{
					if (control.IsVisible == false)
					{
						continue; 
					}

					if (control.IsParentVisible == false)
					{
						continue;
					}

					control.WriteDynamicElements(view, LineVertsStream, ref LineVerts, LinesIndicesStream, ref LinesIndices, TriangleVertsStream, ref TriangleVerts, TriangleIndicesStream, ref TriangleIndices);
				}
			}
			finally
			{
				m_DynamicBuffer.UnmapStreams(LineVerts, LinesIndices, TriangleVerts, TriangleIndices);
			}

		}
Ejemplo n.º 48
0
		public void OnMouseMoved(View3D view, Vector2 mousePosition, out bool shouldUpdate)
		{
			Vector2 mousePositionCorrected = mousePosition + view.ViewportOffset; // new Vector2(view.Viewport.X, view.Viewport.Y);

			shouldUpdate = false;

			if (m_Focused != null &&
				(m_MouseState == MouseState.Dragging ||
				m_MouseState == MouseState.DragStart))
			{
				m_MouseState = MouseState.Dragging;
				m_Focused.DoMouseInteraction(m_MouseState, m_MouseButtons, mousePositionCorrected, out shouldUpdate);
			}
			else
			{
				UiControl foundTopMost = null;

				foreach (UiControl control in Controls)
				{
					UiControl found = null;

					if (control.IsVisible == true)
					{
						control.BeginPick(mousePositionCorrected, out found);
					}

					if (found != null)
					{
						if (foundTopMost == null)
						{
							foundTopMost = found;
						}
						else if (foundTopMost.ZIndex < found.ZIndex)
						{
							foundTopMost = found;
						}
					}
				}

				if (foundTopMost != null && m_Control_ClickStart == foundTopMost)
				{
					m_MouseState = MouseState.ClickStart;
				}
				else
				{
					if (m_Hovered != null && foundTopMost != m_Hovered && m_Hovered is UiSubScene)
					{
						bool shouldSubUpdate;
						(m_Hovered as UiSubScene).OnMouseMoved(view, mousePosition, out shouldSubUpdate);
					}

					if (m_Hovered != null && foundTopMost != null)
					{
						if (m_Hovered != foundTopMost)
						{
							m_Hovered.EndPick(mousePositionCorrected, PickType.UnHover, foundTopMost);

							if (m_Hovered is UiSubScene)
							{
								(m_Hovered as UiSubScene).UnhoverControls();
							}

							m_Hovered = foundTopMost;

							m_Hovered.EndPick(mousePositionCorrected, PickType.Hover, m_Hovered);

							shouldUpdate = true;
						}
					}
					else if (foundTopMost != null)
					{
						m_Hovered = foundTopMost;

						m_Hovered.EndPick(mousePositionCorrected, PickType.Hover, m_Hovered);

						shouldUpdate = true;
					}
					else if (m_Hovered != null && foundTopMost == null)
					{
						m_Hovered.EndPick(mousePositionCorrected, PickType.UnHover, null);

						if (m_Hovered is UiSubScene)
						{
							(m_Hovered as UiSubScene).UnhoverControls();
						}

						m_Hovered = null;

						shouldUpdate = true;
					}

					if (m_Hovered != null && m_Hovered is UiSubScene)
					{
						bool shouldSubUpdate;
						(m_Hovered as UiSubScene).OnMouseMoved(view, mousePosition, out shouldSubUpdate);
					}

					if (m_Hovered != null)
					{
						m_MouseState = MouseState.Hovering;
					}
					else
					{
						m_MouseState = MouseState.Moving;
					}
				}
			}
		}
Ejemplo n.º 49
0
		public void OnMouseDown(View3D view, Vector2 mousePosition, System.Windows.Forms.MouseButtons mouseButtons, out bool shouldUpdate)
		{
			Vector2 mousePositionCorrected = mousePosition + view.ViewportOffset; // new Vector2(view.Viewport.X, view.Viewport.Y);

			shouldUpdate = false;

			UiControl foundTopMost = null;

			foreach (UiControl control in Controls)
			{
				UiControl found = null;

				if (control.IsVisible == true)
				{
					control.BeginPick(mousePositionCorrected, out found);
				}

				if (found != null)
				{
					if (foundTopMost == null)
					{
						foundTopMost = found;
					}
					else if (foundTopMost.ZIndex < found.ZIndex)
					{
						foundTopMost = found;
					}
				}
			}

			if (m_Focused != null && foundTopMost != null)
			{
				if (m_Focused != foundTopMost)
				{
					m_Focused.EndPick(mousePositionCorrected, PickType.UnFocus, foundTopMost);

					if (m_Focused is UiSubScene)
					{
						(m_Focused as UiSubScene).UnfocusControls();
					}

					m_Focused = foundTopMost;

					m_Focused.EndPick(mousePositionCorrected, PickType.Focus, m_Focused);

					shouldUpdate = true;
				}
			}
			else if (foundTopMost != null)
			{
				m_Focused = foundTopMost;

				m_Focused.EndPick(mousePositionCorrected, PickType.Focus, m_Focused);

				shouldUpdate = true;
			}
			else if (m_Focused != null && foundTopMost == null)
			{
				m_Focused.EndPick(mousePositionCorrected, PickType.UnFocus, null);

				if (m_Focused is UiSubScene)
				{
					(m_Focused as UiSubScene).UnfocusControls();
				}

				m_Focused = null;

				shouldUpdate = true;
			}

			if (m_Focused != null)
			{
				if (m_Focused is UiSubScene)
				{
					bool shouldSubUpdate;					
					(m_Focused as UiSubScene).OnMouseDown(view, mousePosition, mouseButtons, out shouldSubUpdate);

					m_MouseState = MouseState.Hovering;
					m_MouseButtons = System.Windows.Forms.MouseButtons.None;
				}
				else
				{
					if ((m_Focused.InteractionType & ControlInteractionType.Drag) == ControlInteractionType.Drag)
					{
						m_MouseState = MouseState.DragStart;
						m_MouseButtons = mouseButtons;

						m_Focused.DoMouseInteraction(m_MouseState, m_MouseButtons, mousePositionCorrected, out shouldUpdate);
					}
					else if ((m_Focused.InteractionType & ControlInteractionType.Click) == ControlInteractionType.Click)
					{
						m_MouseState = MouseState.ClickStart;
						m_MouseButtons = mouseButtons;
						m_Control_ClickStart = m_Focused;

						m_Focused.DoMouseInteraction(m_MouseState, m_MouseButtons, mousePositionCorrected, out shouldUpdate);
					}
					else
					{
						m_MouseState = MouseState.Hovering;
						m_MouseButtons = System.Windows.Forms.MouseButtons.None;

						m_Focused.DoMouseInteraction(m_MouseState, m_MouseButtons, mousePositionCorrected, out shouldUpdate);
					}
				}
			}
			else
			{
				m_MouseState = MouseState.None;
				m_MouseButtons = System.Windows.Forms.MouseButtons.None;
				m_Control_ClickStart = null;
			}
		}
Ejemplo n.º 50
0
		public virtual void Update(View3D view)
		{


		}
Ejemplo n.º 51
0
		public void OnMouseClick(View3D view, Vector2 mousePosition, System.Windows.Forms.MouseButtons mouseButtons, out bool shouldUpdate)
		{
			shouldUpdate = false;
		}
        /// <summary>
        /// Return a reference to the topmost face of the given element.
        /// </summary>
        private Reference FindTopMostReference(Element e)
        {
            Reference ret = null;
            Document  doc = e.Document;

            #region Revit 2012
#if _2012
            using (SubTransaction t = new SubTransaction(doc))
            {
                t.Start();

                // Create temporary 3D view

                //View3D view3D = doc.Create.NewView3D( // 2012
                //  viewDirection ); // 2012

                ViewFamilyType vft
                    = new FilteredElementCollector(doc)
                      .OfClass(typeof(ViewFamilyType))
                      .Cast <ViewFamilyType>()
                      .FirstOrDefault <ViewFamilyType>(x =>
                                                       ViewFamily.ThreeDimensional == x.ViewFamily);

                Debug.Assert(null != vft,
                             "expected to find a valid 3D view family type");

                View3D view = View3D.CreateIsometric(doc, vft.Id); // 2013

                XYZ eyePosition      = XYZ.BasisZ;
                XYZ upDirection      = XYZ.BasisY;
                XYZ forwardDirection = -XYZ.BasisZ;

                view.SetOrientation(new ViewOrientation3D(
                                        eyePosition, upDirection, forwardDirection));

                XYZ viewDirection = -XYZ.BasisZ;

                BoundingBoxXYZ bb = e.get_BoundingBox(view);

                XYZ max = bb.Max;

                XYZ minAtMaxElevation = Create.NewXYZ(
                    bb.Min.X, bb.Min.Y, max.Z);

                XYZ centerOfTopOfBox = 0.5
                                       * (minAtMaxElevation + max);

                centerOfTopOfBox += 10 * XYZ.BasisZ;

                // Cast a ray through the model
                // to find the topmost surface

#if DEBUG
                //ReferenceArray references
                //  = doc.FindReferencesByDirection(
                //    centerOfTopOfBox, viewDirection, view3D ); // 2011

                IList <ReferenceWithContext> references
                    = doc.FindReferencesWithContextByDirection(
                          centerOfTopOfBox, viewDirection, view); // 2012

                double closest = double.PositiveInfinity;

                //foreach( Reference r in references )
                //{
                //  // 'Autodesk.Revit.DB.Reference.Element' is
                //  // obsolete: Property will be removed. Use
                //  // Document.GetElement(Reference) instead.
                //  //Element re = r.Element; // 2011

                //  Element re = doc.GetElement( r ); // 2012

                //  if( re.Id.IntegerValue == e.Id.IntegerValue
                //    && r.ProximityParameter < closest )
                //  {
                //    ret = r;
                //    closest = r.ProximityParameter;
                //  }
                //}

                foreach (ReferenceWithContext r in references)
                {
                    Element re = doc.GetElement(
                        r.GetReference()); // 2012

                    if (re.Id.IntegerValue == e.Id.IntegerValue &&
                        r.Proximity < closest)
                    {
                        ret     = r.GetReference();
                        closest = r.Proximity;
                    }
                }

                string stable_reference = null == ret ? null
          : ret.ConvertToStableRepresentation(doc);
#endif // DEBUG

                ReferenceIntersector ri
                    = new ReferenceIntersector(
                          e.Id, FindReferenceTarget.Element, view);

                ReferenceWithContext r2 = ri.FindNearest(
                    centerOfTopOfBox, viewDirection);

                if (null == r2)
                {
                    Debug.Print("ReferenceIntersector.FindNearest returned null!");
                }
                else
                {
                    ret = r2.GetReference();

                    Debug.Assert(stable_reference.Equals(ret
                                                         .ConvertToStableRepresentation(doc)),
                                 "expected same reference from "
                                 + "FindReferencesWithContextByDirection and "
                                 + "ReferenceIntersector");
                }
                t.RollBack();
            }
#endif // _2012
            #endregion // Revit 2012

            Options opt = doc.Application.Create
                          .NewGeometryOptions();

            opt.ComputeReferences = true;

            GeometryElement geo = e.get_Geometry(opt);

            foreach (GeometryObject obj in geo)
            {
                GeometryInstance inst = obj as GeometryInstance;

                if (null != inst)
                {
                    geo = inst.GetSymbolGeometry();
                    break;
                }
            }

            Solid solid = geo.OfType <Solid>()
                          .First <Solid>(sol => null != sol);

            double z = double.MinValue;

            foreach (Face f in solid.Faces)
            {
                BoundingBoxUV b        = f.GetBoundingBox();
                UV            p        = b.Min;
                UV            q        = b.Max;
                UV            midparam = p + 0.5 * (q - p);
                XYZ           midpoint = f.Evaluate(midparam);
                XYZ           normal   = f.ComputeNormal(midparam);

                if (Util.PointsUpwards(normal))
                {
                    if (midpoint.Z > z)
                    {
                        z   = midpoint.Z;
                        ret = f.Reference;
                    }
                }
            }
            return(ret);
        }
Ejemplo n.º 53
0
		public DroneShot(View3D dView3DParam)
		{
			definingView = dView3DParam;
		}
Ejemplo n.º 54
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            // This command requires an active document

            if (null == uidoc)
            {
                message = "Please run this command in an active project document.";
                return(Result.Failed);
            }

            View3D view = doc.ActiveView as View3D;

            if (null == view)
            {
                message = "Please run this command in a 3D view.";
                return(Result.Failed);
            }

            // Instantiate our custom context

            ExportContextAdnMesh context
                = new ExportContextAdnMesh(doc);

            // Instantiate a custom exporter with it

            using (CustomExporter exporter
                       = new CustomExporter(doc, context))
            {
                // Tell the exporter whether we need face info.
                // If not, it is better to exclude them, since
                // processing faces takes significant time and
                // memory. In any case, tessellated polymeshes
                // can be exported (and will be sent to the
                // context). Excluding faces just excludes the calls,
                // not the actual processing of face tessellation.
                // Meshes of the faces will still be received by
                // the context.

                exporter.IncludeGeometricObjects = false;
                //exporter.IncludeFaces = false;

                exporter.Export(view);
            }

            // Save ADN mesh data in JSON format

            StreamWriter s = new StreamWriter(
                "C:/tmp/test.json");

            s.Write("[");

            int i = 0;

            foreach (AdnMeshData d in context.MeshData)
            {
                if (0 < i)
                {
                    s.Write(',');
                }

                s.Write(d.ToJson());

                ++i;
            }

            s.Write("\n]\n");
            s.Close();

            return(Result.Succeeded);
        }
Ejemplo n.º 55
0
		public void Render(View3D view)
		{
			Matrix viewProjWorld = (view.World * view.View) * view.Projection;

			Effect.Render(m_DataBindings, m_InstanceCount, viewProjWorld, m_ParticleTextureView, m_ColorScale, m_ParticleScale * m_ParticleScaleX, m_ParticleScale * m_ParticleScaleY, m_MinDistance, m_MaxDistance, m_ScaleDistance); 
		}
Ejemplo n.º 56
0
        /// <summary>
        /// 运行按钮的点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnRun_Click(object sender, RoutedEventArgs e)
        {
            //
            double viewOffset        = 0; //平面视图的偏移量
            double elevationOffset   = 0; //里面的偏移量  暂时不支持"L"型房间 她的生成边框线的法向量不稳定
            double FloorThickness    = 0; //地面楼板的厚度 用于将立面的底边框上抬到楼板上 used to move the bottom of Elevation up the floor
            bool   isViewOffset      = Double.TryParse(tbViewOffset.Text, out viewOffset);
            bool   isElevationOffset = Double.TryParse(tbElevationOffset.Text, out elevationOffset);
            bool   isFloorThickness  = Double.TryParse(tbFloorThickness.Text, out FloorThickness);

            //判断输入数值是否有效
            if (!isViewOffset)
            {
                TaskDialog.Show("ViewOffsetWrong", "Pleace set a right Number of ViewOffset");
                return;
            }
            if (!isElevationOffset)
            {
                TaskDialog.Show("ElevationOffsetWrong", "Pleace set a right Number of ElevationOffset");
                return;
            }
            if (!isElevationOffset)
            {
                TaskDialog.Show("FloorThicknessWrong", "Pleace set a right Number of FloorThickness");
                return;
            }

            //无选择房间时重选 Re selecte a new room if selected room is null
            if (DocSet.selRoom == null)
            {
                TaskDialog.Show("selRoomIsNull", "Pleace selecet a room");
                this.Hide();
                DocSet.selRoom = DocSet.doc.GetElement(DocSet.selection.PickObject(ObjectType.Element, "Pleace selecet a room")) as Room;
                if (DocSet.selRoom == null)
                {
                    TaskDialog.Show("RoomWrong", "the Element you selecet is not a ROOM");
                    this.ShowDialog();
                    return;
                }
            }

            //获取房间的SoA Number  get the SOANumber of the selected room
            _SoANumber = " - A";
            try
            {
                Parameter SoANuber = DocSet.selRoom.LookupParameter("SoA Number");
                _SoANumber += SoANuber.AsString().Replace(".", "-");
            }
            catch
            {
                TaskDialog.Show("soanumber null", "Cant find the SoA Number");
                _SoANumber = null;
            }

            //
            View3D view3d = Create3DView();

            CreateNewViewPlan(viewOffset, view3d);
            CreateElevations(elevationOffset, FloorThickness);

            //CreateSheetView(view);

            this.Close();
        }
Ejemplo n.º 57
0
        private void Stream( ArrayList data, View3D view )
        {
            data.Add( new Snoop.Data.ClassSeparator( typeof( View3D ) ) );
              Utils.StreamWithReflection( data, typeof( View3D ), view );

              /*
              data.Add(new Snoop.Data.Xyz("Eye position", view.EyePosition));
              data.Add(new Snoop.Data.Bool("Is perspective", view.IsPerspective));
              data.Add(new Snoop.Data.Object("Section box", view.SectionBox));
              */
        }
Ejemplo n.º 58
0
        void IExportControl.Init(UIDocument uidoc, View3D view, AppConfig config, Dictionary <int, bool> elementIds)
        {
            _UIDocument  = uidoc;
            _View        = view;
            _Config      = config;
            _LocalConfig = _Config.Gltf;
            _ElementIds  = elementIds;

            _Features = new List <FeatureInfo>
            {
                new FeatureInfo(FeatureType.ExcludeTexture, Strings.FeatureNameExcludeTexture, Strings.FeatureDescriptionExcludeTexture, true, false),
                new FeatureInfo(FeatureType.ExcludeLines, Strings.FeatureNameExcludeLines, Strings.FeatureDescriptionExcludeLines),
                new FeatureInfo(FeatureType.ExcludePoints, Strings.FeatureNameExcludePoints, Strings.FeatureDescriptionExcludePoints, true, false),
                new FeatureInfo(FeatureType.OnlySelected, Strings.FeatureNameOnlySelected, Strings.FeatureDescriptionOnlySelected),
                new FeatureInfo(FeatureType.ExportGrids, Strings.FeatureNameExportGrids, Strings.FeatureDescriptionExportGrids),
                new FeatureInfo(FeatureType.Wireframe, Strings.FeatureNameWireframe, Strings.FeatureDescriptionWireframe, true, false),
                new FeatureInfo(FeatureType.Gray, Strings.FeatureNameGray, Strings.FeatureDescriptionGray, true, false),
                new FeatureInfo(FeatureType.GenerateModelsDb, Strings.FeatureNameGenerateModelsDb, Strings.FeatureDescriptionGenerateModelsDb),
                new FeatureInfo(FeatureType.UseViewOverrideGraphic, Strings.FeatureNameUseViewOverrideGraphic, Strings.FeatureDescriptionUseViewOverrideGraphic, true, false),
                new FeatureInfo(FeatureType.UseBasicRenderColor, string.Empty, string.Empty, true, false),
                new FeatureInfo(FeatureType.UseGoogleDraco, Strings.FeatureNameUseGoogleDraco, Strings.FeatureDescriptionUseGoogleDraco, true, false),
                new FeatureInfo(FeatureType.ExtractShell, Strings.FeatureNameExtractShell, Strings.FeatureDescriptionExtractShell, true, false),
                new FeatureInfo(FeatureType.ExportSvfzip, Strings.FeatureNameExportSvfzip, Strings.FeatureDescriptionExportSvfzip, true, false),
            };

            _VisualStyles = new List <VisualStyleInfo>();
            _VisualStyles.Add(new VisualStyleInfo(@"Wireframe", Strings.VisualStyleWireframe, new Dictionary <FeatureType, bool>
            {
                { FeatureType.ExcludeTexture, true },
                { FeatureType.Wireframe, true },
                { FeatureType.UseViewOverrideGraphic, false },
                { FeatureType.UseBasicRenderColor, false },
                { FeatureType.Gray, false }
            }));
            _VisualStyles.Add(new VisualStyleInfo(@"Gray", Strings.VisualStyleGray, new Dictionary <FeatureType, bool>
            {
                { FeatureType.ExcludeTexture, true },
                { FeatureType.Wireframe, false },
                { FeatureType.UseViewOverrideGraphic, false },
                { FeatureType.UseBasicRenderColor, false },
                { FeatureType.Gray, true }
            }));
            _VisualStyles.Add(new VisualStyleInfo(@"Colored", Strings.VisualStyleColored, new Dictionary <FeatureType, bool>
            {
                { FeatureType.ExcludeTexture, true },
                { FeatureType.Wireframe, false },
                { FeatureType.UseViewOverrideGraphic, true },
                { FeatureType.UseBasicRenderColor, false },
                { FeatureType.Gray, false }
            }));
            _VisualStyles.Add(new VisualStyleInfo(@"Textured", Strings.VisualStyleTextured + $@"({Strings.TextDefault})", new Dictionary <FeatureType, bool>
            {
                { FeatureType.ExcludeTexture, false },
                { FeatureType.Wireframe, false },
                { FeatureType.UseViewOverrideGraphic, false },
                { FeatureType.UseBasicRenderColor, true },
                { FeatureType.Gray, false }
            }));
            _VisualStyles.Add(new VisualStyleInfo(@"Realistic", Strings.VisualStyleRealistic, new Dictionary <FeatureType, bool>
            {
                { FeatureType.ExcludeTexture, false },
                { FeatureType.Wireframe, false },
                { FeatureType.UseViewOverrideGraphic, false },
                { FeatureType.UseBasicRenderColor, false },
                { FeatureType.Gray, false }
            }));
            _VisualStyleDefault = _VisualStyles.First(x => x.Key == @"Colored");

            const int DEFAULT_LEVEL_OF_DETAILS = 6;

            _LevelOfDetails = new List <ComboItemInfo>();
            _LevelOfDetails.Add(new ComboItemInfo(-1, Strings.TextAuto));
            for (var i = 0; i <= 15; i++)
            {
                string text;
                switch (i)
                {
                case 0:
                    text = $@"{i} ({Strings.TextLowest})";
                    break;

                case DEFAULT_LEVEL_OF_DETAILS:
                    text = $@"{i} ({Strings.TextNormal})";
                    break;

                case 15:
                    text = $@"{i} ({Strings.TextHighest})";
                    break;

                default:
                    text = i.ToString();
                    break;
                }

                _LevelOfDetails.Add(new ComboItemInfo(i, text));
            }
            _LevelOfDetailDefault = _LevelOfDetails.Find(x => x.Value == DEFAULT_LEVEL_OF_DETAILS);

            cbVisualStyle.Items.Clear();
            cbVisualStyle.Items.AddRange(_VisualStyles.Select(x => (object)x).ToArray());

            cbLevelOfDetail.Items.Clear();
            cbLevelOfDetail.Items.AddRange(_LevelOfDetails.Select(x => (object)x).ToArray());
        }
Ejemplo n.º 59
0
    public Result Execute(
        ExternalCommandData commandData,
        ref string message,
        ElementSet elements)
    {
        UIApplication uiApp = commandData.Application;

        string      keystr    = @"Software\FamilyToDWG";
        string      revityear = "2016";
        string      subkeystr = "TemplateLocation" + revityear;
        RegistryKey key       = Registry.CurrentUser.OpenSubKey(keystr, true);

        if (key == null)
        {
            key = Registry.CurrentUser.CreateSubKey(keystr);
            key.SetValue(subkeystr, "");
        }

        if (key.GetValue(subkeystr, null).ToString() == "" || File.Exists(key.GetValue(subkeystr).ToString()) == false)
        {
            var templateFD = new OpenFileDialog();
            templateFD.Filter = "rte files (*.rte)|*.rte";
            templateFD.Title  = "Choose a Template";
            templateFD.ShowDialog();
            string docdir = templateFD.FileName;
            key.SetValue(subkeystr, @docdir);
        }

        if (key.GetValue(subkeystr, null).ToString() == null)
        {
            return(Result.Failed);
        }

        Autodesk.Revit.DB.Document uiDoc;

        try
        {
            uiDoc = uiApp.Application.NewProjectDocument(key.GetValue(subkeystr).ToString());
        }
        catch
        {
            DialogResult res = MessageBox.Show("The Selected template file was unable to be opened by Revit.");
            return(Result.Failed);
        }

        if (uiDoc == null)
        {
            return(Result.Failed);
        }

        if (!Directory.Exists(@"C:\temp\"))
        {
            Directory.CreateDirectory(@"C:\temp\");
        }

        if (File.Exists(@"C:\temp\new_project.rvt"))
        {
            File.Delete(@"C:\temp\new_project.rvt");
        }

        SaveAsOptions options1 = new SaveAsOptions();

        options1.OverwriteExistingFile = true;
        uiDoc.SaveAs(@"C:/temp/new_project.rvt", options1);

        uiApp.OpenAndActivateDocument(@"C:/temp/new_project.rvt");

        var FD = new OpenFileDialog();

        FD.Filter = "rfa files (*.rfa)|*.rfa";
        FD.Title  = "Choose A RevitRFA Family file";
        FD.ShowDialog();

        string filename = FD.SafeFileName;
        string filedir  = FD.FileName.Replace(filename, "");

        if (File.Exists(FD.FileName))
        {
            using (Transaction tx = new Transaction(uiDoc))
            {
                tx.Start("Load Family");
                Autodesk.Revit.DB.Family family = null;
                uiDoc.LoadFamily(FD.FileName, out family);
                tx.Commit();

                string name = family.Name;
                foreach (ElementId id in family.GetFamilySymbolIds())
                {
                    FamilySymbol famsymbol = family.Document.GetElement(id) as FamilySymbol;
                    XYZ          origin    = new XYZ(0, 0, 0);
                    tx.Start("Load Family Member");
                    famsymbol.Activate();
                    FamilyInstance instance = uiDoc.Create.NewFamilyInstance(origin, famsymbol, StructuralType.NonStructural);
                    tx.Commit();

                    DWGExportOptions options = new DWGExportOptions();
                    options.FileVersion             = ACADVersion.R2007;
                    options.ExportOfSolids          = SolidGeometry.ACIS;
                    options.HideUnreferenceViewTags = true;
                    //options.FileVersion = (ACADVersion)(3);

                    var collector = new FilteredElementCollector(uiDoc);

                    var viewFamilyType = collector
                                         .OfClass(typeof(ViewFamilyType))
                                         .OfType <ViewFamilyType>()
                                         .FirstOrDefault(x => x.ViewFamily == ViewFamily.ThreeDimensional);

                    // Export the active view
                    ICollection <ElementId> views = new List <ElementId>();
                    tx.Start("ChangeView");
                    View3D view = View3D.CreateIsometric(uiDoc, viewFamilyType.Id);
                    view.DisplayStyle = DisplayStyle.Shading;
                    tx.Commit();
                    views.Add(view.Id);
                    //views.Add(uiDoc.ActiveView.Id);
                    string dwgfilename     = famsymbol.Name + ".dwg";
                    string dwgfullfilename = filedir + dwgfilename;
                    if (File.Exists(dwgfullfilename))
                    {
                        File.Delete(dwgfullfilename);
                    }
                    uiDoc.Export(@filedir, @dwgfilename, views, options);

                    tx.Start("Delete Family Member");
                    uiDoc.Delete(instance.Id);
                    tx.Commit();
                }
            }
        }
        else
        {
            Console.WriteLine("Please Create Export Directory For the chosen CAPS file.");
        }

        return(Result.Succeeded);
    }
Ejemplo n.º 60
0
        /// <summary>
        /// Get geometry of family instances and show them in Revit views
        /// </summary>
        public void GetInstanceGeometry()
        {
            FilteredElementCollector instanceCollector = new FilteredElementCollector(RevitDoc);

            instanceCollector.OfClass(typeof(FamilyInstance));

            // create views by different names
            ElementId       View3DId = new ElementId(-1);
            IList <Element> elems    = new FilteredElementCollector(RevitDoc).OfClass(typeof(ViewFamilyType)).ToElements();

            foreach (Element e in elems)
            {
                ViewFamilyType v = e as ViewFamilyType;

                if (v != null && v.ViewFamily == ViewFamily.ThreeDimensional)
                {
                    View3DId = e.Id;
                    break;
                }
            }

            //View instanceView = RevitDoc.Create.NewView3D(new XYZ(1, 1, -1));
            View3D            instanceView = View3D.CreateIsometric(RevitDoc, View3DId);
            ViewOrientation3D instanceViewOrientation3D = new ViewOrientation3D(new XYZ(-30.8272352809007, -2.44391067967133, 18.1013736367246), new XYZ(0.577350269189626, 0.577350269189626, -0.577350269189626), new XYZ(0.408248290463863, 0.408248290463863, 0.816496580927726));

            instanceView.SetOrientation(instanceViewOrientation3D);
            instanceView.SaveOrientation();
            instanceView.Name = "InstanceGeometry";

            //View originalView = RevitDoc.Create.NewView3D(new XYZ(0, 1, -1));
            View3D            originalView = View3D.CreateIsometric(RevitDoc, View3DId);
            ViewOrientation3D originalViewOrientation3D = new ViewOrientation3D(new XYZ(-19.0249866627872, -5.09536632799455, 20.7528292850478), new XYZ(0, 0.707106781186547, -0.707106781186547), new XYZ(0, 0.707106781186548, 0.707106781186548));

            originalView.SetOrientation(originalViewOrientation3D);
            originalView.SaveOrientation();
            originalView.Name = "OriginalGeometry";

            //View transView = RevitDoc.Create.NewView3D(new XYZ(-1, 1, -1));
            View3D transView = View3D.CreateIsometric(RevitDoc, View3DId);
            //ViewOrientation3D transViewOrientation3D = new ViewOrientation3D(new XYZ(-7.22273804467383, -2.44391067967133, 18.1013736367246), new XYZ(-0.577350269189626, 0.577350269189626, -0.577350269189626), new XYZ(-0.408248290463863, 0.408248290463863, 0.816496580927726));
            ViewOrientation3D transViewOrientation3D = new ViewOrientation3D(new XYZ(-19.0249866627872, -5.09536632799455, 20.7528292850478), new XYZ(0, 0.707106781186547, -0.707106781186547), new XYZ(0, 0.707106781186548, 0.707106781186548));

            transView.SetOrientation(transViewOrientation3D);
            transView.SaveOrientation();
            transView.Name = "TransformedGeometry";

            foreach (FamilyInstance instance in instanceCollector)
            {
                GeometryElement instanceGeo  = instance.get_Geometry(m_options);
                GeometryElement slaveGeo     = instance.GetOriginalGeometry(m_options);
                GeometryElement transformGeo = slaveGeo.GetTransformed(instance.GetTransform());

                // show family instance geometry
                //foreach (GeometryObject obj in instanceGeo.Objects)
                IEnumerator <GeometryObject> Objects = instanceGeo.GetEnumerator();
                while (Objects.MoveNext())
                {
                    GeometryObject obj = Objects.Current;

                    if (obj is Solid)
                    {
                        Solid solid = obj as Solid;
                        PaintSolid(solid, instanceView);
                    }
                }

                // show geometry that is original geometry
                //foreach (GeometryObject obj in slaveGeo.Objects)
                IEnumerator <GeometryObject> Objects1 = slaveGeo.GetEnumerator();
                while (Objects1.MoveNext())
                {
                    GeometryObject obj = Objects1.Current;

                    if (obj is Solid)
                    {
                        Solid solid = obj as Solid;
                        PaintSolid(solid, originalView);
                    }
                }

                // show geometry that was transformed
                //foreach (GeometryObject obj in transformGeo.Objects)
                IEnumerator <GeometryObject> Objects2 = transformGeo.GetEnumerator();
                while (Objects2.MoveNext())
                {
                    GeometryObject obj = Objects2.Current;

                    if (obj is Solid)
                    {
                        Solid solid = obj as Solid;
                        PaintSolid(solid, transView);
                    }
                }
            }
            // remove original instances to view point results.
            RevitDoc.Delete(instanceCollector.ToElementIds());
        }