Пример #1
0
        private void buttonOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Title  = "Open Scene File";
            ofd.Filter = "Wavefront OBJ Files|*.obj;*.obj.gz" +
                         "|All scene types|*.obj";

            ofd.FilterIndex = 1;
            ofd.FileName    = "";
            if (ofd.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            WavefrontObj objReader = new WavefrontObj();

            objReader.MirrorConversion = false;
            int faces = objReader.ReadBrep(ofd.FileName, scene);

            scene.BuildCornerTable();
            int errors = scene.CheckCornerTable(null);

            labelFaces.Text = string.Format("{0} faces, {1} errors", faces, errors);
            redraw();
        }
Пример #2
0
        private void buttonLoad_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Title  = "Open Scene File";
            ofd.Filter = "Wavefront OBJ Files|*.obj;*.obj.gz" +
                         "|All scene types|*.obj";

            ofd.FilterIndex = 1;
            ofd.FileName    = "";
            if (ofd.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            WavefrontObj objReader = new WavefrontObj();

            objReader.MirrorConversion = false;
            int faces = objReader.ReadBrep(ofd.FileName, brepScene);

            brepScene.BuildCornerTable();
            labelSample.Text = string.Format("{0} faces", faces);

            imf  = null; // reset the scene object (to be sure)
            rend = null; // reset the renderer as well..
        }
Пример #3
0
        private void buttonSaveOBJ_Click(object sender, EventArgs e)
        {
            if (scene == null || scene.Triangles < 1)
            {
                return;
            }

            SaveFileDialog sfd = new SaveFileDialog();

            sfd.Title        = "Save OBJ file";
            sfd.Filter       = "OBJ Files|*.obj";
            sfd.AddExtension = true;
            sfd.FileName     = "";
            if (sfd.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            WavefrontObj objWriter = new WavefrontObj();

            objWriter.MirrorConversion = true;
            StreamWriter writer = new StreamWriter(new FileStream(sfd.FileName, FileMode.Create));

            objWriter.WriteBrep(writer, scene);
            writer.Close();
        }
Пример #4
0
        private void buttonOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Title  = "Open Scene File";
            ofd.Filter = "Wavefront OBJ Files|*.obj;*.obj.gz" +
                         "|All scene types|*.obj";

            ofd.FilterIndex = 1;
            ofd.FileName    = "";
            if (ofd.ShowDialog() != DialogResult.OK)
            {
                cn     = null;
                points = 0;
                return;
            }

            WavefrontObj objReader = new WavefrontObj();

            objReader.MirrorConversion = false;

            int faces = objReader.ReadBrep(ofd.FileName, scene);

            scene.BuildCornerTable();
            diameter = scene.GetDiameter(out center);
            ResetCamera();

            cn     = new Subdivision();
            points = cn.Subdivide(scene, (float)numericSubdivision.Value * diameter, checkNormals.Checked, checkColors.Checked, false, 0.0f, textParam.Text);

            labelFile.Text = string.Format("{0}: {1} f, {2} pts", ofd.SafeFileName, faces, points);

            PrepareDataBuffers();
            glControl1.Invalidate();
        }
Пример #5
0
        private void buttonOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Title  = "Open Scene File";
            ofd.Filter = "Wavefront OBJ Files|*.obj;*.obj.gz" +
                         "|All scene types|*.obj";

            ofd.FilterIndex = 1;
            ofd.FileName    = "";
            if (ofd.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            WavefrontObj objReader = new WavefrontObj();

            objReader.MirrorConversion = false;

            int faces = objReader.ReadBrep(ofd.FileName, scene);

            scene.BuildCornerTable();
            diameter = scene.GetDiameter(out center);
            scene.GenerateColors(12);
            ResetCamera();

            labelFile.Text = string.Format("{0}: {1} faces", ofd.SafeFileName, faces);
            PrepareDataBuffers();
            glControl1.Invalidate();
        }
Пример #6
0
        private void buttonOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Title  = "Open Scene File";
            ofd.Filter = "Wavefront OBJ Files|*.obj;*.obj.gz" + "|Polygon File Format|*.ply" +
                         "|All scene types|*.obj;*.ply";
            ofd.FilterIndex = 1;
            ofd.FileName    = "";
            if (ofd.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            string ext = Path.GetExtension(ofd.FileName);

            StanfordPly  plyReader;
            WavefrontObj objReader;

            if (ext == ".ply")
            {
                plyReader = new StanfordPly();
                if (plyReader.ReadBrep(ofd.FileName, scene) == -1)
                {
                    MessageBox.Show("Invalid .ply file");
                }
            }
            else
            {
                objReader = new WavefrontObj();
                objReader.MirrorConversion  = false;
                objReader.TextureUpsideDown = checkOrientation.Checked;
                objReader.ReadBrep(ofd.FileName, scene);
            }

            scene.BuildCornerTable();
            diameter = scene.GetDiameter(out center);
            scene.GenerateColors(12);
            scene.ComputeNormals();

            UpdateParams(textParam.Text);
            tb.Center   = center;
            tb.Diameter = diameter;
            SetLight(diameter, ref light);
            tb.Reset();

            labelFile.Text = string.Format("{0} @ {1} vertices, {2} edges ({3}), {4} faces",
                                           ofd.SafeFileName, scene.Vertices,
                                           scene.statEdges, scene.statShared,
                                           scene.Triangles);
            PrepareDataBuffers();

            glControl1.Invalidate();

            // Supports point selection
            selectedPoints = new Selection(scene);
            commandManager = new CommandManager();
        }
Пример #7
0
        public MorphForm()
        {
            InitializeComponent();
            Text += " (rev: " + rev + ')';

            mMorph        = new Morph();
            mWavefrontObj = new WavefrontObj();
            //mFirstObject = new SceneBrep();
            //mSecondObject = new SceneBrep();
            mCamera = new Camera();
        }
Пример #8
0
        public Model LoadModel(string path)
        {
            if (Models.TryGetValue(path, out var value))
            {
                return(value);
            }

            var mesh = WavefrontObj.Load(path);

            value = Model.FromMesh(Device, mesh);
            Models.Add(path, value);
            return(value);
        }
Пример #9
0
        private void buttonExportPly_Click(object sender, EventArgs e)
        {
            if (scene == null ||
                scene.Triangles < 1)
            {
                return;
            }

            SaveFileDialog sfd = new SaveFileDialog();

            sfd.Title        = "Save file";
            sfd.Filter       = "PLY Files|*.ply" + "|OBJ Files|*.obj";
            sfd.AddExtension = true;
            sfd.FileName     = "";
            if (sfd.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            string ext = Path.GetExtension(sfd.FileName);

            switch (ext)
            {
            case ".ply":
                StanfordPly plyWriter = new StanfordPly();
                plyWriter.TextFormat    = true;
                plyWriter.NativeNewLine = true;
                plyWriter.Orientation   = checkOrientation.Checked;
                //plyWriter.DoNormals     = false;
                //plyWriter.DoTxtCoords   = false;
                plyWriter.DoColors = false;
                using (StreamWriter writer = new StreamWriter(new FileStream(sfd.FileName, FileMode.Create)))
                {
                    plyWriter.WriteBrep(writer, scene);
                }
                break;

            case ".obj":
                WavefrontObj objWriter = new WavefrontObj();
                using (StreamWriter writer = new StreamWriter(new FileStream(sfd.FileName, FileMode.Create)))
                {
                    objWriter.WriteBrep(writer, scene);
                }
                break;

            default:
                break;
            }
        }
Пример #10
0
        private void buttonOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Title  = "Open Scene File";
            ofd.Filter = "Wavefront OBJ Files|*.obj;*.obj.gz" +
                         "|All scene types|*.obj";

            ofd.FilterIndex = 1;
            ofd.FileName    = "";
            if (ofd.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            WavefrontObj objReader = new WavefrontObj();

            objReader.MirrorConversion  = false;
            objReader.TextureUpsideDown = checkOrientation.Checked;
            objReader.ReadBrep(ofd.FileName, scene);

            // Scene postprocessing.
            scene.BuildCornerTable();
            scene.GenerateColors(12);
            scene.ComputeNormals();
            diameter = scene.GetDiameter(out center);

            // Viewport update.
            UpdateParams(textParam.Text);
            tb.Center   = center;
            tb.Diameter = diameter;
            tb.Reset();

            camera.Center   = center;
            camera.Diameter = diameter;
            camera.Reset();

            SetupViewport();
            SetLight(diameter, ref light);

            modelStatus    = $"{ofd.SafeFileName}: {scene.Vertices}v, {scene.statEdges}e({scene.statShared}), {scene.Triangles + scene.Lines}f";
            labelFile.Text = modelStatus;

            // Prepare rendering system.
            PrepareDataBuffers();
            glControl1.Invalidate();
        }
Пример #11
0
        private void buttonExportPly_Click(object sender, EventArgs e)
        {
            if (scene == null ||
                scene.Triangles < 1)
            {
                return;
            }

            SaveFileDialog sfd = new SaveFileDialog();

            sfd.Title        = "Save OBJ/PLY file";
            sfd.Filter       = "OBJ Files|*.obj|PLY Files|*.ply";
            sfd.AddExtension = true;
            sfd.FileName     = "";
            if (sfd.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            if (sfd.FileName.EndsWith(".ply"))
            {
                // Stanford PLY format.
                StanfordPly plyWriter = new StanfordPly();
                plyWriter.TextFormat    = true;
                plyWriter.NativeNewLine = true;
                plyWriter.Orientation   = checkOrientation.Checked;
                //plyWriter.DoNormals     = false;
                //plyWriter.DoTxtCoords   = false;
                plyWriter.DoColors = false;
                using (StreamWriter writer = new StreamWriter(new FileStream(sfd.FileName, FileMode.Create)))
                {
                    plyWriter.WriteBrep(writer, scene);
                }
            }
            else
            {
                // Wavefront OBJ format.
                WavefrontObj objWriter = new WavefrontObj();
                objWriter.MirrorConversion = true;
                using (StreamWriter writer = new StreamWriter(new FileStream(sfd.FileName, FileMode.Create)))
                {
                    objWriter.WriteBrep(writer, scene);
                }
            }
        }
Пример #12
0
 public static MeshDef Load(FileSystem fs, string path)
 {
     if (path.EndsWith(".obj"))
     {
         return(WavefrontObj.Load(fs, path));
     }
     else if (path.EndsWith(".mdf"))
     {
         return(MeshDefFile.Load(fs, path).mapBones());
     }
     else if (path.EndsWith(".3ds"))
     {
         return(load.Loader_3ds.Load(fs, path));
     }
     else
     {
         throw new UserException(path + " does not use a known fileformat");
     }
 }
Пример #13
0
        /// <summary>
        /// Converts the file.
        /// </summary>
        /// <param name="path">The path.</param>
        private static void ConvertFile(string path)
        {
            Console.WriteLine("Parsing file: " + path + "...");

            DateTime startTime = DateTime.Now;

            QuakeMap     map = QuakeMap.ParseFile(path);
            WavefrontObj obj = map.ToObj();

            obj.FilterTextures(textureFilter);

            string fileNameBase = Path.Combine(Path.GetDirectoryName(path) !, Path.GetFileNameWithoutExtension(path));

            obj.SaveFile(fileNameBase + ".obj", scale);
            obj.SaveMaterialFile(fileNameBase + ".mtl", new TextureFinder(new TextureSettings()));

            DateTime endTime = DateTime.Now;

            Console.WriteLine("Finished in: " + (endTime - startTime).TotalMilliseconds + "ms.");
        }
Пример #14
0
    protected void OnZastpActionActivated(object sender, EventArgs e)
    {
        FileChooserDialog fc = new FileChooserDialog("Wybierz model", this, FileChooserAction.Open,
                                                     "Anuluj", ResponseType.Cancel, "Otwórz", ResponseType.Ok);

        fc.Filter = new FileFilter();
        fc.Filter.AddPattern("*.obj");

        if (fc.Run() == (int)ResponseType.Ok)
        {
            var model = new WavefrontObj(fc.Filename);
            model.Obroc(new Vector3D(Math.PI * 100, 0, 0));
            model.Renderowanie = scena.Swiat[comboboxModele.Active].Renderowanie;

            int tmp = comboboxModele.Active;
            scena.Swiat[comboboxModele.Active] = model;
            comboboxModele.AppendText(model.Nazwa);
            comboboxModele.Active = tmp;
        }

        fc.Destroy();
    }
Пример #15
0
        private static void ProcessBlocks(string outputPath, Dictionary <CoordinateInt, Block> rawBlocks)
        {
            /* We need to identify any bricks that are hidden from vision. */
            Console.WriteLine("Identifying invisible blocks.");
            HashSet <CoordinateInt> invisibleBricks = new HashSet <CoordinateInt>();

            foreach (KeyValuePair <CoordinateInt, Block> pair in rawBlocks)
            {
                if (IsInvisible(pair.Key, rawBlocks))
                {
                    invisibleBricks.Add(pair.Key);
                }
            }
            foreach (CoordinateInt coord in invisibleBricks)
            {
                rawBlocks.Remove(coord);
            }
            Console.WriteLine("Identified {0} invisible bricks.", invisibleBricks.Count);

            /* Before we can start expanding cubes, we need to organize by block type. */
            Console.WriteLine("Extracting largest volumes.");
            Dictionary <Block, List <Volume> > volumizedWorld = new Dictionary <Block, List <Volume> >();

            foreach (KeyValuePair <Block, HashSet <CoordinateInt> > pair in OrganizeRawBlocks(rawBlocks))
            {
                volumizedWorld.Add(pair.Key, new List <Volume>(new LargestVolumeExtractor(pair.Value, invisibleBricks)));
            }

            /* Scan for interior faces that we can remove. */
            HiddenFaces.totalHiddenFaces = 0;
            Console.WriteLine("Identifying interior faces.");
            Dictionary <Block, List <FacedVolume> > facedVolumizedWorld = HiddenFaces.DetectHiddenFaces(volumizedWorld, rawBlocks);

            Console.WriteLine("Identified {0} interior faces.", HiddenFaces.totalHiddenFaces);

            /* Storage for the actual 3D geometry. */
            List <CoordinateDecimal> vertices = new List <CoordinateDecimal>();
            Dictionary <string, List <FaceVertices> >           collisionBoxes = new Dictionary <string, List <FaceVertices> >();
            Dictionary <BlockFaceTexture, List <TexturedFace> > texturedFaces  = new Dictionary <BlockFaceTexture, List <TexturedFace> >();
            TextureCoordinateDictionary textureCoordinates = new TextureCoordinateDictionary();

            /* Build the textured faces from the volumes. */
            foreach (KeyValuePair <Block, List <FacedVolume> > pair in facedVolumizedWorld)
            {
                List <FacedVolume> volumes = pair.Value;
                for (int idx = 0; idx < volumes.Count; idx++)
                {
                    FacedVolume facedVolume = volumes[idx];
                    Iterators.FacesInVolume(vertices.Count, facedVolume.excludedFaces, (Face face, FaceVertices faceVertices) =>
                                            { AppendTexturedFaces(texturedFaces, textureCoordinates, pair.Key, facedVolume.volume, face, faceVertices); });
                    Iterators.VerticesInVolume(volumes[idx].volume,
                                               (CoordinateDecimal a) => { vertices.Add(a); });
                }
            }
            Console.WriteLine(textureCoordinates.mappingList.Count + " unique texture coordinates.");

            /* Delete duplicate vertices before adding collision UBXs because the UBX vertices will all be unique. */
            Console.WriteLine("Detecting duplicate vertices.");
            int duplicatesRemoved = DuplicateVertices.DetectAndErase(vertices, texturedFaces);

            Console.WriteLine(duplicatesRemoved + " duplicate vertices removed.");

            Console.WriteLine("Generate UBX collision volumes.");
            foreach (KeyValuePair <Block, List <FacedVolume> > pair in facedVolumizedWorld)
            {
                List <FacedVolume> volumes = pair.Value;
                for (int idx = 0; idx < volumes.Count; idx++)
                    #warning Potential for collision meshes to be far from visual mesh!
                {
                    MakeCollisionUBX("UBX_" + pair.Key.ToString() + string.Format("_{0:00}", idx), volumes[idx].volume, vertices, collisionBoxes);
                }
            }

            /* Export the geometry to Wavefront's OBJ format. */
            WavefrontObj objFile = new WavefrontObj(vertices, collisionBoxes, texturedFaces, textureCoordinates, facedVolumizedWorld);

            /* Save the OBJ file to the specified destination. */
            File.WriteAllText(outputPath, objFile.ToString());
        }
Пример #16
0
        private async void button_ExportSelection_Click(object sender, EventArgs e)
        {
            if (scene == null ||
                scene.Triangles < 1)
            {
                return;
            }

            if (selectedPoints.GetCount() == 0)
            {
                MessageBox.Show("No points on the source mesh are selected.");
                return;
            }

            SaveFileDialog sfd = new SaveFileDialog();

            sfd.Title        = "Save file";
            sfd.Filter       = "PLY Files|*.ply" + "|OBJ Files|*.obj";
            sfd.AddExtension = true;
            sfd.FileName     = "";
            if (sfd.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            string       ext       = Path.GetExtension(sfd.FileName);
            WavefrontObj objWriter = null;

            switch (ext)
            {
            case ".ply":
                StanfordPly plyWriter = new StanfordPly();
                plyWriter.TextFormat    = true;
                plyWriter.NativeNewLine = true;
                plyWriter.Orientation   = checkOrientation.Checked;
                plyWriter.DoColors      = false;

                handler = new WriteBrepHandler(plyWriter.WriteBrepSelection);

                break;

            case ".obj":
                objWriter = new WavefrontObj();
                handler   = new WriteBrepHandler(objWriter.WriteBrepSelection);
                break;

            default:
                break;
            }


            // lambda will be run on the UI thread
            var progress = new Progress <string>(ReportProgress);

            label_percentageReport.Text = "Saving 0%";

            // writing the file is run on the thread pool

            StreamWriter writer = null;

            stopButton.Visible = true;

            // get prepared triangle and vertex pointers
            List <int> trianglePointers = null;
            List <int> vertexPointers   = null;

            try
            {
                cts    = new CancellationTokenSource();
                writer = new StreamWriter(new FileStream(sfd.FileName, FileMode.Create));
                await Task.Run(() => handler( writer, scene, selectedPoints, progress, cts.Token, out trianglePointers, out vertexPointers ));
            }
            catch (OperationCanceledException)
            {
            }
            finally
            {
                RewriteReportLabel();
                cts = null;

                if (writer != null)
                {
                    writer.Close();
                }
            }

            // support: Export batch
            String name = null;

            if (sender is ToolStripMenuItem)
            {
                name = (sender as ToolStripMenuItem).Name;
            }
            if (name == "exportBatch")
            {
                cts = new CancellationTokenSource();
                ExportBatch eb   = new ExportBatch(vertexPointers, trianglePointers, Path.GetDirectoryName(sfd.FileName), ext);
                Task        task = new Task(() => eb.ProcessDirectory(progress, cts.Token, () => RewriteReportLabel()));
                task.RunSynchronously();
                stopButton.Visible = true;
            }
        }
Пример #17
0
        public static long TestScene(IRayScene sc, string[] names)
        {
            Debug.Assert(sc != null);

            Vector3  center = Vector3.Zero; // center of the mesh
            Vector3d dir    = new Vector3d(0.1, -0.3, 0.9);

            dir.Normalize();           // normalized viewing vector of the camera
            float  diameter = 2.0f;    // default scene diameter
            double FoVy     = 60.0;    // Field of View in degrees
            int    faces    = 0;

            // CSG scene:
            CSGInnerNode root = new CSGInnerNode(SetOperation.Union);

            // OBJ file to read:
            if (names.Length == 0 ||
                names[0].Length == 0)
            {
                names = new string[] { "teapot.obj" }
            }
            ;

            string[] paths = Scenes.SmartFindFiles(names);
            if (paths[0] == null || paths[0].Length == 0)
            {
                for (int i = 0; i < names.Length; i++)
                {
                    if (names[i].Length > 0)
                    {
                        names[i] += ".gz";
                    }
                }
                paths = Scenes.SmartFindFiles(names);
            }
            if (paths[0] == null || paths[0].Length == 0)
            {
                root.InsertChild(new Sphere(), Matrix4d.Identity);
            }
            else
            {
                // B-rep scene construction:
                WavefrontObj objReader = new WavefrontObj();
                objReader.MirrorConversion = false;
                SceneBrep brep = new SceneBrep();
                faces = objReader.ReadBrep(paths[0], brep);
                brep.BuildCornerTable();
                diameter = brep.GetDiameter(out center);
                TriangleMesh m = new FastTriangleMesh(brep);
                root.InsertChild(m, Matrix4d.Identity);
            }

            root.SetAttribute(PropertyName.REFLECTANCE_MODEL, new PhongModel());
            root.SetAttribute(PropertyName.MATERIAL, new PhongMaterial(new double[] { 0.5, 0.5, 0.5 }, 0.2, 0.5, 0.4, 12));
            root.SetAttribute(PropertyName.COLOR, new double[] { 1.0, 0.6, 0.0 });
            sc.Intersectable = root;

            // Background color:
            sc.BackgroundColor = new double[] { 0.0, 0.05, 0.07 };

            // Camera:
            double   dist = (0.6 * diameter) / Math.Tan(MathHelper.DegreesToRadians((float)(0.5 * FoVy)));
            Vector3d cam  = (Vector3d)center - dist * dir;

            sc.Camera = new StaticCamera(cam, dir, FoVy);

            // Light sources:
            sc.Sources = new LinkedList <ILightSource>();
            sc.Sources.Add(new AmbientLightSource(0.8));
            sc.Sources.Add(new PointLightSource(new Vector3d(-20.0, 12.0, -12.0), 1.0));

            return(faces);
        }
    }