/// <summary> /// パーティクルの更新 /// </summary> protected override void UpdateParticle() { particleActiveBuffer.SetCounterValue(0); cs.SetFloat("_DT", Time.deltaTime); cs.SetFloat("_LifeTime", lifeTime); cs.SetBuffer(updateKernel, "_Particles", particleBuffer); cs.SetBuffer(updateKernel, "_DeadList", particlePoolBuffer); cs.SetBuffer(updateKernel, "_ActiveList", particleActiveBuffer); cs.Dispatch(updateKernel, particleNum / THREAD_NUM_X, 1, 1); particleActiveCountBuffer.SetData(particleCounts); ComputeBuffer.CopyCount(particleActiveBuffer, particleActiveCountBuffer, 0); particleActiveCountBuffer.GetData(particleCounts); particleActiveNum = particleCounts[0]; }
void Update() { int[] args_init = new int[] { 0, 1, 0, 0 }; buffer_args.SetData(args_init); buffer_visible.SetCounterValue(0); // 運動 Matrix4x4 mV = Camera.main.worldToCameraMatrix; Matrix4x4 mP = Camera.main.projectionMatrix; Matrix4x4 mVP = mP * mV; computeShader.SetMatrix("mVP", mVP); computeShader.SetFloat("deltaTime", Time.deltaTime); computeShader.Dispatch(updateKernel, maxParticleNum / 32, 1, 1); ComputeBuffer.CopyCount(buffer_visible, buffer_args, 0); }
/// <summary> /// Performs the Marching Cubes algorithm and generates the mesh. /// </summary> /// <param name="cells">The cells of a CellularAutomaton</param> override public void Render(ComputeBuffer cells) { mesh.SetCounterValue(0); marchingCubesCS.SetBuffer(marchingCubesCSKernel, "currentGeneration", cells); marchingCubesCS.Dispatch(marchingCubesCSKernel, dimensions.x, dimensions.y * 2, dimensions.z * 2); RenderTexture3D(cells); ComputeBuffer.CopyCount(mesh, args, 0); #if REALISTIC if (!type.Equals(Type.CUBES)) { RenderRealisticWater(); } #endif }
// Update is called once per frame void Update() { rendererCS.SetTexture(kernelMain, "_densityTexture", DFMRef_.densityTexture_); rendererCS.SetTexture(kernelMain, "_colorTexture", DFMRef_.colorTexture_); appendVertexBuffer.SetCounterValue(0); rendererCS.SetFloat("_isoLevel", isoLevel); rendererCS.SetFloat("_time", Time.time); rendererCS.Dispatch(kernelMain, DFMRef_.Resolution / 8, DFMRef_.Resolution / 8, DFMRef_.Resolution / 8); //ComputeBuffer.CopyCount(appendVertexBuffer, argBuffer, 0); //MarchingCubesCS.SetBuffer(kernelMultiply, "_numVertices", argBuffer); //MarchingCubesCS.Dispatch(kernelMultiply, 1, 1, 1); //int[] args2 = new int[] { 0, 1, 0, 0 }; //argBuffer.GetData(args2); //args2[0] *= 3; //argBuffer.SetData(args); //Debug.Log("Vertex count:" + args2[0]); ComputeBuffer.CopyCount(appendVertexBuffer, argBuffer, 0); //int[] args2 = new int[] { 0, 1, 0, 0, 0 }; //argBuffer.GetData(args2); //Debug.Log("Index count:" + args2[0] + " Instances count:" + args2[1]); densityFieldRendererCS.SetBuffer(kernelInstances, "_numVertices", argBuffer); densityFieldRendererCS.Dispatch(kernelInstances, 1, 1, 1); mat.SetPass(0); mat.SetBuffer("triangles", appendVertexBuffer); mat.SetBuffer("indexStructure", argBuffer); mat.SetMatrix("_LocalToWorld", Matrix4x4.Translate(-transform.position) * transform.localToWorldMatrix); mat.SetMatrix("_WorldToLocal", transform.worldToLocalMatrix); if (renderDensityField) { Graphics.DrawMeshInstancedIndirect( emptyMesh, 0, mat, new Bounds(transform.position, transform.lossyScale * 1.5f), argBuffer); } }
/// <summary> /// Handles batched GPU exec. /// </summary> public static void Update() { // Not Empty and not reading back stuffs if ((!(CSGenerationQueue.First == null)) && (!csgen_readingBack)) { int _count = 0; var p = CSGenerationQueue.First; CSGenerationQueue_waitForReadback = new GeometryIndependentPass[cs_generation_batchsize]; while (p != null && _count < cs_generation_batchsize) { host_csgen_chkBuf[_count * 3 + 0] = p.Value.chunk.positionOffset.x; host_csgen_chkBuf[_count * 3 + 1] = p.Value.chunk.positionOffset.y; host_csgen_chkBuf[_count * 3 + 2] = p.Value.chunk.positionOffset.z; CSGenerationQueue_waitForReadback[_count] = p.Value; _count += 1; var _p = p; p = p.Next; CSGenerationQueue.Remove(_p); } // Upload buffers to GPU csgen_chkBuf.SetData(host_csgen_chkBuf); csgen_structureBuf.SetCounterValue(0); // Run cs_generation.Dispatch(0, 4 * _count, 4, 4); //cs_generation.Dispatch(0, 4 * cs_generation_batchsize, 4, 4); ComputeBuffer.CopyCount(csgen_structureBuf, csgen_structureCountBuf, 0); // Set flags for reading back blkBufOK = false; strBufOK = false; strlenBufOK = false; csgen_readingBack = true; // Wait for readback UnityEngine.Rendering.AsyncGPUReadback.Request(csgen_blkBuf, batched_OnGPUComplete); UnityEngine.Rendering.AsyncGPUReadback.Request(csgen_structureBuf, batched_OnGPUComplete_structure); UnityEngine.Rendering.AsyncGPUReadback.Request(csgen_structureCountBuf, batched_OnGPUComplete_structureCount); } }
public MarchingCubesController.Mesh ExportMesh() { int[] args = new int[] { 0, 1, 0, 0 }; argBuffer.SetData(args); ComputeBuffer.CopyCount(appendVertexBuffer, argBuffer, 0); argBuffer.GetData(args); int numTris = args[0]; int numVerts = args[0] * 3; // 18 floats per Tri // x,y,z,nx,ny,nz // x,y,z,nx,ny,nz // x,y,z,nx,ny,nz float[] dataCPU = new float[numTris * 18]; appendVertexBuffer.GetData(dataCPU); MarchingCubesController.Mesh outmesh = new MarchingCubesController.Mesh(); outmesh.faces = new int[numVerts]; outmesh.verts = new Vector3[numVerts]; for (int i = 0; i < numVerts; i++) { outmesh.faces[i] = i; } int vertIndex = 0; for (int i = 0; i < numTris; i++) { int addr = i * 18; outmesh.verts[vertIndex++] = new Vector3(dataCPU[addr++], dataCPU[addr++], dataCPU[addr++]); Vector3 n0 = new Vector3(dataCPU[addr++], dataCPU[addr++], dataCPU[addr++]); outmesh.verts[vertIndex++] = new Vector3(dataCPU[addr++], dataCPU[addr++], dataCPU[addr++]); Vector3 n1 = new Vector3(dataCPU[addr++], dataCPU[addr++], dataCPU[addr++]); outmesh.verts[vertIndex++] = new Vector3(dataCPU[addr++], dataCPU[addr++], dataCPU[addr++]); Vector3 n2 = new Vector3(dataCPU[addr++], dataCPU[addr++], dataCPU[addr++]); } doRender = false; return(outmesh); }
void EmitKernel() { argsBuffer.SetData(particleArgs); ComputeBuffer.CopyCount(particlePoolBuffer, argsBuffer, 0); argsBuffer.GetData(particleArgs); int poolNum = particleArgs[0]; if (poolNum < emitNum) { return; } computeShader.SetBuffer(emitKernelIndex, "_ParticlePool", particlePoolBuffer); computeShader.SetBuffer(emitKernelIndex, "_Particles", particleBuffer); computeShader.Dispatch(emitKernelIndex, emitNum / THREAD_NUM_X, 1, 1); }
public void DispatchEmitIndirect(ComputeBuffer uploads) { int emitKernel = computeShader.FindKernel("EmitIndirect"); ComputeBuffer.CopyCount(uploads, emitCounter, 0); ComputeBuffer.CopyCount(deadBuffer, counter, 0); computeShader.SetInt("UploadCounterOffset", 0); computeShader.SetInt("CounterOffset", 0); computeShader.SetFloat("Lifetime", 1000); computeShader.SetBuffer(emitKernel, "UploadCounter", emitCounter); computeShader.SetBuffer(emitKernel, "Counter", counter); computeShader.SetBuffer(emitKernel, "Uploads", uploads); computeShader.SetBuffer(emitKernel, "Pool", deadBuffer); computeShader.SetBuffer(emitKernel, "PositionsWRITE", positionsBuffer); computeShader.SetBuffer(emitKernel, "VelocitiesWRITE", velocitiesBuffer); computeShader.SetBuffer(emitKernel, "Lifetimes", lifetimesBuffer); computeShader.Dispatch(emitKernel, Groups(uploads.count), 1, 1); }
private void Update() { MarchingCubesCS.SetTexture(kernelMC, "_densityTexture", DensityTexture); appendVertexBuffer.SetCounterValue(0); MarchingCubesCS.Dispatch(kernelMC, Resolution / 8, Resolution / 8, Resolution / 8); int[] args = new int[] { 0, 1, 0, 0 }; argBuffer.SetData(args); ComputeBuffer.CopyCount(appendVertexBuffer, argBuffer, 0); argBuffer.GetData(args); args[0] *= 3; argBuffer.SetData(args); Debug.Log("Vertex count:" + args[0]); }
private float2[] GetTerritoryPixels(float[] _searchColFloat4, Texture2D _indirectionMap) { getTerritoryPixelsBuffer.SetCounterValue(0); getTerritoryPixelsCS.SetFloats("SearchColor", _searchColFloat4); getTerritoryPixelsCS.SetTexture(0, "Indirection", _indirectionMap); getTerritoryPixelsCS.Dispatch(0, ProvinceIdTex.width / 32, ProvinceIdTex.height / 32, 1); int[] args = new int[] { 0, 1, 0, 0 }; getTerritoryPixelsArgBuffer.SetData(args); ComputeBuffer.CopyCount(getTerritoryPixelsBuffer, getTerritoryPixelsArgBuffer, 0); getTerritoryPixelsArgBuffer.GetData(args); float2[] result = new float2[args[0]]; getTerritoryPixelsBuffer.GetData(result, 0, 0, args[0]); return(result); }
void CreateMesh() { m_triangleBuffer.SetCounterValue(0); var mWarpCount = Mathf.CeilToInt((float)m_currentNumParticles / WARP_SIZE); m_computeShader.Dispatch(m_kernelIDs["GenerateMesh"], mWarpCount, 1, 1); int[] args = new int[] { 0, 1, 0, 0 }; m_triangleArgBuffer.SetData(args); ComputeBuffer.CopyCount(m_triangleBuffer, m_triangleArgBuffer, 0); m_triangleArgBuffer.GetData(args); args[0] *= 3; m_triangleArgBuffer.SetData(args); Debug.Log("Vertex count:" + args[0]); }
public bool onRender(CommandBuffer _cmd) { // Indirect args uint[] args = new uint[ARG_BUFFER_SIZE] { 0, 0, 0, 0, 0 }; const int SUBMESH_INDEX = 0; const int SHADER_PASS = 0; if (cube) { args[0] = (uint)cube.GetIndexCount(SUBMESH_INDEX); // index count per instance args[1] = (uint)PARTICLE_COUNT; // instance count args[2] = (uint)cube.GetIndexStart(SUBMESH_INDEX); // start index location args[3] = (uint)cube.GetBaseVertex(SUBMESH_INDEX); // base vertex location args[4] = (uint)0; // start instance location } argBuffer.SetData(args); // cull if (enableGpuCulling) { ComputeBuffer.CopyCount(cullResultBuffer, argBuffer, sizeof(uint)); material.SetBuffer(particleBufferID, cullResultBuffer); } else { material.SetBuffer(particleBufferID, particleBuffer); } _cmd.DrawMeshInstancedIndirect( cube, SUBMESH_INDEX, material, SHADER_PASS, argBuffer ); return(true); }
public void Generate() { // Get the object's mesh filter meshFilter = transform.GetComponent <MeshFilter>(); int threadsPerAxis = Mathf.CeilToInt(resolution / 8.0f); // Converts range 0 / 1 to -1 / 1 float trueSurfaceLevel = surfaceLevel * 2 - 1; // Create compute buffers for data extraction CreateBuffers(); // Setup the marchingCubes shader triangleBuffer.SetCounterValue(0); shader.SetBuffer(0, "triangles", triangleBuffer); shader.SetInt("offset", offset); shader.SetInt("pointsPerAxis", resolution); shader.SetFloat("pointRes", pointResolution); shader.SetFloat("surfaceLevel", trueSurfaceLevel); shader.SetFloat("frequency", frequency); shader.SetBool("smoothMesh", smoothMesh); // Run the kernel shader.Dispatch(0, threadsPerAxis, threadsPerAxis, threadsPerAxis); // Get number of triangles in the triangle buffer ComputeBuffer.CopyCount(triangleBuffer, triCountBuffer, 0); int[] triCountArray = { 0 }; triCountBuffer.GetData(triCountArray); int numTris = triCountArray[0]; // Get triangle data from shader Tri[] triangles = new Tri[numTris]; triangleBuffer.GetData(triangles, 0, 0, numTris); // Convert the tri data into mesh data Mesh m = GenerateMesh(triangles); // Apply the mesh to the object meshFilter.mesh = m; ReleaseBuffers(); }
private void Update() { //Make filter change, so that we see different result if (!staticTest) { if (_filter >= _amount) { _filter = 0; } else { _filter++; } } //Reset count cbPoints.SetCounterValue(0); //Direct dispatch to do filter shader.SetFloat("_Filter", _filter); shader.SetBuffer(_kernelDirect, "pointBufferOutput", cbPoints); shader.Dispatch(_kernelDirect, _amount * (int)_threadsizeX, (int)_threadsizeY, (int)_threadsizeZ); //Copy Count ComputeBuffer.CopyCount(cbPoints, cbDrawArgs, 0); //Indirect dispatch to only execute kernel on filtered data shader.SetBuffer(_kernelIndirect, "pointBuffer", cbPoints); shader.DispatchIndirect(_kernelIndirect, cbDrawArgs, 0); //Read data from GPU int[] ff = new int[cbPoints.count]; cbPoints.GetData(ff); int[] aa = new int[args.Length]; cbDrawArgs.GetData(aa); //Output tx.text = "Indirect \n cbDrawArgs = [0]:" + aa[0] + " [1]:" + aa[1] + " [2]:" + aa[2] + " [3]:" + aa[3] + " \n cbPoints = " + cbPoints.count; for (int i = 0; i < ff.Length; i++) { tx.text += "\n" + "ff[" + i + "] = " + ff[i]; } }
void UpdateBuffers() { /// reset the append buffer counter, /// this is important! otherwise we'll keep appending to a buffer indefinitely! positionAppendBuffer.SetCounterValue(0); /// TODO this only works with POT, integral sqrt vals int bs = instanceCount / 64; positionComputeShader.Dispatch(positionComputeKernelId, bs, 1, 1); positionComputeShader.SetBuffer(positionComputeKernelId, "positionBuffer", positionAppendBuffer); positionComputeShader.SetFloat("_Dim", Mathf.Sqrt(instanceCount)); /// as we don't know exactly how many positions were output, we use this function /// to copy the count from positionAppendBuffer to argsBuffer, which will be used for rendering. /// The offset 4 is because the instance count is placed in args[1] for the DrawMeshInstancedIndirect /// + info https://docs.unity3d.com/ScriptReference/ComputeBuffer.CopyCount.html ComputeBuffer.CopyCount(positionAppendBuffer, argsBuffer, 4); }
private void DispatchEmit(List <Vector4> emitList, int minPoolCount, int flags, float lifeTime) { if (emitList.Count > 0) { ComputeBuffer.CopyCount(pool, counter, 0); uploads.SetData(emitList); computeShader.SetInt("_CounterOffset", 0); computeShader.SetInt("_EmitCount", emitList.Count); computeShader.SetInt("_EmitMinPoolCount", minPoolCount); computeShader.SetInt("_Flags", flags); computeShader.SetFloat("_LifeTime", lifeTime); computeShader.SetBuffer(emitKernel, propCounter, counter); computeShader.SetBuffer(emitKernel, propUploads, uploads); computeShader.SetBuffer(emitKernel, propPool, pool); computeShader.SetBuffer(emitKernel, propParticles, particles); computeShader.Dispatch(emitKernel, uploads.count / threadCount, 1, 1); emitList.Clear(); } }
void Update() { //Reset count particleFilteredResultBuffer.SetCounterValue(0); //Direct dispatch to do filter computeShader.SetFloat("_Time", Time.time); computeShader.Dispatch(_kernelDirect, particleCount, 1, 1); //Copy Count - visually no change but this is necessary in terms of performance! //because without this, shader will draw full amount of particles, just overlapping //Check Profiler > GPU > Hierarchy search Graphics.DrawProcedural > GPU time //4 is the offset byte. "particleCount" is the second int in args[], and 1 int = 4 bytes ComputeBuffer.CopyCount(particleFilteredResultBuffer, argsBuffer, 4); //Draw //3*4 is the offset byte, where the indirect draw in args starts Graphics.DrawProceduralIndirect(material, bounds, MeshTopology.Points, argsBuffer, 0); }
public void RunMarchingCubes(RenderTexture texture) { MarchingCubesCS.SetTexture(kernelMC, "_densityTexture", texture); appendVertexBuffer.SetCounterValue(0); MarchingCubesCS.Dispatch(kernelMC, m_resolution / 8, m_resolution / 8, m_resolution / 8); int[] args = new int[] { 0, 1, 0, 0 }; argBuffer.SetData(args); ComputeBuffer.CopyCount(appendVertexBuffer, argBuffer, 0); argBuffer.GetData(args); trisToDraw = args[0]; args[0] *= 3; argBuffer.SetData(args); Debug.LogFormat("Meshed {0} verts, {1} tris", args[0], args[0] / 3); }
// パーティクルの更新処理 private void UpdateParticle() { // バッファのカウンターをリセット m_activeParticlesBuffer.SetCounterValue(0); // 変数を設定 _computeShader.SetFloat(ShaderDefines.GetFloatPropertyID(ShaderDefines.FloatID._deltaTime), Time.deltaTime); // バッファを設定 _computeShader.SetBuffer(m_updateKernel, ShaderDefines.GetBufferPropertyID(ShaderDefines.BufferID._particlesBuffer), m_particlesBuffer); _computeShader.SetBuffer(m_updateKernel, ShaderDefines.GetBufferPropertyID(ShaderDefines.BufferID._deadParticlesBuffer), m_particlePoolBuffer); _computeShader.SetBuffer(m_updateKernel, ShaderDefines.GetBufferPropertyID(ShaderDefines.BufferID._activeParticlesBuffer), m_activeParticlesBuffer); // 更新カーネルを実行 _computeShader.Dispatch(m_updateKernel, m_numParticles / THREAD_NUM_X, 1, 1); // 使用中のパーティクル数を取得 ComputeBuffer.CopyCount(m_activeParticlesBuffer, m_activeParticleCountsBuffer, 0); }
// 更新処理 public void Update(ComputeShader _computeShader, Camera _camera, int _numParticles, ComputeBuffer _particlesBuffer, ComputeBuffer _activeParticlesBuffer) { // 視錘台カリングを行うカーネル int kernel = _computeShader.FindKernel("FrustumCulling"); // 視錘台の計算 CalculateFrustumPlanes(_camera.projectionMatrix * _camera.worldToCameraMatrix, ref m_planes); // 視錘台の法線を分解 for (int i = 0; i < 4; i++) { Debug.DrawRay(_camera.transform.position, m_planes[i].normal * 10f, Color.yellow); m_normalsFloat[i + 0] = m_planes[i].normal.x; m_normalsFloat[i + 4] = m_planes[i].normal.y; m_normalsFloat[i + 8] = m_planes[i].normal.z; } // バッファのカウンターをリセット m_inViewParticlesBuffer.SetCounterValue(0); // カメラの座標 Vector3 cameraPosition = _camera.transform.position; // 変数を設定 _computeShader.SetInt(ShaderDefines.GetIntPropertyID(ShaderDefines.IntID._numParticles), _numParticles); _computeShader.SetFloats(ShaderDefines.GetVectorPropertyID(ShaderDefines.VectorID._cameraPosition), cameraPosition.x, cameraPosition.y, cameraPosition.z); _computeShader.SetFloats(ShaderDefines.GetVectorPropertyID(ShaderDefines.VectorID._cameraFrustumNormals), m_normalsFloat); // バッファを設定 _computeShader.SetBuffer(kernel, ShaderDefines.GetBufferPropertyID(ShaderDefines.BufferID._particlesBuffer), _particlesBuffer); _computeShader.SetBuffer(kernel, ShaderDefines.GetBufferPropertyID(ShaderDefines.BufferID._activeParticlesBuffer), _activeParticlesBuffer); _computeShader.SetBuffer(kernel, ShaderDefines.GetBufferPropertyID(ShaderDefines.BufferID._inViewParticlesBuffer), m_inViewParticlesBuffer); // カーネルを実行 _computeShader.Dispatch(kernel, Mathf.CeilToInt((float)_activeParticlesBuffer.count / NUM_THREAD_X), 1, 1); // バッファにデータを渡す m_inViewCountsBuffer.SetData(m_inViewCounts); // 視界内のパーティクル数を取得 ComputeBuffer.CopyCount(m_inViewParticlesBuffer, m_inViewCountsBuffer, 4); }
public void Update(ComputeShader cs, Camera camera, int particleNum, ComputeBuffer particleBuffer, ComputeBuffer activeList) { int kernel = cs.FindKernel("CheckCameraCulling"); CalculateFrustumPlanes(camera.projectionMatrix * camera.worldToCameraMatrix, _planes); for (int i = 0; i < 4; i++) { //Debug.DrawRay(camera.transform.position, _planes[i].normal * 10f, Color.yellow); _normalsFloat[i + 0] = _planes[i].normal.x; _normalsFloat[i + 4] = _planes[i].normal.y; _normalsFloat[i + 8] = _planes[i].normal.z; } inViewsAppendBuffer.SetCounterValue(0); var cPos = camera.transform.position; cs.SetFloats("_CameraPos", cPos.x, cPos.y, cPos.z); cs.SetInt("_ParticleNum", particleNum); cs.SetFloats("_CameraFrustumNormals", _normalsFloat); cs.SetBuffer(kernel, "_InViewAppend", inViewsAppendBuffer); cs.SetBuffer(kernel, "_ParticleBuffer", particleBuffer); cs.SetBuffer(kernel, "_ParticleActiveList", activeList); cs.Dispatch(kernel, Mathf.CeilToInt((float)activeList.count / NUM_THREAD_X), 1, 1); inViewsCountBuffer.SetData(inViewsCounts); ComputeBuffer.CopyCount(inViewsAppendBuffer, inViewsCountBuffer, 4); // インスタンス数 //inViewsCountBuffer.GetData(inViewsCounts); //inViewsNum = inViewsCounts[0]; //Debug.Log("inViewsCounts " + inViewsCounts[0]); // debug //if (Input.GetKeyDown(KeyCode.M)) //{ // //inViewsCountBuffer.GetData(inViewsCounts); // //Debug.Log("inViewsCounts " + inViewsCounts[0]); // DumpAppendData(inViewsAppendBuffer, particleNum, "inviews"); // DumpAppendData(activeList, particleNum, "activeList"); //} }
void computeShaderWork() { int numVoxelsPerAxis = numPointsPerAxis - 1; int threadGroups = Mathf.CeilToInt(29.0f / 8.0f); tris.SetCounterValue(0); shader.SetBuffer(0, "tris", tris); shader.SetBuffer(0, "points", meta.pointBuffer); shader.SetInt("numPointsPerAxis", numPointsPerAxis); shader.SetFloat("isolevel", 0.5f); shader.Dispatch(0, threadGroups, threadGroups, threadGroups); ComputeBuffer.CopyCount(tris, trisCount, 0); trisCount.GetData(triCountArray); int triNum = triCountArray[0]; triArray = new Triangle[triNum]; tris.GetData(triArray, 0, 0, triNum); vertices = new Vector3[triNum * 3]; indices = new int[triNum * 3]; for (int i = 0; i < triNum; i++) { for (int j = 0; j < 3; j++) { vertices[i * 3 + j] = triArray[i][j]; indices[i * 3 + j] = i * 3 + j; } } Mesh mesh = new Mesh(); mesh.vertices = vertices; mesh.triangles = indices; mesh.RecalculateNormals(); recalcNorm(mesh); meshFilter.mesh = mesh; }
void GetVertices() { mesh.Clear(); ComputeBuffer triBuffer = new ComputeBuffer(5, sizeof(float) * 3 * 3, ComputeBufferType.Append); ComputeBuffer triCountBuffer = new ComputeBuffer(1, sizeof(int), ComputeBufferType.Raw); triBuffer.SetCounterValue(0); shader.SetBuffer(kernel, "triangles", triBuffer); shader.SetInt("cubeIndex", cubeIndex); shader.Dispatch(0, 1, 1, 1); ComputeBuffer.CopyCount(triBuffer, triCountBuffer, 0); int[] triCountArray = { 0 }; triCountBuffer.GetData(triCountArray); int numTris = triCountArray[0]; Triangle[] tris = new Triangle[numTris]; triBuffer.GetData(tris, 0, 0, numTris); var vertices = new Vector3[numTris * 3]; var triangles = new int[numTris * 3]; for (int i = 0; i < numTris; i++) { for (int j = 0; j < 3; j++) { triangles[i * 3 + j] = i * 3 + j; vertices[i * 3 + j] = tris[i][j]; } } triBuffer.Release(); triCountBuffer.Release(); mesh.vertices = vertices; mesh.triangles = triangles; mesh.RecalculateNormals(); meshFilter.mesh = mesh; }
public void EmitWithTexture(Texture posTex, Texture normTex, Texture colTex) { poolCountBuffer.SetData(particleCounts); ComputeBuffer.CopyCount(poolBuffer, poolCountBuffer, 4); poolCountBuffer.GetData(particleCounts); poolCount = particleCounts[1]; particleCompute.SetInt("_PoolCount", poolCount); particleCompute.SetInt("_TexSize", posTex.height); particleCompute.SetFloat("_LifeTime", lifeTime); particleCompute.SetFloat("_StartVel", startVelocity); particleCompute.SetTexture(emitKernel, "_PosTex", posTex); particleCompute.SetTexture(emitKernel, "_NormTex", normTex); particleCompute.SetTexture(emitKernel, "_ColTex", colTex); particleCompute.SetFloat("_Size", particleSize); particleCompute.SetBuffer(emitKernel, propParticleBuffer, particleBuffer); particleCompute.SetBuffer(emitKernel, propPoolBuffer, poolBuffer); particleCompute.Dispatch(emitKernel, posTex.width / 8, posTex.height / 8, 1); }
protected void OnCameraRender(ScriptableRenderContext context, Camera[] cameras) { material.SetBuffer("_Detections", detector.OutputBuffer); material.SetInt("_UpperBodyOnly", upperBodyOnly ? 1 : 0); ComputeBuffer.CopyCount(detector.OutputBuffer, boxDrawArgs, sizeof(uint)); ComputeBuffer.CopyCount(detector.OutputBuffer, lineDrawArgs, sizeof(uint)); // Face material.SetPass(0); Graphics.DrawProceduralIndirectNow(MeshTopology.Triangles, boxDrawArgs); // Pose material.SetPass(1); Graphics.DrawProceduralIndirectNow(MeshTopology.Triangles, boxDrawArgs); // Hip-Shoulder body line material.SetPass(2); Graphics.DrawProceduralIndirectNow(MeshTopology.Lines, lineDrawArgs); }
private void DispatchEmit() { if (emitList.Count > 0) { int emitKernel = computeShader.FindKernel("Emit"); ComputeBuffer.CopyCount(deadBuffer, counter, 0); emitBuffer.SetData(emitList); computeShader.SetInt("CounterOffset", 0); computeShader.SetInt("Width", emitList.Count); computeShader.SetFloat("Lifetime", 1000); computeShader.SetBuffer(emitKernel, "Counter", counter); computeShader.SetBuffer(emitKernel, "Uploads", emitBuffer); computeShader.SetBuffer(emitKernel, "Pool", deadBuffer); computeShader.SetBuffer(emitKernel, "PositionsWRITE", positionsBuffer); computeShader.SetBuffer(emitKernel, "VelocitiesWRITE", velocitiesBuffer); computeShader.SetBuffer(emitKernel, "Lifetimes", lifetimesBuffer); computeShader.Dispatch(emitKernel, Groups(emitList.Count), 1, 1); emitList.Clear(); } }
void FillArgBuffer(int subMeshIdx) { uint[] args = new uint[ARG_BUFFER_SIZE] { 0, 0, 0, 0, 0 }; args[0] = (uint)mesh.GetIndexCount(subMeshIdx); // index count per instance args[1] = (uint)0; // instance count args[2] = (uint)mesh.GetIndexStart(subMeshIdx); // start index location args[3] = (uint)mesh.GetBaseVertex(subMeshIdx); // base vertex location args[4] = (uint)0; argBuffer.SetData(args); ComputeBuffer.CopyCount(cullingResultBuffer, argBuffer, sizeof(uint)); argBuffer.GetData(args); Debug.LogFormat("count = {0}", args[1]); }
void Update() { if (quadDataBuffer != null) { ComputeBuffer.CopyCount(quadDataBuffer[READ], quadArgBuffer, 0); material.SetPass(0); material.SetBuffer("_Data", quadDataBuffer[READ]); Matrix4x4 BigScaleToSmallScale = Matrix4x4.identity; if (DanceBoxManager.inst.sizeAdjuster != null) { BigScaleToSmallScale = DanceBoxManager.inst.sizeAdjuster.worldToLocalMatrix; } Matrix4x4 SmallScaleToEnvScale = Matrix4x4.identity; if (DanceBoxManager.inst.environmentBoxTransform != null) { SmallScaleToEnvScale = DanceBoxManager.inst.environmentBoxTransform.localToWorldMatrix; //tried using the delayed version here but couldn't get it to sync. I dont understand quite why though } Matrix4x4 final4x4 = SmallScaleToEnvScale * BigScaleToSmallScale; material.SetMatrix("_TransformationMatrix", final4x4); if (_props == null) { _props = new MaterialPropertyBlock(); } _props.SetBuffer("_Data", quadDataBuffer[READ]); Matrix4x4 cameraToBurn = DanceBoxManager.inst.burnTransform.worldToLocalMatrix; _props.SetMatrix("_BurnMatrix", cameraToBurn); Graphics.DrawProceduralIndirect(material, new Bounds(DanceBoxManager.inst.renderBoundsCenter, DanceBoxManager.inst.renderBoundsScale), MeshTopology.Points, quadArgBuffer, 0, null, _props, UnityEngine.Rendering.ShadowCastingMode.On, true); } }
public void Draw(Camera camera) { if (CanDraw()) { var lodLevelCount = Mathf.Min(MaxLodLevelCount, _renderer.LodLevelCount); for (int i = 0; i < lodLevelCount; ++i) { var lodRenderer = _renderer.GetLodRenderer(i); var count = lodRenderer.Renderers.Length; int drawCallOffset = 0; for (int j = 0; j < count; ++j) { var renderer = lodRenderer.Renderers[j]; for (int k = 0; k < renderer.SubMeshCount; ++k) { ComputeBuffer.CopyCount(_drawInstanceData[i], _argsData[i], drawCallOffset + Constants.StrideSizeUint); _mbp.SetBuffer(Constants.MeshVariable.DrawInstanceData, _drawInstanceData[i]); SetMaterialPropertyBlock(); Graphics.DrawMeshInstancedIndirect( renderer.Mesh, k, renderer.Materials[k], testBounds, _argsData[0], drawCallOffset, _mbp, _castShadow, _receiveShadow, Layer, camera); drawCallOffset += ArgCountPerDraw * sizeof(uint); } } } } }
private static void RunShader(Vector3Int terrainSize) { int kernel = polygonizer.FindKernel("Polygonize"); polygonizer.SetBuffer(kernel, "points", points); polygonizer.SetBuffer(kernel, "triangles", triangleBuffer); polygonizer.Dispatch(kernel, Mathf.CeilToInt(terrainSize.x / 4f), Mathf.CeilToInt(terrainSize.y / 4f), Mathf.CeilToInt(terrainSize.z / 2f)); //getting the data from the compute shader // Copy the count. ComputeBuffer.CopyCount(triangleBuffer, countBuffer, 0); // Retrieve it into array. int[] counter = new int[1] { 0 }; countBuffer.GetData(counter); triangles = new Triangle[counter[0]]; triangleBuffer.GetData(triangles, 0, 0, counter[0]); }