public void CreateGroundPlane(float minValue, float size, float uvScale) { VertexElement[] vElements = new VertexElement[] { new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0), new VertexElement(0, 12, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0), new VertexElement(0, 20, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Normal, 0), new VertexElement(0, 32, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.Tangent, 0), VertexElement.VertexDeclarationEnd }; model = new Mesh(2, 4, MeshFlags.Managed | MeshFlags.Use32Bit, vElements, device); Vertex[] vertexList = new Vertex[4]; // Initialize the values for the 4 vertexes. vertexList[0].Position = new Vector3(-size, minValue, -size); vertexList[0].Normal = new Vector3(0, 1.0f, 0); vertexList[0].TexCoord = new Vector2(0, 0); vertexList[1].Position = new Vector3(-size, minValue, size); vertexList[1].Normal = new Vector3(0, 1.0f, 0); vertexList[1].TexCoord = new Vector2(0, uvScale); vertexList[2].Position = new Vector3(size, minValue, -size); vertexList[2].Normal = new Vector3(0, 1.0f, 0); vertexList[2].TexCoord = new Vector2(uvScale, 0); vertexList[3].Position = new Vector3(size, minValue, size); vertexList[3].Normal = new Vector3(0, 1.0f, 0); vertexList[3].TexCoord = new Vector2(uvScale, uvScale); int[] indexList = { 0, 3, 2, 1, 3, 0 }; model.SetIndexBufferData(indexList, LockFlags.None); model.SetVertexBufferData(vertexList, LockFlags.None); TangentBuilder.CalculateTangents(model); }
static WaterVertex() { elements = new VertexElement[2]; elements[0] = new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position); elements[1] = new VertexElement(elements[0].Size, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0); }
public void VertexElementPosition3D() { var element = new VertexElement(VertexElementType.Position3D); Assert.AreEqual(VertexElementType.Position3D, element.ElementType); Assert.AreEqual(3, element.ComponentCount); Assert.AreEqual(12, element.Size); }
internal static int GetVertexStride(VertexElement[] elements) { int num2 = 0; for (int i = 0; i < elements.Length; i++) num2 += elements[i].Format.SizeInBytes(); return num2; }
public GroundPlane(Device device, Effect effect) { VertexElement[] vElements = new VertexElement[] { new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0), new VertexElement(0, 12, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0), new VertexElement(0, 20, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Normal, 0), new VertexElement(0, 32, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.Tangent, 0), VertexElement.VertexDeclarationEnd }; this.device = device; objLoader = new ObjLoader(device); xLoader = new XLoader(device); model = new Mesh(1, 1, MeshFlags.Managed | MeshFlags.Use32Bit, vElements, device); min = max = 0; enabled = false; pathname = ""; uvScale = 1.0f; minValue = 0.0f; size = 10.0f; // Initialize the texture classes and set the shader variables. ambientTexture = new TextureClass(device, effect, "ambientMap", "useAmbientMap"); diffuseTexture = new TextureClass(device, effect, "diffuseMap", "useDiffuseMap"); emissiveTexture = new EmissiveClass(device, effect); specularTexture = new SpecularClass(device, effect, "specularMap", "useSpecularMap"); normalTexture = new NormalClass(device, effect, "normalMap", "useNormalMap"); CreateGroundPlane(minValue, size, uvScale); }
static TreeVertex() { elements = new VertexElement[4]; elements[0] = new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position); elements[1] = new VertexElement(elements[0].Size, VertexElementFormat.Vector3, VertexElementUsage.Normal); elements[2] = new VertexElement(elements[1].Offset + elements[1].Size, VertexElementFormat.Vector3, VertexElementUsage.TextureCoordinate, 0); elements[3] = new VertexElement(elements[2].Offset + elements[2].Size, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 1); }
static TerrainVertex() { elements = new VertexElement[3]; elements[0] = new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position); elements[1] = new VertexElement(elements[0].Size, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0); elements[2] = new VertexElement(elements[1].Size + elements[1].Offset, VertexElementFormat.Single, VertexElementUsage.TextureCoordinate, 1); }
internal static void Validate(int vertexStride, VertexElement[] elements) { if (vertexStride <= 0) { throw new ArgumentOutOfRangeException("vertexStride"); } if ((vertexStride & 3) != 0) { throw new ArgumentException("VertexElementOffsetNotMultipleFour"); } int[] numArray = new int[vertexStride]; for (int i = 0; i < vertexStride; i++) { numArray[i] = -1; } int totalOffset = 0; for (int j = 0; j < elements.Length; j++) { int offset = elements[j].AlignedByteOffset; if (offset == VertexElement.AppendAligned) { if (j == 0) { offset = 0; } else { offset = totalOffset + elements[j - 1].Format.SizeInBytes(); } } totalOffset = offset; int typeSize = elements[j].Format.SizeInBytes(); if ((offset < 0) || ((offset + typeSize) > vertexStride)) { throw new ArgumentException("VertexElementOutsideStride"); } if ((offset & 3) != 0) { throw new ArgumentException("VertexElementOffsetNotMultipleFour"); } for (int k = 0; k < j; k++) { if (elements[j].SemanticName == elements[k].SemanticName && elements[j].SemanticIndex == elements[k].SemanticIndex) { throw new ArgumentException("DuplicateVertexElement"); } } for (int m = offset; m < (offset + typeSize); m++) { if (numArray[m] >= 0) { throw new ArgumentException("VertexElementsOverlap"); } numArray[m] = j; } } }
public void SaveDataColor() { var element = new VertexElement(VertexElementType.TextureUV); using(var stream = new MemoryStream()) { var writer = new BinaryWriter(stream); element.SaveData(writer, Color.Red); Assert.AreEqual(stream.Length, 4); } }
public VertexDecl(Device device, VertexElement[] elements) { if (elements == null) return; if (elements[elements.Length - 1] != VertexElement.VertexDeclarationEnd) return; d3d9VertexDecl = new VertexDeclaration(device.RawDevice, elements); }
public void SaveDataPoint() { var element = new VertexElement(VertexElementType.TextureUV); using (var stream = new MemoryStream()) { var writer = new BinaryWriter(stream); element.SaveData(writer, Vector2D.UnitX); Assert.AreEqual(stream.Length, 8); } }
/// <summary> /// Method to load in a directx mesh. /// </summary> /// <param name="filename">Path of the model to load.</param> /// <returns></returns> public Mesh LoadModel(string filename) { Mesh mesh; VertexElement[] vElements = new VertexElement[] { new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0), new VertexElement(0, 12, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0), new VertexElement(0, 20, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Normal, 0), new VertexElement(0, 32, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.Tangent, 0), VertexElement.VertexDeclarationEnd }; // Load the mesh from file. mesh = Mesh.FromFile(filename, MeshFlags.Managed | MeshFlags.Use32Bit, device); // Clone the mesh. mesh = mesh.Clone(MeshFlags.Managed | MeshFlags.Use32Bit, vElements, device); // Generates a list of adjacent faces used for generating normals. int[] adjacency = new int[mesh.NumberFaces * 3]; mesh.GenerateAdjacency(0, adjacency); //mesh.ComputeTangentFrame(TangentOptions.GenerateInPlace | TangentOptions.CalculateNormals); mesh.ComputeNormals(adjacency); // Create the variables needed to convert the mesh to right handed coordinates. GraphicsStream gStream = mesh.LockVertexBuffer(LockFlags.None); List<Vertex> vertices = new List<Vertex>(); Vertex vertex; // Convert the mesh to right handed coordinates. for (int i = 0; i < mesh.NumberVertices; i++) { vertex = (Vertex)gStream.Read(typeof(Vertex)); vertex.Position.Z *= -1.0f; vertex.Normal = Vector3.TransformNormal(vertex.Normal, Matrix.Scaling(1.0f, 1.0f, -1.0f)); vertices.Add(vertex); } // Set the vertex buffer mesh.SetVertexBufferData(vertices.ToArray(), LockFlags.None); // Calculate the tangents TangentBuilder.CalculateTangents(mesh); return mesh; }
/// <summary> /// Dynamically creates a vertex declaration that fits the data contained by this /// vertex container. /// </summary> /// <returns>A fitting vertex declaration</returns> public VertexDeclaration CreateVertexDeclaration() { VertexElement[] elements = new VertexElement[_vertexChannels.Count]; short offset = 0; int index = 0; foreach (VertexChannel channel in _vertexChannels) { VertexElement element = channel.Description; element.Offset = offset; offset += (short)(channel.Source.Stride * sizeof(float)); elements[index++] = element; } return(new VertexDeclaration(elements)); }
public PosW_color(float _x, float _y, float _z, float _w, int _color) { x = _x; y = _y; z = _z; w = _w; color = _color; if (PosW_color.vertDecl == null) { VertexElement[] elements = new VertexElement[] { new VertexElement(0, 0, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.PositionTransformed, 0), new VertexElement(0, 16, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0), VertexElement.VertexDeclarationEnd, }; vertDecl = new VertexDeclaration(BRenderDevice.getDevice(), elements); } }
/// <summary> /// Creates a VertexDeclaration suitable for a full-screen quad /// </summary> /// <returns></returns> protected VertexDeclaration CreateQuadVertexDeclaration() { var declElements = new VertexElement[2]; declElements[0].Offset = 0; declElements[0].Stream = 0; declElements[0].UsageIndex = 0; declElements[0].VertexElementFormat = VertexElementFormat.Vector3; declElements[0].VertexElementMethod = VertexElementMethod.Default; declElements[0].VertexElementUsage = VertexElementUsage.Position; declElements[1].Offset = 12; declElements[1].Stream = 0; declElements[1].UsageIndex = 0; declElements[1].VertexElementFormat = VertexElementFormat.Vector2; declElements[1].VertexElementMethod = VertexElementMethod.Default; declElements[1].VertexElementUsage = VertexElementUsage.TextureCoordinate; return(new VertexDeclaration(_graphicsDevice, declElements)); }
/// <summary> /// Generate vertex declaration /// </summary> private static VertexElement[] GenerateVertexElements() { VertexElement[] decl = new VertexElement[] { // Construct new vertex declaration with tangent info // First the normal stuff (we should already have that) new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0), new VertexElement(12, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0), new VertexElement(20, VertexElementFormat.Vector3, VertexElementUsage.Normal, 0), // And now the tangent new VertexElement(32, VertexElementFormat.Vector3, VertexElementUsage.Tangent, 0), }; return(decl); }
public Pos_Color_uv0(float _x, float _y, float _z, float _u, float _v, int _color) { x = _x; y = _y; z = _z; u = _u; v = _v; color = _color; if (Pos_Color_uv0.vertDecl == null) { VertexElement[] elements = new VertexElement[] { new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0), new VertexElement(0, 12, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0), new VertexElement(0, 24, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0), VertexElement.VertexDeclarationEnd, }; vertDecl = new VertexDeclaration(BRenderDevice.getDevice(), elements); } }
/// <summary> /// Builds a vertex element list that can be used to construct a vertex declaration /// from a vertex structure that has the vertex element attributes applied to it /// </summary> /// <typeparam name="VertexType"> /// Vertex structure with vertex element attributes applied to it /// </typeparam> /// <returns> /// A vertex element list that can be used to create a new vertex declaration matching /// the provided vertex structure /// </returns> public static VertexElement[] BuildElementList <VertexType>() where VertexType : struct { FieldInfo[] fields = getFields <VertexType>(); int fieldOffset = 0; int elementCount = 0; // Set up an array for the vertex elements and fill it with the data we // gather directly from the vertex structure VertexElement[] elements = new VertexElement[fields.Length]; for (int index = 0; index < fields.Length; ++index) { // Find out whether this field is used by the vertex shader. If so, add // it to the elements list so it ends up in the vertex shader. VertexElementAttribute attribute = getVertexElementAttribute(fields[index]); if (attribute != null) { buildVertexElement(fields[index], attribute, ref elements[elementCount]); #if !(XBOX360 || WINDOWS_PHONE) fieldOffset = Marshal.OffsetOf(typeof(VertexType), fields[index].Name).ToInt32(); #endif elements[elementCount].Offset = (short)fieldOffset; ++elementCount; } #if XBOX360 fieldOffset += Marshal.SizeOf(fields[index].FieldType); #endif } // If there isn't a single vertex element, this type would be completely useless // as a vertex. Probably the user forgot to add the VertexElementAttribute. if (elementCount == 0) { throw new InvalidOperationException( "No fields had the VertexElementAttribute assigned to them." ); } Array.Resize(ref elements, elementCount); return(elements); }
public static void GetSubmeshVertexData(out Vector3[] points, VertexData vertexData) { // if (subMesh.operationType != RenderMode.TriangleList) // continue; points = null; for (ushort bindIdx = 0; bindIdx < vertexData.vertexDeclaration.ElementCount; ++bindIdx) { VertexElement element = vertexData.vertexDeclaration.GetElement(bindIdx); HardwareVertexBuffer vBuffer = vertexData.vertexBufferBinding.GetBuffer(bindIdx); if (element.Semantic != VertexElementSemantic.Position) { continue; } points = new Vector3[vertexData.vertexCount]; ReadBuffer(vBuffer, vertexData.vertexCount, element.Size, ref points); return; } Debug.Assert(points != null, "Unable to retrieve position vertex data"); }
public void drawNumberOfQuads(int n, int start) { if (n == start) { return; } if (this.m_pQuads == null || (int)this.m_pQuads.Length < 1) { return; } CCApplication texture2D = CCApplication.sharedApplication(); CCDirector.sharedDirector().getWinSize(); texture2D.basicEffect.Texture = this.Texture.getTexture2D(); texture2D.basicEffect.TextureEnabled = true; texture2D.GraphicsDevice.BlendState = BlendState.AlphaBlend; texture2D.basicEffect.VertexColorEnabled = true; List <VertexPositionColorTexture> vertexPositionColorTextures = new List <VertexPositionColorTexture>(); short[] numArray = new short[n * 6]; for (int i = start; i < start + n; i++) { ccV3F_C4B_T2F_Quad mPQuads = this.m_pQuads[i]; if (mPQuads != null) { vertexPositionColorTextures.AddRange(mPQuads.getVertices(ccDirectorProjection.kCCDirectorProjection3D).ToList <VertexPositionColorTexture>()); numArray[i * 6] = (short)(i * 4); numArray[i * 6 + 1] = (short)(i * 4 + 1); numArray[i * 6 + 2] = (short)(i * 4 + 2); numArray[i * 6 + 3] = (short)(i * 4 + 2); numArray[i * 6 + 4] = (short)(i * 4 + 1); numArray[i * 6 + 5] = (short)(i * 4 + 3); } } VertexElement[] vertexElement = new VertexElement[] { new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0), new VertexElement(12, VertexElementFormat.Vector3, VertexElementUsage.Color, 0), new VertexElement(24, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0) }; VertexDeclaration vertexDeclaration = new VertexDeclaration(vertexElement); foreach (EffectPass pass in texture2D.basicEffect.CurrentTechnique.Passes) { pass.Apply(); texture2D.GraphicsDevice.DrawUserIndexedPrimitives <VertexPositionColorTexture>(PrimitiveType.TriangleList, vertexPositionColorTextures.ToArray(), 0, vertexPositionColorTextures.Count, numArray, 0, vertexPositionColorTextures.Count / 2); } }
public void Encode(VertexElement element, Short4 value) { var dstVertex = _Vertex.Slice(element.Offset); if (element.VertexElementFormat == VertexElementFormat.Vector4) { var v4 = value.ToVector4(); System.Runtime.InteropServices.MemoryMarshal.Write(dstVertex, ref v4); return; } if (element.VertexElementFormat == VertexElementFormat.Short4) { System.Runtime.InteropServices.MemoryMarshal.Write(dstVertex, ref value); return; } throw new ArgumentException(nameof(element)); }
public void Encode(VertexElement element, XNAV3 value) { var dstVertex = _Vertex.Slice(element.Offset); if (element.VertexElementFormat == VertexElementFormat.Vector3) { System.Runtime.InteropServices.MemoryMarshal.Write(dstVertex, ref value); return; } if (element.VertexElementFormat == VertexElementFormat.Color) { var c = new Color(value); System.Runtime.InteropServices.MemoryMarshal.Write(dstVertex, ref c); return; } throw new ArgumentException(nameof(element)); }
private VertexData InitVertexBuffer(int numVerts) { VertexData vertexData = new VertexData(); vertexData.vertexCount = numVerts; vertexData.vertexStart = 0; // set up the vertex declaration int vDecOffset = 0; // Position vertexData.vertexDeclaration.AddElement(0, vDecOffset, VertexElementType.Float3, VertexElementSemantic.Position); vDecOffset += VertexElement.GetTypeSize(VertexElementType.Float3); // Normal vertexData.vertexDeclaration.AddElement(0, vDecOffset, VertexElementType.Float3, VertexElementSemantic.Normal); vDecOffset += VertexElement.GetTypeSize(VertexElementType.Float3); // Texture Coords vertexData.vertexDeclaration.AddElement(0, vDecOffset, VertexElementType.Float2, VertexElementSemantic.TexCoords, 0); vDecOffset += VertexElement.GetTypeSize(VertexElementType.Float2); // Vertex offset from base of plant vertexData.vertexDeclaration.AddElement(0, vDecOffset, VertexElementType.Float2, VertexElementSemantic.TexCoords, 1); vDecOffset += VertexElement.GetTypeSize(VertexElementType.Float2); // Wind Params vertexData.vertexDeclaration.AddElement(0, vDecOffset, VertexElementType.Float2, VertexElementSemantic.TexCoords, 2); vDecOffset += VertexElement.GetTypeSize(VertexElementType.Float2); // color vertexData.vertexDeclaration.AddElement(0, vDecOffset, VertexElementType.Color, VertexElementSemantic.Diffuse); vDecOffset += VertexElement.GetTypeSize(VertexElementType.Color); // create the hardware vertex buffer and set up the buffer binding HardwareVertexBuffer hvBuffer = HardwareBufferManager.Instance.CreateVertexBuffer( vertexData.vertexDeclaration.GetVertexSize(0), vertexData.vertexCount, BufferUsage.StaticWriteOnly, false); vertexData.vertexBufferBinding.SetBinding(0, hvBuffer); return(vertexData); }
public Pos_Normal_uv0(float _x, float _y, float _z, float _nx, float _ny, float _nz, float _u, float _v) { x = _x; y = _y; z = _z; nx = _nx; ny = _ny; nz = _nz; u = _u; v = _v; if (Pos_Normal_uv0.vertDecl == null) { VertexElement[] elements = new VertexElement[] { new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0), new VertexElement(0, 12, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Normal, 0), new VertexElement(0, 24, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0), new VertexElement(0, 32, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Tangent, 0), VertexElement.VertexDeclarationEnd, }; vertDecl = new VertexDeclaration(BRenderDevice.getDevice(), elements); } }
public PosW_uv0(float _x, float _y, float _z, float _w, float _u0, float _v0) { x = _x; y = _y; z = _z; w = _w; u = _u0; v = _v0; if (PosW_uv0.vertDecl == null) { VertexElement[] elements = new VertexElement[] { new VertexElement(0, 0, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.Position, 0), new VertexElement(0, 16, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0), VertexElement.VertexDeclarationEnd, }; vertDecl = new VertexDeclaration(BRenderDevice.getDevice(), elements); } }
protected string GetGeometryFormatString(SubMeshLodGeometryLink geom) { // Formulate an identifying string for the geometry format // Must take into account the vertex declaration and the index type // Format is (all lines separated by '|'): // Index type // Vertex element (repeating) // source // semantic // type string str = string.Format("{0}|", geom.indexData.indexBuffer.Type); for (int i = 0; i < geom.vertexData.vertexDeclaration.ElementCount; ++i) { VertexElement elem = geom.vertexData.vertexDeclaration.GetElement(i); str += string.Format("{0}|{0}|{1}|{2}|", elem.Source, elem.Semantic, elem.Type); } return(str); }
static VertexDeclaration GetVertexDeclaration(SimpleMesh mesh) { var elements = new List <VertexElement>(); elements.Add(VertexElement.Position <Vector3>()); if (mesh.HasVertexNormals) { elements.Add(VertexElement.Normal <Vector3>()); } if (mesh.HasVertexUVs) { elements.Add(VertexElement.TextureCoordinate <Vector2>()); } if (mesh.HasVertexColors) { elements.Add(VertexElement.Color <Color>()); } return(new VertexDeclaration(elements.ToArray())); }
public override void draw() { base.draw(); CCApplication mCOpacity = CCApplication.sharedApplication(); CCDirector.sharedDirector().getWinSize(); mCOpacity.basicEffect.VertexColorEnabled = true; mCOpacity.basicEffect.TextureEnabled = false; mCOpacity.basicEffect.Alpha = (float)this.m_cOpacity / 255f; VertexElement[] vertexElement = new VertexElement[] { new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0), new VertexElement(12, VertexElementFormat.Vector4, VertexElementUsage.Color, 0) }; VertexDeclaration vertexDeclaration = new VertexDeclaration(vertexElement); foreach (EffectPass pass in mCOpacity.basicEffect.CurrentTechnique.Passes) { pass.Apply(); mCOpacity.GraphicsDevice.DrawUserPrimitives <VertexPositionColor>(PrimitiveType.TriangleStrip, this.vertices, 0, 2); } mCOpacity.basicEffect.Alpha = 1f; }
private static VertexElement CreateVertexElement(D3D.ShaderParameterDescription desc, ref int offset) { D3DC.RegisterComponentType compType = desc.ComponentType; D3DC.RegisterComponentMaskFlags components = desc.UsageMask; String semanticName = desc.SemanticName; uint semanticIndex = desc.SemanticIndex; if (D3D10Helper.IsFlagSet((int)components, (int)D3DC.RegisterComponentMaskFlags.All)) { if (semanticName.Equals("COLOR")) { VertexElement element = new VertexElement(VertexSemantic.Color, (int)semanticIndex, VertexFormat.Color, offset); offset += 4; return(element); } else { VertexElement element = new VertexElement(D3D10Helper.FromD3DVertexSemantic(semanticName), (int)semanticIndex, VertexFormat.Vector4, offset); offset += 16; return(element); } } else if (D3D10Helper.IsFlagSet((int)components, (int)(D3DC.RegisterComponentMaskFlags.ComponentX | D3DC.RegisterComponentMaskFlags.ComponentY | D3DC.RegisterComponentMaskFlags.ComponentZ))) { VertexElement element = new VertexElement(D3D10Helper.FromD3DVertexSemantic(semanticName), (int)semanticIndex, VertexFormat.Vector3, offset); offset += 12; return(element); } else if (D3D10Helper.IsFlagSet((int)components, (int)(D3DC.RegisterComponentMaskFlags.ComponentX | D3DC.RegisterComponentMaskFlags.ComponentY))) { VertexElement element = new VertexElement(D3D10Helper.FromD3DVertexSemantic(semanticName), (int)semanticIndex, VertexFormat.Vector2, offset); offset += 8; return(element); } else if (D3D10Helper.IsFlagSet((int)components, (int)(D3DC.RegisterComponentMaskFlags.ComponentX))) { VertexElement element = new VertexElement(D3D10Helper.FromD3DVertexSemantic(semanticName), (int)semanticIndex, VertexFormat.Single, offset); offset += 4; return(element); } throw new ArgumentException("Invalid vertex element"); }
public static void ExtractModelMeshPartData(ModelMeshPart meshPart, ref Matrix transform, ref List <Vector3> vertices, ref List <TriangleIndice> indices) { var offset = vertices.Count; var declaration = meshPart.VertexBuffer.VertexDeclaration; var vertexElements = declaration.GetVertexElements(); var vertexPosition = new VertexElement(); foreach (var vert in vertexElements) { if (vert.VertexElementUsage == VertexElementUsage.Position && vert.VertexElementFormat == VertexElementFormat.Vector3) { vertexPosition = vert; break; } } var allVertex = new Vector3[meshPart.NumVertices]; meshPart.VertexBuffer.GetData <Vector3>(meshPart.VertexOffset * declaration.VertexStride + vertexPosition.Offset, allVertex, 0, meshPart.NumVertices, declaration.VertexStride); for (var i = 0; i != allVertex.Length; ++i) { Vector3.Transform(ref allVertex[i], ref transform, out allVertex[i]); } vertices.AddRange(allVertex); var indexElements = new short[meshPart.PrimitiveCount * 3]; meshPart.IndexBuffer.GetData <short>(meshPart.StartIndex * 2, indexElements, 0, meshPart.PrimitiveCount * 3); var tvi = new TriangleIndice[meshPart.PrimitiveCount]; for (int i = 0; i != tvi.Length; ++i) { tvi[i].A = indexElements[i * 3 + 0] + offset; tvi[i].B = indexElements[i * 3 + 1] + offset; tvi[i].C = indexElements[i * 3 + 2] + offset; } indices.AddRange(tvi); }
/// <summary> /// Adds a vertex element to the vertexData and allocates the vertex /// buffer and populates it with the information in the data array. /// </summary> /// <param name="vertexData"> /// the vertex data object whose vertex declaration and buffer /// bindings must be modified to include the reference to the new /// buffer /// </param> /// <param name="bindIdx">the index that will be used for this buffer</param> /// <param name="dataList">the list of raw data that will be used to populate the buffer</param> /// <param name="vertexBufferUsage"></param> /// <param name="useVertexShadowBuffer"></param> internal static void AllocateBuffer(VertexData vertexData, ushort bindIdx, List <VertexDataEntry> dataList, BufferUsage vertexBufferUsage, bool useVertexShadowBuffer) { // vertex buffers int offset = 0; List <int> offsets = new List <int>(); foreach (VertexDataEntry vde in dataList) { VertexElementType type = vde.GetVertexElementType(); vertexData.vertexDeclaration.AddElement(bindIdx, offset, type, vde.semantic, vde.textureIndex); offsets.Add(offset); offset += VertexElement.GetTypeSize(type); } int vertexSize = vertexData.vertexDeclaration.GetVertexSize(bindIdx); int vertexCount = vertexData.vertexCount; HardwareVertexBuffer vBuffer = HardwareBufferManager.Instance.CreateVertexBuffer(vertexSize, vertexCount, vertexBufferUsage, useVertexShadowBuffer); for (int i = 0; i < dataList.Count; ++i) { int vertexOffset = offsets[i]; if (dataList[i].fdata != null) { FillBuffer(vBuffer, vertexCount, vertexSize, vertexOffset, vertexSize, dataList[i].fdata); } else if (dataList[i].idata != null) { FillBuffer(vBuffer, vertexCount, vertexSize, vertexOffset, vertexSize, dataList[i].idata); } else { throw new Exception("Invalid data element with no data"); } } // bind the data vertexData.vertexBufferBinding.SetBinding(bindIdx, vBuffer); }
public void Create() { // Create shaders. passes[0].vs.CreateFromFile("res/shader/2DVertexShader.hlsl", "pass0"); passes[0].ps.CreateFromFile("res/shader/2DPixelShader.hlsl", "pass0"); passes[1].vs.CreateFromFile("res/shader/2DVertexShader.hlsl", "pass1"); passes[1].ps.CreateFromFile("res/shader/2DPixelShader.hlsl", "pass1"); passes[2].vs.CreateFromFile("res/shader/2DVertexShader.hlsl", "pass2"); passes[2].ps.CreateFromFile("res/shader/2DPixelShader.hlsl", "pass2"); // Create vertex layout. { VertexElement e1 = new VertexElement("POSITION", 0, Format.Float3, 0, 0, VertexElement.Classification.VertexData, 0); VertexElement e2 = new VertexElement("TEXCOORD", 0, Format.Float2, 1, 0, VertexElement.Classification.VertexData, 0); passes[0].layout.Create(new VertexElement[] { e1 }, passes[0].vs); passes[1].layout.Create(new VertexElement[] { e1, e2 }, passes[1].vs); passes[2].layout = passes[1].layout; } // Create vertex buffers. { Vector3[] vb0_src = { new Vector3(-0.5f, +0.5f, 0), new Vector3(+0.5f, +0.5f, 0), new Vector3(-0.5f, -0.5f, 0), new Vector3(+0.5f, -0.5f, 0) }; vb0.Create(vb0_src, Accessibility.None); vb0_dynamic.Create(vb0_src, Accessibility.DynamicWriteOnly); Vector2[] vb1_src = { new Vector2(0, 0), new Vector2(1, 0), new Vector2(0, 1), new Vector2(1, 1) }; vb1.Create(vb1_src, Accessibility.None); vb1_dynamic.Create(vb1_src, Accessibility.DynamicWriteOnly); } }
byte[] BuildVertexArray(ref int stride) { // calc stride for output WriteConversion[] convert = new WriteConversion[dataChannels.Count]; for (int i = 0, n = dataChannels.Count; i != n; ++i) { VertexElement ve = dataChannels[i]; ve.Offset = (short)stride; dataChannels[i] = ve; stride += GetFormatSize(dataChannels[i].VertexElementFormat); switch (dataChannels[i].VertexElementFormat) { case VertexElementFormat.Vector2: convert[i] = new WriteConversion(WriteVector2); break; case VertexElementFormat.Vector3: convert[i] = new WriteConversion(WriteVector3); break; case VertexElementFormat.Color: convert[i] = new WriteConversion(WriteColor); break; default: throw new System.InvalidOperationException(String.Format( "Internal error; seeing {0} for output format is not supported.", dataChannels[i].VertexElementFormat)); } } byte[] ret = new byte[vertexData.Count * stride]; int offset = 0; for (int i = 0, n = vertexData.Count; i != n; ++i) { for (int j = 0, m = convert.Length; j != m; ++j) { convert[j](vertexData[i][j], ret, ref offset); } } return(ret); }
public static VertexElement[] GetElements() { short offset = 0; VertexElement[] result = new VertexElement[3]; result[0] = new VertexElement { Offset = offset, Type = DeclarationType.Float3, Usage = DeclarationUsage.Position }; offset += (short)Marshal.SizeOf(typeof(Vector3)); result[1] = new VertexElement { Offset = offset, Type = DeclarationType.Float3, Usage = DeclarationUsage.Normal }; offset += (short)Marshal.SizeOf(typeof(Vector3)); result[2] = new VertexElement { Offset = offset, Type = DeclarationType.Float2, Usage = DeclarationUsage.TextureCoordinate }; offset += (short)Marshal.SizeOf(typeof(Vector2)); //for (byte i = 1; i < 5; i++) //{ // result[2+i] = new VertexElement // { // Offset = offset, // Type = DeclarationType.Float4, // Usage = DeclarationUsage.TextureCoordinate, // UsageIndex = i // }; // offset += (short)Marshal.SizeOf(typeof(Vector2)); //} return(result); }
public static BoundingBox CreateBoundingBoxFromModel(BatchInformation bi) { // Read the format of the vertex buffer VertexDeclaration declaration = bi.VertexBuffer.VertexDeclaration; VertexElement[] vertexElements = declaration.GetVertexElements(); // Find the element that holds the position VertexElement vertexPosition = new VertexElement(); foreach (VertexElement vert in vertexElements) { if (vert.VertexElementUsage == VertexElementUsage.Position && vert.VertexElementFormat == VertexElementFormat.Vector3) { vertexPosition = vert; // There should only be one break; } } // Check the position element found is valid if (vertexPosition == null || vertexPosition.VertexElementUsage != VertexElementUsage.Position || vertexPosition.VertexElementFormat != VertexElementFormat.Vector3) { throw new Exception("Model uses unsupported vertex format!"); } // This where we store the vertices until transformed Vector3[] allVertex = new Vector3[bi.NumVertices]; // Read the vertices from the buffer in to the array bi.VertexBuffer.GetData <Vector3>( bi.StreamOffset * declaration.VertexStride + vertexPosition.Offset, allVertex, 0, bi.NumVertices, declaration.VertexStride); // Transform them based on the relative bone location and the world if provided for (int i = 0; i != allVertex.Length; ++i) { Vector3.Transform(ref allVertex[i], ref bi.ModelLocalTransformation, out allVertex[i]); } return(BoundingBox.CreateFromPoints(allVertex)); }
private unsafe uint ReadVertexData(uint vertexOffset, VertexData vertexData) { VertexElement posElem = vertexData.vertexDeclaration.FindElementBySemantic(VertexElementSemantic.VES_POSITION); HardwareVertexBufferSharedPtr vertexBuffer = vertexData.vertexBufferBinding.GetBuffer(posElem.Source); byte * vertexMemory = (byte *)vertexBuffer.Lock(HardwareBuffer.LockOptions.HBL_READ_ONLY); float *pElem; for (uint i = 0; i < vertexData.vertexCount; i++) { posElem.BaseVertexPointerToElement(vertexMemory, &pElem); Vector3 point = new Vector3(pElem[0], pElem[1], pElem[2]); vertices[vertexOffset] = point * this.scale; vertexMemory += vertexBuffer.VertexSize; vertexOffset++; } vertexBuffer.Unlock(); return(vertexOffset); }
public static Vector3[] GetVertexElement(ModelMeshPart meshPart, VertexElementUsage usage) { VertexDeclaration vd = meshPart.VertexBuffer.VertexDeclaration; VertexElement[] elements = vd.GetVertexElements(); Func <VertexElement, bool> elementPredicate = ve => ve.VertexElementUsage == usage && ve.VertexElementFormat == VertexElementFormat.Vector3; if (!elements.Any(elementPredicate)) { return(null); } VertexElement element = elements.First(elementPredicate); Vector3[] vertexData = new Vector3[meshPart.NumVertices]; meshPart.VertexBuffer.GetData((meshPart.VertexOffset * vd.VertexStride) + element.Offset, vertexData, 0, vertexData.Length, vd.VertexStride); return(vertexData); }
public void removeBinormals() { //This code makes the editor crash and is currently not being called. Being left for reference. using (MeshPtr mesh = entity.getMesh()) { SubMesh subMesh = mesh.Value.getSubMesh(0); VertexData vertexData = subMesh.vertexData; VertexDeclaration vertexDeclaration = vertexData.vertexDeclaration; //VertexBufferBinding vertexBinding = vertexData.vertexBufferBinding; //VertexElement normalElement = vertexDeclaration.findElementBySemantic(VertexElementSemantic.VES_NORMAL); //VertexElement tangentElement = vertexDeclaration.findElementBySemantic(VertexElementSemantic.VES_TANGENT); VertexElement binormalElement = vertexDeclaration.findElementBySemantic(VertexElementSemantic.VES_BINORMAL); if (binormalElement != null) { vertexDeclaration.removeElement(VertexElementSemantic.VES_BINORMAL); vertexData.reorganizeBuffers(vertexDeclaration); } } Log.Info("Binormals Removed"); }
/// <summary> /// /// </summary> /// <param name="vertexData"></param> /// <param name="normals"></param> private unsafe void NormalsSaveNormalized(VertexData vertexData, float *normals) { VertexElement element = vertexData.vertexDeclaration.FindElementBySemantic(VertexElementSemantic.Normal); HardwareVertexBuffer buffer = vertexData.vertexBufferBinding.GetBuffer(element.Source); int numVerts = buffer.VertexCount; for (int i = 0, index = 0; i < numVerts; i++, index += 3) { Vector3 n = new Vector3(normals[index], normals[index + 1], normals[index + 2]); n.Normalize(); normals[index] = n.x; normals[index + 1] = n.y; normals[index + 2] = n.z; } // don't forget to unlock! buffer.Unlock(); }
public Pos_uv0_uv1(float _x, float _y, float _z, float _u0, float _v0, float _u1, float _v1) { x = _x; y = _y; z = _z; u0 = _u0; v0 = _v0; u1 = _u1; v1 = _v1; if (Pos_uv0_uv1.vertDecl == null) { VertexElement[] elements = new VertexElement[] { new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0), new VertexElement(0, 12, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0), new VertexElement(0, 20, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 1), VertexElement.VertexDeclarationEnd, }; vertDecl = new VertexDeclaration(BRenderDevice.getDevice(), elements); } }
private RenderWindow(RenderWindowThread t) { myThread = t; InitializeComponent(); SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true); PresentParameters presentationParameters = new PresentParameters(); presentationParameters.Windowed = true; presentationParameters.SwapEffect = SwapEffect.Discard; DeviceType dt = DeviceType.Hardware; if (Manager.GetDeviceCaps(0, DeviceType.Hardware).PixelShaderVersion.Major < 3) { dt = DeviceType.Reference; Text += " (emulated in SW)"; } myDevice = new Device(0, dt, this, CreateFlags.HardwareVertexProcessing, presentationParameters); // gamma-correct rendering myDevice.RenderState.SrgbWriteEnable = true; Assembly assem = Assembly.GetAssembly(typeof(RenderWindow)); Stream st = assem.GetManifestResourceStream("BilievelTextureMagnification.Shader.fx"); myEffect = Effect.FromStream(myDevice, st, null, null, ShaderFlags.None, null); st.Close(); st = null; myEffect.Technique = "threshold"; VertexElement[] vertexElements = new VertexElement[] { new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0), new VertexElement(0, 3 * 4, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0), new VertexElement(0, 5 * 4, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 1), VertexElement.VertexDeclarationEnd }; myVertexDeclaration = new VertexDeclaration(myDevice, vertexElements); }
private void CreateHardwareBuffer(uint size) { this.renderOp = new RenderOperation { vertexData = new VertexData { vertexStart = 0 } }; VertexDeclaration vd = this.renderOp.vertexData.vertexDeclaration; vd.AddElement( 0, 0, VertexElementType.VET_FLOAT3, VertexElementSemantic.VES_POSITION); vd.AddElement( 0, VertexElement.GetTypeSize(VertexElementType.VET_FLOAT3), VertexElementType.VET_FLOAT2, VertexElementSemantic.VES_TEXTURE_COORDINATES); vd.AddElement( 0, VertexElement.GetTypeSize(VertexElementType.VET_FLOAT3) + VertexElement.GetTypeSize(VertexElementType.VET_FLOAT2), VertexElementType.VET_COLOUR, VertexElementSemantic.VES_DIFFUSE); this.hardwareBuffer = HardwareBufferManager.Singleton.CreateVertexBuffer( vd.GetVertexSize(0), size, HardwareBuffer.Usage.HBU_DYNAMIC_WRITE_ONLY, false); this.renderOp.vertexData.vertexBufferBinding.SetBinding(0, this.hardwareBuffer); this.renderOp.operationType = RenderOperation.OperationTypes.OT_TRIANGLE_LIST; this.renderOp.useIndexes = false; }
public C3Sprite(C3Texture texture) { _arrVertex = new SpriteVertex[4]; for (int i = 0; i < 4; i++) { _arrVertex[i].z = 0.5f; _arrVertex[i].rhw = 1.0f; _arrVertex[i].color = new Color4(255, 255, 255, 255).ToArgb(); } _texture = texture; source = new Rectangle( 0, 0, _texture.width, _texture.height ); CalcCoor(); VertexElement[] vertexElems = new VertexElement[]{ new VertexElement(0, 0, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.PositionTransformed, 0 ), new VertexElement(0, 16, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0 ), new VertexElement(0, 20, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0 ), VertexElement.VertexDeclarationEnd }; _vertexDecl = new VertexDeclaration(Core.Device, vertexElems); }
private int GetElementSize(VertexElement element) { switch (element.Type) { case VertexAttribPointerType.Byte: case VertexAttribPointerType.UnsignedByte: return element.Size * Marshal.SizeOf<byte>(); case VertexAttribPointerType.Double: return element.Size * Marshal.SizeOf<double>(); case VertexAttribPointerType.Float: return element.Size * Marshal.SizeOf<float>(); case VertexAttribPointerType.Int: case VertexAttribPointerType.UnsignedInt: return element.Size * Marshal.SizeOf<int>(); case VertexAttribPointerType.Short: case VertexAttribPointerType.UnsignedShort: return element.Size * Marshal.SizeOf<short>(); } return 0; }
public void VertexElementColor() { var element = new VertexElement(VertexElementType.Color); Assert.AreEqual(VertexElementType.Color, element.ElementType); Assert.AreEqual(4, element.ComponentCount); Assert.AreEqual(4, element.Size); }
//ncrunch: no coverage start public void LoadFromFile(Stream fileData) { var reader = new BinaryReader(fileData); string shortName = reader.ReadString(); var dataVersion = reader.ReadBytes(4); var boolean = reader.ReadBoolean(); if (boolean) reader.ReadString(); boolean = reader.ReadBoolean(); var type = reader.ReadString(); if (type == null) throw new NullReferenceException(); boolean = reader.ReadBoolean(); var count = reader.ReadByte(); var typeOfByte = reader.ReadByte(); if (typeOfByte == 255) throw new NullReferenceException(); type = reader.ReadString(); var list = new VertexElement[count]; for (int i = 0; i < count; i++) { var vertexElementType = reader.ReadInt32(); var size = reader.ReadInt32(); var vertexCount = reader.ReadInt32(); var vertexElementOffset = reader.ReadInt32(); list[i] = new VertexElement((VertexElementType)vertexElementType, size, vertexCount); } Format = new VertexFormat(list); var formatStride = reader.ReadInt32(); int verticesLength = reader.ReadInt32(); //Int32 numberofvertices boolean = reader.ReadBoolean(); if (boolean) { verticesLength = ReadNumberMostlyBelow255(reader); vertices = reader.ReadBytes(verticesLength); } reader.ReadBoolean(); //Indices var indicesLength = ReadNumberMostlyBelow255(reader); typeOfByte = reader.ReadByte(); reader.ReadString(); indices = new short[indicesLength]; for (int i = 0; i < indicesLength; i++) indices[i] = reader.ReadInt16(); SetNativeData(vertices, indices); }
static VertexPositionColorTexture() { VertexElement[] elements = new VertexElement[] { new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0), new VertexElement(12, VertexElementFormat.Color, VertexElementUsage.Color, 0), new VertexElement(0x10, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0) }; VertexDeclaration declaration = new VertexDeclaration(elements); VertexDeclaration = declaration; }
void ParseObject(XmlReader xml, ParsedXmlModel data, ref XmlModelObject obj) { int depth = xml.Depth; Vector3[] positions = null; Vector3[] normals = null; MeshFace[] faces = null; Vector2[] texVtx = null; Index3i[] texIdx = null; VertexWeight[] vtxWeights = null; #region 从Xml中读取数据 while (xml.Read() && xml.Depth > depth) { if (xml.IsStartElement() && !xml.IsEmptyElement) { switch (xml.Name) { case "Parent": obj.ID = int.Parse(xml.GetAttribute("ID")); break; case "LocalTM": obj.LocalTM = ParseMatrix(xml); break; case "WorldTM": obj.WorldTM = ParseMatrix(xml); break; case "BoundingBox": obj.AABB = ParseBoundingBox(xml); break; case "Vertex": positions = ParseMeshVector3Array(xml); break; case "VertexNormal": normals = ParseMeshVector3Array(xml); for (int i = 0; i < normals.Length; i++) { normals[i].Normalize(); } break; case "TexVertex": texVtx = ParseMeshVector2Array(xml); break; case "TriIndex": faces = ParseMeshFaces(xml); break; case "TexIndex": texIdx = ParseTexIndex(xml, faces.Length); break; case "VertexWeight": vtxWeights = ParseVertexWeightArray(xml, positions.Length); break; case "Key": obj.BoneData = ParseBoneData(xml); break; } } } #endregion if (obj.Type == XmlModelObjectType.Mesh) { FastList<VertexElement> elementsList = new FastList<VertexElement>(); int ofs = 0; if (positions != null) { VertexElement e = new VertexElement(ofs, VertexElementFormat.Vector3, VertexElementUsage.Position); elementsList.Add(e); ofs += e.Size; } if (normals != null) { VertexElement e = new VertexElement(ofs, VertexElementFormat.Vector3, VertexElementUsage.Normal); elementsList.Add(e); ofs += e.Size; } if (texVtx != null) { VertexElement e = new VertexElement(ofs, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0); elementsList.Add(e); ofs += e.Size; } if (vtxWeights != null) { VertexElement e = new VertexElement(ofs, VertexElementFormat.Byte4, VertexElementUsage.BlendWeight, 0); elementsList.Add(e); ofs += e.Size; } VertexElement[] elements = new VertexElement[elementsList.Count]; Array.Copy(elementsList.Elements, elements, elementsList.Count); obj.Mesh = new MeshData((RenderSystem)null); MeshData mesh = obj.Mesh; mesh.Faces = faces; mesh.Name = obj.Name; byte[] buffer = null; if (VertexElement.Compare(elements, VertexPBNT1.Elements)) { buffer = BuildVertexPBNT1Data(positions, normals, texVtx, texIdx, vtxWeights, faces); mesh.VertexSize = sizeof(VertexPBNT1); mesh.VertexElements = VertexPBNT1.Elements; } else if (VertexElement.Compare(elements, VertexPNT1.Elements)) { buffer = BuildVertexPNT1Data(positions, normals, texVtx, texIdx, faces); mesh.VertexSize = sizeof(VertexPNT1); mesh.VertexElements = VertexPNT1.Elements; } else if (VertexElement.Compare(elements, VertexPT1.Elements)) { buffer = BuildVertexPT1Data(positions, texVtx, texIdx, faces); mesh.VertexSize = sizeof(VertexPT1); mesh.VertexElements = VertexPT1.Elements; } else if (VertexElement.Compare(elements, VertexPN.Elements)) { buffer = BuildVertexPNData(positions, normals, faces); mesh.VertexSize = sizeof(VertexPN); mesh.VertexElements = VertexPN.Elements; } else if (VertexElement.Compare(elements, VertexP.Elements)) { buffer = BuildVertexPData(positions, faces); mesh.VertexSize = sizeof(VertexP); mesh.VertexElements = VertexP.Elements; } if (buffer != null) { if (mesh.VertexSize != 0) { mesh.VertexCount = buffer.Length / mesh.VertexSize; } fixed (byte* src = &buffer[0]) { mesh.SetData(src, buffer.Length); } } } }
/// <summary> /// Initializes the <see cref="VertexElement"/> struct. /// </summary> static VertexElement() { VertexDeclarationEnd = new VertexElement(0xff, 0, DeclarationType.Unused, DeclarationMethod.Default, DeclarationUsage.Position, 0); }
/// <summary> /// Copies over the vertex and index buffers and calls the function within /// the model class to build a Mesh class. /// </summary> private void buildMesh() { VertexElement[] vElements = new VertexElement[] { new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0), new VertexElement(0, 12, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0), new VertexElement(0, 20, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Normal, 0), new VertexElement(0, 32, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.Tangent, 0), VertexElement.VertexDeclarationEnd }; // Creates a new mesh try { mesh = new Mesh(faceList.Count, vertexInfo.Count, MeshFlags.Managed | MeshFlags.Use32Bit, vElements, device); mesh.SetVertexBufferData(vertexInfo.ToArray(), LockFlags.None); mesh.SetIndexBufferData(faceList.ToArray(), LockFlags.None); } catch(DirectXException) { MessageBox.Show("A problem occured with the model", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); faceList.Clear(); vertexInfo.Clear(); vertexList.Clear(); mesh = new Mesh(1, 1, MeshFlags.Managed, vElements, device); return; } // Try loop to generate normals (if needed), tangents and binormals. try { // Generates a list of adjacent faces used for generating normals. int[] adjacency = new int[mesh.NumberFaces * 3]; mesh.GenerateAdjacency(0, adjacency); if(!hasNormals) mesh.ComputeNormals(adjacency); TangentBuilder.CalculateTangents(mesh); } catch (DirectXException dxe) { Console.WriteLine(dxe); } }
/// <summary> /// Loads in an obj/x file. /// </summary> /// <param name="filename">Full path of the 3d model file.</param> public void LoadModel(string filename) { VertexElement[] vElements = new VertexElement[] { new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0), new VertexElement(0, 12, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0), new VertexElement(0, 20, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Normal, 0), new VertexElement(0, 32, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.Tangent, 0), VertexElement.VertexDeclarationEnd }; model = new Mesh(1, 1, MeshFlags.Managed, vElements, device); if (filename.EndsWith(".obj")) model = objLoader.LoadModel(filename); else if (filename.EndsWith(".x")) model = xLoader.LoadModel(filename); // Calculate the min/max values. calcSize(); enabled = true; }
static RectVertex() { elements = new VertexElement[2]; elements[0] = new VertexElement(0, VertexElementFormat.Vector4, VertexElementUsage.PositionTransformed); elements[1] = new VertexElement(Vector4.SizeInBytes, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0); }
public Pipeline CreatePipeline(VertexLayout vertexLayout, Shader vertexShader, Shader fragmentShader, bool required) { VertexElement[] ves = new VertexElement[vertexLayout.Items.Count]; foreach (var kvp in vertexLayout.Items) { var item = kvp.Value; d3d9.DeclarationType decltype = DeclarationType.Float1; switch (item.AttribType) { case gl.VertexAttribPointerType.Float: if (item.Components == 1) decltype = DeclarationType.Float1; else if (item.Components == 2) decltype = DeclarationType.Float2; else if (item.Components == 3) decltype = DeclarationType.Float3; else if (item.Components == 4) decltype = DeclarationType.Float4; else throw new NotSupportedException(); break; default: throw new NotSupportedException(); } d3d9.DeclarationUsage usage = DeclarationUsage.Position; byte usageIndex = 0; switch(item.Usage) { case AttributeUsage.Position: usage = DeclarationUsage.Position; break; case AttributeUsage.Texcoord0: usage = DeclarationUsage.TextureCoordinate; break; case AttributeUsage.Texcoord1: usage = DeclarationUsage.TextureCoordinate; usageIndex = 1; break; case AttributeUsage.Color0: usage = DeclarationUsage.Color; break; default: throw new NotSupportedException(); } ves[kvp.Key] = new VertexElement(0, (short)item.Offset, decltype, DeclarationMethod.Default, usage, usageIndex); } var pw = new PipelineWrapper(); pw.VertexDeclaration = new VertexDeclaration(dev, ves); Pipeline pipeline = new Pipeline(this,IntPtr.Zero,true, vertexLayout, new List<UniformInfo>()); pipeline.Opaque = pw; return pipeline; }
public void VertexElementTextureUV() { var element = new VertexElement(VertexElementType.TextureUV); Assert.AreEqual(VertexElementType.TextureUV, element.ElementType); Assert.AreEqual(2, element.ComponentCount); Assert.AreEqual(8, element.Size); }
public Pipeline CreatePipeline(VertexLayout vertexLayout, Shader vertexShader, Shader fragmentShader, bool required, string memo) { if (!vertexShader.Available || !fragmentShader.Available) { string errors = string.Format("Vertex Shader:\r\n {0} \r\n-------\r\nFragment Shader:\r\n{1}", vertexShader.Errors, fragmentShader.Errors); if (required) throw new InvalidOperationException("Couldn't build required GL pipeline:\r\n" + errors); var pipeline = new Pipeline(this, null, false, null, null, null); pipeline.Errors = errors; return pipeline; } VertexElement[] ves = new VertexElement[vertexLayout.Items.Count]; int stride = 0; foreach (var kvp in vertexLayout.Items) { var item = kvp.Value; d3d9.DeclarationType decltype = DeclarationType.Float1; switch (item.AttribType) { case gl.VertexAttribPointerType.Float: if (item.Components == 1) decltype = DeclarationType.Float1; else if (item.Components == 2) decltype = DeclarationType.Float2; else if (item.Components == 3) decltype = DeclarationType.Float3; else if (item.Components == 4) decltype = DeclarationType.Float4; else throw new NotSupportedException(); stride += 4 * item.Components; break; default: throw new NotSupportedException(); } d3d9.DeclarationUsage usage = DeclarationUsage.Position; byte usageIndex = 0; switch(item.Usage) { case AttributeUsage.Position: usage = DeclarationUsage.Position; break; case AttributeUsage.Texcoord0: usage = DeclarationUsage.TextureCoordinate; break; case AttributeUsage.Texcoord1: usage = DeclarationUsage.TextureCoordinate; usageIndex = 1; break; case AttributeUsage.Color0: usage = DeclarationUsage.Color; break; default: throw new NotSupportedException(); } ves[kvp.Key] = new VertexElement(0, (short)item.Offset, decltype, DeclarationMethod.Default, usage, usageIndex); } var pw = new PipelineWrapper() { VertexDeclaration = new VertexDeclaration(dev, ves), VertexShader = vertexShader.Opaque as ShaderWrapper, FragmentShader = fragmentShader.Opaque as ShaderWrapper, VertexStride = stride, }; //scan uniforms from constant tables //handles must be disposed later (with the pipeline probably) var uniforms = new List<UniformInfo>(); var fs = pw.FragmentShader; var vs = pw.VertexShader; var fsct = fs.bytecode.ConstantTable; var vsct = vs.bytecode.ConstantTable; foreach(var ct in new[]{fsct,vsct}) { Queue<Tuple<string,EffectHandle>> todo = new Queue<Tuple<string,EffectHandle>>(); int n = ct.Description.Constants; for (int i = 0; i < n; i++) { var handle = ct.GetConstant(null, i); todo.Enqueue(Tuple.Create("", handle)); } while(todo.Count != 0) { var tuple = todo.Dequeue(); var prefix = tuple.Item1; var handle = tuple.Item2; var descr = ct.GetConstantDescription(handle); //Console.WriteLine("D3D UNIFORM: " + descr.Name); if (descr.StructMembers != 0) { string newprefix = prefix + descr.Name + "."; for (int j = 0; j < descr.StructMembers; j++) { var subhandle = ct.GetConstant(handle, j); todo.Enqueue(Tuple.Create(newprefix, subhandle)); } continue; } UniformInfo ui = new UniformInfo(); UniformWrapper uw = new UniformWrapper(); ui.Opaque = uw; string name = prefix + descr.Name; //mehhh not happy about this stuff if (fs.MapCodeToNative != null || vs.MapCodeToNative != null) { string key = name.TrimStart('$'); if (descr.Rows != 1) key = key + "[0]"; if (fs.MapCodeToNative != null && ct == fsct) if (fs.MapCodeToNative.ContainsKey(key)) name = fs.MapCodeToNative[key]; if (vs.MapCodeToNative != null && ct == vsct) if (vs.MapCodeToNative.ContainsKey(key)) name = vs.MapCodeToNative[key]; } ui.Name = name; uw.Description = descr; uw.EffectHandle = handle; uw.FS = (ct == fsct); uw.CT = ct; if (descr.Type == ParameterType.Sampler2D) { ui.IsSampler = true; ui.SamplerIndex = descr.RegisterIndex; uw.SamplerIndex = descr.RegisterIndex; } uniforms.Add(ui); } } pw.fsct = fsct; pw.vsct = vsct; return new Pipeline(this, pw, true, vertexLayout, uniforms,memo); }
public void ElementToString() { var element = new VertexElement(VertexElementType.TextureUV); Assert.AreEqual("TextureUV*2", element.ToString()); }
/// <summary>Updates the mesh to a new vertex declaration</summary> public void SetVertexDeclaration(Device device, VertexElement[] decl) { Mesh tempSystemMesh = null; Mesh tempLocalMesh = null; VertexElement[] oldDecl = null; using(systemMemoryMesh) { using (localMemoryMesh) { // Clone the meshes if (systemMemoryMesh != null) { oldDecl = systemMemoryMesh.Declaration; tempSystemMesh = systemMemoryMesh.Clone(systemMemoryMesh.Options.Value, decl, device); } if (localMemoryMesh != null) { tempLocalMesh = localMemoryMesh.Clone(localMemoryMesh.Options.Value, decl, device); } } } // Store the new meshes systemMemoryMesh = tempSystemMesh; localMemoryMesh = tempLocalMesh; bool hadNormal = false; // Check if the old declaration contains a normal. for(int i = 0; i < oldDecl.Length; i++) { if (oldDecl[i].DeclarationUsage == DeclarationUsage.Normal) { hadNormal = true; break; } } // Check to see if the new declaration has a normal bool hasNormalNow = false; for(int i = 0; i < decl.Length; i++) { if (decl[i].DeclarationUsage == DeclarationUsage.Normal) { hasNormalNow = true; break; } } // Compute normals if they are being requested and the old mesh didn't have them if ( !hadNormal && hasNormalNow ) { if (systemMemoryMesh != null) systemMemoryMesh.ComputeNormals(); if (localMemoryMesh != null) localMemoryMesh.ComputeNormals(); } }
public SdkMeshVertexBuffer(BinaryReader reader) { NumVertices = reader.ReadUInt64(); SizeBytes = reader.ReadUInt64(); StrideBytes = reader.ReadUInt64(); Decl = new List<VertexElement>(); var processElem = true; for (int j = 0; j < MaxVertexElements; j++) { var stream = reader.ReadUInt16(); var offset = reader.ReadUInt16(); var type = reader.ReadByte(); var method = reader.ReadByte(); var usage = reader.ReadByte(); var usageIndex = reader.ReadByte(); if (stream < 16 && processElem) { var element = new VertexElement((short)stream, (short)offset, (DeclarationType)type, (DeclarationMethod)method, (DeclarationUsage)usage, usageIndex); Decl.Add(element); } else { processElem = false; } } DataOffset = reader.ReadUInt64(); Vertices = new List<PosNormalTexTan>(); if (SizeBytes > 0) { ReadVertices(reader); } }
public VertexElementWithOffset(VertexElement vertexElement, int offset, int size) { VertexElement = vertexElement; Offset = offset; Size = size; }
private unsafe void BasicSetup(byte[] data, string tex0) { LoadReturn lr=Load(data, data.Length); if(lr.Subsets<=0) throw new ApplicationException("Failed to load nif"); subsets=new Subset[lr.Subsets]; radius=lr.maxsize; loadLog=new string(lr.log); if(lr.FailedSubsets>0) System.Windows.Forms.MessageBox.Show(""+lr.FailedSubsets+" could not be rendered", "Warning"); string texFileName; for(uint i=0;i<subsets.Length;i++) { //Get basic info GetInfo(i, out subsets[i].info); GetMaterial(i, out subsets[i].mat); GetTransform(i, out subsets[i].transform); if(i==0&&tex0!=null) texFileName=tex0; else if(subsets[i].info.containsTexture) { sbyte* charPtr; GetTex(i, out charPtr); texFileName=new string(charPtr); } else texFileName=null; //sanity check //if(!subsets[i].info.containsTexCoords) throw new ApplicationException("Vertex texture coords are missing from subset "+i); //if(!subsets[i].info.containsNormals) throw new ApplicationException("Vertex normals are missing from subset "+i); //if(texFileName==null) throw new ApplicationException("No texture name was specified in subset "+i); //Load textures if(texFileName!=null) { System.IO.Stream stream=BSAArchive.GetTexture(texFileName); if(stream!=null) { subsets[i].colorMap=TextureLoader.FromStream(device, stream); SurfaceDescription desc=subsets[i].colorMap.GetLevelDescription(0); subsets[i].data.cWidth=desc.Width; subsets[i].data.cHeight=desc.Height; subsets[i].data.cformat=desc.Format; subsets[i].data.path=texFileName; } else throw new ApplicationException("Could not load texture for subset "+i); stream=BSAArchive.GetGlowTexture(texFileName); if(stream!=null) { subsets[i].glowMap=TextureLoader.FromStream(device, stream); SurfaceDescription desc=subsets[i].glowMap.GetLevelDescription(0); subsets[i].data.gWidth=desc.Width; subsets[i].data.gHeight=desc.Height; subsets[i].data.gformat=desc.Format; } else subsets[i].data.gWidth=-1; stream=BSAArchive.GetNormalTexture(texFileName); if(stream!=null) { subsets[i].normalMap=TextureLoader.FromStream(device, stream); SurfaceDescription desc=subsets[i].normalMap.GetLevelDescription(0); subsets[i].data.nWidth=desc.Width; subsets[i].data.nHeight=desc.Height; subsets[i].data.nformat=desc.Format; } else subsets[i].data.nWidth=-1; } else { subsets[i].colorMap=null; subsets[i].data.cWidth=-1; subsets[i].data.gWidth=-1; subsets[i].data.nWidth=-1; } //Get vertex information VertexElement[] decl=new VertexElement[7]; decl[0]=new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0); decl[1]=new VertexElement(0, 12, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Tangent, 0); decl[2]=new VertexElement(0, 24, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.BiNormal, 0); decl[3]=new VertexElement(0, 36, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Normal, 0); decl[4]=new VertexElement(0, 48, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0); decl[5]=new VertexElement(0, 56, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.Color, 0); decl[6]=VertexElement.VertexDeclarationEnd; subsets[i].vDecl=new VertexDeclaration(device, decl); if(subsets[i].info.containsTangentBinormal) { Mesh m=new Mesh(subsets[i].info.iCount/3, subsets[i].info.vCount, MeshFlags.SystemMemory, decl, device); subsets[i].vBuffer=new VertexBuffer(typeof(ConvertedVertex), subsets[i].info.vCount, device, Usage.WriteOnly, VertexFormats.None, Pool.Managed); //ConvertedVertex[] cv=(ConvertedVertex[])subsets[i].vBuffer.Lock(0, LockFlags.None); ConvertedVertex[] cv=(ConvertedVertex[])m.LockVertexBuffer(typeof(ConvertedVertex), LockFlags.None, subsets[i].info.vCount); fixed(ConvertedVertex* cvPtr = cv) { GetVerticies(i, cvPtr); } m.UnlockVertexBuffer(); //subsets[i].vBuffer.Unlock(); //Indicies subsets[i].iBuffer=new IndexBuffer(typeof(ushort), subsets[i].info.iCount, device, Usage.WriteOnly, Pool.Managed); //ushort[] indicies=(ushort[])subsets[i].iBuffer.Lock(0, LockFlags.None); ushort[] indicies=(ushort[])m.LockIndexBuffer(typeof(ushort), LockFlags.None, subsets[i].info.iCount); fixed(ushort* iPtr = indicies) { GetIndicies(i, iPtr); } //subsets[i].iBuffer.Unlock(); m.UnlockIndexBuffer(); subsets[i].numTris=subsets[i].info.iCount/3; int[] adj=new int[subsets[i].info.iCount]; m.GenerateAdjacency(0.01f, adj); m.ComputeTangent(0, 0, 0, 1, adj); //m.ComputeTangentFrame(TangentOptions.CalculateNormals|TangentOptions.GenerateInPlace); cv=(ConvertedVertex[])m.LockVertexBuffer(typeof(ConvertedVertex), LockFlags.ReadOnly, subsets[i].info.vCount); ConvertedVertex[] cv2=(ConvertedVertex[])subsets[i].vBuffer.Lock(0, LockFlags.None); for(int j=0;j<cv.Length;j++) { cv2[j]=cv[j]; } m.UnlockVertexBuffer(); subsets[i].vBuffer.Unlock(); indicies=(ushort[])m.LockIndexBuffer(typeof(ushort), LockFlags.None, subsets[i].info.iCount); ushort[] indicies2=(ushort[])subsets[i].iBuffer.Lock(0, LockFlags.None); for(int j=0;j<indicies.Length;j++) { indicies2[j]=indicies[j]; } m.UnlockIndexBuffer(); subsets[i].iBuffer.Unlock(); m.Dispose(); } else { subsets[i].vBuffer=new VertexBuffer(typeof(ConvertedVertex), subsets[i].info.vCount, device, Usage.WriteOnly, VertexFormats.None, Pool.Managed); ConvertedVertex[] cv=(ConvertedVertex[])subsets[i].vBuffer.Lock(0, LockFlags.None); fixed(ConvertedVertex* cvPtr = cv) { GetVerticies(i, cvPtr); } subsets[i].vBuffer.Unlock(); //Indicies subsets[i].iBuffer=new IndexBuffer(typeof(ushort), subsets[i].info.iCount, device, Usage.WriteOnly, Pool.Managed); ushort[] indicies=(ushort[])subsets[i].iBuffer.Lock(0, LockFlags.None); fixed(ushort* iPtr = indicies) { GetIndicies(i, iPtr); } subsets[i].iBuffer.Unlock(); subsets[i].numTris=subsets[i].info.iCount/3; } } int alphaCount=0; for(int i=0;i<Subsets;i++) if(subsets[i].info.hasalpha) alphaCount++; AlphaIndicies=new int[alphaCount]; alphaCount=0; for(int i=0;i<Subsets;i++) if(subsets[i].info.hasalpha) AlphaIndicies[alphaCount++]=i; }