public void SwapSubdivisionBuffers() { if (IsInvalid()) { return; } _frameCount++; if (_frameCount > 1) { _frameCount = 0; _ping = !_ping; _pong = !_ping; if (_ping) { _subdivision0Buffer.SetCounterValue(0); } if (_pong) { _subdivision1Buffer.SetCounterValue(0); } } _culledIndexBuffer.SetCounterValue(0); }
private void ComputeShaderMethod() { //reference: https://answers.unity.com/questions/1035132/how-can-i-read-in-the-actual-elements-from-an-appe.html var kernelID = computeShader.FindKernel("CSMain"); var appendBuffer = new ComputeBuffer(64, sizeof(int), ComputeBufferType.Append); appendBuffer.SetCounterValue(0); //定义了缓冲区长度为64*结构大小的appendBuffer. var consumeBuffer = new ComputeBuffer(64, sizeof(int), ComputeBufferType.Append); consumeBuffer.SetCounterValue(0); consumeBuffer.SetData(new int[] { 97, 98, 99 }); consumeBuffer.SetCounterValue(3); //consume类型结构相当于栈,所以取到的第一个值是99。 computeShader.SetBuffer(kernelID, "appendBuffer", appendBuffer); computeShader.SetBuffer(kernelID, "consumeBuffer", consumeBuffer); computeShader.Dispatch(kernelID, 1, 1, 1); //单个线程组的大小为8,定义了1个线程组。也就是说会返回8个数据。 var countBuffer = new ComputeBuffer(1, sizeof(int), ComputeBufferType.IndirectArguments); ComputeBuffer.CopyCount(appendBuffer, countBuffer, 0); //通过这个方法拿到第一个数据。 int[] counter = { 0 }; countBuffer.GetData(counter); int count = counter[0]; Debug.Log("count: " + count); var data = new int[count]; appendBuffer.GetData(data); Debug.Log("data length: " + data.Length); for (int i = 0; i < data.Length; i++) { Debug.Log(data[i]); } consumeBuffer.Release(); consumeBuffer.Dispose(); appendBuffer.Release(); appendBuffer.Dispose(); countBuffer.Release(); countBuffer.Dispose(); }
void Step() { if (pathPoints == bufferSize) { bufferSize *= 2; pathXBuffer.SetCounterValue(bufferSize); pathXBuffer.SetCounterValue(bufferSize); } pathXBuffer.SetData(new float[] { position.x }, 0, pathPoints, 1); pathYBuffer.SetData(new float[] { position.y }, 0, pathPoints, 1); pathPoints++; }
protected void PrepareEnvironmentForChunk(IEnvironmentSurface chunk) { environmentEntities.SetCounterValue(0); environmentSpawner.SetBuffer(0, "minAngleAtCubeIndex", chunk.MinDegreeBuffer); Vector4 v4 = VectorExtension.ToVector4(chunk.AnchorPos); environmentSpawner.SetVector("anchorPosition", v4); environmentPlacer.SetVector("anchorPosition", v4); environmentPlacer.SetVector(BOUNDS_CENTER_NAME, chunk.MeshBounds.Value.center); if (chunk.BuildDetailedEnvironment) { } }
// LateUpdate is called after all Update calls void LateUpdate() { // If in edit mode, we need to update the shaders each Update to make sure settings changes are applied // Don't worry, in edit mode, Update isn't called each frame if (Application.isPlaying == false) { OnDisable(); OnEnable(); } if (Camera.main == null) { return; } // Clear the draw and indirect args buffers of last frame's data drawBuffer.SetCounterValue(0); argsBuffer.SetData(argsBufferReset); // Transform the bounds to world space Bounds bounds = TransformBounds(localBounds); // Update the shader with frame specific data instantiatedGrassComputeShader.SetVector("_Time", new Vector4(0, Time.timeSinceLevelLoad, 0, 0)); instantiatedGrassComputeShader.SetMatrix("_LocalToWorld", transform.localToWorldMatrix); instantiatedGrassComputeShader.SetVector("_CameraPosition", Camera.main.transform.position); // Dispatch the grass shader. It will run on the GPU instantiatedGrassComputeShader.Dispatch(idGrassKernel, dispatchSize, 1, 1); // DrawProceduralIndirect queues a draw call up for our generated mesh Graphics.DrawProceduralIndirect(instantiatedMaterial, bounds, MeshTopology.Triangles, argsBuffer, 0, null, null, ShadowCastingMode.Off, true, gameObject.layer); }
void PreRenderCallback(Camera cam) { if (cam == null || cam.cameraType != CameraType.SceneView) { return; } int buflen = buffer_length < 1 ? 1 : buffer_length; if (current_buffer_length != buflen || freeze_view) { CloseBuffer(); if (freeze_view) { return; } } if (buffer == null) { buffer = new ComputeBuffer(buflen, DEBUG_STRUCT_SIZE, ComputeBufferType.Counter); current_buffer_length = buflen; most_recent_load = -1; debug_array = new DebugStruct[buflen]; } Graphics.ClearRandomWriteTargets(); Graphics.SetRandomWriteTarget(7, buffer, false); buffer.SetCounterValue(0); buffer_length_cache = 0; buf_projmat = cam.projectionMatrix; buf_world2camera = cam.worldToCameraMatrix; buf_scale = new Vector3(cam.scaledPixelWidth, cam.scaledPixelHeight, 1); }
public void ApplyPrepareTrianglesForChunk(CompressedMarchingCubeChunk chunk) { prepareTrisShader.SetInt("pointSpacing", chunk.PointSpacing); prepareTrisShader.SetInt("numPointsPerAxis", chunk.NoisePointsPerAxis); preparedTrisBuffer.SetCounterValue(0); }
void OnEnable() { // メッシュの結合 { particleNumPerMesh_ = MAX_VERTEX_NUM / mesh.vertexCount; meshNum_ = (int)Mathf.Ceil((float)maxParticleNum / particleNumPerMesh_); Debug.Log("meshNum : " + meshNum_); combinedMesh_ = CreateCombinedMesh(mesh, particleNumPerMesh_); } // 必要な数だけマテリアルを作成 material_ = new Material(shader); for (int i = 0; i < meshNum_; ++i) { var props = new MaterialPropertyBlock(); props.SetFloat("_IdOffset", particleNumPerMesh_ * i); propertyBlocks_.Add(props); } // ComputeBuffer の初期化 { particlesBuffer_ = new ComputeBuffer(maxParticleNum, Marshal.SizeOf(typeof(Particle)), ComputeBufferType.Default); particlePoolBuffer_ = new ComputeBuffer(maxParticleNum, sizeof(int), ComputeBufferType.Append); particlePoolBuffer_.SetCounterValue(0); particleArgsBuffer_ = new ComputeBuffer(4, sizeof(int), ComputeBufferType.IndirectArguments); //particleArgs_ = new int[] { 0, 1, 0, 0 }; particleArgs_ = new int[] { 0 }; } updateKernel_ = computeShader.FindKernel("Update"); emitKernel_ = computeShader.FindKernel("Emit"); DispatchInit(); }
private void GenerateBuffers(int maxVertices, int maxIndices) { _maxVertices = maxVertices; _maxIndices = maxIndices; if (_vertices != null) { Debug.LogWarning("--------------------- cleared buffers ---------------------"); _vertices.SafeRelease(); _indices.SafeRelease(); _texcoords.SafeRelease(); } _vertices = new ComputeBuffer(maxVertices, sizeof(float) * 3, ComputeBufferType.Default); _indices = new ComputeBuffer(maxIndices, sizeof(int), ComputeBufferType.Default); _texcoords = new ComputeBuffer(maxVertices, sizeof(float) * 2, ComputeBufferType.Default); _vertices.SetCounterValue(0); _indices.SetCounterValue(0); _texcoords.SetCounterValue(0); _generatorKernel.SetBuffer(ComputeShaderID.surfaceVertices, _vertices); _generatorKernel.SetBuffer(ComputeShaderID.surfaceIndices, _indices); _generatorKernel.SetBuffer(ComputeShaderID.surfaceUVs, _texcoords); }
public override void Reset() { Release(); var attractions = GenerateAttractions(); count = attractions.Length; attractionBuffer = new ComputeBuffer(count, Marshal.SizeOf(typeof(Attraction)), ComputeBufferType.Default); attractionBuffer.SetData(attractions); nodeBuffer = new ComputeBuffer(count, Marshal.SizeOf(typeof(Node)), ComputeBufferType.Default); nodePoolBuffer = new ComputeBuffer(count, Marshal.SizeOf(typeof(int)), ComputeBufferType.Append); nodePoolBuffer.SetCounterValue(0); candidatePoolBuffer = new ComputeBuffer(count, Marshal.SizeOf(typeof(Candidate)), ComputeBufferType.Append); candidatePoolBuffer.SetCounterValue(0); edgePoolBuffer = new ComputeBuffer(count * 2, Marshal.SizeOf(typeof(Edge)), ComputeBufferType.Append); edgePoolBuffer.SetCounterValue(0); // var seeds = Enumerable.Range(0, Random.Range(1, 5)).Select((_) => { return attractions[Random.Range(0, count)].position; }).ToArray(); Setup(new Vector3[] { Vector3.zero }); CopyNodesCount(); CopyEdgesCount(); Step(0f); }
private void ResetComputeSim() { BoidData[] tempArray = new BoidData[NumBoids]; for (int i = 0; i < NumBoids; ++i) { tempArray[i].position = new Vector2(Random.value * TexResolution, Random.value * TexResolution); tempArray[i].direction = Random.insideUnitCircle; tempArray[i].color = new Vector4(Random.value, Random.value, Random.value, 1.0f); } boidBuffer.SetData(tempArray); boidBuffer.SetCounterValue((uint)NumBoids); /* RENDER */ int kernelHandle; SetShaderValues(); kernelHandle = shader.FindKernel("CSRenderWipe"); shader.SetTexture(kernelHandle, "Result", myRt); shader.Dispatch(kernelHandle, TexResolution / 8, TexResolution / 8, 1); // Render Boids kernelHandle = shader.FindKernel("CSRenderMain"); shader.SetBuffer(kernelHandle, "BoidBuffer", boidBuffer); shader.SetTexture(kernelHandle, "Result", myRt); shader.Dispatch(kernelHandle, NumBoids / 8, 1, 1); rend.material.SetTexture("_MainTex", myRt); }
// LateUpdate is called after all Update calls private void LateUpdate() { // Clear the draw buffer of last frame's data drawBuffer.SetCounterValue(0); // Transform the bounds to world space Bounds bounds = TransformBounds(localBounds); // Update the shader with frame specific data pyramidComputeShader.SetMatrix("_LocalToWorld", transform.localToWorldMatrix); pyramidComputeShader.SetFloat("_PyramidHeight", pyramidHeight * Mathf.Sin(animationFrequency * Time.timeSinceLevelLoad)); // Dispatch the pyramid shader. It will run on the GPU pyramidComputeShader.Dispatch(idPyramidKernel, dispatchSize, 1, 1); // Copy the count (stack size) of the draw buffer to the args buffer, at byte position zero // This sets the vertex count for our draw procediral indirect call ComputeBuffer.CopyCount(drawBuffer, argsBuffer, 0); // This the compute shader outputs triangles, but the graphics shader needs the number of vertices, // we need to multiply the vertex count by three. We'll do this on the GPU with a compute shader // so we don't have to transfer data back to the CPU triToVertComputeShader.Dispatch(idTriToVertKernel, 1, 1, 1); // DrawProceduralIndirect queues a draw call up for our generated mesh // It will receive a shadow casting pass, like normal Graphics.DrawProceduralIndirect(material, bounds, MeshTopology.Triangles, argsBuffer, 0, null, null, ShadowCastingMode.On, true, gameObject.layer); }
void Start() { int size = 4 * 4 * 1 * 1; ComputeBuffer counterBuffer = new ComputeBuffer(size, sizeof(int), ComputeBufferType.Counter); counterBuffer.SetCounterValue(0); int handle = incrementCountShader.FindKernel("CSMain8"); incrementCountShader.SetBuffer(handle, "counterBuffer", counterBuffer); incrementCountShader.Dispatch(handle, 1, 1, 1); int[] data = new int[size]; counterBuffer.GetData(data); for (int i = 0; i < data.Length; i++) { Debug.Log(data[i]); } ComputeBuffer argBuffer = new ComputeBuffer(1, sizeof(int), ComputeBufferType.IndirectArguments); int[] args = new int[] { 0 }; ComputeBuffer.CopyCount(counterBuffer, argBuffer, 0); argBuffer.GetData(args); Debug.Log("Count " + args[0]); counterBuffer.Release(); argBuffer.Release(); }
private void RunComputeBuffer() { //set variables and run shader int kernelID = 0; int threadAmount = Mathf.CeilToInt(Mathf.Pow(_VoxelPositionsBuffer.count, 1.0f / 3.0f)); _VoxelsInFrustum.SetCounterValue(0); _Shader.SetBuffer(kernelID, "_VoxelPositions", _VoxelPositionsBuffer); _Shader.SetBuffer(kernelID, "_VoxelsInFrustum", _VoxelsInFrustum); _Shader.SetBuffer(kernelID, "_Args", _ArgsBuffer); _Shader.SetBuffer(kernelID, "_UnitFrustumVectors", _FrustumVectorsBuffer); _Shader.SetBuffer(kernelID, "_FaceFlags", _VoxelFaceFlagsBuffer); _Shader.SetInt("_VoxelAmount", _VoxelPositionsBuffer.count); _Shader.SetInt("_ThreadAmount", threadAmount); _Shader.SetFloat("_FarClipDistance", Camera.main.farClipPlane); _Shader.SetFloat("_NearClipDistance", Camera.main.nearClipPlane); float[] pos = new float[3]; pos[0] = Camera.main.transform.position.x; pos[1] = Camera.main.transform.position.y; pos[2] = Camera.main.transform.position.z; _Shader.SetFloats("_CamPos", pos); _Shader.Dispatch(kernelID, threadAmount, threadAmount, threadAmount); }
protected void March() { TrianglesBuffer.SetCounterValue(0); int threadsPerAxis = Mathf.CeilToInt(VoxelsPerAxis / 8f); marchCompute.Dispatch(0, threadsPerAxis, threadsPerAxis, threadsPerAxis); }
protected virtual void Init() { uint y, z; initKernel = particleCompute.FindKernel(initFunc); emitKernel = particleCompute.FindKernel(emitFunc); updateKernel = particleCompute.FindKernel(updateFunc); particleCompute.GetKernelThreadGroupSizes(updateKernel, out x, out y, out z); numParticles = (int)((maxParticles / x) * x); particleBuffer = new ComputeBuffer(numParticles, Marshal.SizeOf(typeof(ParticleData)), ComputeBufferType.Default); activeBuffer = new ComputeBuffer(numParticles, Marshal.SizeOf(typeof(int)), ComputeBufferType.Append); activeBuffer.SetCounterValue(0); poolBuffer = new ComputeBuffer(numParticles, Marshal.SizeOf(typeof(int)), ComputeBufferType.Append); poolBuffer.SetCounterValue(0); particleCounts = new[] { 0, 1, 0, 0 }; poolCountBuffer = new ComputeBuffer(4, Marshal.SizeOf(typeof(int)), ComputeBufferType.IndirectArguments); poolCountBuffer.SetData(particleCounts); particleCompute.SetBuffer(initKernel, propParticleBuffer, particleBuffer); particleCompute.SetBuffer(initKernel, propDeadBuffer, poolBuffer); particleCompute.Dispatch(initKernel, numParticles / (int)x, 1, 1); }
/// <summary> /// Create all the buffers for the visualize function /// </summary> /// <param name="size"></param> private static void CreateBuffers(int size) { int fullSize = size * size * size; int nrVoxPAxis = size - 1; int nrVox = nrVoxPAxis * nrVoxPAxis * nrVoxPAxis; int maxTriCount = nrVox * 5; if (floatMapBuff == null) { goto Run; } else { if (fullSize != floatMapBuff.count) { DisposeBuffers(); goto Run; } } Run: triangleBuff = new ComputeBuffer(maxTriCount, sizeof(float) * 9, ComputeBufferType.Append); triangleBuff.SetCounterValue(0); floatMapBuff = new ComputeBuffer(fullSize, sizeof(float) * 4); triCountBuffer = new ComputeBuffer(1, sizeof(int), ComputeBufferType.Raw); }
void CreateBuffers() { int pointsCount = MCmesh.pointsPerAxis * MCmesh.pointsPerAxis * MCmesh.pointsPerAxis; int voxelCount = (MCmesh.pointsPerAxis - 1); voxelCount = voxelCount * voxelCount * voxelCount; int maxTrisCount = voxelCount * 5; if (!Application.isPlaying || (pointsBuffer == null || pointsCount != pointsBuffer.count)) { if (Application.isPlaying) { ReleaseBuffer(); } if (substancesBuffer != null) { substancesBuffer.Release(); } triangleBuffer = new ComputeBuffer(maxTrisCount, 36 + sizeof(int), ComputeBufferType.Append); pointsBuffer = new ComputeBuffer(pointsCount, 16); substancesBuffer = new ComputeBuffer(pointsCount, sizeof(int)); trisCountBuffer = new ComputeBuffer(1, sizeof(int), ComputeBufferType.IndirectArguments); triangleBuffer.SetCounterValue(0); density = new Vector4[pointsCount]; substances = new int[pointsCount]; } }
/// <summary> /// 初期化 /// </summary> protected virtual void Initialize() { particleNum = (particleMax / THREAD_NUM_X) * THREAD_NUM_X; emitNum = (emitMax / THREAD_NUM_X) * THREAD_NUM_X; Debug.Log("particleNum " + particleNum + " emitNum " + emitNum + " THREAD_NUM_X " + THREAD_NUM_X); particleBuffer = new ComputeBuffer(particleNum, Marshal.SizeOf(typeof(T)), ComputeBufferType.Default); particleActiveBuffer = new ComputeBuffer(particleNum, Marshal.SizeOf(typeof(int)), ComputeBufferType.Append); particleActiveBuffer.SetCounterValue(0); particlePoolBuffer = new ComputeBuffer(particleNum, Marshal.SizeOf(typeof(int)), ComputeBufferType.Append); particlePoolBuffer.SetCounterValue(0); particleActiveCountBuffer = new ComputeBuffer(4, Marshal.SizeOf(typeof(int)), ComputeBufferType.IndirectArguments); particlePoolCountBuffer = new ComputeBuffer(4, Marshal.SizeOf(typeof(int)), ComputeBufferType.IndirectArguments); particleCounts = new int[] { 0, 1, 0, 0 }; particlePoolCountBuffer.SetData(particleCounts); initKernel = cs.FindKernel("Init"); emitKernel = cs.FindKernel("Emit"); updateKernel = cs.FindKernel("Update"); Debug.Log("initKernel " + initKernel + " emitKernel " + emitKernel + " updateKernel " + updateKernel); cs.SetBuffer(initKernel, "_Particles", particleBuffer); cs.SetBuffer(initKernel, "_DeadList", particlePoolBuffer); cs.SetBuffer(initKernel, "_ActiveList", particleActiveBuffer); cs.Dispatch(initKernel, particleNum / THREAD_NUM_X, 1, 1); }
// Use this for initialization void Awake() { MeshRenderer mr = gameObject.AddComponent <MeshRenderer>(); mf = gameObject.AddComponent <MeshFilter>(); mr.material = meshMat; kernelMC = MarchingCubesCS.FindKernel("MarchingCubes"); //kernelTripleCount = MarchingCubesCS.FindKernel("TripleCount"); MarchingCubesCS.SetInt("_gridSize", resolution); MarchingCubesCS.SetFloat("_isoLevel", 0.0f); // halfway point for noise in range [-1, 1] // * 5 since up to 5 triangles per cube in marching cubes // sizeof(float)*6 because thats the size of a vertex, * 3 cuz 3 verts per triangle // also one less than resolution because 64x64x64 density map represents 63*63*63 cubes only int maxTris = (resolution - 1) * (resolution - 1) * (resolution - 1) * 5; int floatsPerTri = 6 * 3; appendBuffer = new ComputeBuffer(maxTris, floatsPerTri * sizeof(float), ComputeBufferType.Append); argBuffer = new ComputeBuffer(4, sizeof(int), ComputeBufferType.IndirectArguments); appendBuffer.SetCounterValue(0); // init retrieval arrays data = new float[maxTris * floatsPerTri]; count = new int[4]; long bytes = maxTris * floatsPerTri * sizeof(float); Debug.Log((float)bytes / 1000000 + " mb per chunk"); }
protected void Start() { // Initialize particle buffer particleBuffer = new PingPongBuffer(count, typeof(Particle_t)); // Initialize object pool buffer poolBuffer = new ComputeBuffer(count, Marshal.SizeOf(typeof(int)), ComputeBufferType.Append); poolBuffer.SetCounterValue(0); countBuffer = new ComputeBuffer(4, Marshal.SizeOf(typeof(int)), ComputeBufferType.IndirectArguments); countBuffer.SetData(countArgs); // Initialize dividable object pool buffer dividablePoolBuffer = new ComputeBuffer(count, Marshal.SizeOf(typeof(int)), ComputeBufferType.Append); dividablePoolBuffer.SetCounterValue(0); // Execute kernel to initialize particle and pool buffers InitParticlesKernel(); // Initialize for gpu-instancing mesh = BuildQuad(); drawArgs[0] = mesh.GetIndexCount(0); drawArgs[1] = (uint)count; argsBuffer = new ComputeBuffer(1, sizeof(uint) * drawArgs.Length, ComputeBufferType.IndirectArguments); argsBuffer.SetData(drawArgs); pallete = CreatePallete(gradient, 128); material.SetTexture("_Gradient", pallete); StartCoroutine(IDivider()); }
public void MarchAll() { Vector3Int threadCount = volume.VoxelThreadCount; frontBuffer.SetCounterValue(0); march.SetBuffer(0, "points", pointsBuffer); march.SetBuffer(0, "triangles", frontBuffer); march.SetVector("base", Vector4.zero); march.SetInt("numPointsX", volume.SamplesDensity.x); march.SetInt("numPointsY", volume.SamplesDensity.y); march.SetInt("numPointsZ", volume.SamplesDensity.z); march.SetFloat("isoLevel", isoLevel); march.Dispatch(0, threadCount.x, threadCount.y, threadCount.z); numTris = GetNumTris(frontBuffer); }
private void Cull(CommandBuffer _cmd, Camera _cam) { if (enableGpuCulling == false) { return; } int kernel = csCulling.FindKernel("CSMain"); uint sizeX; csCulling.GetKernelThreadGroupSizes( kernel, out sizeX, out _, out _ ); Vector4[] planes = CullingTool.GetFrustumPlane(_cam); cullResultBuffer.SetCounterValue(0); csCulling.SetBuffer(kernel, particleBufferID, particleBuffer); csCulling.SetBuffer(kernel, cullResultID, cullResultBuffer); csCulling.SetInt(particleCountID, PARTICLE_COUNT); csCulling.SetVectorArray(frustumPlaneID, planes); _cmd.DispatchCompute(csCulling, kernel, Mathf.CeilToInt((PARTICLE_COUNT + sizeX - 1) / sizeX), 1, 1); }
void LateUpdate() { bool updateNeeded = false; if (UNHVD.unhvd_get_frame_begin(unhvd, frame) == 0) { updateNeeded = PrepareTextures(); } if (UNHVD.unhvd_get_frame_end(unhvd) != 0) { Debug.LogWarning("Failed to get UNHVD frame data"); } if (!updateNeeded) { return; } depthTexture.Apply(false); colorTexture.Apply(false); vertexBuffer.SetCounterValue(0); unprojectionShader.Dispatch(0, frame[0].width / 8, frame[0].height / 8, 1); ComputeBuffer.CopyCount(vertexBuffer, argsBuffer, 0); }
void GenerateInstances(Vector3 focusPos, Vector3 detailCornerPos, Vector3 shardCornerPos, TETerrainShardData shardData, RenderTexture matId, ComputeBuffer meshBuffer, ComputeBuffer argBuffer) { meshBuffer.SetCounterValue(0); detailSpawnShader.SetBuffer(0, "meshOutput", meshBuffer); detailSpawnShader.SetTexture(0, "materialID", matId); detailSpawnShader.SetTexture(0, "noiseRG", detailNoiseRG); detailSpawnShader.SetVector("focusPos", focusPos); detailSpawnShader.SetVector("detailCornerPos", detailCornerPos); detailSpawnShader.SetVector("detailCellSize", Vector4.one * detailCellSize); detailSpawnShader.SetVector("shardCornerPos", shardCornerPos); detailSpawnShader.SetVector("shardSize", Vector4.one * farMeshEdgeLength); detailSpawnShader.SetTexture(0, "heightmap", shardData.HeightTexture); detailSpawnShader.SetTexture(0, "controlmap", shardData.ControlTexture); detailSpawnShader.SetTexture(0, "colormap", shardData.ColorTexture); detailSpawnShader.SetBuffer(0, "spriteTemplates", m_detailSpriteTemplatesBuffer); detailSpawnShader.SetBuffer(0, "detailLayers", m_detailDetailLayersBuffer); detailSpawnShader.SetBuffer(0, "materialOffsetCount", m_detailMaterialStartOffsetBuffer); detailSpawnShader.SetInt("weakTemplatesOffset", 0); detailSpawnShader.SetFloat("vegetationDensityScale", vegetationDensityScale); detailSpawnShader.Dispatch(0, detailCellSize, detailCellSize, 1); //argBuffer.SetData(m_args0100); ComputeBuffer.CopyCount(meshBuffer, argBuffer, 0); // Separate dispatch just to setup indirect factors :( detailSpawnShader.SetBuffer(1, "argBuffer", argBuffer); detailSpawnShader.Dispatch(1, 1, 1, 1); }
/// <summary> /// 初期化 /// </summary> protected virtual void Initialize() { particleNum = (particleMax / THREAD_NUM_X) * THREAD_NUM_X; emitNum = (emitMax / THREAD_NUM_X) * THREAD_NUM_X; //Debug.Log("particleNum " + particleNum + " emitNum " + emitNum + " THREAD_NUM_X " + THREAD_NUM_X); particleBuffer = new ComputeBuffer(particleNum, Marshal.SizeOf(typeof(T)), ComputeBufferType.Default); particleActiveBuffer = new ComputeBuffer(particleNum, Marshal.SizeOf(typeof(int)), ComputeBufferType.Append); particleActiveBuffer.SetCounterValue(0); particlePoolBuffer = new ComputeBuffer(particleNum, Marshal.SizeOf(typeof(int)), ComputeBufferType.Append); particlePoolBuffer.SetCounterValue(0); particleActiveCountBuffer = new ComputeBuffer(4, Marshal.SizeOf(typeof(int)), ComputeBufferType.IndirectArguments); particlePoolCountBuffer = new ComputeBuffer(4, Marshal.SizeOf(typeof(int)), ComputeBufferType.IndirectArguments); particlePoolCountBuffer.SetData(particleCounts); initKernel = cs.FindKernel("Init"); emitKernel = cs.FindKernel("Emit"); updateKernel = cs.FindKernel("Update"); cspropid_Particles = ShaderDefines.GetBufferPropertyID(ShaderDefines.BufferID._Particles); cspropid_DeadList = ShaderDefines.GetBufferPropertyID(ShaderDefines.BufferID._DeadList); cspropid_ActiveList = ShaderDefines.GetBufferPropertyID(ShaderDefines.BufferID._ActiveList); cspropid_ParticlePool = ShaderDefines.GetBufferPropertyID(ShaderDefines.BufferID._ParticlePool); cspropid_EmitNum = ShaderDefines.GetIntPropertyID(ShaderDefines.IntID._EmitNum); //Debug.Log("initKernel " + initKernel + " emitKernel " + emitKernel + " updateKernel " + updateKernel); cs.SetBuffer(initKernel, cspropid_Particles, particleBuffer); cs.SetBuffer(initKernel, cspropid_DeadList, particlePoolBuffer); cs.Dispatch(initKernel, particleNum / THREAD_NUM_X, 1, 1); isInitialized = true; }
void Start() { buffer = new ComputeBuffer(width * width, sizeof(float) * 3, ComputeBufferType.Append); buffer.SetCounterValue(0); int handle = appendBufferShader.FindKernel("CSMain6"); appendBufferShader.SetBuffer(handle, "appendBuffer", buffer); appendBufferShader.SetFloat("size", size); appendBufferShader.SetFloat("width", width); appendBufferShader.Dispatch(0, width / 8, width / 8, 1); argBuffer = new ComputeBuffer(4, sizeof(int), ComputeBufferType.IndirectArguments); // ComputeBufferType.DrawIndirect int[] args = new int[] { 0, 1, 0, 0 }; argBuffer.SetData(args); ComputeBuffer.CopyCount(buffer, argBuffer, 0); argBuffer.GetData(args); Debug.Log("vertex count " + args[0]); Debug.Log("instance count " + args[1]); Debug.Log("start vertex " + args[2]); Debug.Log("start instance " + args[3]); }
// ******* 9. Finde im sortierten cellTrianglePairsBuffer alle Dreieckspaare, deren Bounding Boxes sich überschneiden ******* void _9_FindTrianglePairs(bool backBufferIsInput) { m_CurComputeShader = m_ComputeShaderList[10]; int kernelID = m_CurComputeShader.FindKernel("main"); if (backBufferIsInput) { m_CurComputeShader.SetBuffer(kernelID, "cellTrianglePairs", m_CellTrianglePairsBackBuffer_Buffer); } else { m_CurComputeShader.SetBuffer(kernelID, "cellTrianglePairs", m_CellTrianglePairs_Buffer); } m_CurComputeShader.SetBuffer(kernelID, "boundingBoxes", m_BoundingBox_Buffer); m_CurComputeShader.SetBuffer(kernelID, "trianglePairs", m_TrianglePairs_Buffer); m_TrianglePairs_Buffer.SetCounterValue(0); int groupCount = (int)Mathf.Ceil(m_TrianglePairsCount / 1024.0f); m_CurComputeShader.Dispatch(kernelID, groupCount, 1, 1); m_CellTrianglePairs_Buffer.SetData(m_CellTrianglePairs_Zero); m_CellTrianglePairsBackBuffer_Buffer.SetData(m_CellTrianglePairs_Zero); }
public override void Reset() { base.Reset(); count = attractions.Length * 2; SetupSkin(); nodeBuffer = new ComputeBuffer(count, Marshal.SizeOf(typeof(SkinnedNode)), ComputeBufferType.Default); nodePoolBuffer = new ComputeBuffer(count, Marshal.SizeOf(typeof(int)), ComputeBufferType.Append); nodePoolBuffer.SetCounterValue(0); candidatePoolBuffer = new ComputeBuffer(count, Marshal.SizeOf(typeof(SkinnedCandidate)), ComputeBufferType.Append); candidatePoolBuffer.SetCounterValue(0); edgePoolBuffer = new ComputeBuffer(count, Marshal.SizeOf(typeof(Edge)), ComputeBufferType.Append); edgePoolBuffer.SetCounterValue(0); var seeds = new List <Vector3>(); for (int i = 0, n = Random.Range(4, 5); i < n; i++) { var attr = attractions[Random.Range(0, attractions.Length)]; seeds.Add(attr.position); } Setup(seeds.ToArray()); CopyNodesCount(); CopyEdgesCount(); Step(0f); }
/// <summary> /// パーティクルを初期化 /// </summary> void InitParticles() { // パーティクルのコンピュートバッファを作成 particleBufferRead = new ComputeBuffer(NUM_PARTICLES, Marshal.SizeOf(typeof(ParticleData)), ComputeBufferType.Append); particleBufferWrite = new ComputeBuffer(NUM_PARTICLES, Marshal.SizeOf(typeof(ParticleData)), ComputeBufferType.Append); particleBufferRead.SetCounterValue(0); particleBufferWrite.SetCounterValue(0); particleIndirectArgsBuffer = new ComputeBuffer(4, sizeof(int), ComputeBufferType.IndirectArguments); particleIndirectArgs = new int[] { 0, 1, 0, 0 }; // パーティクルの初期値を設定 var pData = new ParticleData[NUM_PARTICLES]; for (int i = 0; i < pData.Length; i++) { pData[i].Velocity = Random.insideUnitSphere; pData[i].Position = Random.insideUnitSphere; pData[i].Scale = 1.0f; pData[i].Age = 0.0f; } // コンピュートバッファに初期値データをセット particleBufferRead.SetData(pData); particleBufferWrite.SetData(pData); pData = null; }