Esempio n. 1
0
        private Base ConvertGridLines(ISpeckleConverter converter, ProgressViewModel progress)
        {
            Base converted = null;

            ITFApplication appInst = new TFApplicationList();

            if (0 == appInst.GetProject(0, out ITFLoadableProjectList projList) && projList != null)
            {
                ITFLoadableProject proj = projList.AsTFLoadableProject;
                if (null == proj)
                {
                    progress.Report.ConversionErrors.Add(new Exception("Could not retrieve project for exporting gridlines"));
                    return(converted);
                }

                ITFDrawingGrid drawingGrid = null;
                if (Control.InvokeRequired)
                {
                    Control.Invoke((Action)(() => { proj.GetDrawingGrid(false, 0, out drawingGrid); }));
                }
                else
                {
                    proj.GetDrawingGrid(false, 0, out drawingGrid);
                }

                if (null == drawingGrid)
                {
                    progress.Report.ConversionErrors.Add(new Exception("Could not retrieve drawing grid for exporting gridlines"));
                    return(converted);
                }

                if (Control.InvokeRequired)
                {
                    converted = (Base)Control.Invoke(new SpeckleConversionDelegate(converter.ConvertToSpeckle), new object[] { drawingGrid });
                }
                else
                {
                    converted = converter.ConvertToSpeckle(drawingGrid);
                }
            }
            return(converted);
        }
Esempio n. 2
0
        public override async Task <StreamState> SendStream(StreamState state)
        {
            ConversionErrors.Clear();
            OperationErrors.Clear();

            var kit       = KitManager.GetDefaultKit();
            var converter = kit.LoadConverter(Utils.BentleyAppName);

            if (Control.InvokeRequired)
            {
                Control.Invoke(new SetContextDelegate(converter.SetContextDocument), new object[] { Session.Instance });
            }
            else
            {
                converter.SetContextDocument(Session.Instance);
            }

            var streamId = state.Stream.id;
            var client   = state.Client;

            var selectedObjects = new List <Object>();

            if (state.Filter != null)
            {
                if (Control.InvokeRequired)
                {
                    state.SelectedObjectIds = (List <string>)Control.Invoke(new GetObjectsFromFilterDelegate(GetObjectsFromFilter), new object[] { state.Filter, converter });
                }
                else
                {
                    state.SelectedObjectIds = GetObjectsFromFilter(state.Filter, converter);
                }
            }

            if (state.SelectedObjectIds.Count == 0 && !ExportGridLines)
            {
                RaiseNotification("Zero objects selected; send stopped. Please select some objects, or check that your filter can actually select something.");
                return(state);
            }

            var commitObj = new Base();

            var units = Units.GetUnitsFromString(ModelUnits).ToLower();

            commitObj["units"] = units;

            var conversionProgressDict = new ConcurrentDictionary <string, int>();

            conversionProgressDict["Conversion"] = 0;
            Execute.PostToUIThread(() => state.Progress.Maximum = state.SelectedObjectIds.Count());
            int convertedCount = 0;

            // grab elements from active model
            var objs = new List <Element>();

#if (OPENROADS || OPENRAIL)
            bool convertCivilObject = false;
            var  civObjs            = new List <NamedModelEntity>();

            if (civilElementKeys.Count(x => state.SelectedObjectIds.Contains(x)) > 0)
            {
                if (Control.InvokeRequired)
                {
                    civObjs = (List <NamedModelEntity>)Control.Invoke(new GetCivilObjectsDelegate(GetCivilObjects), new object[] { state });
                }
                else
                {
                    civObjs = GetCivilObjects(state);
                }

                objs = civObjs.Select(x => x.Element).ToList();
                convertCivilObject = true;
            }
            else
            {
                objs = state.SelectedObjectIds.Select(x => Model.FindElementById((ElementId)Convert.ToUInt64(x))).ToList();
            }
#else
            objs = state.SelectedObjectIds.Select(x => Model.FindElementById((ElementId)Convert.ToUInt64(x))).ToList();
#endif

#if (OPENBUILDINGS)
            if (ExportGridLines)
            {
                // grab grid lines
                ITFApplication appInst = new TFApplicationList();

                if (0 == appInst.GetProject(0, out ITFLoadableProjectList projList) && projList != null)
                {
                    ITFLoadableProject proj = projList.AsTFLoadableProject;
                    if (null == proj)
                    {
                        return(null);
                    }

                    ITFDrawingGrid drawingGrid = null;
                    if (Control.InvokeRequired)
                    {
                        Control.Invoke((Action)(() => { proj.GetDrawingGrid(false, 0, out drawingGrid); }));
                    }
                    else
                    {
                        proj.GetDrawingGrid(false, 0, out drawingGrid);
                    }

                    if (null == drawingGrid)
                    {
                        return(null);
                    }

                    Base converted;
                    if (Control.InvokeRequired)
                    {
                        converted = (Base)Control.Invoke(new SpeckleConversionDelegate(converter.ConvertToSpeckle), new object[] { drawingGrid });
                    }
                    else
                    {
                        converted = converter.ConvertToSpeckle(drawingGrid);
                    }

                    if (converted != null)
                    {
                        var containerName = "Grid Systems";

                        if (commitObj[$"@{containerName}"] == null)
                        {
                            commitObj[$"@{containerName}"] = new List <Base>();
                        }
                        ((List <Base>)commitObj[$"@{containerName}"]).Add(converted);

                        // not sure this makes much sense here
                        conversionProgressDict["Conversion"]++;
                        UpdateProgress(conversionProgressDict, state.Progress);

                        //gridLine.applicationId = ??;

                        convertedCount++;
                    }
                }
            }
#endif

            foreach (var obj in objs)
            {
                if (state.CancellationTokenSource.Token.IsCancellationRequested)
                {
                    return(null);
                }

                if (obj == null)
                {
                    state.Errors.Add(new Exception($"Failed to find local object."));
                    continue;
                }

                var objId   = obj.ElementId.ToString();
                var objType = obj.ElementType;

                if (!converter.CanConvertToSpeckle(obj))
                {
                    state.Errors.Add(new Exception($"Objects of type ${objType} are not supported"));
                    continue;
                }

                // convert obj
                // try catch to prevent memory access violation crash in case a conversion goes wrong
                Base   converted     = null;
                string containerName = string.Empty;
                try
                {
                    var levelCache = Model.GetFileLevelCache();
                    var objLevel   = levelCache.GetLevel(obj.LevelId);
                    var layerName  = "Unknown";
                    if (objLevel != null)
                    {
                        layerName = objLevel.Name;
                    }

#if (OPENROADS || OPENRAIL)
                    if (convertCivilObject)
                    {
                        var civilObj = civObjs[objs.IndexOf(obj)];
                        if (Control.InvokeRequired)
                        {
                            converted = (Base)Control.Invoke(new SpeckleConversionDelegate(converter.ConvertToSpeckle), new object[] { civilObj });
                            Control.Invoke((Action)(() => { containerName = civilObj.Name == "" ? "Unnamed" : civilObj.Name; }));
                        }
                        else
                        {
                            converted     = converter.ConvertToSpeckle(civilObj);
                            containerName = civilObj.Name == "" ? "Unnamed" : civilObj.Name;
                        }
                    }
                    else
                    {
                        if (Control.InvokeRequired)
                        {
                            converted = (Base)Control.Invoke(new SpeckleConversionDelegate(converter.ConvertToSpeckle), new object[] { obj });
                        }
                        else
                        {
                            converted = converter.ConvertToSpeckle(obj);
                        }
                        containerName = layerName;
                    }
#else
                    if (Control.InvokeRequired)
                    {
                        converted = (Base)Control.Invoke(new SpeckleConversionDelegate(converter.ConvertToSpeckle), new object[] { obj });
                    }
                    else
                    {
                        converted = converter.ConvertToSpeckle(obj);
                    }

                    containerName = layerName;
#endif
                    if (converted == null)
                    {
                        state.Errors.Add(new Exception($"Failed to convert object ${objId} of type ${objType}."));
                        continue;
                    }
                }
                catch
                {
                    state.Errors.Add(new Exception($"Failed to convert object {objId} of type {objType}."));
                    continue;
                }

                /* TODO: adding the feature data and properties per object
                 * foreach (var key in obj.ExtensionDictionary)
                 * {
                 * converted[key] = obj.ExtensionDictionary.GetUserString(key);
                 * }
                 */

                if (commitObj[$"@{containerName}"] == null)
                {
                    commitObj[$"@{containerName}"] = new List <Base>();
                }
                ((List <Base>)commitObj[$"@{containerName}"]).Add(converted);

                conversionProgressDict["Conversion"]++;
                UpdateProgress(conversionProgressDict, state.Progress);

                converted.applicationId = objId;

                convertedCount++;
            }

            Execute.PostToUIThread(() => state.Progress.Maximum = convertedCount);

            var transports = new List <ITransport>()
            {
                new ServerTransport(client.Account, streamId)
            };

            var commitObjId = await Operations.Send(
                commitObj,
                state.CancellationTokenSource.Token,
                transports,
                onProgressAction : dict => UpdateProgress(dict, state.Progress),
                onErrorAction : (err, exception) => { Exceptions.Add(exception); }
                );

            if (Exceptions.Count != 0)
            {
                RaiseNotification($"Failed to send: \n {Exceptions.Last().Message}");
                return(null);
            }

            if (convertedCount > 0)
            {
                var actualCommit = new CommitCreateInput
                {
                    streamId          = streamId,
                    objectId          = commitObjId,
                    branchName        = state.Branch.name,
                    message           = state.CommitMessage != null ? state.CommitMessage : $"Pushed {convertedCount} elements from {Utils.AppName}.",
                    sourceApplication = Utils.BentleyAppName
                };

                if (state.PreviousCommitId != null)
                {
                    actualCommit.parents = new List <string>()
                    {
                        state.PreviousCommitId
                    };
                }

                try
                {
                    var commitId = await client.CommitCreate(actualCommit);

                    await state.RefreshStream();

                    state.PreviousCommitId = commitId;

                    try
                    {
                        PersistAndUpdateStreamInFile(state);
                    }
                    catch (Exception e)
                    {
                    }
                    RaiseNotification($"{convertedCount} objects sent to {state.Stream.name}.");
                }
                catch (Exception e)
                {
                    Globals.Notify($"Failed to create commit.\n{e.Message}");
                    state.Errors.Add(e);
                }
            }
            else
            {
                Globals.Notify($"Did not create commit: no objects could be converted.");
            }

            return(state);
        }
        public Base GridSystemsToSpeckle(ITFDrawingGrid drawingGrid, string units = null)
        {
            Base        container = new Base();
            List <Base> gridLines = new List <Base>();

            container["Grid Lines"] = gridLines;

            drawingGrid.GetGridSystems(0, out ITFGridSystemList gridSystems);
            if (gridSystems == null)
            {
                return(null);
            }

            for (ITFGridSystem gridSystem = gridSystems.AsTFGridSystem;
                 gridSystem != null;
                 gridSystems.GetNext("", out gridSystems), gridSystem = (gridSystems != null) ? gridSystems.AsTFGridSystem : null)
            {
                gridSystem.GetGridCurves(0, out ITFGridCurveList curves);

                if (curves == null)
                {
                    continue;
                }

                gridSystem.GetLCS(out DPoint3d origin, 0, out double angle);

                gridSystem.GetMinGridLineExtension(0, out double mindGridLineExtendsion);

                // find overall minimum/maximum extends of grid lines
                double minimumValueX        = 0;
                double minimumValueY        = 0;
                double maximumValueX        = 0;
                double maximumValueY        = 0;
                double maximumRadius        = 0;
                double maximumCircularAngle = 0;

                List <ITFGridCurve> gridCurveList = new List <ITFGridCurve>();
                for (ITFGridCurve gridCurve = curves.AsTFGridCurve; gridCurve != null; curves.GetNext("", out curves), gridCurve = curves != null ? curves.AsTFGridCurve : null)
                {
                    gridCurveList.Add(gridCurve);
                    gridCurve.GetType(0, out TFdGridCurveType curveType);
                    gridCurve.GetValue(0, out double gridValue);
                    gridCurve.GetMinimumValue(0, out double minimumValue);

                    switch (curveType)
                    {
                    case (TFdGridCurveType.TFdGridCurveType_OrthogonalX):
                        if (gridValue < minimumValueX)
                        {
                            minimumValueX = gridValue;
                        }
                        // grid lines pick up the minimum value of their neighbors
                        if (minimumValue < minimumValueY)
                        {
                            minimumValueY = minimumValue;
                        }
                        if (gridValue > maximumValueX)
                        {
                            maximumValueX = gridValue;
                        }
                        break;

                    case (TFdGridCurveType.TFdGridCurveType_OrthogonalY):
                        if (gridValue < minimumValueY)
                        {
                            minimumValueY = gridValue;
                        }
                        // grid lines pick up the minimum value of their neighbors
                        if (minimumValue < minimumValueX)
                        {
                            minimumValueX = minimumValue;
                        }
                        if (gridValue > maximumValueY)
                        {
                            maximumValueY = gridValue;
                        }
                        break;

                    case (TFdGridCurveType.TFdGridCurveType_Circular):
                        if (gridValue > maximumRadius)
                        {
                            maximumRadius = gridValue;
                        }
                        break;

                    case (TFdGridCurveType.TFdGridCurveType_Radial):
                        if (gridValue > maximumCircularAngle)
                        {
                            maximumCircularAngle = gridValue;
                        }
                        break;

                    default:
                        break;
                    }
                }

                // for some reason only angles are scaled
                maximumCircularAngle *= UoR;

                foreach (ITFGridCurve gridCurve in gridCurveList)
                {
                    ICurve baseLine;

                    gridCurve.GetLabel(0, out string label);
                    gridCurve.GetType(0, out TFdGridCurveType curveType);
                    gridCurve.GetValue(0, out double gridValue);
                    //gridCurve.GetMsElementDescrP(out Element obj, 0);

                    var u = units ?? ModelUnits;

                    //if (obj != null)
                    //{
                    //    // coordinate transformation
                    //    //double axx = Math.Cos(angle);
                    //    //double axy = -Math.Sin(angle);
                    //    //double axz = 0;
                    //    //double axw = origin.X;
                    //    //double ayx = Math.Sin(angle);
                    //    //double ayy = Math.Cos(angle);
                    //    //double ayz = 0;
                    //    //double ayw = origin.Y;
                    //    //double azx = 0;
                    //    //double azy = 0;
                    //    //double azz = 1;
                    //    //double azw = origin.Z;
                    //    //DTransform3d transform = new DTransform3d(axx, axy, axz, axw, ayx, ayy, ayz, ayw, azx, azy, azz, azw);
                    //    if (obj is LineElement)
                    //    {
                    //        Line line = LineToSpeckle((LineElement)obj, u);
                    //        baseLine = TransformCurve(line, origin, angle);
                    //    }
                    //    else if (obj is ArcElement)
                    //    {
                    //        ICurve arc = ArcToSpeckle((ArcElement)obj, u);
                    //        baseLine = arc;
                    //        baseLine = TransformCurve(arc, origin, angle);
                    //    }
                    //    else
                    //    {
                    //        throw new NotSupportedException("GridCurveType " + curveType + " not supported!");
                    //    }
                    //    gridLines.Add(CreateGridLine(baseLine, label, u));
                    //}
                    switch (curveType)
                    {
                    case TFdGridCurveType.TFdGridCurveType_OrthogonalX:
                    case TFdGridCurveType.TFdGridCurveType_OrthogonalY:
                        baseLine = GridCurveToSpeckle(gridCurve, origin, angle, minimumValueX, minimumValueY, maximumValueX, maximumValueY, u);
                        break;

                    case TFdGridCurveType.TFdGridCurveType_Circular:
                        Plane xy = new Plane(new Point(origin.X, origin.Y, 0, u), new Vector(0, 0, 1, u), new Vector(1, 0, 0, u), new Vector(0, 1, 0, u), u);
                        baseLine = new Arc(xy, gridValue, angle, maximumCircularAngle + angle, maximumCircularAngle, u);
                        break;

                    case TFdGridCurveType.TFdGridCurveType_Radial:
                        Point startPoint = Translate(Rotate(new Point(0, 0, 0, u), angle), origin.X, origin.Y);
                        Point endPoint   = Translate(Rotate(Rotate(new Point(maximumRadius, 0, 0, u), gridValue * UoR), angle), origin.X, origin.Y);
                        baseLine = new Line(startPoint, endPoint, u);
                        break;

                    default:
                        continue;
                    }
                    gridLines.Add(CreateGridLine(baseLine, label, u));
                }
            }
            return(container);
        }