Exemplo n.º 1
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);
            }
        }
Exemplo n.º 2
0
        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...
            }
        }
Exemplo n.º 3
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();
        }
Exemplo n.º 4
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>
        /// <param name="data"></param>
        /// <param name="primitiveIds"></param>
        /// <param name="schemaName"></param>
        /// <param name="description"></param>
        /// <param name="unitType"></param>
        private void InternalSetSpatialFieldValues(IStructuredData <Point, double> data, ref List <int> primitiveIds, string schemaName, string description, Type unitType)
        {
            TransactionManager.Instance.EnsureInTransaction(Document);

            // We chunk here because the API has a limitation for the
            // number of points that can be sent in one run.

            var chunkSize = 1000;

            var dataLocations = data.ValueLocations.Select(l => l.ToXyz());
            var values        = data.Values.ToList();

            while (dataLocations.Any())
            {
                // Compute the chunks
                var pointLocationChunk = dataLocations.Take(chunkSize);
                var valuesChunk        = values.Take(chunkSize).ToList();

                // Create the ValueAtPoint objects
                var valList = valuesChunk.Select(n => new ValueAtPoint(new List <double> {
                    n
                }));

                // Create the field domain points and values
                var samplePts    = new FieldDomainPointsByXYZ(pointLocationChunk.ToList());
                var sampleValues = new FieldValues(valList.ToList());

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

                // Update the values
                var primitiveId = SpatialFieldManager.AddSpatialFieldPrimitive();
                primitiveIds.Add(primitiveId);
                SpatialFieldManager.UpdateSpatialFieldPrimitive(primitiveId, samplePts, sampleValues, schemaIndex);

                dataLocations = dataLocations.Skip(chunkSize);
                values        = values.Skip(chunkSize).ToList();
            }

            TransactionManager.Instance.TransactionTaskDone();
        }
        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);
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Create a Vector Analysis Display in the current view
        /// </summary>
        /// <param name="view"></param>
        /// <param name="data"></param>
        /// <param name="resultsName"></param>
        /// <param name="description"></param>
        /// <param name="unitType"></param>
        private VectorAnalysisDisplay(Autodesk.Revit.DB.View view, VectorData data,
                                      string resultsName, string description, Type unitType)
        {
            SpatialFieldManager sfm;
            var primitiveIds = new List <int>();

            TransactionManager.Instance.EnsureInTransaction(Document);

            var TraceData = GetElementAndPrimitiveIdFromTrace();

            if (TraceData != null)
            {
                sfm          = TraceData.Item1;
                primitiveIds = TraceData.Item2;
                foreach (var idx in primitiveIds)
                {
                    sfm.RemoveSpatialFieldPrimitive(idx);
                }
                primitiveIds.Clear();
            }
            else
            {
                sfm = GetSpatialFieldManagerFromView(view);

                sfm.SetMeasurementNames(new List <string>()
                {
                    Properties.Resources.Dynamo_AVF_Data_Name
                });
            }

            InternalSetSpatialFieldManager(sfm);

            var primitiveId = SpatialFieldManager.AddSpatialFieldPrimitive();

            InternalSetSpatialFieldValues(primitiveId, data, resultsName, description, unitType);
            primitiveIds.Add(primitiveId);
            InternalSetSpatialPrimitiveIds(primitiveIds);
            TransactionManager.Instance.TransactionTaskDone();
            SetElementAndPrimitiveIdsForTrace(sfm, primitiveIds);
        }
Exemplo n.º 7
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);
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Create a Point Analysis Display in the current view
        /// </summary>
        /// <param name="view"></param>
        /// <param name="faceReference"></param>
        /// <param name="sampleLocations"></param>
        /// <param name="samples"></param>
        private FaceAnalysisDisplay(Autodesk.Revit.DB.View view, Reference faceReference, IEnumerable <Autodesk.Revit.DB.UV> sampleLocations,
                                    IEnumerable <double> samples)
        {
            var sfm = GetSpatialFieldManagerFromView(view);

            var sfmAndId = GetElementAndPrimitiveIdFromTrace();

            // we can rebind as we're dealing with the same view
            if (sfmAndId != null && sfmAndId.Item1.Id == sfm.Id)
            {
                InternalSetSpatialFieldManager(sfmAndId.Item1);
                InternalSetPrimitiveId(sfmAndId.Item2);
                InternalSetSpatialFieldValues(sampleLocations, samples);
                return;
            }

            // the input view has changed, remove the old primitive from the old view
            if (sfmAndId != null)
            {
                var oldSfm = sfmAndId.Item1;
                var oldId  = sfmAndId.Item2;

                oldSfm.RemoveSpatialFieldPrimitive(oldId);
            }

            // create a new spatial field primitive
            TransactionManager.Instance.EnsureInTransaction(Document);

            InternalSetSpatialFieldManager(sfm);

            var primitiveId = SpatialFieldManager.AddSpatialFieldPrimitive(faceReference);

            InternalSetPrimitiveId(primitiveId);
            InternalSetSpatialFieldValues(sampleLocations, samples);

            SetElementAndPrimitiveIdForTrace(SpatialFieldManager, primitiveId);

            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);
            }
        }
Exemplo n.º 10
0
        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);
        }
Exemplo n.º 11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="view"></param>
        /// <param name="data"></param>
        /// <param name="resultsName"></param>
        /// <param name="description"></param>
        /// <param name="unitType"></param>
        protected FaceAnalysisDisplay(
            Autodesk.Revit.DB.View view, ISurfaceData <Autodesk.DesignScript.Geometry.UV, double> data, string resultsName, string description, Type unitType)
        {
            SpatialFieldManager sfm;

            // create a new spatial field primitive
            TransactionManager.Instance.EnsureInTransaction(Document);

            var refPriIds    = new Dictionary <Reference, int>();
            var primitiveIds = new List <int>();

            var reference = data.Surface.Tags.LookupTag(DefaultTag) as Reference;

            if (reference == null)
            {
                // Dont' throw an exception here. Handle the case of a bad tag
                // in the static constructor.
                return;
            }

            var TraceData = GetElementAndRefPrimitiveIdFromTrace();

            if (TraceData != null)
            {
                sfm       = TraceData.Item1;
                refPriIds = TraceData.Item2;

                InternalSetSpatialFieldManager(sfm);
                int primitiveId;
                if (refPriIds.TryGetValue(reference, out primitiveId))
                {
                    InternalSetSpatialFieldValues(primitiveId, data, resultsName, description, unitType);

                    TransactionManager.Instance.TransactionTaskDone();

                    return;
                }
                else
                {
                    foreach (var refPriId in refPriIds)
                    {
                        sfm.RemoveSpatialFieldPrimitive(refPriId.Value);
                    }
                    refPriIds.Clear();

                    primitiveId = SpatialFieldManager.AddSpatialFieldPrimitive(reference);
                    primitiveIds.Add(primitiveId);
                    refPriIds.Add(reference, primitiveId);
                    InternalSetSpatialPrimitiveIds(primitiveIds);
                    InternalSetReferencePrimitiveIdPairs(refPriIds);

                    InternalSetSpatialFieldValues(primitiveId, data, resultsName, description, unitType);
                }
            }
            else
            {
                sfm = GetSpatialFieldManagerFromView(view);

                sfm.SetMeasurementNames(new List <string>()
                {
                    Properties.Resources.Dynamo_AVF_Data_Name
                });

                InternalSetSpatialFieldManager(sfm);

                var primitiveId = SpatialFieldManager.AddSpatialFieldPrimitive(reference);
                primitiveIds.Add(primitiveId);
                refPriIds.Add(reference, primitiveId);
                InternalSetSpatialPrimitiveIds(primitiveIds);
                InternalSetReferencePrimitiveIdPairs(refPriIds);

                InternalSetSpatialFieldValues(primitiveId, data, resultsName, description, unitType);
            }

            TransactionManager.Instance.TransactionTaskDone();
            SetElementAndRefPrimitiveIdsForTrace();
        }
Exemplo n.º 12
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;
                }
            }
        }
Exemplo n.º 13
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);
        }
Exemplo n.º 14
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;
                }
            }
        }
Exemplo n.º 15
0
        public bool AnalysisByElements()
        {
            bool result = false;

            try
            {
                if (radianceDictionary.Count > 0)
                {
                    int                  resultIndex = FindIndexOfResult(sfm);
                    bool                 firstLoop   = true;
                    int                  index       = sfm.AddSpatialFieldPrimitive();//not associated with any geometry
                    IList <XYZ>          xyzPoints   = new List <XYZ>();
                    IList <ValueAtPoint> valList     = new List <ValueAtPoint>();

                    foreach (int keyIndex in radianceDictionary.Keys)
                    {
                        RadianceResult rr      = radianceDictionary[keyIndex];
                        List <double>  dblList = new List <double>(); //double values to be displayed on the face.

                        dblList.Add(rr.Value1);
                        dblList.Add(rr.Value2);
                        dblList.Add(rr.Value3);

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

                        xyzPoints.Add(rr.PointXYZ);
                        valList.Add(new ValueAtPoint(dblList));
                        //dblList.Clear();
                    }
                    FieldDomainPointsByXYZ domainPoints = new FieldDomainPointsByXYZ(xyzPoints);
                    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);
        }
Exemplo n.º 16
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();
        }
Exemplo n.º 17
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;
                }
            }
        }
        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);
        }
Exemplo n.º 19
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);
        }
Exemplo n.º 20
0
        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);
        }
Exemplo n.º 21
0
        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);
        }
Exemplo n.º 22
0
        //Display on the floor
        private bool MeasureDistanceOnFloor()
        {
            bool result = false;

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

                //Find point of view from the sphere element
                if (null != sphere)
                {
                    LocationPoint location = sphere.Location as LocationPoint;
                    XYZ           pointXYZ = location.Point;

                    int  resultIndex = FindIndexOfResult(sfm);
                    bool firstLoop   = true;
                    foreach (int floorId in floorFaces.Keys)
                    {
                        Face floorFace = floorFaces[floorId];
                        XYZ  vectorZ   = new XYZ(0, 0, 1);
#if RELEASE2013
                        Transform transform = Transform.get_Translation(vectorZ);
#else
                        Transform transform = Transform.CreateTranslation(vectorZ);
#endif

                        int index = sfm.AddSpatialFieldPrimitive(floorFace, transform);

                        List <double>        doubleList = new List <double>();
                        IList <UV>           uvPoints   = new List <UV>();
                        IList <ValueAtPoint> valList    = new List <ValueAtPoint>();
                        BoundingBoxUV        bb         = floorFace.GetBoundingBox();
                        for (double u = bb.Min.U; u < bb.Max.U; u = u + (bb.Max.U - bb.Min.U) / 30)
                        {
                            for (double v = bb.Min.V; v < bb.Max.V; v = v + (bb.Max.V - bb.Min.V) / 30)
                            {
                                UV uvPoint = new UV(u, v);
                                uvPoints.Add(uvPoint);
                                XYZ faceXYZ = floorFace.Evaluate(uvPoint);
#if RELEASE2013
                                Line line = doc.Application.Create.NewLine(pointXYZ, faceXYZ, true);
#else
                                Line line = Line.CreateBound(pointXYZ, faceXYZ);
#endif
                                double dblValue = 1;

                                IntersectionResultArray resultArray;
                                foreach (int wallId in wallFaces.Keys)
                                {
                                    Face wallFace = wallFaces[wallId];
                                    SetComparisonResult compResult = wallFace.Intersect(line, out resultArray);
                                    //if intersects with walls the level of visibility will have negative values
                                    if (compResult == SetComparisonResult.Overlap && null != resultArray)
                                    {
                                        if (dblValue > 0)
                                        {
                                            dblValue = 0 - resultArray.Size;
                                        }
                                        else
                                        {
                                            dblValue = dblValue - resultArray.Size;
                                        }
                                    }
                                }

                                doubleList.Add(dblValue);
                                valList.Add(new ValueAtPoint(doubleList));
                                doubleList.Clear();
                            }
                            progressBar.PerformStep();
                        }

                        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 floor face.\n" + ex.Message, "FieldOfViewAnalysis:MeasureDistanceOnFloor", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                result = false;
            }
            return(result);
        }
        /// <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);
            }
        }
Exemplo n.º 24
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);
        }