예제 #1
0
        /// <summary>
        /// Get the SpatialFieldManager for a particular view.  This is a singleton for every view.  Note that the
        /// number of values per analysis point is ignored if the SpatialFieldManager has already been obtained
        /// for this view.  This field cannot be mutated once the SpatialFieldManager is set for a partiular
        /// view.
        /// </summary>
        /// <param name="view"></param>
        /// <param name="numValuesPerAnalysisPoint"></param>
        /// <returns></returns>
        protected static SpatialFieldManager GetSpatialFieldManagerFromView(Autodesk.Revit.DB.View view, uint numValuesPerAnalysisPoint = 1)
        {
            if (view == null)
            {
                throw new ArgumentNullException("view");
            }

            TransactionManager.Instance.EnsureInTransaction(Document);

            var sfm = SpatialFieldManager.GetSpatialFieldManager(view);

            if (sfm == null)
            {
                sfm = SpatialFieldManager.CreateSpatialFieldManager(view, (int)numValuesPerAnalysisPoint);
            }
            else
            {
                // If the number of values stored
                // at each location is not equal to what we are requesting,
                // then create a new SFM
                if (sfm.NumberOfMeasurements != numValuesPerAnalysisPoint)
                {
                    DocumentManager.Instance.CurrentDBDocument.Delete(sfm.Id);
                    sfm = SpatialFieldManager.CreateSpatialFieldManager(view, (int)numValuesPerAnalysisPoint);
                }
            }

            TransactionManager.Instance.TransactionTaskDone();

            return(sfm);
        }
예제 #2
0
        /// <summary>
        ///   Getting ready to preform an analysis for the given in view
        /// </summary>
        /// <remarks>
        ///   This initializes the Spatial Field Manager,
        ///   adds a field primitive corresponding to the face,
        ///   and registers our result schema we want to use.
        ///   The method clears any previous results in the view.
        /// </remarks>
        ///
        public void Initialize()
        {
            // create of get field manager for the view

            m_SFManager = SpatialFieldManager.GetSpatialFieldManager(m_view);
            if (m_SFManager == null)
            {
                m_SFManager = SpatialFieldManager.CreateSpatialFieldManager(m_view, 1);
            }

            // For the sake of simplicity, we remove any previous results

            m_SFManager.Clear();

            // register schema for the results

            AnalysisResultSchema schema = new AnalysisResultSchema("E4623E91-8044-4721-86EA-2893642F13A9", "SDK2014-AL, Sample Schema");

            m_schemaId = m_SFManager.RegisterResult(schema);

            // Add a spatial field for our face reference

            m_fieldId = m_SFManager.AddSpatialFieldPrimitive(GetReference());

            m_needInitialization = false;
        }
예제 #3
0
        /// <summary>
        /// Prepares a container object that carries out the calculations without invoking Revit API calls.
        /// </summary>
        /// <param name="element">The element for the calculations.</param>
        /// <returns>The container.</returns>
        public static MultithreadedCalculationContainer CreateContainer(Element element)
        {
            Document doc        = element.Document;
            View     activeView = doc.GetElement(s_activeViewId) as View;

            // Figure out which is the largest face facing the user
            XYZ  viewDirection = activeView.ViewDirection.Normalize();
            Face biggestFace   = GetBiggestFaceFacingUser(element, viewDirection);

            // Get or create SpatialFieldManager for AVF results
            SpatialFieldManager sfm = SpatialFieldManager.GetSpatialFieldManager(activeView);

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

            // Reference the target face
            s_spatialFieldId = sfm.AddSpatialFieldPrimitive(biggestFace.Reference);

            // Compute the range of U and V for the calculation
            BoundingBoxUV bbox = biggestFace.GetBoundingBox();

            return(new MultithreadedCalculationContainer(doc.PathName, bbox.Min, bbox.Max));
        }
예제 #4
0
        internal static void Clear(Autodesk.Revit.UI.UIDocument uiDoc)
        {
            Document    doc = uiDoc.Document;
            Transaction t   = null;

            if (doc.IsModifiable == false)
            {
                t = new Transaction(doc, "Clear Visualizations");
                t.Start();
            }
            SpatialFieldManager sfm = null;

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

            sfm.Clear();

            if (t != null)
            {
                t.Commit();
            }
        }
예제 #5
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);
        }
예제 #6
0
        /// <summary>
        /// Initialise the external webcam event driver.
        /// </summary>
        public static void Start(View view, Reference r)
        {
            _faceReference = r;

            SpatialFieldManager sfm
                = SpatialFieldManager.GetSpatialFieldManager(
                      view);

            if (null == sfm)
            {
                sfm = SpatialFieldManager
                      .CreateSpatialFieldManager(view, 1);
            }
            else if (0 < _sfp_index)
            {
                sfm.RemoveSpatialFieldPrimitive(
                    _sfp_index);

                _sfp_index = -1;
            }

            _sfp_index = sfm.AddSpatialFieldPrimitive(
                _faceReference);

            _event = ExternalEvent.Create(
                new WebcamEventHandler());

            Thread thread = new Thread(
                new ThreadStart(Run));

            thread.Start();
        }
예제 #7
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();
                }
            }
        }
        private SpatialFieldManager SetSpatialFieldManager(Autodesk.Revit.DB.View view, out int index)
        {
            SpatialFieldManager sfm = null;

            index = -1;
            try
            {
                sfm = SpatialFieldManager.GetSpatialFieldManager(view);

                using (Transaction trans = new Transaction(m_doc))
                {
                    trans.Start("Create Spatial Manager");
                    try
                    {
                        if (null == sfm)
                        {
                            sfm = SpatialFieldManager.CreateSpatialFieldManager(view, 1);
                            List <string> names        = new List <string>();
                            List <string> descriptions = new List <string>();
                            names.Add("Visibility Index");
                            descriptions.Add("0: area with no views, 1: area with views");
                            sfm.SetMeasurementNames(names);
                            sfm.SetMeasurementDescriptions(descriptions);
                        }

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

                        foreach (int i in resultIndices)
                        {
                            AnalysisResultSchema resultSchema = sfm.GetResultSchema(i);
                            if (resultSchema.Name == "View Analysis")
                            {
                                index = i;
                            }
                        }
                        if (index == -1)
                        {
                            AnalysisResultSchema resultSchema = new AnalysisResultSchema("View Analysis", "Calculating area with views");
                            index = sfm.RegisterResult(resultSchema);
                        }

                        trans.Commit();
                    }
                    catch (Exception ex)
                    {
                        string message = ex.Message;
                        trans.RollBack();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Set Spatial Field Manager.\n" + ex.Message, "Set Spatial Field Manager", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            return(sfm);
        }
예제 #9
0
        public SpatialFieldManager GetSpatialFieldManager(int numOfMeasurments)
        {
            var sfm = SpatialFieldManager.GetSpatialFieldManager(this.RevitView);

            if (null == sfm || sfm.NumberOfMeasurements != numOfMeasurments)
            {
                sfm = SpatialFieldManager.CreateSpatialFieldManager(this.RevitView, numOfMeasurments);
            }
            return(sfm);
        }
예제 #10
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);
        }
예제 #11
0
        /// <summary>
        /// Set up the AVF spatial field manager
        /// for the given view.
        /// </summary>
        static void SetUpAvfSfm(
            View view,
            Reference faceReference)
        {
            if (view.AnalysisDisplayStyleId
                == ElementId.InvalidElementId)
            {
                SetAvfDisplayStyle(view);
            }

            _sfm = SpatialFieldManager
                   .GetSpatialFieldManager(view);

            if (null == _sfm)
            {
                _sfm = SpatialFieldManager
                       .CreateSpatialFieldManager(view, 1);
            }
            else if (0 < _sfp_index)
            {
                _sfm.RemoveSpatialFieldPrimitive(
                    _sfp_index);
            }

            _sfp_index = _sfm.AddSpatialFieldPrimitive(
                faceReference);

            if (-1 != _schemaId)
            {
                IList <int> results = _sfm.GetRegisteredResults();
                if (!results.Contains(_schemaId))
                {
                    _schemaId = -1;
                }
            }

            if (-1 == _schemaId)
            {
                AnalysisResultSchema schema
                    = new AnalysisResultSchema("Attenuation",
                                               "RvtFader signal attenuation");

                List <string> unitNames = new List <string>(new string[1] {
                    "dB"
                });
                List <double> unitFactors = new List <double>(new double[1] {
                    1.0
                });
                schema.SetUnits(unitNames, unitFactors);

                _schemaId = _sfm.RegisterResult(schema);
            }
        }
예제 #12
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            var uiApp = commandData.Application;
            var doc   = uiApp.ActiveUIDocument.Document;

            SetStatusText("Updating CO2e visualisation...");

            var view = new ViewFinder(doc).Get3DViewNamed("CO2e");

            if (view == null)
            {
                TaskDialog.Show("Error", "A 3D view named 'CO2e' must exist to view the AMEE CO2e visualization.");
                return(Result.Failed);
            }

            new AnalysisDisplayStyles().SetCO2eAnalysisDisplayStyle(view);

            var sfm = SpatialFieldManager.GetSpatialFieldManager(view);

            if (sfm == null)
            {
                sfm = SpatialFieldManager.CreateSpatialFieldManager(view, 1);              // One measurement value for each point
            }
            sfm.Clear();

            var sw = new Stopwatch();

            sw.Start();
            var collector = new FilteredElementCollector(doc, view.Id);
            ICollection <Element> co2eElements = collector.WherePasses(Settings.CreateFilterForElementsWithCO2eParameter()).WhereElementIsNotElementType().ToElements();
            var count = 0;

            foreach (var element in co2eElements)
            {
                if (count++ > 200)
                {
                    logger.InfoFormat("Skipping CO2e visualisation update for element {0} since we have already updated more than 200", element.Name);
                    continue;
                }
                SetStatusText("Updating CO2e visualisation for element {0}...", element.Name);
                CO2eVisualisationCreator.UpdateCO2eVisualization(sfm, element);
            }

            sw.Stop();
            SetStatusText("Updated all CO2e visualisations in {0}", sw.Elapsed);
            logger.InfoFormat("Updated all CO2e visualisations in {0}", sw.Elapsed);

            return(Result.Succeeded);
        }
        /// <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);
            }
        }
예제 #14
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));
        }
예제 #15
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();
        }
        /// <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);
            }
        }
예제 #17
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;
                        }
                    }
                }
            }
예제 #18
0
        internal static void ShowVectors(Document doc, IList <Objects.VectorObject> points, bool scaleVectors)
        {
            double viewScale = 12.0 / Convert.ToDouble(doc.ActiveView.Scale);


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

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

            if (sfm == null)
            {
                throw new System.ApplicationException("SFM still null!");
            }
            sfm.Clear();

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

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

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



            IList <VectorAtPoint> valList   = new List <VectorAtPoint>();
            List <XYZ>            dummyList = new List <XYZ>();

            dummyList.Add(XYZ.BasisZ);

            FieldDomainPointsByXYZ pnts = null;

            FieldValues vals = null;

            List <XYZ>    tmpXYZ   = new List <XYZ>();
            List <string> tmpNames = new List <String>();

            int idx             = sfm.AddSpatialFieldPrimitive();
            int localPointCount = 0;
            int max             = points.Count;

            for (int i = 0; i < max; i++)
            {
                tmpXYZ.Add(points[i].Origin);


                if (scaleVectors)
                {
                    dummyList[0] = points[i].Vector.Multiply(viewScale);
                }
                else
                {
                    dummyList[0] = points[i].Vector;
                }
                valList.Add(new VectorAtPoint(dummyList));

                if (localPointCount > MAX_POINTS_PER_PRIMITIVE)
                {
                    pnts = new FieldDomainPointsByXYZ(tmpXYZ);
                    vals = new FieldValues(valList);
                    sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, _SchemaId);

                    // create a new primitive
                    idx = sfm.AddSpatialFieldPrimitive();

                    // reset
                    localPointCount = 0;
                    tmpXYZ          = new List <XYZ>();
                    valList         = new List <VectorAtPoint>();
                }


                localPointCount++;
            }

            // do it one more time if there are leftovers
            if (tmpXYZ.Count > 0)
            {
                pnts = new FieldDomainPointsByXYZ(tmpXYZ);
                vals = new FieldValues(valList);
                sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, _SchemaId);
            }



            updateView(doc.ActiveView, StyleEnum.Vectors);
        }
예제 #19
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;
                }
            }
        }
예제 #20
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;
                }
            }
        }
예제 #21
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>();

            try
            {
                refList = uiDoc.Selection.PickObjects(Autodesk.Revit.UI.Selection.ObjectType.Face);
            }
            catch (Exception)
            {
                //    throw;
            }
            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;

                uvPts.Add(min);
                uvPts.Add(max);
                valList.Add(new ValueAtPoint(new List <double>()
                {
                    0
                }));
                valList.Add(new ValueAtPoint(new List <double>()
                {
                    0
                }));

                /*
                 * 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(0);
                 *          valList.Add(new ValueAtPoint(doubleList));
                 *          doubleList.Clear();
                 *      }
                 *  }
                 * }*/

                //FieldDomainPointsByUV pnts = new FieldDomainPointsByUV(uvPts);

                var points = new FieldDomainPointsByXYZ(new List <XYZ>()
                {
                    new XYZ(0, 0, 0), new XYZ(0, 0, 10)
                });

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



            return(Result.Succeeded);
        }
예제 #22
0
        public static SpatialFieldManager GetSpatialFieldManager(Document doc)
        {
            var sfm = SpatialFieldManager.GetSpatialFieldManager(doc.ActiveView) ?? SpatialFieldManager.CreateSpatialFieldManager(doc.ActiveView, 1);

            return(sfm);
        }
        public bool CreateSpatialField()
        {
            bool result = false;

            try
            {
                SpatialFieldManager sfm = SpatialFieldManager.GetSpatialFieldManager(doc.ActiveView);
                switch (settings.ResultType)
                {
                case ResultType.MassAnalysis:
                    if (sfm == null)
                    {
                        sfm = SpatialFieldManager.CreateSpatialFieldManager(doc.ActiveView, settings.NumberOfMeasurement);
                    }
                    sfm.SetMeasurementNames(settings.Configurations.Keys.ToList());
                    sfm.SetMeasurementDescriptions(settings.Configurations.Values.ToList());

                    if (IsAnalysisByFaces())
                    {
                        result = AnalysisByFaces(sfm);
                    }
                    else
                    {
                        result = AnalysisByElements(sfm);
                    }
                    break;

                case ResultType.FARCalculator:
                    if (sfm == null)
                    {
                        sfm = SpatialFieldManager.CreateSpatialFieldManager(doc.ActiveView, settings.NumberOfMeasurement);
                    }
                    sfm.SetMeasurementNames(settings.Configurations.Keys.ToList());
                    sfm.SetMeasurementDescriptions(settings.Configurations.Values.ToList());

                    FARCalculator farCalculator = new FARCalculator(doc, settings, progressBar, sfm);
                    if (farCalculator.MapMassToArea())
                    {
                        farCalculator.UnitNames   = unitNames;
                        farCalculator.Multipliers = multipliers;
                        result = farCalculator.AnalysisByElements();
                    }
                    break;

                case ResultType.Topography:
                    break;

                case ResultType.BuildingNetwork:
                    break;

                case ResultType.FacadeAnalysis:
                    break;

                case ResultType.HeatMap:
                    break;

                case ResultType.RadianceAnalysis:
                    if (sfm == null)
                    {
                        sfm = SpatialFieldManager.CreateSpatialFieldManager(doc.ActiveView, 3);
                    }
                    List <string> measurementNames = new List <string>();
                    measurementNames.Add("Value 1"); measurementNames.Add("Value 2"); measurementNames.Add("Value 3");
                    sfm.SetMeasurementNames(measurementNames);
                    sfm.SetMeasurementDescriptions(measurementNames);

                    RadianceDisplay radianceDisplay = new RadianceDisplay(doc, settings, progressBar, sfm);
                    if (File.Exists(settings.ReferenceDataFile))
                    {
                        if (radianceDisplay.ReadDatFile())
                        {
                            radianceDisplay.UnitNames   = unitNames;
                            radianceDisplay.Multipliers = multipliers;
                            result = radianceDisplay.AnalysisByElements();
                        }
                    }
                    else
                    {
                        MessageBox.Show("Please import a data file to display the result of the readiance analysis.", "File Not Found : Data File", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    break;

                case ResultType.FieldOfView:
                    if (sfm == null)
                    {
                        sfm = SpatialFieldManager.CreateSpatialFieldManager(doc.ActiveView, settings.NumberOfMeasurement);
                    }
                    sfm.SetMeasurementNames(settings.Configurations.Keys.ToList());
                    sfm.SetMeasurementDescriptions(settings.Configurations.Values.ToList());

                    FieldOfViewAnalysis viewAnalysis = new FieldOfViewAnalysis(doc, settings, progressBar, sfm);
                    if (null != viewAnalysis.FindPointOfView())
                    {
                        viewAnalysis.UnitNames   = unitNames;
                        viewAnalysis.Multipliers = multipliers;
                        result = viewAnalysis.AnalysisByElements();
                    }
                    break;

                case ResultType.CustomizedAnalysis:
                    break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to create spatial filed. \n" + ex.Message, "AnalysisDataManager : CreateSpatialField", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            return(result);
        }
        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);
        }
예제 #25
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;
                }
            }
        }
예제 #26
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();
        }
        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);
            }
        }