Пример #1
0
        public OptixIntersectionDevice(IRayEngineScene scene, bool lowLatency = false) : base(scene)
        {
            this.lowLatency = lowLatency;
            Context = new Context { CpuNumThreads = 4, RayTypeCount = 1, EntryPointCount = 1 };
            
            var rayBufferDesc = new BufferDesc()
            {
                Format = Format.User,
                Width = (uint)(lowLatency ? RayBuffer.RayBufferSize / 8 : RayBuffer.RayBufferSize),
                Type = BufferType.InputOutput,
                ElemSize = (uint)Marshal.SizeOf(typeof(RayData))
            };
            var rayHitBufferDesc = new BufferDesc()
            {
                Format = Format.User,
                Width =  (uint)(lowLatency ? RayBuffer.RayBufferSize / 8 : RayBuffer.RayBufferSize),
                Type = BufferType.InputOutput,
                ElemSize = (uint)Marshal.SizeOf(typeof(RayHit))
            };

            this.todoRayBuffers = new InputRayBufferCollection();
            this.doneRayBuffers = new OutputRayBufferCollection();
            this.started = false;

            Rays = new DeviceBuffer(Context, rayBufferDesc);
            RayHits = new DeviceBuffer(Context, rayHitBufferDesc);
            Context["rayHits"].Set(RayHits);
            Context["rays"].Set(Rays);
            Builder = AccelBuilder.TriangleKdTree;
            Traverser = AccelTraverser.KdTree;
            GeoGroup = new GeometryGroup(Context);
            this.SetScene(scene);
        }
Пример #2
0
        public void TestSerialization()
        {
            var geometryGroup = new GeometryGroup { Geometries = new Pablo.Graphics.Geometry[]
            {
                new LineGeometry {Start = new Point(0, 1), End = new Point(2,3)},
                new EllipseGeometry {Center = new Point(4,5), RadiusX = 1, RadiusY = 2},
                new PolygonGeometry {Points = new []{new Point(1,2), new Point(2,2),new Point(3,4),  }},
                new CurveGeometry {Start = new Point(1,2), End = new Point(2,3), Bulge = 1},
            } };

            var writer = new StringWriter();
            _serializer.Serialize(writer, geometryGroup);
            var reader = new StringReader(writer.ToString());

            Assert.AreEqual(geometryGroup, _serializer.Deserialize(reader));
        }
Пример #3
0
        public static GeometryGroup DarkModuleGeometry(BitMatrix matrix)
        {
            GeometryCollection gCollection = new GeometryCollection();
            GeometryGroup gGroup = new GeometryGroup();
            if (matrix == null)
            {
                gGroup.Children = gCollection;
                return gGroup;
            }

            int preX = -1;
            int width = matrix.Width;
            for (int y = 0; y < width; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    if (matrix[x, y])
                    {
                        //Set start point if preX == -1
                        if (preX == -1)
                            preX = x;
                        //If this is last module in that row. Draw rectangle
                        if (x == width - 1)
                        {
                            gCollection.Add(CreateRectGeometry(new Rect(preX, y, x - preX + 1, 1)));
                            preX = -1;
                        }
                    }
                    else if (!matrix[x, y] && preX != -1)
                    {
                        //Here will be first light module after sequence of dark module.
                        //Draw previews sequence of dark Module
                        gCollection.Add(CreateRectGeometry(new Rect(preX, y, x - preX, 1)));
                        preX = -1;
                    }
                }
            }

            gGroup.Children = gCollection;
            return gGroup;
        }
Пример #4
0
        /// <summary>
        /// Draws a collection of rectangles, where all have the same stroke and fill.
        /// This performs better than calling DrawRectangle multiple times.
        /// </summary>
        /// <param name="rectangles">The rectangles.</param>
        /// <param name="fill">The fill color.</param>
        /// <param name="stroke">The stroke color.</param>
        /// <param name="thickness">The stroke thickness.</param>
        public void DrawRectangles(IList<OxyRect> rectangles, OxyColor fill, OxyColor stroke, double thickness)
        {
            var path = new Path();
            this.SetStroke(path, stroke, thickness);
            if (fill.IsVisible())
            {
                path.Fill = this.GetCachedBrush(fill);
            }

            var gg = new GeometryGroup { FillRule = FillRule.Nonzero };
            foreach (var rect in rectangles)
            {
                gg.Children.Add(new RectangleGeometry { Rect = rect.ToRect(true) });
            }

            path.Data = gg;
            this.Add(path);
        }
Пример #5
0
        private void SetCursor(CursorT t)
        {
            Task.Run(() =>
            {
                if (CurrentCursor == t)
                {
                    return;
                }
                CurrentCursor = t;
                switch (t)
                {
                case CursorT.Paint:
                    {
                        Correcting = true;
                        Dispatcher.Invoke(() =>
                        {
                            using var dc = CursorVisual.RenderOpen();
                        });
                    }
                    break;

                case CursorT.Standart:
                    {
                        Correcting = true;
                        Dispatcher.Invoke(() =>
                        {
                            using var dc = CursorVisual.RenderOpen();
                            dc.DrawLine(LinesPen, new Point(-15, 0), new Point(15, 0));
                            dc.DrawLine(LinesPen, new Point(0, -15), new Point(0, 15));
                        });
                    }
                    break;

                case CursorT.Select:
                    {
                        Correcting = false;
                        var geo    = new PathGeometry(new[] { new PathFigure(new Point(0, 0),
                                                                             new[]
                            {
                                new LineSegment(new Point(0, 75), true),
                                new LineSegment(new Point(75, 0), true)
                            },
                                                                             true) }); geo.Freeze();

                        var clip = new GeometryGroup();
                        #region Clip Geometry
                        clip.Children.Add(new CombinedGeometry
                        {
                            GeometryCombineMode = GeometryCombineMode.Exclude,
                            Geometry1           = new EllipseGeometry()
                            {
                                Center  = new Point(150, 235),
                                RadiusX = 65, RadiusY = 65
                            },
                            Geometry2 = new RectangleGeometry(new Rect(
                                                                  new Point(60, 100), new Size(180, 135)))
                        });
                        clip.Children.Add(new CombinedGeometry
                        {
                            GeometryCombineMode = GeometryCombineMode.Exclude,
                            Geometry1           = new EllipseGeometry()
                            {
                                Center  = new Point(150, 235),
                                RadiusX = 50,
                                RadiusY = 50
                            },
                            Geometry2 = new RectangleGeometry(new Rect(
                                                                  new Point(60, 100), new Size(180, 135)))
                        });

                        clip.Children.Add(new CombinedGeometry
                        {
                            GeometryCombineMode = GeometryCombineMode.Exclude,
                            Geometry1           = new EllipseGeometry()
                            {
                                Center  = new Point(135, 50),
                                RadiusX = 50,
                                RadiusY = 50
                            },
                            Geometry2 = new RectangleGeometry(new Rect(
                                                                  new Point(85, 50), new Size(180, 150)))
                        });
                        clip.Children.Add(new CombinedGeometry
                        {
                            GeometryCombineMode = GeometryCombineMode.Exclude,
                            Geometry1           = new EllipseGeometry()
                            {
                                Center  = new Point(135, 50),
                                RadiusX = 35,
                                RadiusY = 35
                            },
                            Geometry2 = new RectangleGeometry(new Rect(
                                                                  new Point(85, 50), new Size(180, 150)))
                        });

                        clip.Children.Add(new CombinedGeometry
                        {
                            GeometryCombineMode = GeometryCombineMode.Exclude,
                            Geometry1           = new EllipseGeometry()
                            {
                                Center  = new Point(150, 200),
                                RadiusX = 35,
                                RadiusY = 35
                            },
                            Geometry2 = new RectangleGeometry(new Rect(
                                                                  new Point(85, 100), new Size(100, 100)))
                        });
                        clip.Children.Add(new CombinedGeometry
                        {
                            GeometryCombineMode = GeometryCombineMode.Exclude,
                            Geometry1           = new EllipseGeometry()
                            {
                                Center  = new Point(150, 200),
                                RadiusX = 20,
                                RadiusY = 20
                            },
                            Geometry2 = new RectangleGeometry(new Rect(
                                                                  new Point(85, 100), new Size(100, 100)))
                        });

                        clip.Children.Add(new CombinedGeometry
                        {
                            GeometryCombineMode = GeometryCombineMode.Union,
                            Geometry1           = new EllipseGeometry()
                            {
                                Center  = new Point(122.5, 80),
                                RadiusX = 7.5,
                                RadiusY = 7.5
                            },
                            Geometry2 = new RectangleGeometry(new Rect(
                                                                  new Point(115, 80), new Size(15, 120)))
                        });
                        clip.Children.Add(new CombinedGeometry
                        {
                            GeometryCombineMode = GeometryCombineMode.Union,
                            Geometry1           = new EllipseGeometry()
                            {
                                Center  = new Point(207.5, 80),
                                RadiusX = 7.5,
                                RadiusY = 7.5
                            },
                            Geometry2 = new RectangleGeometry(new Rect(
                                                                  new Point(200, 80), new Size(15, 155)))
                        });

                        clip.Children.Add(new RectangleGeometry(new Rect(new Point(85, 50), new Size(15, 185))));
                        clip.Children.Add(new RectangleGeometry(new Rect(new Point(170, 50), new Size(15, 150))));
                        #endregion
                        clip.Freeze();

                        Dispatcher.Invoke(() =>
                        {
                            using var dc = CursorVisual.RenderOpen();
                            //dc.PushTransform(new TranslateTransform(-4, 3));
                            //dc.PushTransform(new RotateTransform(-30));
                            //dc.PushTransform(new ScaleTransform(1.5, 1.5));

                            //dc.DrawGeometry(LinesPen.Brush, null, geo);

                            //dc.Pop();
                            //dc.Pop();
                            //dc.Pop();

                            //dc.PushTransform(new TranslateTransform(0, 0));
                            dc.PushTransform(new ScaleTransform(0.10, 0.10));

                            dc.DrawGeometry(LinesPen.Brush, null, geo);
                            dc.DrawGeometry(LinesPen.Brush, null, clip);
                        });
                    }
                    break;

                case CursorT.Hook:
                    {
                        Correcting = false;
                        var geo    = new PathGeometry(new[] { new PathFigure(new Point(4, 0),
                                                                             new[]
                            {
                                new LineSegment(new Point(8, 12), true),
                                new LineSegment(new Point(6, 13), true),
                                new LineSegment(new Point(5, 10), true),
                                new LineSegment(new Point(5, 18), true),
                                new LineSegment(new Point(3, 18), true),
                                new LineSegment(new Point(3, 10), true),
                                new LineSegment(new Point(2, 13), true),
                                new LineSegment(new Point(0, 12), true)
                            },
                                                                             true) }); geo.Freeze();

                        Dispatcher.Invoke(() =>
                        {
                            using var dc = CursorVisual.RenderOpen();
                            dc.PushTransform(new TranslateTransform(-4, 3));
                            dc.PushTransform(new RotateTransform(-30));
                            dc.PushTransform(new ScaleTransform(1.5, 1.5));

                            dc.DrawGeometry(LinesPen.Brush, null, geo);
                        });
                    }
                    break;

                case CursorT.None:
                    {
                        Correcting = true;
                        Dispatcher.Invoke(() =>
                        {
                            using var dc = CursorVisual.RenderOpen();
                        });
                    }
                    break;
                }
                if (MagnetState)
                {
                    MagnetAdd();
                }

                if (t == CursorT.Hook || t == CursorT.Select)
                {
                    Hide = true;
                    Dispatcher.Invoke(() =>
                    {
                        CursorPriceVisual.RenderOpen().Close();
                        CursorTimeVisual.RenderOpen().Close();
                        CursorLinesVisual.RenderOpen().Close();
                    });
                }

                else
                {
                    Hide = false; SetCursorLines();
                }
            });
        }
Пример #6
0
        public static ImageSource GetImage(double shear)
        {
            const double height    = 1;
            const double width     = 1;
            const double lineWidth = 0.08;
            const double lwHalf    = lineWidth / 2;

            // draws a transparent outline to fix the borders
            var outlineDrawing = new GeometryDrawing
            {
                Geometry = new RectangleGeometry(new Rect(-lineWidth, -lineWidth, width + lineWidth, height + lineWidth)),
                Pen      = new Pen(Brushes.Transparent, 0)
            };

            //	outlineDrawing.Brush = new SolidColorBrush(Colors.LightBlue);

            //
            // Create the Geometry to draw.
            //
            shear = -shear;
            var geometryGroup = new GeometryGroup();
            var figure1       = new PathFigure();

            if (shear == 0)
            {
                figure1.StartPoint = new Point(0, 0);
                figure1.Segments.Add(new LineSegment(new Point(0, height), true));
                figure1.Segments.Add(new LineSegment(new Point(width, height), true));
                figure1.Segments.Add(new ArcSegment(new Point(0, 0), new Size(width, height), 90, false, SweepDirection.Counterclockwise, true));
                geometryGroup.Children.Add(new PathGeometry(new PathFigure[] { figure1 }));

                geometryGroup.Children.Add(new EllipseGeometry(new Point(width / 3, height - height / 3), lwHalf, lwHalf));
            }
            else if (shear > 0)
            {
                double phi   = Math.PI / 2 - Math.Atan(shear);
                var    start = new Point(width * Math.Cos(phi), height - height * Math.Sin(phi));
                figure1.StartPoint = start;
                figure1.Segments.Add(new LineSegment(new Point(0, height), true));
                figure1.Segments.Add(new LineSegment(new Point(width, height), true));
                figure1.Segments.Add(new ArcSegment(start, new Size(width, height), 180 * phi / Math.PI, false, SweepDirection.Counterclockwise, true));

                var figure2 = new PathFigure
                {
                    StartPoint = new Point(0, 0)
                };
                figure2.Segments.Add(new ArcSegment(start, new Size(width, height), 180 - 180 * phi / Math.PI, false, SweepDirection.Clockwise, true));
                figure2.IsFilled = false;

                geometryGroup.Children.Add(new PathGeometry(new PathFigure[] { figure1, figure2 }));
            }
            else if (shear < 0)
            {
                double phi   = Math.PI / 2 - Math.Atan(-shear);
                var    start = new Point(width - width * Math.Cos(phi), height - height * Math.Sin(phi));
                figure1.StartPoint = start;
                figure1.Segments.Add(new LineSegment(new Point(width, height), true));
                figure1.Segments.Add(new LineSegment(new Point(0, height), true));
                figure1.Segments.Add(new ArcSegment(start, new Size(width, height), 180 * phi / Math.PI, false, SweepDirection.Clockwise, true));

                var figure2 = new PathFigure
                {
                    StartPoint = new Point(width, 0)
                };
                figure2.Segments.Add(new ArcSegment(start, new Size(width, height), 180 - 180 * phi / Math.PI, false, SweepDirection.Counterclockwise, true));
                figure2.IsFilled = false;

                geometryGroup.Children.Add(new PathGeometry(new PathFigure[] { figure1, figure2 }));
            }

            var geometryDrawing = new GeometryDrawing
            {
                Geometry = geometryGroup,

                // Outline the drawing with a solid color.
                Pen = new Pen(Brushes.Black, lineWidth)
                {
                    LineJoin = PenLineJoin.Round
                },
                Brush =
                    new LinearGradientBrush(
                        Color.FromRgb(100, 100, 255),
                        Color.FromRgb(204, 204, 255),
                        new Point(0, 0),
                        new Point(1, 1))
            };

            var group = new DrawingGroup();

            group.Children.Add(outlineDrawing);
            group.Children.Add(geometryDrawing);
            var geometryImage = new DrawingImage(group);

            // Freeze the DrawingImage for performance benefits.
            geometryImage.Freeze();
            return(geometryImage);
        }
Пример #7
0
 public virtual void Draw(GeometryGroup mainDrawingGroup)
 {
     mainDrawingGroup.Children.Add(new RectangleGeometry(new Rect(upperLeft, downRight)));
 }
Пример #8
0
        private void BuildGeometry(SceneMeshData SceneData, SceneMeshEntity[] sceneMesh, bool hasAreaLights = false, IEnumerable<SceneLightsource> areaLights = null)
        {
            topObject = new GeometryGroup(Session.OptixContext);
            Session.OptixContext["scene_sphere_radius"].Set(SceneData.BoundingSphereRadius);
            Session.OptixContext["scene_sphere_center"].SetFloat3(SceneData.BoundingSphereCenter);

            var vDesc = new BufferDesc { Width = (uint)SceneData.Positions.Count, Format = Format.Float3, Type = BufferType.Input };
            var nDesc = new BufferDesc { Width = (uint)SceneData.Normals.Count, Format = Format.Float3, Type = BufferType.Input };
            var tcDesc = new BufferDesc { Width = (uint)SceneData.TexCoords.Count, Format = Format.Float2, Type = BufferType.Input };

            var vBuffer = new Buffer(Session.OptixContext, vDesc);
            var nBuffer = new Buffer(Session.OptixContext, nDesc);
            var tcBuffer = new Buffer(Session.OptixContext, tcDesc);

            vBuffer.SetData(SceneData.Positions.ToArray());
            nBuffer.SetData(SceneData.Normals.ToArray());
            tcBuffer.SetData(SceneData.TexCoords.ToArray());

            var lightTriangleIndexes = new Dictionary<string, List<int>>(StringComparer.InvariantCultureIgnoreCase);

            var instances = new List<GeometryInstance>();
            var triLights = new List<TriangleLight>();
            int idx = 0;
            foreach (var group in sceneMesh)
            {
                //empty group

                if (group.VertexIndexes.Count == 0 && group.NormalIndexes.Count == 0 && group.TextureIndexes.Count == 0)
                    continue;

                var center = new Vector3();
                foreach (var vi in group.VertexIndexes)
                {
                    center += SceneData.Positions[vi.X];
                    center += SceneData.Positions[vi.Y];
                    center += SceneData.Positions[vi.Z];
                    center /= 3.0f;
                }
                //ValidateGroup( group );

                //var mat = this.ResolveMaterial(group.Material);

                bool normalsUseVIndices = GenerateNormals && group.NormalIndexes.Count == 0 && SceneData.Normals.Count > 0;

                if (normalsUseVIndices)
                    Debug.Assert(SceneData.Normals.Count == SceneData.Positions.Count);

                int numNormIndices = normalsUseVIndices ? group.VertexIndexes.Count : group.NormalIndexes.Count;

                var viDesc = new BufferDesc() { Width = (uint)group.VertexIndexes.Count, Format = Format.Int3, Type = BufferType.Input };
                var niDesc = new BufferDesc() { Width = (uint)numNormIndices, Format = Format.Int3, Type = BufferType.Input };
                var tiDesc = new BufferDesc() { Width = (uint)group.TextureIndexes.Count, Format = Format.Int3, Type = BufferType.Input };

                var viBuffer = new Buffer(Session.OptixContext, viDesc);
                var niBuffer = new Buffer(Session.OptixContext, niDesc);
                var tiBuffer = new Buffer(Session.OptixContext, tiDesc);

                viBuffer.SetData(group.VertexIndexes.ToArray());
                niBuffer.SetData(normalsUseVIndices ? group.VertexIndexes.ToArray() : group.NormalIndexes.ToArray());
                tiBuffer.SetData(group.TextureIndexes.ToArray());

                var geometry = new Geometry(Session.OptixContext);
                string intersect_program = "mesh_intersect";
                string isect_script = IntersectionScript;
                //if (!string.IsNullOrWhiteSpace(group.mtrl) && matTypes.ContainsKey(group.mtrl))
                //{
                //    if (matTypes[group.mtrl].Equals("Volume"))
                //    {
                //        intersect_program = "volume_mesh_intersect";
                //        isect_script = GetScript("triangle_mesh_iterative.ptx");
                //    }
                //}

                geometry.IntersectionProgram = new Program(Session.OptixContext, isect_script, intersect_program);
                geometry.BoundingBoxProgram = new Program(Session.OptixContext, isect_script, "mesh_bounds");
                geometry.PrimitiveCount = (uint)group.VertexIndexes.Count;

                geometry["vertex_buffer"].Set(vBuffer);
                geometry["normal_buffer"].Set(nBuffer);
                geometry["texcoord_buffer"].Set(tcBuffer);
                geometry["vindex_buffer"].Set(viBuffer);
                geometry["nindex_buffer"].Set(niBuffer);
                geometry["tindex_buffer"].Set(tiBuffer);

                var instance = new GeometryInstance(Session.OptixContext);
                instance.Geometry = geometry;
                instance["geometric_center"].SetFloat3(center);
                //instance.AddMaterial(mat);
                group.EngineEntity = geometry;
                if (group.Material != null)
                {
                    int lindex;
                    if (hasAreaLights && MeshIsLight(group.Name, out lindex))
                    {
                        instance.AddMaterial(this.GetLightMaterial(group.Material, lindex));
                    }
                    else
                    {
                        var mtrl = ResolveMaterial(group.Material);

                        if (mtrl != null)
                        {
                            group.Material.EngineEntity = mtrl;
                            instance.AddMaterial(mtrl);
                            SetDefaultMaterialProperties(instance, mtrl, group.Material);
                        }
                        else
                        {
                            Tracer.WriteLine("Mesh {0} missed material {1}", group.Name, group.Material.Name);
                        }
                    }
                }
                else
                {
                    Tracer.WriteLine("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ----Mesh {0} missed material {1}", group.Name, group.Material);
                    Console.ReadLine();
                }

                //if (!string.IsNullOrWhiteSpace(LightNameTemplate))
                //{
                //    Regex lightReg = new Regex(LightNameTemplate, RegexOptions.IgnoreCase);

                //    if (lightReg.IsMatch(group.Name))
                //    {
                //        var lt = new Lightsource()
                //        {
                //            Type = LightSourceTypes.Area,
                //            Emission = Scene.LightGain,
                //            Name = group.Name,
                //        };
                //        lt[Lightsource.AreaMeshName] = group.Name;
                //        Scene.Lights = Scene.Lights.Union(new[] { lt }).ToArray();
                //    }
                //}

                if (hasAreaLights)
                {
                    var light =
                        areaLights.FirstOrDefault(
                            lt => lt.Name.Equals(group.Name, StringComparison.InvariantCultureIgnoreCase));
                    //    SetDefaultLightProperties(instance, light);

                    if (light != null)
                    {
                        var ti = new List<int>();
                        lightTriangleIndexes.Add(group.Name, ti);
                        for (int index = 0; index < group.VertexIndexes.Count; index++)
                        {
                            var vIndex = group.VertexIndexes[index];
                            var v1 = SceneData.Positions[vIndex.X];
                            var v2 = SceneData.Positions[vIndex.Y];
                            var v3 = SceneData.Positions[vIndex.Z];
                            var e1 = v2 - v3;
                            var e2 = v1 - v3;
                            Vector3 n = Vector3.Cross(ref e1, ref e2);//SceneGraph.LightOrientation *
                            if (group.NormalIndexes.Any())
                            {
                                n = (SceneData.Normals[group.NormalIndexes[index].X]);//Scene.LightOrientation *
                            }

                            n.Normalize();
                            ti.Add(idx + 1);
                            triLights.Add(new TriangleLight()
                            {
                                color = light.Color, //Emission * emissionScale,
                                v1 = v1,
                                v2 = v2,
                                v3 = v3,
                                normal = n,
                                idx = idx++
                            });
                        }
                    }
                }
                instances.Add(instance);
            }

            var Builder = AccelBuilder.Sbvh;
            var Traverser = AccelTraverser.Bvh;

            //create an acceleration structure for the geometry
            var accel = new Acceleration(Session.OptixContext, Builder, Traverser);

            if (Builder == AccelBuilder.Sbvh || Builder == AccelBuilder.TriangleKdTree)
            {
                accel.VertexBufferName = "vertex_buffer";
                accel.IndexBufferName = "vindex_buffer";
            }

            //now attach the instance and accel to the geometry group
            topObject.Acceleration = accel;
            topObject.AddChildren(instances);
            topObject.Acceleration.MarkAsDirty();
            BuildCache.Add("LightTrianglesIndexes", lightTriangleIndexes);
            BuildCache.Add("LightTriangles", triLights);
        }
Пример #9
0
        /// <summary>
        /// Updates the segments based on its data point value. This method is not
        /// intended to be called explicitly outside the Chart but it can be overridden by
        /// any derived class.
        /// </summary>
        /// <param name="transformer">Represents the view port of chart control.(refer <see cref="IChartTransformer"/>)</param>
        public override void Update(IChartTransformer transformer)
        {
            if (!this.IsSegmentVisible)
            {
                segmentPath.Visibility = Visibility.Collapsed;
            }
            else
            {
                segmentPath.Visibility = Visibility.Visible;
            }

            segmentPath.StrokeLineJoin      = PenLineJoin.Round;
            segmentPath.Width               = transformer.Viewport.Width;
            segmentPath.Height              = transformer.Viewport.Height;
            segmentPath.VerticalAlignment   = VerticalAlignment.Center;
            segmentPath.HorizontalAlignment = HorizontalAlignment.Center;
            double actualRadius = Math.Min(transformer.Viewport.Width, transformer.Viewport.Height) / 2;
            double equalParts   = actualRadius / (pieSeriesCount);

            if (pieIndex == 0)
            {
                Point center;
                if (pieSeriesCount == 1)
                {
                    center = (Series as CircularSeriesBase).Center;
                }
                else
                {
                    center = ChartLayoutUtils.GetCenter(transformer.Viewport);
                }

                double radius = parentSeries.InternalPieCoefficient * (equalParts);
                parentSeries.Radius = radius;
                if (Math.Round((ActualEndAngle - ActualStartAngle), 2) == 6.28)
                {
                    EllipseGeometry ellipseGeometry = new EllipseGeometry()
                    {
                        Center  = center,
                        RadiusX = radius,
                        RadiusY = radius
                    };
                    this.segmentPath.Data = ellipseGeometry;
                }
                else if ((ActualEndAngle - ActualStartAngle) != 0)
                {
                    if (this.IsExploded)
                    {
                        center = new Point(center.X + (parentSeries.ExplodeRadius * Math.Cos(AngleOfSlice)), center.Y + (parentSeries.ExplodeRadius * Math.Sin(AngleOfSlice)));
                    }
                    startPoint = new Point(center.X + radius * Math.Cos(ActualStartAngle), center.Y + radius * Math.Sin(ActualStartAngle));
                    Point      endPoint = new Point(center.X + radius * Math.Cos(ActualEndAngle), center.Y + radius * Math.Sin(ActualEndAngle));
                    PathFigure figure   = new PathFigure();
                    figure.StartPoint = center;
                    WindowsLineSegment line = new WindowsLineSegment();
                    line.Point = startPoint;
                    figure.Segments.Add(line);

                    ArcSegment seg = new ArcSegment();
                    seg.Point          = endPoint;
                    seg.Size           = new Size(radius, radius);
                    seg.RotationAngle  = ActualEndAngle + ActualStartAngle;
                    seg.IsLargeArc     = ActualEndAngle - ActualStartAngle > Math.PI;
                    seg.SweepDirection = StartAngle > EndAngle ? SweepDirection.Counterclockwise : SweepDirection.Clockwise;
                    figure.Segments.Add(seg);

                    figure.IsClosed         = true;
                    this.segmentGeometry    = new PathGeometry();
                    segmentGeometry.Figures = new PathFigureCollection()
                    {
                        figure
                    };
                    this.segmentPath.Data = segmentGeometry;
                }
                else
                {
                    this.segmentPath.Data = null;
                }
            }
            else if (pieIndex >= 1)
            {
                double radius      = (equalParts * (pieIndex + 1)) - (equalParts * (1 - parentSeries.InternalPieCoefficient));
                double innerRadius = equalParts * pieIndex;
                parentSeries.Radius = radius;

                Point center = ChartLayoutUtils.GetCenter(transformer.Viewport);

                if (this.IsExploded)
                {
                    center = new Point(center.X + (parentSeries.ExplodeRadius * Math.Cos(AngleOfSlice)), center.Y + (parentSeries.ExplodeRadius * Math.Sin(AngleOfSlice)));
                }
                startPoint = new Point(center.X + radius * Math.Cos(ActualStartAngle), center.Y + radius * Math.Sin(ActualStartAngle));
                Point endPoint = new Point(center.X + radius * Math.Cos(ActualEndAngle), center.Y + radius * Math.Sin(ActualEndAngle));

                if (Math.Round((ActualEndAngle - ActualStartAngle), 2) == 6.28)
                {
                    GeometryGroup geometryGroup = new GeometryGroup();
                    geometryGroup.Children.Add(new EllipseGeometry()
                    {
                        Center  = center,
                        RadiusX = radius,
                        RadiusY = radius
                    });
                    geometryGroup.Children.Add(new EllipseGeometry()
                    {
                        Center  = center,
                        RadiusX = innerRadius,
                        RadiusY = innerRadius
                    });
                    this.segmentPath.Data = geometryGroup;
                }
                else if ((ActualEndAngle - ActualStartAngle) != 0)
                {
                    Point startDPoint = new Point(center.X + innerRadius * Math.Cos(ActualStartAngle), center.Y + innerRadius * Math.Sin(ActualStartAngle));
                    Point endDPoint   = new Point(center.X + innerRadius * Math.Cos(ActualEndAngle), center.Y + innerRadius * Math.Sin(ActualEndAngle));

                    PathFigure figure = new PathFigure();
                    figure.StartPoint = startPoint;

                    ArcSegment arcseg = new ArcSegment();
                    arcseg.Point          = endPoint;
                    arcseg.Size           = new Size(radius, radius);
                    arcseg.RotationAngle  = ActualEndAngle - ActualStartAngle;
                    arcseg.IsLargeArc     = ActualEndAngle - ActualStartAngle > Math.PI;
                    arcseg.SweepDirection = StartAngle > EndAngle ? SweepDirection.Counterclockwise : SweepDirection.Clockwise;
                    figure.Segments.Add(arcseg);

                    WindowsLineSegment line = new WindowsLineSegment();
                    line.Point = endDPoint;
                    figure.Segments.Add(line);

                    arcseg                = new ArcSegment();
                    arcseg.Point          = startDPoint;
                    arcseg.Size           = new Size(innerRadius, innerRadius);
                    arcseg.RotationAngle  = ActualEndAngle - ActualStartAngle;
                    arcseg.IsLargeArc     = ActualEndAngle - ActualStartAngle > Math.PI;
                    arcseg.SweepDirection = StartAngle < EndAngle ? SweepDirection.Counterclockwise : SweepDirection.Clockwise;
                    figure.Segments.Add(arcseg);

                    figure.IsClosed         = true;
                    this.segmentGeometry    = new PathGeometry();
                    segmentGeometry.Figures = new PathFigureCollection()
                    {
                        figure
                    };
                    this.segmentPath.Data = segmentGeometry;
                }
                else
                {
                    this.segmentPath.Data = null;
                }
            }
        }
Пример #10
0
        public DrawingBrushExample()
        {
            //
            // Create the Geometry to draw.
            //
            GeometryGroup ellipses = new GeometryGroup();

            ellipses.Children.Add(
                new EllipseGeometry(new Point(50, 50), 45, 20)
                );
            ellipses.Children.Add(
                new EllipseGeometry(new Point(50, 50), 20, 45)
                );

            //
            // Create a GeometryDrawing.
            //
            GeometryDrawing aGeometryDrawing = new GeometryDrawing();

            aGeometryDrawing.Geometry = ellipses;

            // Paint the drawing with a gradient.
            aGeometryDrawing.Brush =
                new LinearGradientBrush(
                    Colors.Blue,
                    Color.FromRgb(204, 204, 255),
                    new Point(0, 0),
                    new Point(1, 1));

            // Outline the drawing with a solid color.
            aGeometryDrawing.Pen = new Pen(Brushes.Black, 10);

            DrawingBrush patternBrush = new DrawingBrush(aGeometryDrawing);

            patternBrush.Viewport = new Rect(0, 0, 0.25, 0.25);
            patternBrush.TileMode = TileMode.Tile;
            patternBrush.Freeze();

            //
            // Create an object to paint.
            //
            Rectangle paintedRectangle = new Rectangle();

            paintedRectangle.Width  = 100;
            paintedRectangle.Height = 100;
            paintedRectangle.Fill   = patternBrush;

            //
            // Place the image inside a border and
            // add it to the page.
            //
            Border exampleBorder = new Border();

            exampleBorder.Child               = paintedRectangle;
            exampleBorder.BorderBrush         = Brushes.Gray;
            exampleBorder.BorderThickness     = new Thickness(1);
            exampleBorder.HorizontalAlignment = HorizontalAlignment.Left;
            exampleBorder.VerticalAlignment   = VerticalAlignment.Top;
            exampleBorder.Margin              = new Thickness(10);

            this.Margin     = new Thickness(20);
            this.Background = Brushes.White;
            this.Content    = exampleBorder;
        }
Пример #11
0
 void AddTheHorizontalLineWithTimeMarks(GeometryGroup geometryGroup)
 {
     geometryGroup.Children.Add(new LineGeometry(new Point(0, 0), new Point(actualWidth, 0)));
     AddVerticalTimeMarks(geometryGroup);
 }
Пример #12
0
        /// <summary>
        /// Adds the scarlet box behind the 'a' characters within the given line
        /// </summary>
        /// <param name="line">Line to add the adornments</param>
        private void CreateVisuals()
        {
            if (VSPackage.Options != null)
            {
                this.layer.RemoveAllAdornments();
                var swapColor = (Color)ColorConverter.ConvertFromString(VSPackage.Options.ArrowColor);

                var swapPenBrush = new SolidColorBrush(swapColor);
                swapPenBrush.Freeze();
                var swapPen = new Pen(swapPenBrush, 2);
                swapPen.Freeze();

                IWpfTextViewLineCollection textViewLines = this.view.TextViewLines;
                int whichSwap = 0;
                foreach (SnapshotSpan snapshotSpan in view.Selection.SelectedSpans)
                {
                    Geometry geometry = textViewLines.GetMarkerGeometry(snapshotSpan);
                    if (geometry != null)
                    {
                        Rect swapRect = new Rect(geometry.Bounds.Location, geometry.Bounds.Size);
                        swapRect.Inflate(4, 4);
                        GeometryGroup swapLine = new GeometryGroup();

                        switch (VSPackage.Options.AdornmentType)
                        {
                        case 1:
                            swapLine = MakeSwapArrow(swapRect);
                            break;

                        case 2:
                            swapLine = MakeSwapBracket(swapRect);
                            break;

                        case 3:
                            swapLine = MakeSwapBadge(swapRect);
                            break;
                        }

                        var drawing = new GeometryDrawing(new SolidColorBrush(swapColor), swapPen, swapLine);
                        drawing.Freeze();

                        var drawingImage = new DrawingImage(drawing);
                        drawingImage.Freeze();

                        var swapImage = new Image
                        {
                            Source = drawingImage,
                        };

                        if (whichSwap == 1)
                        {
                            Canvas.SetLeft(swapImage, swapRect.Right - drawing.Bounds.Width);
                            Canvas.SetTop(swapImage, swapRect.Top);

                            swapImage.RenderTransformOrigin = new Point(0.5, 0.5);
                            var flipTrans = new ScaleTransform(-1, 1);

                            swapImage.RenderTransform = flipTrans;
                        }
                        else
                        {
                            Canvas.SetLeft(swapImage, swapRect.Left);
                            Canvas.SetTop(swapImage, swapRect.Top);
                        }

                        this.layer.AddAdornment(AdornmentPositioningBehavior.TextRelative, snapshotSpan, null, swapImage, null);

                        whichSwap = 1;
                    }
                }
            }
        }
Пример #13
0
        /// <summary>
        /// Draws the collection of ellipses, where all have the same stroke and fill.
        /// This performs better than calling DrawEllipse multiple times.
        /// </summary>
        /// <param name="rectangles">The rectangles.</param>
        /// <param name="fill">The fill color.</param>
        /// <param name="stroke">The stroke color.</param>
        /// <param name="thickness">The stroke thickness.</param>
        public void DrawEllipses(IList<OxyRect> rectangles, OxyColor fill, OxyColor stroke, double thickness)
        {
            var ellipseGeometries = rectangles.Select(x => new EllipseGeometry(this.d2dFactory, x.ToEllipse())).ToArray();
            var group = new GeometryGroup(this.d2dFactory, FillMode.Alternate, ellipseGeometries);

            this.renderUnits.Add(new GeometryRenderUnit(group, this.GetBrush(stroke), this.GetBrush(fill), (float)thickness, null));

            foreach (var geometry in ellipseGeometries)
            {
                geometry.Dispose();
            }
        }
 public ProcessingContext(GeometryGroup group)
 {
     _Path       = new PathGeometry();
     _Geometries = group;
     _Geometries.Children.Add(_Path);
 }
Пример #15
0
 public void init(int x, int y)
 {
     _geometryGroup = new GeometryGroup();
 }
        public MainWindow()
        {
            InitializeComponent();

            Width  = 800;
            Height = 800;

            var bitmap = BitmapFactory.New(800, 800);

            Content = new Image()
            {
                Source = bitmap
            };

            var states = new Stack <State>();

            var str = "L";

            {
                var tbl = new Dictionary <char, string>();

                tbl.Add('L', "|-S!L!Y");
                tbl.Add('S', "[F[FF-YS]F)G]+");
                tbl.Add('Y', "--[F-)<F-FG]-");
                tbl.Add('G', "FGF[Y+>F]+Y");

                for (var i = 0; i < 12; i++)
                {
                    str = Rewrite(tbl, str);
                }
            }

            var sizeGrowth  = -1.359672;
            var angleGrowth = -0.138235;

            State state;

            var lines = new List <Point>();

            var pen = new Pen(new SolidColorBrush(Colors.Black), 0.25);

            var geometryGroup = new GeometryGroup();

            Action buildLines = () =>
            {
                lines.Clear();

                state = new State()
                {
                    x     = 400,
                    y     = 400,
                    dir   = 0,
                    size  = 14.11,
                    angle = -3963.7485
                };

                foreach (var elt in str)
                {
                    if (elt == 'F')
                    {
                        var new_x = state.x + state.size * Math.Cos(state.dir * Math.PI / 180.0);
                        var new_y = state.y + state.size * Math.Sin(state.dir * Math.PI / 180.0);

                        lines.Add(new Point(state.x, state.y));
                        lines.Add(new Point(new_x, new_y));

                        state.x = new_x;
                        state.y = new_y;
                    }
                    else if (elt == '+')
                    {
                        state.dir += state.angle;
                    }

                    else if (elt == '-')
                    {
                        state.dir -= state.angle;
                    }

                    else if (elt == '>')
                    {
                        state.size *= (1.0 - sizeGrowth);
                    }

                    else if (elt == '<')
                    {
                        state.size *= (1.0 + sizeGrowth);
                    }

                    else if (elt == ')')
                    {
                        state.angle *= (1 + angleGrowth);
                    }

                    else if (elt == '(')
                    {
                        state.angle *= (1 - angleGrowth);
                    }

                    else if (elt == '[')
                    {
                        states.Push(state.Clone());
                    }

                    else if (elt == ']')
                    {
                        state = states.Pop();
                    }

                    else if (elt == '!')
                    {
                        state.angle *= -1.0;
                    }

                    else if (elt == '|')
                    {
                        state.dir += 180.0;
                    }
                }
            };

            Action updateBitmap = () =>
            {
                using (bitmap.GetBitmapContext())
                {
                    bitmap.Clear();

                    for (var i = 0; i < lines.Count; i += 2)
                    {
                        var a = lines[i];
                        var b = lines[i + 1];

                        bitmap.DrawLine(
                            (int)a.X, (int)a.Y, (int)b.X, (int)b.Y,
                            Colors.Black);
                    }
                }
            };

            MouseDown += (s, e) =>
            {
                angleGrowth += 0.001;
                Console.WriteLine("angleGrowth: {0}", angleGrowth);

                var sw = Stopwatch.StartNew();

                buildLines();
                updateBitmap();

                sw.Stop();

                Console.WriteLine(sw.Elapsed);
            };

            buildLines();

            updateBitmap();
        }
Пример #17
0
        /// <summary>
        /// Geomtries are created, a tube icon is added to the geometries. Patient is in
        /// a flat lying position in this facility. Staff is displayed  on the bottom of the facility
        /// </summary>
        /// <param name="correspondingEntity">Treatment facility the drawing object represents</param>
        /// <param name="startPosition">Position where the treatment facility should be drawn</param>
        /// <param name="size">Size of treatment facility</param>
        /// <param name="personSize">Height used to visualize persons</param>
        /// <param name="color">Color in which the facility should be displayed</param>
        public DrawMRICTFacility(Entity correspondingEntity,
                                 Point startPosition,
                                 Size size,
                                 double personSize,
                                 Color color)
            : base(correspondingEntity, startPosition, size, personSize, color)
        {
            double lineSize = personSize / 15;

            _patientPositionType = PatientPositionInRoomType.FlatLying;

            Point origin = new Point(0, 0);

            GeometryGroup geometries = new GeometryGroup();

            // outline
            geometries.Children.Add(Geometry.Combine(new RectangleGeometry(new Rect(origin, size), lineSize, lineSize),
                                                     new RectangleGeometry(new Rect(origin + new Vector(lineSize, lineSize), new Size(size.Width - 2 * lineSize, size.Height - 2 * lineSize)), lineSize, lineSize),
                                                     GeometryCombineMode.Exclude,
                                                     Transform.Identity));

            // bed
            GeometryGroup bed = new GeometryGroup();

            bed.FillRule = FillRule.Nonzero;

            Point bedStart = origin + new Vector(origin.X + personSize / 1.5 + lineSize, personSize * 1.6);

            bed.Children.Add(new RectangleGeometry(new Rect(bedStart, new Size(personSize - lineSize, lineSize)), lineSize / 2, lineSize / 2));

            geometries.Children.Add(bed);

            // tube

            EllipseGeometry tubeBig = new EllipseGeometry(bedStart + new Vector(personSize - lineSize, lineSize), personSize / 2, personSize / 2);

            EllipseGeometry tubeInner = new EllipseGeometry(bedStart + new Vector(personSize - lineSize, lineSize), personSize / 4, personSize / 4);

            PathGeometry tubeCutoutInner = Geometry.Combine(tubeBig, tubeInner, GeometryCombineMode.Exclude, Transform.Identity);

            RectangleGeometry rectCutout = new RectangleGeometry(new Rect(bedStart + new Vector(0.4 * personSize, -personSize / 10), new Size(personSize / 2, personSize / 2.8)));

            PathGeometry tube = Geometry.Combine(tubeCutoutInner, rectCutout, GeometryCombineMode.Exclude, Transform.Identity);

            geometries.Children.Add(tube);

            // monitor
            double monitorLineSize = lineSize / 2;
            Size   monitorSize     = new Size(personSize / 3, personSize / 4);

            Point monitorStart = bedStart - new Vector(0, personSize / 3);

            GeometryGroup monitor = new GeometryGroup();

            monitor.FillRule = FillRule.Nonzero;

            monitor.Children.Add(Geometry.Combine(new RectangleGeometry(new Rect(monitorStart + new Vector(-personSize / 2, personSize / 2), monitorSize), monitorLineSize, monitorLineSize),
                                                  new RectangleGeometry(new Rect(monitorStart + new Vector(-personSize / 2 + monitorLineSize, personSize / 2 + monitorLineSize), new Size(monitorSize.Width - 2 * monitorLineSize, monitorSize.Height - 2 * monitorLineSize)), monitorLineSize, monitorLineSize),
                                                  GeometryCombineMode.Exclude,
                                                  Transform.Identity));

            monitor.Children.Add(new RectangleGeometry(new Rect(monitorStart + new Vector(-personSize / 2 + monitorSize.Width / 2 - monitorLineSize / 2, monitorLineSize), new Size(monitorLineSize, personSize / 2 - monitorLineSize)), monitorLineSize, monitorLineSize));
            monitor.Children.Add(new RectangleGeometry(new Rect(monitorStart + new Vector(-personSize / 2 + monitorLineSize, 0), new Size(monitorSize.Width - 2 * monitorLineSize, monitorLineSize)), monitorLineSize, monitorLineSize));


            geometries.Children.Add(monitor);

            _staffStartPosition = new Point(origin.X + 2 * lineSize + personSize / 4, origin.Y + 2 * lineSize);

            _patientInRoomPosition = bedStart + new Vector(0, 1.5 * lineSize);

            _drawingShape.Data = geometries;
        } // end of Constructor
Пример #18
0
 public virtual void RenderGeometry(GeometryGroup geometry, double scale, double x, double y)
 {
 }
Пример #19
0
        Geometry GetRoundRectangleGeometry()
        {
            GeometryGroup roundedRectGeometry = new GeometryGroup
            {
                FillRule = FillRule.Nonzero
            };

            if (CornerRadius.TopLeft > 0)
            {
                roundedRectGeometry.Children.Add(
                    new EllipseGeometry(new Point(Rect.Location.X + CornerRadius.TopLeft, Rect.Location.Y + CornerRadius.TopLeft), CornerRadius.TopLeft, CornerRadius.TopLeft));
            }

            if (CornerRadius.TopRight > 0)
            {
                roundedRectGeometry.Children.Add(
                    new EllipseGeometry(new Point(Rect.Location.X + Rect.Width - CornerRadius.TopRight, Rect.Location.Y + CornerRadius.TopRight), CornerRadius.TopRight, CornerRadius.TopRight));
            }

            if (CornerRadius.BottomRight > 0)
            {
                roundedRectGeometry.Children.Add(
                    new EllipseGeometry(new Point(Rect.Location.X + Rect.Width - CornerRadius.BottomRight, Rect.Location.Y + Rect.Height - CornerRadius.BottomRight), CornerRadius.BottomRight, CornerRadius.BottomRight));
            }

            if (CornerRadius.BottomLeft > 0)
            {
                roundedRectGeometry.Children.Add(
                    new EllipseGeometry(new Point(Rect.Location.X + CornerRadius.BottomLeft, Rect.Location.Y + Rect.Height - CornerRadius.BottomLeft), CornerRadius.BottomLeft, CornerRadius.BottomLeft));
            }

            PathFigure pathFigure = new PathFigure
            {
                IsClosed   = true,
                StartPoint = new Point(Rect.Location.X + CornerRadius.TopLeft, Rect.Location.Y),
                Segments   = new PathSegmentCollection
                {
                    new LineSegment {
                        Point = new Point(Rect.Location.X + Rect.Width - CornerRadius.TopRight, Rect.Location.Y)
                    },
                    new LineSegment {
                        Point = new Point(Rect.Location.X + Rect.Width, Rect.Location.Y + CornerRadius.TopRight)
                    },
                    new LineSegment {
                        Point = new Point(Rect.Location.X + Rect.Width, Rect.Location.Y + Rect.Height - CornerRadius.BottomRight)
                    },
                    new LineSegment {
                        Point = new Point(Rect.Location.X + Rect.Width - CornerRadius.BottomRight, Rect.Location.Y + Rect.Height)
                    },
                    new LineSegment {
                        Point = new Point(Rect.Location.X + CornerRadius.BottomLeft, Rect.Location.Y + Rect.Height)
                    },
                    new LineSegment {
                        Point = new Point(Rect.Location.X, Rect.Location.Y + Rect.Height - CornerRadius.BottomLeft)
                    },
                    new LineSegment {
                        Point = new Point(Rect.Location.X, Rect.Location.Y + CornerRadius.TopLeft)
                    }
                }
            };

            PathFigureCollection pathFigureCollection = new PathFigureCollection
            {
                pathFigure
            };

            roundedRectGeometry.Children.Add(new PathGeometry(pathFigureCollection, FillRule.Nonzero));

            return(roundedRectGeometry);
        }
Пример #20
0
        public LinkShape(int linkNum, Link thisLink, double xOffset, double yOffset, double strokeThickness, double jointSize, Slider bufferRadiusSlider,
                         double startingBufferRadius)
        {
            this.linkNum  = linkNum;
            this.thisLink = thisLink;
            Name          = thisLink.name;
            Fill          = new SolidColorBrush(AHSLtoARGBColor.Convert(DisplayConstants.LinkFillOpacity,
                                                                        DisplayConstants.LinkHueMultiplier * linkNum,
                                                                        DisplayConstants.LinkFillSaturation,
                                                                        DisplayConstants.LinkFillLuminence));
            Stroke = new SolidColorBrush(AHSLtoARGBColor.Convert(DisplayConstants.LinkStrokeOpacity,
                                                                 DisplayConstants.LinkHueMultiplier * linkNum,
                                                                 DisplayConstants.LinkStrokeSaturation,
                                                                 DisplayConstants.LinkStrokeLuminence));
            StrokeThickness = strokeThickness;
            Height          = Width = DisplayConstants.UnCroppedDimension;
            var centers = new List <Point>();

            foreach (var j in thisLink.joints)
            {
                if (j.SlidingWithRespectTo(thisLink))
                {
                    var slideAngle = j.SlideAngleInitial;
                    var dx         = DisplayConstants.InitialSlidingJointLengthMultiplier * startingBufferRadius *
                                     Math.Cos(slideAngle);
                    var dy = DisplayConstants.InitialSlidingJointLengthMultiplier * startingBufferRadius *
                             Math.Sin(slideAngle);
                    centers.Add(new Point(j.xInitial + xOffset + dx, j.yInitial + yOffset + dy));
                    centers.Add(new Point(j.xInitial + xOffset - dx, j.yInitial + yOffset - dy));

                    if (slideHoles == null)
                    {
                        slideHoles = new GeometryGroup {
                            FillRule = FillRule.Nonzero, Children = new GeometryCollection()
                        };
                        slideBorders = new GeometryGroup {
                            FillRule = FillRule.Nonzero, Children = new GeometryCollection()
                        };
                    }
                    if (j.TypeOfJoint == JointType.P)
                    {
                        slideHoles.Children.Add(SlideShapeMaker.MakePSlotHole(j, thisLink, xOffset, yOffset, jointSize, startingBufferRadius));
                    }
                    else
                    {
                        slideHoles.Children.Add(SlideShapeMaker.MakeRPSlotHole(j, thisLink, xOffset, yOffset, jointSize, startingBufferRadius));
                    }
                    slideBorders.Children.Add(SlideShapeMaker.MakePSlotBorder(j, thisLink, xOffset, yOffset, jointSize, startingBufferRadius));
                }
                else
                {
                    centers.Add(new Point(j.xInitial + xOffset, j.yInitial + yOffset));
                }
            }
            if (centers.Count == 1)
            {
                MinimumBufferRadius = DisplayConstants.SingleJointLinkRadiusMultipler * startingBufferRadius;
                Opacity             = DisplayConstants.LinkFillOpacityForOneJointLinks;
                cvxCenters          = centers;
            }
            else
            {
                MinimumBufferRadius = 0.0;
                cvxCenters          = MIConvexHull.Find(centers);
            }
            // the next line can be removed one the binding is established.
            BufferRadius = startingBufferRadius;
            //var binding = new Binding
            //   {
            //       Source = bufferRadiusSlider,
            //       Mode = BindingMode.TwoWay,
            //       Path = new PropertyPath(RangeBase.ValueProperty),
            //   };
            //SetBinding(BufferRadiusProperty, binding);
            Data = RedrawWithNewBufferRadius();
        }
Пример #21
0
        public static APath ToAPath(this Geometry geometry, Context context)
        {
            APath path = new APath();

            float density = context.Resources.DisplayMetrics.Density;

            if (geometry is LineGeometry)
            {
                LineGeometry lineGeometry = geometry as LineGeometry;

                path.MoveTo(
                    density * (float)lineGeometry.StartPoint.X,
                    density * (float)lineGeometry.StartPoint.Y);

                path.LineTo(
                    density * (float)lineGeometry.EndPoint.X,
                    density * (float)lineGeometry.EndPoint.Y);
            }
            else if (geometry is RectangleGeometry)
            {
                Graphics.Rect rect = (geometry as RectangleGeometry).Rect;

                path.AddRect(
                    density * (float)rect.Left,
                    density * (float)rect.Top,
                    density * (float)rect.Right,
                    density * (float)rect.Bottom,
                    APath.Direction.Cw);
            }
            else if (geometry is EllipseGeometry)
            {
                EllipseGeometry ellipseGeometry = geometry as EllipseGeometry;

                path.AddOval(new Graphics.RectF(
                                 density * (float)(ellipseGeometry.Center.X - ellipseGeometry.RadiusX),
                                 density * (float)(ellipseGeometry.Center.Y - ellipseGeometry.RadiusY),
                                 density * (float)(ellipseGeometry.Center.X + ellipseGeometry.RadiusX),
                                 density * (float)(ellipseGeometry.Center.Y + ellipseGeometry.RadiusY)),
                             APath.Direction.Cw);
            }
            else if (geometry is GeometryGroup)
            {
                GeometryGroup geometryGroup = geometry as GeometryGroup;

                path.SetFillType(geometryGroup.FillRule == FillRule.Nonzero ? APath.FillType.Winding : APath.FillType.EvenOdd);

                foreach (Geometry child in geometryGroup.Children)
                {
                    APath childPath = child.ToAPath(context);
                    path.AddPath(childPath);
                }
            }
            else if (geometry is PathGeometry)
            {
                PathGeometry pathGeometry = geometry as PathGeometry;

                path.SetFillType(pathGeometry.FillRule == FillRule.Nonzero ? APath.FillType.Winding : APath.FillType.EvenOdd);

                foreach (PathFigure pathFigure in pathGeometry.Figures)
                {
                    path.MoveTo(
                        density * (float)pathFigure.StartPoint.X,
                        density * (float)pathFigure.StartPoint.Y);

                    Point lastPoint = pathFigure.StartPoint;

                    foreach (PathSegment pathSegment in pathFigure.Segments)
                    {
                        // LineSegment
                        if (pathSegment is LineSegment)
                        {
                            LineSegment lineSegment = pathSegment as LineSegment;

                            path.LineTo(
                                density * (float)lineSegment.Point.X,
                                density * (float)lineSegment.Point.Y);
                            lastPoint = lineSegment.Point;
                        }
                        // PolylineSegment
                        else if (pathSegment is PolyLineSegment)
                        {
                            PolyLineSegment polylineSegment = pathSegment as PolyLineSegment;
                            PointCollection points          = polylineSegment.Points;

                            for (int i = 0; i < points.Count; i++)
                            {
                                path.LineTo(
                                    density * (float)points[i].X,
                                    density * (float)points[i].Y);
                            }
                            lastPoint = points[points.Count - 1];
                        }
                        // BezierSegment
                        else if (pathSegment is BezierSegment)
                        {
                            BezierSegment bezierSegment = pathSegment as BezierSegment;

                            path.CubicTo(
                                density * (float)bezierSegment.Point1.X, density * (float)bezierSegment.Point1.Y,
                                density * (float)bezierSegment.Point2.X, density * (float)bezierSegment.Point2.Y,
                                density * (float)bezierSegment.Point3.X, density * (float)bezierSegment.Point3.Y);

                            lastPoint = bezierSegment.Point3;
                        }
                        // PolyBezierSegment
                        else if (pathSegment is PolyBezierSegment)
                        {
                            PolyBezierSegment polyBezierSegment = pathSegment as PolyBezierSegment;
                            PointCollection   points            = polyBezierSegment.Points;

                            if (points.Count >= 3)
                            {
                                for (int i = 0; i < points.Count; i += 3)
                                {
                                    path.CubicTo(
                                        density * (float)points[i + 0].X, density * (float)points[i + 0].Y,
                                        density * (float)points[i + 1].X, density * (float)points[i + 1].Y,
                                        density * (float)points[i + 2].X, density * (float)points[i + 2].Y);
                                }
                            }

                            lastPoint = points[points.Count - 1];
                        }
                        // QuadraticBezierSegment
                        else if (pathSegment is QuadraticBezierSegment)
                        {
                            QuadraticBezierSegment bezierSegment = pathSegment as QuadraticBezierSegment;

                            path.QuadTo(
                                density * (float)bezierSegment.Point1.X, density * (float)bezierSegment.Point1.Y,
                                density * (float)bezierSegment.Point2.X, density * (float)bezierSegment.Point2.Y);

                            lastPoint = bezierSegment.Point2;
                        }
                        // PolyQuadraticBezierSegment
                        else if (pathSegment is PolyQuadraticBezierSegment)
                        {
                            PolyQuadraticBezierSegment polyBezierSegment = pathSegment as PolyQuadraticBezierSegment;
                            PointCollection            points            = polyBezierSegment.Points;

                            if (points.Count >= 2)
                            {
                                for (int i = 0; i < points.Count; i += 2)
                                {
                                    path.QuadTo(
                                        density * (float)points[i + 0].X, density * (float)points[i + 0].Y,
                                        density * (float)points[i + 1].X, density * (float)points[i + 1].Y);
                                }
                            }

                            lastPoint = points[points.Count - 1];
                        }
                        // ArcSegment
                        else if (pathSegment is ArcSegment)
                        {
                            ArcSegment arcSegment = pathSegment as ArcSegment;

                            List <Point> points = new List <Point>();

                            GeometryHelper.FlattenArc(
                                points,
                                lastPoint,
                                arcSegment.Point,
                                arcSegment.Size.Width,
                                arcSegment.Size.Height,
                                arcSegment.RotationAngle,
                                arcSegment.IsLargeArc,
                                arcSegment.SweepDirection == SweepDirection.CounterClockwise,
                                1);

                            for (int i = 0; i < points.Count; i++)
                            {
                                path.LineTo(
                                    density * (float)points[i].X,
                                    density * (float)points[i].Y);
                            }

                            if (points.Count > 0)
                            {
                                lastPoint = points[points.Count - 1];
                            }
                        }
                    }

                    if (pathFigure.IsClosed)
                    {
                        path.Close();
                    }
                }
            }

            return(path);
        }
Пример #22
0
        /// <summary>
        /// Draw the hatches and the transparent area where isn't covering the elements.
        /// </summary>
        /// <param name="drawingContext"></param>
        private void DrawBackgound(DrawingContext drawingContext)
        {
            PathGeometry hatchGeometry = null;
            Geometry     rectGeometry  = null;

            int count = _elementsBounds.Count;

            if (count != 0)
            {
                // Create a union collection of the element regions.
                for (int i = 0; i < count; i++)
                {
                    Rect hatchRect = _elementsBounds[i];

                    if (hatchRect.IsEmpty)
                    {
                        continue;
                    }

                    hatchRect.Inflate(HatchBorderMargin / 2, HatchBorderMargin / 2);

                    if (hatchGeometry == null)
                    {
                        PathFigure path = new PathFigure();
                        path.StartPoint = new Point(hatchRect.Left, hatchRect.Top);

                        PathSegmentCollection segments = new PathSegmentCollection();

                        PathSegment line = new LineSegment(new Point(hatchRect.Right, hatchRect.Top), true);
                        line.Freeze();
                        segments.Add(line);

                        line = new LineSegment(new Point(hatchRect.Right, hatchRect.Bottom), true);
                        line.Freeze();
                        segments.Add(line);

                        line = new LineSegment(new Point(hatchRect.Left, hatchRect.Bottom), true);
                        line.Freeze();
                        segments.Add(line);

                        line = new LineSegment(new Point(hatchRect.Left, hatchRect.Top), true);
                        line.Freeze();
                        segments.Add(line);

                        segments.Freeze();
                        path.Segments = segments;

                        path.IsClosed = true;
                        path.Freeze();

                        hatchGeometry = new PathGeometry();
                        hatchGeometry.Figures.Add(path);
                    }
                    else
                    {
                        rectGeometry = new RectangleGeometry(hatchRect);
                        rectGeometry.Freeze();

                        hatchGeometry = Geometry.Combine(hatchGeometry, rectGeometry, GeometryCombineMode.Union, null);
                    }
                }
            }

            // Then, create a region which equals to "SelectionFrame - element1 bounds - element2 bounds - ..."
            GeometryGroup      backgroundGeometry = new GeometryGroup( );
            GeometryCollection geometryCollection = new GeometryCollection();

            // Add the entile rectanlge to the group.
            rectGeometry = new RectangleGeometry(new Rect(0, 0, RenderSize.Width, RenderSize.Height));
            rectGeometry.Freeze();
            geometryCollection.Add(rectGeometry);

            // Add the union of the element rectangles. Then the group will do oddeven operation.
            Geometry outlineGeometry = null;

            if (hatchGeometry != null)
            {
                hatchGeometry.Freeze();

                outlineGeometry = hatchGeometry.GetOutlinedPathGeometry();
                outlineGeometry.Freeze();
                if (count == 1 && ((InkCanvasInnerCanvas)AdornedElement).InkCanvas.GetSelectedStrokes().Count == 0)
                {
                    geometryCollection.Add(outlineGeometry);
                }
            }

            geometryCollection.Freeze();
            backgroundGeometry.Children = geometryCollection;
            backgroundGeometry.Freeze();

            // Then, draw the region which may contain holes so that the elements cannot be covered.
            // After that, the underneath elements can receive the messages.
#if DEBUG_OUTPUT
            // Draw the debug feedback
            drawingContext.DrawGeometry(new SolidColorBrush(Color.FromArgb(128, 255, 255, 0)), null, backgroundGeometry);
#else
            drawingContext.DrawGeometry(Brushes.Transparent, null, backgroundGeometry);
#endif

            // At last, draw the hatch borders
            if (outlineGeometry != null)
            {
                drawingContext.DrawGeometry(null, _hatchPen, outlineGeometry);
            }
        }
Пример #23
0
 void AddVerticalTimeMarks(GeometryGroup geometryGroup)
 {
     AddVerticalDayMarks(geometryGroup);
     AddVerticalHourMarks(geometryGroup);
 }
Пример #24
0
        /// <summary>
        /// Adds the markers.
        /// </summary>
        /// <param name="pts">The points.</param>
        private void AddMarkers(IList <Point> pts)
        {
            var grp = new GeometryGroup {
                FillRule = FillRule.Nonzero
            };
            double sz  = this.MarkerSize;
            double sz2 = sz / 2;

            switch (this.LineMarker)
            {
            case MarkerType.Square:
                foreach (var pt in pts)
                {
                    grp.Children.Add(new RectangleGeometry(new Rect(pt.X - sz2, pt.Y - sz2, sz, sz)));
                }

                break;

            case MarkerType.Circle:
                foreach (var pt in pts)
                {
                    grp.Children.Add(new EllipseGeometry(new Rect(pt.X - sz2, pt.Y - sz2, sz, sz)));
                }

                break;

            case MarkerType.Diamond:
                foreach (var pt in pts)
                {
                    grp.Children.Add(new RectangleGeometry(new Rect(pt.X - sz2, pt.Y - sz2, sz, sz))
                    {
                        Transform = new RotateTransform(45, pt.X, pt.Y)
                    });
                }

                break;
            }

            grp.Freeze();
            var path = new Path {
                Data = grp, Fill = this.Background
            };

            this.Canvas.Children.Add(path);

            for (int i = 0; i < pts.Count; i++)
            {
                var pt = pts[i];
                var tb = new TextBox
                {
                    Text        = string.Format(this.TextFormat, this.points[i].Y),
                    FontSize    = this.FontSize,
                    Foreground  = Brushes.Black,
                    BorderBrush = this.AnnotationBrush
                };

                Canvas.SetLeft(tb, pt.X + this.OffsetX);
                Canvas.SetTop(tb, pt.Y + this.OffsetY);
                this.Canvas.Children.Add(tb);
                this.Canvas.Children.Add(
                    new Line
                {
                    Stroke          = this.AnnotationBrush,
                    StrokeThickness = 1,
                    X1 = pt.X,
                    Y1 = pt.Y,
                    X2 = pt.X + this.OffsetX,
                    Y2 = pt.Y + this.OffsetY
                });
            }
        }
Пример #25
0
 public TreeViaPath()
 {
     tree          = new GeometryGroup();
     tree.FillRule = FillRule.Nonzero;
 }
        /// <summary>
        /// 绘制雷达图
        /// </summary>
        private void DrawRadar(Double o, Double w, Double e, Double t, Double r)
        {
            //--------------------------------------------------------------绘制正五边形--------------------------------------------------------
            Point      p1 = new Point(120, 0);                                                                                 //第一个点
            Point      p2 = new Point(120 - (Math.Cos(18 * Math.PI / 180) * 120), 120 - (Math.Sin(18 * Math.PI / 180) * 120)); //逆时针。第二个点坐标
            Point      p3 = new Point(120 - (Math.Cos(54 * Math.PI / 180) * 120), 120 + (Math.Sin(54 * Math.PI / 180) * 120)); //逆时针第三个点坐标
            Point      p4 = new Point(120 + (Math.Cos(54 * Math.PI / 180) * 120), 120 + (Math.Sin(54 * Math.PI / 180) * 120)); //逆时针第四个点坐标
            Point      p5 = new Point(120 + (Math.Cos(18 * Math.PI / 180) * 120), 120 - (Math.Sin(18 * Math.PI / 180) * 120)); //逆时针第五个点坐标
            PathFigure pf = new PathFigure();

            pf.StartPoint = p1;
            pf.IsClosed   = true;
            LineSegment ls1 = new LineSegment();
            LineSegment ls2 = new LineSegment();
            LineSegment ls3 = new LineSegment();
            LineSegment ls4 = new LineSegment();

            ls1.Point = p2;
            ls2.Point = p3;
            ls3.Point = p4;
            ls4.Point = p5;
            pf.Segments.Add(ls1);
            pf.Segments.Add(ls2);
            pf.Segments.Add(ls3);
            pf.Segments.Add(ls4);
            PathGeometry pg = new PathGeometry();

            pg.Figures.Add(pf);
            this.RadarPF.Data = pg;
            //--------------------------------------------------------------绘制正五边形结束------------------------------------------------------
            //--------------------------------------------------------------绘制正五边形中的连线---------------------------------------------------
            LineGeometry l1 = new LineGeometry(new Point(120, 120), p1);
            LineGeometry l2 = new LineGeometry(new Point(120, 120), p2);
            LineGeometry l3 = new LineGeometry(new Point(120, 120), p3);
            LineGeometry l4 = new LineGeometry(new Point(120, 120), p4);
            LineGeometry l5 = new LineGeometry(new Point(120, 120), p5);
            //--------------------------------------------------------------绘制正五边形中的连线结束---------------------------------------------------
            GeometryGroup gg = new GeometryGroup();

            gg.Children.Add(l1);
            gg.Children.Add(l2);
            gg.Children.Add(l3);
            gg.Children.Add(l4);
            gg.Children.Add(l5);
            this.Midpoint.Data = gg;
            //--------------------------------------------------------------绘制雷达图中的数据显示区域---------------------------------------------------
            Point      rp1 = new Point(120, 120 - MathLong(o));
            Point      rp2 = new Point(120 - (Math.Cos(18 * Math.PI / 180) * MathLong(w)), 120 - (Math.Sin(18 * Math.PI / 180) * MathLong(w)));
            Point      rp3 = new Point(120 - (Math.Cos(54 * Math.PI / 180) * MathLong(e)), 120 + (Math.Sin(54 * Math.PI / 180) * MathLong(e)));
            Point      rp4 = new Point(120 + (Math.Cos(54 * Math.PI / 180) * MathLong(t)), 120 + (Math.Sin(54 * Math.PI / 180) * MathLong(t)));
            Point      rp5 = new Point(120 + (Math.Cos(18 * Math.PI / 180) * MathLong(r)), 120 - (Math.Sin(18 * Math.PI / 180) * MathLong(r)));
            PathFigure rpf = new PathFigure();

            rpf.StartPoint = rp1;
            rpf.IsClosed   = true;
            LineSegment rl1 = new LineSegment(rp2, true);
            LineSegment rl2 = new LineSegment(rp3, true);
            LineSegment rl3 = new LineSegment(rp4, true);
            LineSegment rl4 = new LineSegment(rp5, true);

            rpf.Segments.Add(rl1);
            rpf.Segments.Add(rl2);
            rpf.Segments.Add(rl3);
            rpf.Segments.Add(rl4);
            PathGeometry rpg = new PathGeometry();

            rpg.Figures.Add(rpf);
            this.Radar.Data = rpg;
        }
Пример #27
0
        private void currentPlotting(ParameterName parameterName, Canvas canGraph, params AlarmEventArgs[] aea)
        {
            double LowerLimitForCurrentOnYAxis;
            double UpperLimitForCurrentOnYAxis;
            double LowerLimitForTimeOnXAxis;
            double UpperLimitForTimeOnXAxis;

            GeometryGroup axisX = new GeometryGroup();
            GeometryGroup axisY = new GeometryGroup();

            Rect rectGraphWithAxesBounds = new Rect(0, 0, 0, 0); //структура для хранения координат внутри части окна, где будет рисоваться график с осями координат,
            //обозначаними осей, числоввыми значаниями и полями для масштабирования осей
            Rect rectGraphBounds = new Rect(0, 0, 0, 0);         //структура для хранения координат внутри части окна, где будет рисоваться только линия графика

            this.Dispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(delegate(Object state)
            {
                if (canGraph.ActualWidth == 0)
                {
                    return(null);
                }
                canGraph.Children.Clear();
                rectGraphWithAxesBounds.Width  = canGraph.ActualWidth;
                rectGraphWithAxesBounds.Height = canGraph.ActualHeight;


                double xmin = marginX;
                double xmax = rectGraphWithAxesBounds.Width - marginX;
                double ymin = marginY;
                double ymax = rectGraphWithAxesBounds.Height - marginY;
                //вызов может быть 1) с часов, 2) при начальном запуске программы, 3) при смене файла для отображения параметров
                switch (aea.Length)
                {
                case 1:
                    LowerLimitForTimeOnXAxis = aea[0].TicksToAlarm;                                                                                             //изиенение нижней границы интервала времени
                    UpperLimitForTimeOnXAxis = Int32.Parse(this.endTimeOnXAxis.Ticks.Text);
                    break;

                case 2:
                    LowerLimitForTimeOnXAxis = Int32.Parse(this.begTimeOnXAxis.Ticks.Text);
                    UpperLimitForTimeOnXAxis = aea[1].TicksToAlarm;                                                                                             //изиенение верхней границы интервала времени
                    break;

                default:
                    LowerLimitForTimeOnXAxis = Int32.Parse(this.begTimeOnXAxis.Ticks.Text);                     //интервал времени берётся непосредственно с часов,
                    UpperLimitForTimeOnXAxis = Int32.Parse(this.endTimeOnXAxis.Ticks.Text);                     // вызов пришёл при выполнении условий 2) или 3)
                    break;
                }
                LowerLimitForCurrentOnYAxis = 0;
                UpperLimitForCurrentOnYAxis = Int32.Parse(maxValueForCurrentOnYAxis.Text);

                PrepareTransformations(
                    LowerLimitForTimeOnXAxis, UpperLimitForTimeOnXAxis, LowerLimitForCurrentOnYAxis, UpperLimitForCurrentOnYAxis,
                    xmin, xmax, ymin, ymax
                    );
                rectGraphBounds.X      = xmin;
                rectGraphBounds.Y      = ymin;
                rectGraphBounds.Width  = xmax;
                rectGraphBounds.Height = ymax;
                double step            = Math.Round((xmax - xmin) / (24 * 6));

                double dotsPerSecond = (xmax - xmin) / SecondsInADay;
                int intSecondsPerDot = (int)(SecondsInADay / (xmax - xmin));
                double dotsPerVolt   = 100 * step / 100;

                axisX.Children.Add(new LineGeometry(WtoD(new Point(LowerLimitForTimeOnXAxis, LowerLimitForCurrentOnYAxis)), WtoD(new Point(UpperLimitForTimeOnXAxis, LowerLimitForCurrentOnYAxis))));
                //Расставляем часовые деления на оси X
                //Расставляем получасовые деления на оси X
                //Расставляем 10-минутные деления на оси X
                //Для крупного масштаба расставляем 5 - минутные
                //и минутные деления.
                //Point onX_axis;
                //Point overX_axis;
                Action <string, Point, HorizontalAlignment, VerticalAlignment> PutLabel = DrawText;;
                PutTimeTicks(3600, dashHourTickLength, PutLabel);
                PutLabel = null;
                PutTimeTicks(1800, dashHalfHourTickLength, PutLabel);
                PutTimeTicks(600, dashMinuteTickLength, PutLabel);
                if ((UpperLimitForTimeOnXAxis - LowerLimitForTimeOnXAxis) / 3600 <= 2)
                {
                    PutTimeTicks(300, dashMinuteTickLength, PutLabel);
                    PutTimeTicks(60, dashMinuteTickLength, PutLabel);
                }

                Path axisX_path            = new Path();
                axisX_path.StrokeThickness = axisLineThickness;
                axisX_path.Stroke          = Brushes.Black;
                axisX_path.Data            = axisX;


                // Make the Y ayis.
                axisY = new GeometryGroup();

                axisY.Children.Add(new LineGeometry(new Point(xmin, ymin), new Point(xmin, ymax)));

                for (double y = ymax; y >= ymin; y -= step)
                {
                    if (Math.Round((ymax - y) / step) % 10 == 0)
                    {
                        axisY.Children.Add(new LineGeometry
                                           (
                                               new Point(xmin, y),
                                               new Point(xmin + 2 * dashTickLength, y))
                                           );
                    }
                    else
                    if (Math.Round((ymax - y) / step) % 5 == 0)
                    {
                        axisY.Children.Add(new LineGeometry
                                           (
                                               new Point(xmin, y),
                                               new Point(xmin + dashTickLength, y))
                                           );
                    }
                    else
                    {
                        axisY.Children.Add(new LineGeometry
                                           (
                                               new Point(xmin, y),
                                               new Point(xmin + dashTickLength / 2, y))
                                           );
                    }
                }

                Path axisY_path            = new Path();
                axisY_path.StrokeThickness = 1;
                axisY_path.Stroke          = Brushes.Black;
                axisY_path.Data            = axisY;

                canGraph.Children.Add(axisX_path);
                canGraph.Children.Add(axisY_path);

                WriteLine("Adding VisualHostForPlot_1 to the Children collection of the Canvas");
                canGraph.Children.Add(new VisualHostForPlot_1(unpackedParameters, parameterName, rectGraphBounds));

                return(null);
            }), null);
            void PutTimeTicks(int IntervalInSeconds, double TickLength, Action <string, Point, HorizontalAlignment, VerticalAlignment> PutLabel)
            {
                Point onX_axis;
                Point overX_axis;

                for (double Dash = TickMeasure(LowerLimitForTimeOnXAxis); Dash < UpperLimitForTimeOnXAxis; Dash += IntervalInSeconds)
                {
                    onX_axis     = WtoD(new Point(Dash, LowerLimitForCurrentOnYAxis));
                    overX_axis   = onX_axis;
                    overX_axis.Y = overX_axis.Y - TickLength;
                    axisX.Children.Add(new LineGeometry
                                       (
                                           onX_axis,
                                           overX_axis
                                       )
                                       );
                    Point underX_axis = onX_axis;
                    underX_axis.Y = overX_axis.Y;
                    if (PutLabel != null)
                    {
                        PutLabel(((int)Dash / IntervalInSeconds).ToString(), underX_axis, HorizontalAlignment.Center, VerticalAlignment.Top);
                    }
                }
                double TickMeasure(double timeInSeconds)
                {
                    return((((int)timeInSeconds / IntervalInSeconds) + ((timeInSeconds % IntervalInSeconds == 0) ? 0:1)) * IntervalInSeconds);
                }
            }

            void DrawText(string text, Point location,
                          HorizontalAlignment halign, VerticalAlignment valign)
            {
                // Make the label.
                Label label = new Label();

                label.Content = text;
                canGraph.Children.Add(label);

                // Position the label.
                label.Measure(new Size(double.MaxValue, double.MaxValue));

                double x = location.X;

                if (halign == HorizontalAlignment.Center)
                {
                    x -= label.DesiredSize.Width / 2;
                }
                else if (halign == HorizontalAlignment.Right)
                {
                    x -= label.DesiredSize.Width;
                }
                Canvas.SetLeft(label, x);

                double y = location.Y;

                if (valign == VerticalAlignment.Center)
                {
                    y += label.DesiredSize.Height / 2;
                }
                else if (valign == VerticalAlignment.Bottom)
                {
                    y += label.DesiredSize.Height;
                }
                else
                {
                    y += label.DesiredSize.Height / 6;
                }
                Canvas.SetTop(label, y);
            }
        }
Пример #28
0
 public GeometryElementRenderer(GeometryGroup geometry, double scale)
 {
     _geometry = geometry;
     _scale    = scale;
 }
Пример #29
0
        protected override void OnRefresh()
        {
            RotarySwitch rotarySwitch = Visual as RotarySwitch;

            if (rotarySwitch != null)
            {
                _imageRect.Width  = rotarySwitch.Width;
                _imageRect.Height = rotarySwitch.Height;
                _image            = ConfigManager.ImageManager.LoadImage(rotarySwitch.KnobImage);
                _imageBrush       = new ImageBrush(_image);
                _center           = new Point(rotarySwitch.Width / 2d, rotarySwitch.Height / 2d);

                _lines     = new GeometryDrawing();
                _lines.Pen = new Pen(new SolidColorBrush(rotarySwitch.LineColor), rotarySwitch.LineThickness);

                _labels.Clear();

                Vector v1            = new Point(_center.X, 0) - _center;
                double lineLength    = v1.Length * rotarySwitch.LineLength;
                double labelDistance = v1.Length * rotarySwitch.LabelDistance;
                v1.Normalize();
                GeometryGroup lineGroup  = new GeometryGroup();
                Brush         labelBrush = new SolidColorBrush(rotarySwitch.LabelColor);
                foreach (RotarySwitchPosition position in rotarySwitch.Positions)
                {
                    Matrix m1 = new Matrix();
                    m1.Rotate(position.Rotation);

                    if (rotarySwitch.DrawLines)
                    {
                        Vector v2 = v1 * m1;

                        Point startPoint = _center;
                        Point endPoint   = startPoint + (v2 * lineLength);

                        lineGroup.Children.Add(new LineGeometry(startPoint, endPoint));
                    }

                    if (rotarySwitch.DrawLabels)
                    {
                        FormattedText labelText = rotarySwitch.LabelFormat.GetFormattedText(labelBrush, position.Name);
                        labelText.TextAlignment = TextAlignment.Center;
                        labelText.MaxTextWidth  = rotarySwitch.Width;
                        labelText.MaxTextHeight = rotarySwitch.Height;

                        if (rotarySwitch.MaxLabelHeight > 0d && rotarySwitch.MaxLabelHeight < rotarySwitch.Height)
                        {
                            labelText.MaxTextHeight = rotarySwitch.MaxLabelHeight;
                        }
                        if (rotarySwitch.MaxLabelWidth > 0d && rotarySwitch.MaxLabelWidth < rotarySwitch.Width)
                        {
                            labelText.MaxTextWidth = rotarySwitch.MaxLabelWidth;
                        }

                        Point location = _center + (v1 * m1 * labelDistance);
                        if (position.Rotation <= 10d || position.Rotation >= 350d)
                        {
                            location.X -= labelText.MaxTextWidth / 2d;
                            location.Y -= labelText.Height;
                        }
                        else if (position.Rotation < 170d)
                        {
                            location.X -= (labelText.MaxTextWidth - labelText.Width) / 2d;
                            location.Y -= labelText.Height / 2d;
                        }
                        else if (position.Rotation <= 190d)
                        {
                            location.X -= labelText.MaxTextWidth / 2d;
                        }
                        else
                        {
                            location.X -= (labelText.MaxTextWidth + labelText.Width) / 2d;
                            location.Y -= labelText.Height / 2d;
                        }

                        _labels.Add(new SwitchPositionLabel(labelText, location));
                    }
                }
                _lines.Geometry = lineGroup;
                _lines.Freeze();
            }
            else
            {
                _image      = null;
                _imageBrush = null;
                _lines      = null;
                _labels.Clear();
            }
        }
Пример #30
0
        private static void ApplyTransformations(IEnumerable <Transformation> transformations, GeometryGroup geometry)
        {
            foreach (var transformation in transformations)
            {
                switch (transformation.Kind)
                {
                case TransformationKind.Translate:
                    var tt = (Transformation.Translate)transformation;
                    geometry.Transform.Value.Translate(tt.X, tt.Y);
                    break;

                case TransformationKind.Rotate:
                    var rt = (Transformation.Rotate)transformation;
                    geometry.Transform.Value.Rotate(rt.RotationDegrees);
                    break;

                default:
                    throw new NotSupportedException(
                              $"Unknown {nameof(Transformation)} kind: {transformation.Kind}");
                }
            }
        }
Пример #31
0
        /// <summary>
        /// Draws the collection of ellipses, where all have the same stroke and fill.
        /// This performs better than calling DrawEllipse multiple times.
        /// </summary>
        /// <param name="rectangles">The rectangles.</param>
        /// <param name="fill">The fill color.</param>
        /// <param name="stroke">The stroke color.</param>
        /// <param name="thickness">The stroke thickness.</param>
        public void DrawEllipses(IList<OxyRect> rectangles, OxyColor fill, OxyColor stroke, double thickness)
        {
            var path = new Path();
            this.SetStroke(path, stroke, thickness);
            if (fill.IsVisible())
            {
                path.Fill = this.GetCachedBrush(fill);
            }

            var gg = new GeometryGroup { FillRule = FillRule.Nonzero };
            foreach (var rect in rectangles)
            {
                gg.Children.Add(
                    new EllipseGeometry
                    {
                        Center = new Point(rect.Left + (rect.Width / 2), rect.Top + (rect.Height / 2)),
                        RadiusX = rect.Width / 2,
                        RadiusY = rect.Height / 2
                    });
            }

            path.Data = gg;
            this.Add(path);
        }
Пример #32
0
        void BuildGeometry()
        {
            m_geometry = new GeometryGroup();
            var r = GetBodyRadius();

            if (IsFunction())
            {
                var cosRadian = Math.Cos(20.0 / 180.0 * Math.PI);
                var sinRadian = Math.Sin(20.0 / 180.0 * Math.PI);

                var r0 = r;
                if (m_customData["nCaller"].m_int > 0)
                {
                    var cr = m_customData["callerR"].m_double;

                    var figure = new PathFigure();
                    figure.StartPoint = new Point(-r0, 0);
                    figure.Segments.Add(new LineSegment(new Point(-r0 - cr * cosRadian, cr * sinRadian), true));
                    //figure.Segments.Add(new LineSegment(new Point(-r0 - cr * cosRadian, -sinRadian), true));
                    figure.Segments.Add(new ArcSegment(new Point(-r0 - cr * cosRadian, cr * -sinRadian), new Size(cr, cr), 0.0, false, SweepDirection.Clockwise, true));
                    figure.IsClosed = true;
                    figure.IsFilled = true;
                    var pathGeo = new PathGeometry();
                    pathGeo.Figures.Add(figure);
                    m_geometry.Children.Add(pathGeo);
                }
                if (m_customData["nCallee"].m_int > 0)
                {
                    var cr = m_customData["calleeR"].m_double;

                    var figure = new PathFigure();
                    figure.StartPoint = new Point(r0, 0);
                    figure.Segments.Add(new LineSegment(new Point(r0 + cr * cosRadian, cr * sinRadian), true));
                    figure.Segments.Add(new ArcSegment(new Point(r0 + cr * cosRadian, cr * -sinRadian), new Size(cr, cr), 0.0, false, SweepDirection.Counterclockwise, true));
                    figure.IsClosed = true;
                    figure.IsFilled = true;
                    var pathGeo = new PathGeometry();
                    pathGeo.Figures.Add(figure);
                    m_geometry.Children.Add(pathGeo);
                }

                m_highLightGeometry = new EllipseGeometry(new Point(0.0, 0.0), r, r);
                if (m_lines == 0 || (m_customData.ContainsKey("hasDef") && m_customData["hasDef"].m_int == 0))
                {
                    var innerCircle = new EllipseGeometry(new Point(0.0, 0.0), 1.5, 1.5);
                    m_highLightGeometry = Geometry.Combine(m_highLightGeometry, innerCircle, GeometryCombineMode.Exclude, null);
                }
                m_geometry.Children.Add(m_highLightGeometry);
            }
            else if (m_kind == DoxygenDB.EntKind.VARIABLE)
            {
                var figure = new PathFigure();
                figure.StartPoint = new Point(-r, 0.0);
                figure.Segments.Add(new LineSegment(new Point(r * 0.5, r * 0.85), true));
                figure.Segments.Add(new LineSegment(new Point(r * 0.5, -r * 0.85), true));
                figure.IsClosed = true;
                figure.IsFilled = true;
                var pathGeo = new PathGeometry();
                pathGeo.Figures.Add(figure);
                m_geometry.Children.Add(pathGeo);
                m_highLightGeometry = pathGeo;
            }
            else if (IsClassOrStruct())
            {
                var figure = new PathFigure();
                figure.StartPoint = new Point(r, 0.0);
                figure.Segments.Add(new LineSegment(new Point(0.0, r), true));
                figure.Segments.Add(new LineSegment(new Point(-r, 0.0), true));
                figure.Segments.Add(new LineSegment(new Point(0.0, -r), true));
                figure.IsClosed = true;
                figure.IsFilled = true;
                var pathGeo = new PathGeometry();
                pathGeo.Figures.Add(figure);
                m_geometry.Children.Add(pathGeo);
                m_highLightGeometry = pathGeo;
            }
            else if (m_kind == DoxygenDB.EntKind.TYPEDEF)
            {
                var figure = new PathFigure();
                figure.StartPoint = new Point(r, 0.0);
                figure.Segments.Add(new LineSegment(new Point(0.5 * r, 0.5 * r), true));
                figure.Segments.Add(new LineSegment(new Point(-0.5 * r, 0.5 * r), true));
                figure.Segments.Add(new LineSegment(new Point(-r, 0.0), true));
                figure.Segments.Add(new LineSegment(new Point(0.0, -r), true));
                figure.IsClosed = true;
                figure.IsFilled = true;
                var pathGeo = new PathGeometry();
                pathGeo.Figures.Add(figure);
                m_geometry.Children.Add(pathGeo);
                m_highLightGeometry = pathGeo;
            }
            else if (m_kind == DoxygenDB.EntKind.FILE)
            {
                var rect = new RectangleGeometry(new Rect(new Point(-r, -r), new Point(r, r)));
                m_geometry.Children.Add(rect);
                m_highLightGeometry = rect;
            }
            else if (m_kind == DoxygenDB.EntKind.GROUP)
            {
                var pathGeo = new PathGeometry();
                var figure  = new PathFigure();
                figure.StartPoint = new Point(r, r);
                figure.Segments.Add(new LineSegment(new Point(-r, r), true));
                figure.Segments.Add(new LineSegment(new Point(-r, -r * 0.2), true));
                figure.Segments.Add(new LineSegment(new Point(-r * 0.7, -r * 0.2), true));
                figure.Segments.Add(new LineSegment(new Point(-r * 0.7, -r * 0.5), true));
                figure.Segments.Add(new LineSegment(new Point(-r, -r * 0.5), true));
                figure.Segments.Add(new LineSegment(new Point(-r, -r), true));

                figure.Segments.Add(new LineSegment(new Point(r, -r), true));
                figure.Segments.Add(new LineSegment(new Point(r, -r * 0.5), true));
                figure.Segments.Add(new LineSegment(new Point(r * 0.7, -r * 0.5), true));
                figure.Segments.Add(new LineSegment(new Point(r * 0.7, -r * 0.2), true));
                figure.Segments.Add(new LineSegment(new Point(r, -r * 0.2), true));

                figure.Segments.Add(new LineSegment(new Point(r, r), true));
                figure.IsClosed = true;
                figure.IsFilled = true;
                pathGeo.Figures.Add(figure);
                m_geometry.Children.Add(pathGeo);
                m_highLightGeometry = pathGeo;
            }
            else if (m_kind == DoxygenDB.EntKind.DIR)
            {
                var figure = new PathFigure();
                figure.StartPoint = new Point(r, r);
                figure.Segments.Add(new LineSegment(new Point(-r, r), true));
                figure.Segments.Add(new LineSegment(new Point(-r, -r * 0.6), true));
                figure.Segments.Add(new LineSegment(new Point(-r * 0.8, -r), true));
                figure.Segments.Add(new LineSegment(new Point(r * 0.2, -r), true));
                figure.Segments.Add(new LineSegment(new Point(r * 0.4, -r * 0.6), true));
                figure.Segments.Add(new LineSegment(new Point(r, -r * 0.6), true));
                figure.IsClosed = true;
                figure.IsFilled = true;
                var pathGeo = new PathGeometry();
                pathGeo.Figures.Add(figure);
                m_geometry.Children.Add(pathGeo);
                m_highLightGeometry = pathGeo;
            }
            else if (m_kind == DoxygenDB.EntKind.PAGE)
            {
                var figure = new PathFigure();
                figure.StartPoint = new Point(r, 0.0);
                figure.Segments.Add(new LineSegment(new Point(0, 0.5 * r), true));
                figure.Segments.Add(new LineSegment(new Point(-r, 0.5 * r), true));
                figure.Segments.Add(new LineSegment(new Point(-r, -0.5 * r), true));
                figure.Segments.Add(new LineSegment(new Point(0, -0.5 * r), true));
                figure.IsClosed = true;
                figure.IsFilled = true;
                var pathGeo = new PathGeometry();
                pathGeo.Figures.Add(figure);
                m_geometry.Children.Add(pathGeo);
                m_highLightGeometry = pathGeo;
            }
            else
            {
                float w = 3.0f;

                var pathGeo = new PathGeometry();
                var figure  = new PathFigure();
                figure.StartPoint = new Point(w, w);
                figure.Segments.Add(new LineSegment(new Point(-w, -w), true));
                figure.IsClosed = false;
                figure.IsFilled = false;
                pathGeo.Figures.Add(figure);

                figure            = new PathFigure();
                figure.StartPoint = new Point(w, -w);
                figure.Segments.Add(new LineSegment(new Point(-w, w), true));
                figure.IsClosed = false;
                figure.IsFilled = false;
                pathGeo.Figures.Add(figure);

                var outlinePen = new Pen();
                outlinePen.Thickness = 2.0;
                outlinePen.LineJoin  = PenLineJoin.Round;
                pathGeo = pathGeo.GetWidenedPathGeometry(outlinePen).GetOutlinedPathGeometry();
                m_geometry.Children.Add(pathGeo);
                m_highLightGeometry = pathGeo;
            }
        }
Пример #33
0
 internal static object GetAsFrozen(this GeometryGroup self)
 {
     return(self);
 }
Пример #34
0
        CanvasGeometry BuildGeometry(ICanvasResourceCreator resourceCreator, Geometry geometry)
        {
            CanvasGeometry canvasGeometry = null;

            // Determine what type of geometry we're dealing with.
            if (geometry is RectangleGeometry)
            {
                Rect          xamRect = (geometry as RectangleGeometry).Rect;
                winFound.Rect winRect = new winFound.Rect(xamRect.X, xamRect.Y, xamRect.Width, xamRect.Height);
                canvasGeometry = CanvasGeometry.CreateRectangle(resourceCreator, winRect);
            }

            else if (geometry is EllipseGeometry)
            {
                EllipseGeometry ellipseGeometry = geometry as EllipseGeometry;
                Vector2         center          = ConvertPoint(ellipseGeometry.Center);
                canvasGeometry = CanvasGeometry.CreateEllipse(resourceCreator, center, (float)ellipseGeometry.RadiusX, (float)ellipseGeometry.RadiusY);
            }

            else if (geometry is GeometryGroup)
            {
                GeometryGroup         geometryGroup = geometry as GeometryGroup;
                List <CanvasGeometry> geometries    = new List <CanvasGeometry>();

                foreach (Geometry geometryChild in geometryGroup.Children)
                {
                    geometries.Add(BuildGeometry(resourceCreator, geometryChild));
                }

                canvasGeometry = CanvasGeometry.CreateGroup(resourceCreator, geometries.ToArray(), (CanvasFilledRegionDetermination)(int)geometryGroup.FillRule);
            }

            else
            {
                using (CanvasPathBuilder pathBuilder = new CanvasPathBuilder(resourceCreator))
                {
                    // Determine what type of geometry we're dealing with.
                    if (geometry is LineGeometry)
                    {
                        LineGeometry lineGeometry = geometry as LineGeometry;
                        pathBuilder.BeginFigure(ConvertPoint(lineGeometry.StartPoint), CanvasFigureFill.Default);
                        pathBuilder.AddLine(ConvertPoint(lineGeometry.EndPoint));
                        pathBuilder.EndFigure(CanvasFigureLoop.Open);
                    }

                    else if (geometry is PathGeometry)
                    {
                        PathGeometry pathGeometry = geometry as PathGeometry;
                        pathBuilder.SetFilledRegionDetermination((CanvasFilledRegionDetermination)(int)pathGeometry.FillRule);

                        foreach (PathFigure pathFigure in pathGeometry.Figures)
                        {
                            // TODO: Check this logic!
                            pathBuilder.BeginFigure(ConvertPoint(pathFigure.StartPoint),
                                                    pathFigure.IsFilled ? CanvasFigureFill.Default : CanvasFigureFill.DoesNotAffectFills);

                            foreach (PathSegment pathSegment in pathFigure.Segments)
                            {
                                // LineSegment
                                if (pathSegment is LineSegment)
                                {
                                    pathBuilder.AddLine(ConvertPoint((pathSegment as LineSegment).Point));
                                }

                                // PolylineSegment
                                else if (pathSegment is PolyLineSegment)
                                {
                                    foreach (Point point in (pathSegment as PolyLineSegment).Points)
                                    {
                                        pathBuilder.AddLine(ConvertPoint(point));
                                    }
                                }

                                // BezierSegment
                                else if (pathSegment is BezierSegment)
                                {
                                    BezierSegment bezierSegment = pathSegment as BezierSegment;

                                    pathBuilder.AddCubicBezier(ConvertPoint(bezierSegment.Point1),
                                                               ConvertPoint(bezierSegment.Point2),
                                                               ConvertPoint(bezierSegment.Point3));
                                }

                                // PolyBezierSegment
                                else if (pathSegment is PolyBezierSegment)
                                {
                                    PointCollection points = (pathSegment as PolyBezierSegment).Points;

                                    for (int i = 0; i < points.Count; i += 3)
                                    {
                                        pathBuilder.AddCubicBezier(ConvertPoint(points[i + 0]),
                                                                   ConvertPoint(points[i + 1]),
                                                                   ConvertPoint(points[i + 2]));
                                    }
                                }

                                // QuadraticBezierSegment
                                else if (pathSegment is QuadraticBezierSegment)
                                {
                                    QuadraticBezierSegment quadSegment = pathSegment as QuadraticBezierSegment;

                                    pathBuilder.AddQuadraticBezier(ConvertPoint(quadSegment.Point1),
                                                                   ConvertPoint(quadSegment.Point2));
                                }

                                // PolyQuadraticBezierSegment
                                else if (pathSegment is PolyQuadraticBezierSegment)
                                {
                                    PointCollection points = (pathSegment as PolyQuadraticBezierSegment).Points;

                                    for (int i = 0; i < points.Count; i += 2)
                                    {
                                        pathBuilder.AddQuadraticBezier(ConvertPoint(points[i + 0]),
                                                                       ConvertPoint(points[i + 1]));
                                    }
                                }

                                // ArcSegment
                                else if (pathSegment is ArcSegment)
                                {
                                    ArcSegment arcSegment = pathSegment as ArcSegment;

                                    pathBuilder.AddArc(ConvertPoint(arcSegment.Point),
                                                       (float)arcSegment.Size.Width,
                                                       (float)arcSegment.Size.Height,
                                                       (float)arcSegment.RotationAngle,
                                                       (CanvasSweepDirection)(int)arcSegment.SweepDirection,
                                                       arcSegment.IsLargeArc ? CanvasArcSize.Large : CanvasArcSize.Small);
                                }
                            }

                            pathBuilder.EndFigure(pathFigure.IsClosed ? CanvasFigureLoop.Closed : CanvasFigureLoop.Open);
                        }
                    }

                    else
                    {
                        return(null);
                    }

                    canvasGeometry = CanvasGeometry.CreatePath(pathBuilder);
                }
            }

            // Set transform
            if (geometry.Transform != null)
            {
                canvasGeometry = canvasGeometry.Transform((Matrix3x2)geometry.Transform.GetNativeObject());
            }

            return(canvasGeometry);
        }
        public static void AddGeometryGroup(this D2D.GeometrySink sink, GeometryGroup geometryGroup, RectangleF rect)
        {
            sink.SetFillMode(geometryGroup.FillRule.ToSharpDX());

            foreach (var childGeometry in geometryGroup.Children)
            {
                sink.AddGeometry(childGeometry, rect);
            }
        }
Пример #36
0
    private void voltagePlotting(ParameterName parameterName, Canvas canGraph)
    {
        TickParamsAll unpackedParameters = app.unpackedParameters; //данные для построения графика
        Rect          rectBounds         = new Rect(0, 0, 0, 0);   //структура для хранения координат внутри части окна, где будет рисоваться график

        this.Dispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(delegate(Object state)
        {
            if (canGraph.ActualWidth == 0)
            {
                return(null);
            }
            canGraph.Children.Clear();
            rectBounds.Width  = canGraph.ActualWidth;
            rectBounds.Height = canGraph.ActualHeight;


            const double dashTickLength = 10;
            const double marginX        = 10;
            const double marginY        = 10;
            double xmin = marginX;
            double xmax = rectBounds.Width - marginX;
            double ymin = marginY;
            double ymax = rectBounds.Height - marginY;
            double step = Math.Round((xmax - xmin) / (24 * 6));

            string unitOfMeasure;
            double dotsPerSecond = (xmax - xmin) / SecondsInADay;
            int intSecondsPerDot = (int)(SecondsInADay / (xmax - xmin));
            double dotsPerVolt   = 100 * step / 100;


            // Make the X axis.
            GeometryGroup axis_X_geom = new GeometryGroup();

            axis_X_geom.Children.Add(new LineGeometry(new Point(xmin, ymax), new Point(xmax, ymax)));

            for (double x = xmin + step; x <= xmax; x += step)
            {
                if ((x - xmin) / step % 6 == 0)
                {
                    axis_X_geom.Children.Add(new LineGeometry
                                             (
                                                 new Point(x, ymax - dashTickLength),
                                                 new Point(x, ymax))
                                             );
                }
                else
                {
                    axis_X_geom.Children.Add(new LineGeometry
                                             (
                                                 new Point(x, ymax - dashTickLength / 2),
                                                 new Point(x, ymax))
                                             );
                }
            }

            Path axis_X_path            = new Path();
            axis_X_path.StrokeThickness = 1;
            axis_X_path.Stroke          = Brushes.Black;
            axis_X_path.Data            = axis_X_geom;

            canGraph.Children.Add(axis_X_path);

            // Make the Y ayis.
            GeometryGroup axis_Y_geom = new GeometryGroup();

            axis_Y_geom.Children.Add(new LineGeometry(new Point(xmin, ymin), new Point(xmin, ymax)));

            for (double y = ymax; y >= ymin; y -= step)
            {
                if (Math.Round((ymax - y) / step) % 10 == 0)
                {
                    axis_Y_geom.Children.Add(new LineGeometry
                                             (
                                                 new Point(xmin, y),
                                                 new Point(xmin + 2 * dashTickLength, y))
                                             );
                }
                else
                if (Math.Round((ymax - y) / step) % 5 == 0)
                {
                    axis_Y_geom.Children.Add(new LineGeometry
                                             (
                                                 new Point(xmin, y),
                                                 new Point(xmin + dashTickLength, y))
                                             );
                }
                else
                {
                    axis_Y_geom.Children.Add(new LineGeometry
                                             (
                                                 new Point(xmin, y),
                                                 new Point(xmin + dashTickLength / 2, y))
                                             );
                }
            }

            Path axis_Y_path            = new Path();
            axis_Y_path.StrokeThickness = 1;
            axis_Y_path.Stroke          = Brushes.Black;
            axis_Y_path.Data            = axis_Y_geom;

            canGraph.Children.Add(axis_Y_path);
                        #if POLYLINE
            //Значения для графика тока подтягиваются сюда.
            //Для рисования через Polyline
            points = new PointCollection();

            int numSec = 0;
            short intAssembled;
            double realValueOfFunction;
            double peakAtInterval   = 0;              //максимальное значение функции на интервале
            double bottomAtInterval = Int32.MaxValue; //минимальное значение функции на интервале
            Point begPoint          = new Point(xmin, ymax);
            Point endPoint          = new Point(xmin, ymax);
            bool theFirstDotInPair  = true;
            for (
                int iParam = (int)parameterName / (Constants.ParameterData[(int)(parameterName)].parameterType == ParameterType.аналоговый ? 1:10) + (int)Globals.startOfParameterOutput.TotalSeconds * Constants.ParamsBlockLengthInBytes;
                iParam < unpackedParameters.inflatedParameters.Length;
                iParam = iParam + Constants.ParamsBlockLengthInBytes)
            {
                if (Constants.ParameterData[(int)(parameterName)].parameterType == ParameterType.аналоговый)
                {
                    intAssembled        = BitConverter.ToInt16(unpackedParameters.inflatedParameters, iParam);
                    realValueOfFunction = (double)intAssembled / 10;
                    switch (Constants.ParameterData[(int)(parameterName)].parameterUnit)
                    {
                    case ParameterUnit._:
                        unitOfMeasure = "";
                        break;

                    case ParameterUnit.м3_ч:
                        unitOfMeasure = "м3/ч";
                        break;

                    case ParameterUnit.мм_рт_ст:
                        if (intAssembled < 0)
                        {
                            unitOfMeasure = "мм рт.ст";
                            intAssembled &= 0x777;
                        }
                        else
                        {
                            unitOfMeasure = "мк";
                        }
                        break;
                    }
                }
                else
                {
                    throw new Exception();
                }
                //*
                if (peakAtInterval < realValueOfFunction)
                {
                    peakAtInterval = realValueOfFunction;
                }
                if (bottomAtInterval > realValueOfFunction)
                {
                    bottomAtInterval = realValueOfFunction;
                }
                if (numSec % intSecondsPerDot == 0)
                {
                    //отмечать в графике МАКСИМАЛЬЕОЕ значение на интервале
                    //но надо отмечать и МИНИМАЛЬНОЕ !
                    if (!theFirstDotInPair)
                    {
                        points.Add(new Point(xmin + (numSec - 1) * dotsPerSecond, ymax - dotsPerVolt * bottomAtInterval));
                        points.Add(new Point(xmin + (numSec) * dotsPerSecond, ymax - dotsPerVolt * peakAtInterval));
                        //points.Add( new Point(xmin +(numSec)*dotsPerSecond,ymax - dotsPerVolt*bottomAtInterval));
                        peakAtInterval    = 0;
                        bottomAtInterval  = Int32.MaxValue;
                        theFirstDotInPair = true;
                    }
                    else
                    {
                        theFirstDotInPair = false;
                    }
                }

/*				else
 *                              if(numSec%intSecondsPerDot==(int)(intSecondsPerDot/2))
 *                              {
 *                                      //отмечать в графике МАКСИМАЛЬЕОЕ значение на интервале
 *                                      //но надо отмечать и МИНИМАЛЬНОЕ !
 *                                      points.Add( new Point(xmin +(numSec)*dotsPerSecond,ymax - dotsPerVolt*bottomAtInterval));
 *                                      bottomAtInterval = Int32.MaxValue;
 *                              } */
                //*

                /*endPoint = new Point(xmin +(numSec)*dotsPerSecond,ymax - dotsPerVolt*bottomAtInterval);
                 * plotGeometry.Children.Add(new LineGeometry(begPoint,endPoint));
                 * WriteLine("Dot number {0}",numSec );
                 * endPoint = begPoint;
                 * points.Add( new Point(xmin +(numSec++)*dotsPerSecond,ymax - dotsPerVolt*(double)intAssembled/10));*/
                numSec++;
            }
            Polyline polyline1        = new Polyline();
            polyline1.StrokeThickness = 1;
            polyline1.Stroke          = Brushes.Red;
            polyline1.Points          = points;
            canGraph.Children.Add(polyline1);
                        #else
            canGraph.Children.Add(new VisualHostForPlot(unpackedParameters, parameterName, rectBounds));
                        #endif
            return(null);
        }), null);
    }
Пример #37
0
        /// <summary>
        /// Draws a collection of rectangles, where all have the same stroke and fill.
        /// This performs better than calling DrawRectangle multiple times.
        /// </summary>
        /// <param name="rectangles">The rectangles.</param>
        /// <param name="fill">The fill color.</param>
        /// <param name="stroke">The stroke color.</param>
        /// <param name="thickness">The stroke thickness.</param>
        public void DrawRectangles(IList<OxyRect> rectangles, OxyColor fill, OxyColor stroke, double thickness)
        {
            var rectangleGeometries = rectangles.Select(x => new RectangleGeometry(this.d2dFactory, x.ToRectangleF())).ToArray();
            var group = new GeometryGroup(this.d2dFactory, FillMode.Winding, rectangleGeometries);

            this.renderUnits.Add(new GeometryRenderUnit(group, this.GetBrush(stroke), this.GetBrush(fill), (float)thickness, null));

            foreach (var rectangle in rectangleGeometries)
            {
                rectangle.Dispose();
            }
        }
Пример #38
0
 public override void Execute()
 {
     using (SceneEditTransaction editTransaction = this.SceneViewModel.CreateEditTransaction(this.undoDescription))
     {
         this.ConvertSelectedElementsToPathIfNecessary();
         editTransaction.Update();
         this.SceneViewModel.DefaultView.UpdateLayout();
         SceneElementSelectionSet      elementSelectionSet   = this.SceneViewModel.ElementSelectionSet;
         SceneElement                  primarySelection      = elementSelectionSet.PrimarySelection;
         System.Windows.Media.Geometry renderedGeometryAsWpf = this.SceneView.GetRenderedGeometryAsWpf(primarySelection);
         if (renderedGeometryAsWpf == null)
         {
             return;
         }
         this.Initialize(renderedGeometryAsWpf);
         SceneElementCollection elementCollection = new SceneElementCollection();
         foreach (SceneElement shapeElement in elementSelectionSet.Selection)
         {
             if (shapeElement != primarySelection)
             {
                 elementCollection.Add(shapeElement);
                 System.Windows.Media.Geometry secondaryGeometry = this.SceneView.GetRenderedGeometryAsWpf(shapeElement);
                 if (secondaryGeometry == null)
                 {
                     return;
                 }
                 Matrix transformToElement = shapeElement.GetComputedTransformToElement(primarySelection);
                 if (!transformToElement.IsIdentity)
                 {
                     MatrixTransform matrixTransform = new MatrixTransform(transformToElement);
                     matrixTransform.Freeze();
                     GeometryGroup geometryGroup = new GeometryGroup();
                     geometryGroup.Children.Add(secondaryGeometry);
                     geometryGroup.Transform = (Transform)matrixTransform;
                     secondaryGeometry       = (System.Windows.Media.Geometry)geometryGroup;
                 }
                 this.Combine(secondaryGeometry);
             }
         }
         PathGeometry result = this.GetResult();
         BooleanCommand.CleanUpPathGeometry(ref result);
         PathGeometry pathGeometry = PathConversionHelper.RemoveDegeneratePoints((System.Windows.Media.Geometry)result);
         elementSelectionSet.Clear();
         PathGeometryUtilities.CollapseSingleSegmentsToPolySegments(pathGeometry);
         PathElement pathElement = (PathElement)this.SceneViewModel.CreateSceneNode(PlatformTypes.Path);
         Dictionary <IPropertyId, SceneNode> properties = (Dictionary <IPropertyId, SceneNode>)null;
         using (this.SceneViewModel.DisableUpdateChildrenOnAddAndRemove())
         {
             this.SceneViewModel.AnimationEditor.DeleteAllAnimationsInSubtree(primarySelection);
             properties = SceneElementHelper.StoreProperties((SceneNode)primarySelection);
             ISceneNodeCollection <SceneNode> collectionContainer = primarySelection.GetCollectionContainer();
             int index = collectionContainer.IndexOf((SceneNode)primarySelection);
             collectionContainer[index] = (SceneNode)pathElement;
         }
         foreach (SceneElement element in elementCollection)
         {
             this.SceneViewModel.AnimationEditor.DeleteAllAnimationsInSubtree(element);
             element.Remove();
         }
         using (this.SceneViewModel.ForceBaseValue())
         {
             if (properties != null)
             {
                 SceneElementHelper.ApplyProperties((SceneNode)pathElement, properties);
             }
             pathElement.SetValueAsWpf(ShapeElement.StretchProperty, (object)Stretch.Fill);
             PathCommandHelper.ReplacePathGeometry(pathElement, pathGeometry, editTransaction);
         }
         elementSelectionSet.SetSelection((SceneElement)pathElement);
         editTransaction.Commit();
     }
 }