Beispiel #1
0
        public void LoadAnalysisVisualizationValues(IEnumerable <AGCElement> elems, string visualizationName, string schemeName, IList <string> unitNames, IList <double> unitMultipliers)
        {
            var numOfMeasurments = GetMaxNumOfMeasurments(elems);
            var sfm          = GetSpatialFieldManager(numOfMeasurments);
            var resultSchema = new AnalysisResultSchema(schemeName, visualizationName);

            resultSchema.SetUnits(unitNames, unitMultipliers);
            var schemaIdx = sfm.RegisterResult(resultSchema);

            foreach (var elem in elems)
            {
                foreach (var faceVals in elem.FaceUVValues)
                {
                    if (null != faceVals)
                    {
                        var primIdx = sfm.AddSpatialFieldPrimitive(faceVals.Face, Transform.Identity);
                        try {
                            var paramUVs           = new List <UV>();
                            var paramUVValsAtPoint = new List <ValueAtPoint>();
                            foreach (var vals in faceVals)
                            {
                                paramUVs.Add(vals.Key);
                                paramUVValsAtPoint.Add(new ValueAtPoint(vals.Value));
                            }
                            var domPts    = new FieldDomainPointsByUV(paramUVs);
                            var fieldVals = new FieldValues(paramUVValsAtPoint);
                            sfm.UpdateSpatialFieldPrimitive(primIdx, domPts, fieldVals, schemaIdx);
                        } catch (Exception x) {
                            sfm.RemoveSpatialFieldPrimitive(primIdx);
                            GCLogger.AppendLine("Failed to add face values: {0}, {1}", x.Message, x.StackTrace);
                        }
                    }
                }
            }
        }
Beispiel #2
0
        public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            ExternalCommandData cdata = commandData;

            Autodesk.Revit.ApplicationServices.Application app = commandData.Application.Application;
            Document   doc   = commandData.Application.ActiveUIDocument.Document;
            UIDocument uiDoc = commandData.Application.ActiveUIDocument;

            Transaction trans = new Transaction(doc, "Revit.SDK.Samples.AnalysisVisualizationFramework");

            trans.Start();

            SpatialFieldManager sfm = SpatialFieldManager.GetSpatialFieldManager(doc.ActiveView);

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

            IList <Reference> refList = new List <Reference>();

            refList = uiDoc.Selection.PickObjects(Autodesk.Revit.UI.Selection.ObjectType.Face);
            foreach (Reference reference in refList)
            {
                IList <UV> uvPts = new List <UV>();

                List <double>        doubleList = new List <double>();
                IList <ValueAtPoint> valList    = new List <ValueAtPoint>();
                Face          face = doc.GetElement(reference).GetGeometryObjectFromReference(reference) as Face;
                BoundingBoxUV bb   = face.GetBoundingBox();
                UV            min  = bb.Min;
                UV            max  = bb.Max;

                for (double u = min.U; u < max.U; u += (max.U - min.U) / 10)
                {
                    for (double v = min.V; v < max.V; v += (max.V - min.V) / 10)
                    {
                        UV uv = new UV(u, v);
                        if (face.IsInside(uv))
                        {
                            uvPts.Add(uv);
                            doubleList.Add(v + DateTime.Now.Second);
                            valList.Add(new ValueAtPoint(doubleList));
                            doubleList.Clear();
                        }
                    }
                }

                FieldDomainPointsByUV pnts = new FieldDomainPointsByUV(uvPts);
                FieldValues           vals = new FieldValues(valList);
                int idx = sfm.AddSpatialFieldPrimitive(reference);
                AnalysisResultSchema resultSchema = new AnalysisResultSchema("Schema 1", "Schema 1 Description");
                sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, sfm.RegisterResult(resultSchema));
            }



            trans.Commit();
            return(Result.Succeeded);
        }
Beispiel #3
0
        /// <summary>
        ///   Updating results on the surface being analyzed
        /// </summary>
        /// <remarks>
        ///   This is called periodically by the Idling event
        ///   until there is no more results to be updated.
        /// </remarks>
        /// <returns>
        ///   Returns True if there is still more to be processed.
        /// </returns>
        public bool UpdateResults()
        {
            // If we still need to initialize the result manager
            // it means we were interrupted and we restarted.
            // Therefore we know we do not have any results to pick up.
            // Instead, we initialize the manager and start a new calculation.
            // We will have first results from this new calculation process
            // next time we get called here.

            if (m_needInitialization)
            {
                Initialize();
                return(StartCalculation());
            }

            // We aks the Result instance if there are results available
            // The methods returns True only if there has been results added
            // since the last time we called that method.

            IList <UV>           points;
            IList <ValueAtPoint> values;

            if (m_results.GetResults(out points, out values))
            {
                FieldDomainPointsByUV fieldPoints = new FieldDomainPointsByUV(points);
                FieldValues           fieldValues = new FieldValues(values);
                m_SFManager.UpdateSpatialFieldPrimitive(m_fieldId, fieldPoints, fieldValues, m_schemaId);
            }

            // if the thread is not around anymore to result more data,
            // it means the analysis is finished for the FaceAnalyzer too.

            return((m_threadAgent != null) && (m_threadAgent.IsThreadAlive));
        }
Beispiel #4
0
        public void PaintSolid(Document doc, Solid s, double value)
        {
            int schemaId = -1;
            var rnd      = new Random();

            View view = doc.ActiveView;

            using (Transaction transaction = new Transaction(doc))
            {
                if (transaction.Start("Create model curves") == TransactionStatus.Started)
                {
                    if (view.AnalysisDisplayStyleId == ElementId.InvalidElementId)
                    {
                        CreateAVFDisplayStyle(doc, view);
                    }

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

                    if (-1 != schemaId)
                    {
                        IList <int> results = sfm.GetRegisteredResults();
                        if (!results.Contains(schemaId))
                        {
                            schemaId = -1;
                        }
                    }
                    if (-1 == schemaId)
                    {
                        AnalysisResultSchema resultSchema1 = new AnalysisResultSchema(rnd.Next().ToString(), "Description");
                        schemaId = sfm.RegisterResult(resultSchema1);
                    }

                    FaceArray faces = s.Faces;
                    Transform trf   = Transform.Identity;
                    foreach (Face face in faces)
                    {
                        int                  idx        = sfm.AddSpatialFieldPrimitive(face, trf);
                        IList <UV>           uvPts      = new List <UV>();
                        List <double>        doubleList = new List <double>();
                        IList <ValueAtPoint> valList    = new List <ValueAtPoint>();
                        BoundingBoxUV        bb         = face.GetBoundingBox();
                        uvPts.Add(bb.Min);
                        doubleList.Add(value);
                        valList.Add(new ValueAtPoint(doubleList));

                        FieldDomainPointsByUV pnts = new FieldDomainPointsByUV(uvPts);

                        FieldValues vals = new FieldValues(valList);
                        sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, schemaId);
                    }
                    transaction.Commit();
                }
            }
        }
Beispiel #5
0
        internal static void ShowSolids(Document doc, IEnumerable <Solid> solids, IEnumerable <double> values)
        {
            SpatialFieldManager sfm = SpatialFieldManager.GetSpatialFieldManager(doc.ActiveView);

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


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

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

            if (_SchemaId == -1)
            {
                _SchemaId = registerResults(sfm, "ShowChanges", "Description");
            }

            List <double> valueList = values.ToList();
            int           i         = 0;

            foreach (Solid s in solids)
            {
                double value = valueList[i];
                i++;
                FaceArray faces = s.Faces;
                Transform trf   = Transform.Identity;

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

                    IList <UV>           uvPts      = new List <UV>();
                    List <double>        doubleList = new List <double>();
                    IList <ValueAtPoint> valList    = new List <ValueAtPoint>();
                    BoundingBoxUV        bb         = face.GetBoundingBox();
                    uvPts.Add(bb.Min);
                    doubleList.Add(value);
                    valList.Add(new ValueAtPoint(doubleList));
                    FieldDomainPointsByUV pnts = new FieldDomainPointsByUV(uvPts);
                    FieldValues           vals = new FieldValues(valList);

                    sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, _SchemaId);
                }
            }

            updateView(doc.ActiveView, StyleEnum.Faces);
        }
Beispiel #6
0
        /// <summary>
        /// Calculate and paint the attenuation
        /// values on the given face.
        /// </summary>
        public static void PaintFace(
            Face face,
            XYZ psource,
            AttenuationCalculator calc)
        {
            IList <UV>           uvPts    = new List <UV>();
            IList <ValueAtPoint> uvValues = new List <ValueAtPoint>();

            BoundingBoxUV bb = face.GetBoundingBox();

            double umin  = bb.Min.U;
            double umax  = bb.Max.U;
            double ustep = 0.2 * (umax - umin);

            double vmin  = bb.Min.V;
            double vmax  = bb.Max.V;
            double vstep = 0.2 * (vmax - vmin);

            List <double> vals = new List <double>(1);

            vals.Add(0);

            XYZ psource2 = psource + _z_offset;

            for (double u = umin; u <= umax; u += ustep)
            {
                for (double v = vmin; v <= vmax; v += vstep)
                {
                    UV uv = new UV(u, v);

                    if (face.IsInside(uv))
                    {
                        uvPts.Add(uv);

                        XYZ ptarget = face.Evaluate(uv)
                                      + _z_offset;

                        vals[0] = calc.Attenuation(
                            psource2, ptarget);

                        uvValues.Add(new ValueAtPoint(vals));
                    }
                }
            }

            FieldDomainPointsByUV fpts
                = new FieldDomainPointsByUV(uvPts);

            FieldValues fvals = new FieldValues(uvValues);

            _sfm.UpdateSpatialFieldPrimitive(
                _sfp_index, fpts, fvals, _schemaId);
        }
        public void CreateAnalysisSurface(UIDocument uiDoc, SpatialFieldManager sfm)
        {
            var idx          = sfm.AddSpatialFieldPrimitive(Reference);
            var points       = new FieldDomainPointsByUV(pointsUV);
            var fieldValues  = new FieldValues(valList);
            var resultSchema = new AnalysisResultSchema(name, name);
            var schemaIndex  = sfm.RegisterResult(resultSchema);

            try {
                sfm.UpdateSpatialFieldPrimitive(idx, points, fieldValues, schemaIndex);
            } catch {
                ////FIXME. don't catch nothing...
            }
        }
Beispiel #8
0
        public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            ExternalCommandData cdata = commandData;
             Autodesk.Revit.ApplicationServices.Application app = commandData.Application.Application;
             Document doc = commandData.Application.ActiveUIDocument.Document;
             UIDocument uiDoc = commandData.Application.ActiveUIDocument;

             SpatialFieldManager sfm = SpatialFieldManager.GetSpatialFieldManager(doc.ActiveView);
             if (sfm == null) sfm = SpatialFieldManager.CreateSpatialFieldManager(doc.ActiveView, 1);

             IList<Reference> refList = new List<Reference>();
             refList = uiDoc.Selection.PickObjects(Autodesk.Revit.UI.Selection.ObjectType.Face);
                 foreach (Reference reference in refList)
                 {

                         IList<UV> uvPts = new List<UV>();

                         List<double> doubleList = new List<double>();
                         IList<ValueAtPoint> valList = new List<ValueAtPoint>();
                         Face face = doc.GetElement(reference).GetGeometryObjectFromReference(reference)as Face;
                         BoundingBoxUV bb = face.GetBoundingBox();
                         UV min = bb.Min;
                         UV max = bb.Max;

                         for (double u = min.U; u < max.U; u += (max.U - min.U) / 10)
                         {
                             for (double v = min.V; v < max.V; v += (max.V - min.V) / 10)
                             {
                                 UV uv = new UV(u, v);
                                 if (face.IsInside(uv))
                                 {
                                     uvPts.Add(uv);
                                     doubleList.Add(v + DateTime.Now.Second);
                                     valList.Add(new ValueAtPoint(doubleList));
                                     doubleList.Clear();
                                 }
                             }
                         }

                         FieldDomainPointsByUV pnts = new FieldDomainPointsByUV(uvPts);
                         FieldValues vals = new FieldValues(valList);
                         int idx = sfm.AddSpatialFieldPrimitive(reference);
                         AnalysisResultSchema resultSchema = new AnalysisResultSchema("Schema 1", "Schema 1 Description");
                         sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, sfm.RegisterResult(resultSchema));
                 }

             return Result.Succeeded;
        }
Beispiel #9
0
        /// <summary>
        /// This method creates points from the space syntax meta data and maps the cell
        /// indices value to those points.
        /// Note: If the provided face was aquired by user selection, the face.Reference is null,
        /// and the Reference, which is returned by the selection must be passed to this method.
        /// </summary>
        /// <param name="doc">the document of the active view</param>
        /// <param name="spaceSyntax">the object parsed from xml</param>
        /// <param name="face">the face of the a floor on which it i</param>
        /// <param name="faceReference">the reference to the face</param>
        /// <returns>whether the computation succeeded or was</returns>
        public static void CreateSpaceSyntaxAnalysisResult(Document doc, SpaceSyntax spaceSyntax, Face face, Reference faceReference)
        {
            SpatialFieldManager sfm = SpatialFieldManager.GetSpatialFieldManager(doc.ActiveView);

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

            var uvPts      = new List <UV>();
            var doubleList = new List <double>();
            var valList    = new List <ValueAtPoint>();

            // we map u to x and v to y
            var localOriginInGlobalVector = face.Evaluate(new UV(0.0, 0.0));
            var matrixAInverted           = CalculateMatrixForGlobalToLocalCoordinateSystem(face);

            double deltaX = Math.Abs(spaceSyntax.MinX - spaceSyntax.MaxX) / spaceSyntax.DomainColumns;
            double deltaY = Math.Abs(spaceSyntax.MinY - spaceSyntax.MaxY) / spaceSyntax.DomainRows;

            double minX = spaceSyntax.MinX + deltaX / 2.0;
            double minY = spaceSyntax.MinY + deltaY / 2.0;

            for (double y = minY, i = 1.0; y < spaceSyntax.MaxY; y += deltaY, i += 1.0)
            {
                for (double x = minX, j = 1.0; x < spaceSyntax.MaxX; x += deltaX, j += 1.0)
                {
                    var globalPoint = new XYZ(x, y, 0.0); // z-coordinate is irrelevant, since the UV space is parallel
                    var localUV     = GlobalToLocalCoordinate(matrixAInverted, localOriginInGlobalVector, globalPoint);

                    if (face.IsInside(localUV))
                    {
                        uvPts.Add(localUV);
                        doubleList.Add(GetValueFromSpaceSyntax(spaceSyntax, (int)j, (int)i));
                        valList.Add(new ValueAtPoint(doubleList));
                        doubleList.Clear();
                    }
                }
            }

            var points = new FieldDomainPointsByUV(uvPts);
            var values = new FieldValues(valList);
            int index  = sfm.AddSpatialFieldPrimitive(faceReference);

            var resultSchema = CreateResultSchemaWithUnitNames();

            sfm.UpdateSpatialFieldPrimitive(index, points, values, sfm.RegisterResult(resultSchema));
        }
        /// <summary>
        /// Paint solid by AVF
        /// </summary>
        /// <param name="solid">Solid to be painted</param>
        /// <param name="view">The view that shows solid</param>
        private void PaintSolid(Solid solid, View view)
        {
            String viewName         = view.Name;
            SpatialFieldManager sfm = SpatialFieldManager.GetSpatialFieldManager(view);

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

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

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

            // set up the display style
            if (m_schemaId == -1)
            {
                AnalysisResultSchema resultSchema1 = new AnalysisResultSchema("PaintedSolid " + viewName, "Description");

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

                resultSchema1.AnalysisDisplayStyleId = displayStyle.Id;

                m_schemaId = sfm.RegisterResult(resultSchema1);
            }

            // get points of all faces in the solid
            FaceArray faces = solid.Faces;
            Transform trf   = Transform.Identity;

            foreach (Face face in faces)
            {
                int                  idx     = sfm.AddSpatialFieldPrimitive(face, trf);
                IList <UV>           uvPts   = null;
                IList <ValueAtPoint> valList = null;
                ComputeValueAtPointForFace(face, out uvPts, out valList, 1);

                FieldDomainPointsByUV pnts = new FieldDomainPointsByUV(uvPts);
                FieldValues           vals = new FieldValues(valList);
                sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, m_schemaId);
            }
        }
        InternalSetSpatialFieldValues(int primitiveId, ISurfaceData <Autodesk.DesignScript.Geometry.UV,
                                                                     double> data, string schemaName, string description, Type unitType)
        {
            // Get the surface reference
            var reference = data.Surface.Tags.LookupTag(DefaultTag) as Reference;

            var el             = DocumentManager.Instance.CurrentDBDocument.GetElement(reference.ElementId);
            var pointLocations = new List <UV>();

            if (el != null)
            {
                var face = el.GetGeometryObjectFromReference(reference) as Autodesk.Revit.DB.Face;
                if (face != null)
                {
                    foreach (var loc in data.ValueLocations)
                    {
                        var pt      = data.Surface.PointAtParameter(loc.U, loc.V);
                        var faceLoc = face.Project(pt.ToXyz()).UVPoint;
                        pointLocations.Add(faceLoc);
                    }
                }
            }

            var valList = data.Values.Select(v => new ValueAtPoint(new List <double>()
            {
                v
            }));

            TransactionManager.Instance.EnsureInTransaction(Document);

            // Convert the analysis values to a special Revit type
            //var valList = enumerable.Select(n => new ValueAtPoint(n.ToList())).ToList();
            var sampleValues = new FieldValues(valList.ToList());

            // Convert the sample points to a special Revit Type
            var samplePts = new FieldDomainPointsByUV(pointLocations.ToList());

            // Get the analysis results schema
            var schemaIndex = GetAnalysisResultSchemaIndex(schemaName, description, unitType);

            // Update the values
            SpatialFieldManager.UpdateSpatialFieldPrimitive(primitiveId, samplePts, sampleValues, schemaIndex);

            TransactionManager.Instance.TransactionTaskDone();
        }
Beispiel #12
0
        public static void PaintSolid(Document doc, Solid solid, double value)
        {
            Autodesk.Revit.DB.View view = doc.ActiveView;

            if (view.AnalysisDisplayStyleId == ElementId.InvalidElementId)
            {
                CreateAVFDisplayStyle(doc, view);
            }

            SpatialFieldManager sfm = SpatialFieldManager.GetSpatialFieldManager(view);

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

            IList <int> results = sfm.GetRegisteredResults();

            AnalysisResultSchema resultSchema1 = new AnalysisResultSchema("PaintedSolid2", "Description");
            int schemaId = sfm.RegisterResult(resultSchema1);

            foreach (Face face in solid.Faces)
            {
                int idx = sfm.AddSpatialFieldPrimitive(face, Transform.Identity);

                IList <UV>           uvPts      = new List <UV>();
                List <double>        doubleList = new List <double>();
                IList <ValueAtPoint> valList    = new List <ValueAtPoint>();
                BoundingBoxUV        bb         = face.GetBoundingBox();
                uvPts.Add(bb.Min);
                doubleList.Add(value);
                valList.Add(new ValueAtPoint(doubleList));
                FieldDomainPointsByUV pnts = new FieldDomainPointsByUV(uvPts);
                FieldValues           vals = new FieldValues(valList);

                sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, schemaId);
            }

            //   UIDocument uidoc = new UIDocument(doc);
            //uidoc.RefreshActiveView();
        }
Beispiel #13
0
        /// <summary>
        /// Set the spatial field values for the current spatial field primitive.  The two
        /// input sequences should be of the same length.
        /// </summary>
        /// <param name="pointLocations"></param>
        /// <param name="values"></param>
        private void InternalSetSpatialFieldValues(IEnumerable <UV> pointLocations, IEnumerable <double> values)
        {
            TransactionManager.Instance.EnsureInTransaction(Document);

            // Convert the analysis values to a special Revit type
            var valList = values.Select(n => new ValueAtPoint(new List <double> {
                n
            })).ToList();
            var sampleValues = new FieldValues(valList);

            // Convert the sample points to a special Revit Type
            var samplePts = new FieldDomainPointsByUV(pointLocations.ToList <UV>());

            // Get the analysis results schema
            var schemaIndex = GetAnalysisResultSchemaIndex();

            // Update the values
            SpatialFieldManager.UpdateSpatialFieldPrimitive(SpatialFieldPrimitiveId, samplePts, sampleValues, schemaIndex);

            TransactionManager.Instance.TransactionTaskDone();
        }
Beispiel #14
0
        public static void UpdateCO2eVisualization(SpatialFieldManager sfm, Element element)
        {
            try
            {
                logger.InfoFormat("Adding CO2e Analysis for element: {0}", element.Name);
                double CO2eForElement = 0;
                if (element.ParametersMap.Contains("CO2e"))
                {
                    CO2eForElement = element.ParametersMap.get_Item("CO2e").AsDouble();
                }

                int count = 0;
                foreach (Face face in GetFaces(element))
                {
                    var idx = sfm.AddSpatialFieldPrimitive(face.Reference);

                    IList<UV> uvPts = new List<UV>();
                    IList<ValueAtPoint> valList = new List<ValueAtPoint>();
                    var bb = face.GetBoundingBox();
                    AddMeasurement(CO2eForElement, bb.Min.U, bb.Min.V, uvPts, valList);
                    AddMeasurement(CO2eForElement, bb.Min.U, bb.Max.V, uvPts, valList);
                    AddMeasurement(CO2eForElement, bb.Max.U, bb.Max.V, uvPts, valList);
                    AddMeasurement(CO2eForElement, bb.Max.U, bb.Min.V, uvPts, valList);

                    logger.DebugFormat("elementId: {0}, face: {1}, spf idx: {2}, bounding box: {3},{4},{5},{6}", element.Id.IntegerValue, count, idx, bb.Min.U, bb.Min.V, bb.Max.U, bb.Max.V);

                    var pnts = new FieldDomainPointsByUV(uvPts);
                    var vals = new FieldValues(valList);

                    var resultSchema1 = new AnalysisResultSchema("CO2e schema", "AMEE CO2e schema");

                    sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, GetFirstRegisteredResult(sfm, resultSchema1));
                    count++;
                }
            }
            catch (Exception e)
            {
                logger.Error(e);
            }
        }
        public static void UpdateCO2eVisualization(SpatialFieldManager sfm, Element element)
        {
            try
            {
                logger.InfoFormat("Adding CO2e Analysis for element: {0}", element.Name);
                double CO2eForElement = 0;
                if (element.ParametersMap.Contains("CO2e"))
                {
                    CO2eForElement = element.ParametersMap.get_Item("CO2e").AsDouble();
                }

                int count = 0;
                foreach (Face face in GetFaces(element))
                {
                    var idx = sfm.AddSpatialFieldPrimitive(face.Reference);

                    IList <UV>           uvPts   = new List <UV>();
                    IList <ValueAtPoint> valList = new List <ValueAtPoint>();
                    var bb = face.GetBoundingBox();
                    AddMeasurement(CO2eForElement, bb.Min.U, bb.Min.V, uvPts, valList);
                    AddMeasurement(CO2eForElement, bb.Min.U, bb.Max.V, uvPts, valList);
                    AddMeasurement(CO2eForElement, bb.Max.U, bb.Max.V, uvPts, valList);
                    AddMeasurement(CO2eForElement, bb.Max.U, bb.Min.V, uvPts, valList);

                    logger.DebugFormat("elementId: {0}, face: {1}, spf idx: {2}, bounding box: {3},{4},{5},{6}", element.Id.IntegerValue, count, idx, bb.Min.U, bb.Min.V, bb.Max.U, bb.Max.V);

                    var pnts = new FieldDomainPointsByUV(uvPts);
                    var vals = new FieldValues(valList);

                    var resultSchema1 = new AnalysisResultSchema("CO2e schema", "AMEE CO2e schema");

                    sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, GetFirstRegisteredResult(sfm, resultSchema1));
                    count++;
                }
            }
            catch (Exception e)
            {
                logger.Error(e);
            }
        }
Beispiel #16
0
        /// <summary>
        /// Paint solid by AVF
        /// </summary>
        /// <param name="solid">Solid to be painted</param>
        /// <param name="view">The view that shows solid</param>
        private void PaintSolid(Solid solid, View view)
        {
            String viewName = view.Name;
            SpatialFieldManager sfm = SpatialFieldManager.GetSpatialFieldManager(view);
            if (sfm == null) sfm = SpatialFieldManager.CreateSpatialFieldManager(view, 1);

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

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

            // set up the display style
            if (m_schemaId == -1)
            {
                AnalysisResultSchema resultSchema1 = new AnalysisResultSchema("PaintedSolid " + viewName, "Description");

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

                resultSchema1.AnalysisDisplayStyleId = displayStyle.Id;

                m_schemaId = sfm.RegisterResult(resultSchema1);
            }

            // get points of all faces in the solid
            FaceArray faces = solid.Faces;
            Transform trf = Transform.Identity;
            foreach (Face face in faces)
            {
                int idx = sfm.AddSpatialFieldPrimitive(face, trf);
                IList<UV> uvPts = null;
                IList<ValueAtPoint> valList = null;
                ComputeValueAtPointForFace(face, out uvPts, out valList, 1);

                FieldDomainPointsByUV pnts = new FieldDomainPointsByUV(uvPts);
                FieldValues vals = new FieldValues(valList);
                sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, m_schemaId);
            }
        }
        public bool VisualizeData()
        {
            bool result = false;

            try
            {
                string    viewIdValue       = RegistryKeyManager.GetRegistryKeyValue("RevitOutgoingViewId");
                ElementId viewId            = new ElementId(int.Parse(viewIdValue));
                Autodesk.Revit.DB.View view = m_doc.GetElement(viewId) as Autodesk.Revit.DB.View;
                if (null != view)
                {
                    SpatialFieldManager sfm = SpatialFieldManager.GetSpatialFieldManager(view);
                    if (null == sfm)
                    {
                        sfm = SpatialFieldManager.CreateSpatialFieldManager(view, 1);
                    }
                    AnalysisResultSchema resultSchema = new AnalysisResultSchema(analysisType.ToString(), "Imported from DIVA");

                    int resultIndex = -1;

                    //check order
                    DataContainer      tempContainer = dataDictionary[0];
                    XYZ                node          = new XYZ(tempContainer.Node.XValue, tempContainer.Node.YValue, tempContainer.Node.ZValue);
                    IntersectionResult intersection  = displayingFaces[0].Project(node);
                    if (null == intersection)
                    {
                        displayingFaces.Reverse();
                    }                                                        //reverse the order of faces

                    foreach (int keyIndex in dataDictionary.Keys)
                    {
                        DataContainer container = dataDictionary[keyIndex];
                        Face          face      = displayingFaces[keyIndex];
                        List <double> dblList   = new List <double>();
                        dblList.Add(container.ResultValue);

                        XYZ                  vectorZ   = new XYZ(0, 0, -1);
                        Transform            transform = Transform.CreateTranslation(vectorZ);
                        int                  index     = sfm.AddSpatialFieldPrimitive(face, transform);
                        IList <UV>           uvPts     = new List <UV>();
                        IList <ValueAtPoint> valList   = new List <ValueAtPoint>();

                        XYZ nodePoint = new XYZ(container.Node.XValue, container.Node.YValue, container.Node.ZValue);
                        IntersectionResult intersect = face.Project(nodePoint);
                        if (null != intersect)
                        {
                            UV nodeUV = intersect.UVPoint;
                            uvPts.Add(nodeUV);
                            valList.Add(new ValueAtPoint(dblList));

                            FieldDomainPointsByUV domainPoints = new FieldDomainPointsByUV(uvPts);
                            FieldValues           values       = new FieldValues(valList);

                            FieldValues vals = new FieldValues(valList);

                            if (resultIndex == -1)
                            {
                                resultIndex = sfm.RegisterResult(resultSchema);
                            }
                            else
                            {
                                sfm.SetResultSchema(resultIndex, resultSchema);
                            }

                            sfm.UpdateSpatialFieldPrimitive(index, domainPoints, values, resultIndex);
                        }

                        result = true;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to visualize the result data.\n" + ex.Message, "Analysis Data Manager - Visualize Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                result = false;
            }
            return(result);
        }
Beispiel #18
0
            /// <summary>
            /// The idling callback which adds data to the AVF results.
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            public void UpdateWhileIdling(object sender, IdlingEventArgs e)
            {
                UIApplication uiApp = sender as UIApplication;

                // Get SpatialFieldManager
                SpatialFieldManager sfm = SpatialFieldManager.GetSpatialFieldManager(uiApp.ActiveUIDocument.Document.ActiveView);
                if (sfm == null) sfm = SpatialFieldManager.CreateSpatialFieldManager(uiApp.ActiveUIDocument.Document.ActiveView, 1);

                // If stopping, clear results and unset event.
                if (m_stop)
                {
                    lock (results)
                    {
                        results.Clear();
                    }
                    uiApp.Idling -= UpdateWhileIdling;
                    return;
                }

                // If document was closed and new document opened, do not run the update.
                if (uiApp.ActiveUIDocument.Document.PathName == m_docName)
                {
                    // Lock access to current calculated results
                    lock (results)
                    {
                        if (results.Count == 0) return;

                        // Turn each result to an AVF ValueAtPoint
                        foreach (ResultsData rData in results)
                        {
                            uvPts.Add(new UV(rData.UV.U, rData.UV.V));
                            IList<double> doubleList = new List<double>();
                            doubleList.Add(rData.Value);
                            valList.Add(new ValueAtPoint(doubleList));
                        }
                        FieldDomainPointsByUV pntsByUV = new FieldDomainPointsByUV(uvPts);
                        FieldValues fieldValues = new FieldValues(valList);

                        // Update with calculated values
                        Transaction t = new Transaction(uiApp.ActiveUIDocument.Document);
                        t.SetName("AVF");
                        t.Start();
                        if (!m_stop)
                            sfm.UpdateSpatialFieldPrimitive(s_spatialFieldId, pntsByUV, fieldValues);
                        t.Commit();

                        // Clear results already processed.
                        results.Clear();

                        // If no more results to process, remove the idling event
                        if (m_uvToCalculateCount == 0)
                        {
                            uiApp.Idling -= UpdateWhileIdling;
                            s_oldViewId = s_activeViewId;
                            s_oldSpatialFieldId = s_spatialFieldId;
                        }
                    }
                }
            }
        /// <summary>
        /// Paint a solid in a new named view
        /// </summary>
        /// <param name="s">solid</param>
        /// <param name="viewName">Given the name of view</param>
        public void PaintSolid(Solid s, String viewName)
        {
            View view;

            if (!viewNameList.Contains(viewName))
            {
                view      = m_doc.Create.NewView3D(new XYZ(1, 1, 1));
                view.Name = viewName;
                viewNameList.Add(viewName);
            }
            else
            {
                view = (((new FilteredElementCollector(m_doc).
                          OfClass(typeof(View))).Cast <View>()).
                        Where(e => e.Name == viewName)).First <View>();
            }

            SpatialFieldManager sfm = SpatialFieldManager.GetSpatialFieldManager(view);

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

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

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

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

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

                resultSchema1.AnalysisDisplayStyleId = displayStyle.Id;

                SchemaId = sfm.RegisterResult(resultSchema1);
            }

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

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

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

                FieldDomainPointsByUV pnts = new FieldDomainPointsByUV(uvPts);

                FieldValues vals = new FieldValues(valList);

                sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, SchemaId);
            }
        }
Beispiel #20
0
        public override Value Evaluate(FSharpList<Value> args)
        {
            this.ClearPreviousResults();
            SpatialFieldManager = ((Value.Container)args[2]).Item as Autodesk.Revit.DB.Analysis.SpatialFieldManager;

            var reference = (args[3] as Value.Container).Item as Reference;
            var face = (reference == null) ?
                ((args[3] as Value.Container).Item as Face) :
                dynRevitSettings.Doc.Document.GetElement(reference).GetGeometryObjectFromReference(reference) as Face;

            //if we received a face instead of a reference
            //then use the reference from the face
            if (reference == null && face != null)
                reference = face.Reference;

            if (reference == null)
                throw new Exception("Could not resolved a referenced for the face.");

            int idx = SpatialFieldManager.AddSpatialFieldPrimitive(reference);

            //unwrap the sample locations
            IEnumerable<UV> pts = ((Value.List)args[1]).Item.Select(
               x => (UV)((Value.Container)x).Item
            );
            var samplePts = new FieldDomainPointsByUV(pts.ToList<UV>());

            //unwrap the values
            IEnumerable<double> nvals = ((Value.List)args[0]).Item.Select(
               x => (double)((Value.Number)x).Item
            );

            //for every sample location add a list
            //of valueatpoint objects. for now, we only
            //support one value per point
            IList<ValueAtPoint> valList = nvals.Select(n => new ValueAtPoint(new List<double> {n})).ToList();
            var sampleValues = new FieldValues(valList);

            int schemaIndex = 0;
            if (!SpatialFieldManager.IsResultSchemaNameUnique(DYNAMO_ANALYSIS_RESULTS_NAME, -1))
            {
                IList<int> arses = SpatialFieldManager.GetRegisteredResults();
                foreach (int i in arses)
                {
                    AnalysisResultSchema arsTest = SpatialFieldManager.GetResultSchema(i);
                    if (arsTest.Name == DYNAMO_ANALYSIS_RESULTS_NAME)
                    {
                        schemaIndex = i;
                        break;
                    }
                }
            }
            else
            {
                var ars = new AnalysisResultSchema(DYNAMO_ANALYSIS_RESULTS_NAME, "Resulting analyses from Dynamo.");
                schemaIndex = SpatialFieldManager.RegisterResult(ars);
            }

            SpatialFieldManager.UpdateSpatialFieldPrimitive(idx, samplePts, sampleValues, schemaIndex);

            PastResultIds.Add(idx);

            return Value.NewContainer(idx);
        }
        private bool AnalysisByFaces(SpatialFieldManager sfm)
        {
            bool result = false;

            progressBar.Maximum = settings.SelectedElements.Count;
            try
            {
                Options options = new Options();
                options.ComputeReferences = true;

                Dictionary <ElementId, Dictionary <Reference, Face> > selectedFaces = new Dictionary <ElementId, Dictionary <Reference, Face> >();
                selectedFaces = settings.SelectedFaces;

                Dictionary <Face, Dictionary <Reference, List <double> /*paramValues*/> > faceDictionary = new Dictionary <Face, Dictionary <Reference, List <double> /*paramValues*/> >();
                foreach (Element element in settings.SelectedElements)
                {
                    ElementId elementId = element.Id;
                    if (!selectedFaces.ContainsKey(elementId))
                    {
                        continue;
                    }

                    List <double> valueLists = new List <double>();
                    foreach (string paramName in settings.Configurations.Keys)
                    {
#if RELEASE2015 || RELEASE2016 || RELEASE2017
                        Parameter param = element.LookupParameter(paramName);
#else
                        Parameter param = element.get_Parameter(paramName);
#endif

                        if (param != null)
                        {
                            double value = param.AsDouble();
                            valueLists.Add(value);
                        }
                        else
                        {
                            valueLists.Add(0);
                        }
                    }

                    foreach (Reference reference in selectedFaces[elementId].Keys)
                    {
                        if (null != selectedFaces[elementId][reference] && valueLists.Count == settings.NumberOfMeasurement)
                        {
                            Face face = selectedFaces[elementId][reference];
                            faceDictionary.Add(face, new Dictionary <Reference, List <double> >());
                            faceDictionary[face].Add(reference, valueLists);
                            //break;
                        }
                    }
                    progressBar.PerformStep();
                }

                int  resultIndex = FindIndexOfResult(sfm);
                bool firstLoop   = true;
                foreach (Face face in faceDictionary.Keys)
                {
                    Reference     reference = faceDictionary[face].Keys.First();
                    List <double> dblList   = new List <double>();//double values to be displayed on the face.
                    dblList = faceDictionary[face][reference];
                    int                  index   = sfm.AddSpatialFieldPrimitive(reference);
                    IList <UV>           uvPts   = new List <UV>();
                    IList <ValueAtPoint> valList = new List <ValueAtPoint>();
                    BoundingBoxUV        bb      = face.GetBoundingBox();
                    UV faceCenter = (bb.Min + bb.Max) / 2; //only collect a center point.

                    uvPts.Add(faceCenter);
                    valList.Add(new ValueAtPoint(dblList));
                    //dblList.Clear();

                    FieldDomainPointsByUV domainPoints = new FieldDomainPointsByUV(uvPts);
                    FieldValues           values       = new FieldValues(valList);

                    AnalysisResultSchema resultSchema = new AnalysisResultSchema(settings.LegendTitle, settings.LegendDescription);
                    resultSchema.SetUnits(unitNames, multipliers);
                    if (unitNames.Contains(settings.Units))
                    {
                        resultSchema.CurrentUnits = unitNames.IndexOf(settings.Units);
                    }

                    if (overwriteResult)
                    {
                        sfm.SetResultSchema(resultIndex, resultSchema);
                    }
                    else if (firstLoop)
                    {
                        resultIndex = sfm.RegisterResult(resultSchema); firstLoop = false;
                    }
                    else
                    {
                        sfm.SetResultSchema(resultIndex, resultSchema);
                    }

                    sfm.UpdateSpatialFieldPrimitive(index, domainPoints, values, resultIndex);
                }
                SetCurrentStyle();
                result = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to analyze elements. \n" + ex.Message, "AnalysisDataManager : ElementAnalysis", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            return(result);
        }
Beispiel #22
0
        public override Value Evaluate(FSharpList <Value> args)
        {
            sfm = ((Value.Container)args[2]).Item as SpatialFieldManager;

            var reference = (args[3] as Value.Container).Item as Reference;
            var face      = (reference == null) ?
                            ((args[3] as Value.Container).Item as Face) :
                            dynRevitSettings.Doc.Document.GetElement(reference).GetGeometryObjectFromReference(reference) as Face;

            //if we received a face instead of a reference
            //then use the reference from the face
            if (reference == null && face != null)
            {
                reference = face.Reference;
            }

            if (reference == null)
            {
                throw new Exception("Could not resolved a referenced for the face.");
            }

            int idx = sfm.AddSpatialFieldPrimitive(reference);

            //unwrap the sample locations
            IEnumerable <UV> pts = ((Value.List)args[1]).Item.Select(
                x => (UV)((Value.Container)x).Item
                );
            var samplePts = new FieldDomainPointsByUV(pts.ToList <UV>());

            //unwrap the values
            IEnumerable <double> nvals = ((Value.List)args[0]).Item.Select(
                x => (double)((Value.Number)x).Item
                );

            //for every sample location add a list
            //of valueatpoint objects. for now, we only
            //support one value per point
            IList <ValueAtPoint> valList = nvals.Select(n => new ValueAtPoint(new List <double> {
                n
            })).ToList();
            var sampleValues = new FieldValues(valList);

            int schemaIndex = 0;

            if (!sfm.IsResultSchemaNameUnique(DYNAMO_ANALYSIS_RESULTS_NAME, -1))
            {
                IList <int> arses = sfm.GetRegisteredResults();
                foreach (int i in arses)
                {
                    AnalysisResultSchema arsTest = sfm.GetResultSchema(i);
                    if (arsTest.Name == DYNAMO_ANALYSIS_RESULTS_NAME)
                    {
                        schemaIndex = i;
                        break;
                    }
                }
            }
            else
            {
                var ars = new AnalysisResultSchema(DYNAMO_ANALYSIS_RESULTS_NAME, "Resulting analyses from Dynamo.");
                schemaIndex = sfm.RegisterResult(ars);
            }

            sfm.UpdateSpatialFieldPrimitive(idx, samplePts, sampleValues, schemaIndex);

            idxs.Add(idx);

            return(Value.NewContainer(idx));
        }
Beispiel #23
0
        public override Value Evaluate(FSharpList<Value> args)
        {
            SpatialFieldManager sfm = ((Value.Container)args[1]).Item as SpatialFieldManager;

            //first, cleanup the old one
            if(idxs.Count > 0)
            {
                foreach (int idx in idxs)
                {
                    sfm.RemoveSpatialFieldPrimitive(idx);
                }
            }

            if (!sfm.IsResultSchemaNameUnique(DYNAMO_TEMP_CURVES_SCHEMA, -1))
            {
                IList<int> arses = sfm.GetRegisteredResults();
                foreach (int i in arses)
                {
                    AnalysisResultSchema arsTest = sfm.GetResultSchema(i);
                    if (arsTest.Name == DYNAMO_TEMP_CURVES_SCHEMA)
                    {
                        schemaId = i;
                        break;
                    }
                }
            }
            else
            {
                AnalysisResultSchema ars = new AnalysisResultSchema(DYNAMO_TEMP_CURVES_SCHEMA, "Temporary curves from Dynamo.");
                schemaId = sfm.RegisterResult(ars);
            }

            Transform trf = Transform.Identity;

            //get the list of pairs
            FSharpList<Value> listOfPairs = ((Value.List)args[0]).Item;
            foreach (Value expr in listOfPairs)
            {
                FSharpList<Value> pair = ((Value.List)expr).Item;

                XYZ start = (XYZ)((Value.Container)pair[0]).Item;
                XYZ end = (XYZ)((Value.Container)pair[1]).Item;
                XYZ start1 = start + XYZ.BasisZ * .1;
                XYZ end1 = end + XYZ.BasisZ * .1;

                //http://thebuildingcoder.typepad.com/blog/2012/09/sphere-creation-for-avf-and-filtering.html#3

                var create = dynRevitSettings.Doc.Application.Application.Create;

                Line l1 = create.NewLineBound(start, end);
                Line l2 = create.NewLineBound(end, end1);
                Line l3 = create.NewLineBound(end1, start1);
                Line l4 = create.NewLineBound(start1, start);

                List<CurveLoop> loops = new List<CurveLoop>();
                CurveLoop cl = new CurveLoop();
                cl.Append(l1);
                cl.Append(l2);
                cl.Append(l3);
                cl.Append(l4);
                loops.Add(cl);
                Solid s = GeometryCreationUtilities.CreateExtrusionGeometry(loops, (end-start).CrossProduct(start1-start), .01);

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

                    //need to use double parameters because
                    //we're drawing lines
                    IList<UV> uvPts = new List<UV>();
                    uvPts.Add(face.GetBoundingBox().Min);

                    FieldDomainPointsByUV pnts
                      = new FieldDomainPointsByUV(uvPts);

                    List<double> doubleList
                      = new List<double>();

                    doubleList.Add(0);

                    IList<ValueAtPoint> valList
                      = new List<ValueAtPoint>();

                    valList.Add(new ValueAtPoint(doubleList));

                    FieldValues vals = new FieldValues(valList);

                    sfm.UpdateSpatialFieldPrimitive(
                      idx, pnts, vals, schemaId);

                    idxs.Add(idx);
                }
            }

            return Value.NewList(Utils.SequenceToFSharpList(idxs.Select(x => Value.NewNumber(x))));
        }
Beispiel #24
0
        public void Execute(UpdaterData data)
        {
            Document doc = data.GetDocument();
             Autodesk.Revit.ApplicationServices.Application app = doc.Application;

             View view = doc.get_Element(viewID) as View;
             FamilyInstance sphere = doc.get_Element(sphereID) as FamilyInstance;
             LocationPoint sphereLP = sphere.Location as LocationPoint;
             XYZ sphereXYZ = sphereLP.Point;

             SpatialFieldManager sfm = SpatialFieldManager.GetSpatialFieldManager(view);
             if (sfm == null) sfm = SpatialFieldManager.CreateSpatialFieldManager(view, 3); // Three measurement values for each point
             sfm.Clear();

             FilteredElementCollector collector = new FilteredElementCollector(doc,view.Id);
             ElementCategoryFilter wallFilter = new ElementCategoryFilter(BuiltInCategory.OST_Walls);
             ElementCategoryFilter massFilter = new ElementCategoryFilter(BuiltInCategory.OST_Mass);
             LogicalOrFilter filter = new LogicalOrFilter(wallFilter, massFilter);
             ICollection<Element> elements = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements();

             foreach (Face face in GetFaces(elements))
             {
            int idx = sfm.AddSpatialFieldPrimitive(face.Reference);
            List<double> doubleList = new List<double>();
            IList<UV> uvPts = new List<UV>();
            IList<ValueAtPoint> valList = new List<ValueAtPoint>();
            BoundingBoxUV bb = face.GetBoundingBox();
            for (double u = bb.Min.U; u < bb.Max.U; u = u + (bb.Max.U - bb.Min.U) / 15)
            {
               for (double v = bb.Min.V; v < bb.Max.V; v = v + (bb.Max.V - bb.Min.V) / 15)
               {
                  UV uvPnt = new UV(u, v);
                  uvPts.Add(uvPnt);
                  XYZ faceXYZ = face.Evaluate(uvPnt);
                   // Specify three values for each point
                  doubleList.Add(faceXYZ.DistanceTo(sphereXYZ));
                  doubleList.Add(-faceXYZ.DistanceTo(sphereXYZ));
                  doubleList.Add(faceXYZ.DistanceTo(sphereXYZ) * 10);
                  valList.Add(new ValueAtPoint(doubleList));
                  doubleList.Clear();
               }
            }
            FieldDomainPointsByUV pnts = new FieldDomainPointsByUV(uvPts);
            FieldValues vals = new FieldValues(valList);

            AnalysisResultSchema resultSchema1 = new AnalysisResultSchema("Schema 1", "Schema 1 Description");
            IList<int> registeredResults = new List<int>();
            registeredResults = sfm.GetRegisteredResults();
            int idx1 = 0;
            if (registeredResults.Count == 0)
            {
                idx1 = sfm.RegisterResult(resultSchema1);
            }
            else
            {
                idx1 = registeredResults.First();
            }
            sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, idx1);
             }
        }
        /// <summary>
        /// Paint a solid in a new named view
        /// </summary>
        /// <param name="s">solid</param>
        /// <param name="viewName">Given the name of view</param>
        public void PaintSolid(Solid s, String viewName)
        {
            View view;
             if (!viewNameList.Contains(viewName))
             {
            view = m_doc.Create.NewView3D(new XYZ(1, 1, 1));
            view.Name = viewName;
            viewNameList.Add(viewName);
             }
             else
             {
            view = (((new FilteredElementCollector(m_doc).
               OfClass(typeof(View))).Cast<View>()).
               Where(e => e.Name == viewName)).First<View>();
             }

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

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

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

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

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

            resultSchema1.AnalysisDisplayStyleId = displayStyle.Id;

            SchemaId = sfm.RegisterResult(resultSchema1);
             }

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

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

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

            FieldDomainPointsByUV pnts = new FieldDomainPointsByUV(uvPts);

            FieldValues vals = new FieldValues(valList);

            sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, SchemaId);
             }
        }
        /// <summary>
        /// Create Visualization framework for view
        /// </summary>
        /// <param name="uvPts"></param>
        /// <param name="valList"></param>
        /// <param name="calcFace"></param>
        /// <param name="faceTransform"></param>
        private void DoVisualization(IList<UV> uvPts, IList<ValueAtPoint> valList, Face calcFace, Transform faceTransform)
        {
            // Visualization framework
            FieldDomainPointsByUV pnts = new FieldDomainPointsByUV(uvPts);
            FieldValues vals = new FieldValues(valList);
            AnalysisResultSchema resultSchema = new AnalysisResultSchema("Point by Point", "Illumination Point-by-Point");

            // Units
            IList<string> names = new List<string> { "FC" };
            IList<double> multipliers = new List<double> { 1 };
            resultSchema.SetUnits(names, multipliers);

            // Add field primative to view
            int idx = m_sfm.AddSpatialFieldPrimitive(calcFace, faceTransform);
            int resultIndex = m_sfm.RegisterResult(resultSchema);

            // Update Field Primatives
            m_sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, resultIndex);
        }
        private RoomData FindVisibilityByPointData(RoomData rd, AnalysisData aData, ProgressBar progressBar)
        {
            RoomData updatedData = new RoomData(rd);

            try
            {
                updatedData.RoomFace = FMEDataUtil.CreateFacebyFMEData(aData.RoomFace);
                if (null != updatedData.RoomFace)
                {
                    updatedData.PointDataList = FMEDataUtil.ConvertToPointDataList(updatedData.RoomFace, aData.PointValues);

                    IList <UV>           uvPoints = new List <UV>();
                    IList <ValueAtPoint> valList  = new List <ValueAtPoint>();

                    progressBar.Value   = 0;
                    progressBar.Minimum = 0;
                    progressBar.Maximum = updatedData.PointDataList.Count;
                    UpdateProgressDelegate updateProgressDelegate = new UpdateProgressDelegate(progressBar.SetValue);

                    int    visibleCount  = 0;
                    double progressValue = 0;
                    foreach (PointData ptData in updatedData.PointDataList)
                    {
                        if (AbortFlag.GetAbortFlag())
                        {
                            return(updatedData);
                        }
                        Dispatcher.CurrentDispatcher.Invoke(updateProgressDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { ProgressBar.ValueProperty, progressValue });

                        if (null != ptData.UVPoint && null != ptData.ValueAtPoint)
                        {
                            uvPoints.Add(ptData.UVPoint);
                            valList.Add(ptData.ValueAtPoint);
                            if (ptData.PointValue > 0)
                            {
                                visibleCount++;
                            }
                        }
                        progressValue++;
                    }

                    double ratio = (double)visibleCount / (double)uvPoints.Count;
                    updatedData.VisiblityRatio = ratio;
                    updatedData.AreaWithViews  = rd.RoomArea * ratio;
                    updatedData.SetResultParameterValue(LEEDParameters.LEED_AreaWithViews.ToString(), rd.AreaWithViews);

                    //visualize
                    Transform transform = Transform.CreateTranslation(new XYZ(0, 0, offsetHeight));
                    int       index     = m_sfm.AddSpatialFieldPrimitive(updatedData.RoomFace, transform);

                    FieldDomainPointsByUV domainPoints = new FieldDomainPointsByUV(uvPoints);
                    FieldValues           values       = new FieldValues(valList);

                    m_sfm.UpdateSpatialFieldPrimitive(index, domainPoints, values, resultIndex);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to find visibility.\n" + ex.Message, "Find Visibility", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            return(updatedData);
        }
Beispiel #28
0
        InternalSetSpatialFieldValues(int primitiveId, ISurfaceAnalysisData <Autodesk.DesignScript.Geometry.UV,
                                                                             double> data, string schemaName, string description, Type unitType)
        {
            // Get the surface reference
            var reference = data.Surface.Tags.LookupTag(DefaultTag) as Reference;

            var el             = DocumentManager.Instance.CurrentDBDocument.GetElement(reference.ElementId);
            var pointLocations = new List <UV>();

            if (el != null)
            {
                var face = el.GetGeometryObjectFromReference(reference) as Autodesk.Revit.DB.Face;
                if (face != null)
                {
                    foreach (var loc in data.CalculationLocations)
                    {
                        var pt      = data.Surface.PointAtParameter(loc.U, loc.V);
                        var faceLoc = face.Project(pt.ToXyz()).UVPoint;
                        pointLocations.Add(faceLoc);
                    }
                }
            }

            var values = data.Results.Values.ToList();

            // Data will come in as:
            // A B C D
            // E F G H
            // I J K L

            // We need it in the form:
            // A E I
            // B F J
            // C G K
            // D H L

            var height = values.First().Count();
            var width  = values.Count();

            var valList = new List <ValueAtPoint>();

            for (int i = 0; i < height; i++)
            {
                var lst = new List <double>()
                {
                };

                for (int j = 0; j < width; j++)
                {
                    lst.Add(values.ElementAt(j).ElementAt(i));
                }
                valList.Add(new ValueAtPoint(lst));
            }

            TransactionManager.Instance.EnsureInTransaction(Document);

            // Convert the analysis values to a special Revit type
            //var valList = enumerable.Select(n => new ValueAtPoint(n.ToList())).ToList();
            var sampleValues = new FieldValues(valList);

            // Convert the sample points to a special Revit Type
            var samplePts = new FieldDomainPointsByUV(pointLocations.ToList());

            // Get the analysis results schema
            var schemaIndex = GetAnalysisResultSchemaIndex(schemaName, description, unitType);

            // Update the values
            SpatialFieldManager.UpdateSpatialFieldPrimitive(primitiveId, samplePts, sampleValues, schemaIndex);

            TransactionManager.Instance.TransactionTaskDone();
        }
        public void Execute(UpdaterData data)
        {
            Document doc = data.GetDocument();

            Autodesk.Revit.ApplicationServices.Application app = doc.Application;

            View           view      = doc.GetElement(viewID) as View;
            FamilyInstance sphere    = doc.GetElement(sphereID) as FamilyInstance;
            LocationPoint  sphereLP  = sphere.Location as LocationPoint;
            XYZ            sphereXYZ = sphereLP.Point;

            SpatialFieldManager sfm = SpatialFieldManager.GetSpatialFieldManager(view);

            if (sfm == null)
            {
                sfm = SpatialFieldManager.CreateSpatialFieldManager(view, 3);              // Three measurement values for each point
            }
            sfm.Clear();

            FilteredElementCollector collector  = new FilteredElementCollector(doc, view.Id);
            ElementCategoryFilter    wallFilter = new ElementCategoryFilter(BuiltInCategory.OST_Walls);
            ElementCategoryFilter    massFilter = new ElementCategoryFilter(BuiltInCategory.OST_Mass);
            LogicalOrFilter          filter     = new LogicalOrFilter(wallFilter, massFilter);
            ICollection <Element>    elements   = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements();

            foreach (Face face in GetFaces(elements))
            {
                int                  idx        = sfm.AddSpatialFieldPrimitive(face.Reference);
                List <double>        doubleList = new List <double>();
                IList <UV>           uvPts      = new List <UV>();
                IList <ValueAtPoint> valList    = new List <ValueAtPoint>();
                BoundingBoxUV        bb         = face.GetBoundingBox();
                for (double u = bb.Min.U; u < bb.Max.U; u = u + (bb.Max.U - bb.Min.U) / 15)
                {
                    for (double v = bb.Min.V; v < bb.Max.V; v = v + (bb.Max.V - bb.Min.V) / 15)
                    {
                        UV uvPnt = new UV(u, v);
                        uvPts.Add(uvPnt);
                        XYZ faceXYZ = face.Evaluate(uvPnt);
                        // Specify three values for each point
                        doubleList.Add(faceXYZ.DistanceTo(sphereXYZ));
                        doubleList.Add(-faceXYZ.DistanceTo(sphereXYZ));
                        doubleList.Add(faceXYZ.DistanceTo(sphereXYZ) * 10);
                        valList.Add(new ValueAtPoint(doubleList));
                        doubleList.Clear();
                    }
                }
                FieldDomainPointsByUV pnts = new FieldDomainPointsByUV(uvPts);
                FieldValues           vals = new FieldValues(valList);

                AnalysisResultSchema resultSchema1     = new AnalysisResultSchema("Schema 1", "Schema 1 Description");
                IList <int>          registeredResults = new List <int>();
                registeredResults = sfm.GetRegisteredResults();
                int idx1 = 0;
                if (registeredResults.Count == 0)
                {
                    idx1 = sfm.RegisterResult(resultSchema1);
                }
                else
                {
                    idx1 = registeredResults.First();
                }
                sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, idx1);
            }
        }
Beispiel #30
0
        /// <summary>
        /// Handle Revit Idling event.
        /// Return immediately if less time elapsed than
        /// specified interval.
        /// Otherwise, download the current image file
        /// from the specified URL.
        /// If it has not changed since the last update,
        /// return immediately.
        /// Otherwise, update the spatial field primitive
        /// with the new image data.
        /// Currently, we only display a grey scale image.
        /// Colour images could be handled as well by
        /// defining a custom colour palette.
        /// </summary>
        static void OnIdling(
            object sender,
            IdlingEventArgs e)
        {
            if (DateTime.Now.Subtract(_lastUpdate)
                > _interval)
            {
                Log("OnIdling");

                GreyscaleBitmapData data
                    = new GreyscaleBitmapData(
                          _width, _height, _url);

                byte[] hash = data.HashValue;

                if (null == _lastHash ||
                    0 != CompareBytes(hash, _lastHash))
                {
                    _lastHash = hash;

                    // access active document from sender:

                    // Support both 2011, where sender is an
                    // Application instance, and 2012, where
                    // it is a UIApplication instance:

                    UIApplication uiapp
                        = sender is UIApplication
            ? sender as UIApplication                 // 2012
            : new UIApplication(
                              sender as Application); // 2011

                    Debug.Assert(null != uiapp,
                                 "expected a valid Revit UIApplication instance");

                    UIDocument uidoc = uiapp.ActiveUIDocument;
                    Document   doc   = uidoc.Document;

                    Log("OnIdling image changed, active document "
                        + doc.Title);

                    Transaction transaction
                        = new Transaction(doc, "Revit Webcam Update");

                    transaction.Start();

                    View view = doc.ActiveView; // maybe has to be 3D

                    SpatialFieldManager sfm
                        = SpatialFieldManager.GetSpatialFieldManager(
                              view);

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

                    if (0 > _sfp_index)
                    {
                        _sfp_index = sfm.AddSpatialFieldPrimitive(
                            _faceReference);
                    }

                    int nPoints = data.Width * data.Height;

                    IList <UV> pts = new List <UV>(nPoints);

                    IList <ValueAtPoint> valuesAtPoints
                        = new List <ValueAtPoint>(nPoints);

                    // warning CS0618:
                    // GeometryObject is obsolete: Property will be removed.
                    // Use Element.GetGeometryObjectFromReference(Reference) instead

                    //Face face = _faceReference.GeometryObject as Face; // 2011

                    //Face face = doc.get_Element( _elementId )
                    //  .GetGeometryObjectFromReference(
                    //    _faceReference ) as Face; // 2012

                    // warning CS0618:
                    // Autodesk.Revit.DB.Document.get_Element(Autodesk.Revit.DB.ElementId) is obsolete:
                    // This method has been obsoleted. Use GetElement() instead.

                    //Element eFace = doc.get_Element( _elementId ); // 2012

                    Element eFace = doc.GetElement(_elementId); // 2013

                    Face face = eFace.GetGeometryObjectFromReference(
                        _faceReference) as Face; // 2012

                    GetFieldPointsAndValues(ref pts,
                                            ref valuesAtPoints, ref data, face);

                    FieldDomainPointsByUV fieldPoints
                        = new FieldDomainPointsByUV(pts);

                    FieldValues fieldValues
                        = new FieldValues(valuesAtPoints);

                    int         result_index;
                    IList <int> registeredResults = sfm.GetRegisteredResults();
                    if (0 == registeredResults.Count)
                    {
                        AnalysisResultSchema resultSchema
                            = new AnalysisResultSchema(
                                  "Schema 1", "Schema 1 Description");

                        result_index = sfm.RegisterResult(
                            resultSchema);
                    }
                    else
                    {
                        result_index = registeredResults.First();
                    }

                    // warning CS0618:
                    // UpdateSpatialFieldPrimitive(int, FieldDomainPoints, FieldValues) is obsolete:
                    // This method is obsolete in Revit 2012; use the overload accepting the result index instead.

                    //sfm.UpdateSpatialFieldPrimitive(
                    //  _sfp_index, fieldPoints, fieldValues ); // 2011

                    sfm.UpdateSpatialFieldPrimitive(
                        _sfp_index, fieldPoints, fieldValues,
                        result_index); // 2012

                    doc.Regenerate();
                    transaction.Commit();

                    _lastUpdate = DateTime.Now;
                }
            }
        }
Beispiel #31
0
        public override Value Evaluate(FSharpList <Value> args)
        {
            //unwrap the values
            IEnumerable <double> nvals = ((Value.List)args[0]).Item.Select(q => (double)((Value.Number)q).Item);

            var curve = (Curve)((Value.Container)args[1]).Item;

            sfm = (SpatialFieldManager)((Value.Container)args[2]).Item;

            if (!sfm.IsResultSchemaNameUnique(DYNAMO_TEMP_CURVES_SCHEMA, -1))
            {
                IList <int> arses = sfm.GetRegisteredResults();
                foreach (int i in arses)
                {
                    AnalysisResultSchema arsTest = sfm.GetResultSchema(i);
                    if (arsTest.Name == DYNAMO_TEMP_CURVES_SCHEMA)
                    {
                        schemaId = i;
                        break;
                    }
                }
            }
            else
            {
                var ars = new AnalysisResultSchema(DYNAMO_TEMP_CURVES_SCHEMA, "Temporary curves from Dynamo.");
                schemaId = sfm.RegisterResult(ars);
            }

            Transform trf = Transform.Identity;

            //http://thebuildingcoder.typepad.com/blog/2012/09/sphere-creation-for-avf-and-filtering.html#3

            var create = dynRevitSettings.Doc.Application.Application.Create;

            Transform t = curve.ComputeDerivatives(0, true);

            XYZ x = t.BasisX.Normalize();
            XYZ y = t.BasisX.IsAlmostEqualTo(XYZ.BasisZ) ?
                    t.BasisX.CrossProduct(XYZ.BasisY).Normalize() :
                    t.BasisX.CrossProduct(XYZ.BasisZ).Normalize();
            XYZ z = x.CrossProduct(y);

            Ellipse arc1 = dynRevitSettings.Revit.Application.Create.NewEllipse(t.Origin, .1, .1, y, z, -Math.PI, 0);
            Ellipse arc2 = dynRevitSettings.Revit.Application.Create.NewEllipse(t.Origin, .1, .1, y, z, 0, Math.PI);

            var pathLoop = new CurveLoop();

            pathLoop.Append(curve);
            var profileLoop = new CurveLoop();

            profileLoop.Append(arc1);
            profileLoop.Append(arc2);

            double curveDomain = curve.get_EndParameter(1) - curve.get_EndParameter(0);

            int idx = -1;
            var s   = GeometryCreationUtilities.CreateSweptGeometry(pathLoop, 0, 0, new List <CurveLoop> {
                profileLoop
            });

            foreach (Face face in s.Faces)
            {
                //divide the V domain by the number of incoming
                BoundingBoxUV domain = face.GetBoundingBox();
                double        vSpan  = domain.Max.V - domain.Min.V;

                //analysis values
                idx = sfm.AddSpatialFieldPrimitive(face, trf);

                //a list to hold the analysis points
                IList <UV> uvPts = new List <UV>();

                //a list to hold the analysis values
                IList <ValueAtPoint> valList = new List <ValueAtPoint>();

                //int count = nvals.Count();

                //this is creating a lot of sample points, but if we used less
                //sampling points, AVF would draw the two surfaces as if there was a hard
                //edge between them. this provides a better blend.
                int count = 10;
                for (int i = 0; i < count; i++)
                {
                    //get a UV point on the face
                    //find its XYZ location and project to
                    //the underlying curve. find the value which corresponds
                    //to the location on the curve
                    var uv  = new UV(domain.Min.U, domain.Min.V + vSpan / count * (double)i);
                    var uv1 = new UV(domain.Max.U, domain.Min.V + vSpan / count * (double)i);
                    uvPts.Add(uv);
                    uvPts.Add(uv1);

                    XYZ facePt                    = face.Evaluate(uv);
                    IntersectionResult ir         = curve.Project(facePt);
                    double             curveParam = curve.ComputeNormalizedParameter(ir.Parameter);

                    if (curveParam < 0)
                    {
                        curveParam = 0;
                    }

                    if (curveParam > 1)
                    {
                        curveParam = 1;
                    }

                    var valueIndex = (int)Math.Floor(curveParam * (double)nvals.Count());
                    if (valueIndex >= nvals.Count())
                    {
                        valueIndex = nvals.Count() - 1;
                    }

                    //create list of values at this point - currently supporting only one
                    //var doubleList = new List<double> { nvals.ElementAt(i) };
                    var doubleList = new List <double> {
                        nvals.ElementAt(valueIndex)
                    };

                    //add value at point object containing the value list
                    valList.Add(new ValueAtPoint(doubleList));
                    valList.Add(new ValueAtPoint(doubleList));
                }

                var pnts = new FieldDomainPointsByUV(uvPts);
                var vals = new FieldValues(valList);

                sfm.UpdateSpatialFieldPrimitive(
                    idx, pnts, vals, schemaId);

                idxs.Add(idx);
            }

            return(Value.NewNumber(idx));
        }
Beispiel #32
0
        /// <summary>
        /// Handle Revit Idling event.
        /// If less time elapsed than the specified interval, return immediately.
        /// Otherwise, download the current image frile from the specified URL.
        /// If it has not changed since the last update, return immediately.
        /// Otherwise, update the spatial field primitive with the new image data.
        /// Currently, we only display a grey scale image.
        /// Colour images could be handled as well by defining a custom colour palette.
        /// </summary>
        static void OnIdling(
            object sender,
            IdlingEventArgs e)
        {
            if (DateTime.Now.Subtract(_lastUpdate)
                > _interval)
            {
                Log("OnIdling");

                GreyscaleBitmapData data
                    = new GreyscaleBitmapData(
                          _width, _height, _url);

                byte[] hash = data.HashValue;

                if (null == _lastHash ||
                    0 != CompareBytes(hash, _lastHash))
                {
                    _lastHash = hash;

                    // access active document from sender:

                    Application app = sender as Application;

                    Debug.Assert(null != app,
                                 "expected a valid Revit application instance");

                    UIApplication uiapp = new UIApplication(app);
                    UIDocument    uidoc = uiapp.ActiveUIDocument;
                    Document      doc   = uidoc.Document;

                    Log("OnIdling image changed, active document "
                        + doc.Title);

                    Transaction transaction
                        = new Transaction(doc, "Revit Webcam Update");

                    transaction.Start();

                    View view = doc.ActiveView; // maybe has to be 3D

                    SpatialFieldManager sfm
                        = SpatialFieldManager.GetSpatialFieldManager(
                              view);

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

                    if (0 > _sfp_index)
                    {
                        _sfp_index = sfm.AddSpatialFieldPrimitive(
                            _faceReference);
                    }

                    int nPoints = data.Width * data.Height;

                    IList <UV> pts = new List <UV>(nPoints);

                    IList <ValueAtPoint> valuesAtPoints
                        = new List <ValueAtPoint>(nPoints);

                    Face face = _faceReference.GeometryObject
                                as Face;

                    GetFieldPointsAndValues(ref pts,
                                            ref valuesAtPoints, ref data, face);

                    FieldDomainPointsByUV fieldPoints
                        = new FieldDomainPointsByUV(pts);

                    FieldValues fieldValues
                        = new FieldValues(valuesAtPoints);

                    sfm.UpdateSpatialFieldPrimitive(
                        _sfp_index, fieldPoints, fieldValues);

                    doc.Regenerate();
                    transaction.Commit();

                    _lastUpdate = DateTime.Now;
                }
            }
        }
Beispiel #33
0
        public override Value Evaluate(FSharpList<Value> args)
        {
            this.ClearPreviousResults();

            //unwrap the values
            IEnumerable<double> nvals = ((Value.List)args[0]).Item.Select(q => (double)((Value.Number)q).Item);

            var curve = (Curve)((Value.Container)args[1]).Item;
            SpatialFieldManager = (Autodesk.Revit.DB.Analysis.SpatialFieldManager)((Value.Container)args[2]).Item;

            if (!SpatialFieldManager.IsResultSchemaNameUnique(DYNAMO_TEMP_CURVES_SCHEMA, -1))
            {
                IList<int> arses = SpatialFieldManager.GetRegisteredResults();
                foreach (int i in arses)
                {
                    AnalysisResultSchema arsTest = SpatialFieldManager.GetResultSchema(i);
                    if (arsTest.Name == DYNAMO_TEMP_CURVES_SCHEMA)
                    {
                        schemaId = i;
                        break;
                    }
                }
            }
            else
            {
                var ars = new AnalysisResultSchema(DYNAMO_TEMP_CURVES_SCHEMA, "Temporary curves from Dynamo.");
                schemaId = SpatialFieldManager.RegisterResult(ars);
            }

            Transform trf = Transform.Identity;

            //http://thebuildingcoder.typepad.com/blog/2012/09/sphere-creation-for-avf-and-filtering.html#3

            var create = dynRevitSettings.Doc.Application.Application.Create;

            Transform t = curve.ComputeDerivatives(0, true);

            XYZ x = t.BasisX.Normalize();
            XYZ y = t.BasisX.IsAlmostEqualTo(XYZ.BasisZ) ?
                t.BasisX.CrossProduct(XYZ.BasisY).Normalize() :
                t.BasisX.CrossProduct(XYZ.BasisZ).Normalize();
            XYZ z = x.CrossProduct(y);

            Autodesk.Revit.DB.Ellipse arc1 = dynRevitSettings.Revit.Application.Create.NewEllipse(t.Origin, .1, .1, y,z,-Math.PI, 0);
            Autodesk.Revit.DB.Ellipse arc2 = dynRevitSettings.Revit.Application.Create.NewEllipse(t.Origin, .1, .1, y, z, 0, Math.PI);

            var pathLoop = new Autodesk.Revit.DB.CurveLoop();
            pathLoop.Append(curve);
            var profileLoop = new Autodesk.Revit.DB.CurveLoop();
            profileLoop.Append(arc1);
            profileLoop.Append(arc2);

            double curveDomain = curve.get_EndParameter(1) - curve.get_EndParameter(0);

            int idx = -1;
            var s = GeometryCreationUtilities.CreateSweptGeometry(pathLoop, 0, 0, new List<Autodesk.Revit.DB.CurveLoop>{profileLoop});
            foreach (Face face in s.Faces)
            {
                //divide the V domain by the number of incoming
                BoundingBoxUV domain = face.GetBoundingBox();
                double vSpan = domain.Max.V - domain.Min.V;

                //analysis values
                idx = SpatialFieldManager.AddSpatialFieldPrimitive(face, trf);

                //a list to hold the analysis points
                IList<UV> uvPts = new List<UV>();

                //a list to hold the analysis values
                IList<ValueAtPoint> valList = new List<ValueAtPoint>();

                //int count = nvals.Count();

                //this is creating a lot of sample points, but if we used less
                //sampling points, AVF would draw the two surfaces as if there was a hard
                //edge between them. this provides a better blend.
                int count = 10;
                for (int i = 0; i < count; i ++)
                {
                    //get a UV point on the face
                    //find its XYZ location and project to
                    //the underlying curve. find the value which corresponds
                    //to the location on the curve
                    var uv = new UV(domain.Min.U, domain.Min.V + vSpan / count*(double) i);
                    var uv1 = new UV(domain.Max.U, domain.Min.V + vSpan / count * (double)i);
                    uvPts.Add(uv);
                    uvPts.Add(uv1);

                    XYZ facePt = face.Evaluate(uv);
                    IntersectionResult ir = curve.Project(facePt);
                    double curveParam = curve.ComputeNormalizedParameter(ir.Parameter);

                    if (curveParam < 0)
                        curveParam = 0;

                    if (curveParam > 1)
                        curveParam = 1;

                    var valueIndex = (int)Math.Floor(curveParam * (double)nvals.Count());
                    if (valueIndex >= nvals.Count())
                        valueIndex = nvals.Count() - 1;

                    //create list of values at this point - currently supporting only one
                    //var doubleList = new List<double> { nvals.ElementAt(i) };
                    var doubleList = new List<double> { nvals.ElementAt(valueIndex) };

                    //add value at point object containing the value list
                    valList.Add(new ValueAtPoint(doubleList));
                    valList.Add(new ValueAtPoint(doubleList));
                }

                var pnts = new FieldDomainPointsByUV(uvPts);
                var vals = new FieldValues(valList);

                SpatialFieldManager.UpdateSpatialFieldPrimitive(
                    idx, pnts, vals, schemaId);

                PastResultIds.Add(idx);
            }

            return Value.NewNumber(idx);
        }
Beispiel #34
0
        /// <summary>
        /// Handle Revit Idling event.
        /// If less time elapsed than the specified interval, return immediately.
        /// Otherwise, download the current image frile from the specified URL.
        /// If it has not changed since the last update, return immediately.
        /// Otherwise, update the spatial field primitive with the new image data.
        /// Currently, we only display a grey scale image.
        /// Colour images could be handled as well by defining a custom colour palette.
        /// </summary>
        static void OnIdling(
            object sender,
            IdlingEventArgs e)
        {
            if (DateTime.Now.Subtract(_lastUpdate)
                > _interval)
            {
                Log("OnIdling");

                GreyscaleBitmapData data
                    = new GreyscaleBitmapData(
                          _width, _height, _url);

                byte[] hash = data.HashValue;

                if (null == _lastHash ||
                    0 != CompareBytes(hash, _lastHash))
                {
                    _lastHash = hash;

                    // access active document from sender:

                    Application app = sender as Application;

                    Debug.Assert(null != app,
                                 "expected a valid Revit application instance");

                    UIApplication uiapp = new UIApplication(app);
                    UIDocument    uidoc = uiapp.ActiveUIDocument;
                    Document      doc   = uidoc.Document;

                    Log("OnIdling image changed, active document "
                        + doc.Title);

                    Transaction transaction
                        = new Transaction(doc, "Revit Webcam Update");

                    transaction.Start();

                    View view = doc.ActiveView; // maybe has to be 3D

                    SpatialFieldManager sfm
                        = SpatialFieldManager.GetSpatialFieldManager(
                              view);

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

                    if (0 > _sfp_index)
                    {
                        _sfp_index = sfm.AddSpatialFieldPrimitive(
                            _faceReference);
                    }

                    int nPoints = data.Width * data.Height;

                    IList <UV> pts = new List <UV>(nPoints);

                    IList <ValueAtPoint> valuesAtPoints
                        = new List <ValueAtPoint>(nPoints);

                    // warning CS0618:
                    // GeometryObject is obsolete: Property will be removed.
                    // Use Element.GetGeometryObjectFromReference(Reference) instead

                    //Face face = _faceReference.GeometryObject as Face; // 2011

                    Face face = doc.get_Element(_elementId)
                                .GetGeometryObjectFromReference(
                        _faceReference) as Face; // 2012

                    GetFieldPointsAndValues(ref pts,
                                            ref valuesAtPoints, ref data, face);

                    FieldDomainPointsByUV fieldPoints
                        = new FieldDomainPointsByUV(pts);

                    FieldValues fieldValues
                        = new FieldValues(valuesAtPoints);

                    // warning CS0618:
                    // UpdateSpatialFieldPrimitive(int, FieldDomainPoints, FieldValues) is obsolete:
                    // This method is obsolete in Revit 2012; use the overload accepting the result index instead.

                    //sfm.UpdateSpatialFieldPrimitive(
                    //  _sfp_index, fieldPoints, fieldValues ); // 2011

                    sfm.UpdateSpatialFieldPrimitive(
                        _sfp_index, fieldPoints, fieldValues, _sfp_index); // 2012

                    doc.Regenerate();
                    transaction.Commit();

                    _lastUpdate = DateTime.Now;
                }
            }
        }
Beispiel #35
0
            /// <summary>
            /// The idling callback which adds data to the AVF results.
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            public void UpdateWhileIdling(object sender, IdlingEventArgs e)
            {
                UIApplication uiApp = sender as UIApplication;

                // Get SpatialFieldManager

                AnalysisResultSchema resultSchema = new AnalysisResultSchema("Schema Name", "Description");
                SpatialFieldManager  sfm          = SpatialFieldManager.GetSpatialFieldManager(uiApp.ActiveUIDocument.Document.ActiveView);

                if (sfm == null)
                {
                    sfm = SpatialFieldManager.CreateSpatialFieldManager(uiApp.ActiveUIDocument.Document.ActiveView, 1);
                }
                int schemaIndex = sfm.RegisterResult(resultSchema);

                // If stopping, clear results and unset event.
                if (m_stop)
                {
                    lock (results)
                    {
                        results.Clear();
                    }
                    uiApp.Idling -= UpdateWhileIdling;
                    return;
                }

                // If document was closed and new document opened, do not run the update.
                if (uiApp.ActiveUIDocument.Document.PathName == m_docName)
                {
                    // Lock access to current calculated results
                    lock (results)
                    {
                        if (results.Count == 0)
                        {
                            return;
                        }

                        // Turn each result to an AVF ValueAtPoint
                        foreach (ResultsData rData in results)
                        {
                            uvPts.Add(new UV(rData.UV.U, rData.UV.V));
                            IList <double> doubleList = new List <double>();
                            doubleList.Add(rData.Value);
                            valList.Add(new ValueAtPoint(doubleList));
                        }
                        FieldDomainPointsByUV pntsByUV    = new FieldDomainPointsByUV(uvPts);
                        FieldValues           fieldValues = new FieldValues(valList);

                        // Update with calculated values
                        Transaction t = new Transaction(uiApp.ActiveUIDocument.Document);
                        t.SetName("AVF");
                        t.Start();
                        if (!m_stop)
                        {
                            sfm.UpdateSpatialFieldPrimitive(s_spatialFieldId, pntsByUV, fieldValues, schemaIndex);
                        }
                        t.Commit();

                        // Clear results already processed.
                        results.Clear();

                        // If no more results to process, remove the idling event
                        if (m_uvToCalculateCount == 0)
                        {
                            uiApp.Idling       -= UpdateWhileIdling;
                            s_oldViewId         = s_activeViewId;
                            s_oldSpatialFieldId = s_spatialFieldId;
                        }
                    }
                }
            }
Beispiel #36
0
        public bool AnalysisByElements()
        {
            bool result = false;

            try
            {
                if (areaDictionary.Count > 0)
                {
                    int  resultIndex = FindIndexOfResult(sfm);
                    bool firstLoop   = true;
                    foreach (int areaId in areaDictionary.Keys)
                    {
                        AreaProperties ap      = areaDictionary[areaId];
                        List <double>  dblList = new List <double>(); //double values to be displayed on the face.
                        Face           face    = ap.BaseFace;
                        dblList.Add(ap.FAR);

                        if (dblList.Count != sfm.NumberOfMeasurements)
                        {
                            continue;
                        }

                        int                  index   = sfm.AddSpatialFieldPrimitive(face, Transform.Identity);
                        IList <UV>           uvPts   = new List <UV>();
                        IList <ValueAtPoint> valList = new List <ValueAtPoint>();
                        BoundingBoxUV        bb      = face.GetBoundingBox();
                        UV faceCenter = (bb.Min + bb.Max) / 2; //only collect a center point.

                        uvPts.Add(faceCenter);
                        valList.Add(new ValueAtPoint(dblList));
                        //dblList.Clear();

                        FieldDomainPointsByUV domainPoints = new FieldDomainPointsByUV(uvPts);
                        FieldValues           values       = new FieldValues(valList);

                        AnalysisResultSchema resultSchema = new AnalysisResultSchema(settings.LegendTitle, settings.LegendDescription);
                        resultSchema.SetUnits(unitNames, multipliers);
                        if (unitNames.Contains(settings.Units))
                        {
                            resultSchema.CurrentUnits = unitNames.IndexOf(settings.Units);
                        }

                        if (overwriteResult)
                        {
                            sfm.SetResultSchema(resultIndex, resultSchema);
                        }
                        else if (firstLoop)
                        {
                            resultIndex = sfm.RegisterResult(resultSchema); firstLoop = false;
                        }
                        else
                        {
                            sfm.SetResultSchema(resultIndex, resultSchema);
                        }

                        sfm.UpdateSpatialFieldPrimitive(index, domainPoints, values, resultIndex);
                    }
                    SetCurrentStyle();
                    result = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to visulaize the FAR data. \n" + ex.Message, "FARCalculator : AnalysisByElements", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            return(result);
        }
Beispiel #37
0
        /// <summary>
        /// Set the spatial field values for the current spatial field primitive.  The two 
        /// input sequences should be of the same length.
        /// </summary>
        /// <param name="pointLocations"></param>
        /// <param name="values"></param>
        private void InternalSetSpatialFieldValues(IEnumerable<UV> pointLocations, IEnumerable<double> values)
        {
            TransactionManager.Instance.EnsureInTransaction(Document);

            // Convert the analysis values to a special Revit type
            var valList = values.Select(n => new ValueAtPoint(new List<double> { n })).ToList();
            var sampleValues = new FieldValues(valList);

            // Convert the sample points to a special Revit Type
            var samplePts = new FieldDomainPointsByUV(pointLocations.ToList<UV>());

            // Get the analysis results schema
            var schemaIndex = GetAnalysisResultSchemaIndex();

            // Update the values
            SpatialFieldManager.UpdateSpatialFieldPrimitive(SpatialFieldPrimitiveId, samplePts, sampleValues, schemaIndex);

            TransactionManager.Instance.TransactionTaskDone();
        }
        private RoomData FindVisibility(RoomData rd, ProgressBar progressBar)
        {
            RoomData updatedData = new RoomData(rd);

            try
            {
                LogicalOrFilter      orFilter    = new LogicalOrFilter(categoryFilters);
                ReferenceIntersector intersector = null;
                intersector = new ReferenceIntersector(orFilter, FindReferenceTarget.Face, m_view);
                intersector.FindReferencesInRevitLinks = true;

                Face          face = rd.RoomFace;
                BoundingBoxUV bb   = face.GetBoundingBox();

                IList <UV>           uvPoints = new List <UV>();
                IList <ValueAtPoint> valList  = new List <ValueAtPoint>();

                List <PointData> pointDataList = new List <PointData>();
                double           interval      = analysisSettings.Interval;
                List <double>    uList         = new List <double>();
                List <double>    vList         = new List <double>();
                GetUVArray(bb, interval, out uList, out vList);


                progressBar.Value   = 0;
                progressBar.Minimum = 0;
                progressBar.Maximum = uList.Count * vList.Count;
                UpdateProgressDelegate updateProgressDelegate = new UpdateProgressDelegate(progressBar.SetValue);


                List <XYZ> exteriorPoints = new List <XYZ>();
                List <XYZ> interiorPoints = new List <XYZ>();
                bool       sorted         = SortViewPoints(rd.BoundarySegments, out exteriorPoints, out interiorPoints);

                int    visibleCount  = 0;
                double progressValue = 0;
                foreach (double u in uList) //start from in the middle of grid
                {
                    foreach (double v in vList)
                    {
                        if (AbortFlag.GetAbortFlag())
                        {
                            return(updatedData);
                        }
                        Dispatcher.CurrentDispatcher.Invoke(updateProgressDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { ProgressBar.ValueProperty, progressValue });

                        UV uvPoint = new UV(u, v);
                        if (face.IsInside(uvPoint))
                        {
                            XYZ    evalPoint  = face.Evaluate(uvPoint);
                            XYZ    xyzPoint   = new XYZ(evalPoint.X, evalPoint.Y, evalPoint.Z + offsetHeight); //4.2 inches above from the floor
                            double pointValue = 0;

                            List <XYZ> viewPoints = new List <XYZ>();
                            if (exteriorPoints.Count > 0)
                            {
                                exteriorPoints = exteriorPoints.OrderBy(o => o.DistanceTo(xyzPoint)).ToList();
                                viewPoints.AddRange(exteriorPoints);
                            }
                            if (interiorPoints.Count > 0)
                            {
                                interiorPoints = interiorPoints.OrderBy(o => o.DistanceTo(xyzPoint)).ToList();
                                viewPoints.AddRange(interiorPoints);
                            }

                            if (viewPoints.Count > 0)
                            {
                                bool visible = CheckVisibilityByMaterial(intersector, xyzPoint, viewPoints);
                                if (visible)
                                {
                                    pointValue = 1; visibleCount++;
                                }
                                else
                                {
                                    pointValue = 0;
                                }
                            }

                            PointData pData = new PointData(uvPoint, xyzPoint, pointValue);
                            pointDataList.Add(pData);

                            uvPoints.Add(pData.UVPoint);
                            valList.Add(pData.ValueAtPoint);
                        }
                        progressValue++;
                    }
                }

                rd.PointDataList = pointDataList;
                double ratio = (double)visibleCount / (double)uvPoints.Count;
                rd.VisiblityRatio = ratio;
                rd.AreaWithViews  = rd.RoomArea * ratio;
                rd.SetResultParameterValue(LEEDParameters.LEED_AreaWithViews.ToString(), rd.AreaWithViews);

                //visualize
                Transform transform = Transform.CreateTranslation(new XYZ(0, 0, offsetHeight));

                int index = m_sfm.AddSpatialFieldPrimitive(face, transform);
                FieldDomainPointsByUV domainPoints = new FieldDomainPointsByUV(uvPoints);
                FieldValues           values       = new FieldValues(valList);

                m_sfm.UpdateSpatialFieldPrimitive(index, domainPoints, values, resultIndex);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to find visibility.\n" + ex.Message, "Find Visibility", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            return(updatedData);
        }
Beispiel #39
0
        /// <summary>
        /// External webcam event handler.
        /// </summary>
        public void Execute(UIApplication uiapp)
        {
            UIDocument uidoc = uiapp.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            Log("OnIdling image changed, active document "
                + doc.Title);

            Transaction transaction = new Transaction(doc);

            transaction.Start("Revit Webcam Update");

            View view = doc.ActiveView; // maybe has to be 3D

            SpatialFieldManager sfm
                = SpatialFieldManager.GetSpatialFieldManager(
                      view);

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

            if (0 > _sfp_index)
            {
                _sfp_index = sfm.AddSpatialFieldPrimitive(
                    _faceReference);
            }

            int nPoints = _width * _height; // _data.Width * _data.Height;

            IList <UV> pts = new List <UV>(nPoints);

            IList <ValueAtPoint> valuesAtPoints
                = new List <ValueAtPoint>(nPoints);

            Element eFace = doc.GetElement(
                _faceReference.ElementId); // 2013

            Face face = eFace.GetGeometryObjectFromReference(
                _faceReference) as Face; // 2012

            GetFieldPointsAndValues(ref pts,
                                    ref valuesAtPoints, face);

            FieldDomainPointsByUV fieldPoints
                = new FieldDomainPointsByUV(pts);

            FieldValues fieldValues
                = new FieldValues(valuesAtPoints);

            int         result_index;
            IList <int> registeredResults = sfm.GetRegisteredResults();

            if (0 == registeredResults.Count)
            {
                AnalysisResultSchema resultSchema
                    = new AnalysisResultSchema(
                          "Schema 1", "Schema 1 Description");

                result_index = sfm.RegisterResult(
                    resultSchema);
            }
            else
            {
                result_index = registeredResults.First();
            }

            sfm.UpdateSpatialFieldPrimitive(
                _sfp_index, fieldPoints, fieldValues,
                result_index); // 2012

            doc.Regenerate();

            transaction.Commit();
        }
Beispiel #40
0
        public override Value Evaluate(FSharpList<Value> args)
        {
            SpatialFieldManager sfm = ((Value.Container)args[2]).Item as SpatialFieldManager;

            //first, cleanup the old one
            if (idx != -1)
            {
                sfm.RemoveSpatialFieldPrimitive(idx);
            }

            Reference reference = ((Value.Container)args[3]).Item as Reference;
            idx = sfm.AddSpatialFieldPrimitive(reference);

            Face face = dynRevitSettings.Doc.Document.GetElement(reference).GetGeometryObjectFromReference(reference) as Face;

            //unwrap the sample locations
            IEnumerable<UV> pts = ((Value.List)args[1]).Item.Select(
               x => (UV)((Value.Container)x).Item
            );
            FieldDomainPointsByUV sample_pts = new FieldDomainPointsByUV(pts.ToList<UV>());

            //unwrap the values
            IEnumerable<double> nvals = ((Value.List)args[0]).Item.Select(
               x => (double)((Value.Number)x).Item
            );

            //for every sample location add a list
            //of valueatpoint objets. for now, we only
            //support one value per point
            IList<ValueAtPoint> valList = new List<ValueAtPoint>();
            foreach (var n in nvals)
            {
                valList.Add(new ValueAtPoint(new List<double>{n}));
            }
            FieldValues sample_values = new FieldValues(valList);

            int schemaIndex = 0;
            if (!sfm.IsResultSchemaNameUnique(DYNAMO_ANALYSIS_RESULTS_NAME, -1))
            {
                IList<int> arses = sfm.GetRegisteredResults();
                foreach (int i in arses)
                {
                    AnalysisResultSchema arsTest = sfm.GetResultSchema(i);
                    if (arsTest.Name == DYNAMO_ANALYSIS_RESULTS_NAME)
                    {
                        schemaIndex = i;
                        break;
                    }
                }
            }
            else
            {
                AnalysisResultSchema ars = new AnalysisResultSchema(DYNAMO_ANALYSIS_RESULTS_NAME, "Resulting analyses from Dynamo.");
                schemaIndex = sfm.RegisterResult(ars);
            }

            sfm.UpdateSpatialFieldPrimitive(idx, sample_pts, sample_values, schemaIndex);

            return Value.NewContainer(idx);
        }
Beispiel #41
0
            InternalSetSpatialFieldValues(int primitiveId, ISurfaceAnalysisData<Autodesk.DesignScript.Geometry.UV, 
            double> data, string schemaName, string description, Type unitType)
        {
            // Get the surface reference
            var reference = data.Surface.Tags.LookupTag(DefaultTag) as Reference;

            var el = DocumentManager.Instance.CurrentDBDocument.GetElement(reference.ElementId);
            var pointLocations = new List<UV>();
            if (el != null)
            {
                var face = el.GetGeometryObjectFromReference(reference) as Autodesk.Revit.DB.Face;
                if (face != null)
                {
                    foreach (var loc in data.CalculationLocations)
                    {
                        var pt = data.Surface.PointAtParameter(loc.U, loc.V);
                        var faceLoc = face.Project(pt.ToXyz()).UVPoint;
                        pointLocations.Add(faceLoc);
                    }
                }
            }

            var values = data.Results.Values.ToList();

            // Data will come in as:
            // A B C D
            // E F G H
            // I J K L

            // We need it in the form:
            // A E I
            // B F J
            // C G K
            // D H L

            var height = values.First().Count();
            var width = values.Count();

            var valList = new List<ValueAtPoint>();
            for (int i = 0; i < height; i++)
            {
                var lst = new List<double>() { };

                for (int j = 0; j < width; j++)
                {
                    lst.Add(values.ElementAt(j).ElementAt(i));
                }
                valList.Add(new ValueAtPoint(lst));
            }

            TransactionManager.Instance.EnsureInTransaction(Document);

            // Convert the analysis values to a special Revit type
            //var valList = enumerable.Select(n => new ValueAtPoint(n.ToList())).ToList();
            var sampleValues = new FieldValues(valList);

            // Convert the sample points to a special Revit Type
            var samplePts = new FieldDomainPointsByUV(pointLocations.ToList());

            // Get the analysis results schema
            var schemaIndex = GetAnalysisResultSchemaIndex(schemaName, description, unitType);

            // Update the values
            SpatialFieldManager.UpdateSpatialFieldPrimitive(primitiveId, samplePts, sampleValues, schemaIndex);

            TransactionManager.Instance.TransactionTaskDone();
        }
Beispiel #42
0
        //accumulative values on grid points
        private bool MeasureAccDistance()
        {
            bool result = false;

            try
            {
                //find walls located inside the selected rooms
                FindWallFacesOnRoom();

                //Find point of view from the sphere element
                FamilyInstance sphere = FindPointOfView();
                if (null != sphere)
                {
                    LocationPoint location = sphere.Location as LocationPoint;
                    XYZ           pointXYZ = location.Point;
                    XYZ           vectorZ  = new XYZ(0, 0, 1);
#if RELEASE2013
                    Transform transform = Transform.get_Translation(vectorZ);
#else
                    Transform transform = Transform.CreateTranslation(vectorZ);
#endif

                    int  resultIndex = FindIndexOfResult(sfm);
                    bool firstLoop   = true;
                    foreach (int roomId in roomFaces.Keys)
                    {
                        Face                 roomFace    = roomFaces[roomId];
                        int                  index       = sfm.AddSpatialFieldPrimitive(roomFace, transform);
                        List <double>        doubleList  = new List <double>();
                        IList <UV>           uvPoints    = new List <UV>();
                        IList <ValueAtPoint> valList     = new List <ValueAtPoint>();
                        BoundingBoxUV        boundingBox = roomFace.GetBoundingBox();
                        for (double u = boundingBox.Min.U; u < boundingBox.Max.U; u = u + (boundingBox.Max.U - boundingBox.Min.U) / 15)
                        {
                            for (double v = boundingBox.Min.V; v < boundingBox.Max.V; v = v + (boundingBox.Max.V - boundingBox.Min.V) / 15)
                            {
                                UV  uvPoint  = new UV(u, v);
                                XYZ xyzPoint = roomFace.Evaluate(uvPoint);
                                uvPoints.Add(uvPoint);
#if RELEASE2013
                                Line line = doc.Application.Create.NewLine(pointXYZ, xyzPoint, true);
#else
                                Line line = Line.CreateBound(pointXYZ, xyzPoint);
#endif
                                //double dblValue = 1 / (line.ApproximateLength);
                                double dblValue = 1;

                                IntersectionResultArray resultArray;
                                foreach (int wallId in wallFaces.Keys)
                                {
                                    Face wallFace = wallFaces[wallId];
                                    SetComparisonResult compResult = wallFace.Intersect(line, out resultArray);
                                    if (compResult == SetComparisonResult.Overlap && null != resultArray)
                                    {
                                        if (dblValue > 0)
                                        {
                                            dblValue = 0 - resultArray.Size;
                                        }
                                        else
                                        {
                                            dblValue = -resultArray.Size;
                                        }
                                    }
                                }
                                doubleList.Add(dblValue);
                                valList.Add(new ValueAtPoint(doubleList));
                                doubleList.Clear();
                            }
                        }

                        FieldDomainPointsByUV domainPoints = new FieldDomainPointsByUV(uvPoints);
                        FieldValues           values       = new FieldValues(valList);

                        AnalysisResultSchema resultSchema = new AnalysisResultSchema(settings.LegendTitle, settings.LegendDescription);
                        resultSchema.SetUnits(unitNames, multipliers);
                        if (unitNames.Contains(settings.Units))
                        {
                            resultSchema.CurrentUnits = unitNames.IndexOf(settings.Units);
                        }

                        if (overwriteResult)
                        {
                            sfm.SetResultSchema(resultIndex, resultSchema);
                        }
                        else if (firstLoop)
                        {
                            resultIndex = sfm.RegisterResult(resultSchema); firstLoop = false;
                        }
                        else
                        {
                            sfm.SetResultSchema(resultIndex, resultSchema);
                        }

                        sfm.UpdateSpatialFieldPrimitive(index, domainPoints, values, resultIndex);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to measure distance from the point element to the points on Room face.\n" + ex.Message, "FieldOfViewAnalysis", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                result = false;
            }
            return(result);
        }