void setVertices(Vertex[] arr) { //頂点バッファの作成 var size = Marshal.SizeOf(typeof(Vertex)); if (_vertexBuffer == null || _vertexCount < arr.Length) { if (null != _vertexBuffer) { _vertexBuffer.Dispose(); } _vertexBuffer = new Buffer(_device, new BufferDescription() { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, SizeInBytes = size * arr.Length, Usage = ResourceUsage.Dynamic }); } var ds = _vertexBuffer.Map(MapMode.WriteDiscard); ds.WriteRange(arr); _vertexBuffer.Unmap(); }
private void BringOverlayGeometryIntoDeviceBuffers(D3D10OverlayContext overlayGeometry) { Device device = _cachedDevice; if (device == null || device.IsDisposed) { return; } // ------------------ Triangle buffer ------------------------------------ { var buf = (PositionColorIndexedTriangleBuffer)overlayGeometry.PositionColorIndexedTriangleBuffers; var vertexBuffer = Buffer.Create <float>(device, buf.VertexStream, new BufferDescription() { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = buf.VertexStreamLength, Usage = ResourceUsage.Default }); var indexBuffer = Buffer.Create <int>(device, buf.IndexStream, new BufferDescription() { BindFlags = BindFlags.IndexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = buf.IndexStreamLength, Usage = ResourceUsage.Default }); var indexCount = buf.TriangleCount * 3; var oldBuffer = System.Threading.Interlocked.Exchange( ref _overlayGeometryTriangleDeviceBuffer, new VertexAndIndexDeviceBufferNoMaterial(vertexBuffer: vertexBuffer, vertexCount: buf.VertexCount, indexBuffer: indexBuffer, indexCount: indexCount)); Disposer.RemoveAndDispose(ref oldBuffer); } // ------------------ Line list buffer ------------------------------------ { var buf = (PositionColorLineListBuffer)overlayGeometry.PositionColorLineListBuffer; var vertexBuffer = Buffer.Create <float>(device, buf.VertexStream, new BufferDescription() { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = buf.VertexStreamLength, Usage = ResourceUsage.Default }); var oldBuffer = System.Threading.Interlocked.Exchange( ref _overlayGeometryLineListBuffer, new VertexBufferNoMaterial(vertexBuffer: vertexBuffer, vertexCount: buf.VertexCount)); oldBuffer?.Dispose(); } }
/* * public void RenderSoftBodyTextured(SoftBody softBody) * { * if (!(softBody.UserObject is Array)) * return; * * object[] userObjArr = softBody.UserObject as object[]; * FloatArray vertexBuffer = userObjArr[0] as FloatArray; * IntArray indexBuffer = userObjArr[1] as IntArray; * * int vertexCount = (vertexBuffer.Count / 8); * * if (vertexCount > 0) * { * int faceCount = indexBuffer.Count / 2; * * bool index32 = vertexCount > 65536; * * Mesh mesh = new Mesh(device, faceCount, vertexCount, * MeshFlags.SystemMemory | (index32 ? MeshFlags.Use32Bit : 0), * VertexFormat.Position | VertexFormat.Normal | VertexFormat.Texture1); * * SlimDX.DataStream indices = mesh.LockIndexBuffer(LockFlags.Discard); * if (index32) * { * foreach (int i in indexBuffer) * indices.Write(i); * } * else * { * foreach (int i in indexBuffer) * indices.Write((ushort)i); * } * mesh.UnlockIndexBuffer(); * * SlimDX.DataStream verts = mesh.LockVertexBuffer(LockFlags.Discard); * foreach (float f in vertexBuffer) * verts.Write(f); * mesh.UnlockVertexBuffer(); * * mesh.ComputeNormals(); * mesh.DrawSubset(0); * mesh.Dispose(); * } * } * */ public static Buffer CreateScreenQuad(Device device) { Buffer vertexBuffer; BufferDescription vertexBufferDesc = new BufferDescription() { SizeInBytes = sizeof(float) * 5 * 4, Usage = ResourceUsage.Default, BindFlags = BindFlags.VertexBuffer, }; using (var data = new SharpDX.DataStream(vertexBufferDesc.SizeInBytes, false, true)) { data.Write(new Vector3(0.5f, 0.5f, 0)); data.Write(new Vector2(1, 0)); data.Write(new Vector3(0.5f, -0.5f, 0)); data.Write(new Vector2(1, 1)); data.Write(new Vector3(-0.5f, 0.5f, 0)); data.Write(new Vector2(0, 0)); data.Write(new Vector3(-0.5f, -0.5f, 0)); data.Write(new Vector2(0, 1)); data.Position = 0; vertexBuffer = new Buffer(device, data, vertexBufferDesc); } return(vertexBuffer); }
// Used with soft bodies public void SetDynamicVertexBuffer(Device device, Vector3[] vectors) { if (VertexBuffer != null && VertexCount * 2 == vectors.Length) { // Update existing buffer using (var data = VertexBuffer.Map(MapMode.WriteDiscard)) { data.WriteRange(vectors, 0, vectors.Length); VertexBuffer.Unmap(); } } else { // Create new buffer if (VertexBuffer != null) VertexBuffer.Dispose(); BufferDescription vertexBufferDesc = new BufferDescription() { SizeInBytes = Marshal.SizeOf(typeof(Vector3)) * vectors.Length, Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.Write }; using (var data = new DataStream(vertexBufferDesc.SizeInBytes, false, true)) { data.WriteRange(vectors); data.Position = 0; VertexBuffer = new Buffer(device, data, vertexBufferDesc); } BufferBindings[0] = new VertexBufferBinding(VertexBuffer, 24, 0); } }
public void Create(Device1 device) { PrimitiveTopology = PrimitiveTopology.TriangleList; VertexStride = Marshal.SizeOf <VertexPosColNormTex>(); var verts = new List <VertexPosColNormTex>(); var importer = new AssimpContext(); var s = importer.GetSupportedImportFormats(); if (!importer.IsImportFormatSupported(Path.GetExtension(_FileName))) { throw new ArgumentException( "Model format " + Path.GetExtension(_FileName) + " is not supported! Cannot load {1}", "filename"); } var model = importer.ImportFile(_FileName, PostProcessSteps.GenerateSmoothNormals | PostProcessSteps.CalculateTangentSpace | PostProcessSteps.Triangulate); foreach (var mesh in model.Meshes) { for (int i = 0; i < mesh.VertexCount; i++) { var pos = new Vector3(mesh.Vertices[i].X, mesh.Vertices[i].Y, mesh.Vertices[i].Z); var color = Color.AliceBlue; var norm = new Vector3(mesh.Normals[i].X, mesh.Normals[i].Y, mesh.Normals[i].Z); var tx = new Vector2(mesh.TextureCoordinateChannels[0][i].X, -mesh.TextureCoordinateChannels[0][i].Y); verts.Add(new VertexPosColNormTex(pos, color, norm, tx)); } var bufferDesc = new BufferDescription { Usage = ResourceUsage.Immutable, BindFlags = BindFlags.VertexBuffer, SizeInBytes = VertexStride * verts.Count, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }; VertexBuffer = new Buffer(device, DataStream.Create(verts.ToArray(), false, false), bufferDesc); IndexCount = mesh.GetIndices().Length; //buffer creations bufferDesc = new BufferDescription { Usage = ResourceUsage.Immutable, BindFlags = BindFlags.IndexBuffer, SizeInBytes = sizeof(uint) * IndexCount, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }; IndexBuffer = new Buffer(device, DataStream.Create(mesh.GetIndices(), false, false), bufferDesc); } }
private void CreateBuffer() { _vertexStride = Marshal.SizeOf <ParticleVertex>(); BufferDescription vertexBufferDescription; vertexBufferDescription.BindFlags = BindFlags.VertexBuffer; vertexBufferDescription.CpuAccessFlags = CpuAccessFlags.Write; vertexBufferDescription.OptionFlags = ResourceOptionFlags.None; vertexBufferDescription.Usage = ResourceUsage.Dynamic; vertexBufferDescription.SizeInBytes = _vertexStride * _bufferSize; _vertexBuffer = new Buffer(_context.Device, vertexBufferDescription); DebugLog.Log("Vertex buffer created", "Particle Emitter"); }
public void Dispose() { if (VertexBuffer != null) { VertexBuffer.Dispose(); VertexBuffer = null; } if (IndexBuffer != null) { IndexBuffer.Dispose(); IndexBuffer = null; } if (InstanceDataBuffer != null) { InstanceDataBuffer.Dispose(); InstanceDataBuffer = null; } }
public void SetVertexBuffer(Device device, Vector3[] vectors) { BufferDescription vertexBufferDesc = new BufferDescription() { SizeInBytes = Vector3.SizeInBytes * vectors.Length, Usage = ResourceUsage.Default, BindFlags = BindFlags.VertexBuffer }; using (var data = new DataStream(vertexBufferDesc.SizeInBytes, false, true)) { data.WriteRange(vectors); data.Position = 0; VertexBuffer = new Buffer(device, data, vertexBufferDesc); } BufferBindings[0] = new VertexBufferBinding(VertexBuffer, 24, 0); }
public void SetIndexBuffer(Device device, uint[] indices) { IndexFormat = Format.R32_UInt; BufferDescription indexBufferDesc = new BufferDescription() { SizeInBytes = sizeof(uint) * indices.Length, Usage = ResourceUsage.Default, BindFlags = BindFlags.IndexBuffer }; using (var data = new DataStream(indexBufferDesc.SizeInBytes, false, true)) { data.WriteRange(indices); data.Position = 0; IndexBuffer = new Buffer(device, data, indexBufferDesc); } }
private void CreateIndexBuffer(Device device) { if (IndexBuffer != null) { IndexBuffer.Dispose(); } var desc = new BufferDescription() { BindFlags = BindFlags.IndexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, Usage = ResourceUsage.Immutable, SizeInBytes = sizeof(uint) * MeshData.IndexCount }; IndexBuffer = new Buffer(device, DataStream.Create(MeshData.Indices.ToArray(), false, false), desc); }
public void SetVertexBuffer(Device device, Vector3[] vertices) { BufferDescription vertexBufferDesc = new BufferDescription() { SizeInBytes = Marshal.SizeOf(typeof(Vector3)) * vertices.Length, Usage = ResourceUsage.Default, BindFlags = BindFlags.VertexBuffer }; using (var data = new SharpDX.DataStream(vertexBufferDesc.SizeInBytes, false, true)) { data.WriteRange(vertices); data.Position = 0; VertexBuffer = new Buffer(device, data, vertexBufferDesc); VertexBuffer.Unmap(); } BufferBindings[0] = new VertexBufferBinding(VertexBuffer, 24, 0); }
private void CreateGrid() { _vertices = new List <VertexPosCol>(); float startOffset = -((int)GridLines / 2) * GridLineSpacing; float size = (GridLines - 1) * GridLineSpacing; for (int i = 0; i < GridLines; ++i) { //VERTICAL float lineOffset = startOffset + GridLineSpacing * i; Vector3 vertStart = new Vector3(startOffset, 0, lineOffset); _vertices.Add(new VertexPosCol(vertStart, GridColor)); vertStart.X += size; _vertices.Add(new VertexPosCol(vertStart, GridColor)); //HORIZONTAL vertStart = new Vector3(lineOffset, 0, startOffset); _vertices.Add(new VertexPosCol(vertStart, GridColor)); vertStart.Z += size; _vertices.Add(new VertexPosCol(vertStart, GridColor)); } //*AXIS _vertices.Add(new VertexPosCol(new Vector3(0, 0.01f, 0), Color.DarkRed)); _vertices.Add(new VertexPosCol(new Vector3(AxisLength, 0.01f, 0), Color.DarkRed)); _vertices.Add(new VertexPosCol(new Vector3(0, 0.01f, 0), Color.DarkGreen)); _vertices.Add(new VertexPosCol(new Vector3(0, AxisLength, 0), Color.DarkGreen)); _vertices.Add(new VertexPosCol(new Vector3(0, 0.01f, 0), Color.DarkBlue)); _vertices.Add(new VertexPosCol(new Vector3(0, 0.01f, AxisLength), Color.DarkBlue)); _vertexBuffer?.Dispose(); _vertexStride = Marshal.SizeOf <VertexPosCol>(); BufferDescription desc = new BufferDescription(); desc.BindFlags = BindFlags.VertexBuffer; desc.CpuAccessFlags = CpuAccessFlags.None; desc.OptionFlags = ResourceOptionFlags.None; desc.SizeInBytes = _vertexStride * _vertices.Count; desc.Usage = ResourceUsage.Default; _vertexBuffer = new Buffer(_context.Device, DataStream.Create(_vertices.ToArray(), false, false), desc); }
void IScene.Attach(ISceneHost host) { this.Host = host; Device device = host.Device; if (device == null) { throw new Exception("Scene host device is null"); } ShaderBytecode shaderBytes = ShaderBytecode.CompileFromFile("Simple.fx", "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null); this.SimpleEffect = new Effect(device, shaderBytes); EffectTechnique technique = this.SimpleEffect.GetTechniqueByIndex(0);; EffectPass pass = technique.GetPassByIndex(0); this.VertexLayout = new InputLayout(device, pass.Description.Signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) }); this.VertexStream = new DataStream(3 * 32, true, true); this.VertexStream.WriteRange(new[] { new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f) }); this.VertexStream.Position = 0; this.Vertices = new Buffer(device, this.VertexStream, new BufferDescription() { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = 3 * 32, Usage = ResourceUsage.Default } ); device.Flush(); }
void CreateBuffers() { if (_vertexBuffer != null) { Disposer.RemoveAndDispose(ref _vertexBuffer); } if (_indexBuffer != null) { Disposer.RemoveAndDispose(ref _indexBuffer); } BufferDescription desc = new BufferDescription(); desc.SizeInBytes = sizeof(uint) * _physicsMesh.Indices.Count; desc.BindFlags = BindFlags.IndexBuffer; desc.OptionFlags = ResourceOptionFlags.None; desc.Usage = ResourceUsage.Default; desc.CpuAccessFlags = CpuAccessFlags.None; DataStream stream = DataStream.Create(_physicsMesh.Indices.ToArray(), false, false); _indexBuffer = new Buffer(_context.Device, stream, desc); desc = new BufferDescription(); desc.SizeInBytes = Marshal.SizeOf(typeof(Vector3)) * _physicsMesh.Vertices.Count; desc.BindFlags = BindFlags.VertexBuffer; desc.OptionFlags = ResourceOptionFlags.None; desc.Usage = ResourceUsage.Default; desc.CpuAccessFlags = CpuAccessFlags.None; List <Vector3> vertices = new List <Vector3>(); foreach (PxVec3 v in _physicsMesh.Vertices) { vertices.Add(new Vector3(v.X, v.Y, v.Z)); } stream = DataStream.Create(vertices.ToArray(), false, false); _vertexBuffer = new Buffer(_context.Device, stream, desc); DebugLog.Log($"Buffers initialized", "Physics Debug Renderer"); }
private void CreateBuffers() { if (!GameRoot.Initialized) { return; } float width = 4.0f; DataStream data = new DataStream((Vertices.Length + 1) * 2 * 12, true, true); for (int i = 0; i < Vertices.Length; i++) { Vector3 a = new Vector3(Vertices[i].X, Vertices[i].Y, 1); float len = a.Length(); Vector3 b = new Vector3(Vertices[i].X * (1 - width / len), Vertices[i].Y * (1 - width / len), 1); data.Write(a); data.Write(b); } data.Write(new Vector3(Vertices[0].X, Vertices[0].Y, 1)); float len_ = Vertices[0].Length(); data.Write(new Vector3(Vertices[0].X * (1 - width / len_), Vertices[0].Y * (1 - width / len_), 1)); data.Position = 0; Radius = GetRadius(); buf = new Buffer(GameRoot.Device, data, new BufferDescription() { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = (Vertices.Length + 1) * 2 * 12, Usage = ResourceUsage.Default }); Buffer = new VertexBufferBinding(buf, 12, 0); }
private void BringDrawingIntoBuffers(D3D10GraphicsContext altaxoDrawingGeometry) { Device device = _cachedDevice; if (device == null || device.IsDisposed) { return; } var altaxoBuffersOfType = new IEnumerable <KeyValuePair <MaterialKey, IndexedTriangleBuffer> >[] { altaxoDrawingGeometry.PositionIndexedTriangleBuffersAsIndexedTriangleBuffers, altaxoDrawingGeometry.PositionColorIndexedTriangleBuffersAsIndexedTriangleBuffers, altaxoDrawingGeometry.PositionUVIndexedTriangleBuffersAsIndexedTriangleBuffers, altaxoDrawingGeometry.PositionNormalIndexedTriangleBuffersAsIndexedTriangleBuffers, altaxoDrawingGeometry.PositionNormalColorIndexedTriangleBuffersAsIndexedTriangleBuffers, altaxoDrawingGeometry.PositionNormalUVIndexedTriangleBuffersAsIndexedTriangleBuffers, altaxoDrawingGeometry.PositionNormalUIndexedTriangleBuffersAsIndexedTriangleBuffers }; for (int i = 0; i < altaxoBuffersOfType.Length; ++i) { var newDeviceBuffers = new List <VertexAndIndexDeviceBuffer>(); foreach (var altaxoBuffer in altaxoBuffersOfType[i]) { var altaxoTriangleBuffer = altaxoBuffer.Value; if (altaxoTriangleBuffer.TriangleCount == 0) { continue; } var vertexBuffer = Buffer.Create <float>(device, altaxoTriangleBuffer.VertexStream, new BufferDescription() { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = altaxoTriangleBuffer.VertexStreamLength, Usage = ResourceUsage.Default }); var indexBuffer = Buffer.Create <int>(device, altaxoTriangleBuffer.IndexStream, new BufferDescription() { BindFlags = BindFlags.IndexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = altaxoTriangleBuffer.IndexStreamLength, Usage = ResourceUsage.Default }); var indexCount = altaxoTriangleBuffer.TriangleCount * 3; Plane[] clipPlanes = null; if (altaxoBuffer.Key is MaterialPlusClippingKey) { var axoClipPlanes = ((MaterialPlusClippingKey)altaxoBuffer.Key).ClipPlanes; if (null != axoClipPlanes) { clipPlanes = axoClipPlanes.Select(axoPlane => new Plane((float)axoPlane.X, (float)axoPlane.Y, (float)axoPlane.Z, (float)-axoPlane.W)).ToArray(); } } byte[] uColors = null; var material = altaxoBuffer.Key.Material; if (altaxoTriangleBuffer is PositionNormalUIndexedTriangleBuffer && altaxoBuffer.Key is MaterialPlusClippingPlusColorProviderKey) { var bufs = (PositionNormalUIndexedTriangleBuffer)altaxoTriangleBuffer; var colorProvider = ((MaterialPlusClippingPlusColorProviderKey)(altaxoBuffer.Key)).ColorProvider; var fColors = bufs.GetColorArrayForColorProvider(colorProvider); uColors = new byte[fColors.Length * 4]; System.Buffer.BlockCopy(fColors, 0, uColors, 0, uColors.Length); material = material.WithColor(new NamedColor(colorProvider.GetAxoColor(double.NaN))); // Material needs to have InvalidColor, because this can not be represented in the Texture1D } newDeviceBuffers.Add(new VertexAndIndexDeviceBuffer(material: altaxoBuffer.Key.Material, vertexBuffer: vertexBuffer, vertexCount: altaxoTriangleBuffer.VertexCount, indexBuffer: indexBuffer, indexCount: indexCount, clipPlanes: clipPlanes, uColors: uColors)); } System.Threading.Interlocked.Exchange(ref _nextTriangleDeviceBuffers[i], newDeviceBuffers); } }
void makeSurface(int width, int height) { var vertices = new List <Vertex>(); for (int y = 0; y <= height; ++y) { for (int x = 0; x <= width; ++x) { vertices.Add(new Vertex(2 * (x - width / 2.0f) / width, 2 * (y - height / 2.0f) / height, 0, (float)x / width, (float)y / height)); } } var indices = new List <int>(); for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { indices.Add(y * (width + 1) + x); indices.Add((y + 1) * (width + 1) + x + 1); indices.Add(y * (width + 1) + x + 1); indices.Add(y * (width + 1) + x); indices.Add((y + 1) * (width + 1) + x); indices.Add((y + 1) * (width + 1) + x + 1); } } //[TODO]なぜかBuffer作成時にDataStreamを指定するとメモリアクセス違反? //現状DynamicなBufferしか作れないのを何とかする //頂点バッファを作成して書き込み _surfaceVertexBuffer = new Buffer(_device, new BufferDescription() { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, SizeInBytes = vertices.Count * Marshal.SizeOf(typeof(Vertex)), Usage = ResourceUsage.Dynamic }); var vertexStream = _surfaceVertexBuffer.Map(MapMode.WriteDiscard); vertexStream.WriteRange(vertices.ToArray()); _surfaceVertexBuffer.Unmap(); //インデックスバッファを作成して書き込み _surfaceIndexBuffer = new Buffer(_device, new BufferDescription() { BindFlags = BindFlags.IndexBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, SizeInBytes = indices.Count * Marshal.SizeOf(typeof(int)), Usage = ResourceUsage.Dynamic }); var indexStream = _surfaceIndexBuffer.Map(MapMode.WriteDiscard); indexStream.WriteRange(indices.ToArray()); _surfaceIndexBuffer.Unmap(); _surfaceVertexCount = vertices.Count; _surfaceIndexCount = indices.Count; }
private void CreateIndexBuffer(Device1 device) { IndexList = new List<uint>() { 0, 1, 2, 2, 1, 3, 4, 6, 5, 5, 6, 7, 8, 10, 9, 9, 10, 11, 12, 13, 14, 14, 13, 15, 16, 18, 17, 17, 18, 19, 20, 21, 22, 22, 21, 23 }; IndexCount = IndexList.Count; //CREATE BUFFER if (IndexBuffer != null) IndexBuffer.Dispose(); var bufferDescription = new BufferDescription { BindFlags = BindFlags.IndexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, Usage = ResourceUsage.Immutable, SizeInBytes = sizeof(uint) * IndexCount }; IndexBuffer = new Buffer(device, DataStream.Create(IndexList.ToArray(), false, false), bufferDescription); }
public D3D10Renderer(Device1 device3D) { Contract.Requires(device3D != null); _Device3D = device3D; string shader = GetShaderText(Properties.Resources.RenderingEffects); using(var byteCode = ShaderBytecode.Compile( shader, "fx_4_0", ShaderFlags.None, EffectFlags.None)) { _Effect = new Effect(_Device3D, byteCode); } _EffectTechnique = _Effect.GetTechniqueByName("WithTexture"); Contract.Assert(_EffectTechnique != null); _EffectPass = _EffectTechnique.GetPassByIndex(0); Contract.Assert(_EffectPass != null); _InputLayout = new InputLayout( _Device3D, _EffectPass.Description.Signature, _InputLayoutData); const int byteSize = _Stride * _VertexCount; using(DataStream stream = new DataStream(byteSize, true, true)) { for(int i = 0; i < _QuadPrimitiveData.Length; i += 2) { float fx = (2.0f * _QuadPrimitiveData[i + 0].X) - 1.0f; float fy = (2.0f * _QuadPrimitiveData[i + 0].Y) - 1.0f; stream.Write(new Vector3(fx, -fy, 0.5f)); stream.Write(_QuadPrimitiveData[i + 1]); } stream.Seek(0, SeekOrigin.Begin); BufferDescription description = new BufferDescription { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, Usage = ResourceUsage.Immutable, SizeInBytes = byteSize }; description.SizeInBytes = byteSize; _VertexBuffer = new Buffer(_Device3D, stream, description); _VertexBufferBinding = new VertexBufferBinding( _VertexBuffer, _Stride, _Offset); } }
private void StartD3D() { this.Device = new Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport, FeatureLevel.Level_10_0); this.D3DSurface = new DX10ImageSource(); this.D3DSurface.IsFrontBufferAvailableChanged += OnIsFrontBufferAvailableChanged; this.CreateAndBindTargets(); this.Source = this.D3DSurface; try { ShaderBytecode shaderBytes = ShaderBytecode.CompileFromFile("Shaders\\Bloom.fx", "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null); this.BloomEffect = new Effect(Device, shaderBytes); } catch { } EffectTechnique technique = this.BloomEffect.GetTechniqueByIndex(0); EffectPass pass = technique.GetPassByIndex(0); this.VertexLayout = new InputLayout(Device, pass.Description.Signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 16, 0) }); DataStream vertices = new DataStream(4 * 6 * 4, true, true); vertices.Write(new Vector4(-1.0f, 1.0f, 0.0f, 1.0f)); vertices.Write(new Vector2(0.0f, 0.0f)); vertices.Write(new Vector4(1.0f, 1.0f, 0.0f, 1.0f)); vertices.Write(new Vector2(1.0f, 0.0f)); vertices.Write(new Vector4(-1.0f, -1.0f, 0.0f, 1.0f)); vertices.Write(new Vector2(0.0f, 1.0f)); vertices.Write(new Vector4(1.0f, -1.0f, 0.0f, 1.0f)); vertices.Write(new Vector2(1.0f, 1.0f)); vertices.Position = 0; this.QuadBuffer = new Buffer(Device, vertices, new BufferDescription() { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = 4 * 6 * 4, Usage = ResourceUsage.Default }); vertices = new DataStream(4 * 6 * 4, true, true); vertices.Write(new Vector4(-1.0f, 1.0f, 0.0f, 1.0f)); vertices.Write(new Vector2(0.0f, 0.0f)); vertices.Write(new Vector4(1.0f, 1.0f, 0.0f, 1.0f)); vertices.Write(new Vector2(2.0f, 0.0f)); vertices.Write(new Vector4(-1.0f, -1.0f, 0.0f, 1.0f)); vertices.Write(new Vector2(0.0f, 2.0f)); vertices.Write(new Vector4(1.0f, -1.0f, 0.0f, 1.0f)); vertices.Write(new Vector2(2.0f, 2.0f)); vertices.Position = 0; this.HalfQuadBuffer = new Buffer(Device, vertices, new BufferDescription() { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = 4 * 6 * 4, Usage = ResourceUsage.Default }); }
private void ParseFile(Device1 device, string path) { var verts = new List<VertexPosColNorm>(); IndexList = new List<uint>(); uint vertCount = 0; using (BinaryReader reader = new BinaryReader(File.Open(path, FileMode.Open))) { int versionMaj = reader.ReadByte(); int versionMin = reader.ReadByte(); for (; ; ) { // block stuff int blockId = reader.ReadByte(); if (blockId == 0) break; uint blockLength = reader.ReadUInt32(); if (blockId == 1) { //general reader.ReadString(); vertCount = reader.ReadUInt32(); IndexCount = (int)reader.ReadUInt32(); } else if (blockId == 2) { //positions for (int i = 0; i < vertCount; i++) { float x = reader.ReadSingle(); float y = reader.ReadSingle(); float z = reader.ReadSingle(); verts.Add(new VertexPosColNorm(new Vector3(x, y, z) , Color.Gray, Vector3.Zero)); } } else if (blockId == 3) { //indices for (int i = 0; i < IndexCount; i++) { IndexList.Add(reader.ReadUInt32()); } } else if (blockId == 4) { //normals for (int i = 0; i < vertCount; i++) { float x = reader.ReadSingle(); float y = reader.ReadSingle(); float z = reader.ReadSingle(); var copy = verts[i]; verts[i] = new VertexPosColNorm(copy.Position, Color.Gray, new Vector3(x, y, z)); } } else if (blockId == 7) { //colors for (int i = 0; i < vertCount; i++) { float r = reader.ReadSingle(); float g = reader.ReadSingle(); float b = reader.ReadSingle(); float a = reader.ReadSingle(); var copy = verts[i]; verts[i] = new VertexPosColNorm(copy.Position, new Color(r, g, b, a), copy.Normal); } } else { reader.ReadBytes((int)blockLength); } } } //CREATE vertex buffer if (VertexBuffer != null) VertexBuffer.Dispose(); var vertBufferDescription = new BufferDescription { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, Usage = ResourceUsage.Immutable, SizeInBytes = VertexStride * verts.Count }; VertexBuffer = new Buffer(device, DataStream.Create(verts.ToArray(), false, false), vertBufferDescription); //CREATE index buffer if (IndexBuffer != null) IndexBuffer.Dispose(); var intBufferDescription = new BufferDescription { BindFlags = BindFlags.IndexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, Usage = ResourceUsage.Immutable, SizeInBytes = sizeof(uint) * IndexCount }; IndexBuffer = new Buffer(device, DataStream.Create(IndexList.ToArray(), false, false), intBufferDescription); VertexList = new List<Vector3>(); foreach (var vertex in verts) { VertexList.Add(vertex.Position); } }
private void SetDevice() { this.RenderForm = new RenderForm("SharpDX - Basics") { Width = 1700, Height = 900 }; // SwapChain description var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(RenderForm.ClientSize.Width, RenderForm.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = RenderForm.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Create Device and SwapChain { Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain); this.Device = device; this.SwapChain = swapChain; } // Ignore all windows events var factory = SwapChain.GetParent<Factory>(); factory.MakeWindowAssociation(RenderForm.Handle, WindowAssociationFlags.IgnoreAll); // New RenderTargetView from the backbuffer var backBuffer = Texture2D.FromSwapChain<Texture2D>(SwapChain, 0); this.RenderTargetView = new RenderTargetView(Device, backBuffer); // Create Constant Buffer var ConstantBuffer = new Buffer(Device, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None); // Create Depth Buffer & View var depthBuffer = new Texture2D(Device, new Texture2DDescription() { Format = Format.D32_Float_S8X24_UInt, ArraySize = 1, MipLevels = 1, Width = RenderForm.ClientSize.Width, Height = RenderForm.ClientSize.Height, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }); this.DepthStencilView = new DepthStencilView(Device, depthBuffer); Device.VertexShader.SetConstantBuffer(0, ConstantBuffer); Device.Rasterizer.SetViewports(new Viewport(0, 0, RenderForm.ClientSize.Width, RenderForm.ClientSize.Height, 0.0f, 1.0f)); }
private static void Main2() { var form = new RenderForm("SharpDX - MiniTri Direct3D 10 Sample"); // SwapChain description var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Create Device and SwapChain Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain); // Ignore all windows events Factory factory = swapChain.GetParent <Factory>(); factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll); // New RenderTargetView from the backbuffer Texture2D backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0); var renderView = new RenderTargetView(device, backBuffer); // Compile Vertex and Pixel shaders var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "VS", "vs_4_0", ShaderFlags.None, EffectFlags.None); var vertexShader = new VertexShader(device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "PS", "ps_4_0", ShaderFlags.None, EffectFlags.None); var pixelShader = new PixelShader(device, pixelShaderByteCode); // Layout from VertexShader input signature var layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) }); // Instantiate Vertex buiffer from vertex data var vertices = Buffer.Create(device, BindFlags.VertexBuffer, new[] { new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f) }); // Prepare All the stages device.InputAssembler.InputLayout = layout; device.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, 32, 0)); device.VertexShader.Set(vertexShader); device.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f)); device.PixelShader.Set(pixelShader); device.OutputMerger.SetTargets(renderView); // Main loop RenderLoop.Run(form, () => { device.ClearRenderTargetView(renderView, Color.Black); device.Draw(3, 0); swapChain.Present(0, PresentFlags.None); }); // Release all resources vertexShaderByteCode.Dispose(); vertexShader.Dispose(); pixelShaderByteCode.Dispose(); pixelShader.Dispose(); vertices.Dispose(); layout.Dispose(); renderView.Dispose(); backBuffer.Dispose(); device.ClearState(); device.Flush(); device.Dispose(); device.Dispose(); swapChain.Dispose(); factory.Dispose(); }
void IScene.Attach(ISceneHost host) { this.Host = host; Device device = host.Device; if (device == null) { throw new Exception("Scene host device is null"); } Uri executablePath = new Uri(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase); String shaderPath = System.IO.Path.GetDirectoryName(executablePath.LocalPath) + "\\Shaders\\"; if (videoPlayerViewModel.DecodedVideoFormat == VideoLib.VideoPlayer.DecodedVideoFormat.YUV420P) { shaderPath += "YUVtoRGB.fx"; } else { shaderPath += "Simple.fx"; } try { ShaderBytecode shaderBytes = ShaderBytecode.CompileFromFile(shaderPath, "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null); this.SimpleEffect = new Effect(device, shaderBytes); } catch (Exception e) { System.Diagnostics.Debug.Print(e.Message); throw new Exception("Error compiling: " + shaderPath); } EffectTechnique technique = this.SimpleEffect.GetTechniqueByIndex(0); EffectPass pass = technique.GetPassByIndex(0); this.VertexLayout = new InputLayout(device, pass.Description.Signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32B32A32_Float, InputElement.AppendAligned, 0) //new InputElement("COLOR", 0, Format.R32G32B32A32_Float, InputElement.AppendAligned, 0) }); int bytesPerVertexInfo = 4 * 8; nrVertices = 4; this.VertexStream = new DataStream(bytesPerVertexInfo * nrVertices, true, true); this.VertexStream.WriteRange(new[] { new Vector4(-1.0f, 1.0f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 0.0f, 0.0f), new Vector4(1.0f, -1.0f, 0.5f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 0.0f), new Vector4(-1.0f, -1.0f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 0.0f), new Vector4(1.0f, 1.0f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 0.0f) } ); this.VertexStream.Position = 0; this.Vertices = new Buffer(device, this.VertexStream, new BufferDescription() { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = bytesPerVertexInfo * nrVertices, Usage = ResourceUsage.Default } ); nrIndices = 4; int indicesSizeBytes = nrIndices * sizeof(Int32); IndexStream = new DataStream(indicesSizeBytes, true, true); IndexStream.WriteRange <int>(new[] { 3, 1, 0, 2 } ); this.IndexStream.Position = 0; this.Indices = new Buffer(device, this.IndexStream, new BufferDescription() { BindFlags = BindFlags.IndexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = indicesSizeBytes, Usage = ResourceUsage.Default } ); device.Flush(); }
private static void Main() { var form = new RenderForm("SharpDX - MiniTri Direct3D 10 Sample"); // SwapChain description var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Create Device and SwapChain Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, desc, out device, out swapChain); // Ignore all windows events Factory factory = swapChain.GetParent <Factory>(); factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll); // New RenderTargetView from the backbuffer Texture2D backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0); var renderView = new RenderTargetView(device, backBuffer); // Compile Vertex and Pixel shaders var effectByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "fx_4_0", ShaderFlags.None, EffectFlags.None); var effect = new Effect(device, effectByteCode); var technique = effect.GetTechniqueByIndex(0); var pass = technique.GetPassByIndex(0); // Layout from VertexShader input signature var layout = new InputLayout(device, pass.Description.Signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) }); // Write vertex data to a datastream var stream = new DataStream(32 * 3, true, true); stream.WriteRange(new[] { new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f) }); stream.Position = 0; // Instantiate Vertex buiffer from vertex data var vertices = new Buffer(device, stream, new BufferDescription() { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = 32 * 3, Usage = ResourceUsage.Default, }); stream.Release(); // Prepare All the stages device.InputAssembler.SetInputLayout(layout); device.InputAssembler.SetPrimitiveTopology(PrimitiveTopology.TriangleList); device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, 32, 0)); device.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f)); device.OutputMerger.SetTargets(renderView); // Main loop RenderLoop.Run(form, () => { device.ClearRenderTargetView(renderView, new Color4(1.0f, 0.0f, 0.0f, 0.0f)); for (int i = 0; i < technique.Description.PassCount; ++i) { pass.Apply(); device.Draw(3, 0); } swapChain.Present(0, PresentFlags.None); }); // Release all resources effectByteCode.Release(); vertices.Release(); layout.Release(); renderView.Release(); backBuffer.Release(); device.ClearState(); device.Flush(); device.Release(); device.Release(); swapChain.Release(); factory.Release(); }
public override void Initialize() { Form.SizeChanged += (o, args) => { _width = Form.ClientSize.Width; _height = Form.ClientSize.Height; if (_swapChain == null) { return; } renderView.Dispose(); depthView.Dispose(); _swapChain.ResizeBuffers(_swapChain.Description.BufferCount, 0, 0, Format.Unknown, 0); CreateBuffers(); SetSceneConstants(); }; _width = 1024; _height = 768; _nearPlane = 1.0f; ambient = new Color4(Color.Gray.ToArgb()); try { OnInitializeDevice(); } catch (Exception e) { MessageBox.Show(e.ToString(), "Could not create DirectX 10 device."); return; } // shader.fx const ShaderFlags shaderFlags = ShaderFlags.None; //const ShaderFlags shaderFlags = ShaderFlags.Debug | ShaderFlags.SkipOptimization; ShaderBytecode shaderByteCode = LoadShader("shader.fx", shaderFlags); effect = new Effect(_device, shaderByteCode); EffectTechnique technique = effect.GetTechniqueByIndex(0); shadowGenPass = technique.GetPassByIndex(0); gBufferGenPass = technique.GetPassByIndex(1); debugDrawPass = technique.GetPassByName("debug"); BufferDescription sceneConstantsDesc = new BufferDescription() { SizeInBytes = Marshal.SizeOf(typeof(ShaderSceneConstants)), Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None }; sceneConstantsBuffer = new Buffer(_device, sceneConstantsDesc); EffectConstantBuffer effectConstantBuffer = effect.GetConstantBufferByName("scene"); effectConstantBuffer.SetConstantBuffer(sceneConstantsBuffer); RasterizerStateDescription desc = new RasterizerStateDescription() { CullMode = CullMode.None, FillMode = FillMode.Solid, IsFrontCounterClockwise = true, DepthBias = 0, DepthBiasClamp = 0, SlopeScaledDepthBias = 0, IsDepthClipEnabled = true, }; _device.Rasterizer.State = new RasterizerState(_device, desc); DepthStencilStateDescription depthDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less }; depthStencilState = new DepthStencilState(_device, depthDesc); DepthStencilStateDescription lightDepthStateDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less }; lightDepthStencilState = new DepthStencilState(_device, lightDepthStateDesc); // grender.fx shaderByteCode = LoadShader("grender.fx", shaderFlags); effect2 = new Effect(_device, shaderByteCode); technique = effect2.GetTechniqueByIndex(0); gBufferRenderPass = technique.GetPassByIndex(0); gBufferOverlayPass = technique.GetPassByIndex(1); Buffer quad = DemoFramework.SharpDX.MeshFactory.CreateScreenQuad(_device); quadBinding = new VertexBufferBinding(quad, 20, 0); Matrix quadProjection = Matrix.OrthoLH(1, 1, 0.1f, 1.0f); effect2.GetVariableByName("ViewProjection").AsMatrix().SetMatrix(quadProjection); InputElement[] elements = new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0), }; quadBufferLayout = new InputLayout(_device, gBufferRenderPass.Description.Signature, elements); info = new InfoText(_device); _meshFactory = new MeshFactory(this); MeshFactory = _meshFactory; CreateBuffers(); LibraryManager.LibraryStarted(); }
private void CreateVertexBuffer(Device1 device) { var verts = new List<VertexPosColNorm>(); Color col = Color.Red; Vector3 norm = new Vector3(0, 0, -1); //FRONT RED verts.Add(new VertexPosColNorm(new Vector3(-0.5f, -0.5f, -0.5f), col, norm)); verts.Add(new VertexPosColNorm(new Vector3(-0.5f, 0.5f, -0.5f), col, norm)); verts.Add(new VertexPosColNorm(new Vector3(0.5f, -0.5f, -0.5f), col, norm)); verts.Add(new VertexPosColNorm(new Vector3(0.5f, 0.5f, -0.5f), col, norm)); //BACK RED norm = new Vector3(0, 0, 1); verts.Add(new VertexPosColNorm(new Vector3(-0.5f, -0.5f, 0.5f), col, norm)); verts.Add(new VertexPosColNorm(new Vector3(-0.5f, 0.5f, 0.5f), col, norm)); verts.Add(new VertexPosColNorm(new Vector3(0.5f, -0.5f, 0.5f), col, norm)); verts.Add(new VertexPosColNorm(new Vector3(0.5f, 0.5f, 0.5f), col, norm)); //LEFT GREEN col = Color.Green; norm = new Vector3(-1, 0, 0); verts.Add(new VertexPosColNorm(new Vector3(-0.5f, -0.5f, -0.5f), col, norm)); verts.Add(new VertexPosColNorm(new Vector3(-0.5f, 0.5f, -0.5f), col, norm)); verts.Add(new VertexPosColNorm(new Vector3(-0.5f, -0.5f, 0.5f), col, norm)); verts.Add(new VertexPosColNorm(new Vector3(-0.5f, 0.5f, 0.5f), col, norm)); //RIGHT GREEN norm = new Vector3(1, 0, 0); verts.Add(new VertexPosColNorm(new Vector3(0.5f, -0.5f, -0.5f), col, norm)); verts.Add(new VertexPosColNorm(new Vector3(0.5f, 0.5f, -0.5f), col, norm)); verts.Add(new VertexPosColNorm(new Vector3(0.5f, -0.5f, 0.5f), col, norm)); verts.Add(new VertexPosColNorm(new Vector3(0.5f, 0.5f, 0.5f), col, norm)); //TOP BLUE col = Color.Blue; norm = new Vector3(0, 1, 0); verts.Add(new VertexPosColNorm(new Vector3(-0.5f, 0.5f, 0.5f), col, norm)); verts.Add(new VertexPosColNorm(new Vector3(-0.5f, 0.5f, -0.5f), col, norm)); verts.Add(new VertexPosColNorm(new Vector3(0.5f, 0.5f, 0.5f), col, norm)); verts.Add(new VertexPosColNorm(new Vector3(0.5f, 0.5f, -0.5f), col, norm)); //BOTTOM BLUE norm = new Vector3(0, -1, 0); verts.Add(new VertexPosColNorm(new Vector3(-0.5f, -0.5f, 0.5f), col, norm)); verts.Add(new VertexPosColNorm(new Vector3(-0.5f, -0.5f, -0.5f), col, norm)); verts.Add(new VertexPosColNorm(new Vector3(0.5f, -0.5f, 0.5f), col, norm)); verts.Add(new VertexPosColNorm(new Vector3(0.5f, -0.5f, -0.5f), col, norm)); //CREATE BUFFER if (VertexBuffer != null) VertexBuffer.Dispose(); var bufferDescription = new BufferDescription { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, Usage = ResourceUsage.Immutable, SizeInBytes = VertexStride * verts.Count }; VertexBuffer = new Buffer(device, DataStream.Create(verts.ToArray(), false, false), bufferDescription); VertexList = new List<Vector3>(); foreach (var vertex in verts) { VertexList.Add(vertex.Position); } }
public override void Initialize() { Form.SizeChanged += (o, args) => { if (_swapChain == null) return; renderView.Dispose(); depthView.Dispose(); DisposeBuffers(); if (Form.WindowState == FormWindowState.Minimized) return; _width = Form.ClientSize.Width; _height = Form.ClientSize.Height; _swapChain.ResizeBuffers(_swapChain.Description.BufferCount, 0, 0, Format.Unknown, 0); CreateBuffers(); SetSceneConstants(); }; _width = 1024; _height = 768; _nearPlane = 1.0f; ambient = new Color4(Color.Gray.ToArgb()); try { OnInitializeDevice(); } catch (Exception e) { MessageBox.Show(e.ToString(), "Could not create DirectX 10 device."); return; } // shader.fx const ShaderFlags shaderFlags = ShaderFlags.None; //const ShaderFlags shaderFlags = ShaderFlags.Debug | ShaderFlags.SkipOptimization; ShaderBytecode shaderByteCode = LoadShader("shader.fx", shaderFlags); effect = new Effect(_device, shaderByteCode); EffectTechnique technique = effect.GetTechniqueByIndex(0); shadowGenPass = technique.GetPassByIndex(0); gBufferGenPass = technique.GetPassByIndex(1); debugDrawPass = technique.GetPassByName("debug"); BufferDescription sceneConstantsDesc = new BufferDescription() { SizeInBytes = Marshal.SizeOf(typeof(ShaderSceneConstants)), Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None }; sceneConstantsBuffer = new Buffer(_device, sceneConstantsDesc); EffectConstantBuffer effectConstantBuffer = effect.GetConstantBufferByName("scene"); effectConstantBuffer.SetConstantBuffer(sceneConstantsBuffer); RasterizerStateDescription desc = new RasterizerStateDescription() { CullMode = CullMode.None, FillMode = FillMode.Solid, IsFrontCounterClockwise = true, DepthBias = 0, DepthBiasClamp = 0, SlopeScaledDepthBias = 0, IsDepthClipEnabled = true, }; _device.Rasterizer.State = new RasterizerState(_device, desc); DepthStencilStateDescription depthDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less }; depthStencilState = new DepthStencilState(_device, depthDesc); DepthStencilStateDescription lightDepthStateDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less }; lightDepthStencilState = new DepthStencilState(_device, lightDepthStateDesc); // grender.fx shaderByteCode = LoadShader("grender.fx", shaderFlags); effect2 = new Effect(_device, shaderByteCode); technique = effect2.GetTechniqueByIndex(0); gBufferRenderPass = technique.GetPassByIndex(0); gBufferOverlayPass = technique.GetPassByIndex(1); info = new InfoText(_device); _meshFactory = new MeshFactory(this); MeshFactory = _meshFactory; CreateBuffers(); LibraryManager.LibraryStarted(); }
void Initialize() { // shader.fx ShaderFlags shaderFlags = ShaderFlags.None; //ShaderFlags shaderFlags = ShaderFlags.Debug | ShaderFlags.SkipOptimization; ShaderBytecode shaderByteCode = ShaderBytecode.CompileFromFile(Application.StartupPath + "\\shader.fx", "fx_4_0", shaderFlags, EffectFlags.None); effect = new Effect(_device, shaderByteCode); EffectTechnique technique = effect.GetTechniqueByIndex(0); shadowGenPass = technique.GetPassByIndex(0); gBufferGenPass = technique.GetPassByIndex(1); BufferDescription sceneConstantsDesc = new BufferDescription() { SizeInBytes = Marshal.SizeOf(typeof(ShaderSceneConstants)), Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None }; sceneConstantsBuffer = new Buffer(_device, sceneConstantsDesc); EffectConstantBuffer effectConstantBuffer = effect.GetConstantBufferByName("scene"); effectConstantBuffer.SetConstantBuffer(sceneConstantsBuffer); RasterizerStateDescription desc = new RasterizerStateDescription() { CullMode = CullMode.None, FillMode = FillMode.Solid, IsFrontCounterClockwise = true, DepthBias = 0, DepthBiasClamp = 0, SlopeScaledDepthBias = 0, IsDepthClipEnabled = true, }; _device.Rasterizer.State = new RasterizerState(_device, desc); DepthStencilStateDescription depthDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less }; depthStencilState = new DepthStencilState(_device, depthDesc); DepthStencilStateDescription lightDepthStateDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less }; lightDepthStencilState = new DepthStencilState(_device, lightDepthStateDesc); // grender.fx shaderByteCode = ShaderBytecode.CompileFromFile(Application.StartupPath + "\\grender.fx", "fx_4_0", shaderFlags, EffectFlags.None); effect2 = new Effect(_device, shaderByteCode); technique = effect2.GetTechniqueByIndex(0); gBufferRenderPass = technique.GetPassByIndex(0); Buffer quad = MeshFactory.CreateScreenQuad(_device); quadBinding = new VertexBufferBinding(quad, 20, 0); Matrix quadProjection = Matrix.OrthoLH(1, 1, 0.1f, 1.0f); effect2.GetVariableByName("ViewProjection").AsMatrix().SetMatrix(quadProjection); InputElement[] elements = new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0), }; quadBufferLayout = new InputLayout(_device, gBufferRenderPass.Description.Signature, elements); Info = new InfoText(_device); meshFactory = new MeshFactory(this); OnInitialize(); CreateBuffers(); SetSceneConstants(); }
private void LoadRenderShader() { var shaderBytes = ShaderBytecode.Compile(Properties.Resources.FillShader, "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null); fillEffect = new Effect(device, shaderBytes); EffectTechnique technique = fillEffect.GetTechniqueByIndex(0); ; fillPass = technique.GetPassByIndex(0); // Compile Vertex and Pixel shaders var vertexShaderByteCode = ShaderBytecode.Compile(Properties.Resources.FillShader, "vs_main", "vs_4_0"); vertexShader = new VertexShader(device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.Compile(Properties.Resources.FillShader, "ps_main", "ps_4_0"); pixelShader = new PixelShader(device, pixelShaderByteCode); // Layout from VertexShader input signature layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 16, 0) }); // Instantiate Vertex buiffer from vertex data vertices = Buffer.Create(device, BindFlags.VertexBuffer, new[] { new RenderVertex(){pos = new Vector4(1.0f, -1.0f, 0.0f, 1.0f), tex = new Vector2(1,1)}, new RenderVertex(){pos = new Vector4(-1.0f, -1.0f, 0.0f, 1.0f), tex = new Vector2(0,1)}, new RenderVertex(){pos = new Vector4(-1.0f, 1.0f, 0.0f, 1.0f), tex = new Vector2(0,0)}, new RenderVertex(){pos = new Vector4(1.0f, 1.0f, 0.0f, 1.0f), tex = new Vector2(1,0)}, }); vertices_binding = new VertexBufferBinding(vertices, Utilities.SizeOf<Vector2>() + Utilities.SizeOf<Vector4>(), 0); indices = Buffer.Create(device, BindFlags.IndexBuffer, new short[] { 0, 1, 2, 2, 3, 0 }); // Create Constant Buffer //constants = new Buffer(device, Utilities.SizeOf<Vector2>() + Utilities.SizeOf<Vector4>(), ResourceUsage.Dynamic, BindFlags.ShaderResource, CpuAccessFlags.Write, ResourceOptionFlags.None); device.Rasterizer.SetViewports(new Viewport(0, 0, Width, Height, 0.0f, 1.0f)); RasterizerStateDescription rsd = new RasterizerStateDescription() { CullMode = CullMode.None, FillMode = FillMode.Solid, }; RasterizerState rsdState = new RasterizerState(device, rsd); device.Rasterizer.State = rsdState; options.halfPixel = new Vector2(0.5f / (float)Width,0.5f / (float)Height); options.color = new Vector4(1, 0, 1, 1); }
private void CreateBuffers() { if (!GameRoot.Initialized) return; float width = 4.0f; DataStream data = new DataStream((Vertices.Length + 1) * 2 * 12, true, true); for (int i = 0; i < Vertices.Length; i++) { Vector3 a = new Vector3(Vertices[i].X, Vertices[i].Y, 1); float len = a.Length(); Vector3 b = new Vector3(Vertices[i].X * (1 - width / len), Vertices[i].Y * (1 - width / len), 1); data.Write(a); data.Write(b); } data.Write(new Vector3(Vertices[0].X, Vertices[0].Y, 1)); float len_ = Vertices[0].Length(); data.Write(new Vector3(Vertices[0].X * (1 - width / len_), Vertices[0].Y * (1 - width / len_), 1)); data.Position = 0; Radius = GetRadius(); buf = new Buffer(GameRoot.Device, data, new BufferDescription() { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = (Vertices.Length + 1) * 2 * 12, Usage = ResourceUsage.Default }); Buffer = new VertexBufferBinding(buf, 12, 0); }
public override void Initialize() { Form.SizeChanged += (o, args) => { _width = Form.ClientSize.Width; _height = Form.ClientSize.Height; if (_swapChain == null) return; renderView.Dispose(); depthView.Dispose(); _swapChain.ResizeBuffers(_swapChain.Description.BufferCount, 0, 0, Format.Unknown, 0); CreateBuffers(); SetSceneConstants(); }; _width = 1024; _height = 768; _nearPlane = 1.0f; ambient = new Color4(Color.Gray.ToArgb()); try { OnInitializeDevice(); } catch (Exception e) { MessageBox.Show(e.ToString(), "Could not create DirectX 10 device."); return; } // shader.fx const ShaderFlags shaderFlags = ShaderFlags.None; //const ShaderFlags shaderFlags = ShaderFlags.Debug | ShaderFlags.SkipOptimization; ShaderBytecode shaderByteCode = LoadShader("shader.fx", shaderFlags); effect = new Effect(_device, shaderByteCode); EffectTechnique technique = effect.GetTechniqueByIndex(0); shadowGenPass = technique.GetPassByIndex(0); gBufferGenPass = technique.GetPassByIndex(1); debugDrawPass = technique.GetPassByName("debug"); BufferDescription sceneConstantsDesc = new BufferDescription() { SizeInBytes = Marshal.SizeOf(typeof(ShaderSceneConstants)), Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None }; sceneConstantsBuffer = new Buffer(_device, sceneConstantsDesc); EffectConstantBuffer effectConstantBuffer = effect.GetConstantBufferByName("scene"); effectConstantBuffer.SetConstantBuffer(sceneConstantsBuffer); RasterizerStateDescription desc = new RasterizerStateDescription() { CullMode = CullMode.None, FillMode = FillMode.Solid, IsFrontCounterClockwise = true, DepthBias = 0, DepthBiasClamp = 0, SlopeScaledDepthBias = 0, IsDepthClipEnabled = true, }; _device.Rasterizer.State = new RasterizerState(_device, desc); DepthStencilStateDescription depthDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less }; depthStencilState = new DepthStencilState(_device, depthDesc); DepthStencilStateDescription lightDepthStateDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less }; lightDepthStencilState = new DepthStencilState(_device, lightDepthStateDesc); // grender.fx shaderByteCode = LoadShader("grender.fx", shaderFlags); effect2 = new Effect(_device, shaderByteCode); technique = effect2.GetTechniqueByIndex(0); gBufferRenderPass = technique.GetPassByIndex(0); gBufferOverlayPass = technique.GetPassByIndex(1); Buffer quad = DemoFramework.SharpDX.MeshFactory.CreateScreenQuad(_device); quadBinding = new VertexBufferBinding(quad, 20, 0); Matrix quadProjection = Matrix.OrthoLH(1, 1, 0.1f, 1.0f); effect2.GetVariableByName("ViewProjection").AsMatrix().SetMatrix(quadProjection); InputElement[] elements = new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0), }; quadBufferLayout = new InputLayout(_device, gBufferRenderPass.Description.Signature, elements); info = new InfoText(_device); _meshFactory = new MeshFactory(this); MeshFactory = _meshFactory; CreateBuffers(); LibraryManager.LibraryStarted(); }
void IScene.Attach(ISceneHost host) { this.Host = host; Device device = host.Device; if (device == null) throw new Exception("Scene host device is null"); ShaderBytecode shaderBytes = ShaderBytecode.CompileFromFile("Simple.fx", "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null); this.SimpleEffect = new Effect(device, shaderBytes); EffectTechnique technique = this.SimpleEffect.GetTechniqueByIndex(0); ; EffectPass pass = technique.GetPassByIndex(0); this.VertexLayout = new InputLayout(device, pass.Description.Signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) }); this.VertexStream = new DataStream(3 * 32, true, true); this.VertexStream.WriteRange(new[] { new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f) }); this.VertexStream.Position = 0; this.Vertices = new Buffer(device, this.VertexStream, new BufferDescription() { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = 3 * 32, Usage = ResourceUsage.Default } ); device.Flush(); }
/* public void RenderSoftBodyTextured(SoftBody softBody) { if (!(softBody.UserObject is Array)) return; object[] userObjArr = softBody.UserObject as object[]; FloatArray vertexBuffer = userObjArr[0] as FloatArray; IntArray indexBuffer = userObjArr[1] as IntArray; int vertexCount = (vertexBuffer.Count / 8); if (vertexCount > 0) { int faceCount = indexBuffer.Count / 2; bool index32 = vertexCount > 65536; Mesh mesh = new Mesh(device, faceCount, vertexCount, MeshFlags.SystemMemory | (index32 ? MeshFlags.Use32Bit : 0), VertexFormat.Position | VertexFormat.Normal | VertexFormat.Texture1); SlimDX.DataStream indices = mesh.LockIndexBuffer(LockFlags.Discard); if (index32) { foreach (int i in indexBuffer) indices.Write(i); } else { foreach (int i in indexBuffer) indices.Write((ushort)i); } mesh.UnlockIndexBuffer(); SlimDX.DataStream verts = mesh.LockVertexBuffer(LockFlags.Discard); foreach (float f in vertexBuffer) verts.Write(f); mesh.UnlockVertexBuffer(); mesh.ComputeNormals(); mesh.DrawSubset(0); mesh.Dispose(); } } * */ public static Buffer CreateScreenQuad(Device device) { Buffer vertexBuffer; BufferDescription vertexBufferDesc = new BufferDescription() { SizeInBytes = sizeof(float) * 5 * 4, Usage = ResourceUsage.Default, BindFlags = BindFlags.VertexBuffer, }; using (var data = new DataStream(vertexBufferDesc.SizeInBytes, false, true)) { data.Write(new Vector3(0.5f, 0.5f, 0)); data.Write(new Vector2(1, 0)); data.Write(new Vector3(0.5f, -0.5f, 0)); data.Write(new Vector2(1, 1)); data.Write(new Vector3(-0.5f, 0.5f, 0)); data.Write(new Vector2(0, 0)); data.Write(new Vector3(-0.5f, -0.5f, 0)); data.Write(new Vector2(0, 1)); data.Position = 0; vertexBuffer = new Buffer(device, data, vertexBufferDesc); } return vertexBuffer; }
public void Update(TimeSpan timeSpan) { if (!isRunning) return; TimeSpan ts = (DateTime.Now - Last); Time.Dt = (float)ts.TotalSeconds; //Time.Dt = 1.0f / 60.0f; Last = DateTime.Now; double fps = 1 / ts.TotalSeconds; sumFps += (float)fps; Profiles.Current.State.Score = Math.Max((int)(PlayerShip.Instance.Position.Y / 10), Profiles.Current.State.Score); if (counter++ % 60 == 0) { { float fa = 0.18618986725025f; float fb = 210125.0f / 156.0f; float fc = 31.0f / 6.0f; maxEntities = (int)(fa * Math.Sqrt(fb + Profiles.Current.State.Score) + fc); } { float fa = 38.0f / 9.0f; float fb = 70.0f / 9.0f; float fc = 200f; float x = (float)Profiles.Current.State.Score / 1000.0f; linesSpeed = (int)(fa * x * x + fb * x + fc); } } for (int i = EntityManager.Count; i < maxEntities; i++) EntityManager.Add(Rock.Create()); EntityManager.Update(); ParticleManager.Update(); Profiles.Current.State.LinesPosition += linesSpeed * Time.Dt; if (Profiles.Current.State.LinesPosition > PlayerShip.Instance.Position.Y) GameOver(); Device device = Host.Device; if (ParticleManager.particleList.Count > 0) { DataStream particles = new DataStream(ParticleManager.particleList.Count * 32, true, true); for (int i = 0; i < ParticleManager.particleList.Count; i++) { var particle = ParticleManager.particleList[i]; Vector2 a = new Vector2(particle.Position.X, particle.Position.Y); Vector2 b = new Vector2(particle.Scale.X, -particle.Orientation); particles.WriteRange(new[] { a, b }); particles.Write(particle.Color); } particles.Position = 0; Disposer.RemoveAndDispose(ref this.Particles); this.Particles = new Buffer(device, particles, new BufferDescription() { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = ParticleManager.particleList.Count * 32, Usage = ResourceUsage.Default }); Disposer.RemoveAndDispose(ref particles); } }
public void Create(Device1 device, GenericShader effect) { PrimitiveTopology = PrimitiveTopology.TriangleList; VertexStride = effect.VertexStride; List <int> indices = new List <int>(); var importer = new AssimpContext(); Scene scene = importer.ImportFile(_fileName, PostProcessSteps.GenerateSmoothNormals | PostProcessSteps.CalculateTangentSpace | PostProcessSteps.Triangulate); if (!importer.IsImportFormatSupported(Path.GetExtension(_fileName))) { throw new Exception("File Format not supported"); } long vertCount = 0; foreach (var model in scene.Meshes) { vertCount += model.VertexCount; } var verts = new float[VertexStride * vertCount]; int meshOffset = 0; foreach (var model in scene.Meshes) { for (var i = 0; i < model.VertexCount; ++i) { var pos = model.Vertices[i]; var nor = model.Normals[i]; var uv = model.TextureCoordinateChannels[0][i]; uv.Y = -uv.Y; var col = model.HasVertexColors(0) ? model.VertexColorChannels[0][i] : new Color4D(1, 0, 1); var tan = model.Tangents[i]; var inputOffset = 0; foreach (var inputParam in effect.InputParameters) { if (inputParam.SemanticName == "POSITION") { Array.Copy(pos.ToArray(), 0, verts, i * (VertexStride / sizeof(float)) + inputOffset + meshOffset, 3); inputOffset += 3; } else if (inputParam.SemanticName == "NORMAL") { Array.Copy(nor.ToArray(), 0, verts, i * (VertexStride / sizeof(float)) + inputOffset + meshOffset, 3); inputOffset += 3; } else if (inputParam.SemanticName == "COLOR") { Array.Copy(col.ToArray(), 0, verts, i * (VertexStride / sizeof(float)) + inputOffset + meshOffset, 4); inputOffset += 4; } else if (inputParam.SemanticName == "TEXCOORD" || inputParam.SemanticName == "TEXCOORD0") { Array.Copy(uv.ToArray(), 0, verts, i * (VertexStride / sizeof(float)) + inputOffset + meshOffset, 2); inputOffset += 2; } else if (inputParam.SemanticName == "TANGENT") { Array.Copy(tan.ToArray(), 0, verts, i * (VertexStride / sizeof(float)) + inputOffset + meshOffset, 3); inputOffset += 3; } else { MessageBox.Show("AssimpModel::Create() > Unsupported Semantic type! ({inputParam.SemanticName})"); } } } meshOffset += model.VertexCount * VertexStride; indices.AddRange(model.GetIndices().ToList()); } IndexCount = indices.Count; BufferDescription bd = new BufferDescription( (int)(verts.Length), ResourceUsage.Immutable, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None); VertexBuffer = new Buffer(device, DataStream.Create(verts, false, false), bd); bd = new BufferDescription( sizeof(int) * IndexCount, ResourceUsage.Immutable, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None); IndexBuffer = new Buffer(device, DataStream.Create(indices.ToArray(), false, false), bd); }
public override void Initialize() { Form.SizeChanged += (o, args) => { if (_swapChain == null) { return; } renderView.Dispose(); depthView.Dispose(); DisposeBuffers(); if (Form.WindowState == FormWindowState.Minimized) { return; } _width = Form.ClientSize.Width; _height = Form.ClientSize.Height; _swapChain.ResizeBuffers(_swapChain.Description.BufferCount, 0, 0, Format.Unknown, 0); CreateBuffers(); SetSceneConstants(); }; _width = 1024; _height = 768; _nearPlane = 1.0f; ambient = new Color4(Color.Gray.ToArgb()); try { OnInitializeDevice(); } catch (Exception e) { MessageBox.Show(e.ToString(), "Could not create DirectX 10 device."); return; } // shader.fx const ShaderFlags shaderFlags = ShaderFlags.None; //const ShaderFlags shaderFlags = ShaderFlags.Debug | ShaderFlags.SkipOptimization; ShaderBytecode shaderByteCode = LoadShader("shader.fx", shaderFlags); effect = new Effect(_device, shaderByteCode); EffectTechnique technique = effect.GetTechniqueByIndex(0); shadowGenPass = technique.GetPassByIndex(0); gBufferGenPass = technique.GetPassByIndex(1); debugDrawPass = technique.GetPassByName("debug"); BufferDescription sceneConstantsDesc = new BufferDescription() { SizeInBytes = Marshal.SizeOf(typeof(ShaderSceneConstants)), Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None }; sceneConstantsBuffer = new Buffer(_device, sceneConstantsDesc); EffectConstantBuffer effectConstantBuffer = effect.GetConstantBufferByName("scene"); effectConstantBuffer.SetConstantBuffer(sceneConstantsBuffer); RasterizerStateDescription desc = new RasterizerStateDescription() { CullMode = CullMode.None, FillMode = FillMode.Solid, IsFrontCounterClockwise = true, DepthBias = 0, DepthBiasClamp = 0, SlopeScaledDepthBias = 0, IsDepthClipEnabled = true, }; _device.Rasterizer.State = new RasterizerState(_device, desc); DepthStencilStateDescription depthDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less }; depthStencilState = new DepthStencilState(_device, depthDesc); DepthStencilStateDescription lightDepthStateDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less }; lightDepthStencilState = new DepthStencilState(_device, lightDepthStateDesc); // grender.fx shaderByteCode = LoadShader("grender.fx", shaderFlags); effect2 = new Effect(_device, shaderByteCode); technique = effect2.GetTechniqueByIndex(0); gBufferRenderPass = technique.GetPassByIndex(0); gBufferOverlayPass = technique.GetPassByIndex(1); info = new InfoText(_device); _meshFactory = new MeshFactory(this); MeshFactory = _meshFactory; CreateBuffers(); LibraryManager.LibraryStarted(); }
private static void Main() { var form = new RenderForm("SharpDX - MiniCube Direct3D 10 Sample"); // SwapChain description var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Create Device and SwapChain Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain); var context = device; // Ignore all windows events var factory = swapChain.GetParent <Factory>(); factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll); // New RenderTargetView from the backbuffer var backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0); var renderView = new RenderTargetView(device, backBuffer); // Compile Vertex and Pixel shaders var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "VS", "vs_4_0"); var vertexShader = new VertexShader(device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "PS", "ps_4_0"); var pixelShader = new PixelShader(device, pixelShaderByteCode); // Layout from VertexShader input signature var layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) }); // Instantiate Vertex buiffer from vertex data var vertices = Buffer.Create(device, BindFlags.VertexBuffer, new[] { new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), // Front new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), // BACK new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), // Top new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), // Bottom new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), // Left new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), // Right new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), }); // Create Constant Buffer var contantBuffer = new Buffer(device, Utilities.SizeOf <Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None); // Create Depth Buffer & View var depthBuffer = new Texture2D(device, new Texture2DDescription() { Format = Format.D32_Float_S8X24_UInt, ArraySize = 1, MipLevels = 1, Width = form.ClientSize.Width, Height = form.ClientSize.Height, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }); var depthView = new DepthStencilView(device, depthBuffer); // Prepare All the stages context.InputAssembler.InputLayout = layout; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, Utilities.SizeOf <Vector4>() * 2, 0)); context.VertexShader.SetConstantBuffer(0, contantBuffer); context.VertexShader.Set(vertexShader); context.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f)); context.PixelShader.Set(pixelShader); // Prepare matrices var view = Matrix.LookAtLH(new Vector3(0, 0, -5), new Vector3(0, 0, 0), Vector3.UnitY); var proj = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, form.ClientSize.Width / (float)form.ClientSize.Height, 0.1f, 100.0f); var viewProj = Matrix.Multiply(view, proj); // Use clock var clock = new Stopwatch(); clock.Start(); // Main loop RenderLoop.Run(form, () => { var time = clock.ElapsedMilliseconds / 1000.0f; // Clear views context.OutputMerger.SetTargets(depthView, renderView); context.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0); context.ClearRenderTargetView(renderView, Color.Black); // Update WorldViewProj Matrix var worldViewProj = Matrix.RotationX(time) * Matrix.RotationY(time * 2) * Matrix.RotationZ(time * .7f) * viewProj; worldViewProj.Transpose(); context.UpdateSubresource(ref worldViewProj, contantBuffer); // Draw the cube context.Draw(36, 0); // Present! swapChain.Present(0, PresentFlags.None); }); // Release all resources vertexShaderByteCode.Dispose(); vertexShader.Dispose(); pixelShaderByteCode.Dispose(); pixelShader.Dispose(); vertices.Dispose(); layout.Dispose(); renderView.Dispose(); backBuffer.Dispose(); context.ClearState(); context.Flush(); device.Dispose(); context.Dispose(); swapChain.Dispose(); factory.Dispose(); }
public void Update(TimeSpan timeSpan) { if (!isRunning) { return; } TimeSpan ts = (DateTime.Now - Last); Time.Dt = (float)ts.TotalSeconds; //Time.Dt = 1.0f / 60.0f; Last = DateTime.Now; double fps = 1 / ts.TotalSeconds; sumFps += (float)fps; Profiles.Current.State.Score = Math.Max((int)(PlayerShip.Instance.Position.Y / 10), Profiles.Current.State.Score); if (counter++ % 60 == 0) { { float fa = 0.18618986725025f; float fb = 210125.0f / 156.0f; float fc = 31.0f / 6.0f; maxEntities = (int)(fa * Math.Sqrt(fb + Profiles.Current.State.Score) + fc); } { float fa = 38.0f / 9.0f; float fb = 70.0f / 9.0f; float fc = 200f; float x = (float)Profiles.Current.State.Score / 1000.0f; linesSpeed = (int)(fa * x * x + fb * x + fc); } } for (int i = EntityManager.Count; i < maxEntities; i++) { EntityManager.Add(Rock.Create()); } EntityManager.Update(); ParticleManager.Update(); Profiles.Current.State.LinesPosition += linesSpeed * Time.Dt; if (Profiles.Current.State.LinesPosition > PlayerShip.Instance.Position.Y) { GameOver(); } Device device = Host.Device; if (ParticleManager.particleList.Count > 0) { DataStream particles = new DataStream(ParticleManager.particleList.Count * 32, true, true); for (int i = 0; i < ParticleManager.particleList.Count; i++) { var particle = ParticleManager.particleList[i]; Vector2 a = new Vector2(particle.Position.X, particle.Position.Y); Vector2 b = new Vector2(particle.Scale.X, -particle.Orientation); particles.WriteRange(new[] { a, b }); particles.Write(particle.Color); } particles.Position = 0; Disposer.RemoveAndDispose(ref this.Particles); this.Particles = new Buffer(device, particles, new BufferDescription() { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = ParticleManager.particleList.Count * 32, Usage = ResourceUsage.Default }); Disposer.RemoveAndDispose(ref particles); } }
private static void Main() { var form = new RenderForm("SharpDX - MiniCube Direct3D 10 Sample"); // SwapChain description var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription= new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Create Device and SwapChain Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain); var context = device; // Ignore all windows events var factory = swapChain.GetParent<Factory>(); factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll); // New RenderTargetView from the backbuffer var backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0); var renderView = new RenderTargetView(device, backBuffer); // Compile Vertex and Pixel shaders var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "VS", "vs_4_0"); var vertexShader = new VertexShader(device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "PS", "ps_4_0"); var pixelShader = new PixelShader(device, pixelShaderByteCode); // Layout from VertexShader input signature var layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) }); // Instantiate Vertex buiffer from vertex data var vertices = Buffer.Create(device, BindFlags.VertexBuffer, new[] { new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), // Front new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4( 1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4( 1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4( 1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), // BACK new Vector4( 1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4( 1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4( 1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), // Top new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4( 1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4( 1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4( 1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f,-1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), // Bottom new Vector4( 1.0f,-1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f,-1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f,-1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4( 1.0f,-1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4( 1.0f,-1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), // Left new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4( 1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), // Right new Vector4( 1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4( 1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4( 1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4( 1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4( 1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), }); // Create Constant Buffer var contantBuffer = new Buffer(device, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None); // Create Depth Buffer & View var depthBuffer = new Texture2D(device, new Texture2DDescription() { Format = Format.D32_Float_S8X24_UInt, ArraySize = 1, MipLevels = 1, Width = form.ClientSize.Width, Height = form.ClientSize.Height, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }); var depthView = new DepthStencilView(device, depthBuffer); // Prepare All the stages context.InputAssembler.InputLayout = layout; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, Utilities.SizeOf<Vector4>() * 2, 0)); context.VertexShader.SetConstantBuffer(0, contantBuffer); context.VertexShader.Set(vertexShader); context.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f)); context.PixelShader.Set(pixelShader); // Prepare matrices var view = Matrix.LookAtLH(new Vector3(0, 0, -5), new Vector3(0, 0, 0), Vector3.UnitY); var proj = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, form.ClientSize.Width / (float)form.ClientSize.Height, 0.1f, 100.0f); var viewProj = Matrix.Multiply(view, proj); // Use clock var clock = new Stopwatch(); clock.Start(); // Main loop RenderLoop.Run(form, () => { var time = clock.ElapsedMilliseconds / 1000.0f; // Clear views context.OutputMerger.SetTargets(depthView, renderView); context.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0); context.ClearRenderTargetView(renderView, Color.Black); // Update WorldViewProj Matrix var worldViewProj = Matrix.RotationX(time) * Matrix.RotationY(time * 2) * Matrix.RotationZ(time * .7f) * viewProj; worldViewProj.Transpose(); context.UpdateSubresource(ref worldViewProj, contantBuffer); // Draw the cube context.Draw(36, 0); // Present! swapChain.Present(0, PresentFlags.None); }); // Release all resources vertexShaderByteCode.Dispose(); vertexShader.Dispose(); pixelShaderByteCode.Dispose(); pixelShader.Dispose(); vertices.Dispose(); layout.Dispose(); renderView.Dispose(); backBuffer.Dispose(); context.ClearState(); context.Flush(); device.Dispose(); context.Dispose(); swapChain.Dispose(); factory.Dispose(); }
private static void Main() { var form = new RenderForm("SharpDX - MiniTri Direct3D 10 Sample"); // SwapChain description var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Create Device and SwapChain Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, desc, out device, out swapChain); // Ignore all windows events Factory factory = swapChain.GetParent<Factory>(); factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll); // New RenderTargetView from the backbuffer Texture2D backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0); var renderView = new RenderTargetView(device, backBuffer); // Compile Vertex and Pixel shaders var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "VS", "vs_4_0", ShaderFlags.None, EffectFlags.None); var vertexShader = new VertexShader(device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "PS", "ps_4_0", ShaderFlags.None, EffectFlags.None); var pixelShader = new PixelShader(device, pixelShaderByteCode); // Layout from VertexShader input signature var layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), new[] { new InputElement("POSITION",0,Format.R32G32B32A32_Float,0,0), new InputElement("COLOR",0,Format.R32G32B32A32_Float,16,0) }); // Write vertex data to a datastream var stream = new DataStream(32*3, true, true); stream.WriteRange(new[] { new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f) }); stream.Position = 0; // Instantiate Vertex buiffer from vertex data var vertices = new Buffer(device, stream, new BufferDescription() { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = 32*3, Usage = ResourceUsage.Default, }); stream.Release(); // Prepare All the stages device.InputAssembler.SetInputLayout(layout); device.InputAssembler.SetPrimitiveTopology(PrimitiveTopology.TriangleList); device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, 32, 0)); device.VertexShader.Set(vertexShader); device.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f)); device.PixelShader.Set(pixelShader); device.OutputMerger.SetTargets(renderView); // Main loop RenderLoop.Run(form, () => { device.ClearRenderTargetView(renderView, new Color4(1.0f, 0.0f, 0.0f, 0.0f)); device.Draw(3, 0); swapChain.Present(0, PresentFlags.None); }); // Release all resources vertexShaderByteCode.Release(); vertexShader.Release(); pixelShaderByteCode.Release(); pixelShader.Release(); vertices.Release(); layout.Release(); renderView.Release(); backBuffer.Release(); device.ClearState(); device.Flush(); device.Release(); device.Release(); swapChain.Release(); factory.Release(); }
void IScene.Attach(ISceneHost host) { this.Host = host; Device device = host.Device; if (device == null) throw new Exception("Scene host device is null"); Uri executablePath = new Uri(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase); String shaderPath = System.IO.Path.GetDirectoryName(executablePath.LocalPath) + "\\Shaders\\"; if (videoPlayerViewModel.DecodedVideoFormat == VideoLib.VideoPlayer.DecodedVideoFormat.YUV420P) { shaderPath += "YUVtoRGB.fx"; } else { shaderPath += "Simple.fx"; } try { ShaderBytecode shaderBytes = ShaderBytecode.CompileFromFile(shaderPath, "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null); this.SimpleEffect = new Effect(device, shaderBytes); } catch (Exception e) { System.Diagnostics.Debug.Print(e.Message); throw new Exception("Error compiling: " + shaderPath); } EffectTechnique technique = this.SimpleEffect.GetTechniqueByIndex(0); EffectPass pass = technique.GetPassByIndex(0); this.VertexLayout = new InputLayout(device, pass.Description.Signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32B32A32_Float, InputElement.AppendAligned, 0) //new InputElement("COLOR", 0, Format.R32G32B32A32_Float, InputElement.AppendAligned, 0) }); int bytesPerVertexInfo = 4 * 8; nrVertices = 4; this.VertexStream = new DataStream(bytesPerVertexInfo * nrVertices, true, true); this.VertexStream.WriteRange(new[] { new Vector4(-1.0f, 1.0f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 0.0f, 0.0f), new Vector4(1.0f, -1.0f, 0.5f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 0.0f), new Vector4(-1.0f, -1.0f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 0.0f), new Vector4(1.0f, 1.0f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 0.0f) } ); this.VertexStream.Position = 0; this.Vertices = new Buffer(device, this.VertexStream, new BufferDescription() { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = bytesPerVertexInfo * nrVertices, Usage = ResourceUsage.Default } ); nrIndices = 4; int indicesSizeBytes = nrIndices * sizeof(Int32); IndexStream = new DataStream(indicesSizeBytes, true, true); IndexStream.WriteRange<int>(new[] { 3,1,0,2 } ); this.IndexStream.Position = 0; this.Indices = new Buffer(device, this.IndexStream, new BufferDescription() { BindFlags = BindFlags.IndexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = indicesSizeBytes, Usage = ResourceUsage.Default } ); device.Flush(); }