public void UpdateParameter(ParameterUpdater paramUpdater) { //the below does not work because ApplicationIds are stored within a stream //try to get element using ApplicationId //this will only work if the element has been successfully been received in Revit before //var element = GetExistingElementByApplicationId(paramUpdater.revitId); Element element = null; //try to get element using ElementId int intId; if (int.TryParse(paramUpdater.revitId, out intId)) { var elemId = new ElementId(intId); element = Doc.GetElement(elemId); } //try to get element using UniqueId if (element == null) { element = Doc.GetElement(paramUpdater.revitId); } if (element == null) { ConversionErrors.Add(new System.Exception($"Could not find element to update: Element Id = {paramUpdater.revitId}")); return; } SetInstanceParameters(element, paramUpdater); }
public ApplicationPlaceholderObject RoomBoundaryLineToNative(RoomBoundaryLine speckleCurve) { var docObj = GetExistingElementByApplicationId(speckleCurve.applicationId); var baseCurve = CurveToNative(speckleCurve.baseCurve); //delete and re-create line //TODO: check if can be modified if (docObj != null) { Doc.Delete(docObj.Id); } try { var res = Doc.Create.NewRoomBoundaryLines(NewSketchPlaneFromCurve(baseCurve.get_Item(0), Doc), baseCurve, Doc.ActiveView).get_Item(0); return(new ApplicationPlaceholderObject() { applicationId = speckleCurve.applicationId, ApplicationGeneratedId = res.UniqueId, NativeObject = res }); } catch (Exception) { ConversionErrors.Add(new Exception("Room boundary line creation failed\nView is not valid for room boundary line creation.")); throw; } }
public ApplicationPlaceholderObject DirectShapeToNative(DirectShape speckleDs) { var docObj = GetExistingElementByApplicationId(speckleDs.applicationId); //just create new one if (docObj != null) { Doc.Delete(docObj.Id); } var converted = new List <GeometryObject>(); speckleDs.baseGeometries.ToList().ForEach(b => { switch (b) { case Brep brep: try { var solid = BrepToNative(brep); converted.Add(solid); } catch (Exception e) { var mesh = MeshToNative(brep.displayValue); converted.AddRange(mesh); } break; case Mesh mesh: var rMesh = MeshToNative(mesh); converted.AddRange(rMesh); break; default: ConversionErrors.Add(new Error("Incompatible geometry type", $"Type ${b.GetType()} is not supported in DirectShape conversions.")); break; } }); BuiltInCategory cat; var bic = RevitUtils.GetBuiltInCategory(speckleDs.category); BuiltInCategory.TryParse(bic, out cat); var catId = Doc.Settings.Categories.get_Item(cat).Id; var revitDs = DB.DirectShape.CreateElement(Doc, catId); revitDs.ApplicationId = speckleDs.applicationId; revitDs.ApplicationDataId = Guid.NewGuid().ToString(); revitDs.SetShape(converted); revitDs.Name = speckleDs.name; SetInstanceParameters(revitDs, speckleDs); return(new ApplicationPlaceholderObject { applicationId = speckleDs.applicationId, ApplicationGeneratedId = revitDs.UniqueId, NativeObject = revitDs }); }
public List <ApplicationPlaceholderObject> DuctToNative(BuiltElements.Duct speckleDuct) { var baseLine = LineToNative(speckleDuct.baseLine); XYZ startPoint = baseLine.GetEndPoint(0); XYZ endPoint = baseLine.GetEndPoint(1); Autodesk.Revit.DB.Level level; var speckleRevitDuct = speckleDuct as RevitDuct; level = LevelToNative(speckleRevitDuct != null ? speckleRevitDuct.level : LevelFromCurve(baseLine)); var ductType = GetElementType <DB.DuctType>(speckleDuct); var systemFamily = (speckleDuct is RevitDuct rd) ? rd.systemName : ""; List <ElementType> types = new FilteredElementCollector(Doc).WhereElementIsElementType() .OfClass(typeof(MechanicalSystemType)).ToElements().Cast <ElementType>().ToList(); var system = types.FirstOrDefault(x => x.Name == systemFamily); if (system == null) { system = types.FirstOrDefault(); ConversionErrors.Add(new Exception($"Duct type {systemFamily} not found; replaced with {system.Name}")); } var docObj = GetExistingElementByApplicationId((( Base )speckleDuct).applicationId); // deleting instead of updating for now! if (docObj != null) { Doc.Delete(docObj.Id); } DB.Duct duct = DB.Duct.Create(Doc, system.Id, ductType.Id, level.Id, startPoint, endPoint); if (speckleRevitDuct != null) { TrySetParam(duct, BuiltInParameter.RBS_CURVE_HEIGHT_PARAM, speckleRevitDuct.height, speckleRevitDuct.units); TrySetParam(duct, BuiltInParameter.RBS_CURVE_WIDTH_PARAM, speckleRevitDuct.width, speckleRevitDuct.units); TrySetParam(duct, BuiltInParameter.RBS_CURVE_DIAMETER_PARAM, speckleRevitDuct.diameter, speckleRevitDuct.units); TrySetParam(duct, BuiltInParameter.CURVE_ELEM_LENGTH, speckleRevitDuct.length, speckleRevitDuct.units); TrySetParam(duct, BuiltInParameter.RBS_VELOCITY, speckleRevitDuct.velocity, speckleRevitDuct.units); SetInstanceParameters(duct, speckleRevitDuct); } var placeholders = new List <ApplicationPlaceholderObject> { new ApplicationPlaceholderObject { applicationId = speckleRevitDuct.applicationId, ApplicationGeneratedId = duct.UniqueId, NativeObject = duct } }; return(placeholders); }
public List <ApplicationPlaceholderObject> PipeToNative(BuiltElements.Pipe specklePipe) { // geometry var baseLine = LineToNative(specklePipe.baseLine); var speckleRevitPipe = specklePipe as RevitPipe; var level = LevelToNative(speckleRevitPipe != null ? speckleRevitPipe.level : LevelFromCurve(baseLine)); // get MEP pipe system by name or by type var pipeType = GetElementType <DB.Plumbing.PipeType>(specklePipe); var types = new FilteredElementCollector(Doc).WhereElementIsElementType() .OfClass(typeof(DB.Plumbing.PipingSystemType)).ToElements().Cast <ElementType>().ToList(); var systemFamily = speckleRevitPipe?.systemType ?? ""; var system = types.FirstOrDefault(x => x.Name == speckleRevitPipe?.systemName) ?? types.FirstOrDefault(x => x.Name == systemFamily); if (system == null) { system = types.FirstOrDefault(); ConversionErrors.Add(new Exception($"Pipe type {systemFamily} not found; replaced with {system.Name}")); } // create or update the pipe DB.Plumbing.Pipe pipe; var docObj = GetExistingElementByApplicationId(specklePipe.applicationId); if (docObj == null) { pipe = DB.Plumbing.Pipe.Create(Doc, system.Id, pipeType.Id, level.Id, baseLine.GetEndPoint(0), baseLine.GetEndPoint(1)); } else { pipe = (DB.Plumbing.Pipe)docObj; pipe.SetSystemType(system.Id); (( LocationCurve )pipe.Location).Curve = baseLine; } if (speckleRevitPipe != null) { TrySetParam(pipe, BuiltInParameter.RBS_START_LEVEL_PARAM, level); TrySetParam(pipe, BuiltInParameter.RBS_PIPE_DIAMETER_PARAM, speckleRevitPipe.diameter, speckleRevitPipe.units); SetInstanceParameters(pipe, speckleRevitPipe); } var placeholders = new List <ApplicationPlaceholderObject> { new ApplicationPlaceholderObject { applicationId = specklePipe.applicationId, ApplicationGeneratedId = pipe.UniqueId, NativeObject = pipe } }; return(placeholders); }
public ApplicationPlaceholderObject FreeformElementToNative( Objects.BuiltElements.Revit.FreeformElement freeformElement) { // 1. Convert the freeformElement geometry to native var solids = new List <DB.Solid>(); switch (freeformElement.baseGeometry) { case Brep brep: try { var solid = BrepToNative(freeformElement.baseGeometry as Brep); solids.Add(solid); } catch (Exception e) { ConversionErrors.Add(new SpeckleException($"Could not convert BREP {freeformElement.id} to native, falling back to mesh representation.", e)); var brepMeshSolids = MeshToNative(brep.displayMesh, DB.TessellatedShapeBuilderTarget.Solid, DB.TessellatedShapeBuilderFallback.Abort) .Select(m => m as DB.Solid); solids.AddRange(brepMeshSolids); } break; case Mesh mesh: var meshSolids = MeshToNative(mesh, DB.TessellatedShapeBuilderTarget.Solid, DB.TessellatedShapeBuilderFallback.Abort) .Select(m => m as DB.Solid); solids.AddRange(meshSolids); break; } var tempPath = CreateFreeformElementFamily(solids, freeformElement.id); Doc.LoadFamily(tempPath, new FamilyLoadOption(), out var fam); var symbol = Doc.GetElement(fam.GetFamilySymbolIds().First()) as DB.FamilySymbol; symbol.Activate(); try { File.Delete(tempPath); } catch { } var freeform = Doc.Create.NewFamilyInstance(DB.XYZ.Zero, symbol, DB.Structure.StructuralType.NonStructural); SetInstanceParameters(freeform, freeformElement); return(new ApplicationPlaceholderObject { applicationId = freeformElement.id, ApplicationGeneratedId = freeform.UniqueId, NativeObject = freeform }); }
/// <summary> /// Tries to find a level by ELEVATION only, otherwise it creates it. /// Unless it was created with schema builder and has `referenceOnly=true`, in which case it gets it by name only /// Reason for this approach, take the example below: /// source file has L0 @0m and L1 @4m /// dest file has L1 @0m and L2 @4m /// attempting to move or rename levels would just be a mess, hence, we don't do that! /// </summary> /// <param name="speckleLevel"></param> /// <returns></returns> public Level LevelToNative(BuiltElements.Level speckleLevel) { if (speckleLevel == null) { return(null); } var docLevels = new FilteredElementCollector(Doc).OfClass(typeof(DB.Level)).ToElements().Cast <DB.Level>(); // it's a level created with schema builder for reference only // we only try to match it by name var rl = speckleLevel as RevitLevel; if (rl != null && rl.referenceOnly) { var existingLevel = docLevels.FirstOrDefault(docLevel => docLevel.Name == speckleLevel.name); if (existingLevel != null) { return(existingLevel); } else { ConversionErrors.Add(new Error { message = $"Could not find level '{speckleLevel.name}' in this document." }); return(null); } } var speckleLevelElevation = ScaleToNative((double)speckleLevel.elevation, speckleLevel.units); var existingLevelByElevation = docLevels.FirstOrDefault(l => Math.Abs(l.Elevation - (double)speckleLevelElevation) < 0.0164042); if (existingLevelByElevation != null) { return(existingLevelByElevation); } // If we don't have an existing level, create it. var level = Level.Create(Doc, (double)speckleLevelElevation); if (!docLevels.Any(x => x.Name == speckleLevel.name)) { level.Name = speckleLevel.name; } if (rl != null && rl.createView) { CreateViewPlan(speckleLevel.name, level.Id); } return(level); }
public void ToDateRange_InvalidInput_ValidError(string[] args, ConversionErrors error, string culture = "pl-PL") { var expeted = error.Humanize(); var oldCulture = CultureInfo.CurrentCulture; CultureInfo.CurrentCulture = new CultureInfo(culture); var conversionResult = InputHelper.ToDateRange(args); Assert.False(conversionResult.Success); Assert.Equal(expeted, conversionResult.Error); CultureInfo.CurrentCulture = oldCulture; }
public List <ApplicationPlaceholderObject> SetHostedElements(Base @base, HostObject host) { var placeholders = new List <ApplicationPlaceholderObject>(); if (@base["elements"] != null && @base["elements"] is List <Base> elements) { CurrentHostElement = host; foreach (var obj in elements) { if (obj == null) { continue; } if (!CanConvertToNative(obj)) { ConversionErrors.Add(new Error { message = $"Skipping {obj.speckle_type}, not supported" }); continue; } try { var res = ConvertToNative(obj); if (res is ApplicationPlaceholderObject apl) { placeholders.Add(apl); } else if (res is List <ApplicationPlaceholderObject> apls) { placeholders.AddRange(apls); } } catch (Exception e) { ConversionErrors.Add(new Error { message = $"Failed to create hosted element {obj.speckle_type} in host ({host.Id}): \n{e.Message}" }); } } CurrentHostElement = null; // unset the current host element. } return(placeholders); }
private void SetAdaptivePoints(DB.FamilyInstance revitAc, List <Point> points) { var pointIds = AdaptiveComponentInstanceUtils.GetInstancePlacementPointElementRefIds(revitAc).ToList(); if (pointIds.Count != points.Count) { ConversionErrors.Add(new Exception("Adaptive family error\nWrong number of points supplied to adaptive family")); return; } //set adaptive points for (int i = 0; i < pointIds.Count; i++) { var point = Doc.GetElement(pointIds[i]) as ReferencePoint; point.Position = PointToNative(points[i]); } }
// This is to support raw geometry being sent to Revit (eg from rhino, gh, autocad...) public ApplicationPlaceholderObject DirectShapeToNative(Brep brep, BuiltInCategory cat = BuiltInCategory.OST_GenericModel) { // if it comes from GH it doesn't have an applicationId, the use the hash id if (brep.applicationId == null) { brep.applicationId = brep.id; } var docObj = GetExistingElementByApplicationId(brep.applicationId); //just create new one if (docObj != null) { Doc.Delete(docObj.Id); } var catId = Doc.Settings.Categories.get_Item(cat).Id; var revitDs = DB.DirectShape.CreateElement(Doc, catId); revitDs.ApplicationId = brep.applicationId; revitDs.ApplicationDataId = Guid.NewGuid().ToString(); revitDs.Name = "Brep " + brep.applicationId; try { var solid = BrepToNative(brep); if (solid == null) { throw new SpeckleException("Could not convert brep to native"); } revitDs.SetShape(new List <GeometryObject> { solid }); } catch (Exception e) { ConversionErrors.Add(new Exception(e.Message)); var mesh = MeshToNative(brep.displayMesh); revitDs.SetShape(mesh); } return(new ApplicationPlaceholderObject { applicationId = brep.applicationId, ApplicationGeneratedId = revitDs.UniqueId, NativeObject = revitDs }); }
/// <summary> /// Saves the specified path. /// </summary> /// <param name="path">The path.</param> /// <param name="mode">The mode.</param> public void Save(String path, getWritableFileMode mode = getWritableFileMode.overwrite) { if (!path.EndsWith(".dgml")) { path = path + ".dgml"; } FileInfo fi = path.getWritableFile(mode); objectSerialization.saveObjectToXML(this, fi.FullName); if (ConversionErrors.Any()) { String errFileName = Path.GetFileNameWithoutExtension(path) + "_conversionErrors.txt"; folderNode fl = fi.Directory; String errFilePath = fl.pathFor(errFileName, getWritableFileMode.overwrite); File.WriteAllLines(errFilePath, ConversionErrors); } }
public List <ApplicationPlaceholderObject> DetailCurveToNative(DetailCurve speckleCurve) { var docObj = GetExistingElementByApplicationId(speckleCurve.applicationId); //delete and re-create line //TODO: check if can be modified if (docObj != null) { Doc.Delete(docObj.Id); } var placeholders = new List <ApplicationPlaceholderObject>(); var crvEnum = CurveToNative(speckleCurve.baseCurve).GetEnumerator(); while (crvEnum.MoveNext() && crvEnum.Current != null) { var baseCurve = crvEnum.Current as DB.Curve; DB.DetailCurve revitCurve = null; try { revitCurve = Doc.Create.NewDetailCurve(Doc.ActiveView, baseCurve); } catch (Exception) { ConversionErrors.Add(new Exception($"Detail curve creation failed\nView is not valid for detail curve creation.")); throw; } var lineStyles = revitCurve.GetLineStyleIds(); var lineStyleId = lineStyles.FirstOrDefault(x => Doc.GetElement(x).Name == speckleCurve.lineStyle); if (lineStyleId != null) { revitCurve.LineStyle = Doc.GetElement(lineStyleId); } placeholders.Add(new ApplicationPlaceholderObject() { applicationId = speckleCurve.applicationId, ApplicationGeneratedId = revitCurve.UniqueId, NativeObject = revitCurve }); } return(placeholders); }
//NOTE: FaceWalls cannot be updated, as well we can't seem to get their base face easily so they are ToNatvie only public List <ApplicationPlaceholderObject> FaceWallToNative(RevitFaceWall speckleWall) { if (speckleWall.face == null) { throw new Exception("Only surface based FaceWalls are currently supported."); } var wallType = GetElementType <WallType>(speckleWall); //TODO: Convert speckle surface to face Face f = null; var revitWall = DB.FaceWall.Create(Doc, wallType.Id, GetWallLocationLine(speckleWall.locationLine), f.Reference); if (revitWall == null) { ConversionErrors.Add(new Error { message = $"Failed to create wall ${speckleWall.applicationId}." }); return(null); } SetInstanceParameters(revitWall, speckleWall); var placeholders = new List <ApplicationPlaceholderObject>() { new ApplicationPlaceholderObject { applicationId = speckleWall.applicationId, ApplicationGeneratedId = revitWall.UniqueId, NativeObject = revitWall } }; var hostedElements = SetHostedElements(speckleWall, revitWall); placeholders.AddRange(hostedElements); return(placeholders); }
public RevitWall WallToSpeckle(DB.Wall revitWall) { var baseGeometry = LocationToSpeckle(revitWall); if (baseGeometry is Geometry.Point) { ConversionErrors.Add(new Error { message = "Failed to convert wall by point. Currently not supported." }); return(null); } RevitWall speckleWall = new RevitWall(); speckleWall.family = revitWall.WallType.FamilyName.ToString(); speckleWall.type = revitWall.WallType.Name; speckleWall.baseLine = (ICurve)baseGeometry; speckleWall.level = ConvertAndCacheLevel(revitWall, BuiltInParameter.WALL_BASE_CONSTRAINT); speckleWall.topLevel = ConvertAndCacheLevel(revitWall, BuiltInParameter.WALL_HEIGHT_TYPE); speckleWall.height = GetParamValue <double>(revitWall, BuiltInParameter.WALL_USER_HEIGHT_PARAM); speckleWall.baseOffset = GetParamValue <double>(revitWall, BuiltInParameter.WALL_BASE_OFFSET); speckleWall.topOffset = GetParamValue <double>(revitWall, BuiltInParameter.WALL_TOP_OFFSET); speckleWall.structural = GetParamValue <bool>(revitWall, BuiltInParameter.WALL_STRUCTURAL_SIGNIFICANT); speckleWall.flipped = revitWall.Flipped; speckleWall["@displayMesh"] = GetWallDisplayMesh(revitWall); GetAllRevitParamsAndIds(speckleWall, revitWall, new List <string> { "WALL_USER_HEIGHT_PARAM", "WALL_BASE_OFFSET", "WALL_TOP_OFFSET", "WALL_BASE_CONSTRAINT", "WALL_HEIGHT_TYPE", "WALL_STRUCTURAL_SIGNIFICANT" }); GetHostedElements(speckleWall, revitWall); return(speckleWall); }
private static void SetAdaptiveComponentPoints(FamilyInstance component, List <SpecklePoint> points) { var pointIds = new List <ElementId>(); pointIds = AdaptiveComponentInstanceUtils.GetInstancePlacementPointElementRefIds(component).ToList(); if (pointIds.Count != points.Count) { ConversionErrors.Add(new SpeckleConversionError { Message = $"Wrong number of points supplied to adapive family" }); return; } //set base points for (int i = 0; i < pointIds.Count; i++) { var point = Doc.GetElement(pointIds[i]) as ReferencePoint; point.Position = (XYZ)SpeckleCore.Converter.Deserialise(obj: points[i], excludeAssebmlies: new string[] { "SpeckleCoreGeometryDynamo" }); } }
public DirectShape BrepToDirectShape(Brep brep, BuiltInCategory cat = BuiltInCategory.OST_GenericModel) { var revitDs = DirectShape.CreateElement(Doc, new ElementId(cat)); try { var solid = BrepToNative(brep); if (solid == null) { throw new Exception("Could not convert Brep to Solid"); } revitDs.SetShape(new List <GeometryObject> { solid }); } catch (Exception e) { var mesh = MeshToNative(brep.displayValue); revitDs.SetShape(mesh); ConversionErrors.Add(new Error(e.Message, e.InnerException?.Message ?? "No details available.")); } return(revitDs); }
public DirectShape BrepToDirectShape(Brep brep, BuiltInCategory cat = BuiltInCategory.OST_GenericModel) { var revitDs = DirectShape.CreateElement(Doc, new ElementId(cat)); try { var solid = BrepToNative(brep); if (solid == null) { throw new Speckle.Core.Logging.SpeckleException("Could not convert Brep to Solid"); } revitDs.SetShape(new List <GeometryObject> { solid }); } catch (Exception e) { ConversionErrors.Add(new Exception($"Failed to convert BREP with id {brep.id}, using display mesh value instead.", e)); var mesh = MeshToNative(brep.displayMesh); revitDs.SetShape(mesh); } return(revitDs); }
private Level GetLevelByName(string name) { var collector = new FilteredElementCollector(Doc).OfClass(typeof(DB.Level)).ToElements().Cast <DB.Level>(); //match by name var revitLevel = collector.FirstOrDefault(x => x.Name == name); if (revitLevel != null) { return(revitLevel); } //match by id? revitLevel = collector.FirstOrDefault(x => x.Id.ToString() == name); if (revitLevel != null) { return(revitLevel); } ConversionErrors.Add(new Error($"Could not find level `{name}`", "A default level will be used.")); return(collector.FirstOrDefault()); }
public ApplicationPlaceholderObject DetailCurveToNative(DetailCurve speckleCurve) { var docObj = GetExistingElementByApplicationId(speckleCurve.applicationId); //TODO: support polybline/polycurve lines var baseCurve = CurveToNative(speckleCurve.baseCurve).get_Item(0); //delete and re-create line //TODO: check if can be modified if (docObj != null) { Doc.Delete(docObj.Id); } DB.DetailCurve revitCurve = null; try { revitCurve = Doc.Create.NewDetailCurve(Doc.ActiveView, baseCurve); } catch (Exception) { ConversionErrors.Add(new Error("Detail curve creation failed", $"View is not valid for detail curve creation.")); throw; } var lineStyles = revitCurve.GetLineStyleIds(); var lineStyleId = lineStyles.FirstOrDefault(x => Doc.GetElement(x).Name == speckleCurve.lineStyle); if (lineStyleId != null) { revitCurve.LineStyle = Doc.GetElement(lineStyleId); } return(new ApplicationPlaceholderObject() { applicationId = speckleCurve.applicationId, ApplicationGeneratedId = revitCurve.UniqueId, NativeObject = revitCurve }); }
/// <summary> /// Receives a stream and bakes into the existing revit file. /// </summary> /// <param name="state"></param> /// <returns></returns> public override async Task <StreamState> ReceiveStream(StreamState state) { ConversionErrors.Clear(); OperationErrors.Clear(); var kit = KitManager.GetDefaultKit(); var converter = kit.LoadConverter(ConnectorRevitUtils.RevitAppName); converter.SetContextDocument(CurrentDoc.Document); var previouslyReceiveObjects = state.ReceivedObjects; var transport = new ServerTransport(state.Client.Account, state.Stream.id); string referencedObject = state.Commit.referencedObject; if (state.CancellationTokenSource.Token.IsCancellationRequested) { return(null); } //if "latest", always make sure we get the latest commit when the user clicks "receive" if (state.Commit.id == "latest") { var res = await state.Client.BranchGet(state.CancellationTokenSource.Token, state.Stream.id, state.Branch.name, 1); referencedObject = res.commits.items.FirstOrDefault().referencedObject; } var commit = state.Commit; var commitObject = await Operations.Receive( referencedObject, state.CancellationTokenSource.Token, transport, onProgressAction : dict => UpdateProgress(dict, state.Progress), onErrorAction : (s, e) => { OperationErrors.Add(e); state.Errors.Add(e); state.CancellationTokenSource.Cancel(); }, onTotalChildrenCountKnown : count => Execute.PostToUIThread(() => state.Progress.Maximum = count) ); if (OperationErrors.Count != 0) { Globals.Notify("Failed to get commit."); return(state); } if (state.CancellationTokenSource.Token.IsCancellationRequested) { return(null); } // Bake the new ones. Queue.Add(() => { using (var t = new Transaction(CurrentDoc.Document, $"Baking stream {state.Stream.name}")) { var failOpts = t.GetFailureHandlingOptions(); failOpts.SetFailuresPreprocessor(new ErrorEater(converter)); failOpts.SetClearAfterRollback(true); t.SetFailureHandlingOptions(failOpts); t.Start(); var flattenedObjects = FlattenCommitObject(commitObject, converter); // needs to be set for editing to work converter.SetPreviousContextObjects(previouslyReceiveObjects); // needs to be set for openings in floors and roofs to work converter.SetContextObjects(flattenedObjects.Select(x => new ApplicationPlaceholderObject { applicationId = x.applicationId, NativeObject = x }).ToList()); var newPlaceholderObjects = ConvertReceivedObjects(flattenedObjects, converter, state); // receive was cancelled by user if (newPlaceholderObjects == null) { converter.ConversionErrors.Add(new Exception("fatal error: receive cancelled by user")); t.RollBack(); return; } DeleteObjects(previouslyReceiveObjects, newPlaceholderObjects); state.ReceivedObjects = newPlaceholderObjects; t.Commit(); state.Errors.AddRange(converter.ConversionErrors); } }); Executor.Raise(); while (Queue.Count > 0) { //wait to let queue finish } if (converter.ConversionErrors.Any(x => x.Message.Contains("fatal error"))) { // the commit is being rolled back return(null); } try { await state.RefreshStream(); WriteStateToFile(); } catch (Exception e) { WriteStateToFile(); state.Errors.Add(e); Globals.Notify($"Receiving done, but failed to update stream from server.\n{e.Message}"); } return(state); }
public Base ConvertToSpeckle(object @object) { Base returnObject = null; switch (@object) { case DB.DetailCurve o: returnObject = DetailCurveToSpeckle(o); break; case DB.DirectShape o: returnObject = DirectShapeToSpeckle(o); break; case DB.FamilyInstance o: returnObject = FamilyInstanceToSpeckle(o); break; case DB.Floor o: returnObject = FloorToSpeckle(o); break; case DB.Level o: returnObject = LevelToSpeckle(o); break; case DB.View o: returnObject = ViewToSpeckle(o); break; case DB.ModelCurve o: if ((BuiltInCategory)o.Category.Id.IntegerValue == BuiltInCategory.OST_RoomSeparationLines) { returnObject = RoomBoundaryLineToSpeckle(o); } else { returnObject = ModelCurveToSpeckle(o); } break; case DB.Opening o: returnObject = OpeningToSpeckle(o); break; case DB.RoofBase o: returnObject = RoofToSpeckle(o); break; case DB.Area o: returnObject = AreaToSpeckle(o); break; case DB.Architecture.Room o: returnObject = RoomToSpeckle(o); break; case DB.Architecture.TopographySurface o: returnObject = TopographyToSpeckle(o); break; case DB.Wall o: returnObject = WallToSpeckle(o); break; case DB.Mechanical.Duct o: returnObject = DuctToSpeckle(o); break; case DB.Plumbing.Pipe o: returnObject = PipeToSpeckle(o); break; case DB.Electrical.Wire o: returnObject = WireToSpeckle(o); break; //these should be handled by curtain walls case DB.CurtainGridLine _: returnObject = null; break; case DB.Architecture.BuildingPad o: returnObject = BuildingPadToSpeckle(o); break; case DB.Architecture.Stairs o: returnObject = StairToSpeckle(o); break; //these are handled by Stairs case DB.Architecture.StairsRun _: returnObject = null; break; case DB.Architecture.StairsLanding _: returnObject = null; break; case DB.Architecture.Railing o: returnObject = RailingToSpeckle(o); break; case DB.Architecture.TopRail _: returnObject = null; break; case DB.Ceiling o: returnObject = CeilingToSpeckle(o); break; case DB.PointCloudInstance o: returnObject = PointcloudToSpeckle(o); break; case DB.ProjectInfo o: returnObject = ProjectInfoToSpeckle(o); break; case DB.ElementType o: returnObject = ElementTypeToSpeckle(o); break; case DB.Grid o: returnObject = GridLineToSpeckle(o); break; default: // if we don't have a direct conversion, still try to send this element as a generic RevitElement if ((@object as Element).IsElementSupported()) { returnObject = RevitElementToSpeckle(@object as Element); break; } ConversionErrors.Add(new Exception($"Skipping not supported type: {@object.GetType()}{GetElemInfo(@object)}")); returnObject = null; break; } // NOTE: Only try generic method assignment if there is no existing render material from conversions; // we might want to try later on to capture it more intelligently from inside conversion routines. if (returnObject != null && returnObject["renderMaterial"] == null) { var material = GetElementRenderMaterial(@object as DB.Element); returnObject["renderMaterial"] = material; } return(returnObject); }
public ApplicationPlaceholderObject OpeningToNative(BuiltElements.Opening speckleOpening) { var baseCurves = CurveToNative(speckleOpening.outline); var docObj = GetExistingElementByApplicationId(speckleOpening.applicationId); if (docObj != null) { Doc.Delete(docObj.Id); } DB.Opening revitOpening = null; switch (speckleOpening) { case RevitWallOpening rwo: { if (CurrentHostElement as Wall == null) { throw new Exception($"Hosted wall openings require a host wall"); } var points = (rwo.outline as Polyline).points.Select(x => PointToNative(x)).ToList(); revitOpening = Doc.Create.NewOpening(CurrentHostElement as Wall, points[0], points[2]); break; } case RevitVerticalOpening rvo: { if (CurrentHostElement == null) { throw new Exception($"Hosted vertical openings require a host family"); } revitOpening = Doc.Create.NewOpening(CurrentHostElement, baseCurves, true); break; } case RevitShaft rs: { var bottomLevel = LevelToNative(rs.bottomLevel); var topLevel = LevelToNative(rs.topLevel); revitOpening = Doc.Create.NewOpening(bottomLevel, topLevel, baseCurves); TrySetParam(revitOpening, BuiltInParameter.WALL_USER_HEIGHT_PARAM, rs.height); break; } default: ConversionErrors.Add(new Error("Cannot create Opening", "Opening type not supported")); throw new Exception("Opening type not supported"); } if (speckleOpening is RevitOpening ro) { SetInstanceParameters(revitOpening, ro); } return(new ApplicationPlaceholderObject { NativeObject = revitOpening, applicationId = speckleOpening.applicationId, ApplicationGeneratedId = revitOpening.UniqueId }); }
//TODO: delete temp family after creation //TODO: allow updates to family..? //NOTE: FaceWalls cannot be updated, as well we can't seem to get their base face easily so they are ToNatvie only public List <ApplicationPlaceholderObject> FaceWallToNative(RevitFaceWall speckleWall) { if (speckleWall.surface == null) { throw new Speckle.Core.Logging.SpeckleException("Only surface based FaceWalls are currently supported."); } // Cannot update revit wall to new mass face FaceWall revitWall = GetExistingElementByApplicationId(speckleWall.applicationId) as DB.FaceWall; if (revitWall != null) { Doc.Delete(revitWall.Id); } var famPath = Path.Combine(Doc.Application.FamilyTemplatePath, @"Conceptual Mass\Metric Mass.rft"); if (!File.Exists(famPath)) { ConversionErrors.Add(new Error { message = $"Could not find file Metric Mass.rft" }); return(null); } var tempMassFamilyPath = CreateMassFamily(famPath, speckleWall.surface, speckleWall.applicationId); Family fam; Doc.LoadFamily(tempMassFamilyPath, new FamilyLoadOption(), out fam); var symbol = Doc.GetElement(fam.GetFamilySymbolIds().First()) as FamilySymbol; symbol.Activate(); try { File.Delete(tempMassFamilyPath); } catch { } var mass = Doc.Create.NewFamilyInstance(XYZ.Zero, symbol, DB.Structure.StructuralType.NonStructural); // NOTE: must set a schedule level! // otherwise the wall creation will fail with "Could not create a face wall." var level = new FilteredElementCollector(Doc) .WhereElementIsNotElementType() .OfCategory(BuiltInCategory.OST_Levels) // this throws a null error if user tries to recieve stream in a file with no levels .ToElements().FirstOrDefault(); if (level == null) // create a new level at 0 if no levels could be retrieved from doc { level = Level.Create(Doc, 0); } TrySetParam(mass, BuiltInParameter.INSTANCE_SCHEDULE_ONLY_LEVEL_PARAM, level); //must regenerate before getting the elem geometry Doc.Regenerate(); Reference faceRef = GetFaceRef(mass); var wallType = GetElementType <WallType>(speckleWall); if (!FaceWall.IsWallTypeValidForFaceWall(Doc, wallType.Id)) { ConversionErrors.Add(new Error { message = $"Wall type not valid for face wall ${speckleWall.applicationId}." }); return(null); } revitWall = null; try { revitWall = DB.FaceWall.Create(Doc, wallType.Id, GetWallLocationLine(speckleWall.locationLine), faceRef); } catch (Exception e) { } if (revitWall == null) { ConversionErrors.Add(new Error { message = $"Failed to create face wall ${speckleWall.applicationId}." }); return(null); } Doc.Delete(mass.Id); SetInstanceParameters(revitWall, speckleWall); var placeholders = new List <ApplicationPlaceholderObject>() { new ApplicationPlaceholderObject { applicationId = speckleWall.applicationId, ApplicationGeneratedId = revitWall.UniqueId, NativeObject = revitWall } }; var hostedElements = SetHostedElements(speckleWall, revitWall); placeholders.AddRange(hostedElements); return(placeholders); }
public Base ConvertToSpeckle(object @object) { Base returnObject = null; switch (@object) { case DB.DetailCurve o: returnObject = DetailCurveToSpeckle(o); break; case DB.DirectShape o: returnObject = DirectShapeToSpeckle(o); break; case DB.FamilyInstance o: returnObject = FamilyInstanceToSpeckle(o); break; case DB.Floor o: returnObject = FloorToSpeckle(o); break; case DB.Level o: returnObject = LevelToSpeckle(o); break; case DB.ModelCurve o: if ((BuiltInCategory)o.Category.Id.IntegerValue == BuiltInCategory.OST_RoomSeparationLines) { returnObject = RoomBoundaryLineToSpeckle(o); } else { returnObject = ModelCurveToSpeckle(o); } break; case DB.Opening o: returnObject = OpeningToSpeckle(o); break; case DB.RoofBase o: returnObject = RoofToSpeckle(o); break; case DB.Architecture.Room o: returnObject = RoomToSpeckle(o); break; case DB.Architecture.TopographySurface o: returnObject = TopographyToSpeckle(o); break; case DB.Wall o: returnObject = WallToSpeckle(o); break; case DB.Mechanical.Duct o: returnObject = DuctToSpeckle(o); break; //these should be handled by curtain walls case DB.CurtainGridLine _: returnObject = null; break; case DB.Architecture.BuildingPad o: returnObject = BuildingPadToSpeckle(o); break; case DB.Architecture.Stairs o: returnObject = StairToSpeckle(o); break; //these are handled by Stairs case DB.Architecture.StairsRun _: returnObject = null; break; case DB.Architecture.StairsLanding _: returnObject = null; break; case DB.Architecture.Railing o: returnObject = RailingToSpeckle(o); break; case DB.Architecture.TopRail _: returnObject = null; break; case DB.Ceiling o: returnObject = CeilingToSpeckle(o); break; case DB.ProjectInfo o: returnObject = ProjectInfoToSpeckle(o); break; case DB.ElementType o: returnObject = ElementTypeToSpeckle(o); break; default: ConversionErrors.Add(new Error("Type not supported", $"Cannot convert {@object.GetType()} to Speckle")); returnObject = null; break; } // NOTE: Only try generic method assignment if there is no existing render material from conversions; // we might want to try later on to capture it more intelligently from inside conversion routines. if (returnObject["renderMaterial"] == null) { var material = GetElementRenderMaterial(@object as DB.Element); returnObject["renderMaterial"] = material; } return(returnObject); }
/// <summary> /// Converts a Speckle <see cref="Brep"/> instance to a Rhino <see cref="Rhino.Geometry.Brep"/> /// </summary> /// <param name="brep">The Speckle Brep to convert</param> /// <returns></returns> /// <exception cref="Exception">Throws exception if the provenance is not Rhino</exception> public RH.Brep BrepToNative(Brep brep) { var tol = RhinoDoc.ActiveDoc.ModelAbsoluteTolerance; try { // TODO: Provenance exception is meaningless now, must change for provenance build checks. // if (brep.provenance != Speckle.Core.Kits.Applications.Rhino) // throw new Exception("Unknown brep provenance: " + brep.provenance + // ". Don't know how to convert from one to the other."); var newBrep = new RH.Brep(); brep.Curve3D.ForEach(crv => newBrep.AddEdgeCurve(CurveToNative(crv))); brep.Curve2D.ForEach(crv => newBrep.AddTrimCurve(CurveToNative(crv))); brep.Surfaces.ForEach(surf => newBrep.AddSurface(SurfaceToNative(surf))); brep.Vertices.ForEach(vert => newBrep.Vertices.Add(PointToNative(vert).Location, tol)); brep.Edges.ForEach(edge => { if (edge.Domain == null || (edge.Domain.start == edge.Curve.domain.start && edge.Domain.end == edge.Curve.domain.end)) { newBrep.Edges.Add(edge.Curve3dIndex); } else { newBrep.Edges.Add(edge.StartIndex, edge.EndIndex, edge.Curve3dIndex, IntervalToNative(edge.Domain), tol); } }); brep.Faces.ForEach(face => { var f = newBrep.Faces.Add(face.SurfaceIndex); f.OrientationIsReversed = face.OrientationReversed; }); brep.Loops.ForEach(loop => { var f = newBrep.Faces[loop.FaceIndex]; var l = newBrep.Loops.Add((RH.BrepLoopType)loop.Type, f); loop.Trims.ToList().ForEach(trim => { RH.BrepTrim rhTrim; if (trim.EdgeIndex != -1) { rhTrim = newBrep.Trims.Add(newBrep.Edges[trim.EdgeIndex], trim.IsReversed, newBrep.Loops[trim.LoopIndex], trim.CurveIndex); } else if (trim.TrimType == BrepTrimType.Singular) { rhTrim = newBrep.Trims.AddSingularTrim(newBrep.Vertices[trim.EndIndex], newBrep.Loops[trim.LoopIndex], (RH.IsoStatus)trim.IsoStatus, trim.CurveIndex); } else { rhTrim = newBrep.Trims.Add(trim.IsReversed, newBrep.Loops[trim.LoopIndex], trim.CurveIndex); } rhTrim.IsoStatus = (IsoStatus)trim.IsoStatus; rhTrim.TrimType = (RH.BrepTrimType)trim.TrimType; rhTrim.SetTolerances(tol, tol); }); }); newBrep.Repair(tol); return(newBrep); } catch (Exception e) { ConversionErrors.Add(new Exception("Failed to convert brep.", e)); return(null); } }
public DateRangeConversionResult(ConversionErrors error) { Error = error.Humanize(); }
/// <summary> /// Converts the Revit elements that have been added to the stream by the user, sends them to /// the Server and the local DB, and creates a commit with the objects. /// </summary> /// <param name="state">StreamState passed by the UI</param> public override async Task <StreamState> SendStream(StreamState state) { ConversionErrors.Clear(); OperationErrors.Clear(); var kit = KitManager.GetDefaultKit(); var converter = kit.LoadConverter(ConnectorRevitUtils.RevitAppName); converter.SetContextDocument(CurrentDoc.Document); var streamId = state.Stream.id; var client = state.Client; var selectedObjects = new List <Element>(); if (state.Filter != null) { selectedObjects = GetSelectionFilterObjects(state.Filter, converter); state.SelectedObjectIds = selectedObjects.Select(x => x.UniqueId).ToList(); } else //selection was by cursor { // TODO: update state by removing any deleted or null object ids selectedObjects = state.SelectedObjectIds.Select(x => CurrentDoc.Document.GetElement(x)).Where(x => x != null).ToList(); } if (!selectedObjects.Any()) { state.Errors.Add(new Exception("There are zero objects to send. Please use a filter, or set some via selection.")); return(state); } converter.SetContextObjects(selectedObjects.Select(x => new ApplicationPlaceholderObject { applicationId = x.UniqueId }).ToList()); var commitObject = new Base(); var conversionProgressDict = new ConcurrentDictionary <string, int>(); conversionProgressDict["Conversion"] = 0; Execute.PostToUIThread(() => state.Progress.Maximum = selectedObjects.Count()); var convertedCount = 0; var placeholders = new List <Base>(); foreach (var revitElement in selectedObjects) { try { if (revitElement == null) { continue; } if (!converter.CanConvertToSpeckle(revitElement)) { state.Errors.Add(new Exception($"Skipping not supported type: {revitElement.GetType()}, name {revitElement.Name}")); continue; } var conversionResult = converter.ConvertToSpeckle(revitElement); conversionProgressDict["Conversion"]++; UpdateProgress(conversionProgressDict, state.Progress); placeholders.Add(new ApplicationPlaceholderObject { applicationId = revitElement.UniqueId, ApplicationGeneratedId = revitElement.UniqueId }); convertedCount++; //hosted elements will be returned as `null` by the ConvertToSpeckle method //since they are handled when converting their parents if (conversionResult != null) { var category = $"@{revitElement.Category.Name}"; if (commitObject[category] == null) { commitObject[category] = new List <Base>(); } ((List <Base>)commitObject[category]).Add(conversionResult); } } catch (Exception e) { state.Errors.Add(e); } } if (converter.Report.ConversionErrorsCount != 0) { // TODO: Get rid of the custom Error class. It's not needed. ConversionErrors.AddRange(converter.Report.ConversionErrors); state.Errors.AddRange(converter.Report.ConversionErrors); } if (convertedCount == 0) { Globals.Notify("Zero objects converted successfully. Send stopped."); return(state); } Execute.PostToUIThread(() => state.Progress.Maximum = (int)commitObject.GetTotalChildrenCount()); if (state.CancellationTokenSource.Token.IsCancellationRequested) { return(state); } var transports = new List <ITransport>() { new ServerTransport(client.Account, streamId) }; var objectId = await Operations.Send( @object : commitObject, cancellationToken : state.CancellationTokenSource.Token, transports : transports, onProgressAction : dict => UpdateProgress(dict, state.Progress), onErrorAction : (s, e) => { OperationErrors.Add(e); // TODO! state.Errors.Add(e); state.CancellationTokenSource.Cancel(); }, disposeTransports : true ); if (OperationErrors.Count != 0) { Globals.Notify("Failed to send."); state.Errors.AddRange(OperationErrors); return(state); } if (state.CancellationTokenSource.Token.IsCancellationRequested) { return(null); } var actualCommit = new CommitCreateInput() { streamId = streamId, objectId = objectId, branchName = state.Branch.name, message = state.CommitMessage != null ? state.CommitMessage : $"Sent {convertedCount} objects from {ConnectorRevitUtils.RevitAppName}.", sourceApplication = ConnectorRevitUtils.RevitAppName, }; if (state.PreviousCommitId != null) { actualCommit.parents = new List <string>() { state.PreviousCommitId }; } try { var commitId = await client.CommitCreate(actualCommit); await state.RefreshStream(); state.PreviousCommitId = commitId; WriteStateToFile(); RaiseNotification($"{convertedCount} objects sent to Speckle 🚀"); } catch (Exception e) { state.Errors.Add(e); Globals.Notify($"Failed to create commit.\n{e.Message}"); } return(state); }
public static Autodesk.Revit.DB.FamilyInstance ToNative(this SpeckleElementsClasses.AdaptiveComponent myAdaptiveComponent) { var(docObj, stateObj) = GetExistingElementByApplicationId(myAdaptiveComponent.ApplicationId, myAdaptiveComponent.Type); var familySymbol = GetFamilySymbolByFamilyNameAndType(myAdaptiveComponent.familyName, myAdaptiveComponent.familyType); if (familySymbol == null) { ConversionErrors.Add(new SpeckleConversionError { Message = $"Missing family: {myAdaptiveComponent.familyName} {myAdaptiveComponent.familyType}" }); throw new RevitFamilyNotFoundException($"No 'AdaptiveComponent' family found in the project"); } if (!familySymbol.IsActive) { familySymbol.Activate(); } if (myAdaptiveComponent.points == null) { ConversionErrors.Add(new SpeckleConversionError { Message = $"Wrong number of points supplied to adapive family" }); return(null); } if (docObj != null) // we have a document object already, so check if we can edit it. { var type = Doc.GetElement(docObj.GetTypeId()) as ElementType; // if family changed, tough luck - delete and rewind if (myAdaptiveComponent.familyName != type.FamilyName) { //delete and continue crating it Doc.Delete(docObj.Id); } // edit element else { var existingFamilyInstance = (Autodesk.Revit.DB.FamilyInstance)docObj; // check if type changed, and try and change it if (myAdaptiveComponent.familyType != null && (myAdaptiveComponent.familyType != type.Name)) { existingFamilyInstance.ChangeTypeId(familySymbol.Id); } SetAdaptiveComponentPoints(existingFamilyInstance, myAdaptiveComponent.points); SetElementParams(existingFamilyInstance, myAdaptiveComponent.parameters); return(existingFamilyInstance); } } // if we don't have a document object else { var component = AdaptiveComponentInstanceUtils.CreateAdaptiveComponentInstance(Doc, familySymbol); SetAdaptiveComponentPoints(component, myAdaptiveComponent.points); SetElementParams(component, myAdaptiveComponent.parameters); return(component); } return(null); }
public static Element StructuralFramingToNative(Beam myBeam, StructuralType structuralType) { var(docObj, stateObj) = GetExistingElementByApplicationId(myBeam.ApplicationId, myBeam.Type); try { FamilySymbol familySymbol; familySymbol = GetFamilySymbolByFamilyNameAndTypeAndCategory(myBeam.beamFamily, myBeam.beamType, BuiltInCategory.OST_StructuralFraming); if (familySymbol == null) { familySymbol = GetFamilySymbolByFamilyNameAndTypeAndCategory(myBeam.beamFamily, myBeam.beamType, BuiltInCategory.OST_BeamAnalytical); } // Freak out if we don't have a symbol. if (familySymbol == null) { ConversionErrors.Add(new SpeckleConversionError { Message = $"Missing family: {myBeam.beamFamily} {myBeam.beamType}" }); throw new RevitFamilyNotFoundException($"No 'Beam' family found in the project"); } Autodesk.Revit.DB.Curve baseLine = null; if (myBeam.baseLine != null) { baseLine = (Autodesk.Revit.DB.Curve)SpeckleCore.Converter.Deserialise(obj: myBeam.baseLine, excludeAssebmlies: new string[] { "SpeckleCoreGeometryDynamo" }); } Autodesk.Revit.DB.XYZ basePoint = null; if (myBeam.basePoint != null) { basePoint = (Autodesk.Revit.DB.XYZ)SpeckleCore.Converter.Deserialise(obj: myBeam.basePoint, excludeAssebmlies: new string[] { "SpeckleCoreGeometryDynamo" }); } //var start = baseLine.GetEndPoint( 0 ); //var end = baseLine.GetEndPoint( 1 ); // Activate the symbol yo! if (!familySymbol.IsActive) { familySymbol.Activate(); } // If we have an existing element we can edit: if (docObj != null) { var type = Doc.GetElement(docObj.GetTypeId()) as ElementType; // if family changed, tough luck. delete and let us create a new one. if (myBeam.beamFamily != type.FamilyName) { Doc.Delete(docObj.Id); } else { var existingFamilyInstance = (Autodesk.Revit.DB.FamilyInstance)docObj; if (baseLine != null) { var existingLocationCurve = existingFamilyInstance.Location as LocationCurve; existingLocationCurve.Curve = baseLine; } else { var existingLocationPoint = existingFamilyInstance.Location as LocationPoint; existingLocationPoint.Point = basePoint; } // check for a type change if (myBeam.beamType != null && myBeam.beamType != type.Name) { existingFamilyInstance.ChangeTypeId(familySymbol.Id); } SetElementParams(existingFamilyInstance, myBeam.parameters); return(existingFamilyInstance); } } if (myBeam.level == null) { myBeam.level = new SpeckleElementsClasses.Level() { elevation = 0, levelName = "Speckle Level 0" } } ; var myLevel = myBeam.level.ToNative() as Autodesk.Revit.DB.Level; Autodesk.Revit.DB.FamilyInstance familyInstance = null; if (baseLine != null) { familyInstance = Doc.Create.NewFamilyInstance(baseLine, familySymbol, myLevel, structuralType); } else { familyInstance = Doc.Create.NewFamilyInstance(basePoint, familySymbol, myLevel, structuralType); } SetElementParams(familyInstance, myBeam.parameters); return(familyInstance); } catch (Exception e) { return(null); } }