Example #1
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            renderingMap.FileTileServer = new AutoDisposableFileServer();

            plotter.BeginLongOperation();

            Task task = Task.Run(() =>
            {
                var dataSource = ReliefReader.ReadDataSource();

                Dispatcher.BeginInvoke((Action)(() =>
                {
                    plotter.EndLongOperation();
                }), DispatcherPriority.Send);

                tileServer.Dispatcher.BeginInvoke((Action)(() =>
                {
                    tileServer.ContentBounds = new DataRect(-180, -90, 360, 180);
                }), DispatcherPriority.Send);

                tileServer.ChildCreateHandler = () =>
                {
                    FastIsolineDisplay isoline = new FastIsolineDisplay {
                        WayBeforeTextMultiplier = 100, LabelStringFormat = "F0"
                    };
                    Viewport2D.SetContentBounds(isoline, new DataRect(-180, -90, 360, 180));
                    isoline.DataSource = dataSource;

                    return(isoline);
                };
            });
        }
Example #2
0
        protected override void OnRenderCore(DrawingContext dc, RenderState state) {
            // base.OnRenderCore
            if (DataSource == null) return;
            if (Marker == null) return;
            var left = Viewport.Visible.Location.X;
            var right = Viewport.Visible.Location.X + Viewport.Visible.Size.Width;
            var top = Viewport.Visible.Location.Y;
            var bottom = Viewport.Visible.Location.Y + Viewport.Visible.Size.Height;
            var transform = Plotter2D.Viewport.Transform;
            
            DataRect bounds = DataRect.Empty;
            using (IPointEnumerator enumerator = DataSource.GetEnumerator(GetContext())) {
                Point point = new Point();
                while (enumerator.MoveNext()) {
                    enumerator.GetCurrent(ref point);                                       
                    if (point.X >= left && point.X <= right && point.Y >= top && point.Y <= bottom)
                    {
                        enumerator.ApplyMappings(Marker);
 
                        Point screenPoint = point.DataToScreen(transform);
 
                        bounds = DataRect.Union(bounds, point);
                        Marker.Render(dc, screenPoint);
                    }
                }
            }
            Viewport2D.SetContentBounds(this, bounds);
        }
        public Window1()
        {
            InitializeComponent();
            if (File.Exists("etopo2.dos.bin"))
            {
#if new
                var heightMap = new ETopoHeightMapGraph();
                Viewport2D.SetContentBounds(heightMap, new DataRect(-180, -85, 360, 170));

                OneThreadRenderingMap map = new OneThreadRenderingMap(heightMap)
                {
                    DrawDebugBounds = true
                };
                plotter.Children.Add(map);
#else
                plotter.Children.Add(new ETopoHeightMapGraph());
#endif
            }
            else
            {
                MessageBox.Show("etopo2.dos.bin file is not found.\n" +
                                "Please download it from http://www.ngdc.noaa.gov/mgg/global/relief/ETOPO2/ETOPO2-2001/\n" +
                                "and place in the same folder with this sample.",
                                "Data file is not found!");
            }
        }
		protected override void RebuildUI()
		{
			//if (Plotter == null)
			//    return;
			if (DataSource == null)
				return;

			tokenSource.Cancel();
			tokenSource = new CancellationTokenSource();

			var dataSource = this.GetValueSync<IDataSource2D<Vector>>(DataSourceProperty);
			contentBounds = dataSource.Grid.GetGridBounds();
			Viewport2D.SetContentBounds(this, contentBounds);
			ViewportPanel.SetViewportBounds(image, contentBounds);

			int width = dataSource.Width;
			int height = dataSource.Height;
			// do not create new bitmap if size of previous one equals size of new data source
			if (bmp == null || width != bmp.PixelWidth || height != bmp.PixelHeight)
			{
				bmp = new WriteableBitmap(width, height, 96, 96, PixelFormats.Bgra32, palette: null);
				image.Source = bmp;
			}

			ParallelOptions parallelOptions = new ParallelOptions { CancellationToken = tokenSource.Token };
			Task.Factory.StartNew(() => CreateConvolutionBmp(width, height, parallelOptions), tokenSource.Token);
		}
Example #5
0
        public override void EndBatchAdd()
        {
            base.EndBatchAdd();

            if (plotter == null)
            {
                return;
            }

            overallViewportBounds = DataRect.Empty;
            if (Children.Count > 0 && invalidatePositionCalls == 0)
            {
                var transform = plotter.Viewport.Transform.WithScreenOffset(-translateTransform.X, -translateTransform.Y);
                foreach (FrameworkElement child in Children)
                {
                    if (child != null)
                    {
                        if (child.Visibility != Visibility.Visible)
                        {
                            continue;
                        }

                        Rect bounds = GetElementScreenBounds(transform, child);
                        UniteWithBounds(transform, bounds);
                    }
                }
            }

            Viewport2D.SetContentBounds(this, overallViewportBounds);
            ContentBoundsChanged.Raise(this);
        }
Example #6
0
        protected virtual bool UpdateVertexBufferFromGeometrySource(IEnumerable <TDxPoint> newPoints)
        {
            bool vertexBufferSizeChanged = false;

            // Vertices will be resized to the next power of 2, saves on resizing too much
            _pointList = newPoints.ToArray();
            var pointCount = _pointList.Length;

            // There's an issue with nVidia cards that the rendering pipeline locks up if we try to reuse
            // Vertex buffers allocated on the default pool. AMD cards seem to be ok. Work around is to use
            // the system pool, which is slow, or lock the back buffer via the target image.

            if (DxHost.LockImage())
            {
                if (_vertexBuffer == null || pointCount > _vertexBufferAllocated || pointCount < (_vertexBufferAllocated >> 1))
                {
                    _vertexBuffer?.Dispose();
                    var newSize = MathHelper.CeilingPow2(pointCount);
                    _vertexBuffer           = new VertexBuffer(Device, Utilities.SizeOf <TDxPoint>() * newSize, Usage.WriteOnly, VertexFormat.None, Pool.Default);
                    _vertexBufferAllocated  = newSize;
                    vertexBufferSizeChanged = true;
                }
                // Lock the entire buffer by specifying 0 for the offset and size, throw away it's current contents
                var vertexStream = _vertexBuffer.Lock(0, 0, LockFlags.Discard);
                vertexStream.WriteRange(_pointList);
                _vertexBuffer.Unlock();
                DxHost.UnlockImage();
            }
            _vertexCount = pointCount;

            // Calculate the bounds of the list on a background thread
            var localPointList = _pointList;
            var dataTransform  = Plotter.Viewport.Transform.DataTransform;

            if (localPointList.Any())
            {
                Action resizeAction = () =>
                {
                    var minX = localPointList[0].X;
                    var maxX = localPointList[0].X;
                    var minY = localPointList[0].Y;
                    var maxY = localPointList[0].Y;
                    foreach (var point in localPointList)
                    {
                        minX = Math.Min(minX, point.X);
                        maxX = Math.Max(maxX, point.X);
                        minY = Math.Min(minY, point.Y);
                        maxY = Math.Max(maxY, point.Y);
                    }
                    var bounds = BoundsHelper.GetViewportBounds(new[] { new System.Windows.Point(minX, minY), new System.Windows.Point(maxX, maxY) }, dataTransform);
                    _syncContext.Send(s =>
                    {
                        Viewport2D.SetContentBounds(this, bounds);
                    }, null);
                };
                // Spawn action on throttled update thread
                _throttledAction.InvokeAction(resizeAction);
            }
            return(vertexBufferSizeChanged);
        }
        private void UpdateContentBounds(bool recalculate)
        {
            if (recalculate)
            {
                var transform = plotter.Viewport.Transform.WithScreenOffset(-translateTransform.X, -translateTransform.Y);
                overallViewportBounds = DataRect.Empty;
                foreach (FrameworkElement child in Children)
                {
                    if (child != null)
                    {
                        if (child.Visibility != Visibility.Visible)
                        {
                            continue;
                        }

                        Rect bounds = GetElementScreenBounds(transform, child);
                        UniteWithBounds(transform, bounds);
                    }
                }
            }

            if (useContentBounds)
            {
                Viewport2D.SetContentBounds(this, overallViewportBounds);
                ContentBoundsChanged.Raise(this);
            }
        }
        private void UpdateField()
        {
            var dataSource = DataSource;
            var bounds     = dataSource.GetGridBounds();

            Viewport2D.SetContentBounds(this, bounds);
            ViewportPanel.SetViewportBounds(this, bounds);

            int length = (n + 2) * (n + 2);

            uOld       = new double[length];
            vOld       = new double[length];
            densityOld = new double[length];

            for (int i = 0; i < length; i++)
            {
                int ix = i % n;
                int iy = i / n;

                Vector vector = wrapper.GetVector(ix / (double)n, iy / (double)n);
                if (vector.X.IsNaN() || vector.Y.IsNaN())
                {
                    vector = new Vector();
                }
                vOld[i] = 50000 * vector.X;
                uOld[i] = 50000 * vector.Y;
            }
        }
        private BitmapSource CreateWhiteNoizeBmp(int width, int height)
        {
            var    dataSource = DataSource;
            Random rnd        = new Random();

            int[] pixels = new int[width * height];
            for (int i = 0; i < width * height; i++)
            {
                HsbColor color = new HsbColor(0, 0, Math.Round(5 * rnd.NextDouble()) / 4);
                int      argb  = color.ToArgb();
                pixels[i] = argb;
            }
            //var whiteNoizeBmp = WriteableBitmap.Create(width, height, 96, 96, PixelFormats.Pbgra32, null, pixels, width * 4);

            var contentBounds = dataSource.Grid.GetGridBounds();

            Viewport2D.SetContentBounds(this, contentBounds);

            int[] effectivePixels = CreateConvolutionArray(width, height, pixels);

            var filter = new NormalizeFilter();

            filter.Filter(effectivePixels, width, height);

            var result = WriteableBitmap.Create(width, height, 96, 96, PixelFormats.Pbgra32, null, effectivePixels, width * 4);

            //ScreenshotHelper.SaveBitmapToFile(result, "1.png");

            return(result);
        }
        protected override Size ArrangeOverride(Size finalSize)
        {
            if (plotter == null)
            {
                return(finalSize);
            }

            var transform = plotter.Viewport.Transform;

            overallViewportBounds = DataRect.Empty;
            foreach (UIElement child in InternalChildren)
            {
                if (child != null)
                {
                    if (child.Visibility != Visibility.Visible)
                    {
                        continue;
                    }

                    Rect bounds = GetElementScreenBounds(transform, child);
                    child.Arrange(bounds);

                    UniteWithBounds(transform, bounds);
                }
            }

            if (!InBatchAdd)
            {
                Viewport2D.SetContentBounds(this, overallViewportBounds);
                ContentBoundsChanged.Raise(this);
            }

            return(finalSize);
        }
        public void TestViewportContentBounds()
        {
            ChartPlotter        plotter = new ChartPlotter();
            TempIPlotterElement element = new TempIPlotterElement();

            plotter.Children.Add(element);
            plotter.PerformLoad();
            plotter.Viewport.ClipToBoundsEnlargeFactor = 1.0;

            Assert.AreEqual(new DataRect(0, 0, 1, 1), plotter.Visible);

            Viewport2D.SetContentBounds(element, new DataRect(0, 0, 2, 2));

            Assert.AreEqual(new DataRect(0, 0, 2, 2), plotter.Visible);

            plotter.Children.Remove(element);

            Assert.AreEqual(new DataRect(0, 0, 1, 1), plotter.Visible);

            plotter.Children.Add(element);
            Assert.AreEqual(new DataRect(0, 0, 2, 2), plotter.Visible);

            Viewport2D.SetIsContentBoundsHost(element, false);
            Assert.AreEqual(new DataRect(0, 0, 1, 1), plotter.Visible);
        }
Example #12
0
        protected override void UpdateCore()
        {
            if (DataSource == null)
            {
                return;
            }
            if (Plotter == null)
            {
                return;
            }
            if (!IsEnabled)
            {
                return;
            }

            Rect output    = Viewport.Output;
            var  transform = GetTransform();

            if (FilteredPoints == null || !(transform.DataTransform is IdentityTransform))
            {
                IEnumerable <Point> points = GetPoints();
                if (!points.Any())
                {
                    return;
                }

                var bounds = BoundsHelper.GetViewportBounds(points, transform.DataTransform);
                if (bounds.Width >= 0 && bounds.Height >= 0)
                {
                    bounds = new DataRect(bounds.XMin - 360.0, bounds.YMin, bounds.Width + 720.0, bounds.Height);
                }
                Viewport2D.SetContentBounds(this, bounds);

                // getting new value of transform as it could change after calculating and setting content bounds.
                transform = GetTransform();
                List <Point> transformedPoints = transform.DataToScreenAsList(points);

                var screenOffset = transform.DataToScreen(new Point(360, 0));

                // Analysis and filtering of unnecessary points
                FilteredPoints = new FakePointList(transformedPoints, double.NegativeInfinity, double.PositiveInfinity);
                if (ProvideVisiblePoints)
                {
                    List <Point> viewportPointsList = null;
                    viewportPointsList = new List <Point>(transformedPoints.Count);
                    if (transform.DataTransform is IdentityTransform)
                    {
                        viewportPointsList.AddRange(points);
                    }
                    else
                    {
                        var viewportPoints = points.DataToViewport(transform.DataTransform);
                        viewportPointsList.AddRange(viewportPoints);
                    }
                    SetVisiblePoints(this, new ReadOnlyCollection <Point>(viewportPointsList));
                }
                Offset = new Vector();
            }
        }
Example #13
0
        private void UpdateUI()
        {
            panel.Children.Clear();

            if (plotter == null)
            {
                return;
            }

            var grid = Grid;

            if (grid == null)
            {
                return;
            }

            var bounds = grid.Grid.GetGridBounds();

            Viewport2D.SetContentBounds(this, bounds);

            int width  = grid.Width;
            int height = grid.Height;

            // todo not the best way to determine size of markers in case of warped grids.
            double deltaX = (grid.Grid[width - 1, 0].X - grid.Grid[0, 0].X) / width;
            double deltaY = (grid.Grid[0, height - 1].Y - grid.Grid[0, 0].Y) / height;

            for (int ix = 0; ix < width; ix++)
            {
                int localX = ix;
                Dispatcher.BeginInvoke(() =>
                {
                    for (int iy = 0; iy < height; iy++)
                    {
                        Ellipse ellipse = new Ellipse {
                            MaxWidth = 10, MaxHeight = 10
                        };
                        var position = grid.Grid[localX, iy];
                        ViewportPanel.SetX(ellipse, position.X);
                        ViewportPanel.SetY(ellipse, position.Y);
                        ViewportPanel.SetViewportWidth(ellipse, deltaX / 2);
                        ViewportPanel.SetViewportHeight(ellipse, deltaY / 2);

                        if (localX % 10 == 0 && iy % 10 == 0)
                        {
                            ellipse.Fill = Brushes.Black;
                        }
                        else
                        {
                            ellipse.Fill = Brushes.Gray.MakeTransparent(0.7);
                        }

                        panel.Children.Add(ellipse);
                    }
                }, DispatcherPriority.Background);
            }
        }
Example #14
0
 private void UpdateBounds(IPointDataSource dataSource)
 {
     if (this.Plotter != null)
     {
         var      transform = ((Plotter2D)Plotter).Viewport.Transform;
         DataRect bounds    = BoundsHelper.GetViewportBounds(dataSource.GetPoints(), transform.DataTransform);
         Viewport2D.SetContentBounds(this, bounds);
     }
 }
        private void UpdateContentBounds()
        {
            IRenderingTileServer renderingServer = SourceTileServer as IRenderingTileServer;

            if (renderingServer != null)
            {
                Viewport2D.SetContentBounds(this, renderingServer.ContentBounds);
            }
        }
Example #16
0
        protected override void OnRender(DrawingContext drawingContext)
        {
            if (Plotter2D == null)
            {
                return;
            }
            if (Collection == null)
            {
                return;
            }
            if (DataSource == null)
            {
                return;
            }
            if (Collection.Lines.Count == 0)
            {
                IsolineBuilder.DataSource   = DataSource;
                IsolineBuilder.MissingValue = MissingValue;
                Collection = IsolineBuilder.BuildIsoline();
            }

            IsolineCollection = Collection;

            var dc = drawingContext;
            var strokeThickness = StrokeThickness;
            var collection      = Collection;

            var bounds = DataRect.Empty;

            // determining content bounds
            foreach (LevelLine line in collection)
            {
                foreach (Point point in line.AllPoints)
                {
                    bounds.Union(point);
                }
            }

            Viewport2D.SetContentBounds(this, bounds);
            ViewportPanel.SetViewportBounds(this, bounds);

            if (bounds.IsEmpty)
            {
                return;
            }

            // custom transform with output set to renderSize of this control
            var transform = Plotter2D.Transform.WithRects(bounds, new Rect(RenderSize));

            // actual drawing of isolines
            RenderIsolineCollection(dc, strokeThickness, collection, transform);

            RenderLabels(dc, collection);
        }
        private void RecalculateViewportBounds()
        {
            DataRect bounds = DataRect.Empty;

            foreach (UIElement item in itemsPanel.Children)
            {
                DataRect elementBounds = ViewportPanel.GetActualViewportBounds(item);
                bounds.Union(elementBounds);
            }

            Viewport2D.SetContentBounds(this, bounds);
        }
        public Map()
        {
            Viewport2D.SetIsContentBoundsHost(this, true);
            Viewport2D.SetContentBounds(this, new DataRect(new Point(-180, -90), new Point(180, 90)));

            server.ImageLoaded         += OnTileLoaded;
            server.SourceServerChanged += OnSourceServerChanged;

#if DEBUG
            drawDebugBounds = false;
#endif
        }
        protected override void CreateUIRepresentation()
        {
            if (Plotter2D == null)
            {
                return;
            }

            content.Children.Clear();
            linePaths.Clear();

            if (Collection != null)
            {
                DataRect bounds = DataRect.Empty;

                foreach (var line in Collection.Lines)
                {
                    foreach (var point in line.AllPoints)
                    {
                        bounds.Union(point);
                    }

                    Path path = new Path
                    {
                        Stroke          = new SolidColorBrush(Palette.GetColor(line.Value01)),
                        StrokeThickness = StrokeThickness,
                        Data            = CreateGeometry(line),
                        Tag             = line
                    };
                    content.Children.Add(path);
                    linePaths.Add(path);
                }

                Viewport2D.SetContentBounds(this, bounds);

                if (DrawLabels)
                {
                    var    transform     = Plotter2D.Viewport.Transform;
                    double wayBeforeText = new Rect(new Size(2000, 2000)).ScreenToData(transform).Width;
                    Annotater.WayBeforeText = wayBeforeText;
                    var textLabels = Annotater.Annotate(Collection, Plotter2D.Viewport.Visible);

                    foreach (var textLabel in textLabels)
                    {
                        var text = CreateTextLabel(textLabel);
                        content.Children.Add(text);
                        textBlocks.Add(text);
                    }
                }
            }
        }
Example #20
0
        protected override void OnRender(DrawingContext dc)
        {
            if (Plotter2D == null)
            {
                return;
            }

            // Viewport is the range of the data normalized to 1x1 square coordinates
            var corner1 = new Point(0, 0).ViewportToData(Plotter2D.Transform);
            var corner2 = new Point(1, 1).ViewportToData(Plotter2D.Transform);

            var bounds = new DataRect(corner1, corner2);

            Viewport2D.SetContentBounds(this, bounds);
            ViewportPanel.SetViewportBounds(this, bounds);

            bool exportMode = false;

            if (Plotter2D is ChartPlotter p)
            {
                exportMode = p.ExportMode;
            }

            foreach (var line in GetLines())
            {
                Point leftPoint  = new Point(line.Start, line.GroupAxisCoord).DataToScreen(Plotter2D.Transform);
                Point rightPoint = new Point(line.End, line.GroupAxisCoord).DataToScreen(Plotter2D.Transform);
                if (leftPoint.X > rightPoint.X)
                {
                    var temp = leftPoint;
                    leftPoint  = rightPoint;
                    rightPoint = temp;
                }

                double minThickness     = line.IsSelected ? 10.0 : 5.0;
                var    leftRightPadding = Math.Max(minThickness * 0.5 - (rightPoint.X - leftPoint.X) * minThickness, exportMode ? 10 : 0);
                leftPoint  = new Point(leftPoint.X - leftRightPadding, Math.Round(leftPoint.Y));
                rightPoint = new Point(rightPoint.X + leftRightPadding, Math.Round(rightPoint.Y));

                dc.DrawLine(line.IsSelected ? _rangePenSelected : _rangePen, leftPoint, rightPoint);

                if (exportMode)
                {
                    var text = new FormattedText(line.Text, System.Globalization.CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Verdana"), 12, Brushes.Black);

                    dc.DrawText(text, leftPoint + 0.5 * (rightPoint - leftPoint) - new Vector(0.5 * text.Width, 0.5 * text.Height));
                }
            }
        }
Example #21
0
        public Coastline()
        {
            string path = "DynamicDataDisplay.Maps.Coastline.txt";

            Assembly assembly = Assembly.GetAssembly(typeof(Coastline));

            using (StreamReader reader = new StreamReader(assembly.GetManifestResourceStream(path)))
            {
                LoadFromStreamReader(reader);
            }

            Init();

            Viewport2D.SetContentBounds(this, new DataRect(-180, -90, 360, 180));
        }
        private void viewportItemsPanel_ContentBoundsChanged(object sender, EventArgs e)
        {
            var contentBounds = Viewport2D.GetContentBounds(currentItemsPanel);

            var plottedItems = CurrentItemsPanel.Children.OfType <UIElement>()
                               .Where(x => x.Visibility == Visibility.Visible)
                               .Where(item => !double.IsNaN(ViewportPanel.GetX(item)) || !double.IsNaN(ViewportPanel.GetY(item)));

            if (plottedItems.Any())
            {
                Viewport2D.SetContentBounds(this, contentBounds);
            }
            else
            {
                Viewport2D.SetContentBounds(this, DataRect.Empty);
            }
        }
Example #23
0
        private void OnDataSourceReplaced(IDataSource2D <Vector> prevDataSource, IDataSource2D <Vector> currDataSource)
        {
            var dataSource    = this.GetValueSync <IDataSource2D <Vector> >(DataSourceProperty);
            var contentBounds = dataSource.Grid.GetGridBounds();

            if (Parent != null)
            {
                Viewport2D.SetContentBounds(Parent, contentBounds);
            }
            ViewportPanel.SetViewportBounds(this, contentBounds);

            int width  = currDataSource.Width;
            int height = currDataSource.Height;

            bmp    = new WriteableBitmap(width, height, 96, 96, PixelFormats.Pbgra32, null);
            Source = bmp;

            Task task = new Task(() => CreateConvolutionBmp(width, height));

            task.Start();
        }
        protected override void RebuildUI()
        {
            if (Plotter == null)
            {
                return;
            }
            if (DataSource == null)
            {
                return;
            }

            width        = DataSource.Width;
            height       = DataSource.Height;
            fieldWrapper = new UniformField2DWrapper(DataSource.Data);

            bounds           = DataSource.Grid.GetGridBounds();
            particleVelocity = (width + height) * 0.0001;
            Viewport2D.SetContentBounds(this, bounds);

            UpdateParticles(width, height);
        }
        protected override void InvalidatePosition(FrameworkElement child)
        {
            invalidatePositionCalls++;

            if (viewport == null)
            {
                return;
            }
            if (child.Visibility != Visibility.Visible)
            {
                return;
            }

            var transform = viewport.Transform;

            Size elementSize = GetElementSize(child, AvailableSize, transform);

            child.Measure(elementSize);

            Rect bounds = GetElementScreenBounds(transform, child);

            child.Arrange(bounds);

            var viewportBounds = Viewport2D.GetContentBounds(this);

            if (!viewportBounds.IsEmpty)
            {
                overallViewportBounds = viewportBounds;
            }

            UniteWithBounds(transform, bounds);

            if (!InBatchAdd)
            {
                Viewport2D.SetContentBounds(this, overallViewportBounds);
                ContentBoundsChanged.Raise(this);
            }
        }
Example #26
0
        private void viewportItemsPanel_ContentBoundsChanged(object sender, EventArgs e)
        {
            var contentBounds = Viewport2D.GetContentBounds(currentItemsPanel);

            Viewport2D.SetContentBounds(this, contentBounds);
        }
Example #27
0
        private void FillVertexBuffer()
        {
            if (DxHost == null)
            {
                return;
            }
            if (DataSource == null)
            {
                return;
            }
            if (Palette == null)
            {
                return;
            }
            if (Device == null)
            {
                return;
            }

            var dataSource = DataSource;
            var palette    = Palette;
            var minMax     = dataSource.GetMinMax();

            var contentBounds = dataSource.GetGridBounds();

            Viewport2D.SetContentBounds(this, contentBounds);

            var transform = Plotter.Transform;

            vertexCount = DataSource.Width * DataSource.Height;

            verticesArray = new VertexPosition4Color[vertexCount];
            for (int i = 0; i < verticesArray.Length; i++)
            {
                int    ix    = i % DataSource.Width;
                int    iy    = i / DataSource.Width;
                Point  point = dataSource.Grid[ix, iy];
                double data  = dataSource.Data[ix, iy];

                double interpolatedData = (data - minMax.Min) / minMax.GetLength();
                var    color            = palette.GetColor(interpolatedData);

                var pointInScreen = point.DataToScreen(transform);
                var position      = new Vector4((float)pointInScreen.X, (float)pointInScreen.Y, 0.5f, 1);
                verticesArray[i] = new VertexPosition4Color
                {
                    Position = position,
                    Color    = color.ToArgb()
                };
            }

            vertexBuffer = new VertexBuffer(Device, vertexCount * VertexPosition4Color.SizeInBytes, Usage.WriteOnly, VertexFormat.Position | VertexFormat.Diffuse, Pool.Default);
            using (var stream = vertexBuffer.Lock(0, vertexCount * VertexPosition4Color.SizeInBytes, LockFlags.None))
            {
                stream.WriteRange <VertexPosition4Color>(verticesArray);
            }
            vertexBuffer.Unlock();

            indicesCount = (dataSource.Width - 1) * (dataSource.Height - 1) * 2 * 3;

            indicesArray = new int[indicesCount];
            int index = 0;
            int width = dataSource.Width;

            for (int iy = 0; iy < dataSource.Height - 1; iy++)
            {
                for (int ix = 0; ix < dataSource.Width - 1; ix++)
                {
                    indicesArray[index + 0] = ix + 0 + iy * width;
                    indicesArray[index + 1] = ix + 1 + iy * width;
                    indicesArray[index + 2] = ix + (iy + 1) * width;

                    indicesArray[index + 3] = ix + 1 + iy * width;
                    indicesArray[index + 4] = ix + (iy + 1) * width;
                    indicesArray[index + 5] = ix + 1 + (iy + 1) * width;

                    index += 6;
                }
            }

            indexBuffer = new IndexBuffer(Device, indicesCount * sizeof(int), Usage.WriteOnly, Pool.Default, false);
            using (var stream = indexBuffer.Lock(0, indicesCount * sizeof(int), LockFlags.None))
            {
                stream.WriteRange <int>(indicesArray);
            }
            indexBuffer.Unlock();
        }
Example #28
0
        private void UpdateContentBounds(DependencyObject source)
        {
            var contentBounds = Viewport2D.GetContentBounds(source);

            Viewport2D.SetContentBounds(this, contentBounds);
        }
Example #29
0
        private void CreateUIRepresentation()
        {
            if (Plotter == null)
            {
                return;
            }

            if (DataSource == null)
            {
                return;
            }

            drawnPaths.Clear();

            DataSourceEnvironment environment = CreateEnvironment();
            var points = DataSource.GetPoints(environment);

            var indexedPoints = IndexWrapper.Generate(points);

            // do nothing if there is nothing to draw
            if (!points.Any())
            {
                return;
            }

            transformWhileCreateUI = Plotter.Viewport.Transform;

            int globalMinIndex;
            int globalMaxIndex;

            CreateAndAddPath(indexedPoints, out globalMinIndex, out globalMaxIndex, transformWhileCreateUI);

            indexRange = new Range <int>(globalMinIndex, globalMaxIndex);

            ViewportPanel.SetViewportBounds(canvas, Plotter.Viewport.Visible);

            // switching off content bounds calculation for children of ViewportHostPanel.
            panel.BeginBatchAdd();

            if (canvas.Parent == null)
            {
                panel.Children.Add(canvas);
            }

            if (panel.Plotter == null)
            {
                Plotter.Dispatcher.BeginInvoke(() =>
                {
                    if (panel.Plotter == null && Plotter != null)
                    {
                        Plotter.Children.Add(panel);
                    }
                });
            }

            DataRect bounds = DataRect.Empty;

            if (environment.ContentBounds != null)
            {
                bounds = environment.ContentBounds.Value;
            }
            else
            {
                // todo is this necessary?
                bounds = points.GetBounds();
            }

            Viewport2D.SetContentBounds(this, bounds);
        }
Example #30
0
        private void UpdateUI()
        {
            var dataSource = this.GetValueSync <DataSource>(DataSourceProperty);

            if (dataSource == null)
            {
                return;
            }

            var contentBounds = dataSource.Grid.GetGridBounds();

            if (Parent != null)
            {
                Viewport2D.SetContentBounds(Parent, contentBounds);
            }
            ViewportPanel.SetViewportBounds(this, contentBounds);


            var minMaxLength = dataSource.GetMinMaxLength();

            effect.MinLength = (float)minMaxLength.Min;
            effect.MaxLength = (float)minMaxLength.Max;

            effect.Palette = ImageHelper.CreatePaletteBrush(Palette, width: 256);

            var minMaxX = dataSource.GetMinMax(v => v.X);
            var minMaxY = dataSource.GetMinMax(v => v.Y);

            effect.MinX = (float)minMaxX.Min;
            effect.MinY = (float)minMaxY.Min;
            effect.MaxX = (float)minMaxX.Max;
            effect.MaxY = (float)minMaxY.Max;

            int width  = dataSource.Width;
            int height = dataSource.Height;

            effect.Width  = 10 * width;
            effect.Height = -10 * height;

            if (width != prevWidth || height != prevHeight)
            {
                noizeBrush = new ImageBrush(BitmapFrame.Create(width, height, 96, 96, PixelFormats.Bgra32, null,
                                                               ImageHelper.CreateWhiteNoizeImage(width, height), (width * PixelFormats.Bgra32.BitsPerPixel + 7) / 8));

                prevWidth  = width;
                prevHeight = height;
            }
            effect.Noize = noizeBrush;

            var field = dataSource.Data;

            uint[] pixels = new uint[width * height];

            var minX = minMaxX.Min;
            var minY = minMaxY.Min;
            var lenX = minMaxX.GetLength();
            var lenY = minMaxY.GetLength();

            ConcurrentBag <uint> bagX = new ConcurrentBag <uint>();
            ConcurrentBag <uint> bagY = new ConcurrentBag <uint>();

            Parallel.For(0, height, iy =>
            {
                for (int ix = 0; ix < width; ix++)
                {
                    // todo убрать checked
                    checked
                    {
                        int i      = iy * width + ix;
                        var vector = field[ix, height - 1 - iy];

                        double xRatio = (vector.X - minX) / lenX;
                        double yRatio = (vector.Y - minY) / lenY;

                        if (xRatio.IsNaN())
                        {
                            xRatio = 0.5;
                        }
                        if (yRatio.IsNaN())
                        {
                            yRatio = 0.5;
                        }

                        uint x = (byte)(xRatio * 0xFF);
                        uint y = (byte)(yRatio * 0xFF);

                        double xFrac = xRatio * 0xFF - x;
                        double yFrac = yRatio * 0xFF - y;

                        Debug.Assert(0 <= xFrac && xFrac <= 1);
                        Debug.Assert(0 <= yFrac && yFrac <= 1);

                        uint xFracByte = (uint)(xFrac * 0xFF);
                        uint yFracByte = (uint)(yFrac * 0xFF);

                        bagX.Add(x);
                        bagY.Add(y);

                        uint pixel = 0;
                        //pixel |= xFracByte << 24;
                        //pixel |= yFracByte << 16;
                        pixel |= (uint)255 << 24;
                        pixel |= y << 8;
                        pixel |= x;
                        //pixel |= ((uint)255) << 24; // alpha

                        pixels[i] = pixel;
                    }
                }
            });

            Dictionary <uint, int> xdict = new Dictionary <uint, int>();
            Dictionary <uint, int> ydict = new Dictionary <uint, int>();

            foreach (var item in bagX)
            {
                if (xdict.ContainsKey(item))
                {
                    xdict[item]++;
                }
                else
                {
                    xdict[item] = 1;
                }
            }

            foreach (var item in bagY)
            {
                if (ydict.ContainsKey(item))
                {
                    ydict[item]++;
                }
                else
                {
                    ydict[item] = 1;
                }
            }

            ImageBrush fieldBrush = new ImageBrush(BitmapFrame.Create(width, height, 96, 96, PixelFormats.Bgra32, null, pixels, (width * PixelFormats.Bgra32.BitsPerPixel + 7) / 8));

            effect.Field = fieldBrush;
        }