예제 #1
0
        public BitmapSource RenderImage()
        {
            try
            {
                if (sizeInPixels > 48)
                {
                    viewport.Children.Add(myGridLines);
                }

                viewport.Width  = sizeInPixels;
                viewport.Height = sizeInPixels;
                viewport.Measure(new Size(sizeInPixels, sizeInPixels));
                viewport.Arrange(new Rect(0, 0, sizeInPixels, sizeInPixels));

                RenderTargetBitmap bmp =
                    new RenderTargetBitmap
                        (sizeInPixels, sizeInPixels, 96, 96, PixelFormats.Default);
                bmp.Render(viewport);
                if (sizeInPixels > 48)
                {
                    viewport.Children.Remove(myGridLines);
                }
                bmp.Freeze(); // Make it available from other threads.

                return(bmp);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
        public void copyFaceImage(Viewport3D viewport3d)
        {
            if (renderEnabled)
            {
                renderEnabled = false;
            }
            else
            {
                return;
            }

            int width  = 300;
            int height = 300;

            viewport3d.Width = width;

            viewport3d.Height = height;

            viewport3d.Measure(new Size(width, height));

            viewport3d.Arrange(new System.Windows.Rect(0, 0, width, height));

            //            bmp = new RenderTargetBitmap((int)viewport3d.ActualWidth, (int)viewport3d.ActualHeight, 96, 96, PixelFormats.Pbgra32);
            //            bmp.Render(viewport3d);

            RenderTargetBitmap bmp = new RenderTargetBitmap((int)viewport3d.ActualWidth,
                                                            (int)viewport3d.ActualHeight, 96, 96, PixelFormats.Default);

            bmp.Render(viewport3d);
            //FaceImage.imageObj = bmp;
            //            viewport3d.Visibility = Visibility.Collapsed;
            //            FaceImage.Visibility = Visibility.Visible;

            faceGrid[currentMatrixRow, currentMatrixColumn].ImageObj.Source     = bmp;
            faceGrid[currentMatrixRow, currentMatrixColumn].ImageObj.Visibility = Visibility.Visible;

            if (currentMatrixRow < 3)
            {
                currentMatrixRow++;
            }
            else
            {
                currentMatrixRow = 0;
                if (currentMatrixColumn < 3)
                {
                    currentMatrixColumn++;
                }
                else
                {
                    currentMatrixColumn = 0;
                }
            }


            //this.saveFaceImageToFile(bmp);
            //taskFactory.StartNew(() => saveFaceImageToFile(bmp));
        }
예제 #3
0
        protected override Size MeasureOverride(Size availableSize)
        {
            if (availableSize.Width == double.PositiveInfinity || availableSize.Height == double.PositiveInfinity)
            {
                return(Size.Empty);
            }

            _viewport.Measure(availableSize);
            return(_viewport.DesiredSize);
        }
예제 #4
0
 public static void ResizeAndArrange(Viewport3D view, double width, double height)
 {
     view.Width  = width;
     view.Height = height;
     if (double.IsNaN(width) || double.IsNaN(height))
     {
         return;
     }
     view.Measure(new Size(width, height));
     view.Arrange(new Rect(0, 0, width, height));
 }
예제 #5
0
        protected override Size MeasureOverride(Size availableSize)
        {
            Size eltSize = new Size(ElementWidth, ElementHeight);

            foreach (UIElement child in Children)
            {
                child.Measure(eltSize);
            }

            _viewport.Measure(availableSize);

            return(availableSize);
        }
예제 #6
0
        protected override Size MeasureOverride(Size availableSize)
        {
            if (availableSize.Width == double.PositiveInfinity || availableSize.Height == double.PositiveInfinity)
            {
                return(Size.Empty);
            }

            _viewport.Measure(availableSize);

            foreach (UIElement child in Children)
            {
                child.Measure(new Size(ElementWidth, ElementHeight));
            }
            return(availableSize);
        }
예제 #7
0
        protected override Size MeasureOverride(Size constraint)
        {
            viewPort.Measure(constraint);

            if (frontElement != null)
            {
                frontElement.Measure(constraint);
            }

            if (backElement != null)
            {
                backElement.Measure(constraint);
            }

            return(base.MeasureOverride(constraint));
        }
예제 #8
0
        private void RenderButton_OnClick(object sender, RoutedEventArgs e)
        {
            UpdateCamera();

            var stopwatch = new Stopwatch();

            stopwatch.Start();


            BitmapWidth  = (int)ImageBorder.ActualWidth;
            BitmapHeight = (int)ImageBorder.ActualHeight;

            _viewport3D.Width  = BitmapWidth;
            _viewport3D.Height = BitmapHeight;

            _viewport3D.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
            _viewport3D.Arrange(new Rect(0, 0, _viewport3D.DesiredSize.Width, _viewport3D.DesiredSize.Height));

            _camera.Refresh();

            Ab3d.Utilities.LinesUpdater.Instance.Refresh();

            BitmapSource renderBitmap = _dxViewportView.RenderToBitmap(width: BitmapWidth,
                                                                       height: BitmapHeight,
                                                                       preferedMultisampling: 2, // when -1 is used, then the currently used multisampling is used
                                                                       dpiX: BitmapDpiX,         // 96 is the default value and can be changed if needed
                                                                       dpiY: BitmapDpiY);

            // Display render time (note that the first time the scene is rendered the time is bigger because of additional initializations)
            stopwatch.Stop();
            InfoTextBlock.Text = string.Format("Render time: {0:0.0}ms", stopwatch.Elapsed.TotalMilliseconds);

            if (_isFirstRender)
            {
                InfoTextBlock.Text += " (note: render time of the first image is longer then the time to render other images)";
                _isFirstRender      = false;
            }

            RenderedImage.Source = renderBitmap;

            //SaveBitmap(renderBitmap, @"c:\temp\DXEngineRender.png");
        }
예제 #9
0
        protected override Size MeasureOverride(Size constraint)
        {
            _viewPort.Measure(constraint);

            if (_frontElement != null)
            {
                _frontElement.Measure(constraint);
            }

            if (_backElement != null)
            {
                _backElement.Measure(constraint);
            }

            var size = base.MeasureOverride(constraint);

            //return size;

            return(new Size(size.Width, _frontElement.DesiredSize.Height));
        }
예제 #10
0
        protected override Bitmap GetThumbnailImage(uint width) // Implemented abstract function in the base class
        {
            MemoryStream memStream = new MemoryStream();



            Thread thread = new Thread(() =>
            {
                try
                {
                    string color              = (string)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Marlin3DprinterTool", "Color", "Blue");
                    var stlReader             = new StLReader();
                    stlReader.DefaultMaterial = new DiffuseMaterial(
                        new SolidColorBrush((Color)ColorConverter.ConvertFromString(color)));



                    //stlReader.DefaultMaterial = new DiffuseMaterial(new SolidColorBrush(Colors.Blue));
                    var model = stlReader.Read(SelectedItemStream);



                    //...create UI controls...

                    Viewport3D viewport = new Viewport3D();


                    // viewport.Measure(new System.Windows.Size(320, 240));
                    viewport.Measure(new Size(width, width));
                    // viewport.Arrange(new Rect(0, 0, 320, 240));
                    viewport.Arrange(new Rect(0, 0, width, width));

                    ModelVisual3D root = new ModelVisual3D();

                    viewport.Children.Add(root);


                    var camera               = new PerspectiveCamera();
                    camera.Position          = new Point3D(2, 16, 20);
                    camera.LookDirection     = new Vector3D(-2, -16, -20);
                    camera.UpDirection       = new Vector3D(0, 0, 1);
                    camera.FieldOfView       = 45;
                    camera.NearPlaneDistance = 0.1;
                    camera.FarPlaneDistance  = double.PositiveInfinity;
                    viewport.Camera          = camera;


                    root.Children.Add(new DefaultLights());

                    root.Content = model;



                    camera.ZoomExtents(viewport);

                    Brush background        = new SolidColorBrush(Colors.Transparent);
                    BitmapExporter exporter = new BitmapExporter
                    {
                        OversamplingMultiplier = 2,
                        Background             = background
                    };


                    exporter.Export(viewport, memStream);
                }
                catch (Exception treadException)
                {
                }
            });


            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();


            Bitmap thumbnailBitmap = (Bitmap)Image.FromStream(memStream);

            return(thumbnailBitmap);
        }
예제 #11
0
        public System.Drawing.Image Render(RendererOptions options)
        {
            // The main object model group.
            Model3DGroup group = new Model3DGroup();

            // The camera.
            PerspectiveCamera camera = new PerspectiveCamera();

            Viewport3D viewport = new Viewport3D();

            // Give the camera its initial position.
            camera.FieldOfView = 5.75;
            viewport.Camera    = camera;

            // The camera's current location.

            string textureFilePath = options.TextureFilePath;
            int    size            = (int)options.OutputImageSize;
            double cameraPhi       = ToRadians(options.LatitudeShift);
            double cameraTheta     = ToRadians(options.LongutudeShift);
            double cameraR         = 20;

            // Calculate the camera's position in Cartesian coordinates.
            double y   = cameraR * Math.Sin(cameraPhi);
            double hyp = cameraR * Math.Cos(cameraPhi);
            double x   = hyp * Math.Cos(cameraTheta);
            double z   = hyp * Math.Sin(cameraTheta);

            camera.Position = new Point3D(x, y, z);

            // Look toward the origin.
            camera.LookDirection = new Vector3D(-x, -y, -z);

            // Set the Up direction.
            camera.UpDirection = new Vector3D(0, 1, 0);

            // Define lights.
            AmbientLight ambientLight = new AmbientLight(Colors.White);

            group.Children.Add(ambientLight);

            // Create the model.
            // Globe. Place it in a new model so we can transform it.
            Model3DGroup globe = new Model3DGroup();

            group.Children.Add(globe);

            ImageBrush globeBrush    = new ImageBrush(new BitmapImage(new Uri(textureFilePath, UriKind.RelativeOrAbsolute)));
            Material   globeMaterial = new DiffuseMaterial(globeBrush);

            MakeSphere(globe, globeMaterial, 1, 0, 0, 0, 64, 64);

            // Add the group of models to a ModelVisual3D.
            ModelVisual3D visual = new ModelVisual3D();

            visual.Content = group;

            // Display the main visual to the viewport.
            viewport.Children.Add(visual);

            viewport.Width  = size;
            viewport.Height = size;
            viewport.Measure(new System.Windows.Size(size, size));
            viewport.Arrange(new System.Windows.Rect(0, 0, size, size));
            viewport.InvalidateVisual();

            if (targetBitmap == null)
            {
                targetBitmap = new RenderTargetBitmap(size, size, 96, 96, PixelFormats.Pbgra32);
            }

            targetBitmap.Clear();
            targetBitmap.Render(viewport);

            return(ToWinFormsBitmap(targetBitmap));
        }
        protected override Bitmap GetThumbnailImage(uint width) // Implemented abstract function in the base class
        {
            string debug = (string)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Marlin3DprinterTool", "Debug", "false");


            Logger(debug, "Creating Memorystream", EventLogEntryType.Information, 100);
            MemoryStream memStream = new MemoryStream();


            Logger(debug, "Creating Thread", EventLogEntryType.Information, 200);
            Thread thread = new Thread(() =>
            {
                Logger(debug, "Try Thread", EventLogEntryType.Information, 210);
                try
                {
                    Logger(debug, "Get Color", EventLogEntryType.Information, 220);
                    string color = (string)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Marlin3DprinterTool", "Color", "Blue");

                    Logger(debug, $"Color: {color}", EventLogEntryType.Information, 222);

                    Logger(debug, "Start reader", EventLogEntryType.Information, 230);
                    var stlReader             = new StLReader();
                    stlReader.DefaultMaterial = new DiffuseMaterial(
                        new SolidColorBrush((Color)ColorConverter.ConvertFromString(color)));

                    Logger(debug, "Reader configured", EventLogEntryType.Information, 240);

                    //stlReader.DefaultMaterial = new DiffuseMaterial(new SolidColorBrush(Colors.Blue));

                    Logger(debug, "Start reader the model", EventLogEntryType.Information, 250);
                    var model = stlReader.Read(SelectedItemStream);
                    Logger(debug, "Model ok", EventLogEntryType.Information, 260);


                    Logger(debug, "Create UI control", EventLogEntryType.Information, 300);
                    //...create UI controls...

                    Logger(debug, "Create Viewport", EventLogEntryType.Information, 310);
                    Viewport3D viewport = new Viewport3D();
                    Logger(debug, "Viewport done", EventLogEntryType.Information, 320);


                    Logger(debug, $"viewport.Measure: {width}", EventLogEntryType.Information, 330);
                    // viewport.Measure(new System.Windows.Size(320, 240));
                    viewport.Measure(new Size(width, width));
                    // viewport.Arrange(new Rect(0, 0, 320, 240));
                    Logger(debug, $"viewport.Arrange: {width}", EventLogEntryType.Information, 340);
                    viewport.Arrange(new Rect(0, 0, width, width));


                    Logger(debug, "ModelVisual3D", EventLogEntryType.Information, 350);
                    ModelVisual3D root = new ModelVisual3D();

                    Logger(debug, "viewport.Children.Add", EventLogEntryType.Information, 360);
                    viewport.Children.Add(root);


                    Logger(debug, "Camera", EventLogEntryType.Information, 400);
                    var camera               = new PerspectiveCamera();
                    camera.Position          = new Point3D(2, 16, 20);
                    camera.LookDirection     = new Vector3D(-2, -16, -20);
                    camera.UpDirection       = new Vector3D(0, 0, 1);
                    camera.FieldOfView       = 45;
                    camera.NearPlaneDistance = 0.1;
                    camera.FarPlaneDistance  = double.PositiveInfinity;
                    viewport.Camera          = camera;
                    Logger(debug, "Camera Done", EventLogEntryType.Information, 410);



                    Logger(debug, "Add light", EventLogEntryType.Information, 420);
                    root.Children.Add(new DefaultLights());
                    Logger(debug, "Add model", EventLogEntryType.Information, 430);
                    root.Content = model;


                    Logger(debug, "Do camera.ZoomExtents", EventLogEntryType.Information, 440);
                    camera.ZoomExtents(viewport);


                    Logger(debug, "Do background", EventLogEntryType.Information, 450);
                    Brush background = new SolidColorBrush(Colors.Transparent);

                    Logger(debug, "Do a BitmapExporter", EventLogEntryType.Information, 460);
                    BitmapExporter exporter = new BitmapExporter
                    {
                        OversamplingMultiplier = 2,
                        Background             = background
                    };

                    Logger(debug, "Fill the exporter", EventLogEntryType.Information, 470);
                    exporter.Export(viewport, memStream);
                }
                catch (Exception errorException)
                {
                    Logger(debug, errorException.Message, EventLogEntryType.Error, errorException.HResult);
                    //TODO: Empty Catch
                }
            });


            Logger(debug, "Thread STA", EventLogEntryType.Information, 500);
            thread.SetApartmentState(ApartmentState.STA);
            Logger(debug, "Thread Sstart", EventLogEntryType.Information, 510);
            thread.Start();
            Logger(debug, "Thread Join", EventLogEntryType.Information, 520);
            thread.Join();

            Logger(debug, "Create bitmap from memstream", EventLogEntryType.Information, 530);
            Bitmap thumbnailBitmap = (Bitmap)Image.FromStream(memStream);

            Logger(debug, "Return Bitmap!", EventLogEntryType.Information, 500);
            return(thumbnailBitmap);
        }
예제 #13
0
        /*Применяет произвольное 3D-преобразование к изображению*/
        public static void ApplyTransform(string input, string output, Matrix3D matr)
        {
            Viewport3D  myViewport3D;
            BitmapImage image = new BitmapImage(new Uri(input));

            // Declare scene objects.
            myViewport3D = new Viewport3D();
            Model3DGroup    myModel3DGroup  = new Model3DGroup();
            GeometryModel3D myGeometryModel = new GeometryModel3D();
            ModelVisual3D   myModelVisual3D = new ModelVisual3D();
            // Defines the camera used to view the 3D object. In order to view the 3D object,
            // the camera must be positioned and pointed such that the object is within view
            // of the camera.
            PerspectiveCamera myPCamera = new PerspectiveCamera();

            // Specify where in the 3D scene the camera is.
            myPCamera.Position = new Point3D(0, 0, Math.Max(image.PixelWidth, image.PixelHeight) * 2);

            // Specify the direction that the camera is pointing.
            myPCamera.LookDirection = new Vector3D(0, 0, -1);

            // Define camera's horizontal field of view in degrees.
            myPCamera.FieldOfView = 60;

            // Asign the camera to the viewport
            myViewport3D.Camera = myPCamera;

            // Define the lights cast in the scene. Without light, the 3D object cannot
            // be seen. Note: to illuminate an object from additional directions, create
            // additional lights.
            AmbientLight al = new AmbientLight(Colors.White);

            myModel3DGroup.Children.Add(al);

            // The geometry specifes the shape of the 3D plane. In this sample, a flat sheet
            // is created.
            MeshGeometry3D myMeshGeometry3D = new MeshGeometry3D();

            // Create a collection of normal vectors for the MeshGeometry3D.
            Vector3DCollection myNormalCollection = new Vector3DCollection();

            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myNormalCollection.Add(new Vector3D(0, 0, 1));
            myMeshGeometry3D.Normals = myNormalCollection;

            // Create a collection of vertex positions for the MeshGeometry3D.
            Point3DCollection myPositionCollection = new Point3DCollection();

            myPositionCollection.Add(new Point3D(-image.PixelWidth / 2.0, -image.PixelHeight / 2.0, 0.5));
            myPositionCollection.Add(new Point3D(image.PixelWidth / 2.0, -image.PixelHeight / 2.0, 0.5));
            myPositionCollection.Add(new Point3D(image.PixelWidth / 2.0, image.PixelHeight / 2.0, 0.5));
            myPositionCollection.Add(new Point3D(image.PixelWidth / 2.0, image.PixelHeight / 2.0, 0.5));
            myPositionCollection.Add(new Point3D(-image.PixelWidth / 2.0, image.PixelHeight / 2.0, 0.5));
            myPositionCollection.Add(new Point3D(-image.PixelWidth / 2.0, -image.PixelHeight / 2.0, 0.5));
            myMeshGeometry3D.Positions = myPositionCollection;

            // Create a collection of texture coordinates for the MeshGeometry3D.
            PointCollection myTextureCoordinatesCollection = new PointCollection();

            Point p5  = new Point(0, 0);
            Point p34 = new Point(1, 0);
            Point p2  = new Point(1, 1);
            Point p16 = new Point(0, 1);

            myTextureCoordinatesCollection.Add(p16);
            myTextureCoordinatesCollection.Add(p2);
            myTextureCoordinatesCollection.Add(p34);
            myTextureCoordinatesCollection.Add(p34);
            myTextureCoordinatesCollection.Add(p5);
            myTextureCoordinatesCollection.Add(p16);

            myMeshGeometry3D.TextureCoordinates = myTextureCoordinatesCollection;

            // Create a collection of triangle indices for the MeshGeometry3D.
            Int32Collection myTriangleIndicesCollection = new Int32Collection();

            myTriangleIndicesCollection.Add(0);
            myTriangleIndicesCollection.Add(1);
            myTriangleIndicesCollection.Add(2);
            myTriangleIndicesCollection.Add(3);
            myTriangleIndicesCollection.Add(4);
            myTriangleIndicesCollection.Add(5);
            myMeshGeometry3D.TriangleIndices = myTriangleIndicesCollection;

            // Apply the mesh to the geometry model.
            myGeometryModel.Geometry = myMeshGeometry3D;

            // The material specifies the material applied to the 3D object.

            ImageBrush br = new ImageBrush(image);

            // Define material and apply to the mesh geometries.
            DiffuseMaterial myMaterial = new DiffuseMaterial(br);

            myGeometryModel.Material     = myMaterial;
            myGeometryModel.BackMaterial = myMaterial;

            MatrixTransform3D transform = new MatrixTransform3D(matr);

            myGeometryModel.Transform = transform;

            // Add the geometry model to the model group.
            myModel3DGroup.Children.Add(myGeometryModel);

            // Add the group of models to the ModelVisual3d.
            myModelVisual3D.Content = myModel3DGroup;
            myViewport3D.Children.Add(myModelVisual3D);

            //render Viewport3D into bitmap
            int width  = image.PixelWidth;
            int height = image.PixelHeight;

            myViewport3D.Width  = width;
            myViewport3D.Height = height;
            myViewport3D.Measure(new Size(width, height));
            myViewport3D.Arrange(new Rect(0, 0, width, height));

            RenderTargetBitmap rtb = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);

            rtb.Render(myViewport3D);

            //Save bitmap to file
            using (var fileStream = new FileStream(output, FileMode.Create))
            {
                BitmapEncoder encoder = new JpegBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(rtb));
                encoder.Save(fileStream);
            }
        }
예제 #14
0
        protected Bitmap GetThumbnailImage(int width) // Implemented abstract function in the base class
        {
            bool everythingisOk = true;



            MemoryStream memStream = new MemoryStream();



            Thread thread = new Thread(() =>
            {
                //string tracefile = @"C:\temp\stlviewer.stl_log";
                string tracefile = TargetFile.Replace(".stl", ".stl_log");


                Logg("_______________________________________________________________________________");
                FileInfo fileInfo = new FileInfo(TargetFile);
                Logg($"Name: {fileInfo.Name}");
                Logg($"Dir.: {fileInfo.Directory}");

                Logg($"Size: {fileInfo.Length}");
                Logg("1. Tread started");


                object convertFromString = null;
                Color color              = new Color();
                ModelVisual3D root       = new ModelVisual3D();
                Model3DGroup model       = new Model3DGroup();
                PerspectiveCamera camera = new PerspectiveCamera();
                BitmapExporter exporter  = new BitmapExporter();


                if (everythingisOk)
                {
                    try
                    {
                        string colorString = (string)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Marlin3DprinterTool", "Color", "Blue");

                        convertFromString = ColorConverter.ConvertFromString(colorString);
                        Logg($"2. Color: {convertFromString}");
                        if (convertFromString != null)
                        {
                            color = (Color)convertFromString;
                        }
                    }
                    catch (Exception e)
                    {
                        Logg($"Something goes wrong in Color {e.Message}");
                        everythingisOk = false;
                    }
                }

                if (everythingisOk)
                {
                    if (convertFromString != null)
                    {
                        Viewport3D viewport = new Viewport3D();

                        if (everythingisOk)
                        {
                            try
                            {
                                Logg($"3. STLreader");
                                StLReader stlReader       = new StLReader();
                                stlReader.DefaultMaterial = new DiffuseMaterial(new SolidColorBrush(color));

                                Logg($"4. Read the Targetfile {TargetFile}");
                                model = stlReader.Read(TargetFile);
                                Logg($"5. Model read. New Viewport");
                            }
                            catch (Exception e)
                            {
                                Logg($"Something goes wrong in STLreader {e.Message}");
                                everythingisOk = false;
                            }
                        }



                        if (everythingisOk)
                        {
                            try
                            {
                                Logg($"6. Arrange with / height {width}/{width}");
                                viewport.Measure(new Size(width, width));
                                viewport.Arrange(new Rect(0, 0, width, width));

                                Logg($"7. Create root");

                                viewport.Children.Add(root);


                                Logg($"8. Create camera");

                                camera.Position          = new Point3D(2, 16, 20);
                                camera.LookDirection     = new Vector3D(-2, -16, -20);
                                camera.UpDirection       = new Vector3D(0, 0, 1);
                                camera.FieldOfView       = 45;
                                camera.NearPlaneDistance = 0.1;
                                camera.FarPlaneDistance  = double.PositiveInfinity;
                                viewport.Camera          = camera;
                            }
                            catch (Exception e)
                            {
                                Logg($"Something goes wrong in STLarrange {e.Message}");
                                everythingisOk = false;
                            }
                        }

                        if (everythingisOk)
                        {
                            try
                            {
                                Logg($"8.1. Create light");
                                root.Children.Add(new DefaultLights());
                                Logg($"8.2 Load model");
                                root.Content = model;


                                camera.ZoomExtents(viewport);
                                Logg($"9. Create Background");
                                Brush background = new SolidColorBrush(Colors.Transparent);

                                Logg($"10. Create Exporter");

                                exporter.Background             = background;
                                exporter.OversamplingMultiplier = 1;
                            }
                            catch (Exception e)
                            {
                                Logg($"Something goes wrong in Background/Light {e.Message}");
                                everythingisOk = false;
                            }
                        }

                        if (everythingisOk)
                        {
                            try
                            {
                                Logg($"11. Export to memorystream");
                                exporter.Export(viewport, memStream);
                                //Logg($"11. Export to {tempBitmap}");
                                //FileStream fs = new FileStream(tempBitmap, FileMode.Create, FileAccess.ReadWrite);
                                //exporter.Export(viewport, fs);
                                //fs.Flush();
                                //fs.Close();
                            }
                            catch (Exception e)
                            {
                                Logg($"Something goes wrong in Export to memory Stream {e.Message}");
                                everythingisOk = false;
                            }
                        }
                    }
                }
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();



            if (everythingisOk)
            {
                try
                {
                    Logg($"12. Create Bitmap from memorystream");
                    Bitmap thumbnailBitmap = (Bitmap)Image.FromStream(memStream);

                    return(thumbnailBitmap);
                }
                catch (Exception e)
                {
                    Logg($"Something goes wrong in Bitmap from messageStream {e.Message}");
                    Logg("_______________________________________________________________________________");

                    return(null);
                }
            }
            Logg("_______________________________________________________________________________");

            return(null);
        }
예제 #15
0
        private void RenderButton_OnClick(object sender, RoutedEventArgs e)
        {
            // Update camera based on the HeadingSlider value
            UpdateCamera();

            var stopwatch = new Stopwatch();

            stopwatch.Start();


            BitmapWidth  = (int)ImageBorder.ActualWidth;
            BitmapHeight = (int)ImageBorder.ActualHeight;

            double dpiScaleX, dpiScaleY;

            DXView.GetDpiScale(this, out dpiScaleX, out dpiScaleY);

            double dpiX = 96.0 * dpiScaleX; // 96 is the default dpi value without any scaling
            double dpiY = 96.0 * dpiScaleY;


            // The following 6 lines are not needed because the DXViewportView is not shown:

            _viewport3D.Width  = BitmapWidth;
            _viewport3D.Height = BitmapHeight;

            // Because DXViewportView is not actually show, we need to call Measure and Arrange
            _viewport3D.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
            _viewport3D.Arrange(new Rect(0, 0, _viewport3D.DesiredSize.Width, _viewport3D.DesiredSize.Height));

            // Update camera
            _camera.Refresh();

            // Update 3D lines
            Ab3d.Utilities.LinesUpdater.Instance.Refresh();


            int multiSamplingCount, superSamplingCount;

            GetAntiAliasingSettings(out multiSamplingCount, out superSamplingCount);


            var convertToNonPreMultipledAlpha = ConvertToNonPremultipliedAlphaCheckBox.IsChecked ?? false;

            if (ReuseWriteableBitmapCheckBox.IsChecked ?? false)
            {
                // Create only one instance of WriteableBitmap, then reuse it with other calls to RenderToBitmap

                if (_writeableBitmap == null) // we would also need to recreate the WriteableBitmap in case the size changes
                {
                    int finalBitmapWidth  = (int)(BitmapWidth * dpiScaleX);
                    int finalBitmapHeight = (int)(BitmapHeight * dpiScaleY);

                    // When using WriteableBitmap, the RenderToBitmap will use pre-multiplied alpha
                    // or non pre-multiplied alpha based on the pixel format (Pbgra32 for pre-multiplied alpha).
                    //
                    // When the rendered image is shown in WPF, then it is recommended to use Pbgra32 (pre-multiplied alpha)
                    // because this is also what is internally used by WPF.
                    //
                    // But when the image is saved to png image, then the image should be non pre-multiplied
                    // because png does not support pre-multiplied image.

                    var pixelFormat = convertToNonPreMultipledAlpha ? PixelFormats.Bgra32 : PixelFormats.Pbgra32;

                    _writeableBitmap = new WriteableBitmap(finalBitmapWidth, finalBitmapHeight, 96, 96, pixelFormat, null); // always use 96 as dpi for WriteableBitmap otherwise the bitmap will be shown too small
                }

                _dxViewportView.RenderToBitmap(_writeableBitmap, multiSamplingCount, superSamplingCount);

                _renderBitmap = _writeableBitmap;
            }
            else
            {
                // When we do not need to reuse the WriteableBitmap, we can use the following RenderToBitmap method:
                _renderBitmap = _dxViewportView.RenderToBitmap(width:  (int)(BitmapWidth * dpiScaleX),
                                                               height: (int)(BitmapHeight * dpiScaleY),
                                                               preferedMultisampling: multiSamplingCount, // when -1 is used, then the currently used multisampling is used
                                                               supersamplingCount: superSamplingCount,
                                                               dpiX: dpiX,
                                                               dpiY: dpiY,
                                                               convertToNonPreMultipledAlpha: convertToNonPreMultipledAlpha); // pixel format of the returned image will be Pbgra32 (when convertToNonPreMultipledAlpha is false) or Bgra32 when true.
            }


            // Display render time (note that the first time the scene is rendered the time is bigger because of additional initializations)
            stopwatch.Stop();
            InfoTextBlock.Text = string.Format("Render time: {0:0.0}ms", stopwatch.Elapsed.TotalMilliseconds);

            if (_isFirstRender)
            {
                InfoTextBlock.Text += " (note: render time of the first image is longer then the time to render other images)";
                _isFirstRender      = false;
            }

            RenderedImage.Source = _renderBitmap;

            TipTextBlock.Visibility = Visibility.Collapsed;

            SaveButton.Visibility = Visibility.Visible;
        }