public void LoadStl(string path)
        {
            var reader = new StLReader();
            var objCol = reader.Read(path);

            AttachModelList(objCol);
        }
예제 #2
0
 public void Read_Bottle_ValidModel()
 {
     var r = new StLReader();
     var model = r.Read(@"Models\stl\bottle.stl");
     Assert.AreEqual("FLIRIS", r.Header);
     Assert.AreEqual(1, model.Children.Count);
     var m0 = (MeshGeometry3D)((GeometryModel3D)model.Children[0]).Geometry;
     Assert.AreEqual(1240, m0.TriangleIndices.Count / 3);
 }
예제 #3
0
        public override void Calculate()
        {
            if (InputPorts[0].Data == null)
            {
                return;
            }

            if (InputPorts[0].Data is string)
            {
                var extension = Path.GetExtension(InputPorts[0].Data as string);

                var flag = false;

                switch (extension)
                {
                case ".obj":
                    var currentHelixObjReader = new ObjReader();
                    try
                    {
                        var objModel      = currentHelixObjReader.Read((string)InputPorts[0].Data);
                        var modelGroup    = new GroupModel3D();
                        var modelGeometry = new Element3DCollection();
                        modelGeometry.AddRange(
                            objModel.Select(
                                x =>
                                new MeshGeometryModel3D
                        {
                            Geometry = x.Geometry as MeshGeometry3D,
                            Material = x.Material
                        }));

                        modelGroup.Children = modelGeometry;

                        Dispatcher.BeginInvoke((Action) delegate { _control.ViewPort3D.Items.Add(modelGroup); });
                    }
                    catch (Exception)
                    {
                        // ignore
                    }
                    break;

                case ".stl":
                    var currentHelixStlReader = new StLReader();
                    try
                    {
                        var myModel = currentHelixStlReader.Read((string)InputPorts[0].Data);
                        // _control.ViewPort3D.Items.Add(myModel);
                    }
                    catch (Exception)
                    {
                        // ignore
                    }
                    break;
                }
            }
        }
예제 #4
0
 public void Read_BinaryBottle_ValidModel()
 {
     // ASCII format converted to BINARY by MeshLab
     var r = new StLReader();
     var model = r.Read(@"Models\stl\binary\bottle.stl");
     Assert.AreEqual("VCG", r.Header);
     Assert.AreEqual(1, model.Children.Count);
     var m0 = (MeshGeometry3D)((GeometryModel3D)model.Children[0]).Geometry;
     Assert.AreEqual(1240, m0.TriangleIndices.Count / 3);
 }
예제 #5
0
        public void Read_Sphere_ValidModel()
        {
            var r     = new StLReader();
            var model = r.Read(@"Models\stl\sphere.stl");

            Assert.AreEqual(1, model.Children.Count);
            var m0 = (MeshGeometry3D)((GeometryModel3D)model.Children[0]).Geometry;

            Assert.AreEqual(228, m0.TriangleIndices.Count / 3);
        }
예제 #6
0
 public void Read_Bottle_DefaultMaterialChanged()
 {
     var r = new StLReader();
     r.DefaultMaterial = MaterialHelper.CreateMaterial(Colors.Aqua);
     var model = r.Read(@"Models\stl\bottle.stl");
     Assert.AreEqual(1, model.Children.Count);
     var gm0 = (GeometryModel3D)model.Children[0];
     var m0 = (MaterialGroup)gm0.Material;
     var dm = (DiffuseMaterial)m0.Children[0];
     Assert.AreEqual(Colors.Aqua, ((SolidColorBrush)dm.Brush).Color);
 }
예제 #7
0
        public void Read_Cube_ValidModel()
        {
            // reader does not yet support quads
            var r = new StLReader();
            var model = r.Read(@"Models\stl\cube.stl");
            Assert.AreEqual(1, model.Children.Count);
            var m0 = (MeshGeometry3D)((GeometryModel3D)model.Children[0]).Geometry;

            // Expects 6 quad faces => 12 triangles
            Assert.AreEqual(12, m0.TriangleIndices.Count / 3);
        }
예제 #8
0
        public void Read_Bottle_ValidModel()
        {
            var r     = new StLReader();
            var model = r.Read(@"Models\stl\bottle.stl");

            Assert.AreEqual("FLIRIS", r.Header);
            Assert.AreEqual(1, model.Children.Count);
            var m0 = (MeshGeometry3D)((GeometryModel3D)model.Children[0]).Geometry;

            Assert.AreEqual(1240, m0.TriangleIndices.Count / 3);
        }
예제 #9
0
        public void Read_Cube_ValidModel()
        {
            // reader does not yet support quads
            var r     = new StLReader();
            var model = r.Read(@"Models\stl\cube.stl");

            Assert.AreEqual(1, model.Children.Count);
            var m0 = (MeshGeometry3D)((GeometryModel3D)model.Children[0]).Geometry;

            // Expects 6 quad faces => 12 triangles
            Assert.AreEqual(12, m0.TriangleIndices.Count / 3);
        }
예제 #10
0
        public void Read_BinaryBottle_ValidModel()
        {
            // ASCII format converted to BINARY by MeshLab
            var r     = new StLReader();
            var model = r.Read(@"Models\stl\binary\bottle.stl");

            Assert.AreEqual("VCG", r.Header);
            Assert.AreEqual(1, model.Children.Count);
            var m0 = (MeshGeometry3D)((GeometryModel3D)model.Children[0]).Geometry;

            Assert.AreEqual(1240, m0.TriangleIndices.Count / 3);
        }
예제 #11
0
        public void Read_BottleFromStream_ValidModel()
        {
            Model3DGroup model;
            using (var s = File.OpenRead(@"Models\stl\bottle.stl"))
            {
                var r = new StLReader();
                model = r.Read(s);
            }

            Assert.AreEqual(1, model.Children.Count);
            var m0 = (MeshGeometry3D)((GeometryModel3D)model.Children[0]).Geometry;
            Assert.AreEqual(1240, m0.TriangleIndices.Count / 3);
        }
        public static Geometry3D GetConeModel(string coneFile)
        {
            Geometry3D geometry = null;
            var        reader   = new StLReader();
            var        objList  = reader.Read(coneFile);

            if (objList?.Count > 0)
            {
                geometry = objList[0].Geometry;
                geometry.UpdateOctree();
            }

            return(geometry);
        }
예제 #13
0
        public void Read_Bottle_DefaultMaterialChanged()
        {
            var r = new StLReader();

            r.DefaultMaterial = MaterialHelper.CreateMaterial(Colors.Aqua);
            var model = r.Read(@"Models\stl\bottle.stl");

            Assert.AreEqual(1, model.Children.Count);
            var gm0 = (GeometryModel3D)model.Children[0];
            var m0  = (MaterialGroup)gm0.Material;
            var dm  = (DiffuseMaterial)m0.Children[0];

            Assert.AreEqual(Colors.Aqua, ((SolidColorBrush)dm.Brush).Color);
        }
예제 #14
0
        public void Read_BottleFromStream_ValidModel()
        {
            Model3DGroup model;

            using (var s = File.OpenRead(@"Models\stl\bottle.stl"))
            {
                var r = new StLReader();
                model = r.Read(s);
            }

            Assert.AreEqual(1, model.Children.Count);
            var m0 = (MeshGeometry3D)((GeometryModel3D)model.Children[0]).Geometry;

            Assert.AreEqual(1240, m0.TriangleIndices.Count / 3);
        }
예제 #15
0
        public MeshVisualizer()
        {
            InitializeComponent();

            var reader = new StLReader();

            reader.DefaultMaterial = Materials.Green;
            var model = reader.Read(@"D:\Messe.stl");

            model.Freeze();

            viewport.Children.Add(new ModelVisual3D()
            {
                Content = model
            });
        }
        private static Geometry3D LoadGeometry(string geometryFile)
        {
            Geometry3D geometry = null;

            if (!string.IsNullOrEmpty(geometryFile))
            {
                var reader  = new StLReader();
                var objList = reader.Read(geometryFile);

                if (objList?.Count > 0)
                {
                    geometry = objList[0].Geometry;
                    geometry.UpdateOctree();
                }
            }

            return(geometry);
        }
예제 #17
0
        /// <summary>
        /// Display 3D Model
        /// </summary>
        /// <param name="model">Path to the Model file</param>
        /// <returns>3D Model Content</returns>
        private Model3DGroup Display3d(string filePath)
        {
            Model3DGroup device = null;

            try
            {
                //Adding a gesture here
                viewPort3d.RotateGesture = new MouseGesture(MouseAction.LeftClick);

                //Import 3D model file
                StLReader read = new StLReader();

                //Load the 3D model file
                device = read.Read(filePath);
            }
            catch (Exception e)
            {
                // Handle exception in case can not file 3D model
                MessageBox.Show("Exception Error : " + e.StackTrace);
            }
            return(device);
        }
        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);
        }
예제 #19
0
 public void Read_Sphere_ValidModel()
 {
     var r = new StLReader();
     var model = r.Read(@"Models\stl\sphere.stl");
     Assert.AreEqual(1, model.Children.Count);
     var m0 = (MeshGeometry3D)((GeometryModel3D)model.Children[0]).Geometry;
     Assert.AreEqual(228, m0.TriangleIndices.Count / 3);
 }
예제 #20
0
        public static Model3DGroup Load(string path, Dispatcher dispatcher = null, bool freeze = false, bool ignoreErrors = false)
        {
            if (path == null)
            {
                return(null);
            }

            var defaultMaterial = Materials.Blue;

            if (dispatcher == null)
            {
                dispatcher = Dispatcher.CurrentDispatcher;
            }

            Model3DGroup model;
            var          ext = Path.GetExtension(path).ToLower();

            switch (ext)
            {
            case ".3ds":
            {
                var r = new StudioReader(dispatcher)
                {
                    DefaultMaterial = defaultMaterial, Freeze = freeze
                };
                model = r.Read(path);
                break;
            }

            case ".lwo":
            {
                var r = new LwoReader(dispatcher)
                {
                    DefaultMaterial = defaultMaterial, Freeze = freeze
                };
                model = r.Read(path);
                break;
            }

            case ".obj":
            {
                var r = new ObjReader(dispatcher)
                {
                    DefaultMaterial = defaultMaterial, Freeze = freeze, IgnoreErrors = ignoreErrors
                };
                model = r.Read(path);
                break;
            }

            case ".objx":
            {
                var r = new ObjReader(dispatcher)
                {
                    DefaultMaterial = defaultMaterial, Freeze = freeze, IgnoreErrors = ignoreErrors
                };
                model = r.ReadZ(path);
                break;
            }

            case ".stl":
            {
                var r = new StLReader(dispatcher)
                {
                    DefaultMaterial = defaultMaterial, Freeze = freeze
                };
                model = r.Read(path);
                break;
            }

            case ".off":
            {
                var r = new OffReader(dispatcher)
                {
                    DefaultMaterial = defaultMaterial, Freeze = freeze
                };
                model = r.Read(path);
                break;
            }

            default:
                throw new InvalidOperationException("File format not supported.");
            }

            return(model);
        }
예제 #21
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);
        }
예제 #22
0
        /// <summary>
        /// Loads the Stl model into a Viewport3D and renders a bitmap of it.
        /// </summary>
        /// <param name="stream">The Stream instance for the Stl content.</param>
        /// <param name="cx">The maximum thumbnail size, in pixels.</param>
        /// <returns>A thumbnail rendered from the Stl model.</returns>
        public static Bitmap GetThumbnail(Stream stream, uint cx)
        {
            if (cx > MaxThumbnailSize || stream == null || stream.Length == 0)
            {
                return(null);
            }

            Bitmap thumbnail = null;

            var stlReader = new StLReader
            {
                DefaultMaterial = new DiffuseMaterial(new SolidColorBrush(Color.FromRgb(255, 201, 36))),
            };

            var model = stlReader.Read(stream);

            if (model.Bounds == Rect3D.Empty)
            {
                return(null);
            }

            var viewport = new System.Windows.Controls.Viewport3D();

            viewport.Measure(new Size(cx, cx));
            viewport.Arrange(new Rect(0, 0, cx, cx));

            var modelVisual = new ModelVisual3D()
            {
                Transform = new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(0, 0, 1), 180)),
            };

            viewport.Children.Add(modelVisual);
            viewport.Children.Add(new DefaultLights());

            var perspectiveCamera = new PerspectiveCamera
            {
                Position          = new Point3D(1, 2, 1),
                LookDirection     = new Vector3D(-1, -2, -1),
                UpDirection       = new Vector3D(0, 0, 1),
                FieldOfView       = 20,
                NearPlaneDistance = 0.1,
                FarPlaneDistance  = double.PositiveInfinity,
            };

            viewport.Camera = perspectiveCamera;

            modelVisual.Content = model;

            perspectiveCamera.ZoomExtents(viewport);

            var bitmapExporter = new BitmapExporter
            {
                Background             = new SolidColorBrush(Colors.Transparent),
                OversamplingMultiplier = 1,
            };

            var bitmapStream = new MemoryStream();

            bitmapExporter.Export(viewport, bitmapStream);

            bitmapStream.Position = 0;

            thumbnail = new Bitmap(bitmapStream);

            return(thumbnail);
        }
예제 #23
0
        public int LoadModel(String FilePath)
        {
            MeshGeometryModel3D m_model = new MeshGeometryModel3D();

            //ModelGeometry已經有幾何模型存在內部 及 阻擋檔案不存在的情況
            if (/*IsLoaded ||*/ !File.Exists(FilePath))  ///What the F**k is IsLoaded ??????
            {
                return(1);
            }
            //利用helixtoolkit.wpf裡面提供的StlReader讀檔案,後續要轉成wpf.sharpdx可用的格式
            StLReader reader = new StLReader();

            Model3DGroup ModelContainer = reader.Read(FilePath);

            Rect3D bound = ModelContainer.Bounds;


            var ModelCenter = new Vector3(Convert.ToSingle(bound.X + bound.SizeX / 2.0),
                                          Convert.ToSingle(bound.Y + bound.SizeY / 2.0),
                                          Convert.ToSingle(bound.Z + bound.SizeZ / 2.0));

            HelixToolkit.Wpf.SharpDX.MeshGeometry3D modelGeometry = new HelixToolkit.Wpf.SharpDX.MeshGeometry3D
            {
                Normals   = new Vector3Collection(),
                Positions = new Vector3Collection(),
                Indices   = new IntCollection()
            };



            foreach (System.Windows.Media.Media3D.Model3D model in ModelContainer.Children)
            {
                var geometryModel = model as System.Windows.Media.Media3D.GeometryModel3D;

                System.Windows.Media.Media3D.MeshGeometry3D mesh = geometryModel?.Geometry as System.Windows.Media.Media3D.MeshGeometry3D;

                if (mesh == null)
                {
                    continue;
                }

                //將從stlreader讀到的資料轉入
                foreach (Point3D position in mesh.Positions)
                {
                    modelGeometry.Positions.Add(new Vector3(
                                                    Convert.ToSingle(position.X)
                                                    , Convert.ToSingle(position.Y)
                                                    , Convert.ToSingle(position.Z)));
                }
                int i = 0;
                foreach (Vector3D normal in mesh.Normals)
                {
                    //Vector3D v1 = new Vector3D((modelGeometry.Positions[i + 1].X - modelGeometry.Positions[i].X), (modelGeometry.Positions[i + 1].Y - modelGeometry.Positions[i].Y), (modelGeometry.Positions[i + 1].Z - modelGeometry.Positions[i].Z));
                    //Vector3D v2 = new Vector3D((modelGeometry.Positions[i + 2].X - modelGeometry.Positions[i].X), (modelGeometry.Positions[i + 2].Y - modelGeometry.Positions[i].Y), (modelGeometry.Positions[i + 2].Z - modelGeometry.Positions[i].Z));
                    //Vector3D n = Vector3D.CrossProduct(v1, v2);
                    //modelGeometry.Normals.Add(new Vector3(
                    //     Convert.ToSingle(n.X)
                    //    , Convert.ToSingle(n.Y)
                    //    , Convert.ToSingle(n.Z)));
                    modelGeometry.Normals.Add(new Vector3(
                                                  Convert.ToSingle(normal.X)
                                                  , Convert.ToSingle(normal.Y)
                                                  , Convert.ToSingle(normal.Z)));
                }
                foreach (Int32 triangleindice in mesh.TriangleIndices)
                {
                    modelGeometry.Indices.Add(triangleindice);
                }
                //    MessageBox.Show(mesh.Normals.Count.ToString());
            }



            SetModelMaterial(m_model);

            m_model.Geometry = modelGeometry;


            ModelGroup.Children.Add(m_model);

            m_group.Add(m_model);

            ResetCameraPosition(bound);

            return(0);
        }
예제 #24
0
        /// <summary>
        ///     Read FileData
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public ContainerUIElement3D ReadFileData(string path)
        {
            var extension = Path.GetExtension(path);
            // var visModel = new ModelVisual3D();
            var container = new ContainerUIElement3D();

            switch (extension)
            {
            case ".obj":
                var currentHelixObjReader = new ObjReader();
                try
                {
                    var myModel = currentHelixObjReader.Read(path);

                    foreach (var model in myModel.Children)
                    {
                        if (model is GeometryModel3D)
                        {
                            var geom = model as GeometryModel3D;

                            var element = new ModelUIElement3D {
                                Model = geom
                            };
                            element.MouseDown += (sender1, e1) => OnElementMouseDown(sender1, e1, this);
                            container.Children.Add(element);
                        }
                    }
                }
                catch (Exception)
                {
                    // ignore
                }
                break;

            case ".stl":
                var currentHelixStlReader = new StLReader();
                try
                {
                    var myModel = currentHelixStlReader.Read(path);

                    foreach (var model in myModel.Children)
                    {
                        if (model is GeometryModel3D)
                        {
                            var geom = model as GeometryModel3D;

                            var element = new ModelUIElement3D {
                                Model = geom
                            };
                            element.MouseDown += (sender1, e1) => OnElementMouseDown(sender1, e1, this);
                            container.Children.Add(element);
                        }
                    }
                }
                catch (Exception)
                {
                    // ignore
                }
                break;
            }

            return(container);
        }
예제 #25
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);
        }
예제 #26
0
        /// <summary>
        /// load進模型檔案
        /// </summary>
        public void LoadModel()
        {
            //ModelGeometry已經有幾何模型存在內部 及 阻擋檔案不存在的情況
            if (IsLoaded || !File.Exists(FilePath))
            {
                return;
            }
            //利用helixtoolkit.wpf裡面提供的StlReader讀檔案,後續要轉成wpf.sharpdx可用的格式
            StLReader reader = new StLReader();

            ModelContainer = reader.Read(FilePath);

            Rect3D bound = ModelContainer.Bounds;

            ModelCenter = new Vector3(Convert.ToSingle(bound.X + bound.SizeX / 2.0),
                                      Convert.ToSingle(bound.Y + bound.SizeY / 2.0),
                                      Convert.ToSingle(bound.Z + bound.SizeZ / 2.0));

            HelixToolkit.Wpf.SharpDX.MeshGeometry3D modelGeometry = new HelixToolkit.Wpf.SharpDX.MeshGeometry3D
            {
                Normals   = new Vector3Collection(),
                Positions = new Vector3Collection(),
                Indices   = new IntCollection()
            };



            foreach (Model3D model in ModelContainer.Children)
            {
                var geometryModel = model as GeometryModel3D;

                MeshGeometry3D mesh = geometryModel?.Geometry as MeshGeometry3D;

                if (mesh == null)
                {
                    continue;
                }

                //將從stlreader讀到的資料轉入
                foreach (Point3D position in mesh.Positions)
                {
                    modelGeometry.Positions.Add(new Vector3(
                                                    Convert.ToSingle(position.X)
                                                    , Convert.ToSingle(position.Y)
                                                    , Convert.ToSingle(position.Z)));
                }
                foreach (Vector3D normal in mesh.Normals)
                {
                    modelGeometry.Normals.Add(new Vector3(
                                                  Convert.ToSingle(normal.X)
                                                  , Convert.ToSingle(normal.Y)
                                                  , Convert.ToSingle(normal.Z)));
                }
                foreach (Int32 triangleindice in mesh.TriangleIndices)
                {
                    modelGeometry.Indices.Add(triangleindice);
                }
            }

            SetBoneMaterial();

            Geometry = modelGeometry;

            IsLoaded = true;
        }