Ejemplo n.º 1
0
        /// <summary>
        /// Executed upon existing the param_expr rule
        /// </summary>
        /// <param name="context">the param_expr context</param>
        public override void ExitParam_expr([NotNull] ParamExprGrammarParser.Param_exprContext context)
        {
            base.ExitParam_expr(context);
            NodeProperty paramExprNodeProp = GetNodePropertyValue(context.expr());
            object       parValue          = paramExprNodeProp.nodePropertyValue;

            // Unique parameter value can only be "enforced" for a string datatype by appending a running number: <parValue> (#), starting with 2
            if (isUnique && parValue is string)
            {
                Tuple <string, object> key = new Tuple <string, object>(RevitParameterName, parValue);
                int counter = 0;
                if (UniqueParameterValue.TryGetValue(key, out counter))
                {
                    counter++;
                    parValue = parValue.ToString() + " (" + counter.ToString() + ")";
                    UniqueParameterValue[key] = counter;
                }
                else
                {
                    UniqueParameterValue.Add(key, 1);
                }
            }
            FinalParameterValue = parValue;
            UnitType            = paramExprNodeProp.uomTypeId;
            if (paramExprNodeProp.uomTypeId != null)
            {
                if (FinalParameterValue is double)
                {
                    double?paramValueDouble = FinalParameterValue as double?;
                    formattedValue      = UnitFormatUtils.Format(RevitElement.Document.GetUnits(), paramExprNodeProp.uomTypeId, paramValueDouble.Value, false);
                    FinalParameterValue = UnitUtils.ConvertToInternalUnits(paramValueDouble.Value, paramExprNodeProp.uomTypeId);
                }
            }
        }
Ejemplo n.º 2
0
        protected override void Process(IFCAnyHandle ifcCurve)
        {
            base.Process(ifcCurve);

            bool   found  = false;
            double radius = IFCImportHandleUtil.GetRequiredScaledLengthAttribute(ifcCurve, "Radius", out found);

            if (!found)
            {
                Importer.TheLog.LogError(ifcCurve.StepId, "Cannot find the radius of this circle", false);
                return;
            }

            try
            {
                Curve = Arc.Create(Position.Origin, radius, 0, 2.0 * Math.PI, Position.BasisX, Position.BasisY);
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("too small"))
                {
                    string lengthAsString = UnitFormatUtils.Format(IFCImportFile.TheFile.Document.GetUnits(), UnitType.UT_Length, radius, true, false);
                    Importer.TheLog.LogError(Id, "Found a circle with radius of " + lengthAsString + ", ignoring.", false);
                    Curve = null;
                }
                else
                {
                    Importer.TheLog.LogError(Id, ex.Message, false);
                }
                Curve = null;
            }
        }
Ejemplo n.º 3
0
        static public string FormatLengthAsString(double value)
        {
            FormatValueOptions formatValueOptions = new FormatValueOptions();

            formatValueOptions.AppendUnitSymbol = true;
            return(UnitFormatUtils.Format(IFCImportFile.TheFile.Document.GetUnits(), UnitType.UT_Length, value, true, false, formatValueOptions));
        }
Ejemplo n.º 4
0
        private string ConvertFeetInchToString(double feetInch)
        {
            Units  units  = this.doc.GetUnits();
            string output = UnitFormatUtils.Format(units, UnitType.UT_Length, feetInch, true, true);

            return(output);
        }
Ejemplo n.º 5
0
        static public string FormatToRevitUI(string valueName, double value, UnitsAssignment[] Assignments, bool appendUnitSymbol = false)
        {
            string formatedValue = value.ToString();

            if (null == RevitUnits)
            {
                return(formatedValue);
            }

            foreach (UnitsAssignment ua in Assignments)
            {
                if (ua.ValueName.CompareTo(valueName) == 0)
                {
                    FormatOptions fo = RevitUnits.GetFormatOptions(ua.unitType);

                    FormatValueOptions formatValueOptions = new FormatValueOptions();
                    formatValueOptions.SetFormatOptions(fo);
                    formatValueOptions.AppendUnitSymbol = appendUnitSymbol;

                    formatedValue = UnitFormatUtils.Format(RevitUnits, ua.unitType, value, false, false, formatValueOptions);

                    string unitSymbol = GetUnitSymbol(valueName, Assignments);
                    if (unitSymbol.Length > 0)
                    {
                        formatedValue = Regex.Replace(formatedValue, unitSymbol, "");
                    }
                    break;
                }
            }

            return(formatedValue);
        }
Ejemplo n.º 6
0
        private string FormatBoundedValue(IFCPropertyValue propertyValue)
        {
            if (IFCUnit != null)
            {
                FormatValueOptions formatValueOptions = new FormatValueOptions();
                FormatOptions      specFormatOptions  = IFCImportFile.TheFile.Document.GetUnits().GetFormatOptions(IFCUnit.Spec);
                specFormatOptions.Accuracy = 1e-8;
                if (specFormatOptions.CanSuppressTrailingZeros())
                {
                    specFormatOptions.SuppressTrailingZeros = true;
                }
                formatValueOptions.SetFormatOptions(specFormatOptions);

                // If ScaleValues is false, value is in source file units, but 'UnitFormatUtils.Format' expects
                // it in internal units and it then converts it to display units, which should be the same as
                // the source file units.
                double value = Importer.TheProcessor.ScaleValues ?
                               propertyValue.AsDouble() :
                               UnitUtils.ConvertToInternalUnits(propertyValue.AsDouble(), specFormatOptions.GetUnitTypeId());

                return(UnitFormatUtils.Format(IFCImportFile.TheFile.Document.GetUnits(), IFCUnit.Spec, value, false, formatValueOptions));
            }
            else
            {
                return(propertyValue.ValueAsString());
            }
        }
Ejemplo n.º 7
0
        //private static string GetParamaterUnit(DisplayUnitType uniType)
        //{
        //    switch (uniType)
        //    {
        //        case DisplayUnitType.DUT_MILLIMETERS:
        //            return "mm";
        //        case DisplayUnitType.DUT_METERS:
        //            return "m";
        //        case DisplayUnitType.DUT_CENTIMETERS:
        //            return "cm";
        //        default:
        //            return string.Empty;
        //    }
        //}

        private static string FormatNumber(Document doc, UnitType unitType, double value)
        {
#if R2014
            var uStr = FormatUtils.Format(doc, unitType, value);
#else
            var uStr = UnitFormatUtils.Format(doc.GetUnits(), unitType, value, false, false);
#endif
            return(uStr);
        }
 private void Window_Loaded(object sender, RoutedEventArgs e)
 {
     this.pfClip.Text = UnitFormatUtils.Format(
         _doc.GetUnits(),
         UnitType.UT_Length,
         Properties.Settings.Default.PreferFarClip,
         false,
         false);
 }
Ejemplo n.º 9
0
        private string GenerateShortDistanceCommentString(double dist, double shortSegmentTolerance, int lastVertex, int currIdx, bool tryAsSolid)
        {
            string distAsString      = UnitFormatUtils.Format(IFCImportFile.TheFile.Document.GetUnits(), UnitType.UT_Length, dist, true, false);
            string shortDistAsString = UnitFormatUtils.Format(IFCImportFile.TheFile.Document.GetUnits(), UnitType.UT_Length, shortSegmentTolerance, true, false);
            string warningString     = "Distance between vertices " + lastVertex + " and " + currIdx +
                                       " is " + distAsString + ", which is less than the minimum " + (tryAsSolid ? "Solid" : "Mesh") +
                                       " distance of " + shortDistAsString + ", removing second point.";

            return(warningString);
        }
Ejemplo n.º 10
0
        public static string ParameterToString(Document doc, FamilyParameter param, FamilyType type)
        {
            if (!type.HasValue(param))
            {
                return("无");
            }
            if (param.Definition.ParameterType == ParameterType.Invalid)
            {
                return("不可用");
            }
            switch (param.StorageType)
            {
            case StorageType.Double:
#if R2014
                var uStr = FormatUtils.Format(doc, param.Definition.UnitType, type.AsDouble(param).Value);
#else
                var uStr = UnitFormatUtils.Format(doc.GetUnits(), param.Definition.UnitType, type.AsDouble(param).Value, false, false);
#endif
                return(uStr);

            //var uStr = string.Empty;
            //if (param.Definition.ParameterType == ParameterType.Length)
            //{
            //    uStr = GetParamaterUnit(param.DisplayUnitType);
            //}
            //var dStr = param.AsValueString();
            //if (!String.IsNullOrEmpty(uStr) && !dStr.EndsWith(uStr)) dStr += uStr;
            //return dStr;
            case StorageType.Integer:
                var v = type.AsInteger(param).Value;
                if (param.Definition.ParameterType == ParameterType.YesNo)
                {
                    if (v == 0)
                    {
                        return("否");
                    }
                    return("是");
                }
#if R2014
                return(FormatUtils.Format(doc, param.Definition.UnitType, v));
#else
                return(UnitFormatUtils.Format(doc.GetUnits(), param.Definition.UnitType, v, false, false));
#endif
            case StorageType.String:
                return(type.AsString(param));

            case StorageType.ElementId:
                ElementId idVal = type.AsElementId(param);
                return(AsElementName(doc, idVal));

            case StorageType.None:
            default:
                return("无");
            }
        }
Ejemplo n.º 11
0
        private static string FormatDatumOffsetString(DatumPlane datum, double offset, Units docUnits)
        {
            if (datum == null)
            {
                return(UnitFormatUtils.Format(docUnits, 0, offset, false, false));
            }
            double num  = Math.Abs(offset);
            bool   flag = offset < 0.0;

            return("(" + datum.get_Name() + ")" + (flag ? " - " : " + ") + UnitFormatUtils.Format(docUnits, 0, num, false, false));
        }
Ejemplo n.º 12
0
 private string FormatBoundedValue(IFCPropertyValue propertyValue)
 {
     if (IFCUnit != null)
     {
         return(UnitFormatUtils.Format(IFCImportFile.TheFile.Document.GetUnits(), IFCUnit.UnitType, propertyValue.AsDouble(), true, false));
     }
     else
     {
         return(propertyValue.ValueAsString());
     }
 }
Ejemplo n.º 13
0
        public void PE_ShouldFormatText()
        {
            //Arrange
            double   d        = 5.726548;
            Document doc      = GeneralHelper.ExternalCommandData.Application.ActiveUIDocument.Document;
            Units    docUnits = doc.GetUnits();

            //Act
            string output = UnitFormatUtils.Format(docUnits, UnitType.UT_Length, d, false, true);

            //Assert
            Assert.AreEqual(output, "5\'  8 23/32\"");
        }
Ejemplo n.º 14
0
 private void Height_TextBox_LostFocus(object sender, RoutedEventArgs e)
 {
     if (Tools.GetValueFromString(Height_TextBox.Text, _doc.GetUnits()) != null)
     {
         _floorHeight        = (double)Tools.GetValueFromString(Height_TextBox.Text, _doc.GetUnits());
         Height_TextBox.Text = UnitFormatUtils.Format(_doc.GetUnits(), UnitType.UT_Length, _floorHeight, true, true);
     }
     else
     {
         TaskDialog.Show(Tools.LangResMan.GetString("floorFinishes_TaskDialogName", Tools.Cult),
                         Tools.LangResMan.GetString("floorFinishes_heightValueError", Tools.Cult), TaskDialogCommonButtons.Close, TaskDialogResult.Close);
         this.Activate();
     }
 }
Ejemplo n.º 15
0
        /// <summary>
        /// Convert a value into a formatted length string as displayed in Revit.
        /// </summary>
        /// <param name="value">The value, in Revit internal units.</param>
        /// <returns>The formatted string representation.</returns>
        static public string FormatLengthAsString(double value)
        {
            FormatValueOptions formatValueOptions = new FormatValueOptions();

            formatValueOptions.AppendUnitSymbol = true;
            FormatOptions lengthFormatOptions = IFCImportFile.TheFile.Document.GetUnits().GetFormatOptions(SpecTypeId.Length);

            lengthFormatOptions.Accuracy = 1e-8;
            if (lengthFormatOptions.CanSuppressTrailingZeros())
            {
                lengthFormatOptions.SuppressTrailingZeros = true;
            }
            formatValueOptions.SetFormatOptions(lengthFormatOptions);
            return(UnitFormatUtils.Format(IFCImportFile.TheFile.Document.GetUnits(), SpecTypeId.Length, value, false, formatValueOptions));
        }
        public static string ConVertDoubleToImperial(double doubleLength)
        {
            string   empty    = string.Empty;
            double   num      = UnitUtils.Convert(doubleLength, DisplayUnitType.DUT_DECIMAL_FEET, DisplayUnitType.DUT_FEET_FRACTIONAL_INCHES);
            Units    units    = new Units(UnitSystem.Imperial);
            UnitType unitType = UnitType.UT_Length;
            string   text     = UnitFormatUtils.Format(units, unitType, doubleLength, true, true);
            int      num2     = text.IndexOf("'");
            string   text2    = text;

            text2 = text2.Remove(num2, text.Length - num2);
            text  = text.Remove(0, num2 + 1).Trim();
            num2  = text.IndexOf("\"");
            string str = text.Remove(num2, text.Length - num2);

            return(text2 + "'" + "-" + str + "\"");
        }
Ejemplo n.º 17
0
 private string FormatBoundedValue(IFCPropertyValue propertyValue)
 {
     if (IFCUnit != null)
     {
         FormatValueOptions formatValueOptions = new FormatValueOptions();
         FormatOptions      specFormatOptions  = IFCImportFile.TheFile.Document.GetUnits().GetFormatOptions(IFCUnit.Spec);
         specFormatOptions.Accuracy = 1e-8;
         if (specFormatOptions.CanSuppressTrailingZeros())
         {
             specFormatOptions.SuppressTrailingZeros = true;
         }
         formatValueOptions.SetFormatOptions(specFormatOptions);
         return(UnitFormatUtils.Format(IFCImportFile.TheFile.Document.GetUnits(), IFCUnit.Spec, propertyValue.AsDouble(), false, formatValueOptions));
     }
     else
     {
         return(propertyValue.ValueAsString());
     }
 }
Ejemplo n.º 18
0
            public static string Validate_Length_TextBox(Document document, System.Windows.Forms.TextBox Tbox, IsZoroAllowed Zero)
            {
                double value;
                Units  units = document.GetUnits();

                if (GetLengthInput(document, Tbox.Text, out value) == false)
                {
                    TaskDialog.Show("Length is Wrong Input", "Type ? to Help");
                    Tbox.Focus();
                }
                if (Zero == IsZoroAllowed.Deny)
                {
                    if (value <= 0)
                    {
                        TaskDialog.Show("No Zero Length is Allowed", "No Zero Length is Allowed \n Type ? to Help");
                        Tbox.Focus();
                    }
                }
                return(Tbox.Text = UnitFormatUtils.Format(units, UnitType.UT_Length, value, false, false));
            }
Ejemplo n.º 19
0
 public void UpdateLengthRepresentation()
 {
     //Check if in Revit context.
     if (_revitDocument != null)
     {
         Units docUnits          = _revitDocument.GetUnits();
         ValueParsingOptions vpo = new ValueParsingOptions();
         vpo.AllowedValues = AllowedValues.NonNegative;
         bool parsRes = UnitFormatUtils.TryParse(docUnits, UnitType.UT_Length,
                                                 LengthModel.LengthRepresentation, vpo, out double output);
         //If parsing succeded
         if (parsRes == true)
         {
             output = output * 12 * 32;
             output = Math.Round(output, 0, MidpointRounding.AwayFromZero);
             output = output / 12 / 32;
             LengthModel.LengthRepresentation = UnitFormatUtils.Format(
                 docUnits, UnitType.UT_Length, output, true, true);
         }
     }
 }
Ejemplo n.º 20
0
 public bool TryFormatLengthToRepresentation()
 {
     try
     {
         if (_revitDocument != null && !double.IsNaN(LengthModel.LengthInDouble))
         {
             Units docUnits = _revitDocument.GetUnits();
             LengthModel.LengthRepresentation = UnitFormatUtils.Format(
                 docUnits, UnitType.UT_Length, LengthModel.LengthInDouble, true, true);
             return(true);
         }
         return(false);
     }
     catch (Exception ex)
     {
         MessageBox.Show("Exeption hander from ParameterEditorViewModel.cs. \r\n" +
                         "TryFormatLengthToRepresentation method,\r\n" +
                         " Exeption message: \r\n\r\n" + ex.Message);
         return(false);
     }
 }
 private void pfClip_KeyUp(object sender, KeyEventArgs e)
 {
     if (e.Key == Key.Return)
     {
         String   pfc          = this.pfClip.Text;
         UnitType clipUnit     = UnitType.UT_Length;
         Units    thisDocUnits = _doc.GetUnits();
         double   userFarClipSetting;
         UnitFormatUtils.TryParse(thisDocUnits, clipUnit, pfc,
                                  out userFarClipSetting);
         if (userFarClipSetting > 0)
         {
             this.pfClip.Text = UnitFormatUtils.Format(thisDocUnits,
                                                       clipUnit, userFarClipSetting, false, false);
         }
         else
         {
             this.pfClip.Text = "8' - 0\"";
         }
     }
 }
Ejemplo n.º 22
0
        override protected void Process(IFCAnyHandle solid)
        {
            base.Process(solid);

            // We will not fail if the direction is not given, but instead assume it to be normal to the swept area.
            IFCAnyHandle direction = IFCImportHandleUtil.GetRequiredInstanceAttribute(solid, "ExtrudedDirection", false);

            if (direction != null)
            {
                Direction = IFCPoint.ProcessNormalizedIFCDirection(direction);
            }
            else
            {
                Direction = XYZ.BasisZ;
            }

            bool found = false;

            Depth = IFCImportHandleUtil.GetRequiredScaledLengthAttribute(solid, "Depth", out found);
            if (found && Depth < 0.0)
            {
                // Reverse depth and orientation.
                if (Application.IsValidThickness(-Depth))
                {
                    Depth     = -Depth;
                    Direction = -Direction;
                    IFCImportFile.TheLog.LogWarning(solid.StepId, "negative extrusion depth is invalid, reversing direction.", false);
                }
            }

            if (!found || !Application.IsValidThickness(Depth))
            {
                string depthAsString = UnitFormatUtils.Format(IFCImportFile.TheFile.Document.GetUnits(), UnitType.UT_Length, Depth,
                                                              true, false);
                IFCImportFile.TheLog.LogError(solid.StepId, "extrusion depth of " + depthAsString + " is invalid, aborting.", true);
            }
        }
Ejemplo n.º 23
0
 private string GetStringFromNumber(Document doc, double number, ForgeTypeId specTypeId)
 {
     return(UnitFormatUtils.Format(doc.GetUnits(), specTypeId, number, false));
 }
Ejemplo n.º 24
0
 public static string FormatLengthNumber(double length, Units units)
 {
     return(UnitFormatUtils.Format(units,
                                   UnitType.UT_Length, length, true, false));
 }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public ObservableCollection <DimensionWrapper> CollectDimensionOverrides()
        {
            var dInstances = new FilteredElementCollector(_doc)
                             .OfClass(typeof(Dimension))
                             .WhereElementIsNotElementType()
                             .Cast <Dimension>();

            // (Konrad) There is a user override in Configuration that controls what dimension overrides are ignored
            var centralPath = FileInfoUtil.GetCentralFilePath(_doc);
            var config      = MissionControlSetup.Configurations.ContainsKey(centralPath)
                ? MissionControlSetup.Configurations[centralPath]
                : null;

            var dimensionValueCheck = new List <string> {
                "EQ"
            };                                                   //defaults

            if (config != null)
            {
                dimensionValueCheck = config.Updaters.First(x => string.Equals(x.UpdaterId,
                                                                               Properties.Resources.HealthReportTrackerGuid, StringComparison.OrdinalIgnoreCase)).UserOverrides.DimensionValueCheck.Values;
            }

            var units = _doc.GetUnits();
            var dims  = new List <DimensionWrapper>();

            foreach (var d in dInstances)
            {
                if (d.NumberOfSegments == 0)
                {
                    if (string.IsNullOrEmpty(d.ValueOverride))
                    {
                        continue;
                    }

                    // dim w/ zero segments
                    dims.Add(new DimensionWrapper(d)
                    {
                        DimensionId   = d.Id,
                        OwnerViewType = d.ViewSpecific
                            ? ((View)_doc.GetElement(d.OwnerViewId)).ViewType.ToString()
                            : string.Empty,
                        OwnerViewId         = d.OwnerViewId,
                        ValueString         = UnitFormatUtils.Format(units, d.DimensionType.UnitType, (double)d.Value, false, false),
                        IsValueOverrideHuge = EvaluateValueOverride(d.ValueOverride, d.Value),
                        IsVisible           = !dimensionValueCheck.Any(d.ValueOverride.Contains),
                        IsFiltered          = dimensionValueCheck.Any(d.ValueOverride.Contains)
                    });
                }
                else
                {
                    // dim w/ multiple segments
                    foreach (DimensionSegment s in d.Segments)
                    {
                        // not every segment has to be overriden
                        if (string.IsNullOrEmpty(s.ValueOverride))
                        {
                            continue;
                        }

                        dims.Add(new DimensionWrapper(s)
                        {
                            DimensionId   = d.Id,
                            OwnerViewType = d.ViewSpecific
                                ? ((View)_doc.GetElement(d.OwnerViewId)).ViewType.ToString()
                                : string.Empty,
                            OwnerViewId         = d.OwnerViewId,
                            ValueString         = UnitFormatUtils.Format(units, d.DimensionType.UnitType, (double)s.Value, false, false),
                            IsValueOverrideHuge = EvaluateValueOverride(s.ValueOverride, s.Value),
                            IsVisible           = !dimensionValueCheck.Any(s.ValueOverride.Contains),
                            IsFiltered          = dimensionValueCheck.Any(s.ValueOverride.Contains)
                        });
                    }
                }
            }

            return(new ObservableCollection <DimensionWrapper>(dims));
        }
Ejemplo n.º 26
0
 private string AsRevitDistanceFormat(double dist)
 {
     return(UnitFormatUtils.Format(_doc.GetUnits(),
                                   UnitType.UT_Length,
                                   dist, false, false));
 }
Ejemplo n.º 27
0
 private string GetStringFromNumber(Document doc, double number, UnitType unitType)
 {
     return(UnitFormatUtils.Format(doc.GetUnits(), unitType, number, true, false));
 }
Ejemplo n.º 28
0
        protected override void Process(IFCAnyHandle ifcCurve)
        {
            base.Process(ifcCurve);

            // We are going to attempt minor repairs for small but reasonable gaps between Line/Line and Line/Arc pairs.  As such, we want to collect the
            // curves before we create the curve loop.

            IList <IFCAnyHandle> segments = IFCAnyHandleUtil.GetAggregateInstanceAttribute <List <IFCAnyHandle> >(ifcCurve, "Segments");

            if (segments == null)
            {
                Importer.TheLog.LogError(Id, "Invalid IfcCompositeCurve with no segments.", true);
            }

            // need List<> so that we can AddRange later.
            List <Curve> curveSegments = new List <Curve>();

            Segments.Clear();

            foreach (IFCAnyHandle segment in segments)
            {
                IFCCurve currCurve = ProcessIFCCompositeCurveSegment(segment);

                if (currCurve != null)
                {
                    Segments.Add(currCurve);

                    if (currCurve.Curve != null)
                    {
                        curveSegments.Add(currCurve.Curve);
                    }
                    else if (currCurve.CurveLoop != null)
                    {
                        foreach (Curve subCurve in currCurve.CurveLoop)
                        {
                            if (subCurve != null)
                            {
                                curveSegments.Add(subCurve);
                            }
                        }
                    }
                }
            }

            int numSegments = curveSegments.Count;

            if (numSegments == 0)
            {
                Importer.TheLog.LogError(Id, "Invalid IfcCompositeCurve with no segments.", true);
            }

            try
            {
                // We are going to try to reverse or tweak segments as necessary to make the CurveLoop.
                // For each curve, it is acceptable if it can be appended to the end of the existing loop, or prepended to its start,
                // possibly after reversing the curve, and possibly with some tweaking.

                // NOTE: we do not do any checks yet to repair the endpoints of the curveloop to make them closed.
                // NOTE: this is not expected to be perfect with dirty data, but is expected to not change already valid data.

                // curveLoopStartPoint and curveLoopEndPoint will change over time as we add new curves to the start or end of the CurveLoop.
                XYZ curveLoopStartPoint = curveSegments[0].GetEndPoint(0);
                XYZ curveLoopEndPoint   = curveSegments[0].GetEndPoint(1);

                double vertexEps = IFCImportFile.TheFile.Document.Application.VertexTolerance;

                // This is intended to be "relatively large".  The idea here is that the user would rather have the information presented
                // than thrown away because of a gap that is architecturally insignificant.
                double gapVertexEps  = Math.Max(vertexEps, 0.01); // 1/100th of a foot, or 3.048 mm.
                double shortCurveTol = IFCImportFile.TheFile.Document.Application.ShortCurveTolerance;

                // canRepairFirst may change over time, as we may potentially add curves to the start of the CurveLoop.
                bool canRepairFirst = (curveSegments[0] is Line);
                for (int ii = 1; ii < numSegments; ii++)
                {
                    XYZ nextStartPoint = curveSegments[ii].GetEndPoint(0);
                    XYZ nextEndPoint   = curveSegments[ii].GetEndPoint(1);

                    // These will be set below.
                    bool   attachNextSegmentToEnd = false;
                    bool   reverseNextSegment     = false;
                    double minGap = 0.0;

                    // Scoped to prevent distLoopEndPtToNextStartPt and others from being used later on.
                    {
                        // Find the minimum gap between the current curve segment and the existing curve loop.  If it is too large, we will give up.
                        double distLoopEndPtToNextStartPt = curveLoopEndPoint.DistanceTo(nextStartPoint);
                        double distLoopEndPtToNextEndPt   = curveLoopEndPoint.DistanceTo(nextEndPoint);

                        double distLoopStartPtToNextEndPt   = curveLoopStartPoint.DistanceTo(nextEndPoint);
                        double distLoopStartPtToNextStartPt = curveLoopStartPoint.DistanceTo(nextStartPoint);

                        // Determine the minimum gap between the two curves.  If it is too large, we'll give up before trying anything.
                        double minStartGap = Math.Min(distLoopStartPtToNextEndPt, distLoopStartPtToNextStartPt);
                        double minEndGap   = Math.Min(distLoopEndPtToNextStartPt, distLoopEndPtToNextEndPt);

                        minGap = Math.Min(minStartGap, minEndGap);

                        // If the minimum distance between the two curves is greater than gapVertexEps (which is the larger of our two tolerances),
                        // we can't fix the issue.
                        if (minGap > gapVertexEps)
                        {
                            string lengthAsString = UnitFormatUtils.Format(IFCImportFile.TheFile.Document.GetUnits(), UnitType.UT_Length, minGap, true, false);
                            string maxGapAsString = UnitFormatUtils.Format(IFCImportFile.TheFile.Document.GetUnits(), UnitType.UT_Length, gapVertexEps, true, false);
                            throw new InvalidOperationException("IfcCompositeCurve contains a gap of " + lengthAsString +
                                                                " that is greater than the maximum gap size of " + maxGapAsString +
                                                                " and cannot be repaired.");
                        }

                        // We have a possibility to add the segment.  What we do depends on the gap distance.

                        // If the current curve loop's closest end to the next segment is its end (vs. start) point, set attachNextSegmentToEnd to true.
                        attachNextSegmentToEnd = (MathUtil.IsAlmostEqual(distLoopEndPtToNextStartPt, minGap)) ||
                                                 (MathUtil.IsAlmostEqual(distLoopEndPtToNextEndPt, minGap));

                        // We need to reverse the next segment if:
                        // 1. We are attaching the next segment to the end of the curve loop, and the next segment's closest end to the current curve loop is its end (vs. start) point.
                        // 2. We are attaching the next segment to the start of the curve loop, and the next segment's closest end to the current curve loop is its start (vs. end) point.
                        reverseNextSegment = (MathUtil.IsAlmostEqual(distLoopEndPtToNextEndPt, minGap)) ||
                                             (MathUtil.IsAlmostEqual(distLoopStartPtToNextStartPt, minGap));
                    }

                    if (reverseNextSegment)
                    {
                        curveSegments[ii] = curveSegments[ii].CreateReversed();
                        MathUtil.Swap <XYZ>(ref nextStartPoint, ref nextEndPoint);
                    }

                    // If minGap is less than vertexEps, we won't need to do any repairing - just fix the orientation if necessary.
                    if (minGap < vertexEps)
                    {
                        if (attachNextSegmentToEnd)
                        {
                            // Update the curve loop end point to be the end point of the next segment after potentially being reversed.
                            curveLoopEndPoint = nextEndPoint;
                        }
                        else
                        {
                            canRepairFirst      = curveSegments[ii] is Line;
                            curveLoopStartPoint = nextStartPoint;

                            // Update the curve loop start point to be the start point of the next segment, now at the beginning of the loop,
                            // after potentially being reversed.
                            Curve tmpCurve = curveSegments[ii];
                            curveSegments.RemoveAt(ii);
                            curveSegments.Insert(0, tmpCurve);
                        }

                        continue;
                    }

                    // The gap is too big for CurveLoop, but smaller than our maximum tolerance - we will try to fix the gap by extending
                    // one of the line segments around the gap.  If the gap is between two Arcs, we will try to introduce a short
                    // segment between them, as long as the gap is larger than the short curve tolerance.

                    bool canRepairNext     = curveSegments[ii] is Line;
                    bool createdRepairLine = false;

                    if (attachNextSegmentToEnd)
                    {
                        // Update the curve loop end point to be the end point of the next segment after potentially being reversed.
                        XYZ originalCurveLoopEndPoint = curveLoopEndPoint;
                        curveLoopEndPoint = nextEndPoint;
                        if (canRepairNext)
                        {
                            curveSegments[ii] = RepairLineAndReport(Id, originalCurveLoopEndPoint, curveLoopEndPoint, minGap);
                        }
                        else if (curveSegments[ii - 1] is Line) // = canRepairCurrent, only used here.
                        {
                            curveSegments[ii - 1] = RepairLineAndReport(Id, curveSegments[ii - 1].GetEndPoint(0), curveSegments[ii].GetEndPoint(0), minGap);
                        }
                        else
                        {
                            // Can't add a line to fix a gap that is smaller than the short curve tolerance.
                            // In the future, we may fix this gap by intersecting the two curves and extending one of them.
                            if (minGap < shortCurveTol + MathUtil.Eps())
                            {
                                Importer.TheLog.LogError(Id, "IfcCompositeCurve contains a gap between two non-linear segments that is too short to be repaired by a connecting segment.", true);
                            }

                            try
                            {
                                Line repairLine = Line.CreateBound(originalCurveLoopEndPoint, curveSegments[ii].GetEndPoint(0));
                                curveSegments.Insert(ii, repairLine);
                                ii++; // Skip the repair line as we've already "added" it and the non-linear segment to our growing loop.
                                numSegments++;
                                createdRepairLine = true;
                            }
                            catch
                            {
                                Importer.TheLog.LogError(Id, "IfcCompositeCurve contains a gap between two non-linear segments that can't be fixed.", true);
                            }
                        }
                    }
                    else
                    {
                        XYZ originalCurveLoopStartPoint = curveLoopStartPoint;
                        curveLoopStartPoint = nextStartPoint;

                        if (canRepairNext)
                        {
                            curveSegments[ii] = RepairLineAndReport(Id, curveLoopStartPoint, originalCurveLoopStartPoint, minGap);
                        }
                        else if (canRepairFirst)
                        {
                            curveSegments[0] = RepairLineAndReport(Id, curveSegments[ii].GetEndPoint(1), curveSegments[0].GetEndPoint(1), minGap);
                        }
                        else
                        {
                            // Can't add a line to fix a gap that is smaller than the short curve tolerance.
                            // In the future, we may fix this gap by intersecting the two curves and extending one of them.
                            if (minGap < shortCurveTol + MathUtil.Eps())
                            {
                                Importer.TheLog.LogError(Id, "IfcCompositeCurve contains a gap between two non-linear segments that is too short to be repaired by a connecting segment.", true);
                            }

                            Line repairLine = Line.CreateBound(curveSegments[ii].GetEndPoint(1), originalCurveLoopStartPoint);
                            curveSegments.Insert(0, repairLine);
                            ii++; // Skip the repair line as we've already "added" it and the non-linear curve to our growing loop.
                            numSegments++;
                        }

                        // Either canRepairFirst was already true, or canRepairNext was true and we added it to the front of the loop,
                        // or we added a short repair line to the front of the loop.  In any of these cases, the front curve segement of the
                        // loop is now a line segment.
                        if (!canRepairFirst && !canRepairNext && !createdRepairLine)
                        {
                            Importer.TheLog.LogError(Id, "IfcCompositeCurve contains a gap between two non-linear segments that can't be fixed.", true);
                        }

                        canRepairFirst = true;

                        // Move the curve to the front of the loop.
                        Curve tmpCurve = curveSegments[ii];
                        curveSegments.RemoveAt(ii);
                        curveSegments.Insert(0, tmpCurve);
                    }
                }

                if (CurveLoop == null)
                {
                    CurveLoop = new CurveLoop();
                }

                foreach (Curve curveSegment in curveSegments)
                {
                    if (curveSegment != null)
                    {
                        CurveLoop.Append(curveSegment);
                    }
                }
            }
            catch (Exception ex)
            {
                Importer.TheLog.LogError(Id, ex.Message, true);
            }

            // Try to create the curve representation of this IfcCompositeCurve
            Curve = ConvertCurveLoopIntoSingleCurve(CurveLoop);
        }
Ejemplo n.º 29
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="stylesId"></param>
        public void PublishData(Document doc, string stylesId)
        {
            try
            {
                _doc = doc;

                #region Text Note Type stats

                var textTypes = new FilteredElementCollector(doc)
                                .OfClass(typeof(TextNoteType))
                                .ToDictionary(x => x.Id.IntegerValue, x => new Tuple <Element, int>(x, 0));

                var textInstances = new FilteredElementCollector(doc)
                                    .OfClass(typeof(TextNote))
                                    .WhereElementIsNotElementType();

                foreach (var t in textInstances)
                {
                    var key = t.GetTypeId().IntegerValue;
                    if (textTypes.ContainsKey(key))
                    {
                        // increment instance count
                        textTypes[key] = new Tuple <Element, int>(textTypes[key].Item1, textTypes[key].Item2 + 1);
                    }
                }

                var textStats = textTypes.Select(x => new TextNoteTypeInfo(x.Value.Item1)
                {
                    Instances = x.Value.Item2
                })
                                .ToList();

                #endregion

                #region Dimension Type stats

                var dimTypes = new FilteredElementCollector(doc)
                               .OfClass(typeof(DimensionType))
                               .Cast <DimensionType>()
                               .Where(x => !string.IsNullOrEmpty(x.get_Parameter(BuiltInParameter.SYMBOL_NAME_PARAM).AsString()))
                               .ToDictionary(x => x.Id.IntegerValue, x => new Tuple <DimensionType, int>(x, 0));

                var dimInstances = new FilteredElementCollector(doc)
                                   .OfClass(typeof(Dimension))
                                   .WhereElementIsNotElementType()
                                   .Cast <Dimension>();

                // (Konrad) There is a user override in Configuration that controls what dimension overrides are ignored
                var centralPath = FileInfoUtil.GetCentralFilePath(doc);
                var config      = MissionControlSetup.Configurations.ContainsKey(centralPath)
                    ? MissionControlSetup.Configurations[centralPath]
                    : null;

                var dimensionValueCheck = new List <string> {
                    "EQ"
                };                                                   //defaults
                if (config != null)
                {
                    dimensionValueCheck = config.Updaters.First(x => string.Equals(x.UpdaterId,
                                                                                   Properties.Resources.HealthReportTrackerGuid, StringComparison.OrdinalIgnoreCase)).UserOverrides.DimensionValueCheck.Values;
                }

                var units           = _doc.GetUnits();
                var dimSegmentStats = new List <DimensionSegmentInfo>();
                foreach (var d in dimInstances)
                {
                    var key = d.GetTypeId().IntegerValue;
                    if (dimTypes.ContainsKey(key))
                    {
                        // increment instance count
                        dimTypes[key] = new Tuple <DimensionType, int>(dimTypes[key].Item1, dimTypes[key].Item2 + 1);
                    }

                    if (d.NumberOfSegments == 0)
                    {
                        if (string.IsNullOrEmpty(d.ValueOverride))
                        {
                            continue;
                        }
                        if (dimensionValueCheck.Any(d.ValueOverride.Contains))
                        {
                            continue;
                        }

                        // dim w/ zero segments
                        dimSegmentStats.Add(new DimensionSegmentInfo(d)
                        {
#if RELEASE2021
                            ValueString = UnitFormatUtils.Format(units, d.DimensionType.GetSpecTypeId(), (double)d.Value, false),
#else
                            ValueString = UnitFormatUtils.Format(units, d.DimensionType.UnitType, (double)d.Value, false, false),
#endif
                            OwnerViewType = d.ViewSpecific
                                ? ((View)doc.GetElement(d.OwnerViewId)).ViewType.ToString()
                                : string.Empty,
                            OwnerViewId = d.OwnerViewId.IntegerValue
                        });
                    }
                    else
                    {
                        // dim w/ multiple segments
                        foreach (DimensionSegment s in d.Segments)
                        {
                            if (string.IsNullOrEmpty(s.ValueOverride))
                            {
                                continue;
                            }
                            if (dimensionValueCheck.Any(s.ValueOverride.Contains))
                            {
                                continue;
                            }

                            dimSegmentStats.Add(new DimensionSegmentInfo(s)
                            {
#if RELEASE2021
                                ValueString = UnitFormatUtils.Format(units, d.DimensionType.GetSpecTypeId(), (double)d.Value, false),
#else
                                ValueString = UnitFormatUtils.Format(units, d.DimensionType.UnitType, (double)d.Value, false, false),
#endif
                                OwnerViewType = d.ViewSpecific
                                    ? ((View)doc.GetElement(d.OwnerViewId)).ViewType.ToString()
                                    : string.Empty,
                                OwnerViewId = d.OwnerViewId.IntegerValue
                            });
                        }
                    }
                }

                var dimStats = dimTypes.Select(x => new DimensionTypeInfo(x.Value.Item1)
                {
                    Instances = x.Value.Item2
                })
                               .ToList();

                #endregion

                #region Line Style stats

                //TODO: Finish this out.

                #endregion

                var stylesStats = new StylesDataItem
                {
                    User            = Environment.UserName.ToLower(),
                    TextStats       = textStats,
                    DimStats        = dimStats,
                    DimSegmentStats = dimSegmentStats
                };

                if (!ServerUtilities.Post(stylesStats, "styles/" + stylesId + "/stylestats",
                                          out StylesDataItem unused))
                {
                    Log.AppendLog(LogMessageType.ERROR, "Failed to publish Styles Data.");
                }
            }
            catch (Exception e)
            {
                Log.AppendLog(LogMessageType.EXCEPTION, e.Message);
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Formats a station value to a string, using the stationing settings in the document.
        /// </summary>
        /// <param name="station">The station value.</param>
        /// <param name="doc">The document for which to format the value.</param>
        /// <returns></returns>
        private string GetStationFormattedValue(double station, Document doc)
        {
            FormatOptions options = doc.GetUnits().GetFormatOptions(SpecTypeId.Stationing);

            return(UnitFormatUtils.Format(doc.GetUnits(), SpecTypeId.Stationing, station, false));
        }