示例#1
0
            protected void LoadVectorsOrNormals(Dictionary <string, VtkDataAttribute> attributes, int size)
            {
                VectorsOrNormals data;

                if (_curToken == VtkToken.Vectors)
                {
                    data = new Vectors();
                }
                else
                {
                    data = new Normals();
                }
                data.Name             = GetStringPart();
                attributes[data.Name] = data;

                var dtType = GetDataType();

                Debug.WriteLine(string.Format("{2} name: {0}, dataType: {1}", data.Name, dtType, _curToken));
                data.Values = new List <Vector3>(size);
                for (int i = 0; i < size; i++)
                {
                    var v = new Vector3();
                    v.X = GetDataAsFloat(dtType);
                    v.Y = GetDataAsFloat(dtType);
                    v.Z = GetDataAsFloat(dtType);
                    data.Values.Add(v);
                }
            }
示例#2
0
        /// <summary>
        /// Generates the vertices, normals and indices and creates them for the OpenGL.
        /// This method has to be called once before drawing.
        /// </summary>
        /// <param name="gl"></param>
        public void GenerateGeometry(OpenGL gl, OGLModelUsage usage)
        {
            GL     = gl;
            _usage = usage;

            // Create the data buffers.
            var buffers = OGLBufferId.CreateBufferIds(gl, 3);

            IndexBuffer  = new IBO(buffers[0]);
            NormalBuffer = new VBO(buffers[1]);
            VertexBuffer = new VBO(buffers[2]);

            if (AutoCalculateNormals)
            {
                CalculateNormals();
            }

            var vertData = Vertices.SelectMany(v => v.to_array()).ToArray();

            VertexBuffer.BindBuffer(gl);                                                         // GL.BindBuffer(OpenGL.GL_ARRAY_BUFFER, VertexBuffer.Buffer.Value);
            VertexBuffer.SetBufferData(gl, OGLBufferDataTarget.ArrayBuffer, vertData, usage, 3); // GL.BufferData(OpenGL.GL_ARRAY_BUFFER, vertData, (uint)usage);

            var normData = Normals.SelectMany(v => v.to_array()).ToArray();

            NormalBuffer.BindBuffer(gl);                                                         //GL.BindBuffer(OpenGL.GL_ARRAY_BUFFER, NormalBuffer.Buffer.Value);
            NormalBuffer.SetBufferData(gl, OGLBufferDataTarget.ArrayBuffer, normData, usage, 3); // GL.BufferData(OpenGL.GL_ARRAY_BUFFER, normData, (uint)usage);

            IndexBuffer.BindBuffer(gl);                                                          // GL.BindBuffer(OpenGL.GL_ARRAY_BUFFER, IndexBuffer.Buffer.Value);
            IndexBuffer.SetBufferData(gl, OGLBufferDataTarget.ArrayBuffer, Indices, usage, 1);   // GL.BufferData(OpenGL.GL_ARRAY_BUFFER, Indices, (uint)usage);

            if (new OGLModelUsage[] { OGLModelUsage.StaticCopy, OGLModelUsage.StaticDraw, OGLModelUsage.StaticRead }.Contains(usage))
            {
                ClearStaticData();
            }
        }
示例#3
0
 public ObjFaceBuilder Clear()
 {
     Vertices.Clear();
     Normals.Clear();
     UVs.Clear();
     return(this);
 }
示例#4
0
        public void ReportGeometryTo(StringBuilder sb)
        {
            int i   = 0;
            var pEn = Positions.GetEnumerator();
            var nEn = Normals.GetEnumerator();

            while (pEn.MoveNext() && nEn.MoveNext())
            {
                var p = pEn.Current;
                var n = nEn.Current;
                sb.AppendFormat("{0} pos: {1} nrm:{2}\r\n", i++, p, n);
            }

            i = 0;
            sb.AppendLine("Triangles:");
            foreach (var item in TriangleIndices)
            {
                sb.AppendFormat("{0}, ", item);
                i++;
                if (i % 3 == 0)
                {
                    sb.AppendLine();
                }
            }
        }
        public void Parse(string[] lines)
        {
            foreach (var line in lines)
            {
                if (line == string.Empty)
                {
                    continue;
                }
                var splittedline = line.Split(new char[] { ' ' }, 2);
                switch (splittedline[0])
                {
                case "v":
                    Vertices.Add(StringToPoint(splittedline[1]));
                    break;

                case "vn":
                    Normals.Add(StringToVector(splittedline[1]));
                    break;

                case "g":
                    LastGroupAdded = splittedline[1];
                    Groups.Add(LastGroupAdded, new Group());
                    break;

                case "f":
                    Groups[LastGroupAdded].Add(
                        FanTriangulate(splittedline[1]));
                    break;

                default: IgnoredLines++; break;
                }
            }
        }
示例#6
0
 public void AddVertex(Vector3 pos, Vector3 normal, Vector2 texCoord)
 {
     Vertices.Add(pos);
     Normals.Add(normal);
     TexCoords.Add(texCoord);
     Indices.Add(Indices.Count);
 }
示例#7
0
        public void WriteToOBJ(TextWriter writer, int lodNumber, int firstVertexNumber, int firstNormalNumber, int firstCoordNumber,
                               Dictionary <string, int?> materialNames, Stream unknownData)
        {
            unknownData.Write(unknown);
            unknownData.WriteByte(unknown2);
            unknownData.WriteByte(unknown3);

            double scaleFactor = ConvertScale(Scale);

            writer.WriteLine($"g lod{lodNumber}/scale={scaleFactor}");

            writer.WriteLine("# vertices");
            Vertices.ForEach(vertex => vertex.WriteToOBJ(writer, scaleFactor));

            writer.WriteLine("# normals");
            Normals.ForEach(normal => normal.WriteToOBJ(writer));

            List <UVCoordinate> coords = GetAllUVCoords();

            writer.WriteLine("# UV coords");
            coords.ForEach(coord => coord.WriteToOBJ(writer));

            writer.WriteLine("# triangles");
            Triangles.ForEach(polygon => polygon.WriteToOBJ(writer, false, Vertices, Normals, firstVertexNumber, firstNormalNumber, materialNames));

            writer.WriteLine("# quads");
            Quads.ForEach(polygon => polygon.WriteToOBJ(writer, true, Vertices, Normals, firstVertexNumber, firstNormalNumber, materialNames));

            writer.WriteLine("# UV triangles");
            UVTriangles.ForEach(polygon => polygon.WriteToOBJ(writer, false, Vertices, Normals, firstVertexNumber, firstNormalNumber, coords, firstCoordNumber, materialNames));

            writer.WriteLine("# UV quads");
            UVQuads.ForEach(polygon => polygon.WriteToOBJ(writer, true, Vertices, Normals, firstVertexNumber, firstNormalNumber, coords, firstCoordNumber, materialNames));
        }
示例#8
0
 /// <summary>
 /// Clears all data in this mesh.
 /// </summary>
 public void Clear()
 {
     Vertices.Clear();
     Normals.Clear();
     UVs.Clear();
     Triangles.Clear();
 }
        public void NoLod()
        {
            var chunk = new Chunk(new[]
            {
                new V3d(0, 0, 0),
                new V3d(1, 0, 0),
                new V3d(1, 1, 0),
                new V3d(0, 1, 0)
            });

            var config = ImportConfig.Default
                         .WithInMemoryStore()
                         .WithRandomKey()
                         .WithCreateOctreeLod(false)
            ;
            var cloud = PointCloud.Chunks(chunk, config);

            Assert.IsTrue(cloud.HasNormals == false);
            Assert.IsTrue(cloud.HasLodNormals == false);

            config = config
                     .WithRandomKey()
                     .WithEstimateNormals(ps => Normals.EstimateNormals((V3d[])ps, 5))
            ;
            var cloud2 = cloud.GenerateNormals(config);

            Assert.IsTrue(cloud2.HasNormals == true);
            Assert.IsTrue(cloud2.Root.Value.Normals.Value.All(n => n == V3f.OOI));
            Assert.IsTrue(cloud2.HasLodNormals == false);
        }
示例#10
0
        public void Write(AssetWriter writer)
        {
            Vertices.Write(writer);
            UV.Write(writer);
            if (HasBindPoses(writer.Version))
            {
                BindPoses.Write(writer);
            }

            Normals.Write(writer);
            Tangents.Write(writer);
            Weights.Write(writer);
            NormalSigns.Write(writer);
            TangentSigns.Write(writer);
            if (HasFloatColors(writer.Version))
            {
                FloatColors.Write(writer);
            }

            BoneIndices.Write(writer);
            Triangles.Write(writer);
            if (HasColors(writer.Version))
            {
                Colors.Write(writer);
            }
            if (HasUVInfo(writer.Version))
            {
                writer.Write(UVInfo);
            }
        }
示例#11
0
        public YAMLNode ExportYAML(IExportContainer container)
        {
            YAMLMappingNode node = new YAMLMappingNode();

            node.Add(VerticesName, Vertices.ExportYAML(container));
            node.Add(UVName, UV.ExportYAML(container));
            if (HasBindPoses(container.ExportVersion))
            {
                node.Add(BindPosesName, BindPoses.ExportYAML(container));
            }

            node.Add(NormalsName, Normals.ExportYAML(container));
            node.Add(TangentsName, Tangents.ExportYAML(container));
            node.Add(WeightsName, Weights.ExportYAML(container));
            node.Add(NormalSignsName, NormalSigns.ExportYAML(container));
            node.Add(TangentSignsName, TangentSigns.ExportYAML(container));
            if (HasFloatColors(container.ExportVersion))
            {
                node.Add(FloatColorsName, FloatColors.ExportYAML(container));
            }

            node.Add(BoneIndicesName, BoneIndices.ExportYAML(container));
            node.Add(TrianglesName, Triangles.ExportYAML(container));
            if (HasColors(container.ExportVersion))
            {
                node.Add(ColorsName, Colors.ExportYAML(container));
            }
            if (HasUVInfo(container.ExportVersion))
            {
                node.Add(UVInfoName, UVInfo);
            }
            return(node);
        }
示例#12
0
 public ObjFaceBuilder Vertex(int v, int?n = null, int?t = null)
 {
     Vertices.Add(v);
     Normals.Add(n ?? -1);
     UVs.Add(t ?? -1);
     return(this);
 }
示例#13
0
 /// <summary>
 /// Clear Mesh
 /// </summary>
 public void Clear()
 {
     Positions.Clear();
     Normals.Clear();
     UVs.Clear();
     Indices.Clear();
 }
示例#14
0
        public void Read(AssetReader reader)
        {
            Vertices.Read(reader);
            UV.Read(reader);
            if (IsReadBindPoses(reader.Version))
            {
                BindPoses.Read(reader);
            }
            Normals.Read(reader);
            Tangents.Read(reader);
            Weight.Read(reader);
            NormalSigns.Read(reader);
            TangentSigns.Read(reader);
            if (IsReadFloatColors(reader.Version))
            {
                FloatColors.Read(reader);
            }

            BoneIndices.Read(reader);
            Triangles.Read(reader);

            if (IsReadColors(reader.Version))
            {
                Colors.Read(reader);
            }
            if (IsReadUVInfo(reader.Version))
            {
                UVInfo = reader.ReadUInt32();
            }
        }
示例#15
0
 public void CreateDefaultNormals()
 {
     while (Normals.Count < Vertices.Count)
     {
         Normals.Add(new Vector3(0, 0, 1));
     }
 }
示例#16
0
        private void CreateRenderTargets(int width, int height)
        {
            Colors?.Dispose();
            Albedo?.Dispose();
            Normals?.Dispose();
            Depth?.Dispose();

#if OPENGL
            Colors  = new RenderTarget2D(GraphicsDevice, width, height, false, SurfaceFormat.HalfVector4, DepthFormat.Depth24Stencil8);
            Albedo  = new RenderTarget2D(GraphicsDevice, width, height, false, SurfaceFormat.HalfVector4, DepthFormat.Depth24Stencil8);
            Normals = new RenderTarget2D(GraphicsDevice, width, height, false, SurfaceFormat.HalfVector4, DepthFormat.Depth24Stencil8);
            Depth   = new RenderTarget2D(GraphicsDevice, width, height, false, SurfaceFormat.Vector2, DepthFormat.Depth24Stencil8);
#else
            Colors  = new RenderTarget2D(GraphicsDevice, width, height, false, SurfaceFormat.Rgba64, DepthFormat.Depth24Stencil8);
            Albedo  = new RenderTarget2D(GraphicsDevice, width, height, false, SurfaceFormat.Rgba64, DepthFormat.Depth24Stencil8);
            Normals = new RenderTarget2D(GraphicsDevice, width, height, false, SurfaceFormat.Rgba64, DepthFormat.Depth24Stencil8);
            Depth   = new RenderTarget2D(GraphicsDevice, width, height, false, SurfaceFormat.Vector2, DepthFormat.Depth24Stencil8);
#endif
            _bufferTextureSize = new Vector2(width, height);
            _gBufferTargets    = new[] {
                new RenderTargetBinding(Colors),
                new RenderTargetBinding(Normals),
                new RenderTargetBinding(Depth),
                new RenderTargetBinding(Albedo)
            };

            _lightMap?.Dispose();
            _lightMap = new RenderTarget2D(GraphicsDevice, width, height, false, SurfaceFormat.Color, DepthFormat.Depth24Stencil8);
        }
示例#17
0
        public string ToJson()
        {
            // I did think of using a JSON serialiser,
            // either one of these two provided by the
            // .NET framework or one of the other libraries:
            // System.Runtime.Serialization.Json.DataContractJsonSerializer
            // System.Web.Script.Serialization.JavaScriptSerializer
            // However, reading this comparison and alternative
            // implementation, I decided to just write the couple
            // of lines myself.
            // http://procbits.com/2011/08/11/fridaythe13th-the-best-json-parser-for-silverlight-and-net

            string s = string.Format
                           ("\n \"FacetCount\":{0},"
                           + "\n \"VertexCount\":{1},"
                           + "\n \"VertexCoords\":[{2}],"
                           + "\n \"VertexIndices\":[{3}],"
                           + "\n \"Normals\":[{4}],"
                           + "\n \"NormalIndices\":[{5}],"
                           + "\n \"Center\":[{6}],"
                           + "\n \"Color\":[{7}],"
                           + "\n \"Id\":\"{8}\"",
                           FacetCount,
                           VertexCount,
                           string.Join(",", VertexCoords.Select <int, string>(i => (_export_factor * i).ToString("0.#")).ToArray()),
                           string.Join(",", VertexIndices.Select <int, string>(i => i.ToString()).ToArray()),
                           string.Join(",", Normals.Select <double, string>(a => a.ToString("0.####")).ToArray()),
                           string.Join(",", NormalIndices.Select <int, string>(i => i.ToString())),
                           string.Join(",", Center.Select <int, string>(i => (_export_factor * i).ToString("0.#"))),
                           Color,
                           Id);

            return("\n{" + s + "\n}");
        }
示例#18
0
        } = 3;                                 // по Z

        /// <summary>
        /// Добавляет коробку с заданными гранями, выровненными по заданным осям.
        /// </summary>
        /// <param name="c">Точка центра куба.</param>
        /// <param name="Length">Длина коробки вдоль оси X.</param>
        /// <param name="Width">Длина коробки вдоль оси Y.</param>
        /// <param name="Height">Длина коробки вдоль оси Z.</param>

        public override void Update()
        {
            //Очистка
            Positions.Clear();
            Indices.Clear();
            Normals.Clear();

            var c = new Vector3(Length, Width, Height) / 2;

            AddCubeFace(c, Vector3.UnitX, Vector3.UnitZ, Length, Width, Height);
            AddCubeFace(c, -Vector3.UnitX, Vector3.UnitZ, Length, Width, Height);
            AddCubeFace(c, -Vector3.UnitY, Vector3.UnitZ, Width, Length, Height);
            AddCubeFace(c, Vector3.UnitY, Vector3.UnitZ, Width, Length, Height);
            AddCubeFace(c, Vector3.UnitZ, Vector3.UnitY, Height, Length, Width);
            AddCubeFace(c, -Vector3.UnitZ, Vector3.UnitY, Height, Length, Width);

            // добавление ребер
            AddEdge(0, 1);
            AddEdge(1, 2);
            AddEdge(2, 3);
            AddEdge(3, 0);

            AddEdge(4, 5);
            AddEdge(5, 6);
            AddEdge(6, 7);
            AddEdge(7, 4);

            AddEdge(0, 5);
            AddEdge(1, 4);
            AddEdge(2, 7);
            AddEdge(3, 6);
        }
示例#19
0
            public void AddBlendShapesToMesh(Mesh mesh)
            {
                Dictionary <string, BlendShape> map = new Dictionary <string, BlendShape>();

                foreach (var x in BlendShapes)
                {
                    BlendShape bs = null;
                    if (!map.TryGetValue(x.Name, out bs))
                    {
                        bs             = new BlendShape();
                        bs.Positions   = Positions.ToArray();
                        bs.Normals     = Normals.ToArray();
                        bs.Tangents    = Tangents.Select(y => (Vector3)y).ToArray();
                        bs.Name        = x.Name;
                        bs.FrameWeight = x.FrameWeight;
                        map.Add(x.Name, bs);
                    }

                    var j = x.VertexOffset;
                    for (int i = 0; i < x.Positions.Length; ++i, ++j)
                    {
                        bs.Positions[j] = x.Positions[i];
                        bs.Normals[j]   = x.Normals[i];
                        bs.Tangents[j]  = x.Tangents[i];
                    }
                }

                foreach (var kv in map)
                {
                    //Debug.LogFormat("AddBlendShapeFrame: {0}", kv.Key);
                    mesh.AddBlendShapeFrame(kv.Key, kv.Value.FrameWeight,
                                            kv.Value.Positions, kv.Value.Normals, kv.Value.Tangents);
                }
            }
示例#20
0
 public virtual void Clear()
 {
     Vertices.Clear();
     Normals.Clear();
     Colors.Clear();
     Lighting.Clear();
     Indexes.Clear();
 }
示例#21
0
 /// <summary>
 /// Get normals for this object
 /// </summary>
 /// <returns>normals for object</returns>
 public Vector3[] GetNormals()
 {
     if (_recalculateNormals)
     {
         CalculateNormals();
     }
     return(Normals.ToArray());
 }
示例#22
0
        public void ResetCurrent()
        {
            CurrentPosition = Normals.GetEnumerator();

            CurrentPosition.MoveNext();

            Current = CurrentPosition.Current;
        }
示例#23
0
 public void Clear()
 {
     Vertices.Clear();
     UVs.Clear();
     Indices.Clear();
     Normals.Clear();
     Colours.Clear();
 }
示例#24
0
        private void ReadNormal(string[] items)
        {
            var x = double.Parse(items[1]);
            var y = double.Parse(items[2]);
            var z = double.Parse(items[3]);

            Normals.Add(Helper.CreatePoint(x, y, z));
        }
示例#25
0
        /// <summary>
        /// Add OBJ model
        /// </summary>
        /// <param name="Path"></param>
        /// <returns></returns>
        public Mesh AddOBJ(string Path)
        {
            FileStream fileStream = new FileStream(Path, FileMode.Open);

            using (StreamReader reader = new StreamReader(fileStream))
            {
                string line;
                Mesh   tmp = new Mesh();

                while ((line = reader.ReadLine()) != null)
                {
                    string[] d = line.Split(" ");

                    //Vertex
                    if (d.Length == 4 && d[0].Equals("v"))
                    {
                        tmp.Positions.Add(new Vector3(float.Parse(d[1], NumberStyles.Any, CultureInfo.InvariantCulture), float.Parse(d[2], NumberStyles.Any, CultureInfo.InvariantCulture), float.Parse(d[3], NumberStyles.Any, CultureInfo.InvariantCulture)));
                    }
                    //UV
                    if (d.Length == 3 && d[0].Equals("vt"))
                    {
                        tmp.UVs.Add(new Vector2(float.Parse(d[1], NumberStyles.Any, CultureInfo.InvariantCulture), float.Parse(d[2], NumberStyles.Any, CultureInfo.InvariantCulture)));
                    }
                    //Normal
                    if (d.Length == 4 && d[0].Equals("vn"))
                    {
                        tmp.Normals.Add(new Vector3(float.Parse(d[1], NumberStyles.Any, CultureInfo.InvariantCulture), float.Parse(d[2], NumberStyles.Any, CultureInfo.InvariantCulture), float.Parse(d[3], NumberStyles.Any, CultureInfo.InvariantCulture)));
                    }
                    //Face
                    if (d.Length == 4 && d[0].Equals("f"))
                    {
                        string[] tri1 = d[1].Split("/");
                        string[] tri2 = d[2].Split("/");
                        string[] tri3 = d[3].Split("/");

                        Positions.Add(tmp.Positions[int.Parse(tri1[0]) - 1]);
                        Positions.Add(tmp.Positions[int.Parse(tri2[0]) - 1]);
                        Positions.Add(tmp.Positions[int.Parse(tri3[0]) - 1]);

                        UVs.Add(tmp.UVs[int.Parse(tri1[1]) - 1]);
                        UVs.Add(tmp.UVs[int.Parse(tri2[1]) - 1]);
                        UVs.Add(tmp.UVs[int.Parse(tri3[1]) - 1]);

                        Normals.Add(tmp.Normals[int.Parse(tri1[2]) - 1]);
                        Normals.Add(tmp.Normals[int.Parse(tri2[2]) - 1]);
                        Normals.Add(tmp.Normals[int.Parse(tri3[2]) - 1]);

                        for (int i = 0; i < 3; i++)
                        {
                            Indices.Add(Indices.Count);
                        }
                    }
                }
            }

            return(this);
        }
示例#26
0
 public Primitive(int vtxCount)
 {
     VertexCount = vtxCount;
     Matrices.AddRange(new int[vtxCount]);
     Positions.AddRange(new int[vtxCount]);
     Normals.AddRange(new int[vtxCount]);
     Colors.AddRange(new int[vtxCount]);
     TexCoords.AddRange(new int[vtxCount]);
 }
示例#27
0
        public string GetMetrics()
        {
            StringBuilder builder = new StringBuilder();

            builder.Append($"Name = {Name}, ");
            builder.Append($"Point Count = {Points.Count:N0}, ");
            builder.Append($"Non-Zero Normals = {Normals.Count(n => n.X != 0.0f && n.Y != 0.0f && n.Z != 0.0f):N0}");
            return(builder.ToString());
        }
示例#28
0
 public void AddVtx(Primitive src, int vtxIdx)
 {
     VertexCount++;
     Matrices.Add(src.Matrices[vtxIdx]);
     Positions.Add(src.Positions[vtxIdx]);
     Normals.Add(src.Normals[vtxIdx]);
     Colors.Add(src.Colors[vtxIdx]);
     TexCoords.Add(src.TexCoords[vtxIdx]);
 }
示例#29
0
        public ObjFileParser()
        {
            // Dummies to get 1-indexed arrays.
            Vertices.Add(Tuple.Point(0, 0, 0));
            Normals.Add(Tuple.Vector(0, 0, 0));

            // Add the default group
            _groups.Add("", new Group());
        }
示例#30
0
 public void Dispose()
 {
     Vertexes.Dispose();
     FaceIndexes.Dispose();
     TriangleOrder.Dispose();
     Normals.Dispose();
     Tangents.Dispose();
     Uvs.Dispose();
 }