/// <summary> /// Orthogonal View by Perspective Camera. /// </summary> /// <param name="bcfView"></param> /// <param name="camera"></param> /// <returns></returns> private bool SetOrthogonalView(View3D bcfView, PerspectiveCamera camera) { var result = false; try { var direction = RevitUtils.GetRevitXYZ(camera.CameraDirection); var upVector = RevitUtils.GetRevitXYZ(camera.CameraUpVector); var viewPoint = RevitUtils.GetRevitXYZ(camera.CameraViewPoint); var orientation = RevitUtils.ConvertBasePoint(ActiveDoc, viewPoint, direction, upVector, true); using (var trans = new Transaction(ActiveDoc)) { trans.Start("Set Orientation"); try { bcfView.SetOrientation(orientation); trans.Commit(); } catch (Exception) { trans.RollBack(); } } SetViewPointBoundingBox(bcfView); result = true; } catch (Exception) { // ignored } return(result); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { var uiapp = commandData.Application; UIDocument uidoc = commandData.Application.ActiveUIDocument; Document doc = uidoc.Document; Selection sel = uidoc.Selection; Transaction ts =new Transaction(doc,"创建3d视图"); ts.Start(); //Find a 3D view type IEnumerable<ViewFamilyType> viewFamilyTypes = from elem in new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)) let type = elem as ViewFamilyType where type.ViewFamily == ViewFamily.ThreeDimensional select type; //create new Perspective View3D View3D view3D = View3D.CreatePerspective(doc, viewFamilyTypes.First().Id); if (null != view3D) { // by default, the 3d view uses a default orientation. XYZ eye = new XYZ(0, -100, 10); XYZ up = new XYZ(0, 0, 1); XYZ forward = new XYZ(0, 1, 0); view3D.SetOrientation(new ViewOrientation3D(eye, up, forward)); //turn off the far clip plane with standard parameter API Parameter farClip = view3D.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR); farClip.Set(1); } ts.Commit(); return Result.Succeeded; }
/// <summary> /// Get all 3D views in current document /// </summary> private void Get3DViews() { m_view3DList = new List <Autodesk.Revit.DB.Element>(); FilteredElementCollector collector = new FilteredElementCollector(m_document); var query = from elem in collector.OfClass(typeof(View3D)) let viewElem = elem as View3D where null != viewElem && !viewElem.IsTemplate select elem; m_view3DList = query.ToList <Element>(); if (m_view3DList.Count == 0) { //View3D view3D = m_document.Create.NewView3D(new Autodesk.Revit.DB.XYZ (0, 0, 1)); IList <Element> viewFamilyTypes = new FilteredElementCollector(m_document).OfClass(typeof(ViewFamilyType)).ToElements(); ElementId View3DId = new ElementId(-1); foreach (Element e in viewFamilyTypes) { if (e.Name == "3D View") { View3DId = e.Id; } } View3D view3D = View3D.CreateIsometric(m_document, View3DId); ViewOrientation3D viewOrientation3D = new ViewOrientation3D(new XYZ(1, 1, -1), new XYZ(0, 0, 1), new XYZ(0, 1, 0)); view3D.SetOrientation(viewOrientation3D); view3D.SaveOrientation(); m_view3DList.Add(view3D); } }
public static View3D Create3DView(ViewOrientation3D orient, string name, bool isPerspective) { //http://adndevblog.typepad.com/aec/2012/05/viewplancreate-method.html IEnumerable <ViewFamilyType> viewFamilyTypes = from elem in new FilteredElementCollector(dynRevitSettings.Doc.Document).OfClass(typeof(ViewFamilyType)) let type = elem as ViewFamilyType where type.ViewFamily == ViewFamily.ThreeDimensional select type; //create a new view View3D view = isPerspective ? View3D.CreatePerspective(dynRevitSettings.Doc.Document, viewFamilyTypes.First().Id) : View3D.CreateIsometric(dynRevitSettings.Doc.Document, viewFamilyTypes.First().Id); view.SetOrientation(orient); view.SaveOrientationAndLock(); try { //will fail if name is not unique view.Name = name; } catch { view.Name = CreateUniqueViewName(name); } return(view); }
// We need to create a 3dview because the when we open a new project file a 3d view does not exist and raytracers need 3dviews private View3D createView3d() { FilteredElementCollector collector0 = new FilteredElementCollector(_doc).OfClass(typeof(View3D)); foreach (View3D item in collector0) { if (!item.IsTemplate) { return(item); } } FilteredElementCollector collector1 = new FilteredElementCollector(_doc); collector1 = collector1.OfClass(typeof(ViewFamilyType)); IEnumerable <ViewFamilyType> viewFamilyTypes = from elem in collector1 let vftype = elem as ViewFamilyType where (vftype.ViewFamily == ViewFamily.ThreeDimensional) select vftype; using (Transaction createView3D = new Transaction(_doc)) { createView3D.Start("Create 3D View"); View3D view3D = View3D.CreateIsometric(_doc, viewFamilyTypes.First <ViewFamilyType>().Id); if (null != view3D) { XYZ eye = new XYZ(10, 10, 10); XYZ up = new XYZ(0, 1, 1); XYZ forward = new XYZ(0, 1, -1); ViewOrientation3D viewOrientation3D = new ViewOrientation3D(eye, up, forward); view3D.SetOrientation(viewOrientation3D); view3D.Name = "RayTracer View"; } createView3D.Commit(); return(view3D); } }
private void ApplyViewOrientationAndVisibility(UIDocument uiDocument, View3D view, Camera camera) { using var trans = new Transaction(uiDocument.Document); if (trans.Start($"Apply view orientation and visibility in '{view.Name}'") != TransactionStatus.Started) { return; } StatusBarService.SetStatusText("Loading view point data ..."); Log.Information("Calculating view orientation from camera position ..."); ProjectPosition projectPosition = uiDocument.Document.ActiveProjectLocation.GetProjectPosition(XYZ.Zero); var viewOrientation3D = RevitUtils.TransformCameraPosition( new ProjectPositionWrapper(projectPosition), camera.Position.ToInternalUnits(), true) .ToViewOrientation3D(); if (camera.Type == CameraType.Perspective) { Log.Information("Setting active far viewer bound to zero ..."); Parameter farClip = view.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR); if (farClip.HasValue) { farClip.Set(0); } } Log.Information("Applying new view orientation ..."); view.SetOrientation(viewOrientation3D); Log.Information("Applying element visibility ..."); var currentlyVisibleElements = uiDocument.Document.GetVisibleElementsOfView(view); var map = uiDocument.Document.GetIfcGuidElementIdMap(currentlyVisibleElements); var exceptionElements = GetViewpointVisibilityExceptions(map); var selectedElements = GetViewpointSelection(map); if (exceptionElements.Any()) { if (_bcfViewpoint.GetVisibilityDefault()) { view.HideElementsTemporary(exceptionElements); selectedElements = selectedElements.Where(id => !exceptionElements.Contains(id)).ToList(); } else { view.IsolateElementsTemporary(exceptionElements); selectedElements = selectedElements.Where(id => exceptionElements.Contains(id)).ToList(); } } view.ConvertTemporaryHideIsolateToPermanent(); if (selectedElements.Any()) { Log.Information("Select {n} elements ...", selectedElements.Count); uiDocument.Selection.SetElementIds(selectedElements); } trans.Commit(); }
/// <summary> /// Create perspective view with camera settings /// matching the Forge Viewer. /// </summary> void CreatePerspectiveViewMatchingCamera( Document doc, XYZ camera_position, XYZ target) { using (var trans = new Transaction(doc)) { trans.Start("Map Forge Viewer Camera"); ViewFamilyType typ = new FilteredElementCollector(doc) .OfClass(typeof(ViewFamilyType)) .Cast <ViewFamilyType>() .First <ViewFamilyType>( x => x.ViewFamily.Equals( ViewFamily.ThreeDimensional)); // Create a new perspective 3D view View3D view3D = View3D.CreatePerspective( doc, typ.Id); Random rnd = new Random(); view3D.Name = string.Format("Camera{0}", rnd.Next()); // By default, the 3D view uses a default // orientation. Change that by creating and // setting up a suitable ViewOrientation3D. //var position = new XYZ( -15.12436009332275, // -8.984616232971192, 4.921260089050291 ); var up = XYZ.BasisZ; //var target = new XYZ( -15.02436066552734, // -8.984211875061035, 4.921260089050291 ); var sightDir = target.Subtract(camera_position).Normalize(); var orientation = new ViewOrientation3D( camera_position, up, sightDir); view3D.SetOrientation(orientation); // Turn off the far clip plane, etc. view3D.LookupParameter("Far Clip Active") .Set(0); view3D.LookupParameter("Crop Region Visible") .Set(1); view3D.LookupParameter("Crop View") .Set(1); trans.Commit(); } }
public void ViewCreate() { Document doc = this.ActiveUIDocument.Document; // get a ViewFamilyType for a 3D View. created new instance of ViewFamilYType calle 'viewFamilyType' ViewFamilyType viewFamilyType = (from v in new FilteredElementCollector(doc). // Creates new filteredElementCollector to select all ViewFamilyTypes OfClass(typeof(ViewFamilyType)). Cast <ViewFamilyType>() where v.ViewFamily == ViewFamily.ThreeDimensional select v).First(); Categories categories = doc.Settings.Categories; Category dim = categories.get_Item(BuiltInCategory.OST_Dimensions); Category line = categories.get_Item(BuiltInCategory.OST_Lines); XYZ eye = new XYZ(100, 100, 100); XYZ forward = new XYZ(-1, 1, -1); XYZ up = new XYZ(-1, 1, 2); ViewOrientation3D vOrient = new ViewOrientation3D(eye, up, forward); using (Transaction t = new Transaction(doc, "Create view")) { t.Start(); View3D view = View3D.CreateIsometric(doc, viewFamilyType.Id); view.get_Parameter(BuiltInParameter.MODEL_GRAPHICS_STYLE) .Set(4); view.SetOrientation(vOrient); view.HideCategoryTemporary(dim.Id); view.HideCategoryTemporary(line.Id); view.SaveOrientationAndLock(); t.Commit(); } }
public override Value Evaluate(FSharpList <Value> args) { View3D view = null; var eye = (XYZ)((Value.Container)args[0]).Item; var userUp = (XYZ)((Value.Container)args[1]).Item; var direction = (XYZ)((Value.Container)args[2]).Item; var name = ((Value.String)args[3]).Item; XYZ side; if (direction.IsAlmostEqualTo(userUp) || direction.IsAlmostEqualTo(userUp.Negate())) { side = XYZ.BasisZ.CrossProduct(direction); } else { side = userUp.CrossProduct(direction); } XYZ up = side.CrossProduct(direction); //need to reverse the up direction to get the //proper orientation - there might be a better way to handle this var orient = new ViewOrientation3D(eye, -up, direction); if (this.Elements.Any()) { Element e; if (dynUtils.TryGetElement(this.Elements[0], typeof(View3D), out e)) { view = (View3D)e; if (!view.ViewDirection.IsAlmostEqualTo(direction)) { view.Unlock(); view.SetOrientation(orient); view.SaveOrientationAndLock(); } if (view.Name != null && view.Name != name) { view.Name = CreateUniqueViewName(name); } } else { //create a new view view = dynViewBase.Create3DView(orient, name, false); Elements[0] = view.Id; } } else { view = Create3DView(orient, name, false); Elements.Add(view.Id); } return(Value.NewContainer(view)); }
///调整三维视图的角度 /// public static void Modify3DViewDirection(View3D view) { XYZ eyePosition = new XYZ(); XYZ upDirection = XYZ.BasisZ; XYZ forDirection = XYZ.BasisY; ViewOrientation3D orientation = new ViewOrientation3D(eyePosition, upDirection, forDirection); view.SetOrientation(orientation); }
private void SetCamera(Element element, Transform transform, Edge edge, View3D view3D) { if (edge.AsCurve().CreateTransformed(transform) is Line locationCurve) { var up = transform.OfVector(XYZ.BasisZ); view3D.SetOrientation(new ViewOrientation3D(locationCurve.Origin, up, locationCurve.Direction)); _uidoc.ShowElements(element); _uidoc.RefreshActiveView(); } }
public static View3D GetMatching3DView(this View view, Document doc) { ViewFamilyType viewFamilyType = (from v in new FilteredElementCollector(doc). OfClass(typeof(ViewFamilyType)). Cast <ViewFamilyType>() where v.ViewFamily == ViewFamily.ThreeDimensional select v).First(); View3D view3d = View3D.CreateIsometric(doc, viewFamilyType.Id); view3d.Name = view.Name + " 3D temp view"; ViewBox myviewbox = GetViewBox(view); if (myviewbox.bbox == null) { BoundingBoxXYZ boundingBoxXYZ = new BoundingBoxXYZ(); boundingBoxXYZ.Min = myviewbox.P1; boundingBoxXYZ.Max = myviewbox.P2; view3d.SetSectionBox(boundingBoxXYZ); } else { view3d.SetSectionBox(myviewbox.bbox); } view3d.SetOrientation(new ViewOrientation3D(myviewbox.EyePosition, myviewbox.DirectionUp, myviewbox.DirectionView)); foreach (Category cat in doc.Settings.Categories) { try { if (cat.CategoryType == CategoryType.Model && cat.get_AllowsVisibilityControl(view3d)) { view3d.SetVisibility(cat, view.GetVisibility(cat)); } } catch (System.Exception e) { } } doc.Regenerate(); return(view3d); }
private bool SetPerspectiveView(View3D bcfView, PerspectiveCamera camera) { var result = false; try { var zoom = camera.FieldOfView; var direction = RevitUtils.GetRevitXYZ(camera.CameraDirection); var upVector = RevitUtils.GetRevitXYZ(camera.CameraUpVector); var viewPoint = RevitUtils.GetRevitXYZ(camera.CameraViewPoint); var orientation = RevitUtils.ConvertBasePoint(ActiveDoc, viewPoint, direction, upVector, true); using (var trans = new Transaction(ActiveDoc)) { trans.Start("Set Orientation"); try { if (bcfView.CanResetCameraTarget()) { bcfView.ResetCameraTarget(); } bcfView.SetOrientation(orientation); if (bcfView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR).HasValue) { var m_farClip = bcfView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR); m_farClip.Set(0); } bcfView.CropBoxActive = true; bcfView.CropBoxVisible = true; trans.Commit(); } catch (Exception) { trans.RollBack(); } } result = true; } catch (Exception) { // ignored } return(result); }
private static View3D createView3D(string prefix, BoundedViewCreator boundedViewCreator, int demandViewScale, OverrideGraphicSettings modelElementsOgs) { string _fullViewName = boundedViewCreator.GetViewName(prefix, "FP"); View3D _view3D = boundedViewCreator.CreateView3D(demandViewScale, _fullViewName); _view3D.SetCategoryHidden(new ElementId(BuiltInCategory.OST_VolumeOfInterest), true); _view3D.SetCategoryHidden(new ElementId(BuiltInCategory.OST_SectionBox), true); _view3D.SetCategoryHidden(new ElementId(BuiltInCategory.OST_Levels), true); _view3D.SetCategoryHidden(new ElementId(BuiltInCategory.OST_Floors), true); _view3D.SetCategoryOverrides(new ElementId(BuiltInCategory.OST_StructuralColumns), modelElementsOgs); _view3D.SetCategoryOverrides(new ElementId(BuiltInCategory.OST_StructuralFraming), modelElementsOgs); _view3D.SetCategoryOverrides(new ElementId(BuiltInCategory.OST_Walls), modelElementsOgs); _view3D.SetOrientation(new ViewOrientation3D(_view3D.Origin, new XYZ(0, 1, 0), new XYZ(0, 0, -1))); _view3D.AreAnalyticalModelCategoriesHidden = true; return(_view3D); }
////[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] private static void CreatePerspectiveFromSection(UIDocument udoc, View sectionView) { UIView view = ActiveUIView(udoc, sectionView); XYZ eye = GetMiddleOfActiveViewWindow(view); XYZ up = new XYZ(0, 0, 1); XYZ forward = new XYZ(0, 0, -1); ViewOrientation3D v = new ViewOrientation3D(eye, up, forward); using (var t = new Transaction(udoc.Document)) { t.Start("Create perspective view"); View3D np = View3D.CreatePerspective(udoc.Document, Get3DViewFamilyTypes(udoc.Document).First().Id); np.SetOrientation(new ViewOrientation3D(v.EyePosition, v.UpDirection, v.ForwardDirection)); ApplySectionBoxToView(SectionViewExtentsBoundingBox(view), np); t.Commit(); } }
/// <summary> /// Prompt the user for an eye position and a /// view direction, the set the view orientation /// accordingly. /// </summary> public JumpToPosition( View3D view, IWin32Window owner_window_handle) { Document doc = view.Document; JumpForm form = new JumpForm(); DialogResult rslt = form.ShowDialog( owner_window_handle); if (DialogResult.OK == rslt) { using (Transaction tx = new Transaction(doc)) { tx.Start("Jump to Position"); XYZ eye = form.Eye; XYZ forward = form.Viewdir; XYZ left = Util.IsVertical(forward) ? -XYZ.BasisX : XYZ.BasisZ.CrossProduct(forward); XYZ up = forward.CrossProduct(left); // Setting ùp`to the Z axis, XYZ.BasisZ, throws // Autodesk.Revit.Exceptions.ArgumentsInconsistentException: // The vectors upDirection and forwardDirection // are not perpendicular. ViewOrientation3D orientation = new ViewOrientation3D(eye, up, forward); view.SetOrientation(orientation); RefreshView(view); tx.Commit(); } } }
public static Dictionary <string, object> createNavisView(Document document) { string message = ""; //Document doc = DocumentManager.Instance.CurrentDBDocument; //Document openedDoc = null; //UIApplication uiapp = DocumentManager.Instance.CurrentUIApplication; //Autodesk.Revit.ApplicationServices.Application app = uiapp.Application; //UIDocument uidoc = DocumentManager.Instance.CurrentUIApplication.ActiveUIDocument; //ModelPath path = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath); //OpenOptions openOpt = new OpenOptions(); try { //openedDoc = app.OpenDocumentFile(path, openOpt); var direction = new XYZ(-1, 1, -1); var collector = new FilteredElementCollector(document); var viewFamilyType = collector.OfClass(typeof(ViewFamilyType)).Cast <ViewFamilyType>() .FirstOrDefault(x => x.ViewFamily == ViewFamily.ThreeDimensional); using (Transaction ttNew = new Transaction(document, "abc")) { ttNew.Start(); View3D navisView = View3D.CreateIsometric(document, viewFamilyType.Id); navisView.SetOrientation(new ViewOrientation3D(direction, new XYZ(0, 1, 1), new XYZ(0, 1, -1))); navisView.ViewName = "Navisworks"; ttNew.Commit(); message = "Created"; //document.Close(true); } } catch (Exception ex) { message = ex.Message; } return(new Dictionary <string, object> { { "document", document }, { "message", message } }); }
private bool SetOrthogonalView(View3D bcfView, OrthogonalCamera camera) { var result = false; try { var zoom = camera.ViewToWorldScale.ToFeet(); var direction = RevitUtils.GetRevitXYZ(camera.CameraDirection); var upVector = RevitUtils.GetRevitXYZ(camera.CameraUpVector); var viewPoint = RevitUtils.GetRevitXYZ(camera.CameraViewPoint); var orientation = RevitUtils.ConvertBasePoint(ActiveDoc, viewPoint, direction, upVector, true); using (var trans = new Transaction(ActiveDoc)) { trans.Start("Set Orientation"); try { bcfView.SetOrientation(orientation); trans.Commit(); } catch (Exception ex) { trans.RollBack(); var message = ex.Message; } } var m_xyzTl = bcfView.Origin.Add(bcfView.UpDirection.Multiply(zoom)).Subtract(bcfView.RightDirection.Multiply(zoom)); var m_xyzBr = bcfView.Origin.Subtract(bcfView.UpDirection.Multiply(zoom)).Add(bcfView.RightDirection.Multiply(zoom)); BCFUIView.ZoomAndCenterRectangle(m_xyzTl, m_xyzBr); result = true; } catch (Exception ex) { var message = ex.Message; } return(result); }
private void SetCamera(Transform transform, Element element, Edge edge, View3D view3D) { if (edge.AsCurve() is Line locationCurve) { (Line perpendLine, Line orthLine) = PerpendLine(transform, locationCurve); using (var tran = new Transaction(_doc)) { tran.Start("Add line"); Creator.CreateModelCurve(_uidoc.Application, locationCurve); Creator.CreateModelCurve(_uidoc.Application, perpendLine); Creator.CreateModelCurve(_uidoc.Application, orthLine); tran.Commit(); } view3D.SetOrientation(new ViewOrientation3D(transform.Origin, Util.GetVector(perpendLine), Util.GetVector(locationCurve))); _uidoc.ShowElements(element); _uidoc.RefreshActiveView(); } }
/// <summary> /// Creates a perspective View3D. /// </summary> /// <param name="doc">The document.</param> /// <param name="eyePosition">The eye position in 3D model space for the new 3D view.</param> /// <param name="upDir">The up direction in 3D model space for the new 3D view.</param> /// <param name="forwardDir">The forward direction in 3D model space for the new 3D view.</param> /// <returns>The new View3D.</returns> private static View3D Create3DView(Document doc, XYZ eyePosition, XYZ upDir, XYZ forwardDir) { if (null == doc || null == eyePosition || null == upDir || null == forwardDir) { return(null); } var vft = new FilteredElementCollector(doc) .OfClass(typeof(ViewFamilyType)) .Cast <ViewFamilyType>() .FirstOrDefault(t => t.ViewFamily == ViewFamily.ThreeDimensional); View3D view3d = View3D.CreatePerspective(doc, vft.Id); if (null == view3d) { return(null); } view3d.SetOrientation(new ViewOrientation3D(eyePosition, upDir, forwardDir)); return(view3d); }
/// <summary> /// Sample code from Revit API help file What's New /// section on View API and View Creation. /// </summary> void ViewApiCreateViewSample() { Document doc = null; Level level = null; ElementId viewFamily3d = ElementId.InvalidElementId; IEnumerable <ViewFamilyType> viewFamilyTypes = from e in new FilteredElementCollector(doc) .OfClass(typeof(ViewFamilyType)) let type = e as ViewFamilyType where type.ViewFamily == ViewFamily.CeilingPlan select type; ViewPlan ceilingPlan = ViewPlan.Create(doc, viewFamilyTypes.First().Id, level.Id); ceilingPlan.Name = "New Ceiling Plan for " + level.Name; ceilingPlan.DetailLevel = ViewDetailLevel.Fine; // 3D views can be created with // View3D.CreateIsometric and // View3D.CreatePerspective. // The new ViewOrientation3D object is used to // get or set the orientation of 3D views. View3D view = View3D.CreateIsometric( doc, viewFamily3d); XYZ eyePosition = new XYZ(10, 10, 10); XYZ upDirection = new XYZ(-1, 0, 1); XYZ forwardDirection = new XYZ(1, 0, 1); view.SetOrientation(new ViewOrientation3D( eyePosition, upDirection, forwardDirection)); }
/// <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(); BlockingCollection <ElementId> elementsToBeIsolated = new BlockingCollection <ElementId>(); BlockingCollection <ElementId> elementsToBeHidden = new BlockingCollection <ElementId>(); BlockingCollection <ElementId> elementsToBeSelected = new BlockingCollection <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.GetInternalXYZ(v.OrthogonalCamera.CameraDirection.X, v.OrthogonalCamera.CameraDirection.Y, v.OrthogonalCamera.CameraDirection.Z); var CameraUpVector = ARUP.IssueTracker.Revit.Classes.Utils.GetInternalXYZ(v.OrthogonalCamera.CameraUpVector.X, v.OrthogonalCamera.CameraUpVector.Y, v.OrthogonalCamera.CameraUpVector.Z); var CameraViewPoint = ARUP.IssueTracker.Revit.Classes.Utils.GetInternalXYZ(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; } } string userDefault3dViewName = "{3D - " + app.Application.Username + "}"; string default3dViewName = "{3D}"; string userBCForthoViewName = string.Format("BCFortho_{0}", app.Application.Username); if (orthoView == null) { IEnumerable <View3D> viewcollector3D = get3DViews(doc); //find a orthographic 3D view if (viewcollector3D.Any()) { if (viewcollector3D.Where(o => o.Name == userDefault3dViewName).Any()) // 1) try to find user specific 3D view in workshared environment { orthoView = viewcollector3D.Where(o => o.Name == userDefault3dViewName).First(); } else if (viewcollector3D.Where(o => o.Name == default3dViewName).Any()) // 2) try to find the default 3D view if 1) not found { orthoView = viewcollector3D.Where(o => o.Name == default3dViewName).First(); } else if (viewcollector3D.Where(o => o.Name == userBCForthoViewName).Any()) // 3) try to find BCFortho 3D view generated by AIT previously if 2) is not found { orthoView = viewcollector3D.Where(o => o.Name == userBCForthoViewName).First(); } } } using (Transaction trans = new Transaction(uidoc.Document)) { if (trans.Start("Open orthogonal view") == TransactionStatus.Started) { //create a new user-specific 3d ortho view if (orthoView == null) { orthoView = View3D.CreateIsometric(doc, getFamilyViews(doc).First().Id); orthoView.Name = userBCForthoViewName; } 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.GetInternalXYZ(v.PerspectiveCamera.CameraDirection.X, v.PerspectiveCamera.CameraDirection.Y, v.PerspectiveCamera.CameraDirection.Z); var CameraUpVector = ARUP.IssueTracker.Revit.Classes.Utils.GetInternalXYZ(v.PerspectiveCamera.CameraUpVector.X, v.PerspectiveCamera.CameraUpVector.Y, v.PerspectiveCamera.CameraUpVector.Z); XYZ oldO = ARUP.IssueTracker.Revit.Classes.Utils.GetInternalXYZ(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); string userPersp3dViewName = string.Format("BCFperps_{0}", app.Application.Username); // find a perspective view if (viewcollector3D.Any() && viewcollector3D.Where(o => o.Name == userPersp3dViewName).Any()) { perspView = viewcollector3D.Where(o => o.Name == userPersp3dViewName).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 = userPersp3dViewName; } 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) { // resume section box state using (Transaction trans = new Transaction(uidoc.Document)) { if (trans.Start("Resume Section Box") == TransactionStatus.Started) { view3D.IsSectionBoxActive = false; } trans.Commit(); } 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(); } } } } } // resume visibility and selection using (Transaction trans = new Transaction(uidoc.Document)) { if (trans.Start("Resume Visibility/Selection") == TransactionStatus.Started) { #if REVIT2014 uidoc.ActiveView.DisableTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate); uidoc.Selection.Elements.Clear(); #elif REVIT2015 uidoc.ActiveView.DisableTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate); uidoc.Selection.SetElementIds(new List <ElementId>()); #else uidoc.ActiveView.TemporaryViewModes.DeactivateAllModes(); uidoc.Selection.SetElementIds(new List <ElementId>()); #endif } 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; // } //} revitWindow.initializeProgressWin(v.Components.Count); FilteredElementCollector collector = new FilteredElementCollector(doc, doc.ActiveView.Id); var allElementIds = collector.ToElementIds(); Dictionary <Guid, ElementId> exportIdElementIdDic = new Dictionary <Guid, ElementId>(); Dictionary <int, ElementId> uniqueIdElementIdDic = new Dictionary <int, ElementId>(); foreach (ElementId eId in allElementIds) { Guid guid = ExportUtils.GetExportId(doc, eId); int elementIdInteger = Convert.ToInt32(doc.GetElement(eId).UniqueId.Substring(37), 16); if (!exportIdElementIdDic.ContainsKey(guid)) { exportIdElementIdDic.Add(guid, eId); } if (!uniqueIdElementIdDic.ContainsKey(elementIdInteger)) { uniqueIdElementIdDic.Add(elementIdInteger, eId); } } //System.Threading.Tasks.Parallel.For(0, v.Components.Count, i => { for (int i = 0; i < v.Components.Count; i++) { double percentage = ((double)i / (double)v.Components.Count) * 100; revitWindow.updateProgressWin((int)percentage, i, v.Components.Count); ARUP.IssueTracker.Classes.BCF2.Component e = v.Components[i]; ElementId currentElementId = null; // find by ElementId first if OriginatingSystem is Revit if (e.OriginatingSystem != null) { if (e.OriginatingSystem.Contains("Revit") && !string.IsNullOrEmpty(e.AuthoringToolId)) { int elementId = -1; int.TryParse(e.AuthoringToolId, out elementId); if (elementId != -1) { Element ele = doc.GetElement(new ElementId(elementId)); if (ele != null) { currentElementId = ele.Id; } } } } // find by IfcGuid if ElementId not found if (currentElementId == null) { var bcfguid = IfcGuid.FromIfcGUID(e.IfcGuid); if (exportIdElementIdDic.ContainsKey(bcfguid)) { currentElementId = exportIdElementIdDic[bcfguid]; } } // find by UniqueId if IfcGuid not found if (currentElementId == null) { int authoringToolId = -1; int.TryParse(e.AuthoringToolId, out authoringToolId); if (uniqueIdElementIdDic.ContainsKey(authoringToolId)) { currentElementId = uniqueIdElementIdDic[authoringToolId]; } } if (currentElementId != null) { // handle visibility if (e.Visible) { elementsToBeIsolated.Add(currentElementId); } else { elementsToBeHidden.Add(currentElementId); } // handle selection if (e.Selected) { elementsToBeSelected.Add(currentElementId); } } } ; if (elementsToBeHidden.Count > 0) { using (Transaction trans = new Transaction(uidoc.Document)) { if (trans.Start("Hide Elements") == TransactionStatus.Started) { uidoc.ActiveView.HideElementsTemporary(elementsToBeHidden.ToList()); } 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.ToList()); } trans.Commit(); } } if (elementsToBeSelected.Count > 0) { using (Transaction trans = new Transaction(uidoc.Document)) { if (trans.Start("Select Elements") == TransactionStatus.Started) { #if REVIT2014 SelElementSet selectedElements = SelElementSet.Create(); elementsToBeSelected.ToList().ForEach(id => { selectedElements.Add(doc.GetElement(id)); }); uidoc.Selection.Elements = selectedElements; #else uidoc.Selection.SetElementIds(elementsToBeSelected.ToList()); #endif } trans.Commit(); } } revitWindow.disposeProgressWin(); } uidoc.RefreshActiveView(); } catch (Exception ex) { TaskDialog.Show("Error!", "exception: " + ex); } }
/// <summary> /// External Event Implementation /// </summary> /// <param name="app"></param> public void Execute(UIApplication app) { try { UIDocument uidoc = app.ActiveUIDocument; Document doc = uidoc.Document; SelElementSet m_elementsToHide = SelElementSet.Create(); List <ElementId> elementids = 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 = Utils.GetXYZ(v.OrthogonalCamera.CameraDirection.X, v.OrthogonalCamera.CameraDirection.Y, v.OrthogonalCamera.CameraDirection.Z); var CameraUpVector = Utils.GetXYZ(v.OrthogonalCamera.CameraUpVector.X, v.OrthogonalCamera.CameraUpVector.Y, v.OrthogonalCamera.CameraUpVector.Z); var CameraViewPoint = Utils.GetXYZ(v.OrthogonalCamera.CameraViewPoint.X, v.OrthogonalCamera.CameraViewPoint.Y, v.OrthogonalCamera.CameraViewPoint.Z); var orient3d = 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.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 = Utils.GetXYZ(v.PerspectiveCamera.CameraDirection.X, v.PerspectiveCamera.CameraDirection.Y, v.PerspectiveCamera.CameraDirection.Z); var CameraUpVector = Utils.GetXYZ(v.PerspectiveCamera.CameraUpVector.X, v.PerspectiveCamera.CameraUpVector.Y, v.PerspectiveCamera.CameraUpVector.Z); XYZ oldO = Utils.GetXYZ(v.PerspectiveCamera.CameraViewPoint.X, v.PerspectiveCamera.CameraViewPoint.Y, v.PerspectiveCamera.CameraViewPoint.Z); var CameraViewPoint = (oldO.Subtract(CameraDirection.Divide(factor))); var orient3d = 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.SetOrientation(orient3d); // 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.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; } //select/hide elements if (v.Components != null && v.Components.Any()) { 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); var ids = collection.Where(o => bcfguid == ExportUtils.GetExportId(doc, o)); if (ids.Any()) { m_elementsToHide.Add(doc.GetElement(ids.First())); elementids.Add(ids.First()); } } if (null != m_elementsToHide && !m_elementsToHide.IsEmpty) { //do transaction only if there is something to hide/select using (Transaction trans = new Transaction(uidoc.Document)) { if (trans.Start("Apply visibility/selection") == TransactionStatus.Started) { if (MySettings.Get("selattachedelems") == "0") { uidoc.ActiveView.IsolateElementsTemporary(elementids); } else { uidoc.Selection.Elements = m_elementsToHide; } } trans.Commit(); } } } uidoc.RefreshActiveView(); } catch (Exception ex) { TaskDialog.Show("Error!", "exception: " + ex); } }
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)); }
private bool DuplicateCameraView(ModelInfo sModel, ModelInfo rModel, CameraViewInfo cameraInfo, ViewFamilyType vFamilyType, out CameraViewInfo createdViewInfo) { bool duplicated = false; createdViewInfo = null; try { Document sourceDoc = sModel.ModelDoc; Document recipientDoc = rModel.ModelDoc; using (Transaction trans = new Transaction(recipientDoc)) { trans.Start("Create Camera View"); try { View3D createdView = View3D.CreatePerspective(recipientDoc, vFamilyType.Id); if (CanHaveViewName(rModel, cameraInfo.ViewName)) { createdView.Name = cameraInfo.ViewName; } createdView.SetOrientation(cameraInfo.Orientation); createdView.CropBoxActive = cameraInfo.IsCropBoxOn; createdView.CropBox = cameraInfo.CropBox; createdView.IsSectionBoxActive = cameraInfo.IsSectionBoxOn; createdView.SetSectionBox(cameraInfo.SectionBox); createdView.DisplayStyle = cameraInfo.Display; //createdView.SetRenderingSettings(cameraInfo.Rendering); foreach (string paramName in cameraInfo.ViewParameters.Keys) { Parameter sourceParam = cameraInfo.ViewParameters[paramName]; Parameter recipientParam = createdView.LookupParameter(paramName); if (parametersToSkip.Contains(sourceParam.Id.IntegerValue)) { continue; } if (null != recipientParam && sourceParam.HasValue) { if (!recipientParam.IsReadOnly) { switch (sourceParam.StorageType) { case StorageType.Double: try { recipientParam.Set(sourceParam.AsDouble()); } catch { } break; case StorageType.ElementId: /* * try { recipientParam.Set(sourceParam.AsElementId()); } * catch { } */ break; case StorageType.Integer: try { recipientParam.Set(sourceParam.AsInteger()); } catch { } break; case StorageType.String: try { recipientParam.Set(sourceParam.AsString()); } catch { } break; } } } } if (cameraInfo.ViewTemplateId != ElementId.InvalidElementId) { ElementId templateId = GetLinkedItem(sModel, rModel, MapType.ViewTemplate, cameraInfo.ViewTemplateId); if (templateId != ElementId.InvalidElementId && createdView.IsValidViewTemplate(templateId)) { createdView.ViewTemplateId = templateId; } else { MissingItem missingItem = new MissingItem(cameraInfo.ViewName, "View Template", ""); missingItems.Add(missingItem); } } if (cameraInfo.PhaseId != ElementId.InvalidElementId) { ElementId phaseId = GetLinkedItem(sModel, rModel, MapType.Phase, cameraInfo.PhaseId); if (phaseId != ElementId.InvalidElementId) { Parameter param = createdView.get_Parameter(BuiltInParameter.VIEW_PHASE); if (null != param) { param.Set(phaseId); } } else { MissingItem missingItem = new MissingItem(cameraInfo.ViewName, "Phase", ""); missingItems.Add(missingItem); } } if (viewConfig.ApplyWorksetVisibility && cameraInfo.WorksetVisibilities.Count > 0) { bool worksetFound = true; foreach (WorksetId wsId in cameraInfo.WorksetVisibilities.Keys) { WorksetVisibility wsVisibility = cameraInfo.WorksetVisibilities[wsId]; WorksetId worksetId = GetLinkedWorkset(sModel, rModel, wsId); if (worksetId != WorksetId.InvalidWorksetId) { createdView.SetWorksetVisibility(worksetId, wsVisibility); } else { worksetFound = false; } } if (!worksetFound) { MissingItem missingItem = new MissingItem(cameraInfo.ViewName, "Workset", ""); missingItems.Add(missingItem); } } createdViewInfo = new CameraViewInfo(createdView); createdViewInfo.LinkedViewId = cameraInfo.ViewId; createdViewInfo.Linked = true; duplicated = true; trans.Commit(); } catch (Exception ex) { trans.RollBack(); string message = ex.Message; } } } catch (Exception ex) { MessageBox.Show("Failed to duplicate camera views.\n" + ex.Message, "Duplicate Camera Views", MessageBoxButton.OK, MessageBoxImage.Warning); } return(duplicated); }
public ImageExporter(Document doc) { ViewFamilyType viewFamilyType = new FilteredElementCollector(doc) .OfClass(typeof(ViewFamilyType)) .Cast <ViewFamilyType>() .FirstOrDefault(x => x.ViewFamily == ViewFamily.ThreeDimensional); Debug.Assert(null != viewFamilyType); View3D v = View3D.CreateIsometric( doc, viewFamilyType.Id); v.Name = "Isometric"; Debug.Assert(null != v); int nViews = _view_data_to_export.Length; _views_to_export = new List <View>(nViews) { v }; for (int i = 1; i < nViews; ++i) { v = View3D.CreateIsometric( doc, viewFamilyType.Id); object[] d = _view_data_to_export[i]; v.Name = d[0] as string; v.SetOrientation(GetOrientationFor( (int)(d[2]), (int)(d[3]))); v.SaveOrientation(); _views_to_export.Add(v); } foreach (View v2 in _views_to_export) { Parameter graphicDisplayOptions = v2.get_Parameter( BuiltInParameter.MODEL_GRAPHICS_STYLE); // Settings for best quality graphicDisplayOptions.Set(6); // Get categories to hide Categories cats = doc.Settings.Categories; foreach (BuiltInCategory bic in _categories_to_hide) { Category cat = cats.get_Item(bic); // OST_Cameras returns a null Category // object in my model if (null == cat) { Debug.Print("{0} returns null category.", bic); } else { v2.SetCategoryHidden(cat.Id, true); } // BuiltInCategory.OST_Cameras throws exception: // Autodesk.Revit.Exceptions.ArgumentException // Category cannot be hidden. // Parameter name: categoryId //ElementId id = new ElementId( bic ); //view3d.SetCategoryHidden( id, true ); } } }
/// <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 computedGeo = instance.GetOriginalGeometry(m_options); GeometryElement transformGeo = computedGeo.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 computedGeo.Objects) IEnumerator <GeometryObject> Objects1 = computedGeo.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()); }
/// <summary> /// External Event Implementation /// </summary> /// <param name="app"></param> public void Execute(UIApplication app) { try { UIDocument uidoc = app.ActiveUIDocument; Document doc = uidoc.Document; SelElementSet m_elementsToHide = 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) { SelElementSet selectedElements = SelElementSet.Create(); elementsToBeSelected.ForEach(id => { selectedElements.Add(doc.GetElement(id)); }); uidoc.Selection.Elements = selectedElements; } trans.Commit(); } } } uidoc.RefreshActiveView(); } catch (Exception ex) { TaskDialog.Show("Error!", "exception: " + ex); } }
/// <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); }
/// <summary> /// External Event Implementation /// </summary> /// <param name="app"></param> public void Execute(UIApplication app) { try { UIDocument uidoc = app.ActiveUIDocument; Document doc = uidoc.Document; var uniqueView = UserSettings.GetBool("alwaysNewView"); // IS ORTHOGONAL if (v.OrthogonalCamera != null) { if (v.OrthogonalCamera.CameraViewPoint == null || v.OrthogonalCamera.CameraUpVector == null || v.OrthogonalCamera.CameraDirection == null) { return; } //type = "OrthogonalCamera"; var zoom = v.OrthogonalCamera.ViewToWorldScale.ToFeet(); var cameraDirection = RevitUtils.GetRevitXYZ(v.OrthogonalCamera.CameraDirection); var cameraUpVector = RevitUtils.GetRevitXYZ(v.OrthogonalCamera.CameraUpVector); var cameraViewPoint = RevitUtils.GetRevitXYZ(v.OrthogonalCamera.CameraViewPoint); var orient3D = RevitUtils.ConvertBasePoint(doc, cameraViewPoint, cameraDirection, cameraUpVector, true); View3D orthoView = null; //if active view is 3d ortho use it if (doc.ActiveView.ViewType == ViewType.ThreeD) { var activeView3D = doc.ActiveView as View3D; if (!activeView3D.IsPerspective) { orthoView = activeView3D; } } if (orthoView == null) { //try to use an existing 3D view IEnumerable <View3D> viewcollector3D = get3DViews(doc); if (viewcollector3D.Any(o => o.Name == "{3D}" || o.Name == "BCFortho")) { orthoView = viewcollector3D.First(o => o.Name == "{3D}" || o.Name == "BCFortho"); } } using (var trans = new Transaction(uidoc.Document)) { if (trans.Start("Open orthogonal view") == TransactionStatus.Started) { //create a new 3d ortho view if (orthoView == null || uniqueView) { orthoView = View3D.CreateIsometric(doc, getFamilyViews(doc).First().Id); orthoView.Name = (uniqueView) ? "BCFortho" + DateTime.Now.ToString("yyyyMMddTHHmmss") : "BCFortho"; } else { //reusing an existing view, I net to reset the visibility //placed this here because if set afterwards it doesn't work orthoView.DisableTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate); } orthoView.SetOrientation(orient3D); trans.Commit(); } } uidoc.ActiveView = orthoView; //adjust view rectangle // **** CUSTOM VALUE FOR TEKLA **** // // double x = zoom / 2.5; // **** CUSTOM VALUE FOR TEKLA **** // double x = zoom; //if(MySettings.Get("optTekla")=="1") // x = zoom / 2.5; //set UI view position and zoom 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); } //perspective else if (v.PerspectiveCamera != null) { if (v.PerspectiveCamera.CameraViewPoint == null || v.PerspectiveCamera.CameraUpVector == null || v.PerspectiveCamera.CameraDirection == null) { return; } //not used since the fov cannot be changed in Revit var zoom = v.PerspectiveCamera.FieldOfView; //FOV - not used //double z1 = 18 / Math.Tan(zoom / 2 * Math.PI / 180); //double z = 18 / Math.Tan(25 / 2 * Math.PI / 180); //double factor = z1 - z; var cameraDirection = RevitUtils.GetRevitXYZ(v.PerspectiveCamera.CameraDirection); var cameraUpVector = RevitUtils.GetRevitXYZ(v.PerspectiveCamera.CameraUpVector); var cameraViewPoint = RevitUtils.GetRevitXYZ(v.PerspectiveCamera.CameraViewPoint); var orient3D = RevitUtils.ConvertBasePoint(doc, cameraViewPoint, cameraDirection, cameraUpVector, true); View3D perspView = null; //try to use an existing 3D view IEnumerable <View3D> viewcollector3D = get3DViews(doc); if (viewcollector3D.Any(o => o.Name == "BCFpersp")) { perspView = viewcollector3D.First(o => o.Name == "BCFpersp"); } using (var trans = new Transaction(uidoc.Document)) { if (trans.Start("Open perspective view") == TransactionStatus.Started) { if (null == perspView || uniqueView) { perspView = View3D.CreatePerspective(doc, getFamilyViews(doc).First().Id); perspView.Name = (uniqueView) ? "BCFpersp" + DateTime.Now.ToString("yyyyMMddTHHmmss") : "BCFpersp"; } else { //reusing an existing view, I net to reset the visibility //placed this here because if set afterwards it doesn't work perspView.DisableTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate); } perspView.SetOrientation(orient3D); // turn off the far clip plane 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; } //sheet else if (v.SheetCamera != null) { IEnumerable <View> viewcollectorSheet = getSheets(doc, v.SheetCamera.SheetID); if (!viewcollectorSheet.Any()) { MessageBox.Show("View " + v.SheetCamera.SheetName + " with Id=" + v.SheetCamera.SheetID + " not found."); return; } uidoc.ActiveView = viewcollectorSheet.First(); uidoc.RefreshActiveView(); 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); } //no view included else { return; } if (v.Components == null) { return; } var elementsToSelect = new List <ElementId>(); var elementsToHide = new List <ElementId>(); var elementsToShow = new List <ElementId>(); var visibleElems = new FilteredElementCollector(doc, doc.ActiveView.Id) .WhereElementIsNotElementType() .WhereElementIsViewIndependent() .ToElementIds() .Where(e => doc.GetElement(e).CanBeHidden(doc.ActiveView)); //might affect performance, but it's necessary bool canSetVisibility = (v.Components.Visibility != null && v.Components.Visibility.DefaultVisibilitySpecified && v.Components.Visibility.Exceptions.Any()) ; bool canSetSelection = (v.Components.Selection != null && v.Components.Selection.Any()); //loop elements foreach (var e in visibleElems) { var guid = IfcGuid.ToIfcGuid(ExportUtils.GetExportId(doc, e)); if (canSetVisibility) { if (v.Components.Visibility.DefaultVisibility) { if (v.Components.Visibility.Exceptions.Any(x => x.IfcGuid == guid)) { elementsToHide.Add(e); } } else { if (v.Components.Visibility.Exceptions.Any(x => x.IfcGuid == guid)) { elementsToShow.Add(e); } } } if (canSetSelection) { if (v.Components.Selection.Any(x => x.IfcGuid == guid)) { elementsToSelect.Add(e); } } } using (var trans = new Transaction(uidoc.Document)) { if (trans.Start("Apply BCF visibility and selection") == TransactionStatus.Started) { if (elementsToHide.Any()) { doc.ActiveView.HideElementsTemporary(elementsToHide); } //there are no items to hide, therefore hide everything and just show the visible ones else if (elementsToShow.Any()) { doc.ActiveView.IsolateElementsTemporary(elementsToShow); } if (elementsToSelect.Any()) { uidoc.Selection.SetElementIds(elementsToSelect); } } trans.Commit(); } uidoc.RefreshActiveView(); } catch (Exception ex) { TaskDialog.Show("Error!", "exception: " + ex); } }