예제 #1
0
    void InitGrid()
    {
        gridDimensions.Set((int)gridBounds.localScale.x,
                           (int)gridBounds.localScale.y,
                           (int)gridBounds.localScale.z,
                           0);

        float cellSize = smoothingRadius;

        gridDimensions  /= cellSize;
        gridDimensions.w = gridDimensions.x * gridDimensions.y * gridDimensions.z;

        Vector3 halfSize = new Vector3(gridDimensions.x, gridDimensions.y, gridDimensions.z) * cellSize * 0.5f;
        Vector3 pos      = gridBounds.position - halfSize;

        gridStartPosition.Set(pos.x, pos.y, pos.z, cellSize);

        kernelClearGrid = shader.FindKernel("ClearGrid");

        uint numThreadsX;

        shader.GetKernelThreadGroupSizes(kernelClearGrid, out numThreadsX, out _, out _);
        gridGroupSize = Mathf.CeilToInt(gridDimensions.w / (float)numThreadsX);

        gridCount = (int)numThreadsX * gridGroupSize;

        Debug.Log("gridDimensions:" + gridDimensions);
        Debug.Log("gridStartPosition:" + gridStartPosition);

        gridBuffer = new ComputeBuffer(gridCount, SIZE_GRID_CELL);
    }
예제 #2
0
파일: LifeGame.cs 프로젝트: Moosan/Tuber
    private void LifeGameStart()
    {
        // カーネルIdの取得
        kernelInitialize = computeShader.FindKernel("Initialize");
        kernelUpdate     = computeShader.FindKernel("Update");
        kernelDraw       = computeShader.FindKernel("Draw");

        // 状態を格納するテクスチャの作成
        stateTexture                   = new RenderTexture(512, 512, 0, RenderTextureFormat.RInt);
        stateTexture.wrapMode          = TextureWrapMode.Repeat;
        stateTexture.enableRandomWrite = true;
        stateTexture.Create();
        // レンダリング用のテクスチャの取得
        drawTexture                   = new RenderTexture(512, 512, 0, RenderTextureFormat.ARGB32);
        drawTexture.filterMode        = FilterMode.Point;
        drawTexture.enableRandomWrite = true;
        drawTexture.Create();

        // スレッド数の取得
        uint threadSizeX, threadSizeY, threadSizeZ;

        computeShader.GetKernelThreadGroupSizes(kernelInitialize, out threadSizeX, out threadSizeY, out threadSizeZ);
        threadSizeInitialize = new ThreadSize(threadSizeX, threadSizeY, threadSizeZ);
        computeShader.GetKernelThreadGroupSizes(kernelUpdate, out threadSizeX, out threadSizeY, out threadSizeZ);
        threadSizeUpdate = new ThreadSize(threadSizeX, threadSizeY, threadSizeZ);
        computeShader.GetKernelThreadGroupSizes(kernelDraw, out threadSizeX, out threadSizeY, out threadSizeZ);
        threadSizeDraw = new ThreadSize(threadSizeX, threadSizeY, threadSizeZ);

        // LifeGameの状態の初期化
        computeShader.SetFloat("keikaTime", Time.time);
        computeShader.SetTexture(kernelInitialize, "stateTexture", stateTexture);
        computeShader.Dispatch(kernelInitialize, Mathf.CeilToInt(stateTexture.width / threadSizeInitialize.x), Mathf.CeilToInt(stateTexture.height / threadSizeInitialize.y), 1);
    }
예제 #3
0
    // Use this for initialization
    void Start()
    {
        // Get the kernel handles
        updateCenterOfMassKernel     = graphPhysicsShader.FindKernel("UpdateCenterOfMass");
        computeSpringForcesKernel    = graphPhysicsShader.FindKernel("ComputeSpringForces");
        computeRepulsionForcesKernel = graphPhysicsShader.FindKernel("ComputeRepulsionForces");
        updatePositionsKernel        = graphPhysicsShader.FindKernel("UpdatePositions");

        uint y, z;

        graphPhysicsShader.GetKernelThreadGroupSizes(computeSpringForcesKernel, out computeSpringForcesNbThreads, out y, out z);
        if (y != 1 || z != 1)
        {
            throw new UnityException("shader kernels' logic should work on the x dimension only");
        }
        graphPhysicsShader.GetKernelThreadGroupSizes(computeRepulsionForcesKernel, out computeRepulsionForcesNbThreads, out y, out z);
        if (y != 1 || z != 1)
        {
            throw new UnityException("shader kernels' logic should work on the x dimension only");
        }
        graphPhysicsShader.GetKernelThreadGroupSizes(updatePositionsKernel, out updatePositionsNbThreads, out y, out z);
        if (y != 1 || z != 1)
        {
            throw new UnityException("shader kernels' logic should work on the x dimension only");
        }

        listener.OnNewTx.AddListener(NewLink);
    }
예제 #4
0
    // Start is called before the first frame update
    void OnValidate()
    {
        if (compute == null)
        {
            return;
        }
        // round up to thread group size
        var sdfCompute = compute.FindKernel("SphereSDF");

        compute.GetKernelThreadGroupSizes(sdfCompute, out uint x, out uint y, out uint z);

        if ((textureSize.x % x) != 0)
        {
            textureSize.x = (1 + (textureSize.x / (int)x)) * (int)x;
        }

        if ((textureSize.y % y) != 0)
        {
            textureSize.y = (1 + (textureSize.y / (int)y)) * (int)y;
        }

        if ((textureSize.z % z) != 0)
        {
            textureSize.z = (1 + (textureSize.z / (int)z)) * (int)z;
        }
        textureSize.z = textureSize.y = textureSize.x;
    }
    private void InitSetup(Texture humanDepthTexture)
    {
        if (_lastDeviceOrientation == DeviceOrientation.Portrait)
        {
            _tempRenderTexture = new RenderTexture(_positionMapPortrait.width, _positionMapPortrait.height, 0, _positionMapPortrait.format)
            {
                enableRandomWrite = true
            };
            _tempRenderTexture.Create();
            _computeShader.SetTexture(_portraitKernel, PropertyID_Target, _tempRenderTexture);
            _computeShader.GetKernelThreadGroupSizes(_portraitKernel, out _threadSizeX, out _threadSizeY, out _threadSizeZ);
            _computeShader.SetFloat(PropertyID_UVMultiplierPortrait, CalculateUVMultiplierPortrait(humanDepthTexture));
            _visualEffect.SetTexture(PropertyID_PositionMap, _positionMapPortrait);
            _visualEffect.SetTexture(PropertyID_ColorMap, _colorMapPortrait);
        }
        else
        {
            _tempRenderTexture = new RenderTexture(_positionMapLandscape.width, _positionMapLandscape.height, 0, _positionMapLandscape.format)
            {
                enableRandomWrite = true
            };
            _tempRenderTexture.Create();
            _computeShader.SetTexture(_landscapeKernel, PropertyID_Target, _tempRenderTexture);
            _computeShader.GetKernelThreadGroupSizes(_landscapeKernel, out _threadSizeX, out _threadSizeY, out _threadSizeZ);
            _computeShader.SetFloat(PropertyID_UVMultiplierLandScape, CalculateUVMultiplierLandScape(humanDepthTexture));
            _visualEffect.SetTexture(PropertyID_PositionMap, _positionMapLandscape);
            _visualEffect.SetTexture(PropertyID_ColorMap, _colorMapLandscape);
        }

        SetViewPortInv();
    }
예제 #6
0
    private void Start()
    {
        // カーネルIdの取得
        kernelInitialize = _computeShader.FindKernel("Initialize");
        kernelAddWave    = _computeShader.FindKernel("AddWave");
        kernelUpdate     = _computeShader.FindKernel("Update");
        kernelDraw       = _computeShader.FindKernel("Draw");

        // 波の高さを格納するテクスチャの作成
        _waveTexture                   = new RenderTexture(256, 256, 0, RenderTextureFormat.RG32);
        _waveTexture.wrapMode          = TextureWrapMode.Clamp;
        _waveTexture.enableRandomWrite = true;
        _waveTexture.Create();
        // レンダリング用のテクスチャの作成
        _drawTexture = new RenderTexture(256, 256, 0, RenderTextureFormat.ARGB32);
        _drawTexture.enableRandomWrite = true;
        _drawTexture.Create();

        // スレッド数の取得
        uint threadSizeX, threadSizeY, threadSizeZ;

        _computeShader.GetKernelThreadGroupSizes(kernelInitialize, out threadSizeX, out threadSizeY, out threadSizeZ);
        threadSizeInitialize = new ThreadSize(threadSizeX, threadSizeY, threadSizeZ);
        _computeShader.GetKernelThreadGroupSizes(kernelUpdate, out threadSizeX, out threadSizeY, out threadSizeZ);
        threadSizeUpdate = new ThreadSize(threadSizeX, threadSizeY, threadSizeZ);
        _computeShader.GetKernelThreadGroupSizes(kernelDraw, out threadSizeX, out threadSizeY, out threadSizeZ);
        threadSizeDraw = new ThreadSize(threadSizeX, threadSizeY, threadSizeZ);

        // 波の高さの初期化
        _computeShader.SetTexture(kernelInitialize, "waveTexture", _waveTexture);
        _computeShader.Dispatch(kernelInitialize, Mathf.CeilToInt(_waveTexture.width / threadSizeInitialize.x), Mathf.CeilToInt(_waveTexture.height / threadSizeInitialize.y), 1);
    }
예제 #7
0
    public override void InitializeValues(int layersCount)
    {
        var contourGrid = contoursMapLayer.Grid;
        int count       = contourGrid.countX * contourGrid.countY;

        if (contoursMapLayer.ValuesBuffer == null || contoursMapLayer.ValuesBuffer.count != count)
        {
            contoursMapLayer.CreateBuffer();
        }

        int initialValue = excludeCellsWithNoData ? 1 - layersCount : -1;

        // Get kernel thread count
        uint threadsX, threadsY, threadsZ;

        compute.GetKernelThreadGroupSizes(ResetKID, out threadsX, out threadsY, out threadsZ);

        // Calculate threads & groups
        uint threads = threadsX * threadsY * threadsZ;
        int  groups  = (int)((count + threads - 1) / threads);

        // Assign shader variables
        compute.SetBuffer(ResetKID, "contourValues", contoursMapLayer.ValuesBuffer);
        compute.SetInt("contourValueCount", count);
        compute.SetInt("initialValue", initialValue);

        compute.Dispatch(ResetKID, groups, 1, 1);
    }
예제 #8
0
    private void SortPow2(ComputeBufferBase <int> buffer, int count)
    {
        uint gx, gy, gz;

        shader.GetKernelThreadGroupSizes(sortKernel, out gx, out gy, out gz);
        int numGroupsX = Mathf.CeilToInt((count * 0.5f) / gx);

        shader.SetInt("count", count);
        shader.SetBuffer(sortKernel, "data", buffer.Buffer);
        shader.SetBuffer(sortSingleLevelKernel, "data", buffer.Buffer);

        int n = (int)Mathf.Pow(2, Mathf.Ceil(Mathf.Log(count, 2)));

        for (int i = 2; i <= n; i *= 2)
        {
            shader.SetInt("level", i);

            // For phases where the # of required pairwise comparisons exceeds
            // the groupsize, we need to do separate dispatches to synchronize
            // writes across work groups.
            for (int j = i / 2; j > gx; j /= 2)
            {
                shader.SetInt("single_level", j);
                shader.Dispatch(sortSingleLevelKernel, numGroupsX, 1, 1);
            }
            shader.Dispatch(sortKernel, numGroupsX, 1, 1);
        }
    }
    private void UpdateShaderParameters(RenderTexture t, RenderTexture d)
    {
        uint _zf, _zd;

        if (t == null)
        {
            t = _outputRT;
        }

        _materialToShareTexture.SetTexture(_textureName, t);
        _clearKernel      = _shader.FindKernel("Clear");
        _writeDepthKernel = _shader.FindKernel("WriteDepth");
        _displaceKernel   = _shader.FindKernel("DisplaceAlbedo");
        _shader.SetTexture(_clearKernel, "Result", t);
        _shader.SetTexture(_clearKernel, "Depth", d);

        _shader.SetTexture(_writeDepthKernel, "Depth", d);
        _shader.SetTexture(_writeDepthKernel, "DepthTexture", depth);
        _shader.SetTexture(_writeDepthKernel, "Result", t);
        _shader.SetTexture(_writeDepthKernel, "AlbedoTexture", albedo);

        _shader.SetTexture(_displaceKernel, "Result", t);
        _shader.SetTexture(_displaceKernel, "Depth", d);
        _shader.SetTexture(_displaceKernel, "DepthTexture", depth);
        _shader.SetTexture(_displaceKernel, "AlbedoTexture", albedo);

        _shader.GetKernelThreadGroupSizes(_clearKernel, out _xf, out _yf, out _zf);
        _shader.GetKernelThreadGroupSizes(_displaceKernel, out _xd, out _yd, out _zd);
    }
예제 #10
0
    private void UpdateShaderParameters(RenderTexture t, ComputeBuffer myLock)
    {
        uint zf, zw;

        if (t == null)
        {
            t = _outputRT;
        }

        _kernelsLoaded = _shader.HasKernel("WriteDepth") && _shader.HasKernel("Clear");
        if (!_kernelsLoaded)
        {
            Debug.LogError("Shader Kernel compilation error");
            return;
        }

        _materialToShareTexture.SetTexture(_textureName, t);
        _clearKernel      = _shader.FindKernel("Clear");
        _writeDepthKernel = _shader.FindKernel("WriteDepth");

        //_shader.SetBuffer(_clearKernel, "Depth", d);
        _shader.SetTexture(_clearKernel, "Result", t);
        _shader.SetBuffer(_clearKernel, "lock", myLock);

        //_shader.SetBuffer(_writeDepthKernel, "Depth", d);
        _shader.SetBuffer(_writeDepthKernel, "lock", myLock);
        _shader.SetTexture(_writeDepthKernel, "Result", t);
        _shader.SetTexture(_writeDepthKernel, "DepthTexture", depth);
        _shader.SetTexture(_writeDepthKernel, "AlbedoTexture", albedo);



        _shader.GetKernelThreadGroupSizes(_clearKernel, out _xf, out _yf, out zf);
        _shader.GetKernelThreadGroupSizes(_writeDepthKernel, out _xw, out _yw, out zw);
    }
예제 #11
0
    void Start()
    {
        // Reserve render textures
        int reso = (int)Mathf.Pow(2, m_resolution);

        m_renderTextureX = new RenderTexture(reso, reso, 0, RenderTextureFormat.ARGB32);
        m_renderTextureY = new RenderTexture(reso, reso, 0, RenderTextureFormat.ARGB32);
        m_renderTextureX.enableRandomWrite = true;
        m_renderTextureY.enableRandomWrite = true;
        m_renderTextureX.Create();
        m_renderTextureY.Create();

        // Read kernel indices and thread sizes
        m_kernelIdxX = m_computeShader.FindKernel("KernelFuncX");
        m_kernelIdxY = m_computeShader.FindKernel("KernelFuncY");

        uint threadSizeX, threadSizeY, threadSizeZ;

        m_computeShader.GetKernelThreadGroupSizes(m_kernelIdxX, out threadSizeX, out threadSizeY, out threadSizeZ);
        m_kernelThreadSizeX = new ThreadSize(threadSizeX, threadSizeY, threadSizeZ);
        m_computeShader.GetKernelThreadGroupSizes(m_kernelIdxY, out threadSizeX, out threadSizeY, out threadSizeZ);
        m_kernelThreadSizeY = new ThreadSize(threadSizeX, threadSizeY, threadSizeZ);

        m_computeShader.SetTexture(m_kernelIdxX, "textureBuffer", m_renderTextureX);
        m_computeShader.SetTexture(m_kernelIdxY, "textureBuffer", m_renderTextureY);
    }
    public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
    {
        CommandBuffer cmd = CommandBufferPool.Get(profilerTag);

        using (new ProfilingSample(cmd, profilerTag))
        {
            context.ExecuteCommandBuffer(cmd);
            cmd.Clear();

            int width  = renderingData.cameraData.cameraTargetDescriptor.width;
            int height = renderingData.cameraData.cameraTargetDescriptor.height;

            // Downsample
            int reflWidth  = width / 1;
            int reflHeight = height / 1;

            RenderTextureDescriptor desc = new RenderTextureDescriptor();
            desc.width             = reflWidth;
            desc.height            = reflHeight;
            desc.enableRandomWrite = true;
            desc.msaaSamples       = 1;
            desc.dimension         = TextureDimension.Tex2D;
            desc.colorFormat       = RenderTextureFormat.RInt;
            cmd.GetTemporaryRT(ShaderResource.HashTexIdentifier, desc);

            Matrix4x4 view  = renderingData.cameraData.camera.worldToCameraMatrix;
            Matrix4x4 proj  = GL.GetGPUProjectionMatrix(renderingData.cameraData.camera.projectionMatrix, true);
            Matrix4x4 vp    = proj * view;
            Matrix4x4 invVP = (proj * view).inverse;

            cmd.SetComputeMatrixParam(hashShader, "VPMatrix", vp);
            cmd.SetComputeMatrixParam(hashShader, "InvVPMatrix", invVP);
            cmd.SetComputeIntParam(hashShader, "Width", width);
            cmd.SetComputeIntParam(hashShader, "Height", height);
            cmd.SetComputeIntParam(hashShader, "ReflectWidth", reflWidth);
            cmd.SetComputeIntParam(hashShader, "ReflectHeight", reflHeight);

            // Clear Hash Texture
            int  kernel = hashShader.FindKernel("SSPRClear_Main");
            uint threadGroupSizeX = 0, threadGroupSizeY = 0, threadGroupSizeZ = 0;
            hashShader.GetKernelThreadGroupSizes(kernel, out threadGroupSizeX, out threadGroupSizeY, out threadGroupSizeZ);

            cmd.SetComputeTextureParam(hashShader, kernel, "ClearHashTexture", ShaderResource.HashTexIdentifier);
            cmd.DispatchCompute(hashShader, kernel, reflWidth / (int)threadGroupSizeX + 1, height / (int)threadGroupSizeY + 1, 1);

            // Compute Hash Texture
            kernel = hashShader.FindKernel("SSPRHash_Main");
            hashShader.GetKernelThreadGroupSizes(kernel, out threadGroupSizeX, out threadGroupSizeY, out threadGroupSizeZ);

            cmd.SetComputeTextureParam(hashShader, kernel, "DepthTex", ShaderResource.DepthTexIdentifier);
            cmd.SetComputeTextureParam(hashShader, kernel, "HashResult", ShaderResource.HashTexIdentifier);
            cmd.DispatchCompute(hashShader, kernel, reflWidth / (int)threadGroupSizeX + 1, reflHeight / (int)threadGroupSizeY + 1, 1);
        }
        context.ExecuteCommandBuffer(cmd);
        CommandBufferPool.Release(cmd);
    }
예제 #13
0
    public void Insert(ComputeBufferBase <int> values, ComputeBufferBase <int> results)
    {
        uint gx, gy, gz;

        shader.GetKernelThreadGroupSizes(insertKernel, out gx, out gy, out gz);
        int numGroupsX = Mathf.CeilToInt((float)values.Count / gx);

        BindHashSetCommon(insertKernel);
        BindKernelsCommon(insertKernel, values, results);
        shader.Dispatch(insertKernel, numGroupsX, 1, 1);
    }
    private void UpdateShaderParameters(RenderTexture t, ComputeBuffer d, List <ComputeBuffer> d0, ComputeBuffer m)
    {
        uint zf, zd, zw;

        if (t == null)
        {
            t = _outputRT;
        }

        _kernelsLoaded = _shader.HasKernel("WriteDepth") && _shader.HasKernel("DisplaceAlbedo") && _shader.HasKernel("Clear");
        if (!_kernelsLoaded)
        {
            Debug.LogError("Shader Kernel compilation error");
            return;
        }

        _materialToShareTexture.SetTexture(_textureName, t);
        _clearKernel      = _shader.FindKernel("Clear");
        _writeDepthKernel = _shader.FindKernel("WriteDepth");
        _displaceKernel   = _shader.FindKernel("DisplaceAlbedo");

        _shader.SetBuffer(_clearKernel, "Depth", d);
        _shader.SetBuffer(_clearKernel, "Depth0[0]", d0[0]);
        _shader.SetBuffer(_clearKernel, "Depth0[1]", d0[1]);
        _shader.SetBuffer(_clearKernel, "Depth0[2]", d0[2]);
        _shader.SetBuffer(_clearKernel, "Depth0[3]", d0[3]);
        _shader.SetBuffer(_clearKernel, "MutexBuffer", m);
        _shader.SetTexture(_clearKernel, "Result", t);

        _shader.SetBuffer(_writeDepthKernel, "Depth", d);
        _shader.SetBuffer(_writeDepthKernel, "Depth0[0]", d0[0]);
        _shader.SetBuffer(_writeDepthKernel, "Depth0[1]", d0[1]);
        _shader.SetBuffer(_writeDepthKernel, "Depth0[2]", d0[2]);
        _shader.SetBuffer(_writeDepthKernel, "Depth0[3]", d0[3]);
        _shader.SetBuffer(_writeDepthKernel, "MutexBuffer", m);
        _shader.SetTexture(_writeDepthKernel, "Result", t);
        _shader.SetTexture(_writeDepthKernel, "DepthTexture", depth);
        _shader.SetTexture(_writeDepthKernel, "AlbedoTexture", albedo);

        _shader.SetBuffer(_displaceKernel, "Depth", d);
        _shader.SetBuffer(_displaceKernel, "Depth0[0]", d0[0]);
        _shader.SetBuffer(_displaceKernel, "Depth0[1]", d0[1]);
        _shader.SetBuffer(_displaceKernel, "Depth0[2]", d0[2]);
        _shader.SetBuffer(_displaceKernel, "Depth0[3]", d0[3]);
        _shader.SetBuffer(_displaceKernel, "MutexBuffer", m);
        _shader.SetTexture(_displaceKernel, "Result", t);
        _shader.SetTexture(_displaceKernel, "DepthTexture", depth);
        _shader.SetTexture(_displaceKernel, "AlbedoTexture", albedo);

        _shader.GetKernelThreadGroupSizes(_clearKernel, out _xf, out _yf, out zf);
        _shader.GetKernelThreadGroupSizes(_writeDepthKernel, out _xw, out _yw, out zw);
        _shader.GetKernelThreadGroupSizes(_displaceKernel, out _xd, out _yd, out zd);
    }
예제 #15
0
        protected void Initialize()
        {
            SetupProps();

            var kernel = compute.FindKernel("Initialize");

            compute.SetBuffer(kernel, "_Path", pathBuffer);
            compute.SetBuffer(kernel, "_Segments", segmentBuffer);

            uint tx, ty, tz;

            compute.GetKernelThreadGroupSizes(kernel, out tx, out ty, out tz);
            compute.Dispatch(kernel, instancesCount / (int)tx + 1, (int)ty, (int)tz);
        }
예제 #16
0
    public override void InitializeValues(int layersCount, Vector2[] boundary)
    {
        var contourGrid = contoursMapLayer.Grid;
        int count       = contourGrid.countX * contourGrid.countY;

        if (contoursMapLayer.ValuesBuffer == null || contoursMapLayer.ValuesBuffer.count != count)
        {
            contoursMapLayer.CreateBuffer();
        }

        int kernelID = boundary == null ? Reset_KID : (excludeCellsWithNoData ? ClipViewArea_Exclude_KID : ClipViewArea_Include_KID);

        int initialValue = excludeCellsWithNoData ? 1 - layersCount : 1;

        // Get kernel thread count
        compute.GetKernelThreadGroupSizes(kernelID, out uint threadsX, out uint threadsY, out uint threadsZ);

        // Calculate threads & groups
        uint threads = threadsX * threadsY * threadsZ;
        int  groups  = (int)((count + threads - 1) / threads);

        // Assign shader variables
        compute.SetBuffer(kernelID, "contourValues", contoursMapLayer.ValuesBuffer);
        compute.SetInt("contourValueCount", count);
        compute.SetInt("initialValue", initialValue);

        if (boundary != null)
        {
            // Calculate scale and offset
            var    metersNW = GeoCalculator.LonLatToMeters(contourGrid.west, contourGrid.north);
            var    metersSE = GeoCalculator.LonLatToMeters(contourGrid.east, contourGrid.south);
            double scaleX   = (metersSE.x - metersNW.x) / contourGrid.countX;
            double scaleY   = (contourGrid.south - contourGrid.north) / contourGrid.countY;
            double offsetX  = metersNW.x + 0.5 * scaleX;
            double offsetY  = contourGrid.north + 0.5 * scaleY;

            compute.SetInt("contourCountX", contourGrid.countX);
            compute.SetVector("offset", new Vector2((float)offsetX, (float)offsetY));
            compute.SetVector("scale", new Vector2((float)scaleX, (float)scaleY));
            for (int i = 0; i < boundary.Length; i++)
            {
                compute.SetVector("pt" + i, boundary[i]);
            }
        }

        compute.Dispatch(kernelID, groups, 1, 1);
        contoursMapLayer.SetGpuChangedValues();
    }
    // Start is called before the first frame update
    void Start()
    {
        int width  = Mathf.FloorToInt(src.width * widthScale);
        int height = Mathf.FloorToInt(src.height * heightScale);

        kernelIndexHorizontal = sorterKernel.FindKernel("PixelSortKernelHorizontal");
        kernelIndexVertical   = sorterKernel.FindKernel("PixelSortKernelVertical");

        buffers = new RenderTexture[2];
        for (var i = 0; i < buffers.Length; i++)
        {
            buffers[i] = new RenderTexture(width, height, 0, RenderTextureFormat.ARGB32)
            {
                enableRandomWrite = true
            };
            buffers[i].Create();
        }

        mat = GetComponent <Renderer>().sharedMaterial;

        resizeKernelIndex = resizeKernel.FindKernel(GetKernelString(resizeMethod));
        resizeKernel.GetKernelThreadGroupSizes(resizeKernelIndex, out uint threadX, out uint threadY, out uint threadZ);
        groupNumX = Mathf.CeilToInt((float)width / threadX);
        groupNumY = Mathf.CeilToInt((float)height / threadY);

        resizedSrc = new RenderTexture(width, height, 0, RenderTextureFormat.ARGB32)
        {
            enableRandomWrite = true
        };
        resizedSrc.Create();

        resizeKernel.SetTexture(resizeKernelIndex, "src", src);
        resizeKernel.SetTexture(resizeKernelIndex, "dest", resizedSrc);
    }
        public DualQuaternionBlendSkinningDispatcher(ComputeShader computeShader, RenderChunk chunk, Transform[] bones, Func <ComputeBuffer> getPerVertexBuffer, Func <ComputeBuffer> getPerVertexSkinBuffer, Func <ComputeBuffer> getPerVertexStream)
        {
            this.computeShader = computeShader;
            kernelIndex        = computeShader.FindKernel("DualQuaternionBlendCompute");
            computeShader.GetKernelThreadGroupSizes(kernelIndex, out maxThreadSizeX, out maxThreadSizeY, out maxThreadSizeZ);

            vertexCount = chunk.vertexCount;

            this.bones         = bones;
            currentPoseDQArray = new DualQuaternion[bones.Length];

            boneRestPoseDQBuffer    = new ComputeBuffer(bones.Length, Marshal.SizeOf(typeof(DualQuaternion)));
            boneCurrentPoseDQBuffer = new ComputeBuffer(bones.Length, Marshal.SizeOf(typeof(DualQuaternion)));

            boneRestPoseDQBuffer.SetData(chunk.inverseRestPoseDQArray);

            computeShader.SetInt("vertexCount", vertexCount);

            computeShader.SetBuffer(kernelIndex, "currPoseDQ", boneCurrentPoseDQBuffer);
            computeShader.SetBuffer(kernelIndex, "restPoseDQ", boneRestPoseDQBuffer);

            computeShader.SetBuffer(kernelIndex, "vertices", getPerVertexBuffer());
            computeShader.SetBuffer(kernelIndex, "skin", getPerVertexSkinBuffer());
            computeShader.SetBuffer(kernelIndex, "output", getPerVertexStream());
        }
        public LinearBlendSkinningDispatcher(ComputeShader computeShader, RenderChunk chunk, Transform[] bones, Func <ComputeBuffer> getPerVertexBuffer, Func <ComputeBuffer> getPerVertexSkinBuffer, Func <ComputeBuffer> getPerVertexStream)
        {
            this.computeShader = computeShader;
            kernelIndex        = computeShader.FindKernel("LinearBlendCompute");
            computeShader.GetKernelThreadGroupSizes(kernelIndex, out maxThreadSizeX, out maxThreadSizeY, out maxThreadSizeZ);

            vertexCount = chunk.vertexCount;

            this.bones             = bones;
            currentPoseMatrixArray = new Matrix4x4[bones.Length];

            boneRestPoseMatrixBuffer = new ComputeBuffer(bones.Length, Marshal.SizeOf(typeof(Matrix4x4)));
            boneRestPoseMatrixBuffer.SetData(chunk.inverseRestPoseMatrixArray);

            boneCurrentPoseMatrixBuffer = new ComputeBuffer(bones.Length, Marshal.SizeOf(typeof(Matrix4x4)));
            for (int i = 0; i < currentPoseMatrixArray.Length; i++)
            {
                currentPoseMatrixArray[i] = bones[i].localToWorldMatrix;
            }
            boneCurrentPoseMatrixBuffer.SetData(currentPoseMatrixArray);

            computeShader.SetInt("vertexCount", vertexCount);

            computeShader.SetBuffer(kernelIndex, "currPoseMtrx", boneCurrentPoseMatrixBuffer);
            computeShader.SetBuffer(kernelIndex, "restPoseMtrx", boneRestPoseMatrixBuffer);

            computeShader.SetBuffer(kernelIndex, "vertices", getPerVertexBuffer());
            computeShader.SetBuffer(kernelIndex, "skin", getPerVertexSkinBuffer());
            computeShader.SetBuffer(kernelIndex, "output", getPerVertexStream());
        }
예제 #20
0
        void JoinTextures(Texture texture, Texture mask, string kernelName, ref RenderTexture dest)
        {
            if (!SystemInfo.supportsComputeShaders)
            {
#if UNITY_EDITOR && !UNITY_STANDALONE
                Debug.LogError("Compute shaders are not supported for the Android platform in the editor.\n" +
                               "Switch the platform to Standalone (this is not relevant for the assembled project).");
#else
                Debug.LogError("Compute shaders are not supported.");
#endif
                return;
            }

            if (texture == null || mask == null)
            {
                return;
            }

            int kernelIndex = ComputeShader.FindKernel(kernelName);
            instanceShader.GetKernelThreadGroupSizes(kernelIndex, out uint x, out uint y, out uint z);

            instanceShader.SetTexture(kernelIndex, "Texture", texture);
            instanceShader.SetTexture(kernelIndex, "Mask", mask);

            if (dest == null)
            {
                dest = new RenderTexture(texture.width, texture.height, 0, RenderTextureFormat.ARGB32);
                dest.enableRandomWrite = true;
                dest.Create();
            }

            instanceShader.SetTexture(kernelIndex, "Output", dest);

            instanceShader.Dispatch(kernelIndex, dest.width / (int)x, dest.height / (int)y, (int)z);
        }
        void Initialize()
        {
            computeShaderInstance = computeShader;
            //computeShaderInstance = (ComputeShader)Resources.Load("Instancing");
            render = GetComponent <Renderer>();
            uint threadX, threadY, threadZ;

            kernelMap = System.Enum.GetValues(typeof(ComputeKernels))
                        .Cast <ComputeKernels>()
                        .ToDictionary(t => t, t => computeShaderInstance.FindKernel(t.ToString()));


            //kernel sizeを取得
            computeShaderInstance.GetKernelThreadGroupSizes(kernelMap[ComputeKernels.Emit], out threadX, out threadY, out threadZ);
            gpuThreads = new GPUThreads(threadX, threadY, threadZ);

            /*--express
             * //-https://docs.unity3d.com/ja/current/ScriptReference/ComputeBufferType.html
             * //ComputeBuffer (int count, int stride, ComputeBufferType type);
             * //strudeはバッファ一つ値の型
             * //args = new uint[5] { 0, 0, 0, 0, 0 };
             * -----*/
            argsBuffer = new ComputeBuffer(1, args.Length * sizeof(uint), ComputeBufferType.IndirectArguments);

            bufferPropId           = Shader.PropertyToID("buf");
            timesPropId            = Shader.PropertyToID("times");
            convergencePropId      = Shader.PropertyToID("convergence");
            viscosityPropId        = Shader.PropertyToID("viscosity");
            additionalVectorPropId = Shader.PropertyToID("additionalVector");
            modelMatrixPropId      = Shader.PropertyToID("modelMatrix");
            valPropId = Shader.PropertyToID("val");

            InitialCheck();
            UpdateBuffers();
        }
예제 #22
0
        public static float Loss(ComputeShader compute, Signal input, Signal answer)
        {
            int batchSize = input.Rows;

            Signal temp = new Signal(answer.Rows, answer.Columns);

            var kernel = compute.FindKernel("Log");
            int rows = temp.Rows, columns = temp.Columns;

            uint tx, ty, tz;

            compute.GetKernelThreadGroupSizes(kernel, out tx, out ty, out tz);
            compute.SetInt("_Rows", rows);
            compute.SetInt("_Cols", columns);
            compute.SetBuffer(kernel, "_X", input.Buffer);
            compute.SetBuffer(kernel, "_T", answer.Buffer);
            compute.SetBuffer(kernel, "_Y", temp.Buffer);
            compute.Dispatch(kernel, Mathf.FloorToInt(((int)columns - 1) / tx) + 1, Mathf.FloorToInt(((int)rows - 1) / ty) + 1, (int)tz);

            float[,] log = temp.GetData();

            float sum = 0f;

            for (int y = 0; y < rows; y++)
            {
                for (int x = 0; x < columns; x++)
                {
                    sum += log[y, x];
                }
            }

            temp.Dispose();

            return(-sum / batchSize);
        }
예제 #23
0
        public static int GetKernelThreadGroupSizeX(this ComputeShader compute, int kernel)
        {
            uint cx, cy, cz;

            compute.GetKernelThreadGroupSizes(kernel, out cx, out cy, out cz);
            return((int)cx);
        }
        public void RenderRayCount(CommandBuffer cmd, HDCamera camera, Color fontColor)
        {
            if (m_RayCountEnabled)
            {
                using (new ProfilingSample(cmd, "Raytracing Debug Overlay", CustomSamplerId.RaytracingDebug.GetSampler()))
                {
                    int width  = camera.actualWidth;
                    int height = camera.actualHeight;

                    // Sum across all rays per pixel
                    int  countKernelIdx = m_RayCountCompute.FindKernel("CS_CountRays");
                    uint groupSizeX = 0, groupSizeY = 0, groupSizeZ = 0;
                    m_RayCountCompute.GetKernelThreadGroupSizes(countKernelIdx, out groupSizeX, out groupSizeY, out groupSizeZ);
                    int dispatchWidth = 0, dispatchHeight = 0;
                    dispatchWidth  = (int)((width + groupSizeX - 1) / groupSizeX);
                    dispatchHeight = (int)((height + groupSizeY - 1) / groupSizeY);
                    cmd.SetComputeTextureParam(m_RayCountCompute, countKernelIdx, HDShaderIDs._RayCountTexture, m_RayCountTex);
                    cmd.SetComputeBufferParam(m_RayCountCompute, countKernelIdx, _TotalRayCountBuffer, s_TotalRayCountBuffer);
                    cmd.DispatchCompute(m_RayCountCompute, countKernelIdx, dispatchWidth, dispatchHeight, 1);

                    // Draw overlay
                    m_DrawRayCountProperties.SetTexture(HDShaderIDs._DebugFont, s_DebugFontTex);
                    m_DrawRayCountProperties.SetColor(_FontColor, fontColor);
                    m_DrawRayCount.SetBuffer(_TotalRayCountBuffer, s_TotalRayCountBuffer);
                    CoreUtils.DrawFullScreen(cmd, m_DrawRayCount, m_DrawRayCountProperties);
                }
            }
        }
        public static int GetThreadPerGroup(ComputeShader shader, int kernal, int count)
        {
            uint x, y, z;

            shader.GetKernelThreadGroupSizes(kernal, out x, out y, out z);
            return(Mathf.CeilToInt(count / (float)x));
        }
예제 #26
0
        public static void Dispatch(ComputeShader cs, int kernel, Vector3 threadNum)
        {
            uint x, y, z;

            cs.GetKernelThreadGroupSizes(kernel, out x, out y, out z);
            cs.Dispatch(kernel, Mathf.CeilToInt(threadNum.x / x), Mathf.CeilToInt(threadNum.y / y), Mathf.CeilToInt(threadNum.z / z));
        }
예제 #27
0
        DoubleRenderTexture m_obstacles;                //	HACK:2枚も必要ないけど流用

        void Start()
        {
            m_applyImpulse.GetKernelThreadGroupSizes(0, out KernelThreadSize_X, out KernelThreadSize_Y, out KernelThreadSize_Z);

            //Dimension sizes must be pow2 numbers
            m_width  = Mathf.ClosestPowerOfTwo(m_width);
            m_height = Mathf.ClosestPowerOfTwo(m_height);
            m_depth  = Mathf.ClosestPowerOfTwo(m_depth);

            //	オブジェクトのスケールを合わせる
            transform.localScale    = new Vector3(m_width, m_height, m_depth);
            transform.localPosition = new Vector3(0, m_height / 2, 0);

            //Put all dimension sizes in a vector for easy parsing to shader and also prevents user changing
            //dimension sizes during play
            m_size = new Vector4(m_width, m_height, m_depth, 0.0f);

            //Create all the buffers needed

            int SIZE = m_width * m_height * m_depth;

            m_atmosphere = new DoubleRenderTexture(m_width, m_height, m_depth);

            m_velocity   = new DoubleRenderTexture(m_width, m_height, m_depth);
            m_vorticity  = new DoubleRenderTexture(m_width, m_height, m_depth);
            m_divergence = new DoubleRenderTexture(m_width, m_height, m_depth);
            m_pressure   = new DoubleRenderTexture(m_width, m_height, m_depth);

            m_obstacles = new DoubleRenderTexture(m_width, m_height, m_depth);

            //Any areas that are obstacles need to be masked of in the obstacle buffer
            //At the moment is only the border around the edge of the buffers to enforce non-slip boundary conditions
            ComputeObstacles();
        }
예제 #28
0
    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);
    }
예제 #29
0
    private void Process(CommandBuffer _cmd)
    {
        int kernel = isInitial ? csParticle.FindKernel("CSMain") : csParticle.FindKernel("CSInitial");

        isInitial = true;

        uint sizeX;

        csParticle.GetKernelThreadGroupSizes(
            kernel,
            out sizeX,
            out _,
            out _
            );

        // set perlin
        csParticle.SetBuffer(kernel, perlinBufferID, perlinBuffer);
        csParticle.SetInt(octavesID, 2);

        // set curl
        csParticle.SetBuffer(kernel, particleBufferID, particleBuffer);
        csParticle.SetInt(particleCountID, PARTICLE_COUNT);
        csParticle.SetFloat(noiseScaleID, NOISE_SCALE);
        csParticle.SetFloat(speedFactorID, SPEED_FACTOR);
        csParticle.SetFloat(liftTimeID, LIFT_TIME);

        csParticle.SetFloat(deltaTimeID, Time.deltaTime);
        csParticle.SetFloat(elapsedTimeID, Time.time);

        csParticle.SetVector(particlePosWorldID, this.transform.position);

        _cmd.DispatchCompute(csParticle, kernel,
                             Mathf.CeilToInt((PARTICLE_COUNT + sizeX - 1) / sizeX),
                             1, 1);
    }
        private void DispatchCS()
        {
            if (!shouldDispatchCS)
            {
                return;
            }

            shouldDispatchCS = false;
            p.ApplyToCS(cs);
            var  k = cs.FindKernel(GetCurrentNoiseName());
            uint x, y, z;

            cs.GetKernelThreadGroupSizes(k, out x, out y, out z);
            var tSize        = Monobelisk.Utility.GetTerrainVertexSize();
            var csResolution = noisePreview.width;

            var prevWeights = new Vector4
                              (
                EditorPrefs.GetBool(NOISE_PREVIEW_R, true) ? 1 : 0,
                EditorPrefs.GetBool(NOISE_PREVIEW_G, true) ? 1 : 0,
                EditorPrefs.GetBool(NOISE_PREVIEW_B, true) ? 1 : 0,
                EditorPrefs.GetBool(NOISE_PREVIEW_A, true) ? 1 : 0
                              );

            cs.SetFloat("originalHeight", Monobelisk.Utility.GetOriginalTerrainHeight());
            cs.SetFloat("newHeight", Constants.TERRAIN_HEIGHT);
            cs.SetInt("heightmapResolution", csResolution);
            cs.SetVector("terrainPosition", Monobelisk.Utility.GetTerrainVertexPosition(previewMapPixelX, previewMapPixelY));
            cs.SetVector("terrainSize", new Vector2(tSize, tSize) * previewScale);
            cs.SetVector("worldSize", Monobelisk.Utility.GetWorldVertexSize());
            cs.SetVector("prevWeights", prevWeights);
            cs.SetTexture(k, "Result", noisePreview);

            cs.Dispatch(k, csResolution / (int)x, csResolution / (int)y, (int)z);
        }