public override HardwareIndexBuffer GetSharedIndexBuffer(ushort batchSize, ushort vdatasize, int vertexIncrement, ushort xoffset, ushort yoffset, ushort numSkirtRowsCols, ushort skirtRowColSkip) { int hsh = HashIndexBuffer(batchSize, vdatasize, vertexIncrement, xoffset, yoffset, numSkirtRowsCols, skirtRowColSkip); if (!this.SharedIBufMap.ContainsKey(hsh)) { // create new int indexCount = Terrain.GetNumIndexesForBatchSize(batchSize); HardwareIndexBuffer ret = HardwareBufferManager.Instance.CreateIndexBuffer(IndexType.Size16, indexCount, BufferUsage.StaticWriteOnly); var pI = ret.Lock(BufferLocking.Discard); Terrain.PopulateIndexBuffer(pI, batchSize, vdatasize, vertexIncrement, xoffset, yoffset, numSkirtRowsCols, skirtRowColSkip); ret.Unlock(); this.SharedIBufMap.Add(hsh, ret); return(ret); } else { return(this.SharedIBufMap[hsh]); } }
private void CreateBuffers(ushort[] indices, short[] vertices) { var numIndices = indices.Length; var numVertices = vertices.Length; _vertexDeclaration = HardwareBufferManager.Instance.CreateVertexDeclaration(); _vertexDeclaration.AddElement(0, 0, VertexElementType.Short2, VertexElementSemantic.Position); _ib = HardwareBufferManager.Instance.CreateIndexBuffer(IndexType.Size16, numIndices, BufferUsage.WriteOnly); _vb = HardwareBufferManager.Instance.CreateVertexBuffer(_vertexDeclaration, numVertices, BufferUsage.WriteOnly, false); _ib.WriteData(0, numIndices * sizeof(ushort), indices, true); _vb.WriteData(0, numVertices * sizeof(ushort), vertices, true); var binding = new VertexBufferBinding(); binding.SetBinding(0, _vb); VertexData = new VertexData(); VertexData.vertexDeclaration = _vertexDeclaration; VertexData.vertexBufferBinding = binding; VertexData.vertexCount = numVertices; VertexData.vertexStart = 0; IndexData = new IndexData(); IndexData.indexBuffer = _ib; IndexData.indexCount = numIndices; IndexData.indexStart = 0; }
private void CreatePrefabPlane() { Mesh mesh = (Mesh)Create("Prefab_Plane"); SubMesh subMesh = mesh.CreateSubMesh("Prefab_Plane_Submesh"); float[] vertices = { -100, -100, 0, // pos 0, 0, 1, // normal 0, 1, // texcoord 100, -100, 0, 0, 0, 1, 1, 1, 100, 100, 0, 0, 0, 1, 1, 0, -100, 100, 0, 0, 0, 1, 0, 0 }; mesh.SharedVertexData = new VertexData(); mesh.SharedVertexData.vertexCount = 4; VertexDeclaration vertexDeclaration = mesh.SharedVertexData.vertexDeclaration; VertexBufferBinding binding = mesh.SharedVertexData.vertexBufferBinding; int offset = 0; vertexDeclaration.AddElement(0, offset, VertexElementType.Float3, VertexElementSemantic.Position); offset += VertexElement.GetTypeSize(VertexElementType.Float3); vertexDeclaration.AddElement(0, offset, VertexElementType.Float3, VertexElementSemantic.Normal); offset += VertexElement.GetTypeSize(VertexElementType.Float3); vertexDeclaration.AddElement(0, offset, VertexElementType.Float2, VertexElementSemantic.TexCoords, 0); offset += VertexElement.GetTypeSize(VertexElementType.Float2); // allocate vertex buffer HardwareVertexBuffer vertexBuffer = HardwareBufferManager.Instance.CreateVertexBuffer(offset, 4, BufferUsage.StaticWriteOnly); // set up the binding, one source only binding.SetBinding(0, vertexBuffer); vertexBuffer.WriteData(0, vertexBuffer.Size, vertices, true); subMesh.useSharedVertices = true; HardwareIndexBuffer indexBuffer = HardwareBufferManager.Instance.CreateIndexBuffer(IndexType.Size16, 6, BufferUsage.StaticWriteOnly); short[] faces = { 0, 1, 2, 0, 2, 3 }; subMesh.indexData.indexBuffer = indexBuffer; subMesh.indexData.indexCount = 6; subMesh.indexData.indexStart = 0; indexBuffer.WriteData(0, indexBuffer.Size, faces, true); mesh.BoundingBox = new AxisAlignedBox(new Vector3(-100, -100, 0), new Vector3(100, 100, 0)); mesh.BoundingSphereRadius = MathUtil.Sqrt(100 * 100 + 100 * 100); resourceList.Add(mesh.Name, mesh); }
private void LoadLevelFaces(Quake3Level q3lvl) { //----------------------------------------------------------------------- // Faces //----------------------------------------------------------------------- leafFaceGroups = new int[q3lvl.LeafFaces.Length]; Array.Copy(q3lvl.LeafFaces, 0, leafFaceGroups, 0, leafFaceGroups.Length); faceGroups = new BspStaticFaceGroup[q3lvl.Faces.Length]; // Set up index buffer // NB Quake3 indexes are 32-bit // Copy the indexes into a software area for staging numIndexes = q3lvl.NumElements + patchIndexCount; // Create an index buffer manually in system memory, allow space for patches indexes = HardwareBufferManager.Instance.CreateIndexBuffer( IndexType.Size32, numIndexes, BufferUsage.Dynamic ); // Write main indexes indexes.WriteData(0, Marshal.SizeOf(typeof(uint)) * q3lvl.NumElements, q3lvl.Elements, true); }
void UpdateBuffers() { unsafe { VertexData vertexData = staticMeshObject.VertexData; HardwareVertexBuffer vertexBuffer = vertexData.VertexBufferBinding.GetBuffer(0); Vertex *buffer = (Vertex *)vertexBuffer.Lock( HardwareBuffer.LockOptions.Normal).ToPointer(); foreach (Vertex vertex in vertices) { *buffer = vertex; buffer++; } vertexBuffer.Unlock(); } unsafe { HardwareIndexBuffer indexBuffer = staticMeshObject.IndexData.IndexBuffer; ushort * buffer = (ushort *)indexBuffer.Lock( HardwareBuffer.LockOptions.Normal).ToPointer(); foreach (int index in indices) { *buffer = (ushort)index; buffer++; } indexBuffer.Unlock(); } }
public void _notifyIndexBufferDestroyed(HardwareIndexBuffer buf) { OgrePINVOKE.HardwareBufferManagerBase__notifyIndexBufferDestroyed(swigCPtr, HardwareIndexBuffer.getCPtr(buf)); if (OgrePINVOKE.SWIGPendingException.Pending) { throw OgrePINVOKE.SWIGPendingException.Retrieve(); } }
unsafe void MakeRoad() { if (end_make == false && HeightmapTerrain.Instances[0] != null) { Vertex[] vertices = new Vertex[vertex_count]; ushort[] indices = new ushort[index_count]; for (int i = 0; i < index_count; i++) { indices[i] = (ushort)(vertex_ind[i]); } for (int i = 0; i < vertex_count; i++) { Vertex vertex = new Vertex(); Vec3 p = ((vertex_pos[i] * attached_mesh.ScaleOffset) * Rotation) + (Position + attached_mesh.PositionOffset); Vec2 mesh_vertex_pos = new Vec2(p.X, p.Y); float terrain_height = HeightmapTerrain.Instances[0].Position.Z + HeightmapTerrain.Instances[0].GetHeight(mesh_vertex_pos, false); Vec3 terrain_norm = HeightmapTerrain.Instances[0].GetNormal(mesh_vertex_pos); vertex.position = new Vec3(vertex_pos[i].X, vertex_pos[i].Y, terrain_height); vertex.normal = terrain_norm; vertex.texCoord = vertex_tc[i]; vertices[i] = vertex; } SubMesh sub_mesh = mesh.SubMeshes[0]; { HardwareVertexBuffer vertex_buffer = sub_mesh.VertexData.VertexBufferBinding.GetBuffer(0); IntPtr buffer = vertex_buffer.Lock(HardwareBuffer.LockOptions.Discard); fixed(Vertex *pvertices = vertices) { NativeUtils.CopyMemory(buffer, (IntPtr)pvertices, vertices.Length * sizeof(Vertex)); } vertex_buffer.Unlock(); } { HardwareIndexBuffer index_buffer = sub_mesh.IndexData.IndexBuffer; IntPtr buffer = index_buffer.Lock(HardwareBuffer.LockOptions.Discard); fixed(ushort *pindices = indices) { NativeUtils.CopyMemory(buffer, (IntPtr)pindices, indices.Length * sizeof(ushort)); } index_buffer.Unlock(); } if (EngineApp.Instance.ApplicationType == EngineApp.ApplicationTypes.Simulation) { end_make = true; first_init_mesh = true; } } }
private void BuildIndexBuffer() { // // create vertex and index data objects // indexData = new IndexData(); // // create hardware index buffer // int innerIndexCount = numIndicesForPlane(-outerWaveDistance, outerWaveDistance, -outerWaveDistance, outerWaveDistance, innerMetersPerSample); int outerIndexCount = numIndicesForPlane(-outerViewDistance, outerViewDistance, -outerViewDistance, -outerWaveDistance, outerMetersPerSample) + numIndicesForPlane(-outerViewDistance, -outerWaveDistance, -outerWaveDistance, outerWaveDistance, outerMetersPerSample) + numIndicesForPlane(outerWaveDistance, outerViewDistance, -outerWaveDistance, outerWaveDistance, outerMetersPerSample) + numIndicesForPlane(-outerViewDistance, outerViewDistance, outerWaveDistance, outerViewDistance, outerMetersPerSample); indexData.indexCount = innerIndexCount + outerIndexCount; // create the index buffer using the current API indexData.indexBuffer = HardwareBufferManager.Instance.CreateIndexBuffer(IndexType.Size16, indexData.indexCount, BufferUsage.StaticWriteOnly, false); // short v1, v2, v3; (unused) // grab a reference for easy access HardwareIndexBuffer idxBuffer = indexData.indexBuffer; // lock the whole index buffer IntPtr data = idxBuffer.Lock(BufferLocking.Discard); int startIndex = 0; unsafe { short *pIndex = (short *)data.ToPointer(); // make tris in a zigzag pattern (strip compatible) pIndex = fillIndexPlane(pIndex, (short)startIndex, -outerWaveDistance, outerWaveDistance, -outerWaveDistance, outerWaveDistance, innerMetersPerSample); startIndex += numVerticesForPlane(-outerWaveDistance, outerWaveDistance, -outerWaveDistance, outerWaveDistance, innerMetersPerSample); pIndex = fillIndexPlane(pIndex, (short)startIndex, -outerViewDistance, outerViewDistance, -outerViewDistance, -outerWaveDistance, outerMetersPerSample); startIndex += numVerticesForPlane(-outerViewDistance, outerViewDistance, -outerViewDistance, -outerWaveDistance, outerMetersPerSample); pIndex = fillIndexPlane(pIndex, (short)startIndex, -outerViewDistance, -outerWaveDistance, -outerWaveDistance, outerWaveDistance, outerMetersPerSample); startIndex += numVerticesForPlane(-outerViewDistance, -outerWaveDistance, -outerWaveDistance, outerWaveDistance, outerMetersPerSample); pIndex = fillIndexPlane(pIndex, (short)startIndex, outerWaveDistance, outerViewDistance, -outerWaveDistance, outerWaveDistance, outerMetersPerSample); startIndex += numVerticesForPlane(outerWaveDistance, outerViewDistance, -outerWaveDistance, outerWaveDistance, outerMetersPerSample); pIndex = fillIndexPlane(pIndex, (short)startIndex, -outerViewDistance, outerViewDistance, outerWaveDistance, outerViewDistance, outerMetersPerSample); } // unlock the buffer idxBuffer.Unlock(); }
protected XmlElement WriteFaces(SubMesh subMesh, IndexType indexType, bool isTriList) { XmlElement node = document.CreateElement("faces"); // Extract the hardware vertex buffer data into this array int[,] data = new int[subMesh.NumFaces, 3]; HardwareIndexBuffer idxBuffer = subMesh.indexData.indexBuffer; IntPtr indices = idxBuffer.Lock(BufferLocking.ReadOnly); if (isTriList) { GetTriangleListIndices(ref data, indices, indexType, subMesh.indexData.indexCount); } else { GetTriangleStripOrFanIndices(ref data, indices, indexType, subMesh.indexData.indexCount); } // unlock the buffer idxBuffer.Unlock(); int faceCount = data.GetLength(0); XmlAttribute attr; attr = document.CreateAttribute("count"); attr.Value = faceCount.ToString(); node.Attributes.Append(attr); if (isTriList) { for (int i = 0; i < faceCount; ++i) { XmlElement childNode = WriteFace(ref data, i); node.AppendChild(childNode); } } else { // triangle strip or fan if (faceCount != 0) { XmlElement childNode = WriteFace(ref data, 0); node.AppendChild(childNode); } for (int i = 1; i < faceCount; ++i) { XmlElement childNode = WriteNextFace(ref data, i); node.AppendChild(childNode); } } return(node); }
public HardwareIndexBuffer __deref__() { global::System.IntPtr cPtr = OgrePINVOKE.HardwareIndexBufferPtr___deref__(swigCPtr); HardwareIndexBuffer ret = (cPtr == global::System.IntPtr.Zero) ? null : new HardwareIndexBuffer(cPtr, false); if (OgrePINVOKE.SWIGPendingException.Pending) { throw OgrePINVOKE.SWIGPendingException.Retrieve(); } return(ret); }
public static void CopyIndexData(IndexData dst, IndexData src, Dictionary <uint, uint> vertexIdMap) { dst.indexStart = src.indexStart; dst.indexCount = src.indexCount; IndexType iType = IndexType.Size16; if (vertexIdMap.Count > ushort.MaxValue) { iType = IndexType.Size32; } HardwareIndexBuffer srcBuf = src.indexBuffer; HardwareIndexBuffer dstBuf = HardwareBufferManager.Instance.CreateIndexBuffer(iType, dst.indexCount, srcBuf.Usage); // TODO: copy the data IntPtr srcData = srcBuf.Lock(BufferLocking.ReadOnly); IntPtr dstData = dstBuf.Lock(BufferLocking.Discard); unsafe { if (srcBuf.IndexSize == 2 && dstBuf.IndexSize == 2) { ushort *srcPtr = (ushort *)srcData.ToPointer(); ushort *dstPtr = (ushort *)dstData.ToPointer(); for (int i = 0; i < srcBuf.IndexCount; ++i) { dstPtr[i] = (ushort)vertexIdMap[srcPtr[i]]; } } else if (srcBuf.IndexSize == 4 && dstBuf.IndexSize == 2) { uint * srcPtr = (uint *)srcData.ToPointer(); ushort *dstPtr = (ushort *)dstData.ToPointer(); for (int i = 0; i < srcBuf.IndexCount; ++i) { dstPtr[i] = (ushort)vertexIdMap[srcPtr[i]]; } } else if (srcBuf.IndexSize == 4 && dstBuf.IndexSize == 4) { uint *srcPtr = (uint *)srcData.ToPointer(); uint *dstPtr = (uint *)dstData.ToPointer(); for (int i = 0; i < srcBuf.IndexCount; ++i) { dstPtr[i] = vertexIdMap[srcPtr[i]]; } } else { throw new NotImplementedException(); } } dstBuf.Unlock(); srcBuf.Unlock(); dst.indexBuffer = dstBuf; }
public IEnumerator GetShadowVolumeRenderableIterator(ShadowTechnique shadowTechnique, Light light, HardwareIndexBuffer indexBuffer, bool extrudeVertices, float extrusionDistance, ulong flags) { Debug.Assert(indexBuffer != null, "Only external index buffers are supported right now"); Debug.Assert(indexBuffer.Type == IndexType.Size16, "Only 16-bit indexes supported for now"); // Calculate the object space light details var lightPos = light.GetAs4DVector(); var world2Obj = parentNode.FullTransform.Inverse(); lightPos = world2Obj * lightPos; // We need to search the edge list for silhouette edges if (this.edgeList == null) { throw new Exception("You enabled stencil shadows after the buid process! In " + "Region.GetShadowVolumeRenderableIterator"); } // Init shadow renderable list if required var init = this.shadowRenderables.Count == 0; RegionShadowRenderable esr = null; //bool updatedSharedGeomNormals = false; for (var i = 0; i < this.edgeList.EdgeGroups.Count; i++) { var group = (EdgeData.EdgeGroup) this.edgeList.EdgeGroups[i]; if (init) { // Create a new renderable, create a separate light cap if // we're using a vertex program (either for this model, or // for extruding the shadow volume) since otherwise we can // get depth-fighting on the light cap esr = new RegionShadowRenderable(this, indexBuffer, group.vertexData, this.vertexProgramInUse || !extrudeVertices); this.shadowRenderables.Add(esr); } else { esr = (RegionShadowRenderable)this.shadowRenderables[i]; } // Extrude vertices in software if required if (extrudeVertices) { ExtrudeVertices(esr.PositionBuffer, group.vertexData.vertexCount, lightPos, extrusionDistance); } } return((IEnumerator)this.shadowRenderables); }
public static void GetSubmeshIndexData(out int[,] indices, IndexData indexData) { HardwareIndexBuffer idxBuffer = indexData.indexBuffer; IndexType indexType = IndexType.Size16; if ((idxBuffer.Size / indexData.indexCount) != 2) { Debug.Assert(false, "Unexpected index buffer size"); indexType = IndexType.Size32; } Debug.Assert(indexData.indexCount % 3 == 0); indices = new int[indexData.indexCount / 3, 3]; ReadBuffer(idxBuffer, indexData.indexCount, indexType, ref indices); }
private void CreateMesh() { DetachMeshFromEntity(); DestroyMesh(); int maxVertexCount = tesselation * tesselation; int maxIndexCount = (tesselation - 1) * (tesselation - 1) * 6; string meshName = MeshManager.Instance.GetUniqueName("DynamicSinusoidSurface"); mesh = MeshManager.Instance.CreateManual(meshName); SubMesh subMesh = mesh.CreateSubMesh(); subMesh.UseSharedVertices = false; //init vertexData VertexDeclaration declaration = subMesh.VertexData.VertexDeclaration; declaration.AddElement(0, 0, VertexElementType.Float3, VertexElementSemantic.Position); declaration.AddElement(0, 12, VertexElementType.Float3, VertexElementSemantic.Normal); declaration.AddElement(0, 24, VertexElementType.Float2, VertexElementSemantic.TextureCoordinates, 0); //declaration.AddElement( 0, 32, VertexElementType.Float4, VertexElementSemantic.Tangent, 0 ); HardwareBuffer.Usage usage = HardwareBuffer.Usage.DynamicWriteOnly;//HardwareBuffer.Usage.StaticWriteOnly; HardwareVertexBuffer vertexBuffer = HardwareBufferManager.Instance.CreateVertexBuffer( Marshal.SizeOf(typeof(Vertex)), maxVertexCount, usage); subMesh.VertexData.VertexBufferBinding.SetBinding(0, vertexBuffer, true); subMesh.VertexData.VertexCount = maxVertexCount; HardwareIndexBuffer indexBuffer = HardwareBufferManager.Instance.CreateIndexBuffer( HardwareIndexBuffer.IndexType._16Bit, maxIndexCount, usage); subMesh.IndexData.SetIndexBuffer(indexBuffer, true); subMesh.IndexData.IndexCount = maxIndexCount; //set material subMesh.MaterialName = "DynamicSinusoidSurface"; //set mesh gabarites Bounds bounds = new Bounds(-Scale / 2, Scale / 2); mesh.SetBoundsAndRadius(bounds, bounds.GetRadius()); }
public virtual void CreateIndexBuffer(uint triaglecount, HardwareIndexBuffer.IndexType itype, HardwareBuffer.Usage usage, bool useShadowBuffer) { mvbuf.Unlock(); mTriagleCount = triaglecount; mIndexType = itype; mSubMesh.vertexData.vertexBufferBinding.SetBinding(0, mvbuf); mSubMesh.indexData.indexCount = mTriagleCount * 3; HardwareIndexBufferSharedPtr ibuf = HardwareBufferManager.Singleton .CreateIndexBuffer(mIndexType, mTriagleCount * 3, usage, useShadowBuffer); mSubMesh.indexData.indexBuffer = ibuf; unsafe { pIBuffStart = ibuf.Lock(HardwareBuffer.LockOptions.HBL_DISCARD); } }
void CreateMesh() { string meshName = MeshManager.Instance.GetUniqueName("DynamicMesh"); mesh = MeshManager.Instance.CreateManual(meshName); //set mesh gabarites Bounds bounds = new Bounds(new Vec3(-.1f, -.5f, -.5f), new Vec3(.1f, .5f, .5f)); mesh.SetBoundsAndRadius(bounds, bounds.GetRadius()); SubMesh subMesh = mesh.CreateSubMesh(); subMesh.UseSharedVertices = false; int maxVertices = (Type.GridSize.X + 1) * (Type.GridSize.Y + 1); int maxIndices = Type.GridSize.X * Type.GridSize.Y * 6; //init vertexData VertexDeclaration declaration = subMesh.VertexData.VertexDeclaration; declaration.AddElement(0, 0, VertexElementType.Float3, VertexElementSemantic.Position); declaration.AddElement(0, 12, VertexElementType.Float3, VertexElementSemantic.Normal); declaration.AddElement(0, 24, VertexElementType.Float2, VertexElementSemantic.TextureCoordinates, 0); VertexBufferBinding bufferBinding = subMesh.VertexData.VertexBufferBinding; HardwareVertexBuffer vertexBuffer = HardwareBufferManager.Instance.CreateVertexBuffer( 32, maxVertices, HardwareBuffer.Usage.DynamicWriteOnly); bufferBinding.SetBinding(0, vertexBuffer, true); //init indexData HardwareIndexBuffer indexBuffer = HardwareBufferManager.Instance.CreateIndexBuffer( HardwareIndexBuffer.IndexType._16Bit, maxIndices, HardwareBuffer.Usage.DynamicWriteOnly); subMesh.IndexData.SetIndexBuffer(indexBuffer, true); //set material subMesh.MaterialName = Type.MaterialName; needUpdateVertices = true; needUpdateIndices = true; }
/// <summary> /// Tells the system to build the mesh relating to the surface into externally created buffers. /// </summary> /// <remarks> /// The VertexDeclaration of the vertex buffer must be identical to the one passed into /// <see cref="DefineSurface(Array, VertexDeclaration, int, int)"/>. In addition, there must be enough space in the buffer to /// accommodate the patch at full detail level; you should check <see cref="RequiredVertexCount"/> /// and <see cref="RequiredIndexCount"/> to determine this. This method does not create an internal /// mesh for this patch and so GetMesh will return null if you call it after building the /// patch this way. /// </remarks> /// <param name="destVertexBuffer">The destination vertex buffer in which to build the patch.</param> /// <param name="vertexStart">The offset at which to start writing vertices for this patch.</param> /// <param name="destIndexBuffer">The destination index buffer in which to build the patch.</param> /// <param name="indexStart">The offset at which to start writing indexes for this patch.</param> public void Build(HardwareVertexBuffer destVertexBuffer, int vertexStart, HardwareIndexBuffer destIndexBuffer, int indexStart) { if (this.controlPoints.Count == 0) { return; } this.vertexBuffer = destVertexBuffer; this.vertexOffset = vertexStart; this.indexBuffer = destIndexBuffer; this.indexOffset = indexStart; // lock just the region we are interested in var lockedBuffer = this.vertexBuffer.Lock(this.vertexOffset * this.declaration.GetVertexSize(0), this.requiredVertexCount * this.declaration.GetVertexSize(0), BufferLocking.NoOverwrite); DistributeControlPoints(lockedBuffer); // subdivide the curves to the max // Do u direction first, so need to step over v levels not done yet var vStep = 1 << this.maxVLevel; var uStep = 1 << this.maxULevel; // subdivide this row in u for (var v = 0; v < this.meshHeight; v += vStep) { SubdivideCurve(lockedBuffer, v * this.meshWidth, uStep, this.meshWidth / uStep, this.uLevel); } // Now subdivide in v direction, this time all the u direction points are there so no step for (var u = 0; u < this.meshWidth; u++) { SubdivideCurve(lockedBuffer, u, vStep * this.meshWidth, this.meshHeight / vStep, this.vLevel); } // don't forget to unlock! this.vertexBuffer.Unlock(); // Make triangles from mesh at this current level of detail MakeTriangles(); }
/// <summary> /// Populate the index buffer with the information in the data array /// </summary> /// <param name="idxBuffer">HardwareIndexBuffer to populate</param> /// <param name="indexCount">the number of indices</param> /// <param name="indexType">the type of index (e.g. IndexType.Size16)</param> /// <param name="data">the data to fill the buffer</param> internal void FillBuffer(HardwareIndexBuffer idxBuffer, int indexCount, IndexType indexType, int[ , ] data) { int faceCount = data.GetLength(0); int count = data.GetLength(1); IntPtr indices = idxBuffer.Lock(BufferLocking.Discard); if (indexType == IndexType.Size32) { // read the ints into the buffer data unsafe { int *pInts = (int *)indices.ToPointer(); for (int i = 0; i < faceCount; ++i) { for (int j = 0; j < count; ++j) { Debug.Assert(i * count + j < indexCount, "Wrote off end of index buffer"); pInts[i * count + j] = data[i, j]; } } } } else { // read the shorts into the buffer data unsafe { short *pShorts = (short *)indices.ToPointer(); for (int i = 0; i < faceCount; ++i) { for (int j = 0; j < count; ++j) { Debug.Assert(i * count + j < indexCount, "Wrote off end of index buffer"); pShorts[i * count + j] = (short)data[i, j]; } } } } // unlock the buffer to commit idxBuffer.Unlock(); }
private static void ReadBuffer(HardwareIndexBuffer idxBuffer, int maxIndex, IndexType indexType, ref int[,] data) { IntPtr indices = idxBuffer.Lock(BufferLocking.ReadOnly); int faceCount = data.GetLength(0); if (indexType == IndexType.Size32) { // read the ints from the buffer data unsafe { int *pInts = (int *)indices.ToPointer(); for (int i = 0; i < faceCount; ++i) { for (int j = 0; j < 3; ++j) { Debug.Assert(i * 3 + j < maxIndex, "Read off end of index buffer"); data[i, j] = pInts[i * 3 + j]; } } } } else { // read the shorts from the buffer data unsafe { short *pShorts = (short *)indices.ToPointer(); for (int i = 0; i < faceCount; ++i) { for (int j = 0; j < 3; ++j) { Debug.Assert(i * 3 + j < maxIndex, "Read off end of index buffer"); data[i, j] = pShorts[i * 3 + j]; } } } } // unlock the buffer idxBuffer.Unlock(); }
void UpdateMeshIndices() { if (mesh == null) { return; } SubMesh subMesh = mesh.SubMeshes[0]; HardwareIndexBuffer indexBuffer = subMesh.IndexData.IndexBuffer; unsafe { ushort *buffer = (ushort *)indexBuffer.Lock(HardwareBuffer.LockOptions.Normal).ToPointer(); subMesh.IndexData.IndexCount = 0; for (int y = 0; y < Type.GridSize.Y; y++) { for (int x = 0; x < Type.GridSize.X; x++) { bool enableCell = World.Instance.Random.Next(2) == 0; if (enableCell) { *buffer = (ushort)((Type.GridSize.X + 1) * y + x); buffer++; *buffer = (ushort)((Type.GridSize.X + 1) * y + x + 1); buffer++; *buffer = (ushort)((Type.GridSize.X + 1) * (y + 1) + x + 1); buffer++; *buffer = (ushort)((Type.GridSize.X + 1) * (y + 1) + x + 1); buffer++; *buffer = (ushort)((Type.GridSize.X + 1) * (y + 1) + x); buffer++; *buffer = (ushort)((Type.GridSize.X + 1) * y + x); buffer++; subMesh.IndexData.IndexCount += 6; } } } indexBuffer.Unlock(); } }
protected void AddSubmeshIndexData(IndexData indexData) { HardwareIndexBuffer indexBuffer = indexData.indexBuffer; IntPtr indices = indexBuffer.Lock(BufferLocking.ReadOnly); unsafe { if (indexBuffer.IndexSize == sizeof(ushort)) { ushort *pIdx = (ushort *)indices.ToPointer(); for (int i = 0; i < indexData.indexCount; ++i) { uint index = pIdx[indexData.indexStart + i]; if (!vertexIdMap.ContainsKey(index)) { uint nextId = (uint)vertexIdMap.Count; vertexIdMap[index] = nextId; } } } else if (indexBuffer.IndexSize == sizeof(uint)) { uint *pIdx = (uint *)indices.ToPointer(); for (int i = 0; i < indexData.indexCount; ++i) { uint index = pIdx[indexData.indexStart + i]; if (!vertexIdMap.ContainsKey(index)) { uint nextId = (uint)vertexIdMap.Count; vertexIdMap[index] = nextId; } } } else { Debug.Assert(false, "Invalid index buffer index size"); } } indexBuffer.Unlock(); }
void ParsingMesh() { if (mesh != null) { mesh.SubMeshes[0].VertexData.GetSomeGeometry(ref vertex_pos, ref vertex_norm, ref vertex_tc); mesh.SubMeshes[0].IndexData.GetIndices(ref vertex_ind); vertex_count = mesh.SubMeshes[0].VertexData.VertexCount; index_count = mesh.SubMeshes[0].IndexData.IndexCount; SubMesh sub_mesh = mesh.SubMeshes[0]; sub_mesh.UseSharedVertices = false; HardwareBuffer.Usage usage = HardwareBuffer.Usage.DynamicWriteOnly; HardwareVertexBuffer vertexBuffer = HardwareBufferManager.Instance.CreateVertexBuffer( Marshal.SizeOf(typeof(Vertex)), vertex_count, usage); sub_mesh.VertexData.VertexBufferBinding.SetBinding(0, vertexBuffer, true); sub_mesh.VertexData.VertexCount = vertex_count; HardwareIndexBuffer indexBuffer = HardwareBufferManager.Instance.CreateIndexBuffer( HardwareIndexBuffer.IndexType._16Bit, index_count, usage); sub_mesh.IndexData.SetIndexBuffer(indexBuffer, true); sub_mesh.IndexData.IndexCount = index_count; } }
/// <summary> /// /// </summary> protected void Initialize() { Vector3 ax = Vector3.Zero, ay = Vector3.Zero, az = Vector3.Zero; int x = 0; Quaternion q = Quaternion.Identity; this.things.Clear(); this.orbits.Clear(); for (x = 0; x < this.count; x++) { ax = new Vector3(GenerateRandomFloat(), GenerateRandomFloat(), GenerateRandomFloat()); ay = new Vector3(GenerateRandomFloat(), GenerateRandomFloat(), GenerateRandomFloat()); az = ax.Cross(ay); ay = az.Cross(ax); ax.Normalize(); ay.Normalize(); az.Normalize(); q = Quaternion.FromAxes(ax, ay, az); this.things.Add(q); ax = new Vector3(GenerateRandomFloat(), GenerateRandomFloat(), GenerateRandomFloat()); ay = new Vector3(GenerateRandomFloat(), GenerateRandomFloat(), GenerateRandomFloat()); az = ax.Cross(ay); ay = az.Cross(ax); ax.Normalize(); ay.Normalize(); az.Normalize(); q = Quaternion.FromAxes(ax, ay, az); this.orbits.Add(q); } int nVertices = this.count * 4; var indexData = new IndexData(); var vertexData = new VertexData(); //Quads var faces = new short[this.count * 6]; for (x = 0; x < this.count; x++) { faces[x * 6 + 0] = (short)(x * 4 + 0); faces[x * 6 + 1] = (short)(x * 4 + 1); faces[x * 6 + 2] = (short)(x * 4 + 2); faces[x * 6 + 3] = (short)(x * 4 + 0); faces[x * 6 + 4] = (short)(x * 4 + 2); faces[x * 6 + 5] = (short)(x * 4 + 3); } vertexData.vertexStart = 0; vertexData.vertexCount = nVertices; VertexDeclaration decl = vertexData.vertexDeclaration; VertexBufferBinding bind = vertexData.vertexBufferBinding; int offset = 0; offset += decl.AddElement(0, offset, VertexElementType.Float3, VertexElementSemantic.Position).Size; this.vertexBuffer = HardwareBufferManager.Instance.CreateVertexBuffer(decl.Clone(0), nVertices, BufferUsage.DynamicWriteOnly); bind.SetBinding(0, this.vertexBuffer); HardwareIndexBuffer indexBuffer = HardwareBufferManager.Instance.CreateIndexBuffer(IndexType.Size16, this.count * 6, BufferUsage.StaticWriteOnly); indexData.indexBuffer = indexBuffer; indexData.indexStart = 0; indexData.indexCount = this.count * 6; indexBuffer.WriteData(0, indexBuffer.Size, faces, true); faces = null; renderOperation.operationType = OperationType.TriangleList; renderOperation.indexData = indexData; renderOperation.vertexData = vertexData; renderOperation.useIndices = true; }
private unsafe void UpdateGeometry(float time) { //generate geometry Vertex[] vertices = new Vertex[tesselation * tesselation]; ushort[] indices = new ushort[(tesselation - 1) * (tesselation - 1) * 6]; { //vertices int vertexPosition = 0; for (int y = 0; y < tesselation; y++) { for (int x = 0; x < tesselation; x++) { Vertex vertex = new Vertex(); Vec2 pos2 = new Vec2( (float)x / (float)(tesselation - 1) - .5f, (float)y / (float)(tesselation - 1) - .5f); float posZ = MathFunctions.Sin(pos2.Length() * 30 - time * 2) / 2; MathFunctions.Clamp(ref posZ, -5f, .5f); vertex.position = new Vec3(pos2.X, pos2.Y, posZ) * Scale; vertex.normal = Vec3.Zero; vertex.texCoord = new Vec2(pos2.X + .5f, pos2.Y + .5f); //vertex.tangents = Vec4.Zero; vertices[vertexPosition] = vertex; vertexPosition++; } } //indices int indexPosition = 0; for (int y = 0; y < tesselation - 1; y++) { for (int x = 0; x < tesselation - 1; x++) { indices[indexPosition] = (ushort)(tesselation * y + x); indexPosition++; indices[indexPosition] = (ushort)(tesselation * y + x + 1); indexPosition++; indices[indexPosition] = (ushort)(tesselation * (y + 1) + x + 1); indexPosition++; indices[indexPosition] = (ushort)(tesselation * (y + 1) + x + 1); indexPosition++; indices[indexPosition] = (ushort)(tesselation * (y + 1) + x); indexPosition++; indices[indexPosition] = (ushort)(tesselation * y + x); indexPosition++; } } //calculate vertex normals fixed(Vertex *pVertices = vertices) { int triangleCount = indices.Length / 3; for (int n = 0; n < triangleCount; n++) { int index0 = indices[n * 3 + 0]; int index1 = indices[n * 3 + 1]; int index2 = indices[n * 3 + 2]; Vec3 pos0 = pVertices[index0].position; Vec3 pos1 = pVertices[index1].position; Vec3 pos2 = pVertices[index2].position; Vec3 normal = Vec3.Cross(pos1 - pos0, pos2 - pos0); normal.Normalize(); pVertices[index0].normal += normal; pVertices[index1].normal += normal; pVertices[index2].normal += normal; } //normalize for (int n = 0; n < vertices.Length; n++) { pVertices[n].normal = pVertices[n].normal.GetNormalize(); } } } SubMesh subMesh = mesh.SubMeshes[0]; //copy data to vertex buffer { HardwareVertexBuffer vertexBuffer = subMesh.VertexData.VertexBufferBinding.GetBuffer(0); IntPtr buffer = vertexBuffer.Lock(HardwareBuffer.LockOptions.Discard); fixed(Vertex *pVertices = vertices) { NativeUtils.CopyMemory(buffer, (IntPtr)pVertices, vertices.Length * sizeof(Vertex)); } vertexBuffer.Unlock(); } //copy data to index buffer { HardwareIndexBuffer indexBuffer = subMesh.IndexData.IndexBuffer; IntPtr buffer = indexBuffer.Lock(HardwareBuffer.LockOptions.Discard); fixed(ushort *pIndices = indices) { NativeUtils.CopyMemory(buffer, (IntPtr)pIndices, indices.Length * sizeof(ushort)); } indexBuffer.Unlock(); } ////calculate mesh tangent vectors //mesh.BuildTangentVectors( VertexElementSemantic.Tangent, 0, 0, true ); }
public RegionShadowRenderable(Region parent, HardwareIndexBuffer indexBuffer, VertexData vertexData, bool createSeparateLightCap) : this(parent, indexBuffer, vertexData, createSeparateLightCap, false) { }
public RegionShadowRenderable(Region parent, HardwareIndexBuffer indexBuffer, VertexData vertexData, bool createSeparateLightCap, bool isLightCap) { throw new NotImplementedException(); }
/// <summary> /// Split some shared geometry into dedicated geometry. /// </summary> /// <param name="vd"> </param> /// <param name="id"> </param> /// <param name="targetGeomLink"> </param> public void SplitGeometry(VertexData vd, IndexData id, ref SubMeshLodGeometryLink targetGeomLink) { // Firstly we need to scan to see how many vertices are being used // and while we're at it, build the remap we can use later bool use32bitIndexes = id.indexBuffer.Type == IndexType.Size32; var indexRemap = new Dictionary <int, int>(); if (use32bitIndexes) { var p32 = id.indexBuffer.Lock(id.indexStart, id.indexCount * id.indexBuffer.IndexSize, BufferLocking.ReadOnly); BuildIndexRemap(p32, id.indexCount, ref indexRemap); id.indexBuffer.Unlock(); } else { var p16 = id.indexBuffer.Lock(id.indexStart, id.indexCount * id.indexBuffer.IndexSize, BufferLocking.ReadOnly); BuildIndexRemap(p16, id.indexCount, ref indexRemap); id.indexBuffer.Unlock(); } if (indexRemap.Count == vd.vertexCount) { // ha, complete usage after all targetGeomLink.vertexData = vd; targetGeomLink.indexData = id; return; } // Create the new vertex data records targetGeomLink.vertexData = vd.Clone(false); // Convenience VertexData newvd = targetGeomLink.vertexData; //IndexData* newid = targetGeomLink->indexData; // Update the vertex count newvd.vertexCount = indexRemap.Count; int numvbufs = vd.vertexBufferBinding.BindingCount; // Copy buffers from old to new for (int b = 0; b < numvbufs; ++b) { // Lock old buffer HardwareVertexBuffer oldBuf = vd.vertexBufferBinding.GetBuffer((short)b); // Create new buffer HardwareVertexBuffer newBuf = HardwareBufferManager.Instance.CreateVertexBuffer( oldBuf.VertexDeclaration, indexRemap.Count, BufferUsage.Static); // rebind newvd.vertexBufferBinding.SetBinding((short)b, newBuf); // Copy all the elements of the buffer across, by iterating over // the IndexRemap which describes how to move the old vertices // to the new ones. By nature of the map the remap is in order of // indexes in the old buffer, but note that we're not guaranteed to // address every vertex (which is kinda why we're here) var pSrcBase = oldBuf.Lock(BufferLocking.ReadOnly); var pDstBase = newBuf.Lock(BufferLocking.Discard); int vertexSize = oldBuf.VertexSize; // Buffers should be the same size Debug.Assert(vertexSize == newBuf.VertexSize); foreach (var r in indexRemap) { Debug.Assert(r.Key < oldBuf.VertexCount); Debug.Assert(r.Value < newBuf.VertexCount); var pSrc = pSrcBase + r.Key * vertexSize; var pDst = pDstBase + r.Value * vertexSize; var pSrcPtr = pSrc; var pDstPtr = pDst; Memory.Copy(pDstPtr, pSrcPtr, vertexSize); } // unlock oldBuf.Unlock(); newBuf.Unlock(); } // Now create a new index buffer HardwareIndexBuffer ibuf = HardwareBufferManager.Instance.CreateIndexBuffer(id.indexBuffer.Type, id.indexCount, BufferUsage.Static); if (use32bitIndexes) { uint *pSrc32, pDst32; pSrc32 = (uint *)id.indexBuffer.Lock( id.indexStart, id.indexCount * id.indexBuffer.IndexSize, BufferLocking.ReadOnly); pDst32 = (uint *)ibuf.Lock(BufferLocking.Discard); RemapIndexes(pSrc32, pDst32, ref indexRemap, id.indexCount); id.indexBuffer.Unlock(); ibuf.Unlock(); } else { ushort *pSrc16, pDst16; pSrc16 = (ushort *)id.indexBuffer.Lock( id.indexStart, id.indexCount * id.indexBuffer.IndexSize, BufferLocking.ReadOnly); pDst16 = (ushort *)ibuf.Lock(BufferLocking.Discard); RemapIndexes(pSrc16, pDst16, ref indexRemap, id.indexCount); id.indexBuffer.Unlock(); ibuf.Unlock(); } targetGeomLink.indexData = new IndexData(); targetGeomLink.indexData.indexStart = 0; targetGeomLink.indexData.indexCount = id.indexCount; targetGeomLink.indexData.indexBuffer = ibuf; // Store optimised geometry for deallocation later var optGeom = new OptimisedSubMeshGeometry(); optGeom.indexData = targetGeomLink.indexData; optGeom.vertexData = targetGeomLink.vertexData; mOptimisedSubMeshGeometryList.Add(optGeom); }
protected void ReadFaces(XmlNode node, SubMesh subMesh, IndexType indexType) { uint faceCount = uint.Parse(node.Attributes["count"].Value); int faceIndex = 0; int[,] data = new int[faceCount, 3]; foreach (XmlNode childNode in node.ChildNodes) { switch (childNode.Name) { case "face": ReadFace(childNode, data, faceIndex++); break; default: DebugMessage(childNode); break; } } int count = data.GetLength(1); subMesh.indexData.indexStart = 0; subMesh.indexData.indexCount = data.GetLength(0) * data.GetLength(1); HardwareIndexBuffer idxBuffer = null; // create the index buffer idxBuffer = HardwareBufferManager.Instance. CreateIndexBuffer( indexType, subMesh.indexData.indexCount, mesh.IndexBufferUsage, mesh.UseIndexShadowBuffer); IntPtr indices = idxBuffer.Lock(BufferLocking.Discard); if (indexType == IndexType.Size32) { // read the ints into the buffer data unsafe { int *pInts = (int *)indices.ToPointer(); for (int i = 0; i < faceCount; ++i) { for (int j = 0; j < count; ++j) { Debug.Assert(i * count + j < subMesh.indexData.indexCount, "Wrote off end of index buffer"); pInts[i * count + j] = data[i, j]; } } } } else { // read the shorts into the buffer data unsafe { short *pShorts = (short *)indices.ToPointer(); for (int i = 0; i < faceCount; ++i) { for (int j = 0; j < count; ++j) { Debug.Assert(i * count + j < subMesh.indexData.indexCount, "Wrote off end of index buffer"); pShorts[i * count + j] = (short)data[i, j]; } } } } // unlock the buffer to commit idxBuffer.Unlock(); // save the index buffer subMesh.indexData.indexBuffer = idxBuffer; }
internal static global::System.Runtime.InteropServices.HandleRef getCPtr(HardwareIndexBuffer obj) { return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr); }
void CreateDecal() { Bounds bounds = Bounds.Cleared; foreach (Vertex vertex in vertices) { bounds.Add(vertex.position); } VertexData vertexData = new VertexData(); IndexData indexData = new IndexData(); //init vertexData VertexDeclaration declaration = vertexData.VertexDeclaration; declaration.AddElement(0, 0, VertexElementType.Float3, VertexElementSemantic.Position); declaration.AddElement(0, 12, VertexElementType.Float3, VertexElementSemantic.Normal); declaration.AddElement(0, 24, VertexElementType.Float2, VertexElementSemantic.TextureCoordinates, 0); declaration.AddElement(0, 32, VertexElementType.Float3, VertexElementSemantic.Tangent); VertexBufferBinding bufferBinding = vertexData.VertexBufferBinding; HardwareVertexBuffer vertexBuffer = HardwareBufferManager.Instance.CreateVertexBuffer( 44, vertices.Length, HardwareBuffer.Usage.StaticWriteOnly); bufferBinding.SetBinding(0, vertexBuffer, true); vertexData.VertexCount = vertices.Length; //init indexData Trace.Assert(vertices.Length < 65536, "Decal: vertices.Length < 65536"); HardwareIndexBuffer indexBuffer = HardwareBufferManager.Instance.CreateIndexBuffer( HardwareIndexBuffer.IndexType._16Bit, indices.Length, HardwareBuffer.Usage.StaticWriteOnly); indexData.SetIndexBuffer(indexBuffer, true); indexData.IndexCount = indices.Length; //init material Material material = null; shaderBaseMaterial = HighLevelMaterialManager.Instance. GetMaterialByName(sourceMaterialName) as ShaderBaseMaterial; //only default shader technique for ShaderBase material if (shaderBaseMaterial != null && !shaderBaseMaterial.IsDefaultTechniqueCreated()) { shaderBaseMaterial = null; } if (shaderBaseMaterial != null) { //ShaderBase material material = shaderBaseMaterial.BaseMaterial; } else { //standard material or fallback ShaderBase technique Material sourceMaterial = MaterialManager.Instance.GetByName(sourceMaterialName); if (sourceMaterial != null) { //clone standard material clonedStandardMaterial = MaterialManager.Instance.Clone(sourceMaterial, MaterialManager.Instance.GetUniqueName(sourceMaterialName + "_Cloned")); material = clonedStandardMaterial; } } staticMeshObject = SceneManager.Instance.CreateStaticMeshObject(bounds + Position, Position, Quat.Identity, new Vec3(1, 1, 1), true, material, vertexData, indexData, true); staticMeshObject.AddToRenderQueue += StaticMeshObject_AddToRenderQueue; UpdateBuffers(); }
public virtual void CreateIndexBufferForTriStrip(uint indexcount, HardwareIndexBuffer.IndexType itype, HardwareBuffer.Usage usage) { mvbuf.Unlock(); mTriagleCount = 0; mIndexType = itype; mSubMesh.vertexData.vertexBufferBinding.SetBinding(0, mvbuf); mSubMesh.indexData.indexCount = indexcount; HardwareIndexBufferSharedPtr ibuf = HardwareBufferManager.Singleton .CreateIndexBuffer(mIndexType, indexcount, usage, false); mSubMesh.indexData.indexBuffer = ibuf; mSubMesh.operationType = RenderOperation.OperationTypes.OT_TRIANGLE_STRIP; unsafe { pIBuffStart = ibuf.Lock(HardwareBuffer.LockOptions.HBL_DISCARD); pIBuffLastPos = pIBuffStart; } }
public virtual void CreateIndexBuffer(uint triaglecount, HardwareIndexBuffer.IndexType itype, HardwareBuffer.Usage usage) { CreateIndexBuffer(triaglecount, itype, usage, false); }
public override IEnumerator GetShadowVolumeRenderableEnumerator(ShadowTechnique technique, Light light, HardwareIndexBuffer indexBuffer, bool extrudeVertices, float extrusionDistance, int flags) { return(dummyList.GetEnumerator()); }