Пример #1
0
 public RenderOcclusion(ContentManager Content, GraphicsDevice GraphicsDevice)
 {
     effect = Content.Load<Effect>("occlusionshader");
       this.GraphicsDevice = GraphicsDevice;
       GenerateGeometry();
       GenerateInstanceVertexDeclaration();
       GenerateInstanceInformation(GraphicsDevice);
       bindings = new VertexBufferBinding[2];
       bindings[0] = new VertexBufferBinding(geometryBuffer);
       bindings[1] = new VertexBufferBinding(instanceBuffer, 0, 1);
 }
Пример #2
0
 public void setData(DataPoint[] dataPoints)
 {
     transforms = new Matrix[dataPoints.Length];
       Color[] colors = new Color[dataPoints.Length];
       for (int i = 0; i < dataPoints.Length; i++) {
     DataPoint point = dataPoints[i];
     transforms[i] = Matrix.CreateScale(1, 1, point.value) * PreOffset
       * VisualHelper.LatLngRotation(point.lat, point.lng);
     colors[i] = point.value == 0 ? Invisible : VisualHelper.hueToColor((1 - point.value) / 2);
       }
       GenerateInstanceInformation(GraphicsDevice, transforms, colors);
       bindings = new VertexBufferBinding[2];
       bindings[0] = new VertexBufferBinding(useTile ? tileGeometryBuffer : geometryBuffer);
       bindings[1] = new VertexBufferBinding(instanceBuffer, 0, 1);
 }
Пример #3
0
		private void GL_initialize()
		{
			// Load the YUV->RGBA Effect
			shaderProgram = new Effect(
				currentDevice,
				Resources.YUVToRGBAEffect
			);

			// Allocate the vertex buffer
			vertBuffer = new VertexBufferBinding(
				new VertexBuffer(
					currentDevice,
					VertexPositionTexture.VertexDeclaration,
					4,
					BufferUsage.WriteOnly
				)
			);
			vertBuffer.VertexBuffer.SetData(vertices);
		}
Пример #4
0
        public override void DrawInstanced(int drawCount)
        {
                        #if SILVERLIGHT
            Debug.ThrowError("VertexBuffer", "DrawInstanced is not supported, use DrawInstancedClassic instead");
                        #else
            var buffers = new X.VertexBufferBinding[2]
            {
                new X.VertexBufferBinding(vertexBuffer, 0, 0),
                new X.VertexBufferBinding(instanceBuffer.vertexBuffer, 0, 1)
            };
            video.Device.SetVertexBuffers(buffers);

            int primitiveCount;
            if (currentIndexBuffer == null)
            {
                primitiveCount = (vertexCount / primitiveVertexCount);
            }
            else
            {
                primitiveCount = (currentIndexBuffer.IndexCount / primitiveVertexCount);
            }
            video.Device.DrawInstancedPrimitives(primitiveTopology, 0, 0, vertexCount, 0, primitiveCount, drawCount);
                        #endif
        }
Пример #5
0
        /// <summary>
        /// HW インスタンシングで GameObject を描画します。
        /// </summary>
        void DrawGameObjectsWithHardwareInstancing()
        {
            instancingBlockEffect.View = view;
            instancingBlockEffect.Projection = projection;

            // インスタンス情報を一旦コピー
            for (int i = 0; i < gameObjects.Count; ++i)
            {
                objectInstances[i].Position = gameObjects.Items[i].Position;
                objectInstances[i].Scale = gameObjects.Items[i].Scale;
                objectInstances[i].RotateAxis = gameObjects.Items[i].RotateAxis;
                objectInstances[i].Rotation = gameObjects.Items[i].Rotation;
            }

            // インスタンス用の頂点バッファへ書き込む
            int offset = instanceVertexBuffer.SetData(objectInstances, 0, gameObjects.Count);

            mesh.LevelOfDetail = 0;

            // ゲームオブジェクトを描画
            foreach (var meshPart in mesh.MeshParts)
            {
                vertexBufferBindings[0] = new VertexBufferBinding(meshPart.VertexBuffer, meshPart.VertexOffset);
                vertexBufferBindings[1] = new VertexBufferBinding(instanceVertexBuffer.VertexBuffer, offset, 1);

                GraphicsDevice.SetVertexBuffers(vertexBufferBindings);
                GraphicsDevice.Indices = meshPart.IndexBuffer;

                instancingBlockEffect.DiffuseColor = meshPart.MeshMaterial.DiffuseColor;
                instancingBlockEffect.EmissiveColor = meshPart.MeshMaterial.EmissiveColor;
                instancingBlockEffect.SpecularColor = meshPart.MeshMaterial.SpecularColor;
                instancingBlockEffect.SpecularPower = meshPart.MeshMaterial.SpecularPower;

                instancingBlockEffect.Pass.Apply();

                GraphicsDevice.DrawInstancedPrimitives(
                    PrimitiveType.TriangleList, 0, 0,
                    meshPart.NumVertices, meshPart.StartIndex, meshPart.PrimitiveCount, gameObjects.Count);
            }
        }
Пример #6
0
        /// <summary>
        /// GameObject をそのまま頂点バッファへ設定する HW インスタンシングで GameObject を描画します。
        /// </summary>
        void DrawGameObjectsWithDirectMapping()
        {
            instancingBlockEffect.View = view;
            instancingBlockEffect.Projection = projection;

            // インスタンスをそのまま頂点バッファへコピー
            int offset = directMappingVertexBuffer.SetData(gameObjects.Items, 0, gameObjects.Count);

            mesh.LevelOfDetail = 0;

            // ゲームオブジェクトを描画
            foreach (var meshPart in mesh.MeshParts)
            {
                vertexBufferBindings[0] = new VertexBufferBinding(meshPart.VertexBuffer, meshPart.VertexOffset);
                vertexBufferBindings[1] = new VertexBufferBinding(directMappingVertexBuffer.VertexBuffer, offset, 1);

                GraphicsDevice.SetVertexBuffers(vertexBufferBindings);
                GraphicsDevice.Indices = meshPart.IndexBuffer;

                instancingBlockEffect.DiffuseColor = meshPart.MeshMaterial.DiffuseColor;
                instancingBlockEffect.EmissiveColor = meshPart.MeshMaterial.EmissiveColor;
                instancingBlockEffect.SpecularColor = meshPart.MeshMaterial.SpecularColor;
                instancingBlockEffect.SpecularPower = meshPart.MeshMaterial.SpecularPower;

                instancingBlockEffect.Pass.Apply();

                GraphicsDevice.DrawInstancedPrimitives(
                    PrimitiveType.TriangleList, 0, 0,
                    meshPart.NumVertices, meshPart.StartIndex, meshPart.PrimitiveCount, gameObjects.Count);
            }
        }
Пример #7
0
        public void Draw(GameTime gameTime, Effect effect, CDLODSelection selection)
        {
            if (selection.SelectedNodeCount == 0) return;

            // create instances
            for (int i = 0; i < selection.SelectedNodeCount; i++)
                selection.GetPatchInstanceVertex(i, out instances[i]);

            var offset = instanceVertexBuffer.SetData(instances, 0, selection.SelectedNodeCount);

            vertexBufferBindings[0] = new VertexBufferBinding(patchMesh.VertexBuffer, 0);
            vertexBufferBindings[1] = new VertexBufferBinding(instanceVertexBuffer.VertexBuffer, offset, 1);

            GraphicsDevice.SetVertexBuffers(vertexBufferBindings);
            GraphicsDevice.Indices = patchMesh.IndexBuffer;

            foreach (var pass in effect.CurrentTechnique.Passes)
            {
                pass.Apply();
                GraphicsDevice.DrawInstancedPrimitives(
                    PrimitiveType.TriangleList, 0, 0,
                    patchMesh.NumVertices, 0, patchMesh.PrimitiveCount, selection.SelectedNodeCount);
            }
        }
Пример #8
0
        public override void DrawInstanced(int drawCount)
        {
            #if SILVERLIGHT
            Debug.ThrowError("VertexBuffer", "DrawInstanced is not supported, use DrawInstancedClassic instead");
            #else
            var buffers = new X.VertexBufferBinding[2]
            {
                new X.VertexBufferBinding(vertexBuffer, 0, 0),
                new X.VertexBufferBinding(instanceBuffer.vertexBuffer, 0, 1)
            };
            video.Device.SetVertexBuffers(buffers);

            int primitiveCount;
            if (currentIndexBuffer == null) primitiveCount = (vertexCount/primitiveVertexCount);
            else primitiveCount = (currentIndexBuffer.IndexCount/primitiveVertexCount);
            video.Device.DrawInstancedPrimitives(primitiveTopology, 0, 0, vertexCount, 0, primitiveCount, drawCount);
            #endif
        }
Пример #9
0
        /// <summary>
        /// Gets vertex buffers bound to the input slots.
        /// </summary>
        /// <returns>The vertex buffer bindings.</returns>
        public VertexBufferBinding[] Get()
        {
            var bindings = new VertexBufferBinding[Count];
            for (int i = 0; i < bindings.Length; i++)
                bindings[i] = new VertexBufferBinding(
                    _vertexBuffers[i],
                    _vertexOffsets[i],
                    InstanceFrequencies[i]);

            return bindings;
        }
Пример #10
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="drawer">パーティクルを描画するためのシェーダー</param>
		/// <param name="device"></param>
		/// <param name="tex">パーティクルのテクスチャ</param>
		/// <param name="number">パーティクル最大数</param>
		public ParticleEngine(Effect drawer, GraphicsDevice device, Texture2D tex, ushort number,
			ParticleMode mode, Matrix projection, Vector2 fieldSize)
			:base(tex, number)
		{
			Device = device;
			
			//int[] x = { -1, -1, 1, 1 };
			//int[] y = { 1, -1, -1, 1 };
			
			VertexDataBuffer = new DynamicVertexBuffer(device, typeof(ParticleVertex), ParticleNum * 1, BufferUsage.WriteOnly);

		
			IndexVertexBuffer = new VertexBuffer(device, typeof(ParticleIndexVertex), indexVertex.Length, BufferUsage.WriteOnly);
			IndexVertexBuffer.SetData(indexVertex);

			short[] index = new short[] { 0, 1, 2, 0, 2, 3 };
			Index = new IndexBuffer(device, IndexElementSize.SixteenBits, index.Length, BufferUsage.WriteOnly);
			Index.SetData(index);
			
			Drawer = drawer;
			InitEffectParam();
			Mode = mode;
			Projection = projection;
			FieldSize = fieldSize;
			BlendColor = Vector4.One;
			Enable = true;

			SetVertex();//初期化
			bind = new VertexBufferBinding(VertexDataBuffer, 0, 1);
		}
        public virtual void Draw(GameTime gameTime, Effect thisEffect)
        {
            if (!Visible || !Enabled)
                return;

            World = Matrix.CreateScale(Scale) * Matrix.CreateFromQuaternion(Rotation) * Matrix.CreateTranslation(Position);
            timer = (float)gameTime.TotalGameTime.TotalSeconds;

            if (instanceTransformMatrices.Count == 0)
                return;

            // If we have more instances than room in our vertex buffer, grow it to the neccessary size.
            // only grow if we need more room?
            if ((instanceVertexBuffer == null) || (instanceTransformMatrices.Count > instanceVertexBuffer.VertexCount))
            {
                if (instanceVertexBuffer != null)
                    instanceVertexBuffer.Dispose();

                instanceVertexBuffer = new DynamicVertexBuffer(GraphicsDevice, instanceVertexDeclaration, instanceTransformMatrices.Count, BufferUsage.WriteOnly);

                // Transfer the latest instance transform matrices into the instanceVertexBuffer.
            }

            if (UpdateInstances)
            {
                tempMatrixList.Clear();
                tempMatrixList.EnsureCapacity(instanceTransformMatrices.Values.Count);
                instanceTransformMatrices.Values.CopyTo(tempMatrixList.GetRawArray(), 0);
                instanceVertexBuffer.SetData(tempMatrixList.GetRawArray(), 0, instanceTransformMatrices.Count, SetDataOptions.Discard);
            }



            if (thisEffect.CurrentTechnique.Name == "ShadowMapH") // Shadow Map
            {
                thisEffect.CurrentTechnique = thisEffect.Techniques["ShadowMapHP"];

                if (FixedCameraPos == Vector3.One * 10000)
                    thisEffect.Parameters["EyePosition"].SetValue(Camera.Position);
                else
                    thisEffect.Parameters["EyePosition"].SetValue(FixedCameraPos);

                thisEffect.Parameters["World"].SetValue(World);
            }
            else
            {
                thisEffect.Parameters["color"].SetValue(Color.ToVector4());
                
                thisEffect.Parameters["time"].SetValue(timer);

                // Texture
                if (TextureMaterials.Count > 0)
                    thisEffect.Parameters["textureMat"].SetValue(AssetManager.GetAsset<Texture2D>(TextureMaterials[0]));
                else
                    thisEffect.Parameters["textureMat"].SetValue(blank);

                if (thisEffect.Parameters["BumpMap"] != null)
                {
                    if (NormalMaterials.Count > 0)
                        thisEffect.Parameters["BumpMap"].SetValue(AssetManager.GetAsset<Texture2D>(NormalMaterials[0]));
                    else
                        thisEffect.Parameters["BumpMap"].SetValue(blank_normal);
                }

                if (FixedCameraPos == Vector3.One * 10000)
                    thisEffect.Parameters["EyePosition"].SetValue(Camera.Position);
                else
                    thisEffect.Parameters["EyePosition"].SetValue(FixedCameraPos);

                thisEffect.Parameters["vp"].SetValue(Camera.View * Camera.Projection);
                thisEffect.Parameters["World"].SetValue(World);

                if (!DepthContribution)
                    thisEffect.Parameters["depthMap"].SetValue(((BaseDeferredRenderGame)Game).DepthMap);

            }

            VertexBufferBindingArray[0] = new VertexBufferBinding(modelVertexBuffer, 0, 0);
            VertexBufferBindingArray[1] = new VertexBufferBinding(instanceVertexBuffer, 0, 1);

            GraphicsDevice.SetVertexBuffers(VertexBufferBindingArray);

            Game.GraphicsDevice.BlendState = thisBlendState;
            Game.GraphicsDevice.DepthStencilState = thisDepthStencilState;
            
            thisEffect.CurrentTechnique.Passes[0].Apply();
            GraphicsDevice.Indices = indexBuffer;

            Game.GraphicsDevice.DrawInstancedPrimitives(PrimitiveType.TriangleList, 0, 0,
                                                   modelVertexBuffer.VertexCount, 0,
                                                   2,
                                                   instanceTransformMatrices.Count);

        }
Пример #12
0
        private void InitializeBuffers(List<Block> blocks)
        {
            List<VertexNormalTexture> customVertexList = new List<VertexNormalTexture>();
            List<int> indicesList = new List<int>();
            int indexerValue = 0;

            //new Block(new Vector3i(0,0,0),1),
            CreateCube(ref customVertexList, ref indicesList, ref indexerValue);

            foreach (Block block in blocks)
            {
                //top face

                /*for (int i = 0; i < 4; i++)
                {
                    indicesList.Add(indexerValue++);
                }*/
            }

            MyVertexBuffer = new VertexBuffer(Device, VertexNormalTexture.VertexDeclaration, customVertexList.Count, BufferUsage.WriteOnly);
            MyVertexBuffer.SetData(customVertexList.ToArray());

            MyIndexBuffer = new IndexBuffer(Device, typeof(int), indicesList.Count, BufferUsage.WriteOnly);
            MyIndexBuffer.SetData(indicesList.ToArray());

            NumVertices = customVertexList.Count;
            NumTriangles = indicesList.Count / 3;

            InitializeInstances(blocks);

            _bindings = new VertexBufferBinding[2];
            _bindings[0] = new VertexBufferBinding(MyVertexBuffer, 0);
            _bindings[1] = new VertexBufferBinding(_instanceBuffer, 0, 1);
        }
Пример #13
0
            public void NakedUpdate()
            {
                // Initialize the vertex buffer. Should only hold a face.
                    geometryBuffer = new VertexBuffer(BlockGame.graphics.GraphicsDevice, Vertex.VertexDeclaration, Face.Vertices.Length, BufferUsage.WriteOnly);

                    indexBuffer = new IndexBuffer(BlockGame.graphics.GraphicsDevice, typeof(short), Face.Indices.Length, BufferUsage.WriteOnly);

                    instanceBuffer = new VertexBuffer(BlockGame.graphics.GraphicsDevice, FaceInstance.VertexDeclaration, Size, BufferUsage.WriteOnly);

                    // Set the indices
                    indexBuffer.SetData<short>(Face.Indices);

                    // Set the buffer to contain the face.
                    geometryBuffer.SetData<Vertex>(Face.Vertices);

                    // Set buffer to the new faces.
                    instanceBuffer.SetData<FaceInstance>(Faces, 0, Size);

                    // Set the buffer.
                    BlockGame.graphics.GraphicsDevice.Indices = indexBuffer;

                    bindings = new VertexBufferBinding[2];
                    bindings[0] = new VertexBufferBinding(geometryBuffer);
                    bindings[1] = new VertexBufferBinding(instanceBuffer, 0, 1);
                    Console.WriteLine("Updated buffer!");
                    NeedsUpdating = false;
                    Drawn = false;
            }
Пример #14
0
        public void Draw(GameTime gameTime, Selection selection)
        {
            if (selection.SelectedNodeCount == 0) return;

            // create instances
            for (int i = 0; i < selection.SelectedNodeCount; i++)
                selection.GetPatchInstanceVertex(i, out instances[i]);

            var offset = instanceVertexBuffer.SetData(instances, 0, selection.SelectedNodeCount);

            vertexBufferBindings[0] = new VertexBufferBinding(patchMesh.VertexBuffer, 0);
            vertexBufferBindings[1] = new VertexBufferBinding(instanceVertexBuffer.VertexBuffer, offset, 1);

            GraphicsDevice.SetVertexBuffers(vertexBufferBindings);
            GraphicsDevice.Indices = patchMesh.IndexBuffer;
            GraphicsDevice.DepthStencilState = DepthStencilState.Default;

            // Prepare effect parameters.
            // per a selection (a terrain).
            effect.TerrainOffset = selection.TerrainOffset;
            effect.TerrainScale = selection.TerrainScale;
            effect.HeightMap = selection.HeightMapTexture;
            effect.View = selection.View;
            effect.Projection = selection.Projection;
            // render settings.
            effect.AmbientLightColor = ambientLightColor;
            effect.LightDirection = lightDirection;
            effect.DiffuseLightColor = diffuseLightColor;
            effect.LightEnabled = LightEnabled;

            // WhiteSolid tequnique
            if (WhiteSolidVisible)
                DrawPatchInstances(effect.WhiteSolidTequnique, selection.SelectedNodeCount);

            // HeightColor tequnique
            if (HeightColorVisible)
                DrawPatchInstances(effect.HeightColorTequnique, selection.SelectedNodeCount);

            // Wireframe tequnique
            if (WireframeVisible)
            {
                var wireframeTerrainOffset = selection.TerrainOffset;
                wireframeTerrainOffset.Y += WireframeGap;
                effect.TerrainOffset = wireframeTerrainOffset;
                DrawPatchInstances(effect.WireframeTequnique, selection.SelectedNodeCount);
                effect.TerrainOffset = selection.TerrainOffset;
            }

            if (NodeBoundingBoxVisible)
            {
                debugEffect.View = selection.View;
                debugEffect.Projection = selection.Projection;

                SelectedNode selectedNode;
                BoundingBox box;
                for (int i = 0; i < selection.SelectedNodeCount; i++)
                {
                    selection.GetSelectedNode(i, out selectedNode);

                    selectedNode.GetBoundingBox(
                        ref selection.TerrainOffset, settings.PatchScale, settings.HeightScale, out box);
                    var level = selectedNode.Level;
                    level %= 4;
                    boundingBoxDrawer.Draw(ref box, debugEffect, ref debugLevelColors[level]);
                }
            }
        }
Пример #15
0
 /// <summary>
 /// Updates the array with VertexBinding
 /// </summary>
 private void UpdateBindingArray()
 {
     for (int i = 0; i < VertexBindings.Length; i++)
     {
         BindingInfo inf = _bindings[i];
         VertexBufferBinding bufferBinding = new VertexBufferBinding(inf.BufferObject.Buffer,
             inf.VertexOffset, inf.Frequency);
         VertexBindings[i] = bufferBinding;
     }
 }
Пример #16
0
		public void ApplyVertexAttributes(
			VertexBufferBinding[] bindings,
			int numBindings,
			bool bindingsUpdated,
			int baseVertex
		) {
			if (supportsBaseVertex)
			{
				baseVertex = 0;
			}

			if (	bindingsUpdated ||
				baseVertex != ldBaseVertex ||
				currentEffect != ldEffect ||
				currentTechnique != ldTechnique ||
				currentPass != ldPass ||
				effectApplied	)
			{
				/* There's this weird case where you can have multiple vertbuffers,
				 * but they will have overlapping attributes. It seems like the
				 * first buffer gets priority, so start with the last one so the
				 * first buffer's attributes are what's bound at the end.
				 * -flibit
				 */
				for (int i = numBindings - 1; i >= 0; i -= 1)
				{
					BindVertexBuffer(bindings[i].VertexBuffer.buffer);
					VertexDeclaration vertexDeclaration = bindings[i].VertexBuffer.VertexDeclaration;
					IntPtr basePtr = (IntPtr) (
						vertexDeclaration.VertexStride *
						(bindings[i].VertexOffset + baseVertex)
					);
					foreach (VertexElement element in vertexDeclaration.elements)
					{
						int attribLoc = MojoShader.MOJOSHADER_glGetVertexAttribLocation(
							XNAToGL.VertexAttribUsage[(int) element.VertexElementUsage],
							element.UsageIndex
						);
						if (attribLoc == -1)
						{
							// Stream not in use!
							continue;
						}
						attributeEnabled[attribLoc] = true;
						VertexAttribute attr = attributes[attribLoc];
						uint buffer = (bindings[i].VertexBuffer.buffer as OpenGLBuffer).Handle;
						IntPtr ptr = basePtr + element.Offset;
						VertexElementFormat format = element.VertexElementFormat;
						bool normalized = XNAToGL.VertexAttribNormalized(element);
						if (	attr.CurrentBuffer != buffer ||
							attr.CurrentPointer != ptr ||
							attr.CurrentFormat != element.VertexElementFormat ||
							attr.CurrentNormalized != normalized ||
							attr.CurrentStride != vertexDeclaration.VertexStride	)
						{
							glVertexAttribPointer(
								attribLoc,
								XNAToGL.VertexAttribSize[(int) format],
								XNAToGL.VertexAttribType[(int) format],
								normalized,
								vertexDeclaration.VertexStride,
								ptr
							);
							attr.CurrentBuffer = buffer;
							attr.CurrentPointer = ptr;
							attr.CurrentFormat = format;
							attr.CurrentNormalized = normalized;
							attr.CurrentStride = vertexDeclaration.VertexStride;
						}
						if (SupportsHardwareInstancing)
						{
							attributeDivisor[attribLoc] = bindings[i].InstanceFrequency;
						}
					}
				}
				FlushGLVertexAttributes();

				ldBaseVertex = baseVertex;
				ldEffect = currentEffect;
				ldTechnique = currentTechnique;
				ldPass = currentPass;
				effectApplied = false;
				ldVertexDeclaration = null;
				ldPointer = IntPtr.Zero;
			}

			MojoShader.MOJOSHADER_glProgramReady();
			MojoShader.MOJOSHADER_glProgramViewportFlip(flipViewport);
		}
Пример #17
0
        public void DrawInstances(Effect effect, ref VertexBuffer instanceBuffer, int instanceCount)
        {
            GraphicsDevice device = effect.GraphicsDevice;
            VertexBufferBinding[] bindings = new VertexBufferBinding [2];
            bindings [0] = new VertexBufferBinding (vertexBuffer);
            bindings [1] = new VertexBufferBinding (instanceBuffer, 0, 1);
            device.SetVertexBuffers (bindings);
            device.Indices = indexBuffer;

            foreach (EffectPass effectPass in effect.CurrentTechnique.Passes) {
                effectPass.Apply ();
                int primitiveCount = indices.Count / 3;
                device.DrawInstancedPrimitives (PrimitiveType.TriangleList, 0, 0, vertices.Count, 0, primitiveCount, instanceCount);
            }
        }
Пример #18
0
 public void toggleTile()
 {
     useTile = !useTile;
       bindings = new VertexBufferBinding[2];
       bindings[0] = new VertexBufferBinding(useTile ? tileGeometryBuffer : geometryBuffer);
       bindings[1] = new VertexBufferBinding(instanceBuffer, 0, 1);
 }