SetData() private method

private SetData ( Array data ) : void
data Array
return void
Ejemplo n.º 1
1
 public WallService(int capacity)
 {
     this.capacity = capacity;
     _colliders = new List<Transform>(capacity);
     _walls = new Wall[capacity];
     Walls = new ComputeBuffer(capacity, Marshal.SizeOf(typeof(Wall)));
     Walls.SetData(_walls);
 }
Ejemplo n.º 2
0
        void Awake()
        {
            var mf = prefab.GetComponent<MeshFilter>();
            var mesh = mf.sharedMesh;

            _indexBuf = new ComputeBuffer(mesh.triangles.Length, Marshal.SizeOf(mesh.triangles[0]));
            _indexBuf.SetData(mesh.triangles);

            _vertexBuf = new ComputeBuffer(mesh.vertices.Length, Marshal.SizeOf(mesh.vertices[0]));
            _vertexBuf.SetData(mesh.vertices);

            _uvBuf = new ComputeBuffer(mesh.uv.Length, Marshal.SizeOf(mesh.uv[0]));
            _uvBuf.SetData(mesh.uv);

            var gofab = new GameObject("Position");
            gofab.hideFlags = HideFlags.HideAndDontSave;
            _trs = GenerateRandom(gofab, count);
            _worlds = new float[16 * _trs.Length];
            _worldBuf = new ComputeBuffer(_trs.Length, 16 * Marshal.SizeOf(_worlds[0]));
            UpdateWorlds();

            _mat = new Material(prefab.renderer.sharedMaterial);
            _mat.SetBuffer(CS_INDEX_BUFFER, _indexBuf);
            _mat.SetBuffer(CS_VERTEX_BUFFER, _vertexBuf);
            _mat.SetBuffer(CS_UV_BUFFER, _uvBuf);
            _mat.SetBuffer(CS_WORLD_BUFFER, _worldBuf);
        }
Ejemplo n.º 3
0
    /// <summary>
    /// Uses the GPU to generate a RenderTexture where the pixels in the texture represent noise.
    /// Set the octaves variable before calling this to a desired value.
    /// </summary>
    /// <returns>RenderTexture</returns>
    /// <param name="width"> Width of the texture to generate. </param>
    /// <param name="height"> Height of the texture to generate. </param>
    /// <param name="noiseOffsetX"> X Coordinate of the offset for the noise on the texture. </param>
    /// <param name="noiseOffsetY"> Y Coordinate of the offset for the noise on the texture. </param>
    /// <param name="noiseScale"> Value to scale the noise coordinates by. </param>
    /// <param name="normalize"> Whether or not to remap the noise from (-1, 1) to (0, 1). </param>
    public static UnityEngine.RenderTexture GetNoiseRenderTexture(int width, int height, float noiseOffsetX = 0, float noiseOffsetY = 0, float noiseScale = 0.01f, bool normalize = true)
    {
        UnityEngine.RenderTexture retTex = new UnityEngine.RenderTexture(width, height, 0);
        retTex.enableRandomWrite = true;
        retTex.Create();

        UnityEngine.ComputeShader shader = UnityEngine.Resources.Load(shaderPath) as UnityEngine.ComputeShader;
        if (shader == null)
        {
            UnityEngine.Debug.LogError(noShaderMsg);
            return(null);
        }

        int[] resInts = { width, height };

        int kernel = shader.FindKernel("ComputeNoise");

        shader.SetTexture(kernel, "Result", retTex);
        SetShaderVars(shader, new UnityEngine.Vector2(noiseOffsetX, noiseOffsetY), normalize, noiseScale);
        shader.SetInts("reses", resInts);

        UnityEngine.ComputeBuffer permBuffer = new UnityEngine.ComputeBuffer(perm.Length, 4);
        permBuffer.SetData(perm);
        shader.SetBuffer(kernel, "perm", permBuffer);

        shader.Dispatch(kernel, width / 14, height / 15, 1);

        permBuffer.Release();

        return(retTex);
    }
 static public int SetData(IntPtr l)
 {
     try {
                     #if DEBUG
         var    method     = System.Reflection.MethodBase.GetCurrentMethod();
         string methodName = GetMethodName(method);
                     #if UNITY_5_5_OR_NEWER
         UnityEngine.Profiling.Profiler.BeginSample(methodName);
                     #else
         Profiler.BeginSample(methodName);
                     #endif
                     #endif
         UnityEngine.ComputeBuffer self = (UnityEngine.ComputeBuffer)checkSelf(l);
         System.Array a1;
         checkType(l, 2, out a1);
         self.SetData(a1);
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
             #if DEBUG
     finally {
                     #if UNITY_5_5_OR_NEWER
         UnityEngine.Profiling.Profiler.EndSample();
                     #else
         Profiler.EndSample();
                     #endif
     }
             #endif
 }
Ejemplo n.º 5
0
        public static Tensor InvokeFunctionKernel(string name, Tensor input)
        {
            var compute = Pix2PixResources.Compute;
            var kernel  = compute.FindKernel(name);

            uint tgn_x, tgn_y, tgn_z;

            compute.GetKernelThreadGroupSizes(kernel, out tgn_x, out tgn_y, out tgn_z);
            Debug.Assert(tgn_y == 1 && tgn_z == 1);

            var length = input.Data.Length;

            Debug.Assert(length % tgn_x == 0);

            var buffer_input  = new UnityEngine.ComputeBuffer(length, sizeof(float));
            var buffer_output = new UnityEngine.ComputeBuffer(length, sizeof(float));

            buffer_input.SetData(input.Data);
            compute.SetBuffer(kernel, "Input", buffer_input);
            compute.SetBuffer(kernel, "Output", buffer_output);
            compute.Dispatch(kernel, length / (int)tgn_x, 1, 1);

            var output = new Tensor(input.Shape);

            buffer_output.GetData(output.Data);

            buffer_input.Dispose();
            buffer_output.Dispose();

            return(output);
        }
Ejemplo n.º 6
0
    public void Init()
    {
        _numParticlesX = _particleGroupsX * kNumThreadsX;
        _numParticlesY = _particleGroupsY * kNumThreadsY;
        _numParticles = _numParticlesX * _numParticlesY;

        _currentCopiedVertices = 0;

        _particleMaterial = Resources.Load<Material>("GPUParticleMat");

        _computeShader = Resources.Load<ComputeShader>("ComputeShaders/GPUParticleUpdater");
        _kernelMoveParticles = _computeShader.FindKernel(kKernelMoveParticles);

        _particlesData = new Particle[_numParticles];
        InitBuffer(_particlesData);

        for (int i = 0; i < _particlesData.Length; ++i)
        {
            float id = ((float)i) / 10000.1f;
            CreateParticle(id);
        }

        // Set ComputeShader Parameters
        _particlesBuffer = new ComputeBuffer(_particlesData.Length, System.Runtime.InteropServices.Marshal.SizeOf(typeof(GPUParticleSystem.Particle)));
        _particlesBuffer.SetData(_particlesData);

        _computeShader.SetBuffer(_kernelMoveParticles, "_ParticlesBuffer", _particlesBuffer);

        _computeShader.SetFloat("_Width", _numParticlesX);
        _computeShader.SetFloat("_Height", _numParticlesY);

        // Set Shader Parameters
        _particleMaterial.SetBuffer("_ParticlesBuffer", _particlesBuffer);
    }
Ejemplo n.º 7
0
    void CreateResources()
    {
        NumInstances = SceneManager.Get.NumProteinInstances;

        if (quadUVs == null)
        {
            var uvs = quadMesh.uv;
            quadUVs = new ComputeBuffer(uvs.Length, sizeof(float) * 2);
            quadUVs.SetData(uvs);
        }

        if (quadIndices == null)
        {
            var indices = quadMesh.triangles;
            quadIndices = new ComputeBuffer(indices.Length, sizeof(float) * 1);
            quadIndices.SetData(indices);
        }

        if (quadVertices == null)
        {
            var normals = quadMesh.vertices;
            quadVertices = new ComputeBuffer(normals.Length, sizeof(float) * 3);
            quadVertices.SetData(normals);
        }

        if (true)
        {
            var colors = new Color[NumInstances];
            for (int i = 0; i < NumInstances; i++)
            {
                //colors[i] = new Color(Random.value, Random.value, Random.value, 0.2f);
                Vector4 col = SceneManager.Get.ProteinColors[(int) SceneManager.Get.ProteinInstanceInfos[i].x];

                //TODO: expose orderedEntities in trannimation manager, acces it here as orderedEntities[i].isFinalized() ? 1.0 : 0.0 use this as alpha. THEN make the alpha actuall alpha in the shader
                colors[i] = new Color(col.x, col.y, col.z, TrannimationManager.Get.getInstanceBillboardAlpha(i));
            }

            if (instanceColors == null)
                instanceColors = new ComputeBuffer(NumInstances, sizeof(float) * 4);

            instanceColors.SetData(colors);
        }

        if (/*instancePositions == null &&*/ TrannimationManager.Get.upload != null && TrannimationManager.Get.upload.Length >= NumInstances - 1)
        {
            var positions = new Vector3[NumInstances];
            for (int i = 0; i < NumInstances; i++)
            {
                //positions[i] = SceneManager.Get.ProteinInstancePositions[i] * PersistantSettings.Instance.Scale;  //Random.insideUnitSphere * SpawnRegionSize;
                positions[i] = TrannimationManager.Get.upload[i] * PersistantSettings.Instance.Scale;
            }

            if (instancePositions == null)
                instancePositions = new ComputeBuffer(NumInstances, sizeof(float) * 3);

            instancePositions.SetData(positions);
        }
    }
Ejemplo n.º 8
0
 public PositionService(ComputeShader compute, int capacity)
 {
     _kernelUpload = compute.FindKernel(ShaderConst.KERNEL_UPLOAD_POSITION);
     _compute = compute;
     _positions = new Vector2[capacity];
     P0 = new ComputeBuffer(capacity, Marshal.SizeOf(_positions[0]));
     P0.SetData(_positions);
     _uploader = new ComputeBuffer(INITIAL_CAP, Marshal.SizeOf(_positions[0]));
     ShaderUtil.CalcWorkSize(capacity, out SimSizeX, out SimSizeY, out SimSizeZ);
 }
Ejemplo n.º 9
0
 public HashService(ComputeShader compute, LifeService l, PositionService p)
 {
     _compute = compute;
     _lifes = l;
     _positions = p;
     _kernelInitHashes = compute.FindKernel(ShaderConst.KERNEL_INIT_HASHES);
     HashData = new int[l.Lifes.count];
     Hashes = new ComputeBuffer(l.Lifes.count, Marshal.SizeOf(typeof(int)));
     Hashes.SetData (HashData);
 }
Ejemplo n.º 10
0
        public static Tensor InvokeConvolutionKernel(
            ConvolutionMode mode, string name, Tensor input, Tensor filter, Tensor bias
            )
        {
            var compute = Pix2PixResources.Compute;
            var kernel  = compute.FindKernel(name);

            uint tgn_x, tgn_y, tgn_z;

            compute.GetKernelThreadGroupSizes(kernel, out tgn_x, out tgn_y, out tgn_z);

            var deconv      = (mode == ConvolutionMode.Backward);
            var outHeight   = deconv ? input.Shape[0] * 2 : input.Shape[0] / 2;
            var outWidth    = deconv ? input.Shape[1] * 2 : input.Shape[1] / 2;
            var outChannels = filter.Shape[deconv ? 2 : 3];

            Debug.Assert(outHeight % tgn_z == 0);
            Debug.Assert(outWidth % tgn_y == 0);
            Debug.Assert(outChannels % tgn_x == 0);

            var output = new Tensor(new [] { outHeight, outWidth, outChannels });

            var buffer_input  = new UnityEngine.ComputeBuffer(input.Data.Length, sizeof(float));
            var buffer_filter = new UnityEngine.ComputeBuffer(filter.Data.Length, sizeof(float));
            var buffer_bias   = new UnityEngine.ComputeBuffer(bias.Data.Length, sizeof(float));
            var buffer_output = new UnityEngine.ComputeBuffer(output.Data.Length, sizeof(float));

            buffer_input.SetData(input.Data);
            buffer_filter.SetData(filter.Data);
            buffer_bias.SetData(bias.Data);

            compute.SetInts("InputShape", input.Shape);
            compute.SetInts("FilterShape", filter.Shape);
            compute.SetInts("OutputShape", output.Shape);

            compute.SetBuffer(kernel, "Input", buffer_input);
            compute.SetBuffer(kernel, "Filter", buffer_filter);
            compute.SetBuffer(kernel, "Bias", buffer_bias);
            compute.SetBuffer(kernel, "Output", buffer_output);

            compute.Dispatch(kernel,
                             outChannels / (int)tgn_x,
                             outWidth / (int)tgn_y,
                             outHeight / (int)tgn_z
                             );

            buffer_output.GetData(output.Data);

            buffer_input.Dispose();
            buffer_filter.Dispose();
            buffer_bias.Dispose();
            buffer_output.Dispose();

            return(output);
        }
 static public int SetData(IntPtr l)
 {
     try {
                     #if DEBUG
         var    method     = System.Reflection.MethodBase.GetCurrentMethod();
         string methodName = GetMethodName(method);
                     #if UNITY_5_5_OR_NEWER
         UnityEngine.Profiling.Profiler.BeginSample(methodName);
                     #else
         Profiler.BeginSample(methodName);
                     #endif
                     #endif
         int argc = LuaDLL.lua_gettop(l);
         if (argc == 2)
         {
             UnityEngine.ComputeBuffer self = (UnityEngine.ComputeBuffer)checkSelf(l);
             System.Array a1;
             checkType(l, 2, out a1);
             self.SetData(a1);
             pushValue(l, true);
             return(1);
         }
         else if (argc == 5)
         {
             UnityEngine.ComputeBuffer self = (UnityEngine.ComputeBuffer)checkSelf(l);
             System.Array a1;
             checkType(l, 2, out a1);
             System.Int32 a2;
             checkType(l, 3, out a2);
             System.Int32 a3;
             checkType(l, 4, out a3);
             System.Int32 a4;
             checkType(l, 5, out a4);
             self.SetData(a1, a2, a3, a4);
             pushValue(l, true);
             return(1);
         }
         pushValue(l, false);
         LuaDLL.lua_pushstring(l, "No matched override function SetData to call");
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
             #if DEBUG
     finally {
                     #if UNITY_5_5_OR_NEWER
         UnityEngine.Profiling.Profiler.EndSample();
                     #else
         Profiler.EndSample();
                     #endif
     }
             #endif
 }
Ejemplo n.º 12
0
        public LifeService(ComputeShader compute, int capacity)
        {
            _compute = compute;
            _kernelSimulate = compute.FindKernel(ShaderConst.KERNEL_SIMULATE_LIFE);
            _kernelUpload = compute.FindKernel(ShaderConst.KERNEL_UPLOAD_LIFE);
            _lifes = new float[capacity];
            Lifes = new ComputeBuffer(capacity, Marshal.SizeOf(typeof(float)));
            Lifes.SetData(_lifes);
            _uploader = new ComputeBuffer(INIT_CAPACITY, Marshal.SizeOf(typeof(float)));

            ShaderUtil.CalcWorkSize(capacity, out SimSizeX, out SimSizeY, out SimSizeZ);
        }
Ejemplo n.º 13
0
    public static List<Vector4> GetClusters(List<Vector4> atoms, int numCentroids)
    {
        if (ComputeShaderManager.Instance.KMeansCS == null) throw new Exception("KMeans compute shader not assigned");

        if (numCentroids <= 0) throw new Exception("Num centroids too low");

        var centroids = new List<Vector4>();
        var centroidStep = Mathf.CeilToInt(atoms.Count / (float)numCentroids);
        for (int i = 0; i < numCentroids; i++)
        {
            if (i*centroidStep < atoms.Count)
            {
                centroids.Add(atoms[i * centroidStep]);
            }
            else
            {
                centroids.Add(atoms[UnityEngine.Random.Range(0, atoms.Count)]);
            }
        }

        var centroidBuffer = new ComputeBuffer(numCentroids, 4 * sizeof(float));
        centroidBuffer.SetData(centroids.ToArray());

        var pointBuffer = new ComputeBuffer(atoms.Count, 4 * sizeof(float));
        pointBuffer.SetData(atoms.ToArray());

        var membershipBuffer = new ComputeBuffer(atoms.Count, sizeof(int));

        ComputeShaderManager.Instance.KMeansCS.SetInt("_NumPoints", atoms.Count);
        ComputeShaderManager.Instance.KMeansCS.SetInt("_NumCentroids", numCentroids);

        for (int i = 0; i < 5; i++)
        {
            ComputeShaderManager.Instance.KMeansCS.SetBuffer(0, "_PointBuffer", pointBuffer);
            ComputeShaderManager.Instance.KMeansCS.SetBuffer(0, "_CentroidBuffer", centroidBuffer);
            ComputeShaderManager.Instance.KMeansCS.SetBuffer(0, "_MembershipBuffer", membershipBuffer);
            ComputeShaderManager.Instance.KMeansCS.Dispatch(0, Mathf.CeilToInt(atoms.Count / 1), 1, 1);

            ComputeShaderManager.Instance.KMeansCS.SetBuffer(1, "_PointBuffer", pointBuffer);
            ComputeShaderManager.Instance.KMeansCS.SetBuffer(1, "_NewCentroidBuffer", centroidBuffer);
            ComputeShaderManager.Instance.KMeansCS.SetBuffer(1, "_NewMembershipBuffer", membershipBuffer);
            ComputeShaderManager.Instance.KMeansCS.Dispatch(1, Mathf.CeilToInt(numCentroids / 64.0f), 1, 1);
        }

        var newCentroids = new Vector4[numCentroids];
        centroidBuffer.GetData(newCentroids);

        pointBuffer.Release();
        centroidBuffer.Release();
        membershipBuffer.Release();

        return newCentroids.ToList();
    }
Ejemplo n.º 14
0
 public VelocityService(ComputeShader compute, int capacity)
 {
     _kernelUpload = compute.FindKernel(ShaderConst.KERNEL_UPLOAD_VELOCITY);
     _kernelClampVelocity = compute.FindKernel(ShaderConst.KERNEL_CLAMP_VELOCITY);
     _compute = compute;
     _velocities = new Vector2[capacity];
     V0 = new ComputeBuffer(capacity, Marshal.SizeOf(typeof(Vector2)));
     V1 = new ComputeBuffer(capacity, Marshal.SizeOf(typeof(Vector2)));
     V0.SetData(_velocities);
     V1.SetData(_velocities);
     _uploader = new ComputeBuffer(INITIAL_CAP, Marshal.SizeOf(_velocities[0]));
     ShaderUtil.CalcWorkSize(capacity, out SimSizeX, out SimSizeY, out SimSizeZ);
 }
 static public int SetData(IntPtr l)
 {
     try {
         UnityEngine.ComputeBuffer self = (UnityEngine.ComputeBuffer)checkSelf(l);
         System.Array a1;
         checkType(l, 2, out a1);
         self.SetData(a1);
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Ejemplo n.º 16
0
 void CreateComputeResources()
 {
     if (cbDrawArgs == null)
     {
         cbDrawArgs = new ComputeBuffer (1, 16, ComputeBufferType.DrawIndirect);
         var args= new int[4];
         args[0] = 0; args[1] = 1; args[2] = 0; args[3] = 0;
         cbDrawArgs.SetData (args);
     }
     if (cbPoints == null)
     {
         cbPoints = new ComputeBuffer (90000, 12+16, ComputeBufferType.Append);
     }
 }
 static public int SetData(IntPtr l)
 {
     try{
         UnityEngine.ComputeBuffer self = (UnityEngine.ComputeBuffer)checkSelf(l);
         System.Array a1;
         checkType(l, 2, out a1);
         self.SetData(a1);
         return(0);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
Ejemplo n.º 18
0
	void InitiateBuffers()
	{
		bar[] values = new bar[WIDTH*HEIGHT];
		for(int i=0; i < WIDTH*HEIGHT; ++i)
		{
			values[i].Position = 5.0f;
			values[i].Velocity = 0.0f;
			values[i].h		   = 1.0f;
		}

//		Debug.Log(Marshal.SizeOf(bar));
		_BarBuffer = new ComputeBuffer(WIDTH*HEIGHT, sizeof(float)*3);
		_BarBuffer.SetData(values);
	}
Ejemplo n.º 19
0
    //To setup a ComputeBuffer we pass in the array length, as well as the size in bytes of a single element.
    //We fill the offset buffer with random numbers between 0 and 2*PI.
    void CreateBuffers() {
        offsetBuffer = new ComputeBuffer(VertCount, 4); //Contains a single float value (OffsetStruct)

        float[] values = new float[VertCount];

        for (int i = 0; i < VertCount; i++) {
            values[i] = Random.value * 2 * Mathf.PI;
        }

        offsetBuffer.SetData(values);

        constantBuffer = new ComputeBuffer(1, 4); //Contains a single element (time) which is a float

        outputBuffer = new ComputeBuffer(VertCount, 12); //Output buffer contains vertices (float3 = Vector3 -> 12 bytes)
    }
Ejemplo n.º 20
0
        public static Tensor InvokeNormalizationKernel(
            string name, Tensor input, Tensor scale, Tensor offset
            )
        {
            var compute = Pix2PixResources.Compute;
            var kernel  = compute.FindKernel(name);

            uint tgn_x, tgn_y, tgn_z;

            compute.GetKernelThreadGroupSizes(kernel, out tgn_x, out tgn_y, out tgn_z);

            var length   = input.Data.Length;
            var channels = input.Shape[2];

            Debug.Assert(channels % tgn_x == 0);
            Debug.Assert(channels == scale.Data.Length);
            Debug.Assert(channels == offset.Data.Length);

            var buffer_input  = new UnityEngine.ComputeBuffer(length, sizeof(float));
            var buffer_scale  = new UnityEngine.ComputeBuffer(channels, sizeof(float));
            var buffer_offset = new UnityEngine.ComputeBuffer(channels, sizeof(float));
            var buffer_output = new UnityEngine.ComputeBuffer(length, sizeof(float));

            buffer_input.SetData(input.Data);
            buffer_scale.SetData(scale.Data);
            buffer_offset.SetData(offset.Data);

            compute.SetInts("InputShape", input.Shape);
            compute.SetInts("OutputShape", input.Shape);

            compute.SetBuffer(kernel, "Input", buffer_input);
            compute.SetBuffer(kernel, "Filter", buffer_scale);
            compute.SetBuffer(kernel, "Bias", buffer_offset);
            compute.SetBuffer(kernel, "Output", buffer_output);

            compute.Dispatch(kernel, channels / (int)tgn_x, 1, 1);

            var output = new Tensor(input.Shape);

            buffer_output.GetData(output.Data);

            buffer_input.Dispose();
            buffer_scale.Dispose();
            buffer_offset.Dispose();
            buffer_output.Dispose();

            return(output);
        }
    void Start()
    {
        // Setup the base args buffer
        particleLocations = new Vector4[particleCount];
        //particleColors = new Vector4[particleCount];
        particleTargets = new Vector4[particleCount];

        for (int i = 0; i < particleCount; i++)
        {
            // Generate a random location
            Vector3 newLoc = Random.insideUnitSphere * 0.5f + new Vector3(0.5f,0.5f,0.5f);
            particleLocations[i] = new Vector4(newLoc.x, newLoc.y, newLoc.z, particlePower);
            particleTargets[i] = newLoc;
            //particleColors[i] = new Vector3(Random.value, Random.value, Random.value);
        }

        targetBuffer = new ComputeBuffer(particleCount, 16);
        targetBuffer.SetData(particleTargets);

        //particleColorBuffer = new ComputeBuffer(particleCount, 16);
        //particleColorBuffer.SetData(particleColors);

        particleBuffer = new ComputeBuffer(particleCount, 16);
        particleBuffer.SetData(particleLocations);

        int pixelCount = textureSize * textureSize * textureSize;

        tex3D = new Texture3D( textureSize, textureSize, textureSize, TextureFormat.ARGB32, false);
        tex3D.wrapMode = TextureWrapMode.Clamp;
        tex3D.anisoLevel = 0;

        pixels = new Color[pixelCount];
        volumeBuffer = new ComputeBuffer(pixelCount, 16);
        volumeBuffer.SetData(pixels);

        /*
        volume = new RenderTexture(textureSize, textureSize, 0, RenderTextureFormat.ARGB32);
        volume.volumeDepth = textureSize;
        volume.isVolume = true;
        volume.enableRandomWrite = true;
        volume.Create();
        */

        //renderer.material.SetTexture ("_Volume", tex3D);
        //renderer.material.SetTexture ("_Volume", volume);
        //renderer.material.SetTexture("_dataFieldTex", tex3D);
        marchingCubesMaterial.SetTexture("_dataFieldTex", tex3D);
    }
Ejemplo n.º 22
0
        public GridService(ComputeShader compute, Grid g, HashService h)
        {
            _compute = compute;
            _grid = g;
            _hashes = h;
            _kernelInit = compute.FindKernel(ShaderConst.KERNEL_INIT_GRID);
            _kernelConstruct = compute.FindKernel(ShaderConst.KERNEL_CONSTRUCT_GRID);
            var gridCellCount = g.nx * g.ny;

            StartData = new uint[gridCellCount];
            EndData = new uint[gridCellCount];
            _hashGridStart = new ComputeBuffer(gridCellCount, Marshal.SizeOf(typeof(uint)));
            _hashGridEnd = new ComputeBuffer(gridCellCount, Marshal.SizeOf(typeof(uint)));
            _hashGridStart.SetData (StartData);
            _hashGridEnd.SetData (EndData);
        }
    void InitializeBuffers() {
        VertCount = 10 * 10 * 10 * cubeMultiplier * cubeMultiplier * cubeMultiplier;

        outputBuffer = new ComputeBuffer(VertCount, (sizeof(float) * 3) + (sizeof(int) * 6));
        mapBuffer = new ComputeBuffer(VertCount, sizeof(int));

        int width = 10 * cubeMultiplier;
        int height = 10 * cubeMultiplier;
        int depth = 10 * cubeMultiplier;

        TestNoise noise = new TestNoise(1f, 1f, 3);
        float[][] tempNoiseHeight = new float[10 * cubeMultiplier][];
        for(int i = 0; i < tempNoiseHeight.Length; i++) {
            tempNoiseHeight[i] = new float[10 * cubeMultiplier];

            for(int j = 0; j < tempNoiseHeight[i].Length; j++) {
                tempNoiseHeight[i][j] = noise.GetNoise((double)(i) * 0.05, (double)(j) * 0.14, 0.0) * 0.5f + 0.5f; //UnityEngine.Random.Range(0f, 1f);
            }
        }

        int[] map = new int[VertCount];

        for(int x = 0; x < width; x++) {
            for(int y = 0; y < height; y++) {
                for(int z = 0; z < depth; z++) {
                    int idx = x + (y * 10 * cubeMultiplier) + (z * 10 * cubeMultiplier * 10 * cubeMultiplier);

                    if (tempNoiseHeight[x][z] >= y / (float)height)
                        map[idx] = 1;
                    else
                        map[idx] = 0;
                }
            }
        }

        mapBuffer.SetData(map);

        computeShader.SetBuffer(CSKernel, "outputBuffer", outputBuffer);
        computeShader.SetBuffer(CSKernel, "mapBuffer", mapBuffer);

        computeShader.SetVector("group_size", new Vector3(cubeMultiplier, cubeMultiplier, cubeMultiplier));

        if (Debugrender)
            PointMaterial.SetBuffer("buf_Points", outputBuffer);

        transform.position -= (Vector3.one * 10 * cubeMultiplier) * 0.5f;
    }
    public void RunMultiplyShader() {
        VecMatPair[] data = new VecMatPair[5];
        VecMatPair[] output = new VecMatPair[5];
        // Init Data here!!!
        for (int i = 0; i < data.Length; i++) {
            data[i].point = UnityEngine.Random.onUnitSphere;
            data[i].matrix = Matrix4x4.TRS(UnityEngine.Random.onUnitSphere, UnityEngine.Random.rotation, UnityEngine.Random.onUnitSphere);
            Debug.Log("PreShader! Pos: " + data[i].point.ToString() + ", Matrix: " + data[i].matrix.ToString());
        }

        ComputeBuffer buffer = new ComputeBuffer(data.Length, 76);
        int kernelHandle = shader.FindKernel("Multiply");
        buffer.SetData(data);
        shader.SetBuffer(kernelHandle, "dataBuffer", buffer);
        shader.Dispatch(kernelHandle, data.Length, 1, 1);
        buffer.GetData(output);

        for (int i = 0; i < output.Length; i++) {            
            Debug.Log("PostShader! Pos: " + output[i].point.ToString() + ", Matrix: " + output[i].matrix.ToString());
        }

        buffer.Dispose();

        /*public ComputeShader compute;
        public ComputeBuffer buffer;
        public int[] cols;
   
        void Start () {
        var mesh = GetComponent<MeshFilter>().mesh;
        int n = mesh.vertexCount;
            ///
        buffer = new ComputeBuffer (n, 16);
        ///
        cols = new int[n];
            ///
        for (int i = 0; i < n; ++i)
             cols[i] = 0;      
        buffer.SetData (cols); 
            ///
        compute.SetBuffer(compute.FindKernel ("CSMain"),"bufColors", buffer);
            ///
            compute.Dispatch(0,4,4,1);
        ///
        buffer.GetData(cols);
        Debug.Log (cols[0]); 
        */
    }
Ejemplo n.º 25
0
    void InitializeBuffers()
    {
        VertCount = 10 * 10 * 10 * cubeMultiplier * cubeMultiplier * cubeMultiplier;

        // Set output buffer size.
        outputBuffer = new ComputeBuffer(VertCount, (sizeof(float) * 3) + (sizeof(int) * 6));
        mapBuffer = new ComputeBuffer(VertCount, sizeof(int));

        int width = 10 * cubeMultiplier;
        int height = 10 * cubeMultiplier;
        int depth = 10 * cubeMultiplier;

        PerlinNoise.Seed = Seed;
        float[][] fmap = PerlinNoise.GeneratePerlinNoise(width, height, 8);
        //fmap = PerlinNoise.GeneratePerlinNoise(fmap, 8);

        int[] map = new int[VertCount];

        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                for (int z = 0; z < depth; z++)
                {
                    int idx = x + (y * 10 * cubeMultiplier) + (z * 10 * cubeMultiplier * 10 * cubeMultiplier);

                    if (fmap[x][z] >= y / (float)height)
                        map[idx] = 1;
                    else
                        map[idx] = 0;
                }
            }
        }

        mapBuffer.SetData(map);

        computeShader.SetBuffer(CSKernel, "outputBuffer", outputBuffer);
        computeShader.SetBuffer(CSKernel, "mapBuffer", mapBuffer);

        computeShader.SetVector("group_size", new Vector3(cubeMultiplier, cubeMultiplier, cubeMultiplier));

        if (DebugRender)
            PointMaterial.SetBuffer("buf_Points", outputBuffer);

        transform.position -= (Vector3.one * 10 * cubeMultiplier) *.5f;
    }
    void InitializeBuffers() {
        startPointBuffer = new ComputeBuffer(VertCount, 4);  // float = 4 bytes
        constantBuffer = new ComputeBuffer(1, 4);
        modBuffer = new ComputeBuffer(VertCount, 8);
        outputBuffer = new ComputeBuffer(VertCount, 12);

        float[] values = new float[VertCount];
        Vector2[] mods = new Vector2[VertCount];

        for(int i = 0; i < VertCount; i++) {
            values[i] = Random.value * 2 * Mathf.PI;
            mods[i] = new Vector2(0.1f + Random.value, 0.1f + Random.value);
        }

        modBuffer.SetData(mods);
        startPointBuffer.SetData(values);
        computeShader.SetBuffer(CSKernel, "startPointBuffer", startPointBuffer);
    }
Ejemplo n.º 27
0
    /*****/
    void OnEnable()
    {
        this.hideFlags = HideFlags.None;

        _camera = GetComponent<Camera>();
        _camera.depthTextureMode |= DepthTextureMode.Depth;
        _camera.depthTextureMode |= DepthTextureMode.DepthNormals;

        if (_renderProteinsMaterial == null) _renderProteinsMaterial = new Material(RenderProteinsShader) { hideFlags = HideFlags.HideAndDontSave };
        if (_compositeMaterial == null) _compositeMaterial = new Material(CompositeShader) { hideFlags = HideFlags.HideAndDontSave };
        if (_contourMaterial == null) _contourMaterial = new Material(ContourShader) { hideFlags = HideFlags.HideAndDontSave };

        if (_argBuffer == null)
        {
            _argBuffer = new ComputeBuffer(4, sizeof(int), ComputeBufferType.DrawIndirect);
            _argBuffer.SetData( new [] { 0, 1, 0, 0 });
        }
    }
	void Start () 
	{
		//There are 8 threads run per group so N must be divisible by 8.
		if(N%8 != 0)
			throw new System.ArgumentException("N must be divisible be 8");
		
		//Holds the voxel values, generated from perlin noise.
		m_noiseBuffer = new ComputeBuffer(N * N * N, sizeof(float));
		
		//Holds the normals of the voxels.
		m_normalsBuffer  = new ComputeBuffer(N * N * N, sizeof(float)*3);
		
		//Holds the verts generated by the marching cubes.
		m_meshBuffer = new ComputeBuffer(SIZE, sizeof(float)*7);
		
		//These two buffers are just some settings needed by the marching cubes.
		m_cubeEdgeFlags = new ComputeBuffer(256, sizeof(int));
		m_cubeEdgeFlags.SetData(cubeEdgeFlags);
		m_triangleConnectionTable = new ComputeBuffer(256 * 16, sizeof(int));
		m_triangleConnectionTable.SetData(triangleConnectionTable);
		
		//Make the perlin noise, make sure to load resources to match shader used.
		perlin = new ImprovedPerlinNoise(m_seed);
		perlin.LoadResourcesFor4DNoise();

        //Constract a mesh.
        var vcount = N * N * 3 * 5;
        var vertices = new Vector3[vcount];

        var uv = new Vector2[vcount];
        for (var i = 0; i < vcount; i++)
            uv[i] = new Vector2(i, 0);

        var indices = new int[vcount];
        for (var i = 0; i < vcount; i++)
            indices[i] = i;

        m_mesh = new Mesh();
        m_mesh.vertices = vertices;
        m_mesh.uv = uv;
        m_mesh.SetIndices(indices, MeshTopology.Triangles, 0);
        m_mesh.bounds = new Bounds(Vector3.zero, Vector3.one * 1000);
    }
	// Use this for initialization
	void Start () {
        material = new Material(geomShader);

        points = new data[] 
        {
            new data() { pos = Vector3.left + Vector3.up },
            new data() { pos = Vector3.right + Vector3.up },
            new data() { pos = Vector3.zero },
            new data() { pos = Vector3.left + Vector3.down },
            new data() { pos = Vector3.right + Vector3.down }
        };

        //points = new data[] { new data() { pos = Vector3.zero } };

        if(!UseComputeData) {
            outputBuffer = new ComputeBuffer(points.Length, 12);
            outputBuffer.SetData(points);
        }
	}
Ejemplo n.º 30
0
    void Start()
    {
        var mesh = fab.GetComponent<MeshFilter> ().sharedMesh;
        var expandedVertices = new Vector3[mesh.triangles.Length];
        for (var i = 0; i < expandedVertices.Length; i++)
            expandedVertices [i] = fab.transform.TransformPoint(mesh.vertices [mesh.triangles [i]]);
        _vertexBuf = new ComputeBuffer (expandedVertices.Length, Marshal.SizeOf (expandedVertices [0]));
        _vertexBuf.SetData (expandedVertices);

        _positions = new Vector3[nInstances];
        _positionBuf = new ComputeBuffer (_positions.Length, Marshal.SizeOf (_positions [0]));

        _characters = new Character[nInstances];
        for (var i = 0; i < _characters.Length; i++) {
            _characters[i] = new Character(){
                position = radius * Random.insideUnitSphere,
                velocity = speed * Random.onUnitSphere };
        }
    }
    void InitializeBuffers() {
        strokeMaterial = new Material(strokeShader);
        int numStrokes = 16;
        Vector3 dimensions = new Vector3(10f, 10f, 10f);
        strokeArray = new strokeStruct[numStrokes * numStrokes * numStrokes];
        int index = 0;
        for(int x = 0; x < numStrokes; x++) {
            for (int y = 0; y < numStrokes; y++) {
                for (int z = 0; z < numStrokes; z++) {
                    strokeArray[index].pos = new Vector3(((float)x / (float)numStrokes) * dimensions.x, ((float)y / (float)numStrokes) * dimensions.y, ((float)z / (float)numStrokes) * dimensions.z) + brushStrokesWorldOffset + UnityEngine.Random.insideUnitSphere * 0.25f;
                    index++;
                }
            }
        }
        //{
        //    new strokeStruct() { pos = Vector3.left + Vector3.up },
        //    new strokeStruct() { pos = Vector3.right + Vector3.up },
        //    new strokeStruct() { pos = Vector3.zero },
        //    new strokeStruct() { pos = Vector3.left + Vector3.down },
        //    new strokeStruct() { pos = Vector3.right + Vector3.down }
        //};

        strokeBuffer = new ComputeBuffer(strokeArray.Length, sizeof(float) * 3);
        strokeBuffer.SetData(strokeArray);

        //Create quad buffer
        quadPointsBuffer = new ComputeBuffer(6, sizeof(float) * 3);

        quadPointsBuffer.SetData(new[] {
            new Vector3(-0.5f, 0.5f),
            new Vector3(0.5f, 0.5f),
            new Vector3(0.5f, -0.5f),
            new Vector3(0.5f, -0.5f),
            new Vector3(-0.5f, -0.5f),
            new Vector3(-0.5f, 0.5f)
        });


        gessoMaterial = new Material(gessoShader);
        canvasMaterial = new Material(canvasShader);
    }
 public static ComputeBuffer GenerateCubeVertices(float s=0.5f)
 {
     const float p = 1.0f;
     const float n = -1.0f;
     const float z = 0.0f;
     Vector3[] positions = new Vector3[24] {
             new Vector3(-s,-s, s), new Vector3( s,-s, s), new Vector3( s, s, s), new Vector3(-s, s, s),
             new Vector3(-s, s,-s), new Vector3( s, s,-s), new Vector3( s, s, s), new Vector3(-s, s, s),
             new Vector3(-s,-s,-s), new Vector3( s,-s,-s), new Vector3( s,-s, s), new Vector3(-s,-s, s),
             new Vector3(-s,-s, s), new Vector3(-s,-s,-s), new Vector3(-s, s,-s), new Vector3(-s, s, s),
             new Vector3( s,-s, s), new Vector3( s,-s,-s), new Vector3( s, s,-s), new Vector3( s, s, s),
             new Vector3(-s,-s,-s), new Vector3( s,-s,-s), new Vector3( s, s,-s), new Vector3(-s, s,-s),
         };
     Vector3[] normals = new Vector3[24] {
             new Vector3(z, z, p), new Vector3(z, z, p), new Vector3(z, z, p), new Vector3(z, z, p),
             new Vector3(z, p, z), new Vector3(z, p, z), new Vector3(z, p, z), new Vector3(z, p, z),
             new Vector3(z, n, z), new Vector3(z, n, z), new Vector3(z, n, z), new Vector3(z, n, z),
             new Vector3(n, z, z), new Vector3(n, z, z), new Vector3(n, z, z), new Vector3(n, z, z),
             new Vector3(p, z, z), new Vector3(p, z, z), new Vector3(p, z, z), new Vector3(p, z, z),
             new Vector3(z, z, n), new Vector3(z, z, n), new Vector3(z, z, n), new Vector3(z, z, n),
         };
     int[] indices = new int[36] {
             0,1,3, 3,1,2,
             5,4,6, 6,4,7,
             8,9,11, 11,9,10,
             13,12,14, 14,12,15,
             16,17,19, 19,17,18,
             21,20,22, 22,20,23,
         };
     Vertex[] vertices = new Vertex[36];
     for (int i = 0; i < vertices.Length; ++i)
     {
         vertices[i].position = positions[indices[i]];
         vertices[i].normal = normals[indices[i]];
     }
     ComputeBuffer r = new ComputeBuffer(36, 24);
     r.SetData(vertices);
     return r;
 }
Ejemplo n.º 33
0
        void Update()
        {
            var n = Mathf.FloorToInt((Time.timeSinceLevelLoad - _tPrev) / _dt);
            if (n == 0)
                return;
            _tPrev += n * _dt;

            if (Input.GetMouseButton(0)) {
                var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                RaycastHit hit;
                if (collider.Raycast(ray, out hit, float.MaxValue)) {
                    if (_ripples0.Length >= maxRipples) {
                        if (_ripples1.Length < maxRipples)
                            System.Array.Resize(ref _ripples1, maxRipples);
                        System.Array.Copy(_ripples0, 1, _ripples1, 0, maxRipples-1);
                    } else {
                        System.Array.Resize(ref _ripples1, _ripples0.Length + 1);
                        System.Array.Copy(_ripples0, _ripples1, _ripples0.Length);
                    }
                    _ripples1[_ripples1.Length - 1] = new Ripple(hit.textureCoord, Time.timeSinceLevelLoad);
                    var tmpRipples = _ripples0; _ripples0 = _ripples1; _ripples1 = tmpRipples;

                    if (_ripplesBuffer != null)
                        _ripplesBuffer.Release();
                    _ripplesBuffer = new ComputeBuffer(_ripples0.Length, Marshal.SizeOf(typeof(Ripple)));
                    _ripplesBuffer.SetData(_ripples0);
                    rippleSurfaceMat.SetBuffer(SHADER_PROP_RIPPLES, _ripplesBuffer);
                }
            }

            for (var i = 0; i < n; i++) {
                _rtex1.DiscardContents();
                Graphics.Blit(_rtex0, _rtex1, rippleSurfaceMat);
                var tmpRtex = _rtex0; _rtex0 = _rtex1; _rtex1 = tmpRtex;
            }
            foreach (var mat in outputMats)
                mat.mainTexture = _rtex0;
        }
Ejemplo n.º 34
0
    // Use this for initialization
    void Start()
    {
        buffer = new ComputeBuffer(count, sizeof(float) * 6, ComputeBufferType.Default);

        Vert[] points = new Vert[count];

        Random.seed = 0;
        for (int i = 0; i < count; i++)
        {
            points[i] = new Vert();

            points[i].position = new Vector3();
            points[i].position.x = Random.Range(-size, size);
            points[i].position.y = Random.Range(-size, size);
            points[i].position.z = 0;

            points[i].color = new Vector3();
            points[i].color.x = Random.value > 0.5f ? 0.0f : 1.0f;
            points[i].color.y = Random.value > 0.5f ? 0.0f : 1.0f;
            points[i].color.z = Random.value > 0.5f ? 0.0f : 1.0f;
        }

        buffer.SetData(points);

        index = cs.FindKernel("CSMain");

           /* tex = new RenderTexture(64, 64, 24);
        tex.enableRandomWrite = true;
        tex.Create();*/

        cs.SetBuffer(index, "data", buffer);
        cs.SetInt("count", count);
         //   cs.SetTexture(index, "Result", tex);
        cs.Dispatch(index, 1, 1,1);

           /* if (cam != null)
            cam.targetTexture = tex;*/
    }
Ejemplo n.º 35
0
    /// <summary>
    /// Uses the GPU to process an array of 4D coordinates for noise and return an array with the noise at the specified coordinates.
    /// </summary>
    /// <returns>Float array</returns>
    /// <param name="positions"> Array of coordinates to process. </param>
    /// <param name="noiseScale"> Value to scale the noise coordinates by. </param>
    /// <param name="normalize"> Whether or not to remap the noise from (-1, 1) to (0, 1). </param>
    public static float[] NoiseArrayGPU(UnityEngine.Vector4[] positions, float noiseScale = 0.01f, bool normalize = true)
    {
        UnityEngine.ComputeShader shader = UnityEngine.Resources.Load(shaderPath) as UnityEngine.ComputeShader;
        if (shader == null)
        {
            UnityEngine.Debug.LogError(noShaderMsg);
            return(null);
        }

        int kernel = shader.FindKernel("ComputeNoiseArray");

        SetShaderVars(shader, UnityEngine.Vector2.zero, normalize, noiseScale);
        shader.SetInt("dimension", 4);

        UnityEngine.ComputeBuffer permBuffer = new UnityEngine.ComputeBuffer(perm.Length, 4);
        permBuffer.SetData(perm);
        shader.SetBuffer(kernel, "perm", permBuffer);

        UnityEngine.ComputeBuffer posBuffer = new UnityEngine.ComputeBuffer(positions.Length, 16);
        posBuffer.SetData(positions);
        shader.SetBuffer(kernel, "float4Array", posBuffer);

        UnityEngine.ComputeBuffer outputBuffer = new UnityEngine.ComputeBuffer(positions.Length, 4);
        shader.SetBuffer(kernel, "outputArray", outputBuffer);

        shader.Dispatch(kernel, positions.Length / 14, 1, 1);

        float[] outputData = new float[positions.Length];
        outputBuffer.GetData(outputData);

        permBuffer.Release();
        posBuffer.Release();
        outputBuffer.Release();

        return(outputData);
    }
Ejemplo n.º 36
0
 static public int SetData(IntPtr l)
 {
     try {
         int argc = LuaDLL.lua_gettop(l);
         if (argc == 2)
         {
             UnityEngine.ComputeBuffer self = (UnityEngine.ComputeBuffer)checkSelf(l);
             System.Array a1;
             checkType(l, 2, out a1);
             self.SetData(a1);
             pushValue(l, true);
             return(1);
         }
         else if (argc == 5)
         {
             UnityEngine.ComputeBuffer self = (UnityEngine.ComputeBuffer)checkSelf(l);
             System.Array a1;
             checkType(l, 2, out a1);
             System.Int32 a2;
             checkType(l, 3, out a2);
             System.Int32 a3;
             checkType(l, 4, out a3);
             System.Int32 a4;
             checkType(l, 5, out a4);
             self.SetData(a1, a2, a3, a4);
             pushValue(l, true);
             return(1);
         }
         pushValue(l, false);
         LuaDLL.lua_pushstring(l, "No matched override function to call");
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Ejemplo n.º 37
0
    void Start()
    {
        buffer = new ComputeBuffer (count, sizeof(float) * 6, ComputeBufferType.Default);

        Vert[] points = new Vert[count];

        Random.seed = 0;
        for (int i = 0; i < count; i++)
        {
            points[i] = new Vert();

            points[i].position = new Vector3();
            points[i].position.x = Random.Range (0, size);
            points[i].position.y = Random.Range (0, size);
            points[i].position.z = Random.Range (0, size);;

            points[i].color = new Vector3();
            points[i].color.x = points[i].position.x/size;
            points[i].color.y = points[i].position.y/size;
            points[i].color.z = points[i].position.z/size;
        }

        buffer.SetData (points);
    }
Ejemplo n.º 38
0
    void DoInit()
    {
        if(_verticesBuffer != null)
        {
            _verticesBuffer.Release();
            _verticesBuffer = null;
        }

        _verticesBuffer = new ComputeBuffer(_mesh.vertices.Length, System.Runtime.InteropServices.Marshal.SizeOf(typeof(MeshParticleEngine.MeshData)) );
        _particlesBuffer = new ComputeBuffer(_instancesCount*100, System.Runtime.InteropServices.Marshal.SizeOf(typeof(MeshParticleEngine.MeshData)), ComputeBufferType.Append );
        _countArgsBuffer = new ComputeBuffer(4, sizeof(int), ComputeBufferType.DrawIndirect);
        _particlesPhysicsBuffer = new ComputeBuffer(_instancesCount*100, System.Runtime.InteropServices.Marshal.SizeOf(typeof(MeshParticleEngine.MeshPhysicsData)), ComputeBufferType.Append );

        _VP = new ComputeBuffer(1, System.Runtime.InteropServices.Marshal.SizeOf(typeof(Matrix4x4)) );
        _I_VP = new ComputeBuffer(1, System.Runtime.InteropServices.Marshal.SizeOf(typeof(Matrix4x4)) );

        _shaderCompute.SetBuffer(_initKernelId, "_VerticesBuffer", _verticesBuffer);
        _shaderCompute.SetBuffer(_initKernelId, "_ParticlesBuffer", _particlesBuffer);
        _shaderCompute.SetBuffer(_initKernelId, "_ParticlesPhysicsBuffer", _particlesPhysicsBuffer);

        _shaderCompute.SetBuffer(_initKernelId, "_VP", _VP);
        _shaderCompute.SetBuffer(_initKernelId, "_I_VP", _I_VP);

        Matrix4x4 VP = Camera.main.projectionMatrix * Camera.main.worldToCameraMatrix;
        Matrix4x4 I_VP = Matrix4x4.Inverse(VP);
        _VP.SetData(new Matrix4x4 [] { VP });
        _I_VP.SetData(new Matrix4x4 [] { I_VP });

        _shaderCompute.SetVector("_ParticlesSize", new Vector4(_instancesCount, 0f, 0f, 0f));
        Debug.Log("ParticlesSizes.x " + _instancesCount);
        _material.SetBuffer("_ParticlesBuffer", _particlesBuffer);

        DoInitMeshBuffer();

        _shaderCompute.Dispatch(_initKernelId, _numThreadGroupsX, 1, 1);
    }
		public void generateDiffuseNoise( int width, int height,
											PlanetNoise surfaceParams,
											PlanetNoise landParams,
											Color[] landColour,
											PlanetNoise[] landColourNoise,
											float cityReach,
											float cityHeight,
											Color waterColour0,
											Color waterColour1,
											float waterLevel,
											float waterSpecular,
											float waterFalloff,
											Color iceColour,
											float iceReach,
											float iceHeight,
											float shadowRange,
											float shadowStrength,
											float normalScale )
		{
			_width				= width;
			_height				= height;
			_surfaceParams		= surfaceParams;
			_landParams			= landParams;
			_landColour			= landColour;
			_landColourNoise	= landColourNoise;
			_cityReach			= cityReach * 0.5f;
			_cityHeight			= cityHeight;
			_waterColour0		= waterColour0;
			_waterColour1		= waterColour1;
			_waterLevel			= waterLevel;
			_waterSpecular		= waterSpecular;
			_waterFalloff		= waterFalloff;
			_iceColour			= iceColour;
			_iceReach			= iceReach * 0.5f;
			_iceHeight			= iceHeight;
			_shadowRange		= shadowRange;
			_shadowStrength		= shadowStrength;
			_normalScale		= normalScale;
			
			//9 bytes per pixel - all colour data followed by all normal data followed by all illumination data
			//colour - r, g, b, a
			//normal - x, y, z, height
			//illumination - i
			int bytesPerPixel	= 9;
			int pixelCount		= width * height;

			if( diffuseData == null || diffuseData.Length != pixelCount * bytesPerPixel )
				diffuseData = new byte[ pixelCount * bytesPerPixel ];
			
			if( useComputerShader )
			{
				noiseComputeShader.SetFloat( "width",	width );
				noiseComputeShader.SetFloat( "height",	height );

				//diffuse perlin noise data
				int gradBytes		= sizeof( float );
				int gradStride		= PlanetNoisePerlin.gradStride;
				float[] gradArray	= new float[ gradStride * 4 ];

				System.Buffer.BlockCopy( perlinNoiseSurface.getGradArray(),			0, gradArray, 0,							gradStride * gradBytes );
				System.Buffer.BlockCopy( perlinNoiseLand.getGradArray(),			0, gradArray, gradStride * gradBytes,		gradStride * gradBytes );
				System.Buffer.BlockCopy( perlinNoiseLandColour01.getGradArray(),	0, gradArray, gradStride * gradBytes * 2,	gradStride * gradBytes );
				System.Buffer.BlockCopy( perlinNoiseLandColour23.getGradArray(),	0, gradArray, gradStride * gradBytes * 3,	gradStride * gradBytes );

				perlinGradBuffer = new ComputeBuffer( gradArray.Length, gradBytes );
				perlinGradBuffer.SetData( gradArray );
				noiseComputeShader.SetBuffer( _diffuseKernel, "perlinGrad", perlinGradBuffer );

				int permBytes		= sizeof( int );
				int permStride		= PlanetNoisePerlin.permStride;
				uint[] permArray	= new uint[ permStride * 4 ];

				System.Buffer.BlockCopy( perlinNoiseSurface.getPermArray(),			0, permArray, 0,							permStride * permBytes );
				System.Buffer.BlockCopy( perlinNoiseLand.getPermArray(),			0, permArray, permStride * permBytes,		permStride * permBytes );
				System.Buffer.BlockCopy( perlinNoiseLandColour01.getPermArray(),	0, permArray, permStride * permBytes * 2,	permStride * permBytes );
				System.Buffer.BlockCopy( perlinNoiseLandColour23.getPermArray(),	0, permArray, permStride * permBytes * 3,	permStride * permBytes );

				perlinPermBuffer = new ComputeBuffer( permArray.Length, permBytes );
				perlinPermBuffer.SetData( permArray );
				noiseComputeShader.SetBuffer( _diffuseKernel, "perlinPerm", perlinPermBuffer );

				//surface noise data
				noiseComputeShader.SetFloat( "surfaceScale",			surfaceParams.scale );
				noiseComputeShader.SetInt( "surfaceOctaves",			surfaceParams.octaves );
				noiseComputeShader.SetFloat( "surfaceFalloff",			surfaceParams.falloff );
				noiseComputeShader.SetFloat( "surfaceIntensity",		surfaceParams.intensity );
				noiseComputeShader.SetFloat( "surfaceRidginess",		surfaceParams.ridginess );
				noiseComputeShader.SetFloat( "surfaceSmearScale",		surfaceParams.smearScale );
				noiseComputeShader.SetInt( "surfaceSmearOctaves",		surfaceParams.smearOctaves );
				noiseComputeShader.SetFloat( "surfaceSmearFalloff",		surfaceParams.smearFalloff );
				noiseComputeShader.SetFloat( "surfaceSmearIntensity",	surfaceParams.smearIntensity );

				//land noise data
				noiseComputeShader.SetFloat( "landScale",			landParams.scale );
				noiseComputeShader.SetInt( "landOctaves",			landParams.octaves );
				noiseComputeShader.SetFloat( "landFalloff",			landParams.falloff );
				noiseComputeShader.SetFloat( "landIntensity",		landParams.intensity );
				noiseComputeShader.SetFloat( "landRidginess",		landParams.ridginess );
				noiseComputeShader.SetFloat( "landSmearScale",		landParams.smearScale );
				noiseComputeShader.SetInt( "landSmearOctaves",		landParams.smearOctaves );
				noiseComputeShader.SetFloat( "landSmearFalloff",	landParams.smearFalloff );
				noiseComputeShader.SetFloat( "landSmearIntensity",	landParams.smearIntensity );

				//land colours
				for( int i = 0; i < landColour.Length; ++i )
					noiseComputeShader.SetFloats( "landColour" + i, new float[] { landColour[ i ].r, landColour[ i ].g, landColour[ i ].b, landColour[ i ].a } );

				for( int i = 0; i < landColourNoise.Length; ++i )
				{
					string id = ( i * 2 ).ToString() + ( i * 2 + 1 ).ToString();

					//land colour noise data
					noiseComputeShader.SetFloat( "landColour" + id + "Scale",			landColourNoise[ i ].scale );
					noiseComputeShader.SetInt( "landColour" + id + "Octaves",			landColourNoise[ i ].octaves );
					noiseComputeShader.SetFloat( "landColour" + id + "Falloff",			landColourNoise[ i ].falloff );
					noiseComputeShader.SetFloat( "landColour" + id + "Intensity",		landColourNoise[ i ].intensity );
					noiseComputeShader.SetFloat( "landColour" + id + "Ridginess",		landColourNoise[ i ].ridginess );
					noiseComputeShader.SetFloat( "landColour" + id + "SmearScale",		landColourNoise[ i ].smearScale );
					noiseComputeShader.SetInt( "landColour" + id + "SmearOctaves",		landColourNoise[ i ].smearOctaves );
					noiseComputeShader.SetFloat( "landColour" + id + "SmearFalloff",	landColourNoise[ i ].smearFalloff );
					noiseComputeShader.SetFloat( "landColour" + id + "SmearIntensity",	landColourNoise[ i ].smearIntensity );
				}

				//diffuse params
				noiseComputeShader.SetFloat( "cityReach",		_cityReach );
				noiseComputeShader.SetFloat( "cityHeight",		cityHeight );
				noiseComputeShader.SetFloats( "waterColour0",	new float[] { waterColour0.r, waterColour0.g, waterColour0.b, waterColour0.a } );
				noiseComputeShader.SetFloats( "waterColour1",	new float[] { waterColour1.r, waterColour1.g, waterColour1.b, waterColour1.a } );
				noiseComputeShader.SetFloat( "waterLevel",		waterLevel );
				noiseComputeShader.SetFloat( "waterSpecular",	waterSpecular );
				noiseComputeShader.SetFloat( "waterFalloff",	waterFalloff );
				noiseComputeShader.SetFloats( "iceColour",		new float[] { iceColour.r, iceColour.g, iceColour.b, iceColour.a } );
				noiseComputeShader.SetFloat( "iceReach",		_iceReach );
				noiseComputeShader.SetFloat( "iceHeight",		iceHeight );
				noiseComputeShader.SetFloat( "shadowRange",		shadowRange );
				noiseComputeShader.SetFloat( "shadowStrength",	shadowStrength );
				noiseComputeShader.SetFloat( "normalScale",		normalScale );
				
				int pixelsPerDispatch = pixelCount;

				if( pixelsPerDispatch > maxThreadsPerDispatch )
				{
					pixelsPerDispatch = maxThreadsPerDispatch;
					pixelsPerDispatch -= maxThreadsPerDispatch % diffuseThreadsPerGroup;
				}

				noiseComputeShader.SetInt( "threadOffset", 0 );

				_jobCount			= Mathf.CeilToInt( pixelCount / ( float ) pixelsPerDispatch );
				_jobStartedCount	= 1;	//first dispatch is below
				_jobCompletedCount	= 0;

				computeResultBuffer = new ComputeBuffer( pixelsPerDispatch * diffusePixelsPerThread, sizeof( int ) );
				noiseComputeShader.SetBuffer( _diffuseKernel, "resultData", computeResultBuffer );

				noiseComputeShader.Dispatch( _diffuseKernel, pixelsPerDispatch / diffuseThreadsPerGroup, 1, 1 );

				computeResultData = new int[ pixelsPerDispatch * diffusePixelsPerThread ];
			}
			else
			{
				int workerCount = SystemInfo.processorCount - 1;				//-1 to account for main thread

				if( workerCount > 0 )
					_worker = new Thread[ workerCount ];

				//a bit inefficient to have more jobs than workers but with multiple threads
				//per core nowadays it makes sense, also gives an easy way to measure progress
				_jobCount			= Mathf.Max( 32, ( workerCount + 1 ) * ( workerCount + 1 ) );
				_jobCount			= Mathf.Min( width, _jobCount );
				_jobStartedCount	= 0;
				_jobCompletedCount	= 0;
				_jobList			= new int[ _jobCount ];

				for( int i = 0; i < _jobCount; ++i )
					_jobList[ i ] = i;

				for( int i = 0; i < workerCount; ++i )
				{
					_worker[ i ] = new Thread( () => { while( doDiffuseWork() ); } );
					_worker[ i ].Start();
				}
			}
		}
		public void generateCloudNoise( int width, int height,
										PlanetNoise cloudParams,
										int cloudWorleyNoiseOctaves,
										float cloudWorleyNoiseFrequency,
										float cloudWorleyNoiseAmplitude,
										float cloudShadowRange,
										float cloudShadowStrength,
										Color cloudColour0,
										Color cloudColour1,
										float cloudSpin,
										float cloudNormalScale,
										bool preMultiplyAlpha )
		{
			_width						= width;
			_height						= height;
			_cloudWorleyNoiseOctaves	= cloudWorleyNoiseOctaves;
			_cloudWorleyNoiseFrequency	= cloudWorleyNoiseFrequency;
			_cloudWorleyNoiseAmplitude	= cloudWorleyNoiseAmplitude;
			_cloudShadowRange			= cloudShadowRange;
			_cloudShadowStrength		= cloudShadowStrength;
			_cloudParams				= cloudParams;
			_cloudColour0				= cloudColour0;
			_cloudColour1				= cloudColour1;
			_cloudSpin					= cloudSpin;
			_cloudNormalScale			= cloudNormalScale;
			_preMultiplyAlpha			= preMultiplyAlpha;

			//8 bytes per pixel - all colour data followed by all normal data
			//colour - r, g, b, a
			//normal - x, y, z, height
			int bytesPerPixel	= 8;
			int pixelCount		= width * height;

			if( cloudData == null || cloudData.Length != pixelCount * bytesPerPixel )
				cloudData = new byte[ pixelCount * bytesPerPixel ];

			if( useComputerShader )
			{
				noiseComputeShader.SetFloat( "width",	width );
				noiseComputeShader.SetFloat( "height",	height );

				//perlin noise data
				float[] gradArray	= perlinNoiseCloud.getGradArray();
				perlinGradBuffer	= new ComputeBuffer( gradArray.Length, sizeof( float ) );
				perlinGradBuffer.SetData( gradArray );
				noiseComputeShader.SetBuffer( _cloudKernel, "perlinGrad", perlinGradBuffer );

				uint[] permArray	= perlinNoiseCloud.getPermArray();
				perlinPermBuffer	= new ComputeBuffer( permArray.Length, sizeof( int ) );
				perlinPermBuffer.SetData( permArray );
				noiseComputeShader.SetBuffer( _cloudKernel, "perlinPerm", perlinPermBuffer );

				noiseComputeShader.SetInt( "cloudSeed", worleyNoiseCloud.seed );

				//cloud noise data
				noiseComputeShader.SetFloat( "cloudScale",			cloudParams.scale );
				noiseComputeShader.SetInt( "cloudOctaves",			cloudParams.octaves );
				noiseComputeShader.SetFloat( "cloudFalloff",		cloudParams.falloff );
				noiseComputeShader.SetFloat( "cloudIntensity",		cloudParams.intensity );
				noiseComputeShader.SetFloat( "cloudRidginess",		cloudParams.ridginess );
				noiseComputeShader.SetFloat( "cloudSmearScale",		cloudParams.smearScale );
				noiseComputeShader.SetInt( "cloudSmearOctaves",		cloudParams.smearOctaves );
				noiseComputeShader.SetFloat( "cloudSmearFalloff",	cloudParams.smearFalloff );
				noiseComputeShader.SetFloat( "cloudSmearIntensity",	cloudParams.smearIntensity );

				//cloud worley noise data
				noiseComputeShader.SetInt( "cloudWorleyNoiseOctaves",		_cloudWorleyNoiseOctaves );
				noiseComputeShader.SetFloat( "cloudWorleyNoiseFrequency",	_cloudWorleyNoiseFrequency );
				noiseComputeShader.SetFloat( "cloudWorleyNoiseAmplitude",	_cloudWorleyNoiseAmplitude );

				noiseComputeShader.SetFloat( "cloudShadowRange",	_cloudShadowRange );
				noiseComputeShader.SetFloat( "cloudShadowStrength",	_cloudShadowStrength );

				//cloud params
				noiseComputeShader.SetFloats( "cloudColour0",		new float[] { cloudColour0.r, cloudColour0.g, cloudColour0.b, cloudColour0.a } );
				noiseComputeShader.SetFloats( "cloudColour1",		new float[] { cloudColour1.r, cloudColour1.g, cloudColour1.b, cloudColour1.a } );
				noiseComputeShader.SetFloat( "cloudSpin",			cloudSpin );
				noiseComputeShader.SetFloat( "cloudNormalScale",	cloudNormalScale );
				noiseComputeShader.SetInt( "preMultiplyAlpha",		preMultiplyAlpha ? 1 : 0 );
				
				int pixelsPerDispatch = pixelCount;

				if( pixelsPerDispatch > maxThreadsPerDispatch )
				{
					pixelsPerDispatch = maxThreadsPerDispatch;
					pixelsPerDispatch -= maxThreadsPerDispatch % cloudThreadsPerGroup;
				}

				noiseComputeShader.SetInt( "threadOffset", 0 );

				_jobCount			= Mathf.CeilToInt( pixelCount / ( float ) pixelsPerDispatch );
				_jobStartedCount	= 1;	//first dispatch is below
				_jobCompletedCount	= 0;

				computeResultBuffer = new ComputeBuffer( pixelsPerDispatch * cloudPixelsPerThread, sizeof( int ) );
				noiseComputeShader.SetBuffer( _cloudKernel, "resultData", computeResultBuffer );

				noiseComputeShader.Dispatch( _cloudKernel, pixelsPerDispatch / cloudThreadsPerGroup, 1, 1 );

				computeResultData = new int[ pixelsPerDispatch * cloudPixelsPerThread ];
			}
			else
			{
				int workerCount = SystemInfo.processorCount - 1;				//-1 to account for main thread

				if( workerCount > 0 )
					_worker = new Thread[ workerCount ];

				//a bit inefficient to have more jobs than workers but with multiple threads
				//per core nowadays it makes sense, also gives an easy way to measure progress
				_jobCount			= Mathf.Max( 32, ( workerCount + 1 ) * ( workerCount + 1 ) );
				_jobCount			= Mathf.Min( width, _jobCount );
				_jobStartedCount	= 0;
				_jobCompletedCount	= 0;
				_jobList			= new int[ _jobCount ];

				for( int i = 0; i < _jobCount; ++i )
					_jobList[ i ] = i;

				for( int i = 0; i < workerCount; ++i )
				{
					_worker[ i ] = new Thread( () => { while( doCloudWork() ); } );
					_worker[ i ].Start();
				}
			}
		}