/// <summary> /// Constructor /// </summary> /// <param name="device">Device</param> /// <param name="model">Model Data</param> public SharpModel(SharpDevice device, ModelData model) { this.Name = model.Name; this.Device = device; Children = new List<Node>(); Geometries = new List<Geometry>(); Animations = new List<AnimationManager>(); foreach (var m in model.Nodes) { var c = new Node(Device, m, this); Children.Add(c); } //Animations Animations = new List<AnimationManager>(); foreach (Animation anim in model.Animations) { //carica le animazioni Animations.Add(new AnimationManager(anim)); } Initialize(); SetTime(0); }
//Constructor internal Geometry(SharpDevice device, ModelGeometry data, bool animated) { this.Name = data.Name; this.Device = device; //Data List<VertexFormat> vertices = new List<VertexFormat>(data.Vertices); List<int> indices = new List<int>(data.Indices); VertexCount = vertices.Count; IndexCount = indices.Count; //Vertex Buffer VertexBuffer = SharpDX.Direct3D11.Buffer.Create<VertexFormat>(Device.Device, BindFlags.VertexBuffer, vertices.ToArray()); //Index Buffer IndexBuffer = SharpDX.Direct3D11.Buffer.Create<int>(Device.Device, BindFlags.IndexBuffer, indices.ToArray()); Material = new Material(data.Material); IsAnimated = animated; transformBuffer = new Buffer11(Device.Device, Utilities.SizeOf<SkinShaderInformation>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); paletteBuffer = new Buffer11(Device.Device, Utilities.SizeOf<Matrix>() * 256, ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); }
/// <summary> /// Constructor /// </summary> /// <param name="device">Device</param> /// <param name="model">Model Data</param> public SharpModel(SharpDevice device, ModelData model) { this.Name = model.Name; this.Device = device; Children = new List <Node>(); Geometries = new List <Geometry>(); Animations = new List <AnimationManager>(); foreach (var m in model.Nodes) { var c = new Node(Device, m, this); Children.Add(c); } //Animations Animations = new List <AnimationManager>(); foreach (Animation anim in model.Animations) { //carica le animazioni Animations.Add(new AnimationManager(anim)); } Initialize(); SetTime(0); }
//Constructor internal Geometry(SharpDevice device, ModelGeometry data, bool animated) { this.Name = data.Name; this.Device = device; //Data List <VertexFormat> vertices = new List <VertexFormat>(data.Vertices); List <int> indices = new List <int>(data.Indices); VertexCount = vertices.Count; IndexCount = indices.Count; //Vertex Buffer VertexBuffer = SharpDX.Direct3D11.Buffer.Create <VertexFormat>(Device.Device, BindFlags.VertexBuffer, vertices.ToArray()); //Index Buffer IndexBuffer = SharpDX.Direct3D11.Buffer.Create <int>(Device.Device, BindFlags.IndexBuffer, indices.ToArray()); Material = new Material(data.Material); IsAnimated = animated; transformBuffer = new Buffer11(Device.Device, Utilities.SizeOf <SkinShaderInformation>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); paletteBuffer = new Buffer11(Device.Device, Utilities.SizeOf <Matrix>() * 256, ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); }
/// <summary> /// Constructor /// </summary> /// <param name="device">Device</param> /// <param name="node">Parent Node</param> /// <param name="Model">Sharp Model</param> public Node(SharpDevice device, ModelNode node, SharpModel Model) { Name = node.Name; World = node.World; PreComputed = this.World; Children = new List<Node>(); //Create Child Nodes foreach (var m in node.Children) { var c = new Node(device, m, Model); c.Parent = this; Children.Add(c); } //Create Node Geometries foreach (var g in node.Geometries) { var g3d = new Geometry(device, g, node.Skinning != null); g3d.Node = this; Model.Geometries.Add(g3d); } //Get Skinning Data if (node.Skinning != null) { Skinning = new SkinData() { BindMatrix = node.Skinning.BindMatrix, InverseBindMatrix = new List<Matrix>(node.Skinning.InverseBinding), JointNames = new List<string>(node.Skinning.JointNames), }; } }
public void Update(SharpDevice device, Matrix View, Matrix Projection) { TransUpdate( ); SendGPUData(device, View, Projection); MMDModelMorph.UpdateMorph(OrigVertice, Vertice); UpdateMesh( ); Mesh.Begin( ); for (int i = 0; i < Mesh.SubSets.Count; i++) { SharpSubSet sharpSubSet = Mesh.SubSets[i]; PixelShaderStage pixelShader = device.DeviceContext.PixelShader; MaterialGPUData materialData = Materials[i].MaterialData; device.DeviceContext.PixelShader.SetShaderResource(0, sharpSubSet.DiffuseMap); device.DeviceContext.PixelShader.SetShaderResource(1, sharpSubSet.SphereMap); pixelShader.SetConstantBuffer(1, MaterialDataBuffer); device.UpdateData(MaterialDataBuffer, materialData); //set texture Mesh.Draw(i); } // https://gamedev.stackexchange.com/questions/49779/different-shaders-for-different-objects-directx-11 }
/// <summary> /// Constructor /// </summary> /// <param name="device">Device</param> /// <param name="node">Parent Node</param> /// <param name="Model">Sharp Model</param> public Node(SharpDevice device, ModelNode node, SharpModel Model) { Name = node.Name; World = node.World; PreComputed = this.World; Children = new List <Node>(); //Create Child Nodes foreach (var m in node.Children) { var c = new Node(device, m, Model); c.Parent = this; Children.Add(c); } //Create Node Geometries foreach (var g in node.Geometries) { var g3d = new Geometry(device, g, node.Skinning != null); g3d.Node = this; Model.Geometries.Add(g3d); } //Get Skinning Data if (node.Skinning != null) { Skinning = new SkinData() { BindMatrix = node.Skinning.BindMatrix, InverseBindMatrix = new List <Matrix>(node.Skinning.InverseBinding), JointNames = new List <string>(node.Skinning.JointNames), }; } }
public static void Main( string[] args ) { if ( !SharpDevice.IsDirectX11Supported( ) ) { MessageBox.Show( "DirectX11 Not Supported" ); return; } OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "pmx|*.pmx"; if ( openFileDialog.ShowDialog( ) == DialogResult.OK ) { string V = openFileDialog.FileName; //PMXLoader.WriteTestCSV( V ); LoadedFromDialog = new PMXLoader( V ); Model = LoadedFromDialog.MMDModel; MorphViewer = new VertMorphViewer( Model.Morphs ); Model.BindMorphProp( MorphViewer.BarValues ); MorphViewer.Show( ); ModForm = new BlenderModifier.SphereModForm( LoadedFromDialog); ModForm.OnLoadReferenceModel = OnLoadReferenceModel; NormalStart( ); } }
public static void NormalStart() { //render form Form = new RenderForm( ); Form.Text = "MMD Model Viewer"; ModForm.Show( ); ModForm.SetFactorBoxChanged( OnFactorTextChanged ); ModForm.SetRadiusBoxChanged( OnFactorTextChanged ); ModForm.SetAlphaBarChanged( OnAlphaBarChanged ); ModForm.SetOffsetBoxChanged( OnOffsetBoxChanged ); ModForm.SetMorphNameChanged( OnMorphNameChanged ); ModForm.SetScaleChanged( OnScaleChanged ); ModForm.SetRotChanged( OnRotTextChanged ); #region addEvent Form.MouseClick += Form_MouseClick; Form.MouseMove += Form_MouseMove; Form.MouseWheel += Form_MouseWheel; Form.KeyUp += Form_KeyUp; Form.FormClosed += Form_FormClosed; ; Debug = new VDBDebugger( ); #endregion using ( SharpDevice device = new SharpDevice( Form ) ) { #if Lattice LatticeForm = new LatticeForm( Model , device ); LatticeForm.Show( ); #endif Model.LoadTexture( device ); Axis.LoadTexture( device ); #if Lattice LatticeForm.LoadTexture( device ); #endif #if DEBUGLINE Line.LoadTexture(device); Line.AfterLoaded(); #endif //init frame counter FpsCounter.Reset( ); device.SetBlend( BlendOperation.Add , BlendOption.SourceAlpha , BlendOption.InverseSourceAlpha ); OnResizeForm( ( float )Form.ClientRectangle.Width / Form.ClientRectangle.Height , device ); //main loop RenderLoop.Run( Form , () => OnUpdate( device ) ); //release resource Model.Dispose( ); RefModel?.Dispose( ); Axis.Dispose( ); #if DEBUGLINE Line.Dispose(); #endif } }
public Water(SharpDevice device) { vertices = new ColoredVertex[N * M]; for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { vertices[i * N + j] = new ColoredVertex( new Vector3(i * size / N + botLeftCorner.X, 0 + botLeftCorner.Y, j * size / M + botLeftCorner.Z), new Vector4((i + 0.0f) / M, (j + 0.0f) / N, 0, 1) ); } } indices = new int[6 * (N - 1) * (M - 1)]; for (int i = 0; i < M - 1; i++) { for (int j = 0; j < N - 1; j++) { int act = i * (N - 1) + j; int fullIndex = i * N + j; indices[6 * act + 0] = fullIndex; indices[6 * act + 1] = fullIndex + 1; indices[6 * act + 2] = fullIndex + N; indices[6 * act + 3] = fullIndex + 1; indices[6 * act + 4] = fullIndex + N + 1; indices[6 * act + 5] = fullIndex + N; } } this.createMesh(device); }
SharpMesh GetSharpMesh(SharpDevice device) { SharpMesh mesh = new SharpMesh(device); List <int> indices = new List <int>( ); List <Face> faces = new List <Face>( ); List <string> texList = new List <string>( ); List <string> notFoundTexList = new List <string>( ); int icount = 0; foreach (Material item in Materials) { indices.AddRange(item.FlattenFace); int faceCount = item.FlattenFace.Count( ); SharpSubSet subSet = new SharpSubSet( ) { IndexCount = faceCount, StartIndex = icount, }; if (item.TexName != string.Empty) { var filename = TryGetResource(device, item.TexName); // 存在しないパスなら読まない filename.Match(() => notFoundTexList.Add(item.TexName), r => subSet.DiffuseMap = r); } if (item.SphereName != string.Empty) { var filename = TryGetResource(device, item.SphereName); filename.Match(() => notFoundTexList.Add(item.SphereName), r => subSet.SphereMap = r); } mesh.SubSets.Add(subSet); for (int i = icount; i < icount + faceCount; i += 3) { int ind1 = indices[i]; int ind2 = indices[i + 1]; int ind3 = indices[i + 2]; Face item1 = new Face(Vertice[ind1].Position, Vertice[ind2].Position, Vertice[ind3].Position, item.Name); //Debug.WriteLine("first " + item1.TriString); faces.Add(item1); } icount += faceCount; } Index = indices.ToArray( ); Faces = faces.ToArray( ); var inds = Index.Select(x => x.ToString( )); var facesS = Faces.Select(x => x.ToString( )); //inds.Concat( facesS ).Concat( texList ).WriteFile( DirPath + "loadedFile.txt" ); notFoundTexList.WriteFile(DirPath + "notFoundTextures.txt"); ModelStr = Faces.Select(f => f.TriString).ConcatStr( ); mesh.SetOnly(Vertice, Index); return(mesh); }
static void PostViewUpdate( SharpDevice device ) { FpsCounter.Update( ); CameraRay = new RayWrap( Ray.GetPickRay( ( int )Clicked.X , ( int )Clicked.Y , Viewport , View * Projection ) ); RayWrap currentRay = new RayWrap( Ray.GetPickRay( ( int )Mouse.Position.X , ( int )Mouse.Position.Y , Viewport , View * Projection ) ); #if FONT // 最小化したときフォントがなくなることがあった device.Font.Begin( ); //draw string device.Font.DrawString( "FPS: " + FpsCounter.FPS , 0 , 0 ); device.Font.DrawString( "mouse: " + CameraRay.From , 0 , 30 ); device.Font.DrawString( "mouseto: " + CameraRay.To , 0 , 60 ); //Debug.vdb_label( "model" ); //Debug.Send( Axis.ModelStr ); Debug.vdb_label( "ray" ); Debug.Send( CameraRay.RayStr ); #endif var hits = Axis.HitPos( CameraRay ).ToArray( ); for ( int j = 0 ; j < hits.Count( ) ; j++ ) { Debug.vdb_label( "hit" ); Debug.Send( hits[ j ].HitPosition.DebugStr( ) ); #if FONT device.Font.DrawString( "hit: " + hits[ j ].Info , 0 , 90 + 30 * j ); #endif } Axis.OnClicked( Mouse , currentRay ); //Axis.Scale = new Vector3( 0.5f ); ModForm.SetOffset( Axis.Position ); ModForm.EulerRotate = Axis.Rotation.EulerAngle( ); #if DEBUGLINE //Line.OnClicked(Mouse, currentRay); //Line.SetLine( Vector3.Zero , Axis.RotXFrame); //line.SetLine(new Vector3(2,-12,-12), new Vector3(-8,8,10)); #endif #if ENABLE_SPHERE Model.ToSphere( Axis.World ); Model.ToSphere( Axis.World.InvX( ) , true ); #else LatticeForm.FixedUpdate( View , Projection ); Debug.vdb_label( "lattice" ); foreach ( var item in LatticeForm.AllLatticeString) { //item.DebugWrite( ); Debug.Send( item ); } LatticeForm.OnClicked( Mouse , currentRay ); #endif #if FONT //flush text to view device.Font.End( ); #endif }
/// <summary> /// Create a batch manager for drawing text and sprite /// </summary> /// <param name="device">Device pointer</param> /// <param name="filename">Path of the font file</param> public SharpBatch(SharpDevice device, string filename) { Device = device; GraphicsDevice = GraphicsDevice.New(Device.Device); GraphicsDevice.SetViewports(Device.DeviceContext.Rasterizer.GetViewports()[0]); Batch = new SpriteBatch(GraphicsDevice); Font = SpriteFont.Load(GraphicsDevice, filename); }
public void LoadTexture(SharpDevice device) { Mesh = GetSharpMesh(device); PrepareShader(device, "../../HLSLModel.txt"); MaterialDataBuffer = Shader.CreateBuffer <MaterialGPUData>( ); }
/// <summary> /// Draw Animated Model /// </summary> /// <param name="device">Device</param> /// <param name="information">Information</param> public void Draw(SharpDevice device, SkinShaderInformation information) { //Iterate each geometry foreach (Geometry g in Geometries) { g.Apply(information); g.Draw(device.DeviceContext); } }
/// <summary> /// Constructor /// </summary> /// <param name="device">Device</param> /// <param name="breakOnWarning">Generate an error on warning</param> public SharpDebugger(SharpDevice device, bool breakOnWarning) { _device = device; //init the debug device Debug = new DeviceDebug(device.Device); //init the queue interface Queue = Debug.QueryInterface<InfoQueue>(); if (breakOnWarning) Queue.SetBreakOnSeverity(MessageSeverity.Warning, true); }
/// <summary> /// Constructor /// </summary> /// <param name="device">Device</param> /// <param name="size">Buffer size</param> public SharpOutputBuffer(SharpDevice device, int size) { Device = device; BufferDescription desc = new BufferDescription() { SizeInBytes = size, BindFlags = BindFlags.VertexBuffer | BindFlags.StreamOutput, Usage = ResourceUsage.Default, }; _buffer = new Buffer11(Device.Device, desc); }
Option <ShaderResourceView> TryGetResource(SharpDevice device, string path) { string filename = DirPath + Path.DirectorySeparatorChar + path; if (File.Exists(filename)) { return(Option.Return(device.LoadTextureFromFile(filename))); } else { return(Option.Return <ShaderResourceView>( )); } }
protected void SendGPUData(SharpDevice device, Matrix View, Matrix Projection) { //apply shader Shader.Apply( ); //apply constant buffer to shader VertexShader.SetConstantBuffer(0, GPUDataBuffer); PixelShader.SetConstantBuffer(0, GPUDataBuffer); GpuData.View = View; GpuData.WorldViewProjection = World * View * Projection; GpuData.World = World; device.UpdateData(GPUDataBuffer, GpuData); }
static void Main() { if (!SharpDevice.IsDirectX11Supported()) { System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported"); return; } //render form RenderForm form = new RenderForm(); form.Text = "Tutorial 3: Font"; //main loop using (SharpDevice device = new SharpDevice(form)) { //create font from file (generated with tkfont.exe) SharpBatch font = new SharpBatch(device, "textfont.dds"); RenderLoop.Run(form, () => { //resize if form was resized if (device.MustResize) { device.Resize(); font.Resize(); } //clear color device.Clear(Color.CornflowerBlue); //begin drawing text font.Begin(); //draw string font.DrawString("Hello SharpDX", 0, 0, Color.White); font.DrawString("Current Time " + DateTime.Now.ToString(), 0, 32, Color.White); //flush text to view font.End(); //present device.Present(); }); font.Dispose(); } }
static void Main() { if (!SharpDevice.IsDirectX11Supported()) { System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported"); return; } //render form RenderForm form = new RenderForm(); form.Text = "Tutorial 3: Font"; //main loop using (SharpDevice device = new SharpDevice(form)) { //create font from file (generated with tkfont.exe) SharpBatch font = new SharpBatch(device, "textfont.dds"); RenderLoop.Run(form, () => { //resize if form was resized if (device.MustResize) { device.Resize(); font.Resize(); } //clear color device.Clear(Color.CornflowerBlue); //begin drawing text font.Begin(); //draw string font.DrawString("Hello SharpDX", 0, 0, Color.White); font.DrawString("Current Time " + DateTime.Now.ToString(), 0, 32, Color.White); //flush text to view font.End(); //present device.Present(); }); font.Dispose(); } }
protected void PrepareShader(SharpDevice device, string shaderPath) { //init shader Shader = new SharpShader(device, shaderPath, new SharpShaderDescription( ) { VertexShaderFunction = "VS", PixelShaderFunction = "PS" }, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 24, 0) }); VertexShader = device.DeviceContext.VertexShader; PixelShader = device.DeviceContext.PixelShader; GPUDataBuffer = Shader.CreateBuffer <GPUData>( ); }
static void Main() { if (!SharpDevice.IsDirectX11Supported()) { System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported"); return; } //render form RenderForm form = new RenderForm(); form.Text = "Tutorial 3: Font"; //main loop using (SharpDevice device = new SharpDevice(form)) { RenderLoop.Run(form, () => { //resize if form was resized if (device.MustResize) { device.Resize(); } //clear color device.Clear(Color.CornflowerBlue); //begin drawing text device.Font.Begin(); //draw string device.Font.DrawString("Hello SharpDX", 0, 0); device.Font.DrawString("Current Time " + DateTime.Now.ToString(), 0, 32); //flush text to view device.Font.End(); //present device.Present(); }); } }
static void Main() { if (!SharpDevice.IsDirectX11Supported()) { System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported"); return; } //render form RenderForm form = new RenderForm(); form.Text = "Tutorial 3: Font"; //main loop using (SharpDevice device = new SharpDevice(form)) { RenderLoop.Run(form, () => { //resize if form was resized if (device.MustResize) { device.Resize(); } //clear color device.Clear(Color.CornflowerBlue); //begin drawing text device.Font.Begin(); //draw string device.Font.DrawString("Hello SharpDX", 0, 0); device.Font.DrawString("Current Time " + DateTime.Now.ToString(), 0, 32); //flush text to view device.Font.End(); //present device.Present(); }); } }
/// <summary> /// Constructor /// </summary> /// <param name="device">Device</param> /// <param name="size">Cube Size</param> /// <param name="format">Color Format</param> public SharpCubeTarget(SharpDevice device, int size, Format format) { Device = device; Size = size; Texture2D target = new Texture2D(device.Device, new Texture2DDescription() { Format = format, Width = size, Height = size, ArraySize = 6, BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, MipLevels = 1, OptionFlags = ResourceOptionFlags.TextureCube, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, }); _target = new RenderTargetView(device.Device, target); _resource = new ShaderResourceView(device.Device, target); ComObject.Dispose(ref target); var _zbufferTexture = new Texture2D(Device.Device, new Texture2DDescription() { Format = Format.D16_UNorm, ArraySize = 6, MipLevels = 1, Width = size, Height = size, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.TextureCube }); // Create the depth buffer view _zbuffer = new DepthStencilView(Device.Device, _zbufferTexture); ComObject.Dispose(ref _zbufferTexture); }
/// <summary> /// Constructor /// </summary> /// <param name="device">Device</param> /// <param name="width">Width</param> /// <param name="height">Height</param> /// <param name="format">Format</param> public SharpRenderTarget(SharpDevice device, int width, int height, Format format) { Device = device; Height = height; Width = width; Texture2D target = new Texture2D(device.Device, new Texture2DDescription() { Format = format, Width = width, Height = height, ArraySize = 1, BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, }); _target = new RenderTargetView(device.Device, target); _resource = new ShaderResourceView(device.Device, target); target.Dispose(); var _zbufferTexture = new Texture2D(Device.Device, new Texture2DDescription() { Format = Format.D16_UNorm, ArraySize = 1, MipLevels = 1, Width = width, Height = height, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }); // Create the depth buffer view _zbuffer = new DepthStencilView(Device.Device, _zbufferTexture); _zbufferTexture.Dispose(); }
public static void RenderQuadTree2(SharpDevice device, SharpShader shader, SharpDX.Direct3D11.Buffer buffer, Matrix viewProjection) { if (secondQuadTreeMesh == null) { return; } secondQuadtreeRenderData.worldViewProjection = quadTreeTranslation * viewProjection; device.SetFillModeSolid(); device.SetCullModeNone(); device.SetDefaultBlendState(); device.ApplyRasterState(); device.UpdateAllStates(); device.UpdateData(buffer, secondQuadtreeRenderData); device.DeviceContext.VertexShader.SetConstantBuffer(0, buffer); shader.Apply(); secondQuadTreeMesh.Draw(); }
public LatticeForm(MMDModel model, SharpDevice device) { InitializeComponent( ); Lattice = new LatticeDef(model, new int[] { 4, 4, 4 }); //foreach ( var item in Lattice.LatticeData ) for (int i = 0; i < Lattice.LatticeData.Length; i++) { var item = Lattice.LatticeData[i]; var pos = item.Value.Position; SharpMesh mesh = SharpMesh.CreateQuad(device, 0.1f, true); ModelInWorld rectModel = ModelInWorld.Create(mesh, pos.TransMat( ), "../../HLSL.txt"); LatticePoint.Add(rectModel); rectModel.SetFaceFromSharpMesh("lattice" + i); } var lats = new[] { Lat0, Lat1, Lat2, Lat3, Lat4, Lat5, Lat6, Lat7, Lat8, }; for (int i = 0; i < lats.Length; i++) { #if true Lattice.LatticeString[i].BindTo(lats[i], x => x.Text, BindingMode.TwoWay, targetUpdateTrigger: ReactiveHelper.TextBoxChanged(lats[i])); #endif } LatticePointControl = new DraggableAxis("axis/axisold.csv"); }
public void DetermineQuadtreeRenderStuff(ref CLFile data, SharpDevice device, ProgressBar bar) { List <Vertex> QuadNodeVertexList = new List <Vertex>(); List <int> QuadNodeIndexList = new List <int>(); int k = 0; foreach (QuadNode i in data.CLQuadNodeList) { bar.PerformStep(); if (i.Child == 0 | i.Index == 0) { QuadNodeVertexList.Add(new Vertex(new Vector3(i.NodeSquare.X, 0, i.NodeSquare.Y))); QuadNodeIndexList.Add(k); QuadNodeIndexList.Add(k + 1); QuadNodeVertexList.Add(new Vertex(new Vector3(i.NodeSquare.X + i.NodeSquare.Width, 0, i.NodeSquare.Y))); QuadNodeIndexList.Add(k + 1); QuadNodeIndexList.Add(k + 2); QuadNodeVertexList.Add(new Vertex(new Vector3(i.NodeSquare.X + i.NodeSquare.Width, 0, i.NodeSquare.Y + i.NodeSquare.Height))); QuadNodeIndexList.Add(k + 2); QuadNodeIndexList.Add(k + 3); QuadNodeVertexList.Add(new Vertex(new Vector3(i.NodeSquare.X, 0, i.NodeSquare.Y + i.NodeSquare.Height))); QuadNodeIndexList.Add(k + 3); QuadNodeIndexList.Add(k); k += 4; } } if (quadTreeMesh != null) { quadTreeMesh.Dispose(); } quadTreeMesh = SharpMesh.Create(device, QuadNodeVertexList.ToArray(), QuadNodeIndexList.ToArray(), new List <SharpSubSet>() { new SharpSubSet(0, QuadNodeIndexList.Count, null) }, SharpDX.Direct3D.PrimitiveTopology.LineList); mainQuadtreeRenderData.Color = new Vector4(0.9f, 0.3f, 0.6f, 1f); }
public CLFile LoadCLFile(string FileName, SharpDevice device, ProgressBar bar) { CLFile data = new CLFile(0); BinaryReader CLReader = new BinaryReader(new FileStream(FileName, FileMode.Open)); CLReader.BaseStream.Position = 0; data.numBytes = Switch(CLReader.ReadUInt32()); //Get total number of bytes in file if (data.numBytes != CLReader.BaseStream.Length) { throw new ArgumentException("Not a valid CL file."); } //Get offset of structs data.pointQuadtree = Switch(CLReader.ReadUInt32()); data.pointTriangle = Switch(CLReader.ReadUInt32()); data.pointVertex = Switch(CLReader.ReadUInt32()); //Get quadtree center and radius data.quadCenterX = Switch(CLReader.ReadSingle()); data.quadCenterY = Switch(CLReader.ReadSingle()); data.quadCenterZ = Switch(CLReader.ReadSingle()); data.quadLength = Switch(CLReader.ReadSingle()); //Get amount of stuff data.basePower = Switch(CLReader.ReadUInt16()); data.numTriangles = Switch(CLReader.ReadUInt16()); data.numVertices = Switch(CLReader.ReadUInt16()); data.numQuadnodes = Switch(CLReader.ReadUInt16()); bar.Maximum = data.numTriangles + data.numVertices + 3 * data.numQuadnodes; List <Triangle> CLTriangleList = new List <Triangle>(data.numTriangles); List <CollisionVertex> CLVertexList = new List <CollisionVertex>(data.numVertices); data.MeshTypeList = new List <UInt64>(); for (int i = 0; i < data.numVertices; i++) { CLReader.BaseStream.Position = data.pointVertex + i * 0xC; CLVertexList.Add(new CollisionVertex(Switch(CLReader.ReadSingle()), Switch(CLReader.ReadSingle()), Switch(CLReader.ReadSingle()))); bar.PerformStep(); } for (int i = 0; i < data.numTriangles; i++) { CLReader.BaseStream.Position = data.pointTriangle + i * 0x20; CLTriangleList.Add(new Triangle(Switch(CLReader.ReadUInt16()), Switch(CLReader.ReadUInt16()), Switch(CLReader.ReadUInt16()))); CLReader.BaseStream.Position += 6; Vector3 Normals = new Vector3(Switch(CLReader.ReadSingle()), Switch(CLReader.ReadSingle()), Switch(CLReader.ReadSingle())); CLVertexList[CLTriangleList[i].Vertices[0]].NormalList.Add(Normals); CLVertexList[CLTriangleList[i].Vertices[1]].NormalList.Add(Normals); CLVertexList[CLTriangleList[i].Vertices[2]].NormalList.Add(Normals); UInt64 FlagsAsUint64 = CLReader.ReadUInt64(); CLTriangleList[i].ColFlags = BitConverter.GetBytes(FlagsAsUint64); if (!data.MeshTypeList.Contains(FlagsAsUint64)) { data.MeshTypeList.Add(FlagsAsUint64); } Color TempColor = new Color(CLTriangleList[i].ColFlags[1], CLTriangleList[i].ColFlags[2], CLTriangleList[i].ColFlags[3]); if (TempColor.R == 0) { TempColor.R = 255; } else { TempColor.R = (byte)(256 - (Math.Log(TempColor.R, 2) + 1) * 32); } if (TempColor.G == 0) { TempColor.G = 255; } else { TempColor.G = (byte)(256 - (Math.Log(TempColor.G, 2) + 1) * 32); } if (TempColor.B == 0) { TempColor.B = 255; } else { TempColor.B = (byte)(256 - (Math.Log(TempColor.B, 2) + 1) * 32); } CLVertexList[CLTriangleList[i].Vertices[0]].Color = TempColor; CLVertexList[CLTriangleList[i].Vertices[1]].Color = TempColor; CLVertexList[CLTriangleList[i].Vertices[2]].Color = TempColor; bar.PerformStep(); } data.CLTriangleArray = CLTriangleList.ToArray(); for (int i = 0; i < data.numQuadnodes; i++) { CLReader.BaseStream.Position = data.pointQuadtree + i * 0x20; QuadNode TempNode = new QuadNode { Index = Switch(CLReader.ReadUInt16()), Parent = Switch(CLReader.ReadUInt16()), Child = Switch(CLReader.ReadUInt16()) }; CLReader.BaseStream.Position += 8; TempNode.NodeTriangleAmount = Switch(CLReader.ReadUInt16()); TempNode.TriListOffset = Switch(CLReader.ReadUInt32()); TempNode.PosValueX = Switch(CLReader.ReadUInt16()); TempNode.PosValueZ = Switch(CLReader.ReadUInt16()); TempNode.Depth = CLReader.ReadByte(); data.CLQuadNodeList.Add(TempNode); bar.PerformStep(); } ReBuildQuadtree(ref data, bar); DetermineQuadtreeRenderStuff(ref data, device, bar); CLReader.Close(); data.CLVertexArray = new VertexColoredNormalized[CLVertexList.Count()]; for (int i = 0; i < CLVertexList.Count; i++) { data.CLVertexArray[i] = new VertexColoredNormalized(CLVertexList[i].Position, CLVertexList[i].CalculateNormals(), CLVertexList[i].Color); } int[] IndexArray = new int[data.CLTriangleArray.Count() * 3]; for (int i = 0; i < data.CLTriangleArray.Count() * 3; i++) { IndexArray[i] = data.CLTriangleArray[i / 3].Vertices[i % 3]; } if (collisionMesh != null) { collisionMesh.Dispose(); } collisionMesh = SharpMesh.Create(device, data.CLVertexArray, IndexArray, new List <SharpSubSet>() { new SharpSubSet(0, IndexArray.Count(), null) }, SharpDX.Direct3D.PrimitiveTopology.TriangleList); return(data); }
static void Main() { if (!SharpDevice.IsDirectX11Supported()) { System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported"); return; } RenderForm form = new RenderForm(); form.Text = "Tutorial 19: Adaptive Tesselation"; SharpFPS fpsCounter = new SharpFPS(); using (SharpDevice device = new SharpDevice(form)) { SharpBatch font = new SharpBatch(device, "textfont.dds"); InputElement[] description = new InputElement[] { new InputElement("POSITION",0,SharpDX.DXGI.Format.R32G32B32_Float,0,0), new InputElement("TEXCOORD",0,SharpDX.DXGI.Format.R32G32_Float,12,0), }; SharpShader shader = new SharpShader(device, "../../Shader.hlsl", new SharpShaderDescription() { VertexShaderFunction = "VSMain", PixelShaderFunction = "PSMain", DomainShaderFunction = "DSMain", HullShaderFunction = "HSMain" }, description); int seqX = 64; int seqY = 64; float size = 100; float sizeW = seqX * size; float sizeH = seqY * size; TessellationVertex[] vertices = new TessellationVertex[4356]; int[] indices = new int[63504]; int k = 0; for (int y = -1; y < seqY + 1; y++) { for (int x = -1; x < seqX + 1; x++) { float vX = x * size - (seqX / 2.0F) * size; float vY = y * size - (seqY / 2.0F) * size; float vZ = 0; TessellationVertex v = new TessellationVertex(vX, vY, vZ, x / 4.0F, y / 4.0F); vertices[k] = v; k++; } } //indici k = 0; for (int y = 0; y < seqY - 1; y++) { for (int x = 0; x < seqX - 1; x++) { int startX = x + 1; int startY = y + 1; for (int j = -1; j < 3; j++) { for (int i = -1; i < 3; i++) { indices[k] = (i + startX + (seqX + 2) * (j + startY)); k++; } } } } SharpMesh mesh = SharpMesh.Create<TessellationVertex>(device, vertices, indices); string path = @"../../../Models/adaptive_tess/"; ShaderResourceView diffuseMap = ShaderResourceView.FromFile(device.Device, path + "D.dds"); ShaderResourceView normalMap = ShaderResourceView.FromFile(device.Device, path + "N.dds"); ShaderResourceView heightMap = ShaderResourceView.FromFile(device.Device, path + "H.dds"); Buffer11 buffer = shader.CreateBuffer<SceneData>(); fpsCounter.Reset(); float angle = 3.14F; float distance = 1200; float heightPos = 500; form.KeyDown += (sender, e) => { switch (e.KeyCode) { case Keys.A: distance -= 5; if (distance < 100) distance = 100; break; case Keys.Z: distance += 5; if (distance > 2000) distance = 2000; break; case Keys.Up: heightPos--; if (heightPos < 50) heightPos = 50; break; case Keys.Down: heightPos++; if (heightPos > 800) heightPos = 800; break; case Keys.Left: angle -= 0.01F; break; case Keys.Right: angle += 0.01F; break; case Keys.W: device.SetWireframeRasterState(); break; case Keys.S: device.SetDefaultRasterState(); break; } }; //main loop RenderLoop.Run(form, () => { //Resizing if (device.MustResize) { device.Resize(); font.Resize(); } //apply states device.UpdateAllStates(); //clear color device.Clear(Color.CornflowerBlue); //Set matrices float ratio = (float)form.ClientRectangle.Width / (float)form.ClientRectangle.Height; Vector3 vAt = new Vector3((float)Math.Cos(angle) * distance, (float)Math.Sin(angle) * distance, heightPos); Vector3 vTo = new Vector3(0, 0, 0); Vector3 vUp = new Vector3(0, 0, 1); Matrix view = Matrix.LookAtLH(vAt, vTo, vUp); Matrix proj = Matrix.PerspectiveFovLH(3.14F / 3.0F, ratio, 1.0F, 50000); Vector3 lightDir = new Vector3(1, 0, -2); lightDir.Normalize(); Matrix WVP = view * proj; WVP.Transpose(); //update constant buffer SceneData data = new SceneData() { Transform = WVP, LightDirection = new Vector4(lightDir, 0), ViewAt = new Vector4(vAt, 0) }; device.UpdateData<SceneData>(buffer, data); //pass constant buffer to shader device.DeviceContext.VertexShader.SetConstantBuffer(0, buffer); device.DeviceContext.PixelShader.SetConstantBuffer(0, buffer); device.DeviceContext.HullShader.SetConstantBuffer(0, buffer); device.DeviceContext.DomainShader.SetConstantBuffer(0, buffer); //set map to shader device.DeviceContext.DomainShader.SetShaderResource(0, heightMap); device.DeviceContext.PixelShader.SetShaderResource(0, diffuseMap); device.DeviceContext.PixelShader.SetShaderResource(1, normalMap); //apply shader shader.Apply(); //draw mesh mesh.DrawPatch(SharpDX.Direct3D.PrimitiveTopology.PatchListWith16ControlPoints); //begin drawing text font.Begin(); //draw string fpsCounter.Update(); font.DrawString("FPS: " + fpsCounter.FPS, 0, 0, Color.White); font.DrawString("Presso Up,Down,Left,Right,A,Z to move camera", 0, 20, Color.White); font.DrawString("Presso W and S to Switch to Wireframe", 0, 40, Color.White); //flush text to view font.End(); //present device.Present(); }); } }
static void Main() { if (!SharpDevice.IsDirectX11Supported()) { System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported"); return; } //Init textured cube int[] indices = new int[] { 0,1,2,0,2,3, 4,6,5,4,7,6, 8,9,10,8,10,11, 12,14,13,12,15,14, 16,18,17,16,19,18, 20,21,22,20,22,23 }; TexturedVertex[] vertices = new[] { ////TOP new TexturedVertex(new Vector3(-5,5,5),new Vector2(1,1)), new TexturedVertex(new Vector3(5,5,5),new Vector2(0,1)), new TexturedVertex(new Vector3(5,5,-5),new Vector2(0,0)), new TexturedVertex(new Vector3(-5,5,-5),new Vector2(1,0)), //BOTTOM new TexturedVertex(new Vector3(-5,-5,5),new Vector2(1,1)), new TexturedVertex(new Vector3(5,-5,5),new Vector2(0,1)), new TexturedVertex(new Vector3(5,-5,-5),new Vector2(0,0)), new TexturedVertex(new Vector3(-5,-5,-5),new Vector2(1,0)), //LEFT new TexturedVertex(new Vector3(-5,-5,5),new Vector2(0,1)), new TexturedVertex(new Vector3(-5,5,5),new Vector2(0,0)), new TexturedVertex(new Vector3(-5,5,-5),new Vector2(1,0)), new TexturedVertex(new Vector3(-5,-5,-5),new Vector2(1,1)), //RIGHT new TexturedVertex(new Vector3(5,-5,5),new Vector2(1,1)), new TexturedVertex(new Vector3(5,5,5),new Vector2(1,0)), new TexturedVertex(new Vector3(5,5,-5),new Vector2(0,0)), new TexturedVertex(new Vector3(5,-5,-5),new Vector2(0,1)), //FRONT new TexturedVertex(new Vector3(-5,5,5),new Vector2(1,0)), new TexturedVertex(new Vector3(5,5,5),new Vector2(0,0)), new TexturedVertex(new Vector3(5,-5,5),new Vector2(0,1)), new TexturedVertex(new Vector3(-5,-5,5),new Vector2(1,1)), //BACK new TexturedVertex(new Vector3(-5,5,-5),new Vector2(0,0)), new TexturedVertex(new Vector3(5,5,-5),new Vector2(1,0)), new TexturedVertex(new Vector3(5,-5,-5),new Vector2(1,1)), new TexturedVertex(new Vector3(-5,-5,-5),new Vector2(0,1)) }; //render form RenderForm form = new RenderForm(); form.Text = "Tutorial 5: Texture"; SharpFPS fpsCounter = new SharpFPS(); using (SharpDevice device = new SharpDevice(form)) { //Init font SharpBatch font = new SharpBatch(device, "textfont.dds"); //Init Mesh SharpMesh mesh = SharpMesh.Create<TexturedVertex>(device, vertices, indices); //Init shader from file SharpShader shader = new SharpShader(device, "../../HLSL.txt", new SharpShaderDescription() { VertexShaderFunction = "VS", PixelShaderFunction = "PS" }, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0) }); //Create constant buffer Buffer11 buffer = shader.CreateBuffer<Matrix>(); //Create texture from file ShaderResourceView texture = ShaderResourceView.FromFile(device.Device, "../../texture.bmp"); fpsCounter.Reset(); //main loop RenderLoop.Run(form, () => { //Resizing if (device.MustResize) { device.Resize(); font.Resize(); } //apply states device.UpdateAllStates(); //clear color device.Clear(Color.CornflowerBlue); //apply shader shader.Apply(); //apply constant buffer to shader device.DeviceContext.VertexShader.SetConstantBuffer(0, buffer); //set texture device.DeviceContext.PixelShader.SetShaderResource(0, texture); //set transformation matrix float ratio = (float)form.ClientRectangle.Width / (float)form.ClientRectangle.Height; Matrix projection = Matrix.PerspectiveFovLH(3.14F / 3.0F, ratio, 1, 1000); Matrix view = Matrix.LookAtLH(new Vector3(0, 10, -30), new Vector3(), Vector3.UnitY); Matrix world = Matrix.RotationY(Environment.TickCount / 1000.0F); Matrix WVP = world * view * projection; device.UpdateData<Matrix>(buffer, WVP); //draw mesh mesh.Draw(); //begin drawing text font.Begin(); //draw string fpsCounter.Update(); font.DrawString("FPS: " + fpsCounter.FPS, 0, 0, Color.White); //flush text to view font.End(); //present device.Present(); }); //release resource font.Dispose(); mesh.Dispose(); buffer.Dispose(); texture.Dispose(); } }
static void Main() { if (!SharpDevice.IsDirectX11Supported()) { System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported"); return; } //render form RenderForm form = new RenderForm(); form.Text = "Tutorial 7: Loading Obj File"; //frame rate counter SharpFPS fpsCounter = new SharpFPS(); using (SharpDevice device = new SharpDevice(form)) { //load font SharpBatch font = new SharpBatch(device, "textfont.dds"); //load model from wavefront obj file SharpMesh mesh = SharpMesh.CreateFromObj(device, "../../../Models/car/car.obj"); //init shader SharpShader shader = new SharpShader(device, "../../HLSL.txt", new SharpShaderDescription() { VertexShaderFunction = "VS", PixelShaderFunction = "PS" }, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 24, 0) }); //init constant buffer Buffer11 buffer = shader.CreateBuffer<Data>(); //init frame counter fpsCounter.Reset(); //main loop RenderLoop.Run(form, () => { //Resizing if (device.MustResize) { device.Resize(); font.Resize(); } //apply states device.UpdateAllStates(); //clear color device.Clear(Color.CornflowerBlue); //apply shader shader.Apply(); //set transformation matrix float ratio = (float)form.ClientRectangle.Width / (float)form.ClientRectangle.Height; Matrix projection = Matrix.PerspectiveFovLH(3.14F / 3.0F, ratio, 1F, 1000.0F); Matrix view = Matrix.LookAtLH(new Vector3(0, 10, -30), new Vector3(), Vector3.UnitY); Matrix world = Matrix.RotationY(Environment.TickCount / 1000.0F); //light direction Vector3 lightDirection = new Vector3(0.5f, 0, -1); lightDirection.Normalize(); Data sceneInformation = new Data() { world = world, worldViewProjection = world * view * projection, lightDirection = new Vector4(lightDirection, 1) }; //write data inside constant buffer device.UpdateData<Data>(buffer, sceneInformation); //apply constant buffer to shader device.DeviceContext.VertexShader.SetConstantBuffer(0, buffer); device.DeviceContext.PixelShader.SetConstantBuffer(0, buffer); //draw mesh mesh.Begin(); for (int i = 0; i < mesh.SubSets.Count; i++) { device.DeviceContext.PixelShader.SetShaderResource(0, mesh.SubSets[i].DiffuseMap); mesh.Draw(i); } //begin drawing text font.Begin(); //draw string fpsCounter.Update(); font.DrawString("FPS: " + fpsCounter.FPS, 0, 0, Color.White); //flush text to view font.End(); //present device.Present(); }); //release resource font.Dispose(); mesh.Dispose(); buffer.Dispose(); } }
/// <summary> /// Create a batch manager for drawing text and sprite /// </summary> /// <param name="device">Device pointer</param> internal Sharp2D(SharpDevice device) { Device = device; }
static void Main(string[] args) { if (!SharpDevice.IsDirectX11Supported()) { System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported"); return; } //render form RenderForm form = new RenderForm(); form.Text = "Tutorial 2: Init Device (press key from 1 to 8)"; //background color Color4 color = Color.CornflowerBlue; //keydown event form.KeyDown += (sender, e) => { switch (e.KeyCode) { case System.Windows.Forms.Keys.D1: color = Color.CornflowerBlue; break; case System.Windows.Forms.Keys.D2: color = Color.Red; break; case System.Windows.Forms.Keys.D3: color = Color.Blue; break; case System.Windows.Forms.Keys.D4: color = Color.Orange; break; case System.Windows.Forms.Keys.D5: color = Color.Yellow; break; case System.Windows.Forms.Keys.D6: color = Color.Olive; break; case System.Windows.Forms.Keys.D7: color = Color.Orchid; break; case System.Windows.Forms.Keys.D8: color = Color.Black; break; } }; //main loop using (SharpDevice device = new SharpDevice(form)) { RenderLoop.Run(form, () => { //resize if form was resized if (device.MustResize) { device.Resize(); } //clear color device.Clear(color); //present device.Present(); }); } }
static void Main() { if (!SharpDevice.IsDirectX11Supported()) { System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported"); return; } //render form RenderForm form = new RenderForm(); form.Text = "Tutorial 18: Skin Animation"; SharpFPS fpsCounter = new SharpFPS(); //number of cube int count = 1000; using (SharpDevice device = new SharpDevice(form)) { SharpBatch font = new SharpBatch(device, "textfont.dds"); //Input layout for Skinning Mesh InputElement[] description = new InputElement[] { new InputElement("POSITION", 0, SharpDX.DXGI.Format.R32G32B32_Float, 0, 0), new InputElement("NORMAL", 0, SharpDX.DXGI.Format.R32G32B32_Float, 12, 0), new InputElement("TEXCOORD", 0, SharpDX.DXGI.Format.R32G32_Float, 24, 0), new InputElement("BINORMAL", 0, SharpDX.DXGI.Format.R32G32B32_Float, 32, 0), new InputElement("TANGENT", 0, SharpDX.DXGI.Format.R32G32B32_Float, 44, 0), new InputElement("JOINT", 0, SharpDX.DXGI.Format.R32G32B32A32_Float, 56, 0), new InputElement("WEIGHT", 0, SharpDX.DXGI.Format.R32G32B32A32_Float, 72, 0), }; SharpShader staticShader = new SharpShader(device, "../../Basic.hlsl", new SharpShaderDescription() { VertexShaderFunction = "VSMain", PixelShaderFunction = "PSMain" }, description); SharpShader skinShader = new SharpShader(device, "../../BasicSkin.hlsl", new SharpShaderDescription() { VertexShaderFunction = "VSMain", PixelShaderFunction = "PSMain" }, description); Buffer11 lightBuffer = skinShader.CreateBuffer <Vector4>(); string path = @"../../../Models/Troll/"; SharpModel model = new SharpModel(device, ColladaImporter.Import(path + "troll.dae")); foreach (Geometry g in model.Geometries) { if (g.IsAnimated) { g.Shader = skinShader; } else { g.Shader = staticShader; } if (!string.IsNullOrEmpty(g.Material.DiffuseTextureName)) { g.Material.DiffuseTexture = ShaderResourceView.FromFile(device.Device, path + g.Material.DiffuseTextureName); g.Material.NormalTextureName = Path.GetFileNameWithoutExtension(g.Material.DiffuseTextureName) + "N.dds"; g.Material.NormalTexture = ShaderResourceView.FromFile(device.Device, path + g.Material.NormalTextureName); } } fpsCounter.Reset(); form.KeyDown += (sender, e) => { switch (e.KeyCode) { case Keys.Up: if (count < 1000) { count++; } break; case Keys.Down: if (count > 0) { count--; } break; } }; int lastTick = Environment.TickCount; //main loop RenderLoop.Run(form, () => { //Resizing if (device.MustResize) { device.Resize(); font.Resize(); } //apply state device.UpdateAllStates(); //clear color device.Clear(Color.CornflowerBlue); //set transformation matrix float ratio = (float)form.ClientRectangle.Width / (float)form.ClientRectangle.Height; Matrix projection = Matrix.PerspectiveFovLH(3.14F / 3.0F, ratio, 1, 10000); Matrix view = Matrix.LookAtLH(new Vector3(0, -100, 50), new Vector3(0, 0, 50), Vector3.UnitZ); Matrix world = Matrix.Identity; float angle = Environment.TickCount / 2000.0F; Vector3 light = new Vector3((float)Math.Sin(angle), (float)Math.Cos(angle), 0); light.Normalize(); device.UpdateData <Vector4>(lightBuffer, new Vector4(light, 1)); device.DeviceContext.VertexShader.SetConstantBuffer(2, lightBuffer); float animationTime = (Environment.TickCount - lastTick) / 1000.0F; if (animationTime >= model.Animations.First().Duration) { lastTick = Environment.TickCount; animationTime = 0; } model.SetTime(animationTime); model.Draw(device, new SkinShaderInformation() { Trasform = world * view * projection, World = world }); font.Begin(); //draw string fpsCounter.Update(); font.DrawString("FPS: " + fpsCounter.FPS, 0, 0, Color.White); font.DrawString("Skinning Animation With Collada", 0, 30, Color.White); //flush text to view font.End(); //present device.Present(); }); //release resource font.Dispose(); } }
static void Main() { if (!SharpDevice.IsDirectX11Supported()) { System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported"); return; } //render form RenderForm form = new RenderForm(); form.Text = "Tutorial 17: Query"; //frame rate counter SharpFPS fpsCounter = new SharpFPS(); using (SharpDevice device = new SharpDevice(form)) { //load model from wavefront obj file SharpMesh earth = SharpMesh.CreateFromObj(device, "../../../Models/planets/earth.obj"); SharpMesh moon = SharpMesh.CreateFromObj(device, "../../../Models/planets/moon.obj"); //init shader SharpShader shader = new SharpShader(device, "../../HLSL.txt", new SharpShaderDescription() { VertexShaderFunction = "VS", PixelShaderFunction = "PS" }, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 24, 0) }); //init constant buffer Buffer11 buffer = shader.CreateBuffer<Data>(); Query pipelineQuery = new Query(device.Device, new QueryDescription() { Flags = QueryFlags.None, Type = QueryType.PipelineStatistics }); QueryDataPipelineStatistics stats = new QueryDataPipelineStatistics(); //init frame counter fpsCounter.Reset(); int lastX = 0; float currentAngle = 50; form.MouseMove += (sender, e) => { if (e.Button == MouseButtons.Left) { currentAngle += (lastX - e.X); } lastX = e.X; }; //main loop RenderLoop.Run(form, () => { //Resizing if (device.MustResize) { device.Resize(); } //apply states device.UpdateAllStates(); //clear color device.Clear(Color.CornflowerBlue); //apply shader shader.Apply(); //apply constant buffer to shader device.DeviceContext.VertexShader.SetConstantBuffer(0, buffer); device.DeviceContext.PixelShader.SetConstantBuffer(0, buffer); //set transformation matrix float ratio = (float)form.ClientRectangle.Width / (float)form.ClientRectangle.Height; Matrix projection = Matrix.PerspectiveFovLH(3.14F / 3.0F, ratio, 1F, 1000.0F); Matrix view = Matrix.LookAtLH(new Vector3(0, 0, -250), new Vector3(), Vector3.UnitY); Matrix world = Matrix.Translation(0, 0, 200) * Matrix.RotationY(MathUtil.DegreesToRadians(currentAngle)); //light direction Vector3 lightDirection = new Vector3(0.5f, 0, -1); lightDirection.Normalize(); Data sceneInformation = new Data() { world = world, worldViewProjection = world * view * projection, lightDirection = new Vector4(lightDirection, 1) }; //write data inside constant buffer device.UpdateData<Data>(buffer, sceneInformation); //draw mesh moon.Begin(); for (int i = 0; i < moon.SubSets.Count; i++) { device.DeviceContext.PixelShader.SetShaderResource(0, moon.SubSets[i].DiffuseMap); moon.Draw(i); } //begin analizing device.DeviceContext.Begin(pipelineQuery); world = Matrix.RotationY(Environment.TickCount / 2000.0F); sceneInformation = new Data() { world = world, worldViewProjection = world * view * projection, lightDirection = new Vector4(lightDirection, 1) }; //write data inside constant buffer device.UpdateData<Data>(buffer, sceneInformation); //draw mesh earth.Begin(); for (int i = 0; i < earth.SubSets.Count; i++) { device.DeviceContext.PixelShader.SetShaderResource(0, earth.SubSets[i].DiffuseMap); earth.Draw(i); } //end analizing device.DeviceContext.End(pipelineQuery); //get result while (!device.DeviceContext.GetData<QueryDataPipelineStatistics>(pipelineQuery, AsynchronousFlags.None, out stats)) { } //begin drawing text device.Font.Begin(); //draw string fpsCounter.Update(); device.Font.DrawString("Earth Stats : FPS: " + fpsCounter.FPS, 0, 0); //print earth stats device.Font.DrawString("Earth Stats : Use Mouse to Rotate Moon To Cover Earth ", 0, 30); device.Font.DrawString(string.Format("Primitive Count: {0}", stats.IAPrimitiveCount), 0, 60); device.Font.DrawString(string.Format("Vertex Count Count: {0}", stats.IAVerticeCount), 0, 90); device.Font.DrawString(string.Format("Vertex Shader Execution: {0}", stats.VSInvocationCount), 0, 120); device.Font.DrawString(string.Format("Pixel Shader Execution: {0}", stats.PSInvocationCount), 0, 150); //flush text to view device.Font.End(); //present device.Present(); }); //release resource earth.Dispose(); moon.Dispose(); buffer.Dispose(); pipelineQuery.Dispose(); } }
static void Main() { if (!SharpDevice.IsDirectX11Supported()) { System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported"); return; } //render form RenderForm form = new RenderForm(); form.Text = "Tutorial 10: Render Target"; //frame rate counter SharpFPS fpsCounter = new SharpFPS(); using (SharpDevice device = new SharpDevice(form)) { //load font SharpBatch font = new SharpBatch(device, "textfont.dds"); //load model from wavefront obj file SharpMesh dogMesh = SharpMesh.CreateNormalMappedFromObj(device, "../../../Models/dog/dog.obj"); SharpMesh cubeMesh = SharpMesh.CreateFromObj(device, "../../../Models/cube.obj"); //init shader SharpShader phongShader = new SharpShader(device, "../../HLSL.txt", new SharpShaderDescription() { VertexShaderFunction = "VS", PixelShaderFunction = "PS" }, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0), new InputElement("TANGENT", 0, Format.R32G32B32_Float, 24, 0), new InputElement("BINORMAL", 0, Format.R32G32B32_Float, 36, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 48, 0) }); SharpShader renderTargetShader = new SharpShader(device, "../../HLSL_RT.txt", new SharpShaderDescription() { VertexShaderFunction = "VS", PixelShaderFunction = "PS" }, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 24, 0) }); //render target SharpRenderTarget target = new SharpRenderTarget(device, 512, 512, Format.R8G8B8A8_UNorm); //init constant buffer Buffer11 phongConstantBuffer = phongShader.CreateBuffer<PhongData>(); Buffer11 renderTargetConstantBuffer = phongShader.CreateBuffer<RenderTargetData>(); //init frame counter fpsCounter.Reset(); //effect inside shader int mode = 0; form.KeyDown += (sender, e) => { switch (e.KeyCode) { case Keys.D1: mode = 0; break; case Keys.D2: mode = 1; break; case Keys.D3: mode = 2; break; case Keys.D4: mode = 3; break; } }; //main loop RenderLoop.Run(form, () => { //Resizing if (device.MustResize) { device.Resize(); font.Resize(); } //apply states device.UpdateAllStates(); //BEGIN RENDERING TO TEXTURE target.Apply(); target.Clear(Color.CornflowerBlue); //set transformation matrix float ratio = (float)form.ClientRectangle.Width / (float)form.ClientRectangle.Height; Matrix projection = Matrix.PerspectiveFovLH(3.14F / 3.0F, ratio, 1F, 1000.0F); Vector3 from = new Vector3(0, 70, -150); Vector3 to = new Vector3(0, 50, 0); Matrix view = Matrix.LookAtLH(from, to, Vector3.UnitY); Matrix world = Matrix.RotationY(Environment.TickCount / 2000.0F); //light direction Vector3 lightDirection = new Vector3(0.5f, 0, -1); lightDirection.Normalize(); PhongData sceneInformation = new PhongData() { world = world, worldViewProjection = world * view * projection, lightDirection = new Vector4(lightDirection, 1), }; //apply shader phongShader.Apply(); //write data inside constant buffer device.UpdateData<PhongData>(phongConstantBuffer, sceneInformation); //apply constant buffer to shader device.DeviceContext.VertexShader.SetConstantBuffer(0, phongConstantBuffer); device.DeviceContext.PixelShader.SetConstantBuffer(0, phongConstantBuffer); //draw mesh dogMesh.Begin(); for (int i = 0; i < dogMesh.SubSets.Count; i++) { device.DeviceContext.PixelShader.SetShaderResource(0, dogMesh.SubSets[i].DiffuseMap); device.DeviceContext.PixelShader.SetShaderResource(1, dogMesh.SubSets[i].NormalMap); dogMesh.Draw(i); } //RENDERING TO DEVICE //Set original targets device.SetDefaultTargers(); //apply shader renderTargetShader.Apply(); Matrix WVP = Matrix.RotationY(Environment.TickCount / 2000.0F) * Matrix.LookAtLH(new Vector3(7, 10, -13), new Vector3(), Vector3.UnitY) * projection; device.UpdateData<RenderTargetData>(renderTargetConstantBuffer, new RenderTargetData() { worldViewProjection = WVP, data = new Vector4(mode, 0, 0, 0) }); //clear color device.Clear(Color.Black); renderTargetShader.Apply(); //apply constant buffer to shader device.DeviceContext.VertexShader.SetConstantBuffer(0, renderTargetConstantBuffer); device.DeviceContext.PixelShader.SetConstantBuffer(0, renderTargetConstantBuffer); //set target device.DeviceContext.PixelShader.SetShaderResource(0, target.Resource); cubeMesh.Draw(); //begin drawing text font.Begin(); //draw string fpsCounter.Update(); font.DrawString("FPS: " + fpsCounter.FPS, 0, 0, Color.White); font.DrawString("Press 1 To 4 to change Effect", 0, 30, Color.White); //flush text to view font.End(); //present device.Present(); }); //release resource font.Dispose(); dogMesh.Dispose(); cubeMesh.Dispose(); phongConstantBuffer.Dispose(); renderTargetConstantBuffer.Dispose(); phongShader.Dispose(); renderTargetShader.Dispose(); } }
static void Main() { if (!SharpDevice.IsDirectX11Supported()) { System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported"); return; } //Init textured cube int[] indices = new int[] { 0, 1, 2, 0, 2, 3, 4, 6, 5, 4, 7, 6, 8, 9, 10, 8, 10, 11, 12, 14, 13, 12, 15, 14, 16, 18, 17, 16, 19, 18, 20, 21, 22, 20, 22, 23 }; TexturedVertex[] vertices = new[] { ////TOP new TexturedVertex(new Vector3(-5, 5, 5), new Vector2(1, 1)), new TexturedVertex(new Vector3(5, 5, 5), new Vector2(0, 1)), new TexturedVertex(new Vector3(5, 5, -5), new Vector2(0, 0)), new TexturedVertex(new Vector3(-5, 5, -5), new Vector2(1, 0)), //BOTTOM new TexturedVertex(new Vector3(-5, -5, 5), new Vector2(1, 1)), new TexturedVertex(new Vector3(5, -5, 5), new Vector2(0, 1)), new TexturedVertex(new Vector3(5, -5, -5), new Vector2(0, 0)), new TexturedVertex(new Vector3(-5, -5, -5), new Vector2(1, 0)), //LEFT new TexturedVertex(new Vector3(-5, -5, 5), new Vector2(0, 1)), new TexturedVertex(new Vector3(-5, 5, 5), new Vector2(0, 0)), new TexturedVertex(new Vector3(-5, 5, -5), new Vector2(1, 0)), new TexturedVertex(new Vector3(-5, -5, -5), new Vector2(1, 1)), //RIGHT new TexturedVertex(new Vector3(5, -5, 5), new Vector2(1, 1)), new TexturedVertex(new Vector3(5, 5, 5), new Vector2(1, 0)), new TexturedVertex(new Vector3(5, 5, -5), new Vector2(0, 0)), new TexturedVertex(new Vector3(5, -5, -5), new Vector2(0, 1)), //FRONT new TexturedVertex(new Vector3(-5, 5, 5), new Vector2(1, 0)), new TexturedVertex(new Vector3(5, 5, 5), new Vector2(0, 0)), new TexturedVertex(new Vector3(5, -5, 5), new Vector2(0, 1)), new TexturedVertex(new Vector3(-5, -5, 5), new Vector2(1, 1)), //BACK new TexturedVertex(new Vector3(-5, 5, -5), new Vector2(0, 0)), new TexturedVertex(new Vector3(5, 5, -5), new Vector2(1, 0)), new TexturedVertex(new Vector3(5, -5, -5), new Vector2(1, 1)), new TexturedVertex(new Vector3(-5, -5, -5), new Vector2(0, 1)) }; //render form RenderForm form = new RenderForm(); form.Text = "Tutorial 14: Output Stream"; SharpFPS fpsCounter = new SharpFPS(); using (SharpDevice device = new SharpDevice(form)) { //Init font SharpBatch font = new SharpBatch(device, "textfont.dds"); //Init Mesh SharpMesh mesh = SharpMesh.Create <TexturedVertex>(device, vertices, indices); //Init shader from file SharpShader shader = new SharpShader(device, "../../HLSL.txt", new SharpShaderDescription() { VertexShaderFunction = "VS", PixelShaderFunction = "PS" }, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0) }); //output stream element declaration StreamOutputElement[] soDeclaration = new StreamOutputElement[] { new StreamOutputElement() { SemanticName = "POSITION", ComponentCount = 3 }, new StreamOutputElement() { SemanticName = "TEXCOORD", ComponentCount = 2 } }; const int streamOutputVertexSize = 20; //bytes (3 floats for position, 2 floats for texcoord) //output shader SharpShader shaderOutput = new SharpShader(device, "../../HLSL.txt", new SharpShaderDescription() { VertexShaderFunction = "VS_O", GeometryShaderFunction = "GS_O", GeometrySO = soDeclaration }, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0) }); //declare 2 output buffer to switch between them //one will contain the source and the other will be the target of the rendeinrg SharpOutputBuffer outputBufferA = new SharpOutputBuffer(device, 100000); SharpOutputBuffer outputBufferB = new SharpOutputBuffer(device, 100000); //Create constant buffer Buffer11 buffer = shader.CreateBuffer <Matrix>(); //Create texture from file ShaderResourceView texture = ShaderResourceView.FromFile(device.Device, "../../texture.bmp"); fpsCounter.Reset(); //for updating bool update = true; Vector3 nextPosition = new Vector3(); form.KeyUp += (sender, e) => { switch (e.KeyCode) { case Keys.Up: update = true; nextPosition += new Vector3(0, 10, 0); break; case Keys.Down: update = true; nextPosition += new Vector3(0, -10, 0); break; case Keys.A: update = true; nextPosition += new Vector3(-10, 0, 0); break; case Keys.D: update = true; nextPosition += new Vector3(10, 0, 0); break; case Keys.W: update = true; nextPosition += new Vector3(0, 0, 10); break; case Keys.S: update = true; nextPosition += new Vector3(0, 0, -10); break; } }; //main loop RenderLoop.Run(form, () => { //Resizing if (device.MustResize) { device.Resize(); font.Resize(); } //apply states device.UpdateAllStates(); //clear color device.Clear(Color.CornflowerBlue); //apply constant buffer to shader device.DeviceContext.VertexShader.SetConstantBuffer(0, buffer); //set texture device.DeviceContext.PixelShader.SetShaderResource(0, texture); //update output buffer only when needed if (update) { //switch buffer var t = outputBufferA; outputBufferA = outputBufferB; outputBufferB = t; //apply shader shaderOutput.Apply(); //start drawing on output buffer outputBufferA.Begin(); //draw the other output buffer as source device.UpdateData <Matrix>(buffer, Matrix.Identity); outputBufferB.Draw(streamOutputVertexSize); //draw the mesh to add it to buffer device.UpdateData <Matrix>(buffer, Matrix.Translation(nextPosition)); //draw mesh mesh.Draw(); //end rendering on buffer outputBufferA.End(); //stop updating update = false; } //set transformation matrix float ratio = (float)form.ClientRectangle.Width / (float)form.ClientRectangle.Height; Matrix projection = Matrix.PerspectiveFovLH(3.14F / 3.0F, ratio, 1, 1000); Matrix view = Matrix.LookAtLH(new Vector3(0, 50, -100), new Vector3(), Vector3.UnitY); Matrix world = Matrix.Identity; Matrix WVP = world * view * projection; device.UpdateData <Matrix>(buffer, WVP); //stream shader.Apply(); //draw all buffer every frame outputBufferA.Draw(streamOutputVertexSize); //begin drawing text font.Begin(); //draw string fpsCounter.Update(); font.DrawString("FPS: " + fpsCounter.FPS, 0, 0, Color.White); font.DrawString("Press WASD, Up, Down to move cube", 0, 30, Color.White); //flush text to view font.End(); //present device.Present(); }); //release resource font.Dispose(); mesh.Dispose(); buffer.Dispose(); texture.Dispose(); } }
static void Main() { if (!SharpDevice.IsDirectX11Supported()) { System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported"); return; } //render form RenderForm form = new RenderForm(); form.Text = "Tutorial 16: Environment Mapping"; //frame rate counter SharpFPS fpsCounter = new SharpFPS(); using (SharpDevice device = new SharpDevice(form)) { //load model from wavefront obj file SharpMesh teapot = SharpMesh.CreateFromObj(device, "../../../Models/teapot.obj"); //init shader SharpShader cubeMapPass = new SharpShader(device, "../../HLSL.txt", new SharpShaderDescription() { VertexShaderFunction = "VS", GeometryShaderFunction = "GS", PixelShaderFunction = "PS" }, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 24, 0) }); //second pass SharpShader standard = new SharpShader(device, "../../HLSL.txt", new SharpShaderDescription() { VertexShaderFunction = "VS_SECOND", PixelShaderFunction = "PS_SECOND" }, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 24, 0) }); //second pass SharpShader reflection = new SharpShader(device, "../../HLSL.txt", new SharpShaderDescription() { VertexShaderFunction = "VS_SECOND", PixelShaderFunction = "PS_REFLECTION" }, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 24, 0) }); //render target SharpCubeTarget cubeTarget = new SharpCubeTarget(device, 512, Format.R8G8B8A8_UNorm); //init constant buffer Buffer11 dataConstantBuffer = cubeMapPass.CreateBuffer<Data>(); //init frame counter fpsCounter.Reset(); //main loop RenderLoop.Run(form, () => { //Resizing if (device.MustResize) { device.Resize(); } //apply states device.UpdateAllStates(); //MATRICES //set transformation matrix float ratio = (float)form.ClientRectangle.Width / (float)form.ClientRectangle.Height; //90° degree with 1 ratio Matrix projection = Matrix.PerspectiveFovLH(3.14F / 2.0F, 1, 1F, 10000.0F); //camera Vector3 from = new Vector3(0, 30, 70); Vector3 to = new Vector3(0, 0, 0); Matrix view = Matrix.LookAtLH(from, to, Vector3.UnitY); Matrix world = Matrix.Translation(0, 0, 50) * Matrix.RotationY(Environment.TickCount / 1000.0F); //light direction Vector3 lightDirection = new Vector3(0.5f, 0, -1); lightDirection.Normalize(); //six axis Matrix view1 = Matrix.LookAtLH(new Vector3(), new Vector3(1, 0, 0), Vector3.UnitY); Matrix view2 = Matrix.LookAtLH(new Vector3(), new Vector3(-1, 0, 0), Vector3.UnitY); Matrix view3 = Matrix.LookAtLH(new Vector3(), new Vector3(0, 1, 0), -Vector3.UnitZ); Matrix view4 = Matrix.LookAtLH(new Vector3(), new Vector3(0, -1, 0), Vector3.UnitZ); Matrix view5 = Matrix.LookAtLH(new Vector3(), new Vector3(0, 0, 1), Vector3.UnitY); Matrix view6 = Matrix.LookAtLH(new Vector3(), new Vector3(0, 0, -1), Vector3.UnitY); //BEGIN RENDERING TO CUBE TEXTURE cubeTarget.Apply(); cubeTarget.Clear(Color.CornflowerBlue); Data sceneInformation = new Data() { world = world, worldViewProjection = world * view * projection, lightDirection = new Vector4(lightDirection, 1), cameraPosition = new Vector4(from, 1), mat1 = world * view1 * projection, mat2 = world * view2 * projection, mat3 = world * view3 * projection, mat4 = world * view4 * projection, mat5 = world * view5 * projection, mat6 = world * view6 * projection }; //write data inside constant buffer device.UpdateData<Data>(dataConstantBuffer, sceneInformation); //apply shader cubeMapPass.Apply(); //apply constant buffer to shader device.DeviceContext.VertexShader.SetConstantBuffer(0, dataConstantBuffer); device.DeviceContext.GeometryShader.SetConstantBuffer(0, dataConstantBuffer); device.DeviceContext.PixelShader.SetConstantBuffer(0, dataConstantBuffer); //draw mesh teapot.Begin(); for (int i = 0; i < teapot.SubSets.Count; i++) { device.DeviceContext.PixelShader.SetShaderResource(0, teapot.SubSets[i].DiffuseMap); teapot.Draw(i); } //RENDERING TO DEVICE //Set original targets device.SetDefaultTargers(); //clear color device.Clear(Color.Blue); //apply shader standard.Apply(); //set target device.DeviceContext.PixelShader.SetShaderResource(1, cubeTarget.Resource); projection = Matrix.PerspectiveFovLH(3.14F / 3.0F, ratio, 1, 10000.0F); sceneInformation = new Data() { world = world, worldViewProjection = world * view * projection, lightDirection = new Vector4(lightDirection, 1), cameraPosition = new Vector4(from, 1), mat1 = world * view1 * projection, mat2 = world * view2 * projection, mat3 = world * view3 * projection, mat4 = world * view4 * projection, mat5 = world * view5 * projection, mat6 = world * view6 * projection }; //write data inside constant buffer device.UpdateData<Data>(dataConstantBuffer, sceneInformation); //room teapot.Begin(); for (int i = 0; i < teapot.SubSets.Count; i++) { device.DeviceContext.PixelShader.SetShaderResource(0, teapot.SubSets[i].DiffuseMap); teapot.Draw(i); } //apply shader reflection.Apply(); sceneInformation = new Data() { world = Matrix.Identity, worldViewProjection = view * projection, lightDirection = new Vector4(lightDirection, 1), cameraPosition = new Vector4(from, 1), mat1 = Matrix.Identity, mat2 = Matrix.Identity, mat3 = Matrix.Identity, mat4 = Matrix.Identity, mat5 = Matrix.Identity, mat6 = Matrix.Identity }; //write data inside constant buffer device.UpdateData<Data>(dataConstantBuffer, sceneInformation); //draw mesh teapot.Begin(); for (int i = 0; i < teapot.SubSets.Count; i++) { device.DeviceContext.PixelShader.SetShaderResource(0, teapot.SubSets[i].DiffuseMap); teapot.Draw(i); } //begin drawing text device.Font.Begin(); //draw string fpsCounter.Update(); device.Font.DrawString("FPS: " + fpsCounter.FPS, 0, 0); //flush text to view device.Font.End(); //present device.Present(); }); //release resource teapot.Dispose(); dataConstantBuffer.Dispose(); cubeMapPass.Dispose(); standard.Dispose(); reflection.Dispose(); cubeTarget.Dispose(); } }
static void Main() { if (!SharpDevice.IsDirectX11Supported()) { System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported"); return; } //render form RenderForm form = new RenderForm(); form.Text = "Tutorial 9: Normal Mapping"; //frame rate counter SharpFPS fpsCounter = new SharpFPS(); using (SharpDevice device = new SharpDevice(form)) { //load model from wavefront obj file SharpMesh mesh = SharpMesh.CreateNormalMappedFromObj(device, "../../../Models/dog/dog.obj"); //init shader with normal map illumination SharpShader shaderNormal = new SharpShader(device, "../../HLSL_normal.txt", new SharpShaderDescription() { VertexShaderFunction = "VS", PixelShaderFunction = "PS" }, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0), new InputElement("TANGENT", 0, Format.R32G32B32_Float, 24, 0), new InputElement("BINORMAL", 0, Format.R32G32B32_Float, 36, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 48, 0) }); //Init shader with standard illumination SharpShader shaderStandard = new SharpShader(device, "../../HLSL_standard.txt", new SharpShaderDescription() { VertexShaderFunction = "VS", PixelShaderFunction = "PS" }, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0), new InputElement("TANGENT", 0, Format.R32G32B32_Float, 24, 0), new InputElement("BINORMAL", 0, Format.R32G32B32_Float, 36, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 48, 0) }); //init constant buffer Buffer11 buffer = shaderNormal.CreateBuffer<Data>(); //init frame counter fpsCounter.Reset(); //Used for parallax mapping float bias = 0.005f; //to active normal mapping bool normalMap = true; form.KeyDown += (sender, e) => { if (e.KeyCode == Keys.A) bias += 0.005f; else if (e.KeyCode == Keys.S) bias -= 0.005f; if (e.KeyCode == Keys.N) normalMap = true; if (e.KeyCode == Keys.D) normalMap = false; }; //main loop RenderLoop.Run(form, () => { //Resizing if (device.MustResize) { device.Resize(); } //apply states device.UpdateAllStates(); //clear color device.Clear(Color.CornflowerBlue); //set transformation matrix float ratio = (float)form.ClientRectangle.Width / (float)form.ClientRectangle.Height; Matrix projection = Matrix.PerspectiveFovLH(3.14F / 3.0F, ratio, 1F, 1000.0F); //set camera position and target Vector3 from = new Vector3(0, 70, -150); Vector3 to = new Vector3(0, 50, 0); Matrix view = Matrix.LookAtLH(from, to, Vector3.UnitY); //set world matrix Matrix world = Matrix.RotationY(Environment.TickCount / 2000.0F); //light direction Vector3 lightDirection = new Vector3(0.5f, 0, -1); lightDirection.Normalize(); Data sceneInformation = new Data() { world = world, worldViewProjection = world * view * projection, lightDirection = new Vector4(lightDirection, 1), viewDirection = new Vector4(Vector3.Normalize(from - to), 1), bias = new Vector4(bias, 0, 0, 0) }; //apply shader if (normalMap) shaderNormal.Apply(); else shaderStandard.Apply(); //write data inside constant buffer device.UpdateData<Data>(buffer, sceneInformation); //apply constant buffer to shader device.DeviceContext.VertexShader.SetConstantBuffer(0, buffer); device.DeviceContext.PixelShader.SetConstantBuffer(0, buffer); //draw mesh mesh.Begin(); for (int i = 0; i < mesh.SubSets.Count; i++) { device.DeviceContext.PixelShader.SetShaderResource(0, mesh.SubSets[i].DiffuseMap); device.DeviceContext.PixelShader.SetShaderResource(1, mesh.SubSets[i].NormalMap); mesh.Draw(i); } //begin drawing text device.Font.Begin(); //draw string fpsCounter.Update(); device.Font.DrawString("FPS: " + fpsCounter.FPS, 0, 0); device.Font.DrawString("Press N or D to switch mode: ", 0, 20); device.Font.DrawString("Press A or S to change bias: " + bias, 0, 40); //flush text to view device.Font.End(); //present device.Present(); }); //release resource mesh.Dispose(); buffer.Dispose(); shaderNormal.Dispose(); shaderStandard.Dispose(); } }
static void Main() { if (!SharpDevice.IsDirectX11Supported()) { System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported"); return; } //render form RenderForm form = new RenderForm(); form.Text = "Tutorial 15: Toon Shading With Multiple Render Target"; //frame rate counter SharpFPS fpsCounter = new SharpFPS(); using (SharpDevice device = new SharpDevice(form)) { //load font SharpBatch font = new SharpBatch(device, "textfont.dds"); //load model from wavefront obj file SharpMesh dogMesh = SharpMesh.CreateFromObj(device, "../../../Models/dog/dog.obj"); //quad SharpMesh quad = SharpMesh.CreateQuad(device); //init shader SharpShader firstPass = new SharpShader(device, "../../HLSL.txt", new SharpShaderDescription() { VertexShaderFunction = "VS", PixelShaderFunction = "PS" }, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 24, 0) }); //second pass SharpShader secondPass = new SharpShader(device, "../../HLSL.txt", new SharpShaderDescription() { VertexShaderFunction = "VS_QUAD", PixelShaderFunction = "PS_QUAD" }, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), }); //render target SharpRenderTarget target = new SharpRenderTarget(device, form.ClientSize.Width, form.ClientSize.Height, Format.R8G8B8A8_UNorm); //render target SharpRenderTarget target2 = new SharpRenderTarget(device, form.ClientSize.Width, form.ClientSize.Height, Format.R8G8B8A8_UNorm); //toon texture ShaderResourceView bandTexture = ShaderResourceView.FromFile(device.Device, "../../../Models/band.bmp"); //init constant buffer Buffer11 toonConstantBuffer = firstPass.CreateBuffer <ToonData>(); //init frame counter fpsCounter.Reset(); //main loop RenderLoop.Run(form, () => { //Resizing if (device.MustResize) { device.Resize(); //render target target.Dispose(); target = new SharpRenderTarget(device, form.ClientSize.Width, form.ClientSize.Height, Format.R8G8B8A8_UNorm); //render target target2.Dispose(); target2 = new SharpRenderTarget(device, form.ClientSize.Width, form.ClientSize.Height, Format.R8G8B8A8_UNorm); font.Resize(); } //apply states device.UpdateAllStates(); //BEGIN RENDERING TO TEXTURE (MULTIPLE) device.ApplyMultipleRenderTarget(target, target2); target.Clear(Color.CornflowerBlue); target2.Clear(Color.Black); //set transformation matrix float ratio = (float)form.ClientRectangle.Width / (float)form.ClientRectangle.Height; Matrix projection = Matrix.PerspectiveFovLH(3.14F / 3.0F, ratio, 1F, 1000.0F); Vector3 from = new Vector3(0, 70, -150); Vector3 to = new Vector3(0, 50, 0); Matrix view = Matrix.LookAtLH(from, to, Vector3.UnitY); Matrix world = Matrix.RotationY(Environment.TickCount / 2000.0F); //light direction Vector3 lightDirection = new Vector3(0.5f, 0, -1); lightDirection.Normalize(); ToonData sceneInformation = new ToonData() { world = world, worldViewProjection = world * view * projection, lightDirection = new Vector4(lightDirection, 1), cameraPosition = new Vector4(from, 1) }; //apply shader firstPass.Apply(); //set toon band texture device.DeviceContext.PixelShader.SetShaderResource(1, bandTexture); //write data inside constant buffer device.UpdateData <ToonData>(toonConstantBuffer, sceneInformation); //apply constant buffer to shader device.DeviceContext.VertexShader.SetConstantBuffer(0, toonConstantBuffer); device.DeviceContext.PixelShader.SetConstantBuffer(0, toonConstantBuffer); //draw mesh dogMesh.Begin(); for (int i = 0; i < dogMesh.SubSets.Count; i++) { device.DeviceContext.PixelShader.SetShaderResource(0, dogMesh.SubSets[i].DiffuseMap); dogMesh.Draw(i); } //RENDERING TO DEVICE //Set original targets device.SetDefaultTargers(); //apply shader secondPass.Apply(); //clear color device.Clear(Color.Black); secondPass.Apply(); //set target device.DeviceContext.PixelShader.SetShaderResource(0, target.Resource); device.DeviceContext.PixelShader.SetShaderResource(1, target2.Resource); quad.Draw(); //begin drawing text font.Begin(); //draw string fpsCounter.Update(); font.DrawString("FPS: " + fpsCounter.FPS, 0, 0, Color.White); //flush text to view font.End(); //present device.Present(); }); //release resource font.Dispose(); dogMesh.Dispose(); quad.Dispose(); toonConstantBuffer.Dispose(); firstPass.Dispose(); secondPass.Dispose(); bandTexture.Dispose(); target.Dispose(); target2.Dispose(); } }
static void Main() { if (!SharpDevice.IsDirectX11Supported()) { System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported"); return; } int[] indices = Enumerable.Range(0, 1000).ToArray(); List<Vector3> vertices = new List<Vector3>(); for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { for (int z = 0; z < 10; z++) { vertices.Add(new Vector3(i - 5, j - 5, 5 - z) * 12); } } } //render form RenderForm form = new RenderForm(); form.Text = "Tutorial 8: Geometry Shader"; SharpFPS fpsCounter = new SharpFPS(); //number of cube int count = 1000; using (SharpDevice device = new SharpDevice(form)) { SharpBatch font = new SharpBatch(device, "textfont.dds"); SharpMesh mesh = SharpMesh.Create<Vector3>(device, vertices.ToArray(), indices); SharpShader shader = new SharpShader(device, "../../HLSL.txt", new SharpShaderDescription() { VertexShaderFunction = "VS", PixelShaderFunction = "PS", GeometryShaderFunction = "GS" }, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0) }); Buffer11 buffer = shader.CreateBuffer<Data>(); ShaderResourceView texture = ShaderResourceView.FromFile(device.Device, "../../texture.dds"); fpsCounter.Reset(); form.KeyDown += (sender, e) => { switch (e.KeyCode) { case Keys.Up: if (count < 1000) count++; break; case Keys.Down: if (count > 0) count--; break; } }; //main loop RenderLoop.Run(form, () => { //Resizing if (device.MustResize) { device.Resize(); font.Resize(); } //apply state device.UpdateAllStates(); //clear color device.Clear(Color.CornflowerBlue); //apply shader shader.Apply(); //apply constant buffer to shader device.DeviceContext.GeometryShader.SetConstantBuffer(0, buffer); //set texture device.DeviceContext.PixelShader.SetShaderResource(0, texture); //set transformation matrix float ratio = (float)form.ClientRectangle.Width / (float)form.ClientRectangle.Height; Matrix projection = Matrix.PerspectiveFovLH(3.14F / 3.0F, ratio, 1, 10000); Matrix view = Matrix.LookAtLH(new Vector3(10, 20, -100), new Vector3(), Vector3.UnitY); Matrix world = Matrix.RotationY(Environment.TickCount / 1000.0F); Data matrices = new Data() { World = world, ViewProj = view * projection }; device.UpdateData<Data>(buffer, matrices); //draw mesh mesh.DrawPoints(count); //begin drawing text device.DeviceContext.GeometryShader.Set(null); font.Begin(); //draw string fpsCounter.Update(); font.DrawString("FPS: " + fpsCounter.FPS, 0, 0, Color.White); font.DrawString("Cube Count: " + count, 0, 30, Color.White); font.DrawString("Press Up and Down to change number", 0, 60, Color.White); //flush text to view font.End(); //present device.Present(); }); //release resource font.Dispose(); mesh.Dispose(); buffer.Dispose(); } }
static void Main() { if (!SharpDevice.IsDirectX11Supported()) { System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported"); return; } //render form RenderForm form = new RenderForm(); form.Text = "Tutorial 13: Geometry Instancing"; //frame rate counter SharpFPS fpsCounter = new SharpFPS(); using (SharpDevice device = new SharpDevice(form)) { //load font SharpBatch font = new SharpBatch(device, "textfont.dds"); //load model from wavefront obj file SharpMesh mesh = SharpMesh.CreateNormalMappedFromObj(device, "../../../Models/dog/dog.obj"); //init shader with normal map illumination SharpShader shader = new SharpShader(device, "../../HLSL_instancing.txt", new SharpShaderDescription() { VertexShaderFunction = "VS", PixelShaderFunction = "PS" }, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0), new InputElement("TANGENT", 0, Format.R32G32B32_Float, 24, 0), new InputElement("BINORMAL", 0, Format.R32G32B32_Float, 36, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 48, 0), new InputElement("INSTANCEPOSITION",0,Format.R32G32B32_Float,0,1,InputClassification.PerInstanceData,1) }); SharpShader shaderStandard = new SharpShader(device, "../../HLSL_standard.txt", new SharpShaderDescription() { VertexShaderFunction = "VS", PixelShaderFunction = "PS" }, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0), new InputElement("TANGENT", 0, Format.R32G32B32_Float, 24, 0), new InputElement("BINORMAL", 0, Format.R32G32B32_Float, 36, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 48, 0) }); //create instance buffer data List<Vector3> positions = new List<Vector3>(); for (int z = 0; z < 100; z++) { for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { positions.Add(new Vector3(i * 80 - 400, j * 80 - 400, z * 80 - 400)); } } } SharpInstanceBuffer<Vector3> instanceBuffer = new SharpInstanceBuffer<Vector3>(device, positions.ToArray()); //init constant buffer Buffer11 buffer = shader.CreateBuffer<Data>(); //init frame counter fpsCounter.Reset(); //to active normal mapping bool instancing = true; int instanceCount = 5000; form.KeyDown += (sender, e) => { switch (e.KeyCode) { case Keys.I: instancing = true; break; case Keys.D: instancing = false; break; case Keys.Up: instanceCount += 100; if (instanceCount >= 10000) instanceCount = 10000; break; case Keys.Down: instanceCount -= 100; if (instanceCount < 0) instanceCount = 0; break; } }; //main loop RenderLoop.Run(form, () => { //Resizing if (device.MustResize) { device.Resize(); font.Resize(); } //apply states device.UpdateAllStates(); //clear color device.Clear(Color.CornflowerBlue); //set transformation matrix float ratio = (float)form.ClientRectangle.Width / (float)form.ClientRectangle.Height; Matrix projection = Matrix.PerspectiveFovLH(3.14F / 3.0F, ratio, 1F, 50000.0F); //set camera position and target Vector3 from = new Vector3(0, 70, -1000); Vector3 to = new Vector3(0, 50, 0); Matrix view = Matrix.LookAtLH(from, to, Vector3.UnitY); //light direction Vector3 lightDirection = new Vector3(0.5f, 0, -1); lightDirection.Normalize(); if (instancing) { //Instancing rendering loop //set world matrix Matrix world = Matrix.RotationY(Environment.TickCount / 2000.0F); Data sceneInformation = new Data() { world = world, viewProjection = view * projection, lightDirection = new Vector4(lightDirection, 1), viewDirection = new Vector4(Vector3.Normalize(from - to), 1) }; //apply shader shader.Apply(); //write data inside constant buffer device.UpdateData<Data>(buffer, sceneInformation); //apply constant buffer to shader device.DeviceContext.VertexShader.SetConstantBuffer(0, buffer); device.DeviceContext.PixelShader.SetConstantBuffer(0, buffer); //draw mesh mesh.Begin(); for (int i = 0; i < mesh.SubSets.Count; i++) { device.DeviceContext.PixelShader.SetShaderResource(0, mesh.SubSets[i].DiffuseMap); device.DeviceContext.PixelShader.SetShaderResource(1, mesh.SubSets[i].NormalMap); instanceBuffer.DrawInstance(instanceCount, mesh.SubSets[i].IndexCount, mesh.SubSets[i].StartIndex); } } else { //non instancing //apply shader shaderStandard.Apply(); //apply constant buffer to shader device.DeviceContext.VertexShader.SetConstantBuffer(0, buffer); device.DeviceContext.PixelShader.SetConstantBuffer(0, buffer); //prepare mesh mesh.Begin(); for (int j = 0; j < instanceCount; j++) { //set world matrix Matrix world = Matrix.RotationY(Environment.TickCount / 2000.0F) * Matrix.Translation(positions[j]); Data sceneInformation = new Data() { world = world, viewProjection = view * projection, lightDirection = new Vector4(lightDirection, 1), viewDirection = new Vector4(Vector3.Normalize(from - to), 1) }; //write data inside constant buffer device.UpdateData<Data>(buffer, sceneInformation); //draw mesh for (int i = 0; i < mesh.SubSets.Count; i++) { device.DeviceContext.PixelShader.SetShaderResource(0, mesh.SubSets[i].DiffuseMap); device.DeviceContext.PixelShader.SetShaderResource(1, mesh.SubSets[i].NormalMap); mesh.Draw(i); } } } //begin drawing text font.Begin(); //draw string fpsCounter.Update(); font.DrawString("FPS: " + fpsCounter.FPS, 0, 0, Color.White); if (instancing) font.DrawString("Instancing On: Press D to use standard rendering. See FPS", 0, 30, Color.White); else font.DrawString("Instancing Off: Press I to use Instancing. See FPS", 0, 30, Color.White); font.DrawString("Press up and down to change count ", 0, 60, Color.White); font.DrawString("Count: " + instanceCount, 0, 90, Color.White); //flush text to view font.End(); //present device.Present(); }); //release resource font.Dispose(); mesh.Dispose(); buffer.Dispose(); shader.Dispose(); shaderStandard.Dispose(); instanceBuffer.Dispose(); } }
static void Main() { if (!SharpDevice.IsDirectX11Supported()) { System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported"); return; } //Init textured cube int[] indices = new int[] { 0, 1, 2, 0, 2, 3, 4, 6, 5, 4, 7, 6, 8, 9, 10, 8, 10, 11, 12, 14, 13, 12, 15, 14, 16, 18, 17, 16, 19, 18, 20, 21, 22, 20, 22, 23 }; TexturedVertex[] vertices = new[] { ////TOP new TexturedVertex(new Vector3(-5, 5, 5), new Vector2(1, 1)), new TexturedVertex(new Vector3(5, 5, 5), new Vector2(0, 1)), new TexturedVertex(new Vector3(5, 5, -5), new Vector2(0, 0)), new TexturedVertex(new Vector3(-5, 5, -5), new Vector2(1, 0)), //BOTTOM new TexturedVertex(new Vector3(-5, -5, 5), new Vector2(1, 1)), new TexturedVertex(new Vector3(5, -5, 5), new Vector2(0, 1)), new TexturedVertex(new Vector3(5, -5, -5), new Vector2(0, 0)), new TexturedVertex(new Vector3(-5, -5, -5), new Vector2(1, 0)), //LEFT new TexturedVertex(new Vector3(-5, -5, 5), new Vector2(0, 1)), new TexturedVertex(new Vector3(-5, 5, 5), new Vector2(0, 0)), new TexturedVertex(new Vector3(-5, 5, -5), new Vector2(1, 0)), new TexturedVertex(new Vector3(-5, -5, -5), new Vector2(1, 1)), //RIGHT new TexturedVertex(new Vector3(5, -5, 5), new Vector2(1, 1)), new TexturedVertex(new Vector3(5, 5, 5), new Vector2(1, 0)), new TexturedVertex(new Vector3(5, 5, -5), new Vector2(0, 0)), new TexturedVertex(new Vector3(5, -5, -5), new Vector2(0, 1)), //FRONT new TexturedVertex(new Vector3(-5, 5, 5), new Vector2(1, 0)), new TexturedVertex(new Vector3(5, 5, 5), new Vector2(0, 0)), new TexturedVertex(new Vector3(5, -5, 5), new Vector2(0, 1)), new TexturedVertex(new Vector3(-5, -5, 5), new Vector2(1, 1)), //BACK new TexturedVertex(new Vector3(-5, 5, -5), new Vector2(0, 0)), new TexturedVertex(new Vector3(5, 5, -5), new Vector2(1, 0)), new TexturedVertex(new Vector3(5, -5, -5), new Vector2(1, 1)), new TexturedVertex(new Vector3(-5, -5, -5), new Vector2(0, 1)) }; //render form RenderForm form = new RenderForm(); form.Text = "Tutorial 5: Texture"; SharpFPS fpsCounter = new SharpFPS(); using (SharpDevice device = new SharpDevice(form)) { //Init font SharpBatch font = new SharpBatch(device, "textfont.dds"); //Init Mesh SharpMesh mesh = SharpMesh.Create <TexturedVertex>(device, vertices, indices); //Init shader from file SharpShader shader = new SharpShader(device, "../../HLSL.txt", new SharpShaderDescription() { VertexShaderFunction = "VS", PixelShaderFunction = "PS" }, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0) }); //Create constant buffer Buffer11 buffer = shader.CreateBuffer <Matrix>(); //Create texture from file ShaderResourceView texture = ShaderResourceView.FromFile(device.Device, "../../texture.bmp"); fpsCounter.Reset(); //main loop RenderLoop.Run(form, () => { //Resizing if (device.MustResize) { device.Resize(); font.Resize(); } //apply states device.UpdateAllStates(); //clear color device.Clear(Color.CornflowerBlue); //apply shader shader.Apply(); //apply constant buffer to shader device.DeviceContext.VertexShader.SetConstantBuffer(0, buffer); //set texture device.DeviceContext.PixelShader.SetShaderResource(0, texture); //set transformation matrix float ratio = (float)form.ClientRectangle.Width / (float)form.ClientRectangle.Height; Matrix projection = Matrix.PerspectiveFovLH(3.14F / 3.0F, ratio, 1, 1000); Matrix view = Matrix.LookAtLH(new Vector3(0, 10, -30), new Vector3(), Vector3.UnitY); Matrix world = Matrix.RotationY(Environment.TickCount / 1000.0F); Matrix WVP = world * view * projection; device.UpdateData <Matrix>(buffer, WVP); //draw mesh mesh.Draw(); //begin drawing text font.Begin(); //draw string fpsCounter.Update(); font.DrawString("FPS: " + fpsCounter.FPS, 0, 0, Color.White); //flush text to view font.End(); //present device.Present(); }); //release resource font.Dispose(); mesh.Dispose(); buffer.Dispose(); texture.Dispose(); } }
static void Main() { if (!SharpDevice.IsDirectX11Supported()) { System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported"); return; } //render form RenderForm form = new RenderForm(); form.Text = "Tutorial 18: Skin Animation"; SharpFPS fpsCounter = new SharpFPS(); //number of cube int count = 1000; using (SharpDevice device = new SharpDevice(form)) { SharpBatch font = new SharpBatch(device, "textfont.dds"); //Input layout for Skinning Mesh InputElement[] description = new InputElement[] { new InputElement("POSITION",0,SharpDX.DXGI.Format.R32G32B32_Float,0,0), new InputElement("NORMAL",0,SharpDX.DXGI.Format.R32G32B32_Float,12,0), new InputElement("TEXCOORD",0,SharpDX.DXGI.Format.R32G32_Float,24,0), new InputElement("BINORMAL",0,SharpDX.DXGI.Format.R32G32B32_Float,32,0), new InputElement("TANGENT",0,SharpDX.DXGI.Format.R32G32B32_Float,44,0), new InputElement("JOINT",0,SharpDX.DXGI.Format.R32G32B32A32_Float,56,0), new InputElement("WEIGHT",0,SharpDX.DXGI.Format.R32G32B32A32_Float,72,0), }; SharpShader staticShader = new SharpShader(device, "../../Basic.hlsl", new SharpShaderDescription() { VertexShaderFunction = "VSMain", PixelShaderFunction = "PSMain" }, description); SharpShader skinShader = new SharpShader(device, "../../BasicSkin.hlsl", new SharpShaderDescription() { VertexShaderFunction = "VSMain", PixelShaderFunction = "PSMain" }, description); Buffer11 lightBuffer = skinShader.CreateBuffer<Vector4>(); string path = @"../../../Models/Troll/"; SharpModel model = new SharpModel(device, ColladaImporter.Import(path + "troll.dae")); foreach (Geometry g in model.Geometries) { if (g.IsAnimated) g.Shader = skinShader; else g.Shader = staticShader; g.Material.DiffuseTexture = ShaderResourceView.FromFile(device.Device, path + g.Material.DiffuseTextureName); g.Material.NormalTextureName = Path.GetFileNameWithoutExtension(g.Material.DiffuseTextureName) + "N.dds"; g.Material.NormalTexture = ShaderResourceView.FromFile(device.Device, path + g.Material.NormalTextureName); } fpsCounter.Reset(); form.KeyDown += (sender, e) => { switch (e.KeyCode) { case Keys.Up: if (count < 1000) count++; break; case Keys.Down: if (count > 0) count--; break; } }; int lastTick = Environment.TickCount; //main loop RenderLoop.Run(form, () => { //Resizing if (device.MustResize) { device.Resize(); font.Resize(); } //apply state device.UpdateAllStates(); //clear color device.Clear(Color.CornflowerBlue); //set transformation matrix float ratio = (float)form.ClientRectangle.Width / (float)form.ClientRectangle.Height; Matrix projection = Matrix.PerspectiveFovLH(3.14F / 3.0F, ratio, 1, 10000); Matrix view = Matrix.LookAtLH(new Vector3(0, -100, 50), new Vector3(0, 0, 50), Vector3.UnitZ); Matrix world = Matrix.Identity; float angle = 0.2F; Vector3 light = new Vector3((float)Math.Sin(angle), (float)Math.Cos(angle), 0); light.Normalize(); device.UpdateData<Vector4>(lightBuffer, new Vector4(light, 1)); device.DeviceContext.VertexShader.SetConstantBuffer(2, lightBuffer); float animationTime = (Environment.TickCount - lastTick) / 1000.0F; if (animationTime >= model.Animations.First().Duration) { lastTick = Environment.TickCount; animationTime = 0; } model.SetTime(animationTime); model.Draw(device, new SkinShaderInformation() { Trasform = world * view * projection, World = world }); font.Begin(); //draw string fpsCounter.Update(); font.DrawString("FPS: " + fpsCounter.FPS, 0, 0, Color.White); font.DrawString("Skinning Animation With Collada", 0, 30, Color.White); //flush text to view font.End(); //present device.Present(); }); //release resource font.Dispose(); } }
static void Main() { if (!SharpDevice.IsDirectX11Supported()) { System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported"); return; } //render form RenderForm form = new RenderForm(); form.Text = "Tutorial 7: Loading Obj File"; //frame rate counter SharpFPS fpsCounter = new SharpFPS(); using (SharpDevice device = new SharpDevice(form)) { //load font SharpBatch font = new SharpBatch(device, "textfont.dds"); //load model from wavefront obj file SharpMesh mesh = SharpMesh.CreateFromObj(device, "../../../Models/car/car.obj"); //init shader SharpShader shader = new SharpShader(device, "../../HLSL.txt", new SharpShaderDescription() { VertexShaderFunction = "VS", PixelShaderFunction = "PS" }, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 24, 0) }); //init constant buffer Buffer11 buffer = shader.CreateBuffer<Data>(); //init frame counter fpsCounter.Reset(); //main loop RenderLoop.Run(form, () => { //Resizing if (device.MustResize) { device.Resize(); font.Resize(); } //apply states device.UpdateAllStates(); //clear color device.Clear(Color.CornflowerBlue); //apply shader shader.Apply(); //set transformation matrix float ratio = (float)form.ClientRectangle.Width / (float)form.ClientRectangle.Height; Matrix projection = Matrix.PerspectiveFovLH(3.14F / 3.0F, ratio, 1F, 1000.0F); Matrix view = Matrix.LookAtLH(new Vector3(0, 10, -30), new Vector3(), Vector3.UnitY); Matrix world = Matrix.RotationY(Environment.TickCount / 1000.0F); //light direction Vector3 lightDirection = new Vector3(0.5f, 0, -1); lightDirection.Normalize(); Data sceneInformation = new Data() { world = world, worldViewProjection = world * view * projection, lightDirection = new Vector4(lightDirection, 1) }; //write data inside constant buffer device.UpdateData<Data>(buffer, sceneInformation); //apply constant buffer to shader device.DeviceContext.VertexShader.SetConstantBuffer(0, buffer); device.DeviceContext.PixelShader.SetConstantBuffer(0, buffer); //draw mesh mesh.Begin(); for (int i = 0; i < mesh.SubSets.Count; i++) { device.DeviceContext.PixelShader.SetShaderResource(0, mesh.SubSets[i].DiffuseMap); mesh.Draw(i); } //begin drawing text font.Begin(); //draw string fpsCounter.Update(); font.DrawString("FPS: " + fpsCounter.FPS, 0, 0, Color.White); //flush text to view font.End(); //present device.Present(); }); //release resource font.Dispose(); mesh.Dispose(); buffer.Dispose(); } }
/// <summary> /// Draw Animated Model /// </summary> /// <param name="device">Device</param> /// <param name="information">Information</param> public void Draw(SharpDevice device,SkinShaderInformation information) { //Iterate each geometry foreach (Geometry g in Geometries) { g.Apply(information); g.Draw(device.DeviceContext); } }
static void Main() { if (!SharpDevice.IsDirectX11Supported()) { System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported"); return; } //render form RenderForm form = new RenderForm(); form.Text = "Tutorial 6: Rasterizer & Alphablending"; //frame rate counter SharpFPS fpsCounter = new SharpFPS(); using (SharpDevice device = new SharpDevice(form)) { //init mesh int[] indices = new int[] { 0,1,2,0,2,3, 4,6,5,4,7,6, 8,9,10,8,10,11, 12,14,13,12,15,14, 16,18,17,16,19,18, 20,21,22,20,22,23 }; TexturedVertex[] vertices = new[] { ////TOP new TexturedVertex(new Vector3(-5,5,5),new Vector2(1,1)), new TexturedVertex(new Vector3(5,5,5),new Vector2(0,1)), new TexturedVertex(new Vector3(5,5,-5),new Vector2(0,0)), new TexturedVertex(new Vector3(-5,5,-5),new Vector2(1,0)), //BOTTOM new TexturedVertex(new Vector3(-5,-5,5),new Vector2(1,1)), new TexturedVertex(new Vector3(5,-5,5),new Vector2(0,1)), new TexturedVertex(new Vector3(5,-5,-5),new Vector2(0,0)), new TexturedVertex(new Vector3(-5,-5,-5),new Vector2(1,0)), //LEFT new TexturedVertex(new Vector3(-5,-5,5),new Vector2(0,1)), new TexturedVertex(new Vector3(-5,5,5),new Vector2(0,0)), new TexturedVertex(new Vector3(-5,5,-5),new Vector2(1,0)), new TexturedVertex(new Vector3(-5,-5,-5),new Vector2(1,1)), //RIGHT new TexturedVertex(new Vector3(5,-5,5),new Vector2(1,1)), new TexturedVertex(new Vector3(5,5,5),new Vector2(1,0)), new TexturedVertex(new Vector3(5,5,-5),new Vector2(0,0)), new TexturedVertex(new Vector3(5,-5,-5),new Vector2(0,1)), //FRONT new TexturedVertex(new Vector3(-5,5,5),new Vector2(1,0)), new TexturedVertex(new Vector3(5,5,5),new Vector2(0,0)), new TexturedVertex(new Vector3(5,-5,5),new Vector2(0,1)), new TexturedVertex(new Vector3(-5,-5,5),new Vector2(1,1)), //BACK new TexturedVertex(new Vector3(-5,5,-5),new Vector2(0,0)), new TexturedVertex(new Vector3(5,5,-5),new Vector2(1,0)), new TexturedVertex(new Vector3(5,-5,-5),new Vector2(1,1)), new TexturedVertex(new Vector3(-5,-5,-5),new Vector2(0,1)) }; SharpMesh mesh = SharpMesh.Create<TexturedVertex>(device, vertices, indices); //init shader SharpShader shader = new SharpShader(device, "../../HLSL.txt", new SharpShaderDescription() { VertexShaderFunction = "VS", PixelShaderFunction = "PS" }, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0) }); //init constant buffer Buffer11 buffer = shader.CreateBuffer<Matrix>(); //load Shader Resouce View from file //it contains texture for using inside shaders ShaderResourceView texture = device.LoadTextureFromFile("../../texture.dds"); //init frame rate counter fpsCounter.Reset(); //keyboard event //change depth and rasterizer state form.KeyDown += (sender, e) => { switch (e.KeyCode) { case Keys.W: device.SetWireframeRasterState(); device.SetDefaultBlendState(); break; case Keys.S: device.SetDefaultRasterState(); break; case Keys.D1: device.SetDefaultBlendState(); break; case Keys.D2: device.SetBlend(BlendOperation.Add, BlendOption.InverseSourceAlpha, BlendOption.SourceAlpha); break; case Keys.D3: device.SetBlend(BlendOperation.Add, BlendOption.SourceAlpha, BlendOption.InverseSourceAlpha); break; case Keys.D4: device.SetBlend(BlendOperation.Add, BlendOption.SourceColor, BlendOption.InverseSourceColor); break; case Keys.D5: device.SetBlend(BlendOperation.Add, BlendOption.SourceColor, BlendOption.DestinationColor); break; } }; //main loop RenderLoop.Run(form, () => { //Resizing if (device.MustResize) { device.Resize(); } //apply state device.UpdateAllStates(); //clear color device.Clear(Color.CornflowerBlue); //apply shader shader.Apply(); //apply constant buffer to shader device.DeviceContext.VertexShader.SetConstantBuffer(0, buffer); //set texture device.DeviceContext.PixelShader.SetShaderResource(0, texture); //set transformation matrix float ratio = (float)form.ClientRectangle.Width / (float)form.ClientRectangle.Height; //projection matrix Matrix projection = Matrix.PerspectiveFovLH(3.14F / 3.0F, ratio, 1, 1000); //view matrix (camera) Matrix view = Matrix.LookAtLH(new Vector3(0, 10, -40), new Vector3(), Vector3.UnitY); //world matrix Matrix world = Matrix.RotationY(Environment.TickCount / 1000.0F); Matrix worldViewProjection = world * view * projection; //set world view projection matrix inside constant buffer device.UpdateData<Matrix>(buffer, worldViewProjection); //draw mesh mesh.Draw(); //Second Mesh world = Matrix.RotationY(Environment.TickCount / 1000.0F) * Matrix.Translation(5, 0, -15); worldViewProjection = world * view * projection; //refresh constant buffer device.UpdateData<Matrix>(buffer, worldViewProjection); //draw second mesh mesh.Draw(); //Third Mesh world = Matrix.RotationY(Environment.TickCount / 1000.0F) * Matrix.Translation(-5, 0, -15); worldViewProjection = world * view * projection; //refresh constant buffer device.UpdateData<Matrix>(buffer, worldViewProjection); //draw third mesh mesh.Draw(); //begin drawing text device.Font.Begin(); //draw string fpsCounter.Update(); device.Font.DrawString("FPS: " + fpsCounter.FPS, 0, 0); device.Font.DrawString("Press W for wireframe, S for solid", 0, 30); device.Font.DrawString("Press From 1 to 5 for Alphablending", 0, 60); //flush text to view device.Font.End(); //present device.Present(); }); //release resource mesh.Dispose(); buffer.Dispose(); texture.Dispose(); } }
static void Main() { if (!SharpDevice.IsDirectX11Supported()) { System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported"); return; } RenderForm form = new RenderForm(); form.Text = "Tutorial 19: Adaptive Tesselation"; SharpFPS fpsCounter = new SharpFPS(); using (SharpDevice device = new SharpDevice(form)) { InputElement[] description = new InputElement[] { new InputElement("POSITION", 0, SharpDX.DXGI.Format.R32G32B32_Float, 0, 0), new InputElement("TEXCOORD", 0, SharpDX.DXGI.Format.R32G32_Float, 12, 0), }; SharpShader shader = new SharpShader(device, "../../Shader.hlsl", new SharpShaderDescription() { VertexShaderFunction = "VSMain", PixelShaderFunction = "PSMain", DomainShaderFunction = "DSMain", HullShaderFunction = "HSMain" }, description); int seqX = 64; int seqY = 64; float size = 100; float sizeW = seqX * size; float sizeH = seqY * size; TessellationVertex[] vertices = new TessellationVertex[4356]; int[] indices = new int[63504]; int k = 0; for (int y = -1; y < seqY + 1; y++) { for (int x = -1; x < seqX + 1; x++) { float vX = x * size - (seqX / 2.0F) * size; float vY = y * size - (seqY / 2.0F) * size; float vZ = 0; TessellationVertex v = new TessellationVertex(vX, vY, vZ, x / 4.0F, y / 4.0F); vertices[k] = v; k++; } } //indici k = 0; for (int y = 0; y < seqY - 1; y++) { for (int x = 0; x < seqX - 1; x++) { int startX = x + 1; int startY = y + 1; for (int j = -1; j < 3; j++) { for (int i = -1; i < 3; i++) { indices[k] = (i + startX + (seqX + 2) * (j + startY)); k++; } } } } SharpMesh mesh = SharpMesh.Create <TessellationVertex>(device, vertices, indices); string path = @"../../../Models/adaptive_tess/"; ShaderResourceView diffuseMap = device.LoadTextureFromFile(path + "D.dds"); ShaderResourceView normalMap = device.LoadTextureFromFile(path + "N.dds"); ShaderResourceView heightMap = device.LoadTextureFromFile(path + "H.dds"); Buffer11 buffer = shader.CreateBuffer <SceneData>(); fpsCounter.Reset(); float angle = 3.14F; float distance = 1200; float heightPos = 500; form.KeyDown += (sender, e) => { switch (e.KeyCode) { case Keys.A: distance -= 5; if (distance < 100) { distance = 100; } break; case Keys.Z: distance += 5; if (distance > 2000) { distance = 2000; } break; case Keys.Up: heightPos--; if (heightPos < 50) { heightPos = 50; } break; case Keys.Down: heightPos++; if (heightPos > 800) { heightPos = 800; } break; case Keys.Left: angle -= 0.01F; break; case Keys.Right: angle += 0.01F; break; case Keys.W: device.SetWireframeRasterState(); break; case Keys.S: device.SetDefaultRasterState(); break; } }; //main loop RenderLoop.Run(form, () => { //Resizing if (device.MustResize) { device.Resize(); } //apply states device.UpdateAllStates(); //clear color device.Clear(Color.CornflowerBlue); //Set matrices float ratio = (float)form.ClientRectangle.Width / (float)form.ClientRectangle.Height; Vector3 vAt = new Vector3((float)Math.Cos(angle) * distance, (float)Math.Sin(angle) * distance, heightPos); Vector3 vTo = new Vector3(0, 0, 0); Vector3 vUp = new Vector3(0, 0, 1); Matrix view = Matrix.LookAtLH(vAt, vTo, vUp); Matrix proj = Matrix.PerspectiveFovLH(3.14F / 3.0F, ratio, 1.0F, 50000); Vector3 lightDir = new Vector3(1, 0, -2); lightDir.Normalize(); Matrix WVP = view * proj; WVP.Transpose(); //update constant buffer SceneData data = new SceneData() { Transform = WVP, LightDirection = new Vector4(lightDir, 0), ViewAt = new Vector4(vAt, 0) }; device.UpdateData <SceneData>(buffer, data); //pass constant buffer to shader device.DeviceContext.VertexShader.SetConstantBuffer(0, buffer); device.DeviceContext.PixelShader.SetConstantBuffer(0, buffer); device.DeviceContext.HullShader.SetConstantBuffer(0, buffer); device.DeviceContext.DomainShader.SetConstantBuffer(0, buffer); //set map to shader device.DeviceContext.DomainShader.SetShaderResource(0, heightMap); device.DeviceContext.PixelShader.SetShaderResource(0, diffuseMap); device.DeviceContext.PixelShader.SetShaderResource(1, normalMap); //apply shader shader.Apply(); //draw mesh mesh.DrawPatch(SharpDX.Direct3D.PrimitiveTopology.PatchListWith16ControlPoints); //begin drawing text device.Font.Begin(); //draw string fpsCounter.Update(); device.Font.DrawString("FPS: " + fpsCounter.FPS, 0, 0); device.Font.DrawString("Presso Up,Down,Left,Right,A,Z to move camera", 0, 20); device.Font.DrawString("Presso W and S to Switch to Wireframe", 0, 40); //flush text to view device.Font.End(); //present device.Present(); }); } }
static void Main() { if (!SharpDevice.IsDirectX11Supported()) { System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported"); return; } int[] indices = new int[] { 0, 1, 2, 3, 4, 5 }; Vector3[] vertices = new Vector3[] { new Vector3(-50, 0, 50), new Vector3(50, 0, 50), new Vector3(50, 0, -50), new Vector3(-50, 0, 50), new Vector3(50, 0, -50), new Vector3(-50, 0, -50) }; //render form RenderForm form = new RenderForm(); form.Text = "Tutorial 11: Tesselation"; SharpFPS fpsCounter = new SharpFPS(); using (SharpDevice device = new SharpDevice(form)) { //Init mesh SharpMesh mesh = SharpMesh.Create <Vector3>(device, vertices, indices); //Init shader SharpShader shader = new SharpShader(device, "../../HLSL.txt", new SharpShaderDescription() { VertexShaderFunction = "VS", PixelShaderFunction = "PS", GeometryShaderFunction = "GS", HullShaderFunction = "HS", DomainShaderFunction = "DS" }, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), }); //create constant buffer Buffer11 buffer = shader.CreateBuffer <Data>(); fpsCounter.Reset(); //tessellation value int nFactor = 1; form.KeyDown += (sender, e) => { if (e.KeyCode == Keys.Up) { nFactor++; } if (e.KeyCode == Keys.Down && nFactor > 1) { nFactor--; } if (e.KeyCode == Keys.W) { device.SetWireframeRasterState(); } if (e.KeyCode == Keys.S) { device.SetDefaultRasterState(); } }; //main loop RenderLoop.Run(form, () => { //Resizing if (device.MustResize) { device.Resize(); } //clear color device.Clear(Color.CornflowerBlue); device.UpdateAllStates(); float ratio = (float)form.ClientRectangle.Width / (float)form.ClientRectangle.Height; Matrix projection = Matrix.PerspectiveFovLH(MathUtil.Pi / 3.0F, ratio, 1, 1000); Matrix view = Matrix.LookAtLH(new Vector3(0, 30, -80), new Vector3(), Vector3.UnitY); Matrix world = Matrix.RotationY(Environment.TickCount / 2000.0F); Matrix WVP = world * view * projection; device.UpdateData <Data>(buffer, new Data() { world = world, viewProj = view * projection, factor = new Vector4(nFactor, nFactor, 0, 0) }); device.DeviceContext.VertexShader.SetConstantBuffer(0, buffer); device.DeviceContext.PixelShader.SetConstantBuffer(0, buffer); device.DeviceContext.GeometryShader.SetConstantBuffer(0, buffer); device.DeviceContext.HullShader.SetConstantBuffer(0, buffer); device.DeviceContext.DomainShader.SetConstantBuffer(0, buffer); shader.Apply(); //draw mesh as patch mesh.DrawPatch(SharpDX.Direct3D.PrimitiveTopology.PatchListWith3ControlPoints); //remove unused shader shader.Clear(); //begin drawing text device.Font.Begin(); //draw string fpsCounter.Update(); device.Font.DrawString("FPS: " + fpsCounter.FPS, 0, 0); device.Font.DrawString("Tessellation Factor: " + nFactor, 0, 30); device.Font.DrawString("Press Up And Down to change Tessellation Factor,W and S to switch to wireframe ", 0, 60); //flush text to view device.Font.End(); //present device.Present(); }); //release resource mesh.Dispose(); buffer.Dispose(); shader.Dispose(); } }
static void Main() { if (!SharpDevice.IsDirectX11Supported()) { System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported"); return; } //render form RenderForm form = new RenderForm(); form.Text = "Tutorial 15: Toon Shading With Multiple Render Target"; //frame rate counter SharpFPS fpsCounter = new SharpFPS(); using (SharpDevice device = new SharpDevice(form)) { //load font SharpBatch font = new SharpBatch(device, "textfont.dds"); //load model from wavefront obj file SharpMesh dogMesh = SharpMesh.CreateFromObj(device, "../../../Models/dog/dog.obj"); //quad SharpMesh quad = SharpMesh.CreateQuad(device); //init shader SharpShader firstPass = new SharpShader(device, "../../HLSL.txt", new SharpShaderDescription() { VertexShaderFunction = "VS", PixelShaderFunction = "PS" }, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 24, 0) }); //second pass SharpShader secondPass = new SharpShader(device, "../../HLSL.txt", new SharpShaderDescription() { VertexShaderFunction = "VS_QUAD", PixelShaderFunction = "PS_QUAD" }, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), }); //render target SharpRenderTarget target = new SharpRenderTarget(device, form.ClientSize.Width, form.ClientSize.Height, Format.R8G8B8A8_UNorm); //render target SharpRenderTarget target2 = new SharpRenderTarget(device, form.ClientSize.Width, form.ClientSize.Height, Format.R8G8B8A8_UNorm); //toon texture ShaderResourceView bandTexture = ShaderResourceView.FromFile(device.Device, "../../../Models/band.bmp"); //init constant buffer Buffer11 toonConstantBuffer = firstPass.CreateBuffer<ToonData>(); //init frame counter fpsCounter.Reset(); //main loop RenderLoop.Run(form, () => { //Resizing if (device.MustResize) { device.Resize(); //render target target.Dispose(); target = new SharpRenderTarget(device, form.ClientSize.Width, form.ClientSize.Height, Format.R8G8B8A8_UNorm); //render target target2.Dispose(); target2 = new SharpRenderTarget(device, form.ClientSize.Width, form.ClientSize.Height, Format.R8G8B8A8_UNorm); font.Resize(); } //apply states device.UpdateAllStates(); //BEGIN RENDERING TO TEXTURE (MULTIPLE) device.ApplyMultipleRenderTarget(target, target2); target.Clear(Color.CornflowerBlue); target2.Clear(Color.Black); //set transformation matrix float ratio = (float)form.ClientRectangle.Width / (float)form.ClientRectangle.Height; Matrix projection = Matrix.PerspectiveFovLH(3.14F / 3.0F, ratio, 1F, 1000.0F); Vector3 from = new Vector3(0, 70, -150); Vector3 to = new Vector3(0, 50, 0); Matrix view = Matrix.LookAtLH(from, to, Vector3.UnitY); Matrix world = Matrix.RotationY(Environment.TickCount / 2000.0F); //light direction Vector3 lightDirection = new Vector3(0.5f, 0, -1); lightDirection.Normalize(); ToonData sceneInformation = new ToonData() { world = world, worldViewProjection = world * view * projection, lightDirection = new Vector4(lightDirection, 1), cameraPosition = new Vector4(from, 1) }; //apply shader firstPass.Apply(); //set toon band texture device.DeviceContext.PixelShader.SetShaderResource(1, bandTexture); //write data inside constant buffer device.UpdateData<ToonData>(toonConstantBuffer, sceneInformation); //apply constant buffer to shader device.DeviceContext.VertexShader.SetConstantBuffer(0, toonConstantBuffer); device.DeviceContext.PixelShader.SetConstantBuffer(0, toonConstantBuffer); //draw mesh dogMesh.Begin(); for (int i = 0; i < dogMesh.SubSets.Count; i++) { device.DeviceContext.PixelShader.SetShaderResource(0, dogMesh.SubSets[i].DiffuseMap); dogMesh.Draw(i); } //RENDERING TO DEVICE //Set original targets device.SetDefaultTargers(); //apply shader secondPass.Apply(); //clear color device.Clear(Color.Black); secondPass.Apply(); //set target device.DeviceContext.PixelShader.SetShaderResource(0, target.Resource); device.DeviceContext.PixelShader.SetShaderResource(1, target2.Resource); quad.Draw(); //begin drawing text font.Begin(); //draw string fpsCounter.Update(); font.DrawString("FPS: " + fpsCounter.FPS, 0, 0, Color.White); //flush text to view font.End(); //present device.Present(); }); //release resource font.Dispose(); dogMesh.Dispose(); quad.Dispose(); toonConstantBuffer.Dispose(); firstPass.Dispose(); secondPass.Dispose(); bandTexture.Dispose(); target.Dispose(); target2.Dispose(); } }
static void Main() { if (!SharpDevice.IsDirectX11Supported()) { System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported"); return; } int[] indices = new int[] { 0,1,2,3,4,5 }; Vector3[] vertices = new Vector3[]{ new Vector3(-50, 0, 50), new Vector3(50, 0, 50), new Vector3(50, 0, -50), new Vector3(-50, 0, 50), new Vector3(50, 0, -50), new Vector3(-50, 0, -50) }; //render form RenderForm form = new RenderForm(); form.Text = "Tutorial 11: Tesselation"; SharpFPS fpsCounter = new SharpFPS(); using (SharpDevice device = new SharpDevice(form)) { //Init mesh SharpMesh mesh = SharpMesh.Create<Vector3>(device, vertices, indices); //Init shader SharpShader shader = new SharpShader(device, "../../HLSL.txt", new SharpShaderDescription() { VertexShaderFunction = "VS", PixelShaderFunction = "PS", GeometryShaderFunction = "GS", HullShaderFunction = "HS", DomainShaderFunction = "DS" }, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), }); //create constant buffer Buffer11 buffer = shader.CreateBuffer<Data>(); fpsCounter.Reset(); //tessellation value int nFactor = 1; form.KeyDown += (sender, e) => { if (e.KeyCode == Keys.Up) nFactor++; if (e.KeyCode == Keys.Down && nFactor > 1) nFactor--; if (e.KeyCode == Keys.W) device.SetWireframeRasterState(); if (e.KeyCode == Keys.S) device.SetDefaultRasterState(); }; //main loop RenderLoop.Run(form, () => { //Resizing if (device.MustResize) { device.Resize(); } //clear color device.Clear(Color.CornflowerBlue); device.UpdateAllStates(); float ratio = (float)form.ClientRectangle.Width / (float)form.ClientRectangle.Height; Matrix projection = Matrix.PerspectiveFovLH(MathUtil.Pi / 3.0F, ratio, 1, 1000); Matrix view = Matrix.LookAtLH(new Vector3(0, 30, -80), new Vector3(), Vector3.UnitY); Matrix world = Matrix.RotationY(Environment.TickCount / 2000.0F); Matrix WVP = world * view * projection; device.UpdateData<Data>(buffer, new Data() { world = world, viewProj = view * projection, factor = new Vector4(nFactor, nFactor, 0, 0) }); device.DeviceContext.VertexShader.SetConstantBuffer(0, buffer); device.DeviceContext.PixelShader.SetConstantBuffer(0, buffer); device.DeviceContext.GeometryShader.SetConstantBuffer(0, buffer); device.DeviceContext.HullShader.SetConstantBuffer(0, buffer); device.DeviceContext.DomainShader.SetConstantBuffer(0, buffer); shader.Apply(); //draw mesh as patch mesh.DrawPatch(SharpDX.Direct3D.PrimitiveTopology.PatchListWith3ControlPoints); //remove unused shader shader.Clear(); //begin drawing text device.Font.Begin(); //draw string fpsCounter.Update(); device.Font.DrawString("FPS: " + fpsCounter.FPS, 0, 0); device.Font.DrawString("Tessellation Factor: " + nFactor, 0, 30); device.Font.DrawString("Press Up And Down to change Tessellation Factor,W and S to switch to wireframe ", 0, 60); //flush text to view device.Font.End(); //present device.Present(); }); //release resource mesh.Dispose(); buffer.Dispose(); shader.Dispose(); } }
static void Main() { if (!SharpDevice.IsDirectX11Supported()) { System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported"); return; } //Init textured cube int[] indices = new int[] { 0,1,2,0,2,3, 4,6,5,4,7,6, 8,9,10,8,10,11, 12,14,13,12,15,14, 16,18,17,16,19,18, 20,21,22,20,22,23 }; TexturedVertex[] vertices = new[] { ////TOP new TexturedVertex(new Vector3(-5,5,5),new Vector2(1,1)), new TexturedVertex(new Vector3(5,5,5),new Vector2(0,1)), new TexturedVertex(new Vector3(5,5,-5),new Vector2(0,0)), new TexturedVertex(new Vector3(-5,5,-5),new Vector2(1,0)), //BOTTOM new TexturedVertex(new Vector3(-5,-5,5),new Vector2(1,1)), new TexturedVertex(new Vector3(5,-5,5),new Vector2(0,1)), new TexturedVertex(new Vector3(5,-5,-5),new Vector2(0,0)), new TexturedVertex(new Vector3(-5,-5,-5),new Vector2(1,0)), //LEFT new TexturedVertex(new Vector3(-5,-5,5),new Vector2(0,1)), new TexturedVertex(new Vector3(-5,5,5),new Vector2(0,0)), new TexturedVertex(new Vector3(-5,5,-5),new Vector2(1,0)), new TexturedVertex(new Vector3(-5,-5,-5),new Vector2(1,1)), //RIGHT new TexturedVertex(new Vector3(5,-5,5),new Vector2(1,1)), new TexturedVertex(new Vector3(5,5,5),new Vector2(1,0)), new TexturedVertex(new Vector3(5,5,-5),new Vector2(0,0)), new TexturedVertex(new Vector3(5,-5,-5),new Vector2(0,1)), //FRONT new TexturedVertex(new Vector3(-5,5,5),new Vector2(1,0)), new TexturedVertex(new Vector3(5,5,5),new Vector2(0,0)), new TexturedVertex(new Vector3(5,-5,5),new Vector2(0,1)), new TexturedVertex(new Vector3(-5,-5,5),new Vector2(1,1)), //BACK new TexturedVertex(new Vector3(-5,5,-5),new Vector2(0,0)), new TexturedVertex(new Vector3(5,5,-5),new Vector2(1,0)), new TexturedVertex(new Vector3(5,-5,-5),new Vector2(1,1)), new TexturedVertex(new Vector3(-5,-5,-5),new Vector2(0,1)) }; //render form RenderForm form = new RenderForm(); form.Text = "Tutorial 14: Output Stream"; SharpFPS fpsCounter = new SharpFPS(); using (SharpDevice device = new SharpDevice(form)) { //Init font SharpBatch font = new SharpBatch(device, "textfont.dds"); //Init Mesh SharpMesh mesh = SharpMesh.Create<TexturedVertex>(device, vertices, indices); //Init shader from file SharpShader shader = new SharpShader(device, "../../HLSL.txt", new SharpShaderDescription() { VertexShaderFunction = "VS", PixelShaderFunction = "PS" }, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0) }); //output stream element declaration StreamOutputElement[] soDeclaration = new StreamOutputElement[] { new StreamOutputElement(){SemanticName="POSITION",ComponentCount=3}, new StreamOutputElement(){SemanticName="TEXCOORD",ComponentCount=2} }; const int streamOutputVertexSize = 20; //bytes (3 floats for position, 2 floats for texcoord) //output shader SharpShader shaderOutput = new SharpShader(device, "../../HLSL.txt", new SharpShaderDescription() { VertexShaderFunction = "VS_O", GeometryShaderFunction = "GS_O", GeometrySO = soDeclaration }, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0) }); //declare 2 output buffer to switch between them //one will contain the source and the other will be the target of the rendeinrg SharpOutputBuffer outputBufferA = new SharpOutputBuffer(device, 100000); SharpOutputBuffer outputBufferB = new SharpOutputBuffer(device, 100000); //Create constant buffer Buffer11 buffer = shader.CreateBuffer<Matrix>(); //Create texture from file ShaderResourceView texture = ShaderResourceView.FromFile(device.Device, "../../texture.bmp"); fpsCounter.Reset(); //for updating bool update = true; Vector3 nextPosition = new Vector3(); form.KeyUp += (sender, e) => { switch (e.KeyCode) { case Keys.Up: update = true; nextPosition += new Vector3(0, 10, 0); break; case Keys.Down: update = true; nextPosition += new Vector3(0, -10, 0); break; case Keys.A: update = true; nextPosition += new Vector3(-10, 0, 0); break; case Keys.D: update = true; nextPosition += new Vector3(10, 0, 0); break; case Keys.W: update = true; nextPosition += new Vector3(0, 0, 10); break; case Keys.S: update = true; nextPosition += new Vector3(0, 0, -10); break; } }; //main loop RenderLoop.Run(form, () => { //Resizing if (device.MustResize) { device.Resize(); font.Resize(); } //apply states device.UpdateAllStates(); //clear color device.Clear(Color.CornflowerBlue); //apply constant buffer to shader device.DeviceContext.VertexShader.SetConstantBuffer(0, buffer); //set texture device.DeviceContext.PixelShader.SetShaderResource(0, texture); //update output buffer only when needed if (update) { //switch buffer var t = outputBufferA; outputBufferA = outputBufferB; outputBufferB = t; //apply shader shaderOutput.Apply(); //start drawing on output buffer outputBufferA.Begin(); //draw the other output buffer as source device.UpdateData<Matrix>(buffer, Matrix.Identity); outputBufferB.Draw(streamOutputVertexSize); //draw the mesh to add it to buffer device.UpdateData<Matrix>(buffer, Matrix.Translation(nextPosition)); //draw mesh mesh.Draw(); //end rendering on buffer outputBufferA.End(); //stop updating update = false; } //set transformation matrix float ratio = (float)form.ClientRectangle.Width / (float)form.ClientRectangle.Height; Matrix projection = Matrix.PerspectiveFovLH(3.14F / 3.0F, ratio, 1, 1000); Matrix view = Matrix.LookAtLH(new Vector3(0, 50, -100), new Vector3(), Vector3.UnitY); Matrix world = Matrix.Identity; Matrix WVP = world * view * projection; device.UpdateData<Matrix>(buffer, WVP); //stream shader.Apply(); //draw all buffer every frame outputBufferA.Draw(streamOutputVertexSize); //begin drawing text font.Begin(); //draw string fpsCounter.Update(); font.DrawString("FPS: " + fpsCounter.FPS, 0, 0, Color.White); font.DrawString("Press WASD, Up, Down to move cube", 0, 30, Color.White); //flush text to view font.End(); //present device.Present(); }); //release resource font.Dispose(); mesh.Dispose(); buffer.Dispose(); texture.Dispose(); } }
static void Main() { if (!SharpDevice.IsDirectX11Supported()) { System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported"); return; } //render form RenderForm form = new RenderForm(); form.Text = "Tutorial 13: Geometry Instancing"; //frame rate counter SharpFPS fpsCounter = new SharpFPS(); using (SharpDevice device = new SharpDevice(form)) { //load font SharpBatch font = new SharpBatch(device, "textfont.dds"); //load model from wavefront obj file SharpMesh mesh = SharpMesh.CreateNormalMappedFromObj(device, "../../../Models/dog/dog.obj"); //init shader with normal map illumination SharpShader shader = new SharpShader(device, "../../HLSL_instancing.txt", new SharpShaderDescription() { VertexShaderFunction = "VS", PixelShaderFunction = "PS" }, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0), new InputElement("TANGENT", 0, Format.R32G32B32_Float, 24, 0), new InputElement("BINORMAL", 0, Format.R32G32B32_Float, 36, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 48, 0), new InputElement("INSTANCEPOSITION", 0, Format.R32G32B32_Float, 0, 1, InputClassification.PerInstanceData, 1) }); SharpShader shaderStandard = new SharpShader(device, "../../HLSL_standard.txt", new SharpShaderDescription() { VertexShaderFunction = "VS", PixelShaderFunction = "PS" }, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0), new InputElement("TANGENT", 0, Format.R32G32B32_Float, 24, 0), new InputElement("BINORMAL", 0, Format.R32G32B32_Float, 36, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 48, 0) }); //create instance buffer data List <Vector3> positions = new List <Vector3>(); for (int z = 0; z < 100; z++) { for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { positions.Add(new Vector3(i * 80 - 400, j * 80 - 400, z * 80 - 400)); } } } SharpInstanceBuffer <Vector3> instanceBuffer = new SharpInstanceBuffer <Vector3>(device, positions.ToArray()); //init constant buffer Buffer11 buffer = shader.CreateBuffer <Data>(); //init frame counter fpsCounter.Reset(); //to active normal mapping bool instancing = true; int instanceCount = 5000; form.KeyDown += (sender, e) => { switch (e.KeyCode) { case Keys.I: instancing = true; break; case Keys.D: instancing = false; break; case Keys.Up: instanceCount += 100; if (instanceCount >= 10000) { instanceCount = 10000; } break; case Keys.Down: instanceCount -= 100; if (instanceCount < 0) { instanceCount = 0; } break; } }; //main loop RenderLoop.Run(form, () => { //Resizing if (device.MustResize) { device.Resize(); font.Resize(); } //apply states device.UpdateAllStates(); //clear color device.Clear(Color.CornflowerBlue); //set transformation matrix float ratio = (float)form.ClientRectangle.Width / (float)form.ClientRectangle.Height; Matrix projection = Matrix.PerspectiveFovLH(3.14F / 3.0F, ratio, 1F, 50000.0F); //set camera position and target Vector3 from = new Vector3(0, 70, -1000); Vector3 to = new Vector3(0, 50, 0); Matrix view = Matrix.LookAtLH(from, to, Vector3.UnitY); //light direction Vector3 lightDirection = new Vector3(0.5f, 0, -1); lightDirection.Normalize(); if (instancing) { //Instancing rendering loop //set world matrix Matrix world = Matrix.RotationY(Environment.TickCount / 2000.0F); Data sceneInformation = new Data() { world = world, viewProjection = view * projection, lightDirection = new Vector4(lightDirection, 1), viewDirection = new Vector4(Vector3.Normalize(from - to), 1) }; //apply shader shader.Apply(); //write data inside constant buffer device.UpdateData <Data>(buffer, sceneInformation); //apply constant buffer to shader device.DeviceContext.VertexShader.SetConstantBuffer(0, buffer); device.DeviceContext.PixelShader.SetConstantBuffer(0, buffer); //draw mesh mesh.Begin(); for (int i = 0; i < mesh.SubSets.Count; i++) { device.DeviceContext.PixelShader.SetShaderResource(0, mesh.SubSets[i].DiffuseMap); device.DeviceContext.PixelShader.SetShaderResource(1, mesh.SubSets[i].NormalMap); instanceBuffer.DrawInstance(instanceCount, mesh.SubSets[i].IndexCount, mesh.SubSets[i].StartIndex); } } else { //non instancing //apply shader shaderStandard.Apply(); //apply constant buffer to shader device.DeviceContext.VertexShader.SetConstantBuffer(0, buffer); device.DeviceContext.PixelShader.SetConstantBuffer(0, buffer); //prepare mesh mesh.Begin(); for (int j = 0; j < instanceCount; j++) { //set world matrix Matrix world = Matrix.RotationY(Environment.TickCount / 2000.0F) * Matrix.Translation(positions[j]); Data sceneInformation = new Data() { world = world, viewProjection = view * projection, lightDirection = new Vector4(lightDirection, 1), viewDirection = new Vector4(Vector3.Normalize(from - to), 1) }; //write data inside constant buffer device.UpdateData <Data>(buffer, sceneInformation); //draw mesh for (int i = 0; i < mesh.SubSets.Count; i++) { device.DeviceContext.PixelShader.SetShaderResource(0, mesh.SubSets[i].DiffuseMap); device.DeviceContext.PixelShader.SetShaderResource(1, mesh.SubSets[i].NormalMap); mesh.Draw(i); } } } //begin drawing text font.Begin(); //draw string fpsCounter.Update(); font.DrawString("FPS: " + fpsCounter.FPS, 0, 0, Color.White); if (instancing) { font.DrawString("Instancing On: Press D to use standard rendering. See FPS", 0, 30, Color.White); } else { font.DrawString("Instancing Off: Press I to use Instancing. See FPS", 0, 30, Color.White); } font.DrawString("Press up and down to change count ", 0, 60, Color.White); font.DrawString("Count: " + instanceCount, 0, 90, Color.White); //flush text to view font.End(); //present device.Present(); }); //release resource font.Dispose(); mesh.Dispose(); buffer.Dispose(); shader.Dispose(); shaderStandard.Dispose(); instanceBuffer.Dispose(); } }
static void Main() { if (!SharpDevice.IsDirectX11Supported()) { System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported"); return; } //render form RenderForm form = new RenderForm(); form.Text = "Tutorial 6: Rasterizer & Alphablending"; //frame rate counter SharpFPS fpsCounter = new SharpFPS(); using (SharpDevice device = new SharpDevice(form)) { //load font SharpBatch font = new SharpBatch(device, "textfont.dds"); //init mesh int[] indices = new int[] { 0, 1, 2, 0, 2, 3, 4, 6, 5, 4, 7, 6, 8, 9, 10, 8, 10, 11, 12, 14, 13, 12, 15, 14, 16, 18, 17, 16, 19, 18, 20, 21, 22, 20, 22, 23 }; TexturedVertex[] vertices = new[] { ////TOP new TexturedVertex(new Vector3(-5, 5, 5), new Vector2(1, 1)), new TexturedVertex(new Vector3(5, 5, 5), new Vector2(0, 1)), new TexturedVertex(new Vector3(5, 5, -5), new Vector2(0, 0)), new TexturedVertex(new Vector3(-5, 5, -5), new Vector2(1, 0)), //BOTTOM new TexturedVertex(new Vector3(-5, -5, 5), new Vector2(1, 1)), new TexturedVertex(new Vector3(5, -5, 5), new Vector2(0, 1)), new TexturedVertex(new Vector3(5, -5, -5), new Vector2(0, 0)), new TexturedVertex(new Vector3(-5, -5, -5), new Vector2(1, 0)), //LEFT new TexturedVertex(new Vector3(-5, -5, 5), new Vector2(0, 1)), new TexturedVertex(new Vector3(-5, 5, 5), new Vector2(0, 0)), new TexturedVertex(new Vector3(-5, 5, -5), new Vector2(1, 0)), new TexturedVertex(new Vector3(-5, -5, -5), new Vector2(1, 1)), //RIGHT new TexturedVertex(new Vector3(5, -5, 5), new Vector2(1, 1)), new TexturedVertex(new Vector3(5, 5, 5), new Vector2(1, 0)), new TexturedVertex(new Vector3(5, 5, -5), new Vector2(0, 0)), new TexturedVertex(new Vector3(5, -5, -5), new Vector2(0, 1)), //FRONT new TexturedVertex(new Vector3(-5, 5, 5), new Vector2(1, 0)), new TexturedVertex(new Vector3(5, 5, 5), new Vector2(0, 0)), new TexturedVertex(new Vector3(5, -5, 5), new Vector2(0, 1)), new TexturedVertex(new Vector3(-5, -5, 5), new Vector2(1, 1)), //BACK new TexturedVertex(new Vector3(-5, 5, -5), new Vector2(0, 0)), new TexturedVertex(new Vector3(5, 5, -5), new Vector2(1, 0)), new TexturedVertex(new Vector3(5, -5, -5), new Vector2(1, 1)), new TexturedVertex(new Vector3(-5, -5, -5), new Vector2(0, 1)) }; SharpMesh mesh = SharpMesh.Create <TexturedVertex>(device, vertices, indices); //init shader SharpShader shader = new SharpShader(device, "../../HLSL.txt", new SharpShaderDescription() { VertexShaderFunction = "VS", PixelShaderFunction = "PS" }, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0) }); //init constant buffer Buffer11 buffer = shader.CreateBuffer <Matrix>(); //load Shader Resouce View from file //it contains texture for using inside shaders ShaderResourceView texture = ShaderResourceView.FromFile(device.Device, "../../texture.dds"); //init frame rate counter fpsCounter.Reset(); //keyboard event //change depth and rasterizer state form.KeyDown += (sender, e) => { switch (e.KeyCode) { case Keys.W: device.SetWireframeRasterState(); device.SetDefaultBlendState(); break; case Keys.S: device.SetDefaultRasterState(); break; case Keys.D1: device.SetDefaultBlendState(); break; case Keys.D2: device.SetBlend(BlendOperation.Add, BlendOption.InverseSourceAlpha, BlendOption.SourceAlpha); break; case Keys.D3: device.SetBlend(BlendOperation.Add, BlendOption.SourceAlpha, BlendOption.InverseSourceAlpha); break; case Keys.D4: device.SetBlend(BlendOperation.Add, BlendOption.SourceColor, BlendOption.InverseSourceColor); break; case Keys.D5: device.SetBlend(BlendOperation.Add, BlendOption.SourceColor, BlendOption.DestinationColor); break; } }; //main loop RenderLoop.Run(form, () => { //Resizing if (device.MustResize) { device.Resize(); font.Resize(); } //apply state device.UpdateAllStates(); //clear color device.Clear(Color.CornflowerBlue); //apply shader shader.Apply(); //apply constant buffer to shader device.DeviceContext.VertexShader.SetConstantBuffer(0, buffer); //set texture device.DeviceContext.PixelShader.SetShaderResource(0, texture); //set transformation matrix float ratio = (float)form.ClientRectangle.Width / (float)form.ClientRectangle.Height; //projection matrix Matrix projection = Matrix.PerspectiveFovLH(3.14F / 3.0F, ratio, 1, 1000); //view matrix (camera) Matrix view = Matrix.LookAtLH(new Vector3(0, 10, -40), new Vector3(), Vector3.UnitY); //world matrix Matrix world = Matrix.RotationY(Environment.TickCount / 1000.0F); Matrix worldViewProjection = world * view * projection; //set world view projection matrix inside constant buffer device.UpdateData <Matrix>(buffer, worldViewProjection); //draw mesh mesh.Draw(); //Second Mesh world = Matrix.RotationY(Environment.TickCount / 1000.0F) * Matrix.Translation(5, 0, -15); worldViewProjection = world * view * projection; //refresh constant buffer device.UpdateData <Matrix>(buffer, worldViewProjection); //draw second mesh mesh.Draw(); //Third Mesh world = Matrix.RotationY(Environment.TickCount / 1000.0F) * Matrix.Translation(-5, 0, -15); worldViewProjection = world * view * projection; //refresh constant buffer device.UpdateData <Matrix>(buffer, worldViewProjection); //draw third mesh mesh.Draw(); //begin drawing text font.Begin(); //draw string fpsCounter.Update(); font.DrawString("FPS: " + fpsCounter.FPS, 0, 0, Color.White); font.DrawString("Press W for wireframe, S for solid", 0, 30, Color.White); font.DrawString("Press From 1 to 5 for Alphablending", 0, 60, Color.White); //flush text to view font.End(); //present device.Present(); }); //release resource font.Dispose(); mesh.Dispose(); buffer.Dispose(); texture.Dispose(); } }
static void Main(string[] args) { if (!SharpDevice.IsDirectX11Supported()) { System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported"); return; } //render form RenderForm form = new RenderForm(); form.Text = "Tutorial 2: Init Device (press key from 1 to 8)"; //background color Color4 color = Color.CornflowerBlue; //keydown event form.KeyDown += (sender, e) => { switch (e.KeyCode) { case System.Windows.Forms.Keys.D1: color = Color.CornflowerBlue; break; case System.Windows.Forms.Keys.D2: color = Color.Red; break; case System.Windows.Forms.Keys.D3: color = Color.Blue; break; case System.Windows.Forms.Keys.D4: color = Color.Orange; break; case System.Windows.Forms.Keys.D5: color = Color.Yellow; break; case System.Windows.Forms.Keys.D6: color = Color.Olive; break; case System.Windows.Forms.Keys.D7: color = Color.Orchid; break; case System.Windows.Forms.Keys.D8: color = Color.Black; break; } }; //main loop using (SharpDevice device = new SharpDevice(form)) { RenderLoop.Run(form, () => { //resize if form was resized if (device.MustResize) { device.Resize(); } //clear color device.Clear(color); //present device.Present(); }); } }