Esempio n. 1
0
        public QuadBuffers(Device device) {
            VertexBuffer = new Buffer(
                    device,
                    new DataStream(new[] {
                        new InputLayouts.VerticePT(new Vector3(-1, -1, 0.999f), new Vector2(0, 1)),
                        new InputLayouts.VerticePT(new Vector3(-1, 1, 0.999f), new Vector2(0, 0)),
                        new InputLayouts.VerticePT(new Vector3(1, 1, 0.999f), new Vector2(1, 0)),
                        new InputLayouts.VerticePT(new Vector3(1, -1, 0.999f), new Vector2(1, 1))
                    }, false, false),
                    new BufferDescription(
                            InputLayouts.VerticePT.StrideValue * 4,
                            ResourceUsage.Immutable,
                            BindFlags.VertexBuffer,
                            CpuAccessFlags.None,
                            ResourceOptionFlags.None,
                            0));

            IndexBuffer = new Buffer(
                    device,
                    new DataStream(new ushort[] { 0, 1, 2, 0, 2, 3 }, false, false),
                    new BufferDescription(
                            sizeof(short) * 6,
                            ResourceUsage.Immutable,
                            BindFlags.IndexBuffer,
                            CpuAccessFlags.None,
                            ResourceOptionFlags.None,
                            0));

            VertexBinding = new VertexBufferBinding(VertexBuffer, InputLayouts.VerticePT.StrideValue, 0);
        }
Esempio n. 2
0
		public void LoadResources()
		{
			if (m_Disposed == true)
			{
				if (m_Filename != null)
				{
					m_ImposterTexture = Texture2D.FromFile(GameEnvironment.Device, Helper.ResolvePath(m_Filename));
					TextureView = new ShaderResourceView(GameEnvironment.Device, m_ImposterTexture);
				}

				m_Vertices = new SlimDX.Direct3D11.Buffer(GameEnvironment.Device, new BufferDescription()
				{
					BindFlags = BindFlags.VertexBuffer,
					CpuAccessFlags = CpuAccessFlags.Write,
					OptionFlags = ResourceOptionFlags.None,
					SizeInBytes = 4 * Marshal.SizeOf(typeof(Vertex2D)),
					Usage = ResourceUsage.Dynamic
				});

				m_VerticesBindings = new VertexBufferBinding(m_Vertices, Marshal.SizeOf(typeof(Vertex2D)), 0);

				WriteRectangle(); 		

				m_Disposed = false;
			}
		}
Esempio n. 3
0
        public Quad(int startX,int endX, int startZ, int endZ, Base.Content.Terrain.Terrain terrain, RenderManager renderer)
        {
            _bounds = new QuadBounds
            {
                MinX = startX / terrain.PointsPerMeter,
                MaxX = endX / terrain.PointsPerMeter,
                MinZ = startZ / terrain.PointsPerMeter,
                MaxZ = endZ / terrain.PointsPerMeter,
                MinY = terrain.Height[0],
                MaxY = terrain.Height[0]
            };
            HorizontalCenter = new Vector2(Bounds.MinX + (Bounds.MaxX - Bounds.MinX) / 2, Bounds.MinZ + (Bounds.MaxZ - Bounds.MinZ) / 2);

            int verticesX = endX - startX + 1;
            int verticesZ = endZ - startZ + 1;

            var dataStream = new DataStream(32 * verticesX * verticesZ, true, true);

            for (int i = 0; i < verticesX; i++)
            {
                for (int j = 0; j < verticesZ; j++)
                {
                    //Position
                    int xindex = Math.Min(i + startX, terrain.PointsX - 1);//Clamp to arraybounds if neccessary
                    int zindex = Math.Min(j + startZ, terrain.PointsZ - 1);//(Quadsize needs to be consistent for sharing IndexBuffers)
                    float x = xindex / terrain.PointsPerMeter;
                    float z = zindex / terrain.PointsPerMeter;
                    float y = terrain.Height[xindex * terrain.PointsZ + zindex];
                    dataStream.Write(new Vector3(x, y, z));

                    //Normal
                    float deltax = (terrain.Height[(xindex < terrain.PointsX - 1 ? xindex + 1 : xindex) * terrain.PointsZ + zindex]
                        - terrain.Height[(xindex != 0 ? xindex - 1 : xindex) * terrain.PointsZ + zindex]);

                    float deltaz = (terrain.Height[xindex * terrain.PointsZ + (zindex < terrain.PointsZ - 1 ? zindex + 1 : zindex)]
                        - terrain.Height[xindex * terrain.PointsZ + (zindex != 0 ? zindex - 1 : zindex)]);
                    if (xindex == 0 || xindex == terrain.PointsX - 1)
                        deltax *= 2;
                    if (zindex == 0 || zindex == terrain.PointsZ - 1)
                        deltaz *= 2;
                    var normal = new Vector3(-deltax, 2 / terrain.PointsPerMeter, deltaz);
                    normal.Normalize();
                    dataStream.Write(normal);

                    //TextureCoordinates
                    dataStream.Write(new Vector2(x / terrain.PointsX, z / terrain.PointsZ));

                    //Boundingbox-Params
                    if (y < _bounds.MinY)
                        _bounds.MinY = y;
                    if (y > _bounds.MaxY)
                        _bounds.MaxY = y;
                }
            }

            dataStream.Position = 0;
            VBuffer = new Buffer(renderer.D3DDevice, dataStream, 32 * verticesX * verticesZ, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
            VertexBuffer = new VertexBufferBinding(VBuffer, 32, 0);
            dataStream.Dispose();
        }
		public InstancedVertexBufferIndex(
			int instanceDataStepRate,
			VertexBufferBinding binding,
			int startLocation)
			: base(binding, startLocation)
		{
			_stepRate = instanceDataStepRate;
		}
        private VertexArrayObject(GraphicsDevice graphicsDevice, EffectInputSignature shaderSignature, IndexBufferBinding indexBufferBinding, VertexBufferBinding[] vertexBufferBindings)
            : base(graphicsDevice)
        {
            this.vertexBufferBindings = vertexBufferBindings;
            this.indexBufferBinding = indexBufferBinding;
            this.preferredInputSignature = shaderSignature;

            CreateAttributes();
        }
Esempio n. 6
0
        /// <summary>
        /// Resizes the buffer to the nearest power of two >= nVertices
        /// and sets Count to nVertices
        /// </summary>
        /// <param name="nVertices"></param>
        public void Resize( int nVertices )
        {
            if( nVertices > Capacity || // if we need more than we currently have allocated
                nVertices < Capacity / 2 ) // or if the current one is more than twice as big
            {
                Capacity = nVertices.RoundUpToNearestPowerOfTwo();

                if( VertexBuffer != null )
                {
                    VertexBuffer.Dispose();
                }
                VertexBuffer = BufferFactory.CreateDynamicVertexBuffer( Capacity, VertexSizeBytes );
                DefaultBinding = new VertexBufferBinding( VertexBuffer, VertexSizeBytes, 0 );
            }
            Count = nVertices;
        }
        private VertexArrayObject(GraphicsDevice graphicsDevice, EffectInputSignature shaderSignature, IndexBufferBinding indexBufferBinding, VertexBufferBinding[] vertexBufferBindings)
            : base(graphicsDevice)
        {
            this.vertexBufferBindings = vertexBufferBindings;
            this.indexBufferBinding = indexBufferBinding;
            this.preferredInputSignature = shaderSignature;
            
            // Increase the reference count on the provided buffers -> we do not want to take the ownership
            foreach (VertexBufferBinding vertexBufferBinding in vertexBufferBindings)
                vertexBufferBinding.Buffer.AddReferenceInternal();

            if (indexBufferBinding != null)
                indexBufferBinding.Buffer.AddReferenceInternal();

            CreateAttributes();
        }
Esempio n. 8
0
		public void LoadResources()
		{
			if (m_Disposed == true)
			{
				m_DiffuseTexture = Texture2D.FromFile(GameEnvironment.Device, Helper.ResolvePath(m_DiffuseTexturePath));

				m_DiffuseTextureView = new ShaderResourceView(GameEnvironment.Device, m_DiffuseTexture);

				m_DiffuseLightMapTexture = Texture2D.FromFile(GameEnvironment.Device, Helper.ResolvePath(m_DiffuseLightMapPath));

				m_DiffuseLightMapTextureView = new ShaderResourceView(GameEnvironment.Device, m_DiffuseLightMapTexture);

				m_SpecularLightMapTexture = Texture2D.FromFile(GameEnvironment.Device, Helper.ResolvePath(m_SpecularLightMapPath));

				m_SpecularLightMapTextureView = new ShaderResourceView(GameEnvironment.Device, m_SpecularLightMapTexture);

				#region Create Volume Bounding Box

				float right = (float)m_Size.X * 0.5f;
				float front = (float)m_Size.Y * 0.5f;
				float top = (float)m_Size.Z * 0.5f;

				Vector3 TopLeftBack		= new Vector3(-right, -front,  top);
				Vector3 TopRightBack	= new Vector3( right, -front,  top);
				Vector3 TopLeftFront	= new Vector3(-right,  front,  top);
				Vector3 TopRightFront	= new Vector3( right,  front,  top);
				
				Vector3 BottomLeftBack	 = new Vector3(-right, -front, -top);
				Vector3 BottomRightBack  = new Vector3( right, -front, -top);
				Vector3 BottomLeftFront  = new Vector3(-right,  front, -top);
				Vector3 BottomRightFront = new Vector3( right,  front, -top);

				Vector3 NormalUp = new Vector3(0, 0, 1);
				Vector3 NormalDown = new Vector3(0, 0, -1);
				
				Vector3 NormalLeft = new Vector3(-1, 0, 0);
				Vector3 NormalRight = new Vector3(1, 0, 0);

				Vector3 NormalBack = new Vector3(0, -1, 0);
				Vector3 NormalFront = new Vector3(0, 1, 0);

				//Vector3[] faceNormals = new Vector3[6];

				//faceNormals[(int)FaceIndex.Top] = NormalUp;
				//faceNormals[(int)FaceIndex.Bottom] = NormalDown;
				//faceNormals[(int)FaceIndex.Left] = NormalLeft;
				//faceNormals[(int)FaceIndex.Right] = NormalRight;
				//faceNormals[(int)FaceIndex.Back] = NormalBack;
				//faceNormals[(int)FaceIndex.Front] = NormalFront;

				Vector3 TopLeftBack_Normal = MergeNomrals(NormalLeft, NormalUp, NormalBack);
				Vector3 TopRightBack_Normal = MergeNomrals(NormalRight, NormalUp, NormalBack);
				Vector3 TopLeftFront_Normal = MergeNomrals(NormalLeft, NormalUp, NormalFront);
				Vector3 TopRightFront_Normal = MergeNomrals(NormalRight, NormalUp, NormalFront);

				Vector3 BottomLeftBack_Normal = MergeNomrals(NormalLeft, NormalDown, NormalBack);
				Vector3 BottomRightBack_Normal = MergeNomrals(NormalRight, NormalDown, NormalBack);
				Vector3 BottomLeftFront_Normal = MergeNomrals(NormalLeft, NormalDown, NormalFront);
				Vector3 BottomRightFront_Normal = MergeNomrals(NormalRight, NormalDown, NormalFront);


				Vector2 TexTopLeft		= new Vector2(0, 0);
				Vector2 TexTopRight		= new Vector2(0, 1);
				Vector2 TexBottomLeft	= new Vector2(1, 0);
				Vector2 TexBottomRight	= new Vector2(1, 1);

				MaterialVertex[] verts = new MaterialVertex[4 * 6];

				int virt = 0;
				int faces = 0;

				faces++;
				//virt = faces++ * 4; //  (int)FaceIndex.Top * 4;
				virt = (int)FaceIndex.Top * 4;
				verts[virt++] = new MaterialVertex() { Position = TopLeftBack, DiffuseTextureCoords = TexTopLeft, Normal = NormalUp };
				verts[virt++] = new MaterialVertex() { Position = TopRightBack, DiffuseTextureCoords = TexBottomLeft, Normal = NormalUp };
				verts[virt++] = new MaterialVertex() { Position = TopLeftFront, DiffuseTextureCoords = TexTopRight, Normal = NormalUp };
				verts[virt++] = new MaterialVertex() { Position = TopRightFront, DiffuseTextureCoords = TexBottomRight, Normal = NormalUp };

				faces++;
				//virt = faces++ * 4; // (int)FaceIndex.Front * 4;
				virt = (int)FaceIndex.Front * 4;
				verts[virt++] = new MaterialVertex() { Position = TopLeftFront, DiffuseTextureCoords = TexTopLeft, Normal = NormalFront };
				verts[virt++] = new MaterialVertex() { Position = TopRightFront, DiffuseTextureCoords = TexTopRight, Normal = NormalFront };
				verts[virt++] = new MaterialVertex() { Position = BottomLeftFront, DiffuseTextureCoords = TexBottomLeft, Normal = NormalFront };
				verts[virt++] = new MaterialVertex() { Position = BottomRightFront, DiffuseTextureCoords = TexBottomRight, Normal = NormalFront };	 

				faces++;
				//virt = faces++ * 4; // (int)FaceIndex.Back * 4;
				virt = (int)FaceIndex.Back * 4;
				verts[virt++] = new MaterialVertex() { Position = TopRightBack, DiffuseTextureCoords = TexTopRight, Normal = NormalBack };
				verts[virt++] = new MaterialVertex() { Position = TopLeftBack, DiffuseTextureCoords = TexTopLeft, Normal = NormalBack };
				verts[virt++] = new MaterialVertex() { Position = BottomRightBack, DiffuseTextureCoords = TexBottomRight, Normal = NormalBack };
				verts[virt++] = new MaterialVertex() { Position = BottomLeftBack, DiffuseTextureCoords = TexBottomLeft, Normal = NormalBack };

				faces++;
				//virt = faces++ * 4; // (int)FaceIndex.Left * 4;
				virt = (int)FaceIndex.Left * 4;
				verts[virt++] = new MaterialVertex() { Position = TopLeftBack, DiffuseTextureCoords = TexTopLeft, Normal = NormalLeft };
				verts[virt++] = new MaterialVertex() { Position = TopLeftFront, DiffuseTextureCoords = TexTopRight, Normal = NormalLeft };
				verts[virt++] = new MaterialVertex() { Position = BottomLeftBack, DiffuseTextureCoords = TexBottomLeft, Normal = NormalLeft };
				verts[virt++] = new MaterialVertex() { Position = BottomLeftFront, DiffuseTextureCoords = TexBottomRight, Normal = NormalLeft };

				faces++;
				//virt = faces++ * 4; // (int)FaceIndex.Right * 4;				
				virt = (int)FaceIndex.Right * 4;
				verts[virt++] = new MaterialVertex() { Position = TopRightFront, DiffuseTextureCoords = TexTopRight, Normal = NormalRight };
				verts[virt++] = new MaterialVertex() { Position = TopRightBack, DiffuseTextureCoords = TexTopLeft, Normal = NormalRight };				
				verts[virt++] = new MaterialVertex() { Position = BottomRightFront, DiffuseTextureCoords = TexBottomRight, Normal = NormalRight };
				verts[virt++] = new MaterialVertex() { Position = BottomRightBack, DiffuseTextureCoords = TexBottomLeft, Normal = NormalRight };

				faces++;
				//virt = faces++ * 4; // (int)FaceIndex.Bottom * 4;
				virt = (int)FaceIndex.Bottom * 4;
				verts[virt++] = new MaterialVertex() { Position = BottomRightBack, DiffuseTextureCoords = TexTopLeft, Normal = NormalDown };		
				verts[virt++] = new MaterialVertex() { Position = BottomLeftBack, DiffuseTextureCoords = TexTopRight, Normal = NormalDown };				
				verts[virt++] = new MaterialVertex() { Position = BottomRightFront, DiffuseTextureCoords = TexBottomLeft, Normal = NormalDown };	
				verts[virt++] = new MaterialVertex() { Position = BottomLeftFront, DiffuseTextureCoords = TexBottomRight, Normal = NormalDown };				


				/* 
				faces++;
				//virt = faces++ * 4; //  (int)FaceIndex.Top * 4;
				virt = (int)FaceIndex.Top * 4;
				verts[virt++] = new MaterialVertex() { Position = TopLeftBack, DiffuseTextureCoords = TexTopLeft, Normal = TopLeftBack_Normal }; // NormalUp };
				verts[virt++] = new MaterialVertex() { Position = TopRightBack, DiffuseTextureCoords = TexBottomLeft, Normal = TopRightBack_Normal }; // NormalUp };
				verts[virt++] = new MaterialVertex() { Position = TopLeftFront, DiffuseTextureCoords = TexTopRight, Normal = TopLeftFront_Normal }; // NormalUp };
				verts[virt++] = new MaterialVertex() { Position = TopRightFront, DiffuseTextureCoords = TexBottomRight, Normal = TopRightFront_Normal }; //  NormalUp };

				faces++;
				//virt = faces++ * 4; // (int)FaceIndex.Front * 4;
				virt = (int)FaceIndex.Front * 4;
				verts[virt++] = new MaterialVertex() { Position = TopLeftFront, DiffuseTextureCoords = TexTopLeft, Normal = TopLeftFront_Normal }; // NormalFront };
				verts[virt++] = new MaterialVertex() { Position = TopRightFront, DiffuseTextureCoords = TexTopRight, Normal = TopRightFront_Normal }; // NormalFront };
				verts[virt++] = new MaterialVertex() { Position = BottomLeftFront, DiffuseTextureCoords = TexBottomLeft, Normal = BottomLeftFront_Normal }; // NormalFront };
				verts[virt++] = new MaterialVertex() { Position = BottomRightFront, DiffuseTextureCoords = TexBottomRight, Normal = BottomRightFront_Normal }; // NormalFront };	 

				faces++;
				//virt = faces++ * 4; // (int)FaceIndex.Back * 4;
				virt = (int)FaceIndex.Back * 4;
				verts[virt++] = new MaterialVertex() { Position = TopRightBack, DiffuseTextureCoords = TexTopRight, Normal = TopRightBack_Normal }; // NormalBack };
				verts[virt++] = new MaterialVertex() { Position = TopLeftBack, DiffuseTextureCoords = TexTopLeft, Normal = TopLeftBack_Normal }; // NormalBack };
				verts[virt++] = new MaterialVertex() { Position = BottomRightBack, DiffuseTextureCoords = TexBottomRight, Normal = BottomRightBack_Normal }; // NormalBack };
				verts[virt++] = new MaterialVertex() { Position = BottomLeftBack, DiffuseTextureCoords = TexBottomLeft, Normal = BottomLeftBack_Normal }; // NormalBack };

				faces++;
				//virt = faces++ * 4; // (int)FaceIndex.Left * 4;
				virt = (int)FaceIndex.Left * 4;
				verts[virt++] = new MaterialVertex() { Position = TopLeftBack, DiffuseTextureCoords = TexTopLeft, Normal = TopLeftBack_Normal }; // NormalLeft };
				verts[virt++] = new MaterialVertex() { Position = TopLeftFront, DiffuseTextureCoords = TexTopRight, Normal = TopLeftFront_Normal }; // NormalLeft };
				verts[virt++] = new MaterialVertex() { Position = BottomLeftBack, DiffuseTextureCoords = TexBottomLeft, Normal = BottomLeftBack_Normal }; // NormalLeft };
				verts[virt++] = new MaterialVertex() { Position = BottomLeftFront, DiffuseTextureCoords = TexBottomRight, Normal = BottomLeftFront_Normal }; // NormalLeft };

				faces++;
				//virt = faces++ * 4; // (int)FaceIndex.Right * 4;				
				virt = (int)FaceIndex.Right * 4;
				verts[virt++] = new MaterialVertex() { Position = TopRightFront, DiffuseTextureCoords = TexTopRight, Normal = TopRightFront_Normal }; // NormalRight };
				verts[virt++] = new MaterialVertex() { Position = TopRightBack, DiffuseTextureCoords = TexTopLeft, Normal = TopRightBack_Normal }; // NormalRight };				
				verts[virt++] = new MaterialVertex() { Position = BottomRightFront, DiffuseTextureCoords = TexBottomRight, Normal = BottomRightFront_Normal }; // NormalRight };
				verts[virt++] = new MaterialVertex() { Position = BottomRightBack, DiffuseTextureCoords = TexBottomLeft, Normal = BottomRightBack_Normal }; // NormalRight };

				faces++;
				//virt = faces++ * 4; // (int)FaceIndex.Bottom * 4;
				virt = (int)FaceIndex.Bottom * 4;
				verts[virt++] = new MaterialVertex() { Position = BottomRightBack, DiffuseTextureCoords = TexTopLeft, Normal = BottomRightBack_Normal }; // NormalDown };		
				verts[virt++] = new MaterialVertex() { Position = BottomLeftBack, DiffuseTextureCoords = TexTopRight, Normal = BottomLeftBack_Normal }; // NormalDown };				
				verts[virt++] = new MaterialVertex() { Position = BottomRightFront, DiffuseTextureCoords = TexBottomLeft, Normal = BottomRightFront_Normal }; // NormalDown };	
				verts[virt++] = new MaterialVertex() { Position = BottomLeftFront, DiffuseTextureCoords = TexBottomRight, Normal = BottomLeftFront_Normal }; // NormalDown };				
				*/ 
				int[] indices = new int[faces * 6];

				int ind = 0;
				for (int i = 0; i < faces; i++)
				{
					int baseIndex = i * 4;
					indices[ind++] = baseIndex + 0;
					indices[ind++] = baseIndex + 2;
					indices[ind++] = baseIndex + 1;

					indices[ind++] = baseIndex + 3;
					indices[ind++] = baseIndex + 1;
					indices[ind++] = baseIndex + 2;
				}


				/*
				verts[0] = new MaterialVertex() { Position = new Vector3(-right, -front, -top), DiffuseTextureCoords = new Vector2(0, 0), Normal = new Vector3() };
				verts[1] = new MaterialVertex() { Position = new Vector3(right, -front, -top), DiffuseTextureCoords = new Vector2(1, 0), Normal = new Vector3() };
				verts[2] = new MaterialVertex() { Position = new Vector3(-right, front, -top), DiffuseTextureCoords = new Vector2(0, 1), Normal = new Vector3() };
				verts[3] = new MaterialVertex() { Position = new Vector3(right, front, -top), DiffuseTextureCoords = new Vector2(1, 1), Normal = new Vector3() };

				verts[4] = new MaterialVertex() { Position = new Vector3(-right, -front,  top), DiffuseTextureCoords = new Vector2(0, 1), Normal = new Vector3() };
				verts[5] = new MaterialVertex() { Position = new Vector3( right, -front,  top), DiffuseTextureCoords = new Vector2(1, 1), Normal = new Vector3() };
				verts[6] = new MaterialVertex() { Position = new Vector3(-right,  front,  top), DiffuseTextureCoords = new Vector2(0, 0), Normal = new Vector3() };
				verts[7] = new MaterialVertex() { Position = new Vector3( right,  front,  top), DiffuseTextureCoords = new Vector2(1, 0), Normal = new Vector3() };

				int[] indices = new int[] { 
					// 0
					0, 1, 2, 
					1, 3, 2, 

					// 1
					0, 6, 4, 
					0, 2, 6, 

					// 2
					2, 7, 6, 
					3, 7, 2, 

					// 3
					1, 5, 7, 
					7, 3, 1, 

					// 4
					0, 4, 5, 
					5, 1, 0, 
 
					// 5
					4, 6, 5, 
					6, 7, 5
				};

				int[] indexToFaceMapping = new int[8 * 3] 
				{
					// 0
					0, 1, 4, 

					// 1
					0, 3, 4,

					// 2
					0, 1, 2, 

					// 3
					0, 2, 3, 

					// 4
					1, 4, 5,

					// 5
					3, 4, 5,
					
					// 6
					1, 2, 5,

					// 7					
					2, 1, 5
				};
				/*
				int itf = 0; 

				for (int i = 0; i < 8; i++)
				{
					for (int j = 0; j < 6; j++)
					{
						int faceOffset = j * 6; 

						for (int k = 0; k < 6; k++)
						{

						}
					}
				}
				* / 				

				Vector3[] faceNormals = new Vector3[6];
				int fi = 0;

				for (int i = 0; i < indices.Length; i += 6)
				{
					Vector3 u = verts[indices[i + 1]].Position - verts[indices[i]].Position;
					Vector3 v = verts[indices[i + 2]].Position - verts[indices[i]].Position;

					faceNormals[fi++] = Vector3.Cross(u, v);
				}

				Vector3[] vertNormals = new Vector3[verts.Length];

				fi = 0;
				for (int i = 0; i < verts.Length; i++)
				{
					Vector3 n = faceNormals[indexToFaceMapping[fi++]];
					n += faceNormals[indexToFaceMapping[fi++]];
					n += faceNormals[indexToFaceMapping[fi++]];

					vertNormals[i] = n; 
				}
				
				/* for (int i = 0; i < indices.Length; i += 3)
				{
					Vector3 n = faceNormals[fi++];
					vertNormals[indices[i]] += n;
					vertNormals[indices[i + 1]] += n;
					vertNormals[indices[i + 2]] += n;
				}* / 

				for (int i = 0; i < verts.Length; i++)
				{
					vertNormals[i].Normalize();
					verts[i].Normal = vertNormals[i]; // *-1f; 
				}

				/* 
				Vector3[] faceNormals = new Vector3[12];
				int fi = 0; 

				for (int i = 0; i < indices.Length; i += 3)
				{
					Vector3 u = verts[indices[i + 1]].Position - verts[indices[i]].Position;
					Vector3 v = verts[indices[i + 2]].Position - verts[indices[i]].Position;

					faceNormals[fi++] = Vector3.Cross(u, v);
				}

				Vector3[] vertNormals = new Vector3[verts.Length];

				fi = 0; 
				for (int i = 0; i < indices.Length; i += 3)
				{
					Vector3 n = faceNormals[fi++]; 
					vertNormals[indices[i]] += n;
					vertNormals[indices[i + 1]] += n;
					vertNormals[indices[i + 2]] += n;
				}

				for (int i = 0; i < verts.Length; i++)
				{
					vertNormals[i].Normalize();
					verts[i].Normal = vertNormals[i]; // *-1f; 
				}
				*/

				m_IndexCount = indices.Length;

				using (DataStream stream = new DataStream(verts.Length * Marshal.SizeOf(typeof(MaterialVertex)), false, true))
				{
					stream.WriteRange(verts);

					stream.Position = 0;

					m_Vertices = new SlimDX.Direct3D11.Buffer(GameEnvironment.Device, stream, new BufferDescription()
					{
						BindFlags = BindFlags.VertexBuffer,
						CpuAccessFlags = CpuAccessFlags.None,
						OptionFlags = ResourceOptionFlags.None,
						SizeInBytes = verts.Length * Marshal.SizeOf(typeof(MaterialVertex)),
						Usage = ResourceUsage.Default
					});
				}

				m_CubeBindings = new VertexBufferBinding(m_Vertices, Marshal.SizeOf(typeof(MaterialVertex)), 0);

				using (DataStream stream = new DataStream(indices.Length * sizeof(int), true, true))
				{
					stream.WriteRange(indices);
					stream.Position = 0;

					m_Indices = new SlimDX.Direct3D11.Buffer(GameEnvironment.Device, stream, new BufferDescription()
					{
						BindFlags = BindFlags.IndexBuffer,
						CpuAccessFlags = CpuAccessFlags.None,
						OptionFlags = ResourceOptionFlags.None,
						SizeInBytes = indices.Length * sizeof(int),
						Usage = ResourceUsage.Default
					});
				}

				#endregion
				
			}
		}
Esempio n. 9
0
        protected void InitOnce()
        {
            var shaderdeffile = Manager.Files.Get(@"Shaders\DeferredRendering.hlsl", false);
            var bbuffer = new byte[shaderdeffile.Length];
            shaderdeffile.Read(bbuffer,0, bbuffer.Length);
            shaderdeffile.Dispose();
            var bytecode = ShaderBytecode.Compile(bbuffer, "fx_5_0");
            bbuffer = null;
            _effect = new Effect(D3DDevice, bytecode);
            bytecode.Dispose();

            _composeTechnique = _effect.GetTechniqueByName("Compose");
            _composePass = _composeTechnique.GetPassByIndex(0);

            var vertices = new DataStream(20 * 4, true, true);
            vertices.Write(new Vector3(-1f, -1f, -1f));
            vertices.Write(new Vector2(0f,1f));
            vertices.Write(new Vector3(-1f, 1f, -1f));
            vertices.Write(new Vector2(0f, 0f));
            vertices.Write(new Vector3(1f, -1f, -1f));
            vertices.Write(new Vector2(1f, 1f));
            vertices.Write(new Vector3(1f, 1f, -1f));
            vertices.Write(new Vector2(1f, 0f));
            vertices.Position = 0;
            _composeVertices = new Buffer(D3DDevice, vertices, 20 * 4, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
            _composeVerticesBB = new VertexBufferBinding(_composeVertices, 20, 0);
            vertices.Dispose();
            _composeLayout = new InputLayout(D3DDevice, _composePass.Description.Signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 0) });
            var sampleMode = SamplerState.FromDescription(D3DDevice, new SamplerDescription()
            {
                AddressU = TextureAddressMode.Clamp,
                AddressV = TextureAddressMode.Clamp,
                AddressW = TextureAddressMode.Clamp,
                BorderColor = new Color4(0, 0, 0, 0),
                Filter = Filter.MinLinearMagMipPoint,
                ComparisonFunction = Comparison.Always,
                MipLodBias = 0f,
                MaximumAnisotropy = 8,
                MinimumLod = 0f,
                MaximumLod = float.MaxValue
            });
            _effect.GetVariableByName("composeSampler").AsSampler().SetSamplerState(0, sampleMode);
            sampleMode.Dispose();
            _effect.GetVariableByName("composeFlags").AsScalar().Set(
                Manager.Opts.Get<bool>("rndr_rawGBufferView")?0x1:0
                );

            NotifyHandlers.Add(Manager.Opts.RegisterChangeNotification("rndr_rawGBufferView", delegate(string key, object value)
            {
                Output.BeginInvoke((Action)delegate
                {
                    if ((bool)value)
                        _effect.GetVariableByName("composeFlags").AsScalar().Set(_effect.GetVariableByName("composeFlags").AsScalar().GetInt() | 0x1);
                    else
                        _effect.GetVariableByName("composeFlags").AsScalar().Set(_effect.GetVariableByName("composeFlags").AsScalar().GetInt() & (int.MaxValue - 0x1));
                });
            }));

            NotifyHandlers.Add(Manager.Opts.RegisterChangeNotification("rndr_nearPlane", delegate {
                Output.BeginInvoke((Action)ResetDevice);
            }));
            NotifyHandlers.Add(Manager.Opts.RegisterChangeNotification("rndr_farPlane", delegate {
                Output.BeginInvoke((Action)ResetDevice);
            }));

            SceneRasterizer = RasterizerState.FromDescription(D3DDevice, new RasterizerStateDescription()
                                                                                      {
                                                                                          FillMode = (Manager.Opts.Get<bool>("rndr_wireframe") ? FillMode.Wireframe : FillMode.Solid),
                                                                                          CullMode = (Manager.Opts.Get<bool>("rndr_cull") ? CullMode.Back : CullMode.None)
                                                                                      });
            _composeRasterizer = RasterizerState.FromDescription(D3DDevice, new RasterizerStateDescription()
            {
                FillMode = FillMode.Solid,
                CullMode = CullMode.Back
            });

            var bsd = new BlendStateDescription();
            bsd.RenderTargets[0].BlendEnable = true;

            bsd.RenderTargets[0].SourceBlend = BlendOption.SourceAlpha;
            bsd.RenderTargets[0].DestinationBlend = BlendOption.InverseSourceAlpha;
            bsd.RenderTargets[0].BlendOperation = BlendOperation.Add;

            bsd.RenderTargets[0].SourceBlendAlpha = BlendOption.One;
            bsd.RenderTargets[0].DestinationBlendAlpha = BlendOption.Zero;
            bsd.RenderTargets[0].BlendOperationAlpha = BlendOperation.Add;
            bsd.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;

            Context.OutputMerger.BlendState = BlendState.FromDescription(D3DDevice, bsd);

            NotifyHandlers.Add(Manager.Opts.RegisterChangeNotification("rndr_wireframe", delegate(string key, object value)
            {
                Output.BeginInvoke((Action)delegate {
                    var oldcullmode = CullMode.Back;
                    if (SceneRasterizer != null)
                    {
                        oldcullmode = SceneRasterizer.Description.CullMode;
                        SceneRasterizer.Dispose();
                    }
                    SceneRasterizer = RasterizerState.FromDescription(D3DDevice, new RasterizerStateDescription()
                    {
                        FillMode = (((bool)value) ? FillMode.Wireframe : FillMode.Solid),
                        CullMode = oldcullmode
                    });
                });
            }));
            NotifyHandlers.Add(Manager.Opts.RegisterChangeNotification("rndr_cull", delegate(string key, object value)
            {
                Output.BeginInvoke((Action)delegate
                {
                    var oldfillmode = FillMode.Solid;
                    if (SceneRasterizer != null)
                    {
                        oldfillmode = SceneRasterizer.Description.FillMode;
                        SceneRasterizer.Dispose();
                    }
                    SceneRasterizer = RasterizerState.FromDescription(D3DDevice, new RasterizerStateDescription()
                    {
                        FillMode =  oldfillmode,
                        CullMode = (((bool)value) ? CullMode.Back : CullMode.None)
                    });
                });
            }));

            Context.OutputMerger.DepthStencilState = DepthStencilState.FromDescription(D3DDevice, new DepthStencilStateDescription()
                                                                                                      {
                                                                                                          IsDepthEnabled = true,
                                                                                                          DepthWriteMask = DepthWriteMask.All,
                                                                                                          DepthComparison = Comparison.Less,
                                                                                                          IsStencilEnabled = false,
                                                                                                      });
            _camIncorporeal = Manager.Opts.Get<bool>("rndr_incorporeal");
            NotifyHandlers.Add(Manager.Opts.RegisterChangeNotification("rndr_incorporeal", delegate(string key, object value) { _camIncorporeal = (bool)value; }));

            ViewerLocation = new Vector3(-1, 1, -1);
            ViewerLookAt = new Vector3(0, 0, 0);
            ViewerUpVector = Vector3.UnitY;
            _camLocationIncorporeal = new Vector3(-1, 1, -1);
            _camLookAtIncorporeal = new Vector3(0, 0, 0);
            _camUpVectorIncorporeal = Vector3.UnitY;
            ViewerFrustum = new Frustum();
            _fpsTimer = new HTimer();
            _fpsRingbuffer = new double[60];
            _fpsRingbufferIndex = 0;
        }
        protected override void CreateDeviceDependentResources()
        {
            RemoveAndDispose(ref vertexBuffer);
            RemoveAndDispose(ref indexBuffer);
            RemoveAndDispose(ref textureView);
            RemoveAndDispose(ref samplerState);

            // Retrieve our SharpDX.Direct3D11.Device1 instance
            var device = this.DeviceManager.Direct3DDevice;

            // Load texture (a DDS cube map)
            textureView = TextureLoader.ShaderResourceViewFromFile(device, "CubeMap.dds");

            // Create our sampler state
            samplerState = new SamplerState(device, new SamplerStateDescription()
            {
                AddressU           = TextureAddressMode.Clamp,
                AddressV           = TextureAddressMode.Clamp,
                AddressW           = TextureAddressMode.Clamp,
                BorderColor        = new Color4(0, 0, 0, 0),
                ComparisonFunction = Comparison.Never,
                Filter             = Filter.MinMagMipLinear,
                MaximumLod         = 9, // Our cube map has 10 mip map levels (0-9)
                MinimumLod         = 0,
                MipLodBias         = 0.0f
            });

            // Create vertex buffer for cube
            vertexBuffer = ToDispose(Buffer.Create(device, BindFlags.VertexBuffer, new Vertex[] {
                /*  Vertex Position    Normal, Color */
                new Vertex(-0.5f, 0.5f, -0.5f, -1f, 1f, -1f, Color.Gray),   // 0-Top-left
                new Vertex(0.5f, 0.5f, -0.5f, 1f, 1f, -1f, Color.Gray),     // 1-Top-right
                new Vertex(0.5f, -0.5f, -0.5f, 1f, -1f, -1f, Color.Gray),   // 2-Base-right
                new Vertex(-0.5f, -0.5f, -0.5f, -1f, -1f, -1f, Color.Gray), // 3-Base-left

                new Vertex(-0.5f, 0.5f, 0.5f, -1f, 1f, 1f, Color.Gray),     // 4-Top-left
                new Vertex(0.5f, 0.5f, 0.5f, 1f, 1f, 1f, Color.Gray),       // 5-Top-right
                new Vertex(0.5f, -0.5f, 0.5f, 1f, -1f, 1f, Color.Gray),     // 6-Base-right
                new Vertex(-0.5f, -0.5f, 0.5f, -1f, -1f, 1f, Color.Gray),   // 7-Base-left
            }));
            vertexBinding = new VertexBufferBinding(vertexBuffer, Utilities.SizeOf <Vertex>(), 0);

            // Front    Right    Top      Back     Left     Bottom
            // v0    v1 v1    v5 v1    v0 v5    v4 v4    v0 v3    v2
            // |-----|  |-----|  |-----|  |-----|  |-----|  |-----|
            // | \ A |  | \ A |  | \ A |  | \ A |  | \ A |  | \ A |
            // | B \ |  | B \ |  | B \ |  | B \ |  | B \ |  | B \ |
            // |-----|  |-----|  |-----|  |-----|  |-----|  |-----|
            // v3    v2 v2    v6 v5    v4 v6    v7 v7    v3 v7    v6
            indexBuffer = ToDispose(Buffer.Create(device, BindFlags.IndexBuffer, new ushort[] {
                0, 1, 2, // Front A
                0, 2, 3, // Front B
                1, 5, 6, // Right A
                1, 6, 2, // Right B
                1, 0, 4, // Top A
                1, 4, 5, // Top B
                5, 4, 7, // Back A
                5, 7, 6, // Back B
                4, 0, 3, // Left A
                4, 3, 7, // Left B
                3, 2, 6, // Bottom A
                3, 6, 7, // Bottom B
            }));
        }
Esempio n. 11
0
		public void Render(VertexBufferBinding[] bindings, int count, Matrix worldViewProj, ShaderResourceView texture,
							float ampScale, float partScaleX, float partScaleY,
							float minDistance, float maxDistance, float scaleDistance)
		{
			SlimDX.Direct3D11.DeviceContext context = GameEnvironment.Device.ImmediateContext; 

			m_WorldViewProj.SetMatrix(worldViewProj);
			m_ParticleTexture.SetResource(texture);
			m_AmpScale.Set(ampScale);
			m_PartScaleX.Set(partScaleX);
			m_PartScaleY.Set(partScaleY);
			m_MaxDistance.Set(maxDistance);
			m_MinDistance.Set(minDistance);
			m_ScaleDistance.Set(scaleDistance);

			context.InputAssembler.InputLayout = m_Layout;
			context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;
			context.InputAssembler.SetVertexBuffers(0, bindings);

			m_ParticlePass_Add.Apply(context);
			context.DrawInstanced(4, count, 0, 0);			
		}
        public void Update()
        {
            // Dispose old buffers
            vtxBuffer.Dispose();
            foreach (var buffer in submeshes)
                buffer.Dispose();

            // Write the stream
            var strm = new DataStream(buffersize, true, true);
            for (int i = 0; i < mesh.Positions.Length; i++)
            {
                strm.Write(mesh.Positions[i]);
                if (mesh.Normals != null) strm.Write(mesh.Normals[i]);
                if (mesh.TextureCoordinates != null) strm.Write(mesh.TextureCoordinates[i]);
                if (mesh.Tangents != null) strm.Write(mesh.Tangents[i]);
            }
            strm.Position = 0;

            // Build the buffer
            vtxBuffer = new Buffer(device, strm, new BufferDescription((int)strm.Length, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));
            bufferbinding = new VertexBufferBinding(vtxBuffer, elementsize, 0);

            // Build the indices buffer(s)
            submeshes = new Buffer[mesh.Submeshes.Length];
            for (int i = 0; i < submeshes.Length; i++)
                submeshes[i] = ArrayToBuffer(mesh.Submeshes[i], ResourceUsage.Default);

            // Update iteration
            Iteration = mesh.Iteration;
        }
Esempio n. 13
0
        public static unsafe BoundingBox ComputeBounds(this VertexBufferBinding vertexBufferBinding, ref Matrix matrix, out BoundingSphere boundingSphere)
        {
            var positionOffset = vertexBufferBinding.Declaration
                                 .EnumerateWithOffsets()
                                 .First(x => x.VertexElement.SemanticAsText == "POSITION")
                                 .Offset;

            var boundingBox = BoundingBox.Empty;

            boundingSphere = new BoundingSphere();

            var vertexStride = vertexBufferBinding.Declaration.VertexStride;

            fixed(byte *bufferStart = &vertexBufferBinding.Buffer.GetSerializationData().Content[vertexBufferBinding.Offset])
            {
                // Calculates bounding box and bounding sphere center
                byte *buffer = bufferStart + positionOffset;

                for (int i = 0; i < vertexBufferBinding.Count; ++i)
                {
                    var     position = (Vector3 *)buffer;
                    Vector3 transformedPosition;

                    Vector3.TransformCoordinate(ref *position, ref matrix, out transformedPosition);

                    // Prepass calculate the center of the sphere
                    Vector3.Add(ref transformedPosition, ref boundingSphere.Center, out boundingSphere.Center);

                    BoundingBox.Merge(ref boundingBox, ref transformedPosition, out boundingBox);

                    buffer += vertexStride;
                }

                //This is the center of our sphere.
                boundingSphere.Center /= (float)vertexBufferBinding.Count;

                // Calculates bounding sphere center
                buffer = bufferStart + positionOffset;
                for (int i = 0; i < vertexBufferBinding.Count; ++i)
                {
                    var     position = (Vector3 *)buffer;
                    Vector3 transformedPosition;

                    Vector3.TransformCoordinate(ref *position, ref matrix, out transformedPosition);

                    //We are doing a relative distance comparasin to find the maximum distance
                    //from the center of our sphere.
                    float distance;
                    Vector3.DistanceSquared(ref boundingSphere.Center, ref transformedPosition, out distance);

                    if (distance > boundingSphere.Radius)
                    {
                        boundingSphere.Radius = distance;
                    }

                    buffer += vertexStride;
                }

                //Find the real distance from the DistanceSquared.
                boundingSphere.Radius = MathF.Sqrt(boundingSphere.Radius);
            }

            return(boundingBox);
        }
Esempio n. 14
0
        public WaterMesh(String meshName, float planeSize, int cmplx)           // najak R-F
        // Assign Fields to the Initializer values
        {
            this.meshName = meshName;
            this.size     = planeSize;
            this.cmplx    = cmplx;                         // Number of Rows/Columns in the Water Grid representation
            cmplxAdj      = (float)Math.Pow((cmplx / 64f), 1.4f) * 2;
            numFaces      = 2 * (int)Math.Pow(cmplx, 2);   // Each square is split into 2 triangles.
            numVertices   = (int)Math.Pow((cmplx + 1), 2); // Vertex grid is (Complexity+1) squared

            // Allocate and initialize space for calculated Normals
            vNorms = new Vector3[cmplx + 1, cmplx + 1];        // vertex Normals for each grid point
            fNorms = new Vector3[cmplx, cmplx, 2];             // face Normals for each triangle

            // Create mesh and submesh to represent the Water
            mesh    = (Mesh)MeshManager.Instance.CreateManual(meshName);
            subMesh = mesh.CreateSubMesh();
            subMesh.useSharedVertices = false;

            // Construct metadata to describe the buffers associated with the water submesh
            subMesh.vertexData             = new VertexData();
            subMesh.vertexData.vertexStart = 0;
            subMesh.vertexData.vertexCount = numVertices;

            // Define local variables to point to the VertexData Properties
            VertexDeclaration   vdecl = subMesh.vertexData.vertexDeclaration;            // najak: seems like metadata
            VertexBufferBinding vbind = subMesh.vertexData.vertexBufferBinding;          // najak: pointer to actual buffer

            //najak: Set metadata to describe the three vertex buffers that will be accessed.
            vdecl.AddElement(0, 0, VertexElementType.Float3, VertexElementSemantic.Position);
            vdecl.AddElement(1, 0, VertexElementType.Float3, VertexElementSemantic.Normal);
            vdecl.AddElement(2, 0, VertexElementType.Float2, VertexElementSemantic.TexCoords);

            // Prepare buffer for positions - todo: first attempt, slow
            // Create the Position Vertex Buffer and Bind it index 0 - Write Only
            posVBuf = HwBufMgr.CreateVertexBuffer(3 * 4, numVertices, BufferUsage.DynamicWriteOnly);
            vbind.SetBinding(0, posVBuf);

            // Prepare buffer for normals - write only
            // Create the Normals Buffer and Bind it to index 1 - Write only
            normVBuf = HwBufMgr.CreateVertexBuffer(3 * 4, numVertices, BufferUsage.DynamicWriteOnly);
            vbind.SetBinding(1, normVBuf);

            // Prepare Texture Coordinates buffer (static, written only once)
            // Creates a 2D buffer of 2D coordinates: (Complexity X Complexity), pairs.
            //    Each pair indicates the normalized coordinates of the texture to map to.
            //    (0,1.00), (0.02, 1.00), (0.04, 1.00), ... (1.00,1.00)
            //    (0,0.98), (0.02, 0.98), (0.04, 1.00), ... (1.00,0.98)
            //    ...
            //    (0,0.00), (0.02, 0.00), (0.04, 0.00), ... (1.00,0.00)
            // This construct is simple and is used to calculate the Texture map.
            // Todo: Write directly to the buffer, when Axiom supports this in safe manner
            float[,,] tcBufDat = new float[cmplx + 1, cmplx + 1, 2];
            for (int i = 0; i <= cmplx; i++)
            {
                // 2D column iterator for texture map
                for (int j = 0; j <= cmplx; j++)
                {
                    // 2D row iterator for texture map
                    // Define the normalized(0..1) X/Y-coordinates for this element of the 2D grid
                    tcBufDat[i, j, 0] = (float)i / cmplx;
                    tcBufDat[i, j, 1] = 1.0f - ((float)j / (cmplx));
                }
            }

            // Now Create the actual hardware buffer to contain the Texture Coordinate 2d map.
            //   and Bind it to buffer index 2
            tcVBuf = HwBufMgr.CreateVertexBuffer(2 * 4, numVertices, BufferUsage.StaticWriteOnly);
            tcVBuf.WriteData(0, tcVBuf.Size, tcBufDat, true);
            vbind.SetBinding(2, tcVBuf);

            // Create a Graphics Buffer on non-shared vertex indices (3 points for each triangle).
            //  Since the water grid consist of [Complexity x Complexity] squares, each square is
            //  split into 2 right triangles 45-90-45.  That is how the water mesh is constructed.
            //  Therefore the number of faces = 2 * Complexity * Complexity
            ushort[,,] idxBuf = new ushort[cmplx, cmplx, 6];
            for (int i = 0; i < cmplx; i++)                // iterate the rows
            {
                for (int j = 0; j < cmplx; j++)            // iterate the columns
                // Define 4 corners of each grid
                {
                    ushort p0 = (ushort)(i * (cmplx + 1) + j);                 // top left point on square
                    ushort p1 = (ushort)(i * (cmplx + 1) + j + 1);             // top right
                    ushort p2 = (ushort)((i + 1) * (cmplx + 1) + j);           // bottom left
                    ushort p3 = (ushort)((i + 1) * (cmplx + 1) + j + 1);       // bottom right

                    // Split Square Grid element into 2 adjacent triangles.
                    idxBuf[i, j, 0] = p2; idxBuf[i, j, 1] = p1; idxBuf[i, j, 2] = p0;               // top-left triangle
                    idxBuf[i, j, 3] = p2; idxBuf[i, j, 4] = p3; idxBuf[i, j, 5] = p1;               // bottom-right triangle
                }
            }
            // Copy Index Buffer to the Hardware Index Buffer
            HardwareIndexBuffer hdwrIdxBuf = HwBufMgr.CreateIndexBuffer(IndexType.Size16, 3 * numFaces, BufferUsage.StaticWriteOnly, true);

            hdwrIdxBuf.WriteData(0, numFaces * 3 * 2, idxBuf, true);

            // Set index buffer for this submesh
            subMesh.indexData.indexBuffer = hdwrIdxBuf;
            subMesh.indexData.indexStart  = 0;
            subMesh.indexData.indexCount  = 3 * numFaces;

            //Prepare Vertex Position Buffers (Note: make 3, since each frame is function of previous two)
            vBufs = new Vector3[3][, ];
            for (int b = 0; b < 3; b++)
            {
                vBufs[b] = new Vector3[cmplx + 1, cmplx + 1];
                for (int y = 0; y <= cmplx; y++)
                {
                    for (int x = 0; x <= cmplx; x++)
                    {
                        vBufs[b][y, x].x = (float)(x) / (float)(cmplx) * (float)size;
                        vBufs[b][y, x].y = 0;
                        vBufs[b][y, x].z = (float)(y) / (float)(cmplx) * (float)size;
                    }
                }
            }

            curBufNum = 0;
            vBuf      = vBufs[curBufNum];
            posVBuf.WriteData(0, posVBuf.Size, vBufs[0], true);

            AxisAlignedBox meshBounds = new AxisAlignedBox(new Vector3(0, 0, 0), new Vector3(size, 0, size));

            mesh.BoundingBox = meshBounds;              //	mesh->_setBounds(meshBounds); // najak: can't find _setBounds()

            mesh.Load();
            mesh.Touch();
        }         // end WaterMesh Constructor
        /// <summary>
        /// Create any device dependent resources here.
        /// This method will be called when the device is first
        /// initialized or recreated after being removed or reset.
        /// </summary>
        protected override void CreateDeviceDependentResources()
        {
            // Ensure that if already set the device resources
            // are correctly disposed of before recreating
            RemoveAndDispose(ref vertexBuffer);
            //RemoveAndDispose(ref indexBuffer);

            // Retrieve our SharpDX.Direct3D11.Device1 instance
            // Get a reference to the Device1 instance and immediate context
            var device  = DeviceManager.Direct3DDevice;
            var context = DeviceManager.Direct3DContext;

            ShaderFlags shaderFlags = ShaderFlags.None;

#if DEBUG
            shaderFlags = ShaderFlags.Debug | ShaderFlags.SkipOptimization;
#endif
            // Use our HLSL file include handler to resolve #include directives in the HLSL source
            var includeHandler = new HLSLFileIncludeHandler(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), "Shaders"));

            // Compile and create the vertex shader
            vertexShaderBytecode = ToDispose(ShaderBytecode.CompileFromFile(@"Shaders\SAQuad.hlsl", "VSMain", "vs_5_0", shaderFlags, EffectFlags.None, null, includeHandler));
            vertexShader         = ToDispose(new VertexShader(device, vertexShaderBytecode));

            // Compile and create the pixel shader
            pixelShaderBytecode = ToDispose(ShaderBytecode.CompileFromFile(@"Shaders\SAQuad.hlsl", "PSMain", "ps_5_0", shaderFlags, EffectFlags.None, null, includeHandler));
            pixelShader         = ToDispose(new PixelShader(device, pixelShaderBytecode));

            using (var bytecode = ToDispose(ShaderBytecode.CompileFromFile(@"Shaders\SAQuad.hlsl", "PSMainMultisample", "ps_5_0", shaderFlags, EffectFlags.None, null, includeHandler)))
            {
                pixelShaderMS = ToDispose(new PixelShader(device, pixelShaderBytecode));
            }

            // Layout from VertexShader input signature
            vertexLayout = ToDispose(new InputLayout(device,
                                                     vertexShaderBytecode.GetPart(ShaderBytecodePart.InputSignatureBlob),
                                                     //ShaderSignature.GetInputSignature(vertexShaderBytecode),
                                                     new[]
            {
                // "SV_Position" = vertex coordinate in object space
                new InputElement("SV_Position", 0, Format.R32G32B32_Float, 0, 0),
            }));

            linearSampleState = ToDispose(new SamplerState(device, new SamplerStateDescription
            {
                Filter             = Filter.MinMagMipLinear,
                AddressU           = TextureAddressMode.Wrap,
                AddressV           = TextureAddressMode.Wrap,
                AddressW           = TextureAddressMode.Wrap,
                ComparisonFunction = Comparison.Never,
                MinimumLod         = 0,
                MaximumLod         = float.MaxValue
            }));

            pointSamplerState = ToDispose(new SamplerState(device, new SamplerStateDescription
            {
                Filter             = Filter.MinMagMipPoint,
                AddressU           = TextureAddressMode.Wrap,
                AddressV           = TextureAddressMode.Wrap,
                AddressW           = TextureAddressMode.Wrap,
                ComparisonFunction = Comparison.Never,
                MinimumLod         = 0,
                MaximumLod         = float.MaxValue
            }));

            // Create vertex buffer
            vertexBuffer = ToDispose(Buffer.Create(device, BindFlags.VertexBuffer, new SimpleVertex[] {
                /*  Position: float x 3 */
                new SimpleVertex(-1.0f, -1.0f, 0.5f),
                new SimpleVertex(-1.0f, 1.0f, 0.5f),
                new SimpleVertex(1.0f, -1.0f, 0.5f),
                new SimpleVertex(1.0f, 1.0f, 0.5f),
            }));
            vertexBinding = new VertexBufferBinding(vertexBuffer, Utilities.SizeOf <SimpleVertex>(), 0);

            // Triangle strip:
            // v1   v3
            // |\   |
            // | \ B|
            // | A\ |
            // |   \|
            // v0   v2
        }
Esempio n. 16
0
        /// <summary>
        /// Transform a vertex buffer positions, normals, tangents and bitangents using the given matrix.
        /// </summary>
        /// <param name="vertexBufferBinding">The vertex container to transform</param>
        /// <param name="matrix">The matrix to use for the transform</param>
        public static void TransformBuffer(this VertexBufferBinding vertexBufferBinding, ref Matrix matrix)
        {
            var bufferData = vertexBufferBinding.Buffer.GetSerializationData().Content;

            vertexBufferBinding.TransformBuffer(bufferData, ref matrix);
        }
Esempio n. 17
0
        /// <summary>
        /// Transform a vertex buffer positions, normals, tangents and bitangents using the given matrix.
        /// Using as source/destination data the provided bufferData byte array.
        /// </summary>
        /// <param name="vertexBufferBinding">The vertex container to transform</param>
        /// <param name="bufferData">The source/destination data array to transform</param>
        /// <param name="matrix">The matrix to use for the transform</param>
        public static unsafe void TransformBuffer(this VertexBufferBinding vertexBufferBinding, byte[] bufferData, ref Matrix matrix)
        {
            // List of items that need to be transformed by the matrix
            var vertexElementsToTransform1 = vertexBufferBinding.Declaration.EnumerateWithOffsets()
                                             .Where(x => x.VertexElement.SemanticName == VertexElementUsage.Position &&
                                                    (x.VertexElement.Format == PixelFormat.R32G32B32A32_Float ||
                                                     x.VertexElement.Format == PixelFormat.R32G32B32_Float)).ToArray();

            // List of items that need to be transformed by the inverse transpose matrix
            var vertexElementsToTransform2 = vertexBufferBinding.Declaration.EnumerateWithOffsets()
                                             .Where(x => ((x.VertexElement.SemanticName == VertexElementUsage.Normal ||
                                                           x.VertexElement.SemanticName == VertexElementUsage.Tangent ||
                                                           x.VertexElement.SemanticName == VertexElementUsage.BiTangent)) &&
                                                    (x.VertexElement.Format == PixelFormat.R32G32B32_Float ||
                                                     x.VertexElement.Format == PixelFormat.R32G32B32A32_Float)).ToArray();

            // List the items that have handedness encoded in the W component
            var vertexElementsWithHandedness = vertexElementsToTransform2
                                               .Where(x => x.VertexElement.SemanticName == VertexElementUsage.Tangent &&
                                                      x.VertexElement.Format == PixelFormat.R32G32B32A32_Float).ToArray();

            // If needed, compute matrix inverse transpose
            Matrix inverseTransposeMatrix;

            if (vertexElementsToTransform2.Length > 0)
            {
                Matrix.Invert(ref matrix, out inverseTransposeMatrix);
                Matrix.Transpose(ref inverseTransposeMatrix, out inverseTransposeMatrix);
            }
            else
            {
                inverseTransposeMatrix = Matrix.Identity;
            }

            // Check if handedness is inverted
            bool flipHandedness = false;

            if (vertexElementsWithHandedness.Length > 0)
            {
                flipHandedness = Vector3.Dot(Vector3.Cross(matrix.Right, matrix.Forward), matrix.Up) < 0.0f;
            }

            // Transform buffer data
            var vertexStride = vertexBufferBinding.Declaration.VertexStride;
            var vertexCount  = vertexBufferBinding.Count;

            fixed(byte *bufferPointerStart = &bufferData[vertexBufferBinding.Offset])
            {
                var bufferPointer = bufferPointerStart;

                for (int i = 0; i < vertexCount; ++i)
                {
                    // Transform positions
                    foreach (var vertexElement in vertexElementsToTransform1)
                    {
                        var elementPointer = bufferPointer + vertexElement.Offset;
                        if (vertexElement.VertexElement.Format == PixelFormat.R32G32B32A32_Float)
                        {
                            Vector4.Transform(ref *(Vector4 *)elementPointer, ref matrix, out *(Vector4 *)elementPointer);
                        }
                        else
                        {
                            Vector3.TransformCoordinate(ref *(Vector3 *)elementPointer, ref matrix, out *(Vector3 *)elementPointer);
                        }
                    }

                    // Transform normals
                    foreach (var vertexElement in vertexElementsToTransform2)
                    {
                        var elementPointer = bufferPointer + vertexElement.Offset;
                        Vector3.TransformNormal(ref *(Vector3 *)elementPointer, ref inverseTransposeMatrix, out *(Vector3 *)elementPointer);
                    }

                    // Correct handedness
                    if (flipHandedness)
                    {
                        foreach (var vertexElement in vertexElementsWithHandedness)
                        {
                            var elementPointer    = bufferPointer + vertexElement.Offset;
                            var handednessPointer = (float *)elementPointer + 3;
                            *   handednessPointer = -*handednessPointer;
                        }
                    }

                    bufferPointer += vertexStride;
                }
            }
        }
Esempio n. 18
0
        public override void CreateDeviceResources()
        {
            base.CreateDeviceResources();

            Utilities.Dispose(ref _vertexShader);
            Utilities.Dispose(ref _pixelShader);
            Utilities.Dispose(ref _vertexLayout);
            Utilities.Dispose(ref _constantBuffer);

            var path = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;

            // Loads vertex shader bytecode
            var vertexShaderByteCode = NativeFile.ReadAllBytes(path + "\\MiniCube_VS.fxo");

            _vertexShader = new VertexShader(_device, vertexShaderByteCode);

            // Loads pixel shader bytecode
            _pixelShader = new PixelShader(_device, NativeFile.ReadAllBytes(path + "\\MiniCube_PS.fxo"));

            // Layout from VertexShader input signature
            _vertexLayout = new InputLayout(_device, vertexShaderByteCode, new[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
            });


            // Instantiate Vertex buffer from vertex data
            var vertices = SharpDX.Direct3D11.Buffer.Create(_device, BindFlags.VertexBuffer, new[]
            {
                new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),                       // Front
                new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),

                new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),                        // BACK
                new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),

                new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),                        // Top
                new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),

                new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),                       // Bottom
                new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),

                new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),                       // Left
                new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),

                new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),                        // Right
                new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
            });

            _vertexBufferBinding = new VertexBufferBinding(vertices, Utilities.SizeOf <Vector4>() * 2, 0);

            // Create Constant Buffer
            _constantBuffer = ToDispose(new SharpDX.Direct3D11.Buffer(_device, Utilities.SizeOf <Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            _clock = new Stopwatch();
            _clock.Start();

            _loadingComplete = true;
        }
Esempio n. 19
0
        /// <summary>
        /// Transform a vertex buffer positions, normals, tangents and bitangents using the given matrix.
        /// Using as source/destination data the provided bufferData byte array.
        /// </summary>
        /// <param name="vertexBufferBinding">The vertex container to transform</param>
        /// <param name="bufferData">The source/destination data array to transform</param>
        /// <param name="matrix">The matrix to use for the transform</param>
        public static unsafe void TransformBuffer(this VertexBufferBinding vertexBufferBinding, byte[] bufferData, ref Matrix matrix)
        {
            // List of items that need to be transformed by the matrix
            var vertexElementsToTransform1 = vertexBufferBinding.Declaration
                                             .EnumerateWithOffsets()
                                             .Where(x => x.VertexElement.SemanticName == VertexElementUsage.Position &&
                                                    (x.VertexElement.Format == PixelFormat.R32G32B32A32_Float ||
                                                     x.VertexElement.Format == PixelFormat.R32G32B32_Float))
                                             .ToArray();

            // List of items that need to be transformed by the inverse transpose matrix
            var vertexElementsToTransform2 = vertexBufferBinding.Declaration
                                             .EnumerateWithOffsets()
                                             .Where(x => (x.VertexElement.SemanticName == VertexElementUsage.Normal ||
                                                          x.VertexElement.SemanticName == VertexElementUsage.Tangent ||
                                                          x.VertexElement.SemanticName == VertexElementUsage.BiTangent) &&
                                                    x.VertexElement.Format == PixelFormat.R32G32B32_Float)
                                             .ToArray();

            // If needed, compute matrix inverse transpose
            Matrix inverseTransposeMatrix;

            if (vertexElementsToTransform2.Length > 0)
            {
                Matrix.Invert(ref matrix, out inverseTransposeMatrix);
                Matrix.Transpose(ref inverseTransposeMatrix, out inverseTransposeMatrix);
            }
            else
            {
                inverseTransposeMatrix = Matrix.Identity;
            }

            // Transform buffer data
            var vertexStride = vertexBufferBinding.Declaration.VertexStride;
            var vertexCount  = vertexBufferBinding.Count;

            fixed(byte *bufferPointerStart = &bufferData[vertexBufferBinding.Offset])
            {
                var bufferPointer = bufferPointerStart;

                for (int i = 0; i < vertexCount; ++i)
                {
                    // Transform positions
                    foreach (var vertexElement in vertexElementsToTransform1)
                    {
                        var elementPointer = bufferPointer + vertexElement.Offset;
                        if (vertexElement.VertexElement.Format == PixelFormat.R32G32B32A32_Float)
                        {
                            Vector4.Transform(ref *(Vector4 *)elementPointer, ref matrix, out *(Vector4 *)elementPointer);
                        }
                        else
                        {
                            Vector3.TransformCoordinate(ref *(Vector3 *)elementPointer, ref matrix, out *(Vector3 *)elementPointer);
                        }
                    }

                    // Transform normals
                    foreach (var vertexElement in vertexElementsToTransform2)
                    {
                        var elementPointer = bufferPointer + vertexElement.Offset;
                        Vector3.TransformNormal(ref *(Vector3 *)elementPointer, ref inverseTransposeMatrix, out *(Vector3 *)elementPointer);
                    }

                    bufferPointer += vertexStride;
                }
            }
        }
Esempio n. 20
0
        public static unsafe void CompactHalf(ref VertexBufferBinding vertexBufferBinding)
        {
            var vertexElementsWithOffsets = vertexBufferBinding.Declaration
                                            .EnumerateWithOffsets()
                                            .OrderBy(x => x.Offset)
                                            .ToArray();

            var vertexElements = new VertexElementConvertInfo[vertexElementsWithOffsets.Length];

            int currentOffset = 0;

            for (int index = 0; index < vertexElementsWithOffsets.Length; index++)
            {
                var vertexElementConvertInfo = new VertexElementConvertInfo();
                vertexElementConvertInfo.VertexElementWithOffset = vertexElementsWithOffsets[index];
                var vertexElement       = vertexElementsWithOffsets[index].VertexElement;
                var vertexElementFormat = vertexElementConvertInfo.VertexElementWithOffset.VertexElement.Format;

                // First iteration?
                if (index == 0)
                {
                    currentOffset = vertexElementsWithOffsets[index].Offset;
                }

                vertexElements[index] = vertexElementConvertInfo;
                vertexElementConvertInfo.OldFormat = vertexElementConvertInfo.VertexElementWithOffset.VertexElement.Format;

                int offsetShift = 0;

                switch (vertexElementFormat)
                {
                case PixelFormat.R32G32_Float:
                    vertexElementFormat = PixelFormat.R16G16_Float;

                    // Adjust next offset if current object has been resized
                    offsetShift = Utilities.SizeOf <Half2>() - Utilities.SizeOf <Vector2>();
                    break;

                case PixelFormat.R32G32B32_Float:
                    vertexElementFormat = PixelFormat.R16G16B16A16_Float;

                    // Adjust next offset if current object has been resized
                    offsetShift = Utilities.SizeOf <Half4>() - Utilities.SizeOf <Vector3>();
                    break;

                case PixelFormat.R32G32B32A32_Float:
                    vertexElementFormat = PixelFormat.R16G16B16A16_Float;

                    // Adjust next offset if current object has been resized
                    offsetShift = Utilities.SizeOf <Half4>() - Utilities.SizeOf <Vector4>();
                    break;
                }

                // Has format changed?
                vertexElementConvertInfo.NeedConversion = vertexElementFormat != vertexElementConvertInfo.VertexElementWithOffset.VertexElement.Format;

                // Create new vertex element with adjusted offset, and maybe new vertex format (if modified)
                vertexElementConvertInfo.VertexElementWithOffset.VertexElement
                    = new VertexElement(vertexElement.SemanticName, vertexElement.SemanticIndex, vertexElementFormat, currentOffset);

                // Increment next offset by the same difference as in original declaration
                if (index + 1 < vertexElementsWithOffsets.Length)
                {
                    currentOffset += vertexElementsWithOffsets[index + 1].Offset - vertexElementsWithOffsets[index].Offset;
                }

                currentOffset += offsetShift;

                vertexElements[index] = vertexElementConvertInfo;
            }

            var oldVertexStride = vertexBufferBinding.Declaration.VertexStride;

            var vertexDeclaration = new VertexDeclaration(vertexElements.Select(x => x.VertexElementWithOffset.VertexElement).ToArray());

            var newVertexStride = vertexDeclaration.VertexStride;
            var newBufferData   = new byte[vertexBufferBinding.Count * newVertexStride];

            fixed(byte *oldBuffer = &vertexBufferBinding.Buffer.GetSerializationData().Content[vertexBufferBinding.Offset])
            fixed(byte *newBuffer = &newBufferData[0])
            {
                var oldBufferVertexPtr = (IntPtr)oldBuffer;
                var newBufferVertexPtr = (IntPtr)newBuffer;

                for (int i = 0; i < vertexBufferBinding.Count; ++i)
                {
                    foreach (var element in vertexElements)
                    {
                        var oldBufferElementPtr = oldBufferVertexPtr + element.VertexElementWithOffset.Offset;
                        var newBufferElementPtr = newBufferVertexPtr + element.VertexElementWithOffset.VertexElement.AlignedByteOffset;

                        if (element.NeedConversion)
                        {
                            // Convert floatX => halfX
                            switch (element.OldFormat)
                            {
                            case PixelFormat.R32G32_Float:
                                *((Half2 *)newBufferElementPtr) = (Half2)(*((Vector2 *)oldBufferElementPtr));
                                break;

                            case PixelFormat.R32G32B32_Float:
                                // Put 1.0f in
                                *((Half4 *)newBufferElementPtr) = (Half4)(new Vector4(*((Vector3 *)oldBufferElementPtr), 1.0f));
                                break;

                            case PixelFormat.R32G32B32A32_Float:
                                *((Half4 *)newBufferElementPtr) = (Half4)(*((Vector4 *)oldBufferElementPtr));
                                break;
                            }
                        }
                        else
                        {
                            // Copy as is
                            Utilities.CopyMemory(newBufferElementPtr, oldBufferElementPtr, element.VertexElementWithOffset.Size);
                        }
                    }

                    oldBufferVertexPtr += oldVertexStride;
                    newBufferVertexPtr += newVertexStride;
                }
            }

            vertexBufferBinding = new VertexBufferBinding(new BufferData(BufferFlags.VertexBuffer, newBufferData).ToSerializableVersion(), vertexDeclaration, vertexBufferBinding.Count);
        }
Esempio n. 21
0
		public void RenderImposter(ImposterOverlayType overlay, VertexBufferBinding bindings, ShaderResourceView imposterTexture)
		{
			RenderImposter(overlay, bindings, imposterTexture, 1f);
		}
Esempio n. 22
0
 protected override void CreateVertexBinding()
 {
     buffer_        = ToDispose(Buffer.Create(DeviceManager.Direct3DDevice, BindFlags.VertexBuffer, vertices_.ToArray()));
     vertexBinding_ = new VertexBufferBinding(buffer_, Utilities.SizeOf <Vector4>(), 0);
     PrimitiveCount = vertices_.Count;
 }
Esempio n. 23
0
		public override void LoadResources()
		{
			if (m_Disposed == true)
			{
				m_Effect = m_Effect = new Effect(GameEnvironment.Device, Bytecode); // Effect.FromFile(GameEnvironment.Device, Helper.ResolvePath(m_ShaderLocation), "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null);
				m_Technique = m_Effect.GetTechniqueByName("Imposter");

				m_Pass_NoBlend = m_Technique.GetPassByName("NoBlend");
				m_Pass_OverlayAdd = m_Technique.GetPassByName("OverlayAdd");
				m_Pass_OverlaySubtract = m_Technique.GetPassByName("OverlaySubtract");
				m_Pass_OverlayInvert = m_Technique.GetPassByName("OverlayInvert");
				m_Pass_OverlayAlpha = m_Technique.GetPassByName("OverlayAlpha");

				m_Technique_BrightPass = m_Effect.GetTechniqueByName("Imposter_BrightPass");

				m_Pass_NoBlend_BrightPass = m_Technique_BrightPass.GetPassByName("NoBlend");
				m_Pass_OverlayAdd_BrightPass = m_Technique_BrightPass.GetPassByName("OverlayAdd");
				m_Pass_OverlaySubtract_BrightPass = m_Technique_BrightPass.GetPassByName("OverlaySubtract");
				m_Pass_OverlayAlpha_BrightPass = m_Technique_BrightPass.GetPassByName("OverlayAlpha");

				m_ImposterTextureResource = m_Effect.GetVariableByName("imposter").AsResource();

				m_BrightPassThreshold = m_Effect.GetVariableByName("brightPassThreshold").AsScalar();

				m_Layout = new InputLayout(GameEnvironment.Device, m_Pass_NoBlend.Description.Signature, new[] {
					new InputElement("POSITION", 0, Format.R32G32_Float, 0, 0),
					new InputElement("TEXCOORD", 0, Format.R32G32_Float, 8, 0)		
				});

				float minX = -1f, miny = -1f, maxX = 1f, maxY = 1f;

				using (DataStream stream = new DataStream(4 * Marshal.SizeOf(typeof(Vertex2D)), true, true))
				{
					stream.WriteRange(new Vertex2D[] {					
						new Vertex2D() { Position = new Vector2(maxX, miny), TextureCoords =  new Vector2(1.0f, 1.0f) }, 
						new Vertex2D() { Position = new Vector2(minX, miny), TextureCoords =  new Vector2(0.0f, 1.0f) }, 
						new Vertex2D() { Position = new Vector2(maxX, maxY), TextureCoords = new Vector2(1.0f, 0.0f) },  
						new Vertex2D() { Position = new Vector2(minX, maxY), TextureCoords =  new Vector2(0.0f, 0.0f) } 
					});
					stream.Position = 0;

					m_Vertices = new SlimDX.Direct3D11.Buffer(GameEnvironment.Device, stream, new BufferDescription()
					{
						BindFlags = BindFlags.VertexBuffer,
						CpuAccessFlags = CpuAccessFlags.None,
						OptionFlags = ResourceOptionFlags.None,
						SizeInBytes = 4 * Marshal.SizeOf(typeof(Vertex2D)),
						Usage = ResourceUsage.Default
					});
				}

				m_VerticesBindings = new VertexBufferBinding(m_Vertices, Marshal.SizeOf(typeof(Vertex2D)), 0);

				m_Disposed = false;
			}
		}
Esempio n. 24
0
        private void CreateVertexBinding()
        {
            RemoveAndDispose(ref indexBuffer);

            // Retrieve our SharpDX.Direct3D11.Device1 instance
            var device = this.DeviceManager.Direct3DDevice;
            var color  = Color.SaddleBrown;
            var data   = new Vertex[] {
                /*  Vertex Position    Color */
                new Vertex(new Vector3(-1f, 1f, -.5f), color),  // 0-Top-left
                new Vertex(new Vector3(1f, 1f, -.5f), color),   // 1-Top-right
                new Vertex(new Vector3(1f, -1f, -.5f), color),  // 2-Base-right
                new Vertex(new Vector3(-1f, -1f, -.5f), color), // 3-Base-left

                new Vertex(new Vector3(-1f, 1f, .5f), color),   // 4-Top-left
                new Vertex(new Vector3(1f, 1f, .5f), color),    // 5-Top-right
                new Vertex(new Vector3(1f, -1f, .5f), color),   // 6-Base-right
                new Vertex(new Vector3(-1f, -1f, .5f), color),  // 7-Base-left
            };

            // Create vertex buffer for cube
            buffer_        = ToDispose(Buffer.Create(device, BindFlags.VertexBuffer, data));
            vertexBinding_ = new VertexBufferBinding(buffer_, Utilities.SizeOf <Vertex>(), 0);

            // Front    Right    Top      Back     Left     Bottom
            // v0    v1 v1    v5 v1    v0 v5    v4 v4    v0 v3    v2
            // |-----|  |-----|  |-----|  |-----|  |-----|  |-----|
            // | \ A |  | \ A |  | \ A |  | \ A |  | \ A |  | \ A |
            // | B \ |  | B \ |  | B \ |  | B \ |  | B \ |  | B \ |
            // |-----|  |-----|  |-----|  |-----|  |-----|  |-----|
            // v3    v2 v2    v6 v5    v4 v6    v7 v7    v3 v7    v6
            indexBuffer = ToDispose(Buffer.Create(device, BindFlags.IndexBuffer, new ushort[] {
                0, 1, 2, // Front A
                0, 2, 3, // Front B
                1, 5, 6, // Right A
                1, 6, 2, // Right B
                1, 0, 4, // Top A
                1, 4, 5, // Top B
                5, 4, 7, // Back A
                5, 7, 6, // Back B
                4, 0, 3, // Left A
                4, 3, 7, // Left B
                3, 2, 6, // Bottom A
                3, 6, 7, // Bottom B
            }));
            //indexBuffer = ToDispose(Buffer.Create(device, BindFlags.IndexBuffer, new ushort[] {
            //    2, 1, 0, // Front A
            //    0, 3, 2, // Front B
            //    6, 5, 1, // Right A
            //    1, 2, 6, // Right B
            //    4, 0, 1, // Top A
            //    1, 5, 4, // Top B
            //    7, 4, 5, // Back A
            //    5, 6, 7, // Back B
            //    3, 0, 4, // Left A
            //    4, 7, 3, // Left B
            //    6, 2, 3, // Bottom A
            //    3, 7, 6, // Bottom B
            //}));
            PrimitiveCount = Utilities.SizeOf <Vertex>();

            var max    = data.Max().Position;
            var min    = data.Min().Position;
            var center = (max - min) * .5f;

            meshExtent = new Mesh.MeshExtent
            {
                Min    = min,
                Max    = max,
                Radius = 0.5f,
                Center = center
            };
        }
Esempio n. 25
0
 public void BuildBindings(VertexBuffer instanceBuffer)
 {
     Bindings    = new VertexBufferBinding[2];
     Bindings[0] = new VertexBufferBinding(VertedBuffer);
     Bindings[1] = new VertexBufferBinding(instanceBuffer, 0, 1);
 }
Esempio n. 26
0
            public SharedData(GraphicsDevice device)
            {
                var vertexBuffer = Buffer.Vertex.New(device, QuadsVertices).DisposeBy(this);
                
                // Register reload
                vertexBuffer.Reload = (graphicsResource) => ((Buffer)graphicsResource).Recreate(QuadsVertices);

                VertexBuffer = new VertexBufferBinding(vertexBuffer, VertexDeclaration, QuadsVertices.Length, VertexPositionNormalTexture.Size);
            }
Esempio n. 27
0
        public void Bind(DeviceContext ctx, InputLayout layout)
        {
            ctx.InputAssembler.InputLayout = layout;
            ctx.InputAssembler.PrimitiveTopology = this.Topology;

            if (this.props.AllowIndexBuffer)
            {
                ctx.InputAssembler.SetIndexBuffer(this.buffer.Buffer, SlimDX.DXGI.Format.R32_UInt, this.props.IndexBufferOffset);
            }
            else
            {
                ctx.InputAssembler.SetIndexBuffer(null, SlimDX.DXGI.Format.R32_UInt, 0);
            }

            VertexBufferBinding[] bindings = new VertexBufferBinding[this.props.VertexBufferOffsets.Length];
            for (int i = 0; i < this.props.VertexBufferOffsets.Length; i++)
            {
                VertexBufferBinding vb = new VertexBufferBinding(this.buffer.Buffer, this.props.VertexBufferStrides[i], this.props.VertexBufferOffsets[i]);
                bindings[i] = vb;
            }

            ctx.InputAssembler.SetVertexBuffers(0, bindings);
        }
Esempio n. 28
0
		public override void LoadResources()
		{
			if (m_Disposed == true)
			{ 
				#region Load Volume Effect

				m_Effect = m_Effect = new Effect(GameEnvironment.Device, Bytecode); // Effect.FromFile(GameEnvironment.Device, Helper.ResolvePath(m_ShaderLocation), "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null);

				RayStartTechnique = m_Effect.GetTechniqueByName("RayStart");
				RayStartOutsidePass = RayStartTechnique.GetPassByName("Outside");
				RayStartInsidePass = RayStartTechnique.GetPassByName("Inside");

				VolumeLayout = new InputLayout(GameEnvironment.Device, RayStartOutsidePass.Description.Signature, new[] {
				   new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
				   new InputElement("COLOR", 0, Format.R32G32B32_Float, 12, 0)			
				});


				RayDirectionTechnique = m_Effect.GetTechniqueByName("RayDirection");
				RayDirectionPass0 = RayDirectionTechnique.GetPassByIndex(0);
				//RayDirectionPass1 = RayDirectionTechnique.GetPassByIndex(1);

				BillboardTechnique = m_Effect.GetTechniqueByName("Final");
				BillboardPass0 = BillboardTechnique.GetPassByIndex(0);

				ImposterTechnique = m_Effect.GetTechniqueByName("Imposter");
				ImposterPass0 = ImposterTechnique.GetPassByIndex(0);

				BillboardLayout = new InputLayout(GameEnvironment.Device, BillboardPass0.Description.Signature, new[] {
					new InputElement("POSITION", 0, Format.R32G32_Float, 0, 0),
					new InputElement("TEXCOORD", 0, Format.R32G32_Float, 8, 0)		
				});

				rayStart_texture = m_Effect.GetVariableByName("rayStart_texture").AsResource();
				rayDir_texture = m_Effect.GetVariableByName("rayDir_texture").AsResource();
				imposter = m_Effect.GetVariableByName("imposter").AsResource();
				volume_texture = m_Effect.GetVariableByName("volume_texture").AsResource();
				LocationColor = m_Effect.GetVariableByName("locationColor").AsVector();

				#endregion	

				#region Billboard Verts

				float minX = -1f;
				float miny = -1f;
				float maxX = 1f;
				float maxY = 1f; 

				using (DataStream stream = new DataStream(4 * Marshal.SizeOf(typeof(Vertex2D)), true, true))
				{
					stream.WriteRange(new Vertex2D[] {					
						new Vertex2D() { Position = new Vector2(maxX, miny), TextureCoords =  new Vector2(1.0f, 1.0f) }, 
						new Vertex2D() { Position = new Vector2(minX, miny), TextureCoords =  new Vector2(0.0f, 1.0f) }, 
						new Vertex2D() { Position = new Vector2(maxX, maxY), TextureCoords = new Vector2(1.0f, 0.0f) },  
						new Vertex2D() { Position = new Vector2(minX, maxY), TextureCoords =  new Vector2(0.0f, 0.0f) } 
					});
					stream.Position = 0;

					BillboardVertices = new SlimDX.Direct3D11.Buffer(GameEnvironment.Device, stream, new BufferDescription()
					{
						BindFlags = BindFlags.VertexBuffer,
						CpuAccessFlags = CpuAccessFlags.None,
						OptionFlags = ResourceOptionFlags.None,
						SizeInBytes = 4 * Marshal.SizeOf(typeof(Vertex2D)),
						Usage = ResourceUsage.Default
					});
				}

				BillboardVerticesBindings = new VertexBufferBinding(BillboardVertices, Marshal.SizeOf(typeof(UIVertex)), 0);

				#endregion

				m_Disposed = false; 
			}	
		}
Esempio n. 29
0
        public static unsafe int[] GenerateIndexBufferAEN(IndexBufferBinding indexBuffer, VertexBufferBinding vertexBuffer)
        {
            // More info at http://developer.download.nvidia.com/whitepapers/2010/PN-AEN-Triangles-Whitepaper.pdf
            // This implementation might need some performance improvements

            var triangleCount = indexBuffer.Count / 3;
            var newIndices    = new int[triangleCount * 12];

            var positionMapping  = GenerateIndexMapping(vertexBuffer, "POSITION");
            var dominantEdges    = new Dictionary <EdgeKeyAEN, EdgeAEN>();
            var dominantVertices = new Dictionary <int, int>();
            var indexSize        = indexBuffer.Is32Bit? 4: 2;

            fixed(byte *indexBufferStart = &indexBuffer.Buffer.GetDataSafe()[indexBuffer.Offset])
            {
                var triangleIndices = stackalloc int[3];
                var positionIndices = stackalloc int[3];

                // Step 2: prepare initial data
                for (int i = 0; i < triangleCount; ++i)
                {
                    var oldIndices = indexBufferStart + i * 3 * indexSize;
                    if (indexSize == 2)
                    {
                        var oldIndicesShort = (short *)oldIndices;
                        triangleIndices[0] = oldIndicesShort[0];
                        triangleIndices[1] = oldIndicesShort[1];
                        triangleIndices[2] = oldIndicesShort[2];
                    }
                    else
                    {
                        var oldIndicesShort = (int *)oldIndices;
                        triangleIndices[0] = oldIndicesShort[0];
                        triangleIndices[1] = oldIndicesShort[1];
                        triangleIndices[2] = oldIndicesShort[2];
                    }

                    positionIndices[0] = positionMapping.Indices[triangleIndices[0]];
                    positionIndices[1] = positionMapping.Indices[triangleIndices[1]];
                    positionIndices[2] = positionMapping.Indices[triangleIndices[2]];

                    newIndices[i * 12 + 0]  = triangleIndices[0];
                    newIndices[i * 12 + 1]  = triangleIndices[1];
                    newIndices[i * 12 + 2]  = triangleIndices[2];
                    newIndices[i * 12 + 3]  = triangleIndices[0];
                    newIndices[i * 12 + 4]  = triangleIndices[1];
                    newIndices[i * 12 + 5]  = triangleIndices[1];
                    newIndices[i * 12 + 6]  = triangleIndices[2];
                    newIndices[i * 12 + 7]  = triangleIndices[2];
                    newIndices[i * 12 + 8]  = triangleIndices[0];
                    newIndices[i * 12 + 9]  = triangleIndices[0];
                    newIndices[i * 12 + 10] = triangleIndices[1];
                    newIndices[i * 12 + 11] = triangleIndices[2];

                    // Step 2b/2c: Build dominant vertex/edge list
                    for (int j = 0; j < 3; ++j)
                    {
                        dominantVertices[positionIndices[j]] = triangleIndices[j];

                        var edge = new EdgeAEN(
                            triangleIndices[((j + 0) % 3)],
                            triangleIndices[((j + 1) % 3)],
                            positionIndices[((j + 0) % 3)],
                            positionIndices[((j + 1) % 3)]);

                        dominantEdges[new EdgeKeyAEN(edge)] = edge;

                        edge = edge.Reverse();
                        dominantEdges[new EdgeKeyAEN(edge)] = edge;
                    }
                }

                // Step3: Find dominant vertex/edge
                for (int i = 0; i < triangleCount; ++i)
                {
                    var oldIndices = indexBufferStart + i * 3 * indexSize;
                    if (indexSize == 2)
                    {
                        var oldIndicesShort = (short *)oldIndices;
                        triangleIndices[0] = oldIndicesShort[0];
                        triangleIndices[1] = oldIndicesShort[1];
                        triangleIndices[2] = oldIndicesShort[2];
                    }
                    else
                    {
                        var oldIndicesShort = (int *)oldIndices;
                        triangleIndices[0] = oldIndicesShort[0];
                        triangleIndices[1] = oldIndicesShort[1];
                        triangleIndices[2] = oldIndicesShort[2];
                    }

                    positionIndices[0] = positionMapping.Indices[triangleIndices[0]];
                    positionIndices[1] = positionMapping.Indices[triangleIndices[1]];
                    positionIndices[2] = positionMapping.Indices[triangleIndices[2]];

                    for (int j = 0; j < 3; ++j)
                    {
                        // Dominant edge
                        int vertexKey;
                        if (dominantVertices.TryGetValue(positionIndices[j], out vertexKey))
                        {
                            newIndices[i * 12 + 9 + j] = vertexKey;
                        }

                        // Dominant vertex
                        EdgeAEN edge;
                        var     edgeKey = new EdgeKeyAEN(positionIndices[((j + 0) % 3)], positionIndices[((j + 1) % 3)]);
                        if (dominantEdges.TryGetValue(edgeKey, out edge))
                        {
                            newIndices[i * 12 + 3 + j * 2 + 0] = edge.Index0;
                            newIndices[i * 12 + 3 + j * 2 + 1] = edge.Index1;
                        }
                    }
                }
            }

            return(newIndices);
        }
Esempio n. 30
0
            // encapsulates d3d resources for a camera
            public CameraDeviceResource(SharpDX.Direct3D11.Device device, ProjectorCameraEnsemble.Camera camera, Object renderLock, string directory)
            {
                this.device     = device;
                this.camera     = camera;
                this.renderLock = renderLock;

                // Kinect depth image
                var depthImageTextureDesc = new Texture2DDescription()
                {
                    Width             = Kinect2Calibration.depthImageWidth,
                    Height            = Kinect2Calibration.depthImageHeight,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    Format            = SharpDX.DXGI.Format.R16_UInt,
                    SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                    Usage             = ResourceUsage.Dynamic,
                    BindFlags         = BindFlags.ShaderResource,
                    CpuAccessFlags    = CpuAccessFlags.Write,
                };

                depthImageTexture   = new Texture2D(device, depthImageTextureDesc);
                depthImageTextureRV = new ShaderResourceView(device, depthImageTexture);

                var floatDepthImageTextureDesc = new Texture2DDescription()
                {
                    Width             = Kinect2Calibration.depthImageWidth,
                    Height            = Kinect2Calibration.depthImageHeight,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    Format            = SharpDX.DXGI.Format.R32_Float,
                    SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                    Usage             = ResourceUsage.Default,
                    BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                    CpuAccessFlags    = CpuAccessFlags.None,
                };

                floatDepthImageTexture          = new Texture2D(device, floatDepthImageTextureDesc);
                floatDepthImageRV               = new ShaderResourceView(device, floatDepthImageTexture);
                floatDepthImageRenderTargetView = new RenderTargetView(device, floatDepthImageTexture);

                floatDepthImageTexture2          = new Texture2D(device, floatDepthImageTextureDesc);
                floatDepthImageRV2               = new ShaderResourceView(device, floatDepthImageTexture2);
                floatDepthImageRenderTargetView2 = new RenderTargetView(device, floatDepthImageTexture2);

                // Kinect color image
                var colorImageStagingTextureDesc = new Texture2DDescription()
                {
                    Width             = Kinect2Calibration.colorImageWidth,
                    Height            = Kinect2Calibration.colorImageHeight,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                    SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                    Usage             = ResourceUsage.Dynamic,
                    BindFlags         = BindFlags.ShaderResource,
                    CpuAccessFlags    = CpuAccessFlags.Write
                };

                colorImageStagingTexture = new Texture2D(device, colorImageStagingTextureDesc);

                var colorImageTextureDesc = new Texture2DDescription()
                {
                    Width             = Kinect2Calibration.colorImageWidth,
                    Height            = Kinect2Calibration.colorImageHeight,
                    MipLevels         = 0,
                    ArraySize         = 1,
                    Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                    SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                    Usage             = ResourceUsage.Default,
                    BindFlags         = BindFlags.ShaderResource | BindFlags.RenderTarget,
                    CpuAccessFlags    = CpuAccessFlags.None,
                    OptionFlags       = ResourceOptionFlags.GenerateMipMaps
                };

                colorImageTexture   = new Texture2D(device, colorImageTextureDesc);
                colorImageTextureRV = new ShaderResourceView(device, colorImageTexture);

                // vertex buffer
                var table       = camera.calibration.ComputeDepthFrameToCameraSpaceTable();
                int numVertices = 6 * (Kinect2Calibration.depthImageWidth - 1) * (Kinect2Calibration.depthImageHeight - 1);
                var vertices    = new VertexPosition[numVertices];

                Int3[] quadOffsets = new Int3[]
                {
                    new Int3(0, 0, 0),
                    new Int3(1, 0, 0),
                    new Int3(0, 1, 0),
                    new Int3(1, 0, 0),
                    new Int3(1, 1, 0),
                    new Int3(0, 1, 0),
                };

                int vertexIndex = 0;

                for (int y = 0; y < Kinect2Calibration.depthImageHeight - 1; y++)
                {
                    for (int x = 0; x < Kinect2Calibration.depthImageWidth - 1; x++)
                    {
                        for (int i = 0; i < 6; i++)
                        {
                            int vertexX = x + quadOffsets[i].X;
                            int vertexY = y + quadOffsets[i].Y;

                            var point = table[Kinect2Calibration.depthImageWidth * vertexY + vertexX];

                            var vertex = new VertexPosition();
                            vertex.position         = new SharpDX.Vector4(point.X, point.Y, vertexX, vertexY);
                            vertices[vertexIndex++] = vertex;
                        }
                    }
                }

                var stream = new DataStream(numVertices * VertexPosition.SizeInBytes, true, true);

                stream.WriteRange(vertices);
                stream.Position = 0;

                var vertexBufferDesc = new BufferDescription()
                {
                    BindFlags      = BindFlags.VertexBuffer,
                    CpuAccessFlags = CpuAccessFlags.None,
                    Usage          = ResourceUsage.Default,
                    SizeInBytes    = numVertices * VertexPosition.SizeInBytes,
                };

                vertexBuffer = new SharpDX.Direct3D11.Buffer(device, stream, vertexBufferDesc);

                vertexBufferBinding = new VertexBufferBinding(vertexBuffer, VertexPosition.SizeInBytes, 0);

                stream.Dispose();

                var colorImage = new RoomAliveToolkit.ARGBImage(Kinect2Calibration.colorImageWidth, Kinect2Calibration.colorImageHeight);

                ProjectorCameraEnsemble.LoadFromTiff(imagingFactory, colorImage, directory + "/camera" + camera.name + "/color.tiff");

                var depthImage = new RoomAliveToolkit.ShortImage(Kinect2Calibration.depthImageWidth, Kinect2Calibration.depthImageHeight);

                ProjectorCameraEnsemble.LoadFromTiff(imagingFactory, depthImage, directory + "/camera" + camera.name + "/mean.tiff");

                lock (renderLock) // necessary?
                {
                    UpdateColorImage(device.ImmediateContext, colorImage.DataIntPtr);
                    UpdateDepthImage(device.ImmediateContext, depthImage.DataIntPtr);
                }

                colorImage.Dispose();
                depthImage.Dispose();
            }
Esempio n. 31
0
		public void RenderVolumeTexture(Viewport VolumeViewport, Vector3 CameraPosition, 
										BoundingBox VolumeBounds,  VertexBufferBinding VolumeBoundsVertsBindings, Buffer VolumeBoundsIndices,
										ShaderResourceView VolumeTexture, 
										RenderTargetView RayStartView, ShaderResourceView RayStartResourceView, 
										RenderTargetView RayDirectionView, ShaderResourceView RayDirectionResourceView, 
										RenderTargetView ImposterView, 
										Buffer InsideVertices, VertexBufferBinding InsideVerticesBindings)
		{
			
			/*device.Rasterizer.State = SlimDX.Direct3D11.RasterizerState.FromDescription(device, new RasterizerStateDescription()
			{
				CullMode = CullMode.Back,
				DepthBias = 0,
				DepthBiasClamp = 0,
				FillMode = FillMode.Solid,
				IsAntialiasedLineEnabled = false,
				IsDepthClipEnabled = false,
				IsFrontCounterclockwise = true,
				IsMultisampleEnabled = false,
				IsScissorEnabled = false,
				SlopeScaledDepthBias = 0
			}); */

			//public ShaderResourceView ImposterResourceView;
			//public ShaderResourceView RayDirectionResourceView;
			//public ShaderResourceView RayStartResourceView;			

			rayStart_texture.SetResource(RayStartResourceView);
			rayDir_texture.SetResource(RayDirectionResourceView);			
			volume_texture.SetResource(VolumeTexture);
			//LocationColor.SetResource();

			Device device = GameEnvironment.Device;
			SlimDX.Direct3D11.DeviceContext context = device.ImmediateContext; 

			RenderTargetView[] backupTargets = context.OutputMerger.GetRenderTargets(1);
			Viewport[] backupViewPorts = context.Rasterizer.GetViewports();

			context.Rasterizer.SetViewports(VolumeViewport);
			context.InputAssembler.InputLayout = VolumeLayout;

			context.OutputMerger.SetTargets(RayStartView);
			context.InputAssembler.SetVertexBuffers(0, VolumeBoundsVertsBindings);
			context.InputAssembler.SetIndexBuffer(VolumeBoundsIndices, Format.R32_UInt, 0);

			if (BoundingBox.Contains(VolumeBounds, CameraPosition) == ContainmentType.Contains)
			{
				float x, y, z;
				//float size = 1f / ((float)ExplicitMapObjects.Volume.Size * 16); 
				//float depth = 1f / ((float)ExplicitMapObjects.Volume.Depth * 16 * 8);

				//Vector3 vec = new Vector3(size * (Camera.Center.X / Camera.MapScale), size * (Camera.Center.Y / Camera.MapScale), depth * (Camera.Center.Z / Camera.MapScale)); 

				x = (1f / VolumeBounds.Maximum.X) * CameraPosition.X;
				y = (1f / VolumeBounds.Maximum.Y) * CameraPosition.Y;
				z = (1f / VolumeBounds.Maximum.Z) * CameraPosition.Z; 

				//device.ClearRenderTargetView(RayStartView, new Color4(1, vec.X, vec.Y, vec.Z));*/

				DataStream stream = context.MapSubresource(InsideVertices, MapMode.WriteDiscard, SlimDX.Direct3D11.MapFlags.None).Data;

				stream.WriteRange(new VolumeVertex[] {					
					new VolumeVertex() { Position = new Vector3( 1f, -1f, 0), Color = new Vector3(x, y, z) }, 
					new VolumeVertex() { Position = new Vector3(-1f, -1f, 0), Color = new Vector3(x, y, z) }, 
					new VolumeVertex() { Position = new Vector3( 1f,  1f, 0), Color = new Vector3(x, y, z) },  
					new VolumeVertex() { Position = new Vector3(-1f,  1f, 0), Color = new Vector3(x, y, z) } 
				});

				context.UnmapSubresource(InsideVertices, 0);

				context.InputAssembler.SetVertexBuffers(0, InsideVerticesBindings);
				context.ClearRenderTargetView(RayStartView, Color.Black);
				context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;

				RayStartInsidePass.Apply(context);
				context.Draw(4, 0);

				context.InputAssembler.SetVertexBuffers(0, VolumeBoundsVertsBindings);
				context.InputAssembler.SetIndexBuffer(VolumeBoundsIndices, Format.R32_UInt, 0);
				context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
			}
			else
			{
				context.InputAssembler.SetVertexBuffers(0, VolumeBoundsVertsBindings);
				context.InputAssembler.SetIndexBuffer(VolumeBoundsIndices, Format.R32_UInt, 0);
				context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

				context.ClearRenderTargetView(RayStartView, Color.Black);

				RayStartOutsidePass.Apply(context);
				context.DrawIndexed(6 * 6, 0, 0);
			}

			context.OutputMerger.SetTargets(RayDirectionView);
			context.ClearRenderTargetView(RayDirectionView, Color.Black);

			RayDirectionPass0.Apply(context);
			context.DrawIndexed(6 * 6, 0, 0);

			context.OutputMerger.SetTargets(ImposterView);
			context.ClearRenderTargetView(ImposterView, Color.Black);

			context.InputAssembler.InputLayout = BillboardLayout;
			context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;
			context.InputAssembler.SetVertexBuffers(0, BillboardVerticesBindings);
			context.InputAssembler.SetIndexBuffer(null, Format.Unknown, 0);

			BillboardPass0.Apply(context);
			context.Draw(4, 0);

			context.OutputMerger.SetTargets(backupTargets);
			context.Rasterizer.SetViewports(backupViewPorts);
		}
Esempio n. 32
0
        public void Init(TerrainOptions options)
        {
            this.options = options;

            this.numMipMaps = options.maxMipmap;
            this.size       = options.size;

            this.terrain             = new VertexData();
            this.terrain.vertexStart = 0;

            this.terrain.vertexCount = options.size * options.size;

            VertexDeclaration   decl    = this.terrain.vertexDeclaration;
            VertexBufferBinding binding = this.terrain.vertexBufferBinding;

            int offset = 0;

            // Position/Normal
            decl.AddElement(POSITION, 0, VertexElementType.Float3, VertexElementSemantic.Position);
            decl.AddElement(NORMAL, 0, VertexElementType.Float3, VertexElementSemantic.Normal);

            // TexCoords
            decl.AddElement(TEXCOORD, offset, VertexElementType.Float2, VertexElementSemantic.TexCoords, 0);
            offset += VertexElement.GetTypeSize(VertexElementType.Float2);
            decl.AddElement(TEXCOORD, offset, VertexElementType.Float2, VertexElementSemantic.TexCoords, 1);
            offset += VertexElement.GetTypeSize(VertexElementType.Float2);
            // TODO: Color

            HardwareVertexBuffer buffer = HardwareBufferManager.Instance.CreateVertexBuffer(decl.Clone(POSITION),
                                                                                            this.terrain.vertexCount,
                                                                                            BufferUsage.StaticWriteOnly, true);

            binding.SetBinding(POSITION, buffer);

            buffer = HardwareBufferManager.Instance.CreateVertexBuffer(decl.Clone(NORMAL), this.terrain.vertexCount,
                                                                       BufferUsage.StaticWriteOnly, true);

            binding.SetBinding(NORMAL, buffer);

            buffer = HardwareBufferManager.Instance.CreateVertexBuffer(decl.Clone(TEXCOORD), this.terrain.vertexCount,
                                                                       BufferUsage.StaticWriteOnly, true);

            binding.SetBinding(TEXCOORD, buffer);

            this.minLevelDistSqr = new float[this.numMipMaps];

            int endx = options.startx + options.size;
            int endz = options.startz + options.size;

            // TODO: name buffers different so we can unlock
            HardwareVertexBuffer posBuffer = binding.GetBuffer(POSITION);
            var pos = posBuffer.Lock(BufferLocking.Discard);

            HardwareVertexBuffer texBuffer = binding.GetBuffer(TEXCOORD);
            var tex = texBuffer.Lock(BufferLocking.Discard);

            float min = 99999999, max = 0;

#if !AXIOM_SAFE_ONLY
            unsafe
#endif
            {
                var posPtr = pos.ToFloatPointer();
                var texPtr = tex.ToFloatPointer();

                int posCount = 0;
                int texCount = 0;

                for (int j = options.startz; j < endz; j++)
                {
                    for (int i = options.startx; i < endx; i++)
                    {
                        float height = options.GetWorldHeight(i, j) * options.scaley;

                        posPtr[posCount++] = i * options.scalex;
                        posPtr[posCount++] = height;
                        posPtr[posCount++] = j * options.scalez;

                        texPtr[texCount++] = (float)i / options.worldSize;
                        texPtr[texCount++] = (float)j / options.worldSize;

                        texPtr[texCount++] = ((float)i / options.size) * options.detailTile;
                        texPtr[texCount++] = ((float)j / options.size) * options.detailTile;

                        if (height < min)
                        {
                            min = height;
                        }

                        if (height > max)
                        {
                            max = height;
                        }
                    } // for i
                }     // for j
            }         // unsafe

            // unlock the buffers
            posBuffer.Unlock();
            texBuffer.Unlock();

            this.box.SetExtents(new Vector3(options.startx * options.scalex, min, options.startz * options.scalez),
                                new Vector3((endx - 1) * options.scalex, max, (endz - 1) * options.scalez));

            this.center = new Vector3((options.startx * options.scalex + endx - 1) / 2, (min + max) / 2,
                                      (options.startz * options.scalez + endz - 1) / 2);

            float C = CalculateCFactor();

            CalculateMinLevelDist2(C);
        }
Esempio n. 33
0
        private void Init(string name, float gridSize, int numXVerts, float[][] heights, Vector3 color)
        {
            gridColor = color;

            ///////////////////////////////////
            // Construct grid
            ///////////////////////////////////
            float vertSpacing = gridSize / numXVerts;

            //Generate vertices
            for (int x = 0; x < numXVerts + 1; x++)
            {
                for (int z = 0; z < numXVerts + 1; z++)
                {
                    GridVertex v = new GridVertex(new Vector3(x * vertSpacing, 0f, z * vertSpacing), gridColor);
                    vertices.Add(v);
                    Console.WriteLine(x * vertSpacing + " | " + z * vertSpacing);
                }
            }
            //Generate indices
            for (int j = 0; j < numXVerts; ++j)
            {
                for (int i = 0; i < numXVerts; ++i)
                {
                    int row1 = j * (numXVerts + 1);
                    int row2 = (j + 1) * (numXVerts + 1);

                    // triangle 1
                    indices.Add((uint)(row1 + i));
                    indices.Add((uint)(row1 + i + 1));
                    indices.Add((uint)(row2 + i + 1));
                    // triangle 2
                    indices.Add((uint)(row1 + i));
                    indices.Add((uint)(row2 + i + 1));
                    indices.Add((uint)(row2 + i));
                }
            }

            ///////////////////////////////////
            // Prep D3D stuff
            ///////////////////////////////////
            DataStream vstream = new DataStream(vertices.ToArray(), true, false); vstream.Position = 0;
            DataStream istream = new DataStream(indices.ToArray(), true, false); istream.Position = 0;


            var vbd = new BufferDescription(
                Marshal.SizeOf(new GridVertex()) * vertices.Count,
                ResourceUsage.Dynamic,
                BindFlags.VertexBuffer,
                CpuAccessFlags.Write,
                ResourceOptionFlags.None, 0);

            vb    = new Buffer(Renderer.viewport.Device, vstream, vbd);
            vbind = new VertexBufferBinding(vb, Marshal.SizeOf(new GridVertex()), 0);

            //indices
            var ibd = new BufferDescription(
                sizeof(uint) * indices.Count,
                ResourceUsage.Dynamic,
                BindFlags.IndexBuffer,
                CpuAccessFlags.Write,
                ResourceOptionFlags.None, 0);

            ib = new Buffer(Renderer.viewport.Device, istream, ibd);

            indexCount = indices.Count;
        }
Esempio n. 34
0
        public void Initialize(DeviceManager deviceManager)
        {
            _deviceManager = deviceManager;


            // Remove previous buffer
            //SafeDispose(ref constantBuffer);


            // Setup local variables
            var d3dDevice  = deviceManager.DeviceDirect3D;
            var d3dContext = deviceManager.ContextDirect3D;


            var path = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;


            // Loads vertex shader bytecode
            var vertexShaderByteCode = NativeFile.ReadAllBytes(path + "\\Assets\\MiniCubeTexture_VS.fxo");

            vertexShader = new VertexShader(d3dDevice, vertexShaderByteCode);


            // Loads pixel shader bytecode
            pixelShader = new PixelShader(d3dDevice, NativeFile.ReadAllBytes(path + "\\Assets\\MiniCubeTexture_PS.fxo"));


            // Layout from VertexShader input signature
            layout = new InputLayout(d3dDevice, vertexShaderByteCode, new[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32_Float, 16, 0)
            });


            // Instantiate Vertex buffer from vertex data
            var vertices = SharpDX.Direct3D11.Buffer.Create(d3dDevice, BindFlags.VertexBuffer, new[]
            {
                // 3D coordinates              UV Texture coordinates
                -1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 1.0f,                           // Front
                -1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 0.0f,
                1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 0.0f,
                -1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 1.0f,
                1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 0.0f,
                1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f,


                -1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 1.0f,                            // BACK
                1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
                -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
                -1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
                1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
                1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,


                -1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f,                            // Top
                -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
                1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
                -1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f,
                1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
                1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f,


                -1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 1.0f,                           // Bottom
                1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
                -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
                -1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 1.0f,
                1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 0.0f,
                1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f,


                -1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 1.0f,                           // Left
                -1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
                -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
                -1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 1.0f,
                -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
                -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f,


                1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 1.0f,                            // Right
                1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
                1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
                1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 1.0f,
                1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 0.0f,
                1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
            });


            //vertexBufferBinding = new VertexBufferBinding(vertices, Utilities.SizeOf<Vector4>() * 2, 0);
            vertexBufferBinding = new VertexBufferBinding(vertices, sizeof(float) * 6, 0);


            // Create Constant Buffer
            constantBuffer = ToDispose(new SharpDX.Direct3D11.Buffer(d3dDevice, Utilities.SizeOf <Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));


            // Load texture and create sampler
            using (var bitmap = TextureLoader.LoadBitmap(deviceManager.WICFactory, "Assets\\dot.jpg"))
                using (var texture2D = TextureLoader.CreateTexture2DFromBitmap(d3dDevice, bitmap))
                    textureView = new ShaderResourceView(d3dDevice, texture2D);


            sampler = new SamplerState(d3dDevice, new SamplerStateDescription()
            {
                Filter             = Filter.MinMagMipLinear,
                AddressU           = TextureAddressMode.Wrap,
                AddressV           = TextureAddressMode.Wrap,
                AddressW           = TextureAddressMode.Wrap,
                BorderColor        = Color.Black,
                ComparisonFunction = Comparison.Never,
                MaximumAnisotropy  = 16,
                MipLodBias         = 0,
                MinimumLod         = 0,
                MaximumLod         = 16,
            });



            clock = new Stopwatch();
            clock.Start();
        }
Esempio n. 35
0
 public VegetationMiniPartCollection(ICollection<VegetationMiniPart> ps)
 {
     ManagedWorld.NodeLibrary.RemoveNode(this);
     gps = ps.ToArray<VegetationMiniPart>();
     p = gps[0].sPath;
     D = gps[0].mBody.Device;
     //List<Vector3> ms = new List<Vector3>();
     //List<Quaternion> qs = new List<Quaternion>();
     List<byte> bs = new List<byte>();
     int stride = 3 * 4 + 4 * 4;//float3 + float4
     BoundingBox abs = new BoundingBox(new Vector3(1E10f), new Vector3(-1E10f));
     foreach (VegetationMiniPart gp in gps)
     {
         abs = abs.Extend(gp.bb);
         //ms.Add(gp.vPosition);
         //qs.Add(gp.qOrientation);
         bs.AddRange(gp.vPosition.GetBytes());
         bs.AddRange(gp.qOrientation.GetBytes());
     }
     this.BoundingBox = abs;
     DataStream ds = new DataStream(bs.ToArray(), true, true);
     sBuffer = new ShaderResourceBuffer(ds, SlimDX.Direct3D11.BindFlags.VertexBuffer, SlimDX.Direct3D11.CpuAccessFlags.None, SlimDX.Direct3D11.ResourceUsage.Default, SlimDX.Direct3D11.ResourceOptionFlags.None, stride, D);
     ds.Dispose();
     vb = new SlimDX.Direct3D11.VertexBufferBinding(sBuffer.Buffer, sBuffer.Description.StructureByteStride, 0);
     qTST = new GraphicNode("", null, D); qTST.BoundingBox = this.BoundingBox; qTST.ParentNode = this;
 }
Esempio n. 36
0
        public void RenderDrawData(ImDrawDataPtr drawData)
        {
            // Avoid rendering when minimized
            if (drawData.DisplaySize.X <= 0 || drawData.DisplaySize.Y <= 0)
            {
                return;
            }

            if (!drawData.Valid || drawData.CmdListsCount == 0)
            {
                return;
            }

            // drawData.ScaleClipRects(ImGui.GetIO().DisplayFramebufferScale);

            // Create and grow vertex/index buffers if needed
            if (_vertexBuffer == null || _vertexBufferSize < drawData.TotalVtxCount)
            {
                _vertexBuffer?.Dispose();
                _vertexBufferSize = drawData.TotalVtxCount + 5000;

                _vertexBuffer = new Buffer(_device, new BufferDescription
                {
                    Usage          = ResourceUsage.Dynamic,
                    SizeInBytes    = Unsafe.SizeOf <ImDrawVert>() * _vertexBufferSize,
                    BindFlags      = BindFlags.VertexBuffer,
                    CpuAccessFlags = CpuAccessFlags.Write,
                    OptionFlags    = ResourceOptionFlags.None
                });

                // (Re)make this here rather than every frame
                _vertexBinding = new VertexBufferBinding
                {
                    Buffer = _vertexBuffer,
                    Stride = Unsafe.SizeOf <ImDrawVert>(),
                    Offset = 0
                };
            }

            if (_indexBuffer == null || _indexBufferSize < drawData.TotalIdxCount)
            {
                _indexBuffer?.Dispose();
                _indexBufferSize = drawData.TotalIdxCount + 10000;

                _indexBuffer = new Buffer(_device, new BufferDescription
                {
                    Usage          = ResourceUsage.Dynamic,
                    SizeInBytes    = sizeof(ushort) * _indexBufferSize, // ImGui.NET doesn't provide an ImDrawIdx, but their sample uses ushort
                    BindFlags      = BindFlags.IndexBuffer,
                    CpuAccessFlags = CpuAccessFlags.Write
                });
            }

            // Upload vertex/index data into a single contiguous GPU buffer
            int vertexOffset = 0, indexOffset = 0;
            var vertexData = _deviceContext.MapSubresource(_vertexBuffer, 0, MapMode.WriteDiscard, MapFlags.None).DataPointer;
            var indexData  = _deviceContext.MapSubresource(_indexBuffer, 0, MapMode.WriteDiscard, MapFlags.None).DataPointer;

            for (int n = 0; n < drawData.CmdListsCount; n++)
            {
                var cmdList = drawData.CmdListsRange[n];
                unsafe
                {
                    System.Buffer.MemoryCopy(cmdList.VtxBuffer.Data.ToPointer(),
                                             (ImDrawVert *)vertexData + vertexOffset,
                                             Unsafe.SizeOf <ImDrawVert>() * _vertexBufferSize,
                                             Unsafe.SizeOf <ImDrawVert>() * cmdList.VtxBuffer.Size);

                    System.Buffer.MemoryCopy(cmdList.IdxBuffer.Data.ToPointer(),
                                             (ushort *)indexData + indexOffset,
                                             sizeof(ushort) * _indexBufferSize,
                                             sizeof(ushort) * cmdList.IdxBuffer.Size);

                    vertexOffset += cmdList.VtxBuffer.Size;
                    indexOffset  += cmdList.IdxBuffer.Size;
                }
            }
            _deviceContext.UnmapSubresource(_vertexBuffer, 0);
            _deviceContext.UnmapSubresource(_indexBuffer, 0);

            // Setup orthographic projection matrix into our constant buffer
            // Our visible imgui space lies from drawData.DisplayPos (top left) to drawData.DisplayPos+drawData.DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps.
            var L   = drawData.DisplayPos.X;
            var R   = drawData.DisplayPos.X + drawData.DisplaySize.X;
            var T   = drawData.DisplayPos.Y;
            var B   = drawData.DisplayPos.Y + drawData.DisplaySize.Y;
            var mvp = new float[]
            {
                2f / (R - L), 0, 0, 0,
                0, 2f / (T - B), 0, 0,
                0, 0, 0.5f, 0,
                (R + L) / (L - R), (T + B) / (B - T), 0.5f, 1f
            };

            var constantBuffer = _deviceContext.MapSubresource(_vertexConstantBuffer, 0, MapMode.WriteDiscard, MapFlags.None).DataPointer;

            unsafe
            {
                fixed(void *mvpPtr = mvp)
                {
                    System.Buffer.MemoryCopy(mvpPtr, constantBuffer.ToPointer(), 16 * sizeof(float), 16 * sizeof(float));
                }
            }
            _deviceContext.UnmapSubresource(_vertexConstantBuffer, 0);

            var oldState = new StateBackup(_deviceContext);

            // Setup desired DX state
            SetupRenderState(drawData);

            // Render command lists
            // (Because we merged all buffers into a single one, we maintain our own offset into them)
            vertexOffset = 0;
            indexOffset  = 0;
            var clipOff = drawData.DisplayPos;

            for (int n = 0; n < drawData.CmdListsCount; n++)
            {
                var cmdList = drawData.CmdListsRange[n];
                for (int cmd = 0; cmd < cmdList.CmdBuffer.Size; cmd++)
                {
                    var pcmd = cmdList.CmdBuffer[cmd];
                    if (pcmd.UserCallback != IntPtr.Zero)
                    {
                        // TODO
                        throw new NotImplementedException();
                    }
                    else
                    {
                        // Apply scissor/clipping rectangle
                        _deviceContext.Rasterizer.SetScissorRectangle((int)(pcmd.ClipRect.X - clipOff.X), (int)(pcmd.ClipRect.Y - clipOff.Y), (int)(pcmd.ClipRect.Z - clipOff.X), (int)(pcmd.ClipRect.W - clipOff.Y));

                        // Bind texture, Draw
                        // TODO: might be nice to store samplers for loaded textures so that we can look them up and apply them here
                        // rather than just always using the font sampler
                        var textureSrv = ShaderResourceView.FromPointer <ShaderResourceView>(pcmd.TextureId);
                        _deviceContext.PixelShader.SetShaderResource(0, textureSrv);
                        _deviceContext.DrawIndexed((int)pcmd.ElemCount, (int)(pcmd.IdxOffset + indexOffset), (int)(pcmd.VtxOffset + vertexOffset));
                    }
                }

                indexOffset  += cmdList.IdxBuffer.Size;
                vertexOffset += cmdList.VtxBuffer.Size;
            }

            oldState.Dispose(); // restores the previous state
            oldState = null;
        }
Esempio n. 37
0
 private VertexArrayObject(GraphicsDevice graphicsDevice, object shaderSignature, IndexBufferBinding indexBufferBinding, VertexBufferBinding[] vertexBuffers)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="name">Name of the plane mesh.</param>
        /// <param name="plane">Plane to use for distance and orientation of the mesh.</param>
        /// <param name="width">Width in world coordinates.</param>
        /// <param name="height">Height in world coordinates.</param>
        /// <param name="xSegments">Number of x segments for tesselation.</param>
        /// <param name="ySegments">Number of y segments for tesselation.</param>
        /// <param name="normals">If true, plane normals are created.</param>
        /// <param name="numTexCoordSets">Number of 2d texture coord sets to use.</param>
        /// <param name="uTile">Number of times the texture should be repeated in the u direction.</param>
        /// <param name="vTile">Number of times the texture should be repeated in the v direction.</param>
        /// <param name="upVec">The up direction of the plane.</param>
        /// <returns></returns>
        public Mesh CreatePlane(string name, Plane plane, float width, float height, int xSegments, int ySegments, bool normals, int numTexCoordSets, float uTile, float vTile, Vector3 upVec,
                                BufferUsage vertexBufferUsage, BufferUsage indexBufferUsage, bool vertexShadowBuffer, bool indexShadowBuffer)
        {
            Mesh    mesh    = CreateManual(name);
            SubMesh subMesh = mesh.CreateSubMesh(name + "SubMesh");

            mesh.SharedVertexData = new VertexData();
            VertexData vertexData = mesh.SharedVertexData;

            VertexDeclaration decl = vertexData.vertexDeclaration;
            int currOffset         = 0;

            // add position data
            decl.AddElement(0, currOffset, VertexElementType.Float3, VertexElementSemantic.Position);
            currOffset += VertexElement.GetTypeSize(VertexElementType.Float3);

            // normals are optional
            if (normals)
            {
                decl.AddElement(0, currOffset, VertexElementType.Float3, VertexElementSemantic.Normal);
                currOffset += VertexElement.GetTypeSize(VertexElementType.Float3);
            }

            // add texture coords
            for (ushort i = 0; i < numTexCoordSets; i++)
            {
                decl.AddElement(0, currOffset, VertexElementType.Float2, VertexElementSemantic.TexCoords, i);
                currOffset += VertexElement.GetTypeSize(VertexElementType.Float2);
            }

            vertexData.vertexCount = (xSegments + 1) * (ySegments + 1);

            // create a new vertex buffer (based on current API)
            HardwareVertexBuffer vbuf =
                HardwareBufferManager.Instance.CreateVertexBuffer(decl.GetVertexSize(0), vertexData.vertexCount, vertexBufferUsage, vertexShadowBuffer);

            // get a reference to the vertex buffer binding
            VertexBufferBinding binding = vertexData.vertexBufferBinding;

            // bind the first vertex buffer
            binding.SetBinding(0, vbuf);

            // transform the plane based on its plane def
            Matrix4 translate = Matrix4.Identity;
            Matrix4 transform = Matrix4.Zero;
            Matrix4 rotation  = Matrix4.Identity;
            Matrix3 rot3x3    = Matrix3.Zero;

            Vector3 xAxis, yAxis, zAxis;

            zAxis = plane.Normal;
            zAxis.Normalize();
            yAxis = upVec;
            yAxis.Normalize();
            xAxis = yAxis.Cross(zAxis);

            if (xAxis.Length == 0)
            {
                throw new AxiomException("The up vector for a plane cannot be parallel to the planes normal.");
            }

            rot3x3.FromAxes(xAxis, yAxis, zAxis);
            rotation = rot3x3;

            // set up transform from origin
            translate.Translation = plane.Normal * -plane.D;

            transform = translate * rotation;

            float   xSpace           = width / xSegments;
            float   ySpace           = height / ySegments;
            float   halfWidth        = width / 2;
            float   halfHeight       = height / 2;
            float   xTexCoord        = (1.0f * uTile) / xSegments;
            float   yTexCoord        = (1.0f * vTile) / ySegments;
            Vector3 vec              = Vector3.Zero;
            Vector3 min              = Vector3.Zero;
            Vector3 max              = Vector3.Zero;
            float   maxSquaredLength = 0;
            bool    firstTime        = true;

            // generate vertex data
            GeneratePlaneVertexData(vbuf, ySegments, xSegments, xSpace, halfWidth, ySpace, halfHeight, transform, firstTime, normals, rotation, numTexCoordSets, xTexCoord, yTexCoord, subMesh, ref min, ref max, ref maxSquaredLength);

            // generate face list
            Tesselate2DMesh(subMesh, xSegments + 1, ySegments + 1, false, indexBufferUsage, indexShadowBuffer);

            // generate bounds for the mesh
            mesh.BoundingBox          = new AxisAlignedBox(min, max);
            mesh.BoundingSphereRadius = MathUtil.Sqrt(maxSquaredLength);

            mesh.Load();
            mesh.Touch();

            return(mesh);
        }
        public void BuildVB()
        {
            if (m_VB == null)
            {
                m_VB = new DataStream(Particle.ParticleVSIn.SizeInBytes() * m_MaxParticles, false, true);
                var vb = Engine.Global.Device3d.CreateBuffer(new Device3dD3d11.SCreateBufferCmd()
                {
                    Name = "Particle",
                    SizeInBytes = (int)Particle.ParticleVSIn.SizeInBytes() * m_MaxParticles,
                    BufferBindFlags = BindFlags.VertexBuffer
                });
                m_VBBinding = new VertexBufferBinding(vb, Particle.ParticleVSIn.SizeInBytes(), 0);
            }

            // fill vb with particle data
            Particle.ParticleVSIn[] particle_vsstream = new Particle.ParticleVSIn[m_Alive.Count];
            for (int i = 0; i < m_Alive.Count; ++i)
            {
                particle_vsstream[i].pos = new Vector4(m_Alive[i].pos, 1.0f);
                particle_vsstream[i].size = m_Alive[i].size;
            }

            m_VB = new DataStream(particle_vsstream, false, true);

            // update gpu buffer
            Engine.Global.Device3d.UpdateBufferData("Particle", m_VB);
        }
Esempio n. 40
0
		public void LoadResources()
		{
			if (m_Disposed == true)
			{
				m_ParticleTexture = Texture2D.FromFile(GameEnvironment.Device, m_ParticleTexturePath);
				m_ParticleTextureView = new ShaderResourceView(GameEnvironment.Device, m_ParticleTexture);

				#region Billboard

				using (DataStream stream = new DataStream(4 * Marshal.SizeOf(typeof(TexturedVertex)), true, true))
				{
					stream.WriteRange(new TexturedVertex[] {					
						new TexturedVertex() { Position = new Vector4(1f, -1f, 0.0f, 1f), TextureCoords =  new Vector2(1.0f, 0.0f) }, 
						new TexturedVertex() { Position = new Vector4(-1f, -1f, 0.0f, 1f), TextureCoords =  new Vector2(0.0f, 0.0f) }, 
						new TexturedVertex() { Position = new Vector4(1f, 1f, 0.0f, 1f), TextureCoords = new Vector2(1.0f, 1.0f) },  
						new TexturedVertex() { Position = new Vector4(-1f, 1f, 0.0f, 1f), TextureCoords =  new Vector2(0.0f, 1.0f) } 
					});

					stream.Position = 0;

					m_BillboardVertices = new SlimDX.Direct3D11.Buffer(GameEnvironment.Device, stream, new BufferDescription()
					{
						BindFlags = BindFlags.VertexBuffer,
						CpuAccessFlags = CpuAccessFlags.None,
						OptionFlags = ResourceOptionFlags.None,
						SizeInBytes = 4 * Marshal.SizeOf(typeof(TexturedVertex)),
						Usage = ResourceUsage.Default					
					});
				}

				#endregion

				#region Instances

				m_Instances = new SlimDX.Direct3D11.Buffer(GameEnvironment.Device, new BufferDescription()
				{
					BindFlags = BindFlags.VertexBuffer,
					CpuAccessFlags = CpuAccessFlags.Write,
					OptionFlags = ResourceOptionFlags.None,
					SizeInBytes = m_MaxCount * Marshal.SizeOf(typeof(StarInstanceVertex)),
					Usage = ResourceUsage.Dynamic
				});

				#endregion

				#region Bindings

				m_DataBindings = new VertexBufferBinding[2];

				m_DataBindings[0] = new VertexBufferBinding(m_BillboardVertices, Marshal.SizeOf(typeof(TexturedVertex)), 0);
				m_DataBindings[1] = new VertexBufferBinding(m_Instances, Marshal.SizeOf(typeof(StarInstanceVertex)), 0);

				#endregion

				m_Disposed = false; 
			}
		}
Esempio n. 41
0
		public void RenderImposter(ImposterOverlayType overlay, VertexBufferBinding bindings, ShaderResourceView imposterTexture, float brightPassThreshold)
		{
			if (m_Disposed == true)
			{
				return;
			}

			SlimDX.Direct3D11.DeviceContext context = GameEnvironment.Device.ImmediateContext;

			m_ImposterTextureResource.SetResource(imposterTexture);

			context.InputAssembler.InputLayout = m_Layout;
			context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;
			context.InputAssembler.SetVertexBuffers(0, bindings);
			context.InputAssembler.SetIndexBuffer(null, Format.Unknown, 0);

			m_BrightPassThreshold.Set(brightPassThreshold);

			if (overlay == ImposterOverlayType.None)
			{
				m_Pass_NoBlend.Apply(context);
			}
			else if (overlay == ImposterOverlayType.Add)
			{
				m_Pass_OverlayAdd.Apply(context);
			}
			else if (overlay == ImposterOverlayType.Subtract)
			{
				m_Pass_OverlaySubtract.Apply(context);
			}
			else if (overlay == ImposterOverlayType.Invert)
			{
				m_Pass_OverlayInvert.Apply(context);
			}
			else if (overlay == ImposterOverlayType.Alpha)
			{
				m_Pass_OverlayAlpha.Apply(context);
			}
			else if (overlay == ImposterOverlayType.None_BrightPass)
			{
				m_Pass_NoBlend_BrightPass.Apply(context);
			}
			else if (overlay == ImposterOverlayType.Add_BrightPass)
			{
				m_Pass_OverlayAdd_BrightPass.Apply(context);
			}
			else if (overlay == ImposterOverlayType.Subtract_BrightPass)
			{
				m_Pass_OverlaySubtract_BrightPass.Apply(context);
			}
			else if (overlay == ImposterOverlayType.Alpha_BrightPass)
			{
				m_Pass_OverlayAlpha_BrightPass.Apply(context);
			}
			else
			{
				throw new Exception("Unknown imposter overlay mode '" + overlay.ToString() + "'");
			}

			context.Draw(4, 0);
		}
Esempio n. 42
0
 protected override void CreateVertexBuffer(int elementByteSize, int elements)
 {
     vb           = new Buffer(device, elementByteSize * elements, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, elementByteSize);
     vb.DebugName = "Sprites Vertexbuffer";
     vbBinding    = new VertexBufferBinding(vb, elementByteSize, 0);
 }
        public Mesh CreateBoneMesh(string name)
        {
            Mesh mesh = CreateManual(name);

            mesh.SkeletonName = name + ".skeleton";
            SubMesh subMesh = mesh.CreateSubMesh("BoneSubMesh");

            subMesh.useSharedVertices = true;
            subMesh.MaterialName      = "BaseWhite";

            // short[] faces = { 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 5, 2, 1, 2, 5, 1, 5, 4, 1, 4, 3, 1, 3, 2 };
            // short[] faces = { 0, 3, 2, 0, 4, 3, 0, 5, 4, 0, 2, 5, 1, 5, 2, 1, 4, 5, 1, 3, 4, 1, 2, 3 };
            short[] faces = { 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 5, 2, 1, 2, 5, 1, 5, 4, 1, 4, 3, 1, 3, 2,
                              0, 3, 2, 0, 4, 3, 0, 5, 4, 0, 2, 5, 1, 5, 2, 1, 4, 5, 1, 3, 4, 1, 2, 3 };
            int     faceCount   = faces.Length / 3; // faces per bone
            int     vertexCount = 6;                // vertices per bone

            // set up vertex data, use a single shared buffer
            mesh.SharedVertexData = new VertexData();
            VertexData vertexData = mesh.SharedVertexData;

            // set up vertex declaration
            VertexDeclaration vertexDeclaration = vertexData.vertexDeclaration;
            int currentOffset = 0;

            // always need positions
            vertexDeclaration.AddElement(0, currentOffset, VertexElementType.Float3, VertexElementSemantic.Position);
            currentOffset += VertexElement.GetTypeSize(VertexElementType.Float3);
            vertexDeclaration.AddElement(0, currentOffset, VertexElementType.Float3, VertexElementSemantic.Normal);
            currentOffset += VertexElement.GetTypeSize(VertexElementType.Float3);

            int boneCount = mesh.Skeleton.BoneCount;

            // I want 6 vertices per bone - exclude the root bone
            vertexData.vertexCount = boneCount * vertexCount;

            // allocate vertex buffer
            HardwareVertexBuffer vertexBuffer = HardwareBufferManager.Instance.CreateVertexBuffer(vertexDeclaration.GetVertexSize(0), vertexData.vertexCount, BufferUsage.StaticWriteOnly);

            // set up the binding, one source only
            VertexBufferBinding binding = vertexData.vertexBufferBinding;

            binding.SetBinding(0, vertexBuffer);

            Vector3[] vertices = new Vector3[vertexData.vertexCount];
            GetVertices(ref vertices, mesh.Skeleton.RootBone);

            // Generate vertex data
            unsafe {
                // lock the vertex buffer
                IntPtr data = vertexBuffer.Lock(BufferLocking.Discard);

                float *pData = (float *)data.ToPointer();

                foreach (Vector3 vec in vertices)
                {
                    // assign to geometry
                    *pData++ = vec.x;
                    *pData++ = vec.y;
                    *pData++ = vec.z;
                    // fake normals
                    *pData++ = 0;
                    *pData++ = 1;
                    *pData++ = 0;
                }

                // unlock the buffer
                vertexBuffer.Unlock();
            } // unsafe


            // Generate index data
            HardwareIndexBuffer indexBuffer = HardwareBufferManager.Instance.CreateIndexBuffer(IndexType.Size16, faces.Length * boneCount, BufferUsage.StaticWriteOnly);

            subMesh.indexData.indexBuffer = indexBuffer;
            subMesh.indexData.indexCount  = faces.Length * boneCount;
            subMesh.indexData.indexStart  = 0;
            for (ushort boneIndex = 0; boneIndex < mesh.Skeleton.BoneCount; ++boneIndex)
            {
                Axiom.Animating.Bone bone = mesh.Skeleton.GetBone(boneIndex);
                short[] tmpFaces          = new short[faces.Length];
                for (int tmp = 0; tmp < faces.Length; ++tmp)
                {
                    tmpFaces[tmp] = (short)(faces[tmp] + vertexCount * bone.Handle);
                }
                indexBuffer.WriteData(faces.Length * bone.Handle * sizeof(short), tmpFaces.Length * sizeof(short), tmpFaces, true);
            }

            for (ushort boneIndex = 0; boneIndex < mesh.Skeleton.BoneCount; ++boneIndex)
            {
                Axiom.Animating.Bone bone       = mesh.Skeleton.GetBone(boneIndex);
                Axiom.Animating.Bone parentBone = bone;
                if (bone.Parent != null)
                {
                    parentBone = (Axiom.Animating.Bone)bone.Parent;
                }
                for (int vertexIndex = 0; vertexIndex < vertexCount; ++vertexIndex)
                {
                    Axiom.Animating.VertexBoneAssignment vba = new Axiom.Animating.VertexBoneAssignment();
                    // associate the base of the joint display with the bone's parent,
                    // and the rest of the points with the bone.
                    vba.boneIndex   = parentBone.Handle;
                    vba.weight      = 1.0f;
                    vba.vertexIndex = vertexCount * bone.Handle + vertexIndex;
                    mesh.AddBoneAssignment(vba);
                }
            }

            mesh.Load();
            mesh.Touch();

            return(mesh);
        }
Esempio n. 44
0
        public Render()
        {
            using (var dg = new DisposeGroup())
            {
                //Load Shaders
                var pVSBlob        = dg.Add(ShaderBytecode.CompileFromFile("RenderWithCam.fx", "VS", "vs_4_0"));
                var inputSignature = dg.Add(ShaderSignature.GetInputSignature(pVSBlob));
                m_pVertexShader = new VertexShader(Device, pVSBlob);

                var pPSBlob = dg.Add(ShaderBytecode.CompileFromFile("RenderWithCam.fx", "PS", "ps_4_0"));
                m_pPixelShader = new PixelShader(Device, pPSBlob);

                //Define layout
                var layout = dg.Add(new InputLayout(Device, inputSignature, new[] {
                    new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                    new InputElement("TEXCOORD", 0, Format.R32G32_Float, 16, 0)
                }));

                //Load model
                M2Reader reader = new M2Reader("Z:\\18566_full\\");
                reader.LoadM2(@"World\ArtTest\Boxtest\xyz.m2");

                //Load vertices
                List <float> verticelist = new List <float>();
                for (int i = 0; i < reader.model.vertices.Count(); i++)
                {
                    verticelist.Add(reader.model.vertices[i].position.X);
                    verticelist.Add(reader.model.vertices[i].position.Z * -1);
                    verticelist.Add(reader.model.vertices[i].position.Y);
                    verticelist.Add(1.0f);
                    verticelist.Add(reader.model.vertices[i].textureCoordX);
                    verticelist.Add(reader.model.vertices[i].textureCoordY);
                }

                //Load indices
                List <ushort> indicelist = new List <ushort>();
                for (int i = 0; i < reader.model.skins[0].triangles.Count(); i++)
                {
                    indicelist.Add(reader.model.skins[0].triangles[i].pt1);
                    indicelist.Add(reader.model.skins[0].triangles[i].pt2);
                    indicelist.Add(reader.model.skins[0].triangles[i].pt3);
                }

                //Convert to array
                ushort[] indices  = indicelist.ToArray();
                float[]  vertices = verticelist.ToArray();

                //Set count for use in draw later on
                indicecount = indices.Count();

                //Create buffers
                var vertexBuffer        = dg.Add(Buffer.Create(Device, BindFlags.VertexBuffer, vertices));
                var vertexBufferBinding = new VertexBufferBinding(vertexBuffer, Utilities.SizeOf <Vector4>() + Utilities.SizeOf <Vector2>(), 0);
                var indexBuffer         = dg.Add(Buffer.Create(Device, BindFlags.IndexBuffer, indices));

                Device.ImmediateContext.InputAssembler.InputLayout = (layout);
                Device.ImmediateContext.InputAssembler.SetVertexBuffers(0, vertexBufferBinding);
                Device.ImmediateContext.InputAssembler.SetIndexBuffer(indexBuffer, Format.R16_UInt, 0);
                Device.ImmediateContext.InputAssembler.PrimitiveTopology = (PrimitiveTopology.TriangleList);

                //Get texture, what a mess this could be much better
                var blp = new BLPReader("Z:\\18566_full\\");
                if (File.Exists(Path.Combine("Z:\\18566_full\\", reader.model.filename.Replace("M2", "blp"))))
                {
                    blp.LoadBLP(reader.model.filename.Replace("M2", "blp"));
                }
                else
                {
                    if (reader.model.textures.Count() > 0)
                    {
                        blp.LoadBLP(reader.model.textures[0]);
                    }
                    else
                    {
                        throw new Exception("No forking textures, mate.");
                    }
                }

                MemoryStream s = new MemoryStream();
                blp.bmp.Save(s, System.Drawing.Imaging.ImageFormat.Png);
                s.Seek(0, SeekOrigin.Begin);
                Texture2D texture = Texture2D.FromMemory <Texture2D>(Device, s.ToArray());

                var textureView = new ShaderResourceView(Device, texture);

                var sampler = new SamplerState(Device, new SamplerStateDescription()
                {
                    Filter             = Filter.MinMagMipLinear,
                    AddressU           = TextureAddressMode.Wrap,
                    AddressV           = TextureAddressMode.Wrap,
                    AddressW           = TextureAddressMode.Wrap,
                    BorderColor        = SharpDX.Color.Black,
                    ComparisonFunction = Comparison.Never,
                    MaximumAnisotropy  = 16,
                    MipLodBias         = 0,
                    MinimumLod         = 0,
                    MaximumLod         = 16,
                });

                Device.ImmediateContext.PixelShader.SetSampler(0, sampler);
                Device.ImmediateContext.PixelShader.SetShaderResource(0, textureView);
                //End of texture stuff,

                Set(ref m_pConstantBuffer, new ConstantBuffer <Projections>(Device));
                Device.ImmediateContext.VertexShader.SetConstantBuffer(0, m_pConstantBuffer.Buffer);
            }

            //Make camera
            Camera = new FirstPersonCamera();
            Camera.SetProjParams((float)Math.PI / 2, 1, 0.01f, 100.0f);
            Camera.SetViewParams(new Vector3(0.0f, 0.0f, -5.0f), new Vector3(0.0f, 1.0f, 0.0f));
        }
Esempio n. 45
0
        private void CreateBuffers(ushort[] indices, short[] vertices)
        {
            var numIndices = (uint)indices.Length;
            var numVertices = (uint)vertices.Length;

            _vertexDeclaration = HardwareBufferManager.Singleton.CreateVertexDeclaration();
            _vertexDeclaration.AddElement(0, 0, VertexElementType.VET_SHORT2, VertexElementSemantic.VES_POSITION);
            _ib = HardwareBufferManager.Singleton.CreateIndexBuffer(HardwareIndexBuffer.IndexType.IT_16BIT, numIndices, HardwareBuffer.Usage.HBU_STATIC_WRITE_ONLY);
            _vb = HardwareBufferManager.Singleton.CreateVertexBuffer(_vertexDeclaration.GetVertexSize(0), numVertices, HardwareBuffer.Usage.HBU_STATIC_WRITE_ONLY, false);

            unsafe
            {
                fixed (ushort* x = indices)
                    _ib.WriteData(0, numIndices * sizeof(ushort), x, true);

                fixed (short* x = vertices)
                    _vb.WriteData(0, numVertices * sizeof(ushort), x, true);
            }

            var binding = new VertexBufferBinding();
            binding.SetBinding(0, _vb);

            VertexData = new VertexData(_vertexDeclaration, binding);
            VertexData.vertexCount = numVertices;
            VertexData.vertexStart = 0;

            IndexData = new IndexData();
            IndexData.indexBuffer = _ib;
            IndexData.indexCount = numIndices;
            IndexData.indexStart = 0;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="name"></param>
        /// <param name="plane"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="curvature"></param>
        /// <param name="xSegments"></param>
        /// <param name="ySegments"></param>
        /// <param name="normals"></param>
        /// <param name="numberOfTexCoordSets"></param>
        /// <param name="uTiles"></param>
        /// <param name="vTiles"></param>
        /// <param name="upVector"></param>
        /// <param name="orientation"></param>
        /// <param name="vertexBufferUsage"></param>
        /// <param name="indexBufferUsage"></param>
        /// <param name="vertexShadowBuffer"></param>
        /// <param name="indexShadowBuffer"></param>
        /// <returns></returns>
        public Mesh CreateCurvedIllusionPlane(string name, Plane plane, float width, float height, float curvature, int xSegments, int ySegments, bool normals, int numberOfTexCoordSets, float uTiles, float vTiles, Vector3 upVector, Quaternion orientation, BufferUsage vertexBufferUsage, BufferUsage indexBufferUsage, bool vertexShadowBuffer, bool indexShadowBuffer)
        {
            Mesh    mesh    = CreateManual(name);
            SubMesh subMesh = mesh.CreateSubMesh(name + "SubMesh");

            // set up vertex data, use a single shared buffer
            mesh.SharedVertexData = new VertexData();
            VertexData vertexData = mesh.SharedVertexData;

            // set up vertex declaration
            VertexDeclaration vertexDeclaration = vertexData.vertexDeclaration;
            int currentOffset = 0;

            // always need positions
            vertexDeclaration.AddElement(0, currentOffset, VertexElementType.Float3, VertexElementSemantic.Position);
            currentOffset += VertexElement.GetTypeSize(VertexElementType.Float3);

            // optional normals
            if (normals)
            {
                vertexDeclaration.AddElement(0, currentOffset, VertexElementType.Float3, VertexElementSemantic.Normal);
                currentOffset += VertexElement.GetTypeSize(VertexElementType.Float3);
            }

            for (ushort i = 0; i < numberOfTexCoordSets; i++)
            {
                // assumes 2d texture coordinates
                vertexDeclaration.AddElement(0, currentOffset, VertexElementType.Float2, VertexElementSemantic.TexCoords, i);
                currentOffset += VertexElement.GetTypeSize(VertexElementType.Float2);
            }

            vertexData.vertexCount = (xSegments + 1) * (ySegments + 1);

            // allocate vertex buffer
            HardwareVertexBuffer vertexBuffer = HardwareBufferManager.Instance.CreateVertexBuffer(vertexDeclaration.GetVertexSize(0), vertexData.vertexCount, vertexBufferUsage, vertexShadowBuffer);

            // set up the binding, one source only
            VertexBufferBinding binding = vertexData.vertexBufferBinding;

            binding.SetBinding(0, vertexBuffer);

            // work out the transform required, default orientation of plane is normal along +z, distance 0
            Matrix4 xlate, xform, rot;
            Matrix3 rot3 = Matrix3.Identity;

            xlate = rot = Matrix4.Identity;

            // determine axes
            Vector3 zAxis, yAxis, xAxis;

            zAxis = plane.Normal;
            zAxis.Normalize();
            yAxis = upVector;
            yAxis.Normalize();
            xAxis = yAxis.Cross(zAxis);
            if (xAxis.Length == 0)
            {
                throw new AxiomException("The up vector for a plane cannot be parallel to the planes normal.");
            }

            rot3.FromAxes(xAxis, yAxis, zAxis);
            rot = rot3;

            // set up standard xform from origin
            xlate.Translation = plane.Normal * -plane.D;

            // concatenate
            xform = xlate * rot;

            // generate vertex data, imagine a large sphere with the camera located near the top,
            // the lower the curvature, the larger the sphere.  use the angle from the viewer to the
            // points on the plane
            float cameraPosition;      // camera position relative to the sphere center

            // derive sphere radius (unused)
            //float sphereDistance;      // distance from the camera to the sphere along box vertex vector
            float sphereRadius;

            // actual values irrelevant, it's the relation between the sphere's radius and the camera's position which is important
            float SPHERE_RADIUS   = 100;
            float CAMERA_DISTANCE = 5;

            sphereRadius   = SPHERE_RADIUS - curvature;
            cameraPosition = sphereRadius - CAMERA_DISTANCE;

            // lock the whole buffer
            float   xSpace           = width / xSegments;
            float   ySpace           = height / ySegments;
            float   halfWidth        = width / 2;
            float   halfHeight       = height / 2;
            Vector3 vec              = Vector3.Zero;
            Vector3 norm             = Vector3.Zero;
            Vector3 min              = Vector3.Zero;
            Vector3 max              = Vector3.Zero;
            float   maxSquaredLength = 0;
            bool    firstTime        = true;

            // generate vertex data
            GenerateCurvedIllusionPlaneVertexData(vertexBuffer, ySegments, xSegments, xSpace, halfWidth, ySpace, halfHeight, xform, firstTime, normals, orientation, cameraPosition, sphereRadius, uTiles, vTiles, numberOfTexCoordSets, ref min, ref max, ref maxSquaredLength);

            // generate face list
            subMesh.useSharedVertices = true;
            Tesselate2DMesh(subMesh, xSegments + 1, ySegments + 1, false, indexBufferUsage, indexShadowBuffer);

            // generate bounds for the mesh
            mesh.BoundingBox          = new AxisAlignedBox(min, max);
            mesh.BoundingSphereRadius = MathUtil.Sqrt(maxSquaredLength);

            mesh.Load();
            mesh.Touch();

            return(mesh);
        }
Esempio n. 47
0
        public unsafe static void CompactHalf(ref VertexBufferBinding vertexBufferBinding)
        {
            var vertexElementsWithOffsets = vertexBufferBinding.Declaration
                .EnumerateWithOffsets()
                .OrderBy(x => x.Offset)
                .ToArray();

            var vertexElements = new VertexElementConvertInfo[vertexElementsWithOffsets.Length];

            int currentOffset = 0;
            for (int index = 0; index < vertexElementsWithOffsets.Length; index++)
            {
                var vertexElementConvertInfo = new VertexElementConvertInfo();
                vertexElementConvertInfo.VertexElementWithOffset = vertexElementsWithOffsets[index];
                var vertexElement = vertexElementsWithOffsets[index].VertexElement;
                var vertexElementFormat = vertexElementConvertInfo.VertexElementWithOffset.VertexElement.Format;

                // First iteration?
                if (index == 0)
                    currentOffset = vertexElementsWithOffsets[index].Offset;

                vertexElements[index] = vertexElementConvertInfo;
                vertexElementConvertInfo.OldFormat = vertexElementConvertInfo.VertexElementWithOffset.VertexElement.Format;

                int offsetShift = 0;

                switch (vertexElementFormat)
                {
                    case PixelFormat.R32G32_Float:
                        vertexElementFormat = PixelFormat.R16G16_Float;

                        // Adjust next offset if current object has been resized
                        offsetShift = Utilities.SizeOf<Half2>() - Utilities.SizeOf<Vector2>();
                        break;
                    case PixelFormat.R32G32B32_Float:
                        vertexElementFormat = PixelFormat.R16G16B16A16_Float;

                        // Adjust next offset if current object has been resized
                        offsetShift = Utilities.SizeOf<Half4>() - Utilities.SizeOf<Vector3>();
                        break;
                    case PixelFormat.R32G32B32A32_Float:
                        vertexElementFormat = PixelFormat.R16G16B16A16_Float;

                        // Adjust next offset if current object has been resized
                        offsetShift = Utilities.SizeOf<Half4>() - Utilities.SizeOf<Vector4>();
                        break;
                }

                // Has format changed?
                vertexElementConvertInfo.NeedConversion = vertexElementFormat != vertexElementConvertInfo.VertexElementWithOffset.VertexElement.Format;

                // Create new vertex element with adjusted offset, and maybe new vertex format (if modified)
                vertexElementConvertInfo.VertexElementWithOffset.VertexElement
                    = new VertexElement(vertexElement.semanticName, vertexElement.SemanticIndex, vertexElementFormat, currentOffset);

                // Increment next offset by the same difference as in original declaration
                if (index + 1 < vertexElementsWithOffsets.Length)
                    currentOffset += vertexElementsWithOffsets[index + 1].Offset - vertexElementsWithOffsets[index].Offset;

                currentOffset += offsetShift;

                vertexElements[index] = vertexElementConvertInfo;
            }

            var oldVertexStride = vertexBufferBinding.Declaration.VertexStride;

            var vertexDeclaration = new VertexDeclaration(vertexElements.Select(x => x.VertexElementWithOffset.VertexElement).ToArray());

            var newVertexStride = vertexDeclaration.VertexStride;
            var newBufferData = new byte[vertexBufferBinding.Count * newVertexStride];
            fixed (byte* oldBuffer = &vertexBufferBinding.Buffer.GetSerializationData().Content[vertexBufferBinding.Offset])
            fixed (byte* newBuffer = &newBufferData[0])
            {
                var oldBufferVertexPtr = (IntPtr)oldBuffer;
                var newBufferVertexPtr = (IntPtr)newBuffer;
                for (int i = 0; i < vertexBufferBinding.Count; ++i)
                {
                    foreach (var element in vertexElements)
                    {
                        var oldBufferElementPtr = oldBufferVertexPtr + element.VertexElementWithOffset.Offset;
                        var newBufferElementPtr = newBufferVertexPtr + element.VertexElementWithOffset.VertexElement.AlignedByteOffset;

                        if (element.NeedConversion)
                        {
                            // Convert floatX => halfX
                            switch (element.OldFormat)
                            {
                                case PixelFormat.R32G32_Float:
                                    *((Half2*)newBufferElementPtr) = (Half2)(*((Vector2*)oldBufferElementPtr));
                                    break;
                                case PixelFormat.R32G32B32_Float:
                                    // Put 1.0f in 
                                    *((Half4*)newBufferElementPtr) = (Half4)(new Vector4(*((Vector3*)oldBufferElementPtr), 1.0f));
                                    break;
                                case PixelFormat.R32G32B32A32_Float:
                                    *((Half4*)newBufferElementPtr) = (Half4)(*((Vector4*)oldBufferElementPtr));
                                    break;
                            }
                        }
                        else
                        {
                            // Copy as is
                            Utilities.CopyMemory(newBufferElementPtr, oldBufferElementPtr, element.VertexElementWithOffset.Size);
                        }
                    }

                    oldBufferVertexPtr += oldVertexStride;
                    newBufferVertexPtr += newVertexStride;
                }
            }

            vertexBufferBinding = new VertexBufferBinding(new BufferData(BufferFlags.VertexBuffer, newBufferData).ToSerializableVersion(), vertexDeclaration, vertexBufferBinding.Count);
        }
Esempio n. 48
0
        public EarthFromOBJ(DeviceContext dx11Context)
        {
            _dx11Context = dx11Context;
            World        = Matrix.Translation(0, 100, -5000);
            _light.Color = Color4.White;

            const string obj         = "3DModelsFiles\\Earth\\earth.obj";
            const string mtl         = "3DModelsFiles\\Earth\\earth.mtl";
            const string jpg         = "3DModelsFiles\\Earth\\earthmap.jpg";
            const string shadersFile = "Shaders\\EarthT.hlsl";
            Tuple <List <Face>, List <uint> > tuple = GetFaces(obj);

            _facesCount = tuple.Item2.Count;

            _vertexBuffer  = Buffer.Create(dx11Context.Device, BindFlags.VertexBuffer, tuple.Item1.ToArray());
            _indexBuffer   = Buffer.Create(dx11Context.Device, BindFlags.IndexBuffer, tuple.Item2.ToArray());
            _vertexBinding = new VertexBufferBinding(_vertexBuffer, Utilities.SizeOf <Face>(), 0);

            MtlMaterial material = GetMaterial(mtl);

            _materialsBuffer = Buffer.Create(_dx11Context.Device, BindFlags.ConstantBuffer, ref material);

            _constantBuffer = new Buffer(_dx11Context.Device, Utilities.SizeOf <Matrices>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
            _lightBuffer    = new Buffer(_dx11Context.Device, Utilities.SizeOf <Light>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

            _textureResourse  = _dx11Context.LoadTextureFromFile(jpg);
            _textureResourse1 = _dx11Context.LoadTextureFromFile("3DModelsFiles\\Earth\\map.jpg");
            _textureResourse2 = _dx11Context.LoadTextureFromFile("3DModelsFiles\\Earth\\map1.jpg");


            SamplerStateDescription description = SamplerStateDescription.Default();

            description.Filter   = Filter.MinMagMipLinear;
            description.AddressU = TextureAddressMode.Wrap;
            description.AddressV = TextureAddressMode.Wrap;
            description.AddressW = TextureAddressMode.Wrap;
            _samplerState        = new SamplerState(_dx11Context.Device, description);

            //Загружаем шейдеры из файлов
            InputElement[] inputElements = new InputElement[]
            {
                new InputElement("SV_Position", 0, Format.R32G32B32_Float, 0, 0),
                new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32B32_Float, 24, 0)
            };
            ShaderFlags shaderFlags = ShaderFlags.None;

#if DEBUG
            shaderFlags = ShaderFlags.Debug;
#endif

            using (var vertexShaderByteCode = ShaderBytecode.CompileFromFile(shadersFile, "VS", "vs_5_0", shaderFlags))
            {
                //Синатура храянящая сведения о том какие входные переменные есть у шейдера
                _inputSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode);
                _vertexShader   = new VertexShader(_dx11Context.Device, vertexShaderByteCode);
            }
            using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile(shadersFile, "PS", "ps_5_0", shaderFlags))
            {
                _pixelShader = new PixelShader(_dx11Context.Device, pixelShaderByteCode);
            }
            using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile(shadersFile, "HS", "hs_5_0", shaderFlags))
            {
                _hShader = new HullShader(_dx11Context.Device, pixelShaderByteCode);
            }

            using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile(shadersFile, "DS", "ds_5_0", shaderFlags))
            {
                _dShader = new DomainShader(_dx11Context.Device, pixelShaderByteCode);
            }

            _inputLayout = new InputLayout(_dx11Context.Device, _inputSignature, inputElements);

            RasterizerStateDescription rasterizerStateDescription = RasterizerStateDescription.Default();
            rasterizerStateDescription.CullMode = CullMode.None;
            rasterizerStateDescription.FillMode = FillMode.Solid;

            DepthStencilStateDescription DStateDescripshion = DepthStencilStateDescription.Default();
            DStateDescripshion.IsDepthEnabled = true;

            _DState          = new DepthStencilState(_dx11Context.Device, DStateDescripshion);
            _rasterizerState = new RasterizerState(_dx11Context.Device, rasterizerStateDescription);

            _light.Direction = new Vector3(1f, -1f, 1f);
        }
Esempio n. 49
0
        /// <summary>
        /// Attaches the specified vertex buffer to the geometry stream.
        /// </summary>
        private void AttachInternal(VertexBuffer vbuffer, Int32 instanceFrequency)
        {
            if (vbuffers == null)
                vbuffers = new List<VertexBufferBinding>(1);

            var oglVertexBuffer = (OpenGLVertexBuffer)vbuffer;
            var sdlVertexBufferName = oglVertexBuffer.OpenGLName;

            var binding = new VertexBufferBinding(oglVertexBuffer, instanceFrequency);
            this.vbuffers.Add(binding);
        }
Esempio n. 50
0
        public override void Initialize()
        {
            Form.SizeChanged += (o, args) =>
            {
                if (_swapChain == null)
                {
                    return;
                }

                renderView.Dispose();
                depthView.Dispose();
                DisposeBuffers();

                if (Form.WindowState == FormWindowState.Minimized)
                {
                    return;
                }

                _width  = Form.ClientSize.Width;
                _height = Form.ClientSize.Height;
                _swapChain.ResizeBuffers(_swapChain.Description.BufferCount, 0, 0, Format.Unknown, 0);

                CreateBuffers();
                SetSceneConstants();
            };

            _width     = 1024;
            _height    = 768;
            _nearPlane = 0.1f;

            try
            {
                OnInitializeDevice();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Could not create DirectX 11 device.");
                return;
            }


            // shader.fx

            const ShaderFlags shaderFlags = ShaderFlags.None;

            //const ShaderFlags shaderFlags = ShaderFlags.Debug | ShaderFlags.SkipOptimization;

            string[] sources = { "shader.fx", "grender.fx" };
            using (var shaderByteCode = ShaderLoader.FromResource(Assembly.GetExecutingAssembly(), sources, shaderFlags))
            {
                effect = new Effect(Device, shaderByteCode);
            }
            EffectTechnique technique = effect.GetTechniqueByName("GBufferCreate");

            shadowGenPass  = technique.GetPassByName("ShadowMap");
            gBufferGenPass = technique.GetPassByName("GBufferGen");
            debugDrawPass  = technique.GetPassByName("DebugDraw");

            var sceneConstantsDesc = new BufferDescription
            {
                SizeInBytes    = Marshal.SizeOf(typeof(ShaderSceneConstants)),
                Usage          = ResourceUsage.Dynamic,
                BindFlags      = BindFlags.ConstantBuffer,
                CpuAccessFlags = CpuAccessFlags.Write,
                OptionFlags    = ResourceOptionFlags.None
            };

            sceneConstantsBuffer = new Buffer(Device, sceneConstantsDesc);
            EffectConstantBuffer effectConstantBuffer = effect.GetConstantBufferByName("scene");

            effectConstantBuffer.SetConstantBuffer(sceneConstantsBuffer);

            var _rasterizerStateDesc = new RasterizerStateDescription
            {
                CullMode             = CullMode.None,
                FillMode             = FillMode.Solid,
                DepthBias            = 0,
                DepthBiasClamp       = 0,
                SlopeScaledDepthBias = 0,
                IsDepthClipEnabled   = true,
            };

            noCullState = new RasterizerState(Device, _rasterizerStateDesc);
            _rasterizerStateDesc.CullMode = CullMode.Back;
            backCullState = new RasterizerState(Device, _rasterizerStateDesc);
            _rasterizerStateDesc.CullMode = CullMode.Front;
            frontCullState = new RasterizerState(Device, _rasterizerStateDesc);
            _immediateContext.Rasterizer.State = CullingEnabled ? backCullState : noCullState;

            var depthDesc = new DepthStencilStateDescription
            {
                IsDepthEnabled   = true,
                IsStencilEnabled = false,
                DepthWriteMask   = DepthWriteMask.All,
                DepthComparison  = Comparison.Less
            };

            depthState = new DepthStencilState(Device, depthDesc);
            depthDesc.DepthWriteMask     = DepthWriteMask.Zero;
            outsideLightVolumeDepthState = new DepthStencilState(Device, depthDesc);
            depthDesc.DepthComparison    = Comparison.Greater;
            insideLightVolumeDepthState  = new DepthStencilState(Device, depthDesc);

            var lightDepthStateDesc = new DepthStencilStateDescription
            {
                IsDepthEnabled   = true,
                IsStencilEnabled = false,
                DepthWriteMask   = DepthWriteMask.All,
                DepthComparison  = Comparison.Less
            };

            lightDepthStencilState = new DepthStencilState(Device, lightDepthStateDesc);


            // grender.fx
            technique               = effect.GetTechniqueByName("DeferredShader");
            gBufferRenderPass       = technique.GetPassByName("DeferredShader");
            gBufferPostProcessPass  = technique.GetPassByName("Blur");
            gBufferPostProcessPass2 = technique.GetPassByName("PostProcess");
            gBufferOverlayPass      = technique.GetPassByName("Overlay");

            lightBufferVar            = effect.GetVariableByName("lightBuffer").AsShaderResource();
            normalBufferVar           = effect.GetVariableByName("normalBuffer").AsShaderResource();
            diffuseBufferVar          = effect.GetVariableByName("diffuseBuffer").AsShaderResource();
            depthMapVar               = effect.GetVariableByName("depthMap").AsShaderResource();
            shadowLightDepthBufferVar = effect.GetVariableByName("lightDepthMap").AsShaderResource();

            sunLightDirectionVar = effect.GetVariableByName("SunLightDirection").AsVector();
            viewportWidthVar     = effect.GetVariableByName("ViewportWidth").AsScalar();
            viewportHeightVar    = effect.GetVariableByName("ViewportHeight").AsScalar();
            viewParametersVar    = effect.GetVariableByName("ViewParameters").AsVector();

            overlayViewProjectionVar = effect.GetVariableByName("OverlayViewProjection").AsMatrix();


            // light.fx
            using (var shaderByteCode = ShaderLoader.FromResource(Assembly.GetExecutingAssembly(), "light.fx", shaderFlags))
            {
                lightShader = new Effect(Device, shaderByteCode);
            }

            technique             = lightShader.GetTechniqueByIndex(0);
            lightAccumulationPass = technique.GetPassByName("Light");

            lightWorldVar          = lightShader.GetVariableByName("World").AsMatrix();
            lightPositionRadiusVar = lightShader.GetVariableByName("PositionRadius").AsVector();
            lightColorVar          = lightShader.GetVariableByName("Color").AsVector();

            lightProjectionVar     = lightShader.GetVariableByName("Projection").AsMatrix();
            lightViewVar           = lightShader.GetVariableByName("View").AsMatrix();
            lightViewInverseVar    = lightShader.GetVariableByName("ViewInverse").AsMatrix();
            lightViewportWidthVar  = lightShader.GetVariableByName("ViewportWidth").AsScalar();
            lightViewportHeightVar = lightShader.GetVariableByName("ViewportHeight").AsScalar();
            lightEyePositionVar    = lightShader.GetVariableByName("EyePosition").AsVector();
            lightViewParametersVar = lightShader.GetVariableByName("ViewParameters").AsVector();

            var elements = new InputElement[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
            };

            lightVolumeInputLayout = new InputLayout(Device, lightShader.GetTechniqueByIndex(0).GetPassByName("Light").Description.Signature, elements);

            pointLightVolumeVertices = Light.CreatePointLightVolume(out pointLightVolumeIndices);
            var vertexBufferDesc = new BufferDescription
            {
                SizeInBytes = Vector3.SizeInBytes * pointLightVolumeVertices.Length,
                Usage       = ResourceUsage.Default,
                BindFlags   = BindFlags.VertexBuffer,
            };

            using (var data = new DataStream(vertexBufferDesc.SizeInBytes, false, true))
            {
                data.WriteRange(pointLightVolumeVertices);
                data.Position = 0;
                pointLightVolumeVertexBuffer = new Buffer(Device, data, vertexBufferDesc);
            }
            pointLightVolumeVertexBufferBinding = new VertexBufferBinding(pointLightVolumeVertexBuffer, 12, 0);

            var indexBufferDesc = new BufferDescription
            {
                SizeInBytes = sizeof(uint) * pointLightVolumeIndices.Length,
                Usage       = ResourceUsage.Default,
                BindFlags   = BindFlags.IndexBuffer
            };

            using (var data = new DataStream(indexBufferDesc.SizeInBytes, false, true))
            {
                data.WriteRange(pointLightVolumeIndices);
                data.Position = 0;
                pointLightVolumeIndexBuffer = new Buffer(Device, data, indexBufferDesc);
            }

            lightDepthBufferVar  = lightShader.GetVariableByName("depthBuffer").AsShaderResource();
            lightNormalBufferVar = lightShader.GetVariableByName("normalBuffer").AsShaderResource();

            lights.Add(new Light(pointLightPosition, 60, new Vector4(1, 0.95f, 0.9f, 1)));
            //lights.Add(new Light(pointLightPosition, 60, new Vector4(0, 0, 1, 1)));
            //lights.Add(new Light(new Vector3(-10, 10, 10), 30, new Vector4(1, 0, 0, 1)));
            //lights.Add(new Light(new Vector3(10, 5, -10), 20, new Vector4(0, 1, 0, 1)));
            //lights.Add(new Light(new Vector3(-10, 5, -10), 20, new Vector4(1, 0, 1, 1)));


            info         = new InfoText(Device, 256, 256);
            _meshFactory = new MeshFactory(this);
            MeshFactory  = _meshFactory;

            CreateBuffers();
            GraphicsLibraryManager.LibraryStarted();
        }
 public void Render(Shader shader)
 {
     InputLayout layout = GetInputLayout(shader);
     if (layout != CurrentInputLayout)
     {
         CurrentInputLayout = layout;
         context.InputAssembler.InputLayout = layout;
     }
     context.InputAssembler.PrimitiveTopology = Topology;
     if (bufferbinding != CurrentVertexBufferBinding)
     {
         CurrentVertexBufferBinding = bufferbinding;
         context.InputAssembler.SetVertexBuffers(0, bufferbinding);
     }
     if (ibIndices != CurrentIndexBuffer)
     {
         CurrentIndexBuffer = ibIndices;
         context.InputAssembler.SetIndexBuffer(ibIndices, indexformat, 0);
     }
     context.DrawIndexed(curindices, 0, 0);
 }
Esempio n. 52
0
        /// <summary>
        /// Fills the color type buffer (VertexPositionColor)
        /// </summary>
        /// <param name="points">The points.</param>
        /// <param name="primitiveType">Type of the primitive.</param>
        public override void FillColor(List<PointF> points, GeometryPrimitiveType primitiveType)
        {
            SetPrimitiveCount(primitiveType, points.Count);

            VertexPositionNormalTexture[] vertex = new VertexPositionNormalTexture[points.Count];
            for (int i = 0; i < points.Count; i++)
            {
                vertex[i] = new VertexPositionNormalTexture(new Vector3(points[i].X, points[i].Y, 0), new Vector3(0, 0, 1), Vector2.Zero);
            }

            VertexBuffer = VertexBuffer.Vertex.New(XenkoRenderer.GraphicsDevice, vertex);
            VertexBuffer.Reload = (graphicsResource) => ((VertexBuffer)graphicsResource).Recreate(vertex);
            VertexBufferBinding = new VertexBufferBinding(VertexBuffer, VertexPositionNormalTexture.Layout, vertex.Length, VertexPositionNormalTexture.Size);
            InputElementDescriptions = VertexBufferBinding.Declaration.CreateInputElements();
        }
        public void Init()
        {
            // Determine element and buffer size
            elementsize = Vector3.SizeInBytes;
            if (mesh.Normals != null) elementsize += Vector3.SizeInBytes;
            if (mesh.TextureCoordinates != null) elementsize += Vector2.SizeInBytes;
            if (mesh.Tangents != null) elementsize += Vector3.SizeInBytes;
            buffersize = elementsize * mesh.Positions.Length;

            // Determine input elements
            var inputelementslist = new List<InputElement>();
            int curoffset = 0;
            inputelementslist.Add(new InputElement("POSITION", 0, SlimDX.DXGI.Format.R32G32B32_Float, curoffset, 0));
            curoffset += Vector3.SizeInBytes;
            if (mesh.Normals != null)
            {
                inputelementslist.Add(new InputElement("NORMAL", 0, SlimDX.DXGI.Format.R32G32B32_Float, curoffset, 0));
                curoffset += Vector3.SizeInBytes;
            }
            if (mesh.TextureCoordinates != null)
            {
                inputelementslist.Add(new InputElement("TEXCOORD", 0, SlimDX.DXGI.Format.R32G32_Float, curoffset, 0));
                curoffset += Vector2.SizeInBytes;
            }
            if (mesh.Tangents != null)
            {
                inputelementslist.Add(new InputElement("TANGENT", 0, SlimDX.DXGI.Format.R32G32B32_Float, curoffset, 0));
                curoffset += Vector3.SizeInBytes;
            }
            inputelements = inputelementslist.ToArray();

            // Write the stream
            var strm = new DataStream(buffersize, true, true);
            for (int i = 0; i < mesh.Positions.Length; i++)
            {
                strm.Write(mesh.Positions[i]);
                if (mesh.Normals != null) strm.Write(mesh.Normals[i]);
                if (mesh.TextureCoordinates != null) strm.Write(mesh.TextureCoordinates[i]);
                if (mesh.Tangents != null) strm.Write(mesh.Tangents[i]);
            }
            strm.Position = 0;

            // Build the buffer
            vtxBuffer = new Buffer(device, strm, new BufferDescription((int)strm.Length, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));
            bufferbinding = new VertexBufferBinding(vtxBuffer, elementsize, 0);

            // Build the indices buffer(s)
            indexformat = SlimDX.DXGI.Format.R32_UInt;
            submeshes = new Buffer[mesh.Submeshes.Length];
            for (int i = 0; i < submeshes.Length; i++ )
                submeshes[i] = ArrayToBuffer(mesh.Submeshes[i], ResourceUsage.Default);

            // Build the shader map
            shadermap = new Dictionary<Shader, InputLayout>();

            // Update iteration
            Iteration = mesh.Iteration;
        }
Esempio n. 54
0
        /// <summary>
        /// Fills the texture type buffer (VertexPositionTexture)
        /// </summary>
        /// <param name="points">The points.</param>
        /// <param name="destinationSize">Size of the destination.</param>
        /// <param name="sourceRect">The source rect.</param>
        /// <param name="primitiveType">Type of the primitive.</param>
        public override void FillTexture(List<PointF> points, Size destinationSize, Rect sourceRect, GeometryPrimitiveType primitiveType)
        {
            SetPrimitiveCount(primitiveType, points.Count);

            VertexPositionNormalTexture[] vertex = new VertexPositionNormalTexture[points.Count];
            for (int i = 0; i < points.Count; i++)
            {
                Vector2 uv = new Vector2(sourceRect.X + (points[i].X / destinationSize.Width) * sourceRect.Width,
                                         sourceRect.Y + (points[i].Y / destinationSize.Height) * sourceRect.Height);
                vertex[i] = new VertexPositionNormalTexture(new Vector3(points[i].X, points[i].Y, 0), new Vector3(0,0,1), uv);
            }

            VertexBuffer = VertexBuffer.Vertex.New(XenkoRenderer.GraphicsDevice, vertex);
            VertexBuffer.Reload = (graphicsResource) => ((VertexBuffer)graphicsResource).Recreate(vertex);
            VertexBufferBinding = new VertexBufferBinding(VertexBuffer, VertexPositionNormalTexture.Layout, vertex.Length, VertexPositionNormalTexture.Size);
            InputElementDescriptions = VertexBufferBinding.Declaration.CreateInputElements();
        }
 /// <summary>
 ///   Binds a single vertex buffer to the input assembler.
 /// </summary>
 /// <param name = "slot">Index of the slot to which to bind the vertex buffer.</param>
 /// <param name = "vertexBufferBinding">A binding for the input vertex buffer.</param>
 public void SetVertexBuffers(int slot, VertexBufferBinding vertexBufferBinding)
 {
     SetVertexBuffers(slot, new[] { vertexBufferBinding });
 }
Esempio n. 56
0
        internal void BuildRayDrawInfo(List <Vector3> rays, List <Vector3> hits, float polySize)
        {
            if (mVBRays != null)
            {
                mVBRays.Dispose();
            }
            if (mIBRays != null)
            {
                mIBRays.Dispose();
            }

            if (mHits != null)
            {
                mHits.Free();
            }

            if (rays.Count < 2)
            {
                return;
            }

            VPosNormCol0    [] segVerts = new VPosNormCol0[rays.Count * 3];
            VPosNormCol0    [] hitVerts = new VPosNormCol0[hits.Count * 8];

            UInt32        index   = 0;
            List <UInt32> indexes = new List <UInt32>();

            for (int i = 0; i < rays.Count; i += 2)
            {
                Color col = Mathery.RandomColor(mRand);

                //endpoint
                segVerts[index].Position = rays[i + 1];

                Vector3 lineVec = rays[i + 1] - rays[i];

                //get a perpindicular axis to the a to b axis
                //so the back side of the connection can flare out a bit
                Vector3 crossVec = Vector3.Cross(lineVec, Vector3.UnitY);

                crossVec.Normalize();

                Vector3 normVec = Vector3.Cross(crossVec, lineVec);

                normVec.Normalize();

                //crossVec	*=.2f;

                segVerts[index + 1].Position = rays[i] - crossVec;
                segVerts[index + 2].Position = rays[i] + crossVec;


                //scale up to visible
                segVerts[index].Position.X     *= polySize;
                segVerts[index].Position.Z     *= polySize;
                segVerts[index + 1].Position.X *= polySize;
                segVerts[index + 1].Position.Z *= polySize;
                segVerts[index + 2].Position.X *= polySize;
                segVerts[index + 2].Position.Z *= polySize;

                //upside down tri
                segVerts[index + 3].Position = segVerts[index + 2].Position;
                segVerts[index + 4].Position = segVerts[index + 1].Position;
                segVerts[index + 5].Position = segVerts[index].Position;

                segVerts[index].Color0     = col;
                segVerts[index + 1].Color0 = col;
                segVerts[index + 2].Color0 = col;
                segVerts[index + 3].Color0 = col;
                segVerts[index + 4].Color0 = col;
                segVerts[index + 5].Color0 = col;

                Half4 norm;
                norm.X = normVec.X;
                norm.Y = normVec.Y;
                norm.Z = normVec.Z;
                norm.W = 1f;
                segVerts[index].Normal     = norm;
                segVerts[index + 1].Normal = norm;
                segVerts[index + 2].Normal = norm;

                norm.X = -normVec.X;
                norm.Y = -normVec.Y;
                norm.Z = -normVec.Z;
                segVerts[index + 3].Normal = norm;
                segVerts[index + 4].Normal = norm;
                segVerts[index + 5].Normal = norm;

                indexes.Add(index);
                indexes.Add(index + 1);
                indexes.Add(index + 2);
                indexes.Add(index + 3);
                indexes.Add(index + 4);
                indexes.Add(index + 5);

                index += 6;
            }

            mVBRays  = VertexTypes.BuildABuffer(mGD.GD, segVerts, VertexTypes.GetIndex(segVerts[0].GetType()));
            mIBRays  = VertexTypes.BuildAnIndexBuffer(mGD.GD, indexes.ToArray());
            mVBBRays = VertexTypes.BuildAVBB(VertexTypes.GetIndex(segVerts[0].GetType()), mVBRays);

            mRaysIndexCount = indexes.Count;

            indexes.Clear();

            mHits = PrimFactory.CreateCubes(mGD.GD, hits, 5f);
        }