void FormatPixelData() { int kernel = formatDataShader.FindKernel("CSMain"); Vector3 threadsPerBlock = new Vector3(8, 8, 1); // Send data to compute shader pixelData_gpu = new ComputeBuffer(pixelData.Length, 28); pixelData_gpu.SetData(pixelData); formatDataShader.SetBuffer(kernel, "pixelData", pixelData_gpu); print("Color of pixel 0: " + ProjectiveTextureMapping.Instance.colorTexArray.GetPixels(0)[0]); print("Depth of pixel 0: " + ProjectiveTextureMapping.Instance.depthTexArray.GetPixels(0)[0]); formatDataShader.SetTexture(kernel, "_ColorTexArray", ProjectiveTextureMapping.Instance.colorTexArray); formatDataShader.SetTexture(kernel, "_DepthTexArray", ProjectiveTextureMapping.Instance.depthTexArray); formatDataShader.SetMatrixArray("_VPArray", ProjectiveTextureMapping.Instance.vpArray.ToArray()); formatDataShader.SetMatrixArray("_DVPArray", ProjectiveTextureMapping.Instance.dvpArray.ToArray()); formatDataShader.SetMatrixArray("_InverseVPArray", ProjectiveTextureMapping.Instance.invVPArray.ToArray()); //formatDataShader.SetMatrixArray("_InverseVPArray", ProjectiveTextureMapping.Instance.vpArray.Select(mat => mat.inverse).ToArray()); formatDataShader.SetMatrixArray("_InverseDVPArray", ProjectiveTextureMapping.Instance.dvpArray.Select(mat => mat.inverse).ToArray()); //formatDataShader.SetVectorArray("_PosArray", ProjectiveTextureMapping.Instance.posArray.ToArray()); print("VP Array: (size: " + ProjectiveTextureMapping.Instance.vpArray.Count + ")"); for (int i = 0; i < ProjectiveTextureMapping.Instance.vpArray.Count; i++) { print(ProjectiveTextureMapping.Instance.vpArray[i]); } print("DVP Array: (size: " + ProjectiveTextureMapping.Instance.dvpArray.Count + ")"); for (int i = 0; i < ProjectiveTextureMapping.Instance.dvpArray.Count; i++) { print(ProjectiveTextureMapping.Instance.dvpArray[i]); } var invVPArray = ProjectiveTextureMapping.Instance.invVPArray.ToArray(); print("invVP Array: (size: " + invVPArray.Length + ")"); for (int i = 0; i < invVPArray.Length; i++) { print(invVPArray[i]); } var invDVPArray = ProjectiveTextureMapping.Instance.dvpArray.Select(mat => mat.inverse).ToArray(); print("invDVP Array: (size: " + invDVPArray.Length + ")"); for (int i = 0; i < invDVPArray.Length; i++) { print(invDVPArray[i]); } // Run compute shader int numBlocksX = Mathf.CeilToInt(ProjectiveTextureMapping.Instance.textureWidth / threadsPerBlock.x); int numBlocksY = Mathf.CeilToInt(ProjectiveTextureMapping.Instance.textureHeight / threadsPerBlock.y); int numBlocksZ = Mathf.CeilToInt(ProjectiveTextureMapping.Instance.maxTextures / threadsPerBlock.z); formatDataShader.Dispatch(kernel, numBlocksX, numBlocksY, numBlocksZ); // Get the data from the GPU pixelData_gpu.GetData(pixelData); pixelData_gpu.Dispose(); }
/// <summary> /// Run the compute shader. /// </summary> private void RunComputeShader() { _computeShader.SetInts("sampleIndex", _sampleIndex); _computeShader.SetVector("sampleWeight", _sampleWeight); _computeShader.SetMatrixArray("sampleMatrix", _sampleMatrix); _computeShader.Dispatch(_kernelId, 32, 32, 1); }
public override void Apply(ComputeShader shader, int kernelIndex) { bools.ForEach(v => shader.SetBool(v.name, v.value)); colors.ForEach(v => shader.SetVector(v.name, v.value)); floats.ForEach(v => shader.SetFloat(v.name, v.value)); floatArrays.ForEach(v => shader.SetFloats(v.name, v.value)); ints.ForEach(v => shader.SetInt(v.name, v.value)); matrices.ForEach(v => shader.SetMatrix(v.name, v.value)); matrixArrays.ForEach(v => shader.SetMatrixArray(v.name, v.value)); textures.ForEach(v => shader.SetTexture(kernelIndex, v.name, v.value)); vectors.ForEach(v => shader.SetVector(v.name, v.value)); vectorArrays.ForEach(v => shader.SetVectorArray(v.name, v.value)); buffers.ForEach(v => shader.SetBuffer(kernelIndex, v.name, v.value)); }
public void UpdateShader() { PhysarumUpdate.SetFloat(SizeID, size); PhysarumUpdate.SetFloat(SenseDistanceID, senseDistance); PhysarumUpdate.SetMatrixArray(SenseMatID, senseMats); PhysarumUpdate.SetMatrixArray(TurnMatID, turnMats); PhysarumUpdate.SetInt(SensorCountID, SensorCount); PhysarumUpdate.SetFloat(SpeedID, speed); PhysarumUpdate.SetFloat(DepositRateID, depositRate); PhysarumUpdate.SetFloat(DiffuseRateID, diffuseRate); PhysarumUpdate.SetFloat(DecayRateID, decayRate); PhysarumUpdate.SetFloat(DeltaTimeID, Time.deltaTime); PhysarumUpdate.SetInt(TrailResolutionID, trailResolution); PhysarumUpdate.SetInt(ParticleCountID, particleCount); int particleGroupCount = Mathf.CeilToInt((float)particleCount / particleThreadNum); int texGroupCount = Mathf.CeilToInt((float)trailResolution / texThreadNum); PhysarumUpdate.SetTexture(UpdateParticleHandle, TrailReadID, trailRT[READ]); PhysarumUpdate.SetBuffer(UpdateParticleHandle, ParticleInfoID, particleInfo); PhysarumUpdate.Dispatch(UpdateParticleHandle, particleGroupCount, 1, 1); PhysarumUpdate.SetTexture(DepositHandle, DepositID, depositRT); PhysarumUpdate.SetBuffer(DepositHandle, ParticleInfoID, particleInfo); PhysarumUpdate.Dispatch(DepositHandle, particleGroupCount, 1, 1); PhysarumUpdate.SetTexture(DiffuseTrailHandle, DepositID, depositRT); PhysarumUpdate.SetTexture(DiffuseTrailHandle, TrailReadID, trailRT[READ]); PhysarumUpdate.SetTexture(DiffuseTrailHandle, TrailWriteID, trailRT[WRITE]); PhysarumUpdate.Dispatch(DiffuseTrailHandle, texGroupCount, texGroupCount, texGroupCount); SwitchRT(); PhysarumUpdate.SetTexture(DecayTrailHandle, TrailReadID, trailRT[READ]); PhysarumUpdate.SetTexture(DecayTrailHandle, TrailWriteID, trailRT[WRITE]); PhysarumUpdate.Dispatch(DecayTrailHandle, texGroupCount, texGroupCount, texGroupCount); SwitchRT(); }
public static int SetMatrixArray(IntPtr l) { int result; try { int total = LuaDLL.lua_gettop(l); if (LuaObject.matchType(l, total, 2, typeof(int), typeof(Matrix4x4[]))) { ComputeShader computeShader = (ComputeShader)LuaObject.checkSelf(l); int nameID; LuaObject.checkType(l, 2, out nameID); Matrix4x4[] values; LuaObject.checkArray <Matrix4x4>(l, 3, out values); computeShader.SetMatrixArray(nameID, values); LuaObject.pushValue(l, true); result = 1; } else if (LuaObject.matchType(l, total, 2, typeof(string), typeof(Matrix4x4[]))) { ComputeShader computeShader2 = (ComputeShader)LuaObject.checkSelf(l); string name; LuaObject.checkType(l, 2, out name); Matrix4x4[] values2; LuaObject.checkArray <Matrix4x4>(l, 3, out values2); computeShader2.SetMatrixArray(name, values2); LuaObject.pushValue(l, true); result = 1; } else { LuaObject.pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function SetMatrixArray to call"); result = 2; } } catch (Exception e) { result = LuaObject.error(l, e); } return(result); }
void UpdateFunctionOnGPU() { int resolution_ = resolution / 4; resolution_ *= 4; float step = size / (float)resolution_; isoValsShader.SetInt(resolutionId, resolution_); isoValsShader.SetFloat(stepId, step); // duration += Time.deltaTime; // isoValsShader.SetFloat(sId, (shapeSize * (((Mathf.Sin(5f * duration) + 2f) * 0.5f)))); // isoValsShader.SetFloat(sId, shapeSize); isoValsShader.SetFloat(timeId, Time.time); isoValsShader.SetMatrix(gridToWorldID, this.transform.localToWorldMatrix); isoValsShader.SetMatrixArray(shapeToWorldID, shape.Select(v => v.transform.localToWorldMatrix.inverse).ToArray()); isoValsShader.SetBuffer(0, isoValsId, isoValsBuffer); int groups = Mathf.CeilToInt(resolution_ / 4f); isoValsShader.EnableKeyword(FunctionLibrary.GetName(shapeFunction)); isoValsShader.Dispatch(0, groups, groups, groups); isoValsShader.DisableKeyword(FunctionLibrary.GetName(shapeFunction)); var bounds = new Bounds(Vector3.zero, Vector3.one * (size + step)); if (showGrid) { transparencyMaterial.SetBuffer(isoValsId, isoValsBuffer); transparencyMaterial.SetFloat(stepId, step); transparencyMaterial.SetInt(resolutionId, resolution_); transparencyMaterial.SetMatrix(gridToWorldID, this.transform.localToWorldMatrix); transparencyMaterial.SetVector(viewDirID, -Camera.main.transform.forward); transparencyMaterial.SetFloat(pointBrightnessID, pointBrightness); transparencyMaterial.SetFloat(pointSizeID, pointSize); Graphics.DrawMeshInstancedProcedural(pointMesh, 0, transparencyMaterial, bounds, resolution_ * resolution_ * resolution_); } if (showVolume) { material.SetBuffer(isoValsId, isoValsBuffer); material.SetFloat(stepId, step); material.SetInt(resolutionId, resolution_); material.SetMatrix(gridToWorldID, this.transform.localToWorldMatrix); material.SetVector(viewDirID, -Camera.main.transform.forward); material.SetFloat(pointBrightnessID, pointBrightness); material.SetFloat(pointSizeID, pointSize); Graphics.DrawMeshInstancedProcedural(pointMesh, 0, material, bounds, resolution_ * resolution_ * resolution_); } // surface points surfacePointsShader.SetInt(resolutionId, resolution_); surfacePointsShader.SetMatrix(gridToWorldID, this.transform.localToWorldMatrix); surfacePointsShader.SetMatrixArray(shapeToWorldID, shape.Select(v => v.transform.localToWorldMatrix.inverse).ToArray()); surfacePointsShader.SetFloat(stepId, step); surfacePointsShader.SetBuffer(0, isoValsId, isoValsBuffer); surfacePointsShader.SetBuffer(0, surfacePointsId, surfacePointsBuffer); surfacePointsShader.SetBuffer(0, normalsId, normalsBuffer); surfacePointsShader.EnableKeyword(FunctionLibrary.GetName(shapeFunction)); surfacePointsShader.EnableKeyword(GetSurfacePointsFuncName(surfacePointsFunc)); // surfacePointsShader.SetMatrixArray(shapeToWorldID, shape.Select(v => v.transform.localToWorldMatrix).ToArray()); surfacePointsShader.Dispatch(0, groups, groups, groups); surfacePointsShader.DisableKeyword(FunctionLibrary.GetName(shapeFunction)); surfacePointsShader.DisableKeyword(GetSurfacePointsFuncName(surfacePointsFunc)); // var data = new Vector3[resolution_*resolution_*resolution_]; // surfacePointsBuffer.GetData(data); // print(data[10]); if (showSurface) { surfacePointMaterial.SetFloat(stepId, step); surfacePointMaterial.SetInt(resolutionId, resolution_); surfacePointMaterial.SetMatrix(gridToWorldID, this.transform.localToWorldMatrix); surfacePointMaterial.SetVector(viewDirID, -Camera.main.transform.forward); surfacePointMaterial.SetFloat(pointSizeID, pointSize); surfacePointMaterial.SetBuffer(surfacePointsId, surfacePointsBuffer); surfacePointMaterial.SetBuffer(normalsId, normalsBuffer); Graphics.DrawMeshInstancedProcedural(pointMesh, 0, surfacePointMaterial, bounds, resolution_ * resolution_ * resolution_); } Mesh mesh = GetComponent <MeshFilter>().mesh; mesh.Clear(); if (showMesh) { // construct mesh meshBuffer.SetCounterValue(0); int meshKernel = 0; meshShader.SetInt(resolutionId, resolution_); meshShader.SetMatrix(gridToWorldID, this.transform.localToWorldMatrix); meshShader.SetFloat(stepId, step); meshShader.SetBuffer(meshKernel, isoValsId, isoValsBuffer); meshShader.SetBuffer(meshKernel, surfacePointsId, surfacePointsBuffer); meshShader.SetBuffer(meshKernel, normalsId, normalsBuffer); meshShader.SetBuffer(meshKernel, meshId, meshBuffer); meshShader.EnableKeyword(FunctionLibrary.GetName(shapeFunction)); meshShader.Dispatch(meshKernel, groups, groups, groups); meshShader.DisableKeyword(FunctionLibrary.GetName(shapeFunction)); // Copy the count. ComputeBuffer.CopyCount(meshBuffer, argsBuffer, 0); // TODO: do not retrieve from GPU. write a compute shader to adjust count: https://gist.github.com/DuncanF/353509dd397ea5f292fa52d1b9b5133d // Retrieve it into array. int[] args = new int[4]; argsBuffer.GetData(args); // Actual count in append buffer. args[0] *= 1; // verts per triangle // args[2] += 1; // verts per triangle argsBuffer.SetData(args); fixArgs.SetBuffer(0, "DrawCallArgs", argsBuffer); fixArgs.Dispatch(0, 1, 1, 1); argsBuffer.GetData(args); args[0] *= 2; var meshArr = new Vector4[args[0]]; meshBuffer.GetData(meshArr); var verts3 = new Vector3[args[0]]; // var verts4 = new Vector4[args[0]]; var normals3 = new Vector3[args[0]]; for (int i = 0; i < args[0]; i += 2) { verts3[i / 2] = new Vector3(meshArr[i].x, meshArr[i].y, meshArr[i].z); // verts4[i / 2] = meshArr[i]; normals3[i / 2] = new Vector3(meshArr[i + 1].x, meshArr[i + 1].y, meshArr[i + 1].z); } mesh.vertices = verts3; mesh.normals = normals3; var tris = new int[verts3.Length]; for (int i = 0; i < verts3.Length; i++) { tris[i] = i; } mesh.triangles = tris; if (renderMode == RenderMode.Wireframe) { var indices = new int[verts3.Length / 3 * 6]; for (int i = 0, j = 0; i < indices.Length; i += 6, j += 3) { indices[i] = j; indices[i + 1] = j + 1; indices[i + 2] = j + 1; indices[i + 3] = j + 2; indices[i + 4] = j; indices[i + 5] = j + 2; } mesh.SetIndices(indices, MeshTopology.Lines, 0); } // TODO: custom render shader (URP shader graph) that gets verts from buffer, use vert id, create variant of urp standard // see info at bottom for vert id info?: https://docs.unity3d.com/Manual/SL-ShaderSemantics.html // https://samdriver.xyz/article/compute-shader-intro // https://cyangamedev.wordpress.com/2020/06/05/urp-shader-code/ // https://gist.github.com/phi-lira/225cd7c5e8545be602dca4eb5ed111ba // meshBufferFloat.SetData(verts4); // // if (showMesh) { // meshMaterial.SetPass(0); // meshMaterial.SetMatrix(gridToWorldID, this.transform.localToWorldMatrix); // meshMaterial.SetBuffer(meshId, meshBufferFloat); // Graphics.DrawProceduralIndirect(meshMaterial, bounds, MeshTopology.Triangles, argsBuffer, 0, null, null, UnityEngine.Rendering.ShadowCastingMode.On, true); } }
private void Update() { if (Input.GetKeyDown(KeyCode.C)) { //RenderTexture tex = new RenderTexture(256, 256, 24); //tex.enableRandomWrite = true; //tex.Create(); // Get all ray march colliders. RMCollider[] _colliders = (RMCollider[])FindObjectsOfType(typeof(RMCollider)); // Extract all collider info, and pack into float array. ColliderInfo[] colliderInfos = new ColliderInfo[_colliders.Length]; Matrix4x4[] invModelMats = new Matrix4x4[_colliders.Length]; int[] primitiveTypes = new int[_colliders.Length]; Vector4[] combineOps = new Vector4[_colliders.Length]; Vector4[] primitiveGeoInfo = new Vector4[_colliders.Length]; ColliderInfo colInfo; GameObject obj; for (int i = 0; i < _colliders.Length; ++i) { obj = _colliders[i].gameObject; colInfo.pos = obj.transform.position; colInfo.geoInfo = obj.GetComponent <RMPrimitive>().GeoInfo; colInfo.colliding = -1; colliderInfos[i] = colInfo; invModelMats[i] = obj.transform.localToWorldMatrix.inverse; primitiveTypes[i] = (int)obj.GetComponent <RMPrimitive>().PrimitiveType; combineOps[i] = obj.GetComponent <RMPrimitive>().CombineOp; primitiveGeoInfo[i] = obj.GetComponent <RMPrimitive>().GeoInfo; } int kernel = _collisionCompute.FindKernel("CSMain"); // Create a compute buffer. ComputeBuffer buffer = new ComputeBuffer(colliderInfos.Length, (sizeof(float) * 7) + sizeof(int)); buffer.SetData(colliderInfos); _collisionCompute.SetBuffer(kernel, "_colliderInfo", buffer); //_collisionCompute.SetTexture(0, "Result", tex); _collisionCompute.SetMatrixArray("_invModelMats", invModelMats); _collisionCompute.SetInts("_primitiveTypes", primitiveTypes); _collisionCompute.SetVectorArray("_combineOps", combineOps); _collisionCompute.SetVectorArray("_primitiveGeoInfo", primitiveGeoInfo); int numThreadGroups = _colliders.Length; _collisionCompute.Dispatch(kernel, 1, 1, 1); //_collisionCompute.Dispatch(0, 256/8, 256/8, 1); buffer.GetData(colliderInfos); Debug.Log("Dist: " + colliderInfos[0].geoInfo.w); if (colliderInfos[0].colliding == 1) { Debug.Log("Colliding"); _colliders[0].gameObject.transform.position = colliderInfos[0].pos; } //Graphics.CopyTexture(tex, _computeTex); buffer.Release(); //tex.Release(); } }