// Generate Vector4[] of shading data. This is stored in mesh uvs and used to help shade the body
    public Vector4[] GenerateShadingData(ComputeBuffer vertexBuffer)
    {
        int numVertices = vertexBuffer.count;

        Vector4[] shadingData = new Vector4[numVertices];

        if (shadingDataCompute)
        {
            // Set data
            SetShadingDataComputeProperties();

            shadingDataCompute.SetInt("numVertices", numVertices);
            shadingDataCompute.SetBuffer(0, "vertices", vertexBuffer);
            ComputeHelper.CreateAndSetBuffer <Vector4> (ref shadingBuffer, numVertices, shadingDataCompute, "shadingData");

            // Run
            ComputeHelper.Run(shadingDataCompute, numVertices);

            // Get data
            shadingBuffer.GetData(shadingData);
        }

        cachedShadingData = shadingData;
        return(shadingData);
    }
示例#2
0
    // Set values using custom numCraters and sizeMinMax
    public void SetComputeValues(ComputeShader computeShader, int masterSeed, int numCraters, Vector2 craterSizeMinMax, float sizeDistribution)
    {
        if (!enabled)
        {
            numCraters       = 1;
            craterSizeMinMax = Vector2.zero;
        }

        Random.InitState(craterSeed + masterSeed);
        Crater[] craters = new Crater[numCraters];
        PRNG     prng    = new PRNG(masterSeed);

        // Create craters
        for (int i = 0; i < numCraters; i++)
        {
            float t = prng.ValueBiasLower(sizeDistribution);

            float size        = Mathf.Lerp(craterSizeMinMax.x, craterSizeMinMax.y, t);
            float floorHeight = Mathf.Lerp(-1.2f, -0.2f, t + prng.ValueBiasLower(0.3f));
            float smooth      = Mathf.Lerp(smoothMinMax.x, smoothMinMax.y, 1 - t);
            craters[i] = new Crater()
            {
                centre = Random.onUnitSphere, size = size, floorHeight = floorHeight, smoothness = smooth
            };
        }
        cachedCraters = craters;

        // Set shape data
        ComputeHelper.CreateAndSetBuffer <Crater> (ref craterBuffer, craters, computeShader, "craters");
        computeShader.SetInt("numCraters", numCraters);

        computeShader.SetFloat(nameof(rimSteepness), rimSteepness);
        computeShader.SetFloat(nameof(rimWidth), rimWidth);
        //computeShader.SetFloat (nameof (smoothFactor), smoothFactor);
    }
示例#3
0
        public virtual void Upload(float[] data, TensorShape shape, int managedBufferStartIndex = 0)
        {
            var numItemToCopy          = shape.length;
            var numItemAvailableInData = data.Length - managedBufferStartIndex;

            Assert.IsTrue(managedBufferStartIndex >= 0);
            Assert.IsTrue(numItemToCopy <= numItemAvailableInData);

            int w = Mathf.Min(shape.length, MaxTextureSize);
            int h = Mathf.Max(1, ComputeHelper.IDivC(shape.length, w));

            Texture2D texture     = new Texture2D(w, h, TextureFormat.RFloat, false);
            var       textureData = texture.GetRawTextureData <float>();

            unsafe
            {
                UnsafeUtility.MemSet(textureData.GetUnsafePtr(), 0, sizeof(float) * (textureData.Length));
            }
            NativeArray <float> .Copy(data, managedBufferStartIndex, textureData, 0, shape.length);

            texture.Apply();

            Material material = new Material(PixelShaderSingleton.Instance.FindShader("Barracuda/BufferToTensor"));

            material.SetTexture("Xtex2D", texture);

            material.SetInt("_InputWidth", w);
            material.SetInt("_InputHeight", h);

            material.SetVector("OdeclShape", new Vector4(shape.batch, shape.height, shape.width, shape.channels));

            Graphics.Blit(null, m_BufferAsTexture, material);

            m_AsyncDownloadSchedulingFrame = -1;
        }
示例#4
0
    // Pick craters to be shaded with radial streaks emanating from them
    void SetCraters(MoonShape moonShape)
    {
        PRNG random = new PRNG(ejectaRaySeed);
        //int desiredNumCraterRays = random.Range (5, 15);
        //desiredNumCraterRays = 2;

        // Sort craters from largest to smallest
        var sortedCraters = new List <CraterSettings.Crater> (moonShape.craterSettings.cachedCraters);

        sortedCraters.Sort((a, b) => b.size.CompareTo(a.size));
        int poolSize = Mathf.Clamp((int)((sortedCraters.Count - 1) * candidatePoolSize), 1, sortedCraters.Count);

        sortedCraters = sortedCraters.GetRange(0, poolSize);
        random.Shuffle(sortedCraters);

        // Choose craters
        var chosenCraters = new List <CraterSettings.Crater> ();

        for (int i = 0; i < sortedCraters.Count; i++)
        {
            var currentCrater = sortedCraters[i];

            // Reject those which are too close to already chosen craters as the textures may not overlap
            bool overlapsOtherEjecta = false;
            for (int j = 0; j < chosenCraters.Count; j++)
            {
                float dst             = (currentCrater.centre - chosenCraters[j].centre).magnitude;
                float ejectaRadiusSum = (currentCrater.size + chosenCraters[j].size) * ejectaRaysScale / 2;

                if (dst < ejectaRadiusSum)
                {
                    overlapsOtherEjecta = true;
                    break;
                }
            }

            //Debug.DrawRay (currentCrater.centre, currentCrater.centre * 0.2f, (overlapsOtherEjecta) ? Color.red : Color.green);
            if (!overlapsOtherEjecta)
            {
                chosenCraters.Add(currentCrater);
            }
            if (chosenCraters.Count >= desiredNumCraterRays)
            {
                break;
            }
        }

        // Set
        var ejectaCraters = new Vector4[chosenCraters.Count];

        for (int i = 0; i < chosenCraters.Count; i++)
        {
            var crater = chosenCraters[i];
            ejectaCraters[i] = new Vector4(crater.centre.x, crater.centre.y, crater.centre.z, crater.size * ejectaRaysScale);
            //CustomDebug.DrawSphere (crater.centre, crater.size * ejectaRaysScale / 2, Color.yellow);
        }

        ComputeHelper.CreateAndSetBuffer <Vector4> (ref craterBuffer, ejectaCraters, shadingDataCompute, "ejectaCraters");
        shadingDataCompute.SetInt("numEjectaCraters", chosenCraters.Count);
    }
示例#5
0
  protected virtual void Start()
  {
    ComputeHelper.CreateRenderTexture(ref renderTexture, settings.width, settings.height, FilterMode.Point, format);

    Agent[] agents = new Agent[settings.numAgents];
    for (int i = 0; i < agents.Length; i++)
    {
      Vector2 centre = new Vector2(settings.width / 2, settings.height / 2);
      Vector2 startPos = centre;
      float randomAngle = Random.value * Mathf.PI * 2;
      float angle = randomAngle;
      // float angle = 0f * Mathf.PI;
      float speed = (Random.value * 10.0f) + 10.0f;
      Vector4 color;
      if (Random.Range(0, 5) == 1)
        color = new Vector4(0, 0, 0, 0);
      else
        color = new Vector4((float)Random.Range(0, 5) / 16f, 0, (float)Random.Range(0, 2), 1.0f);
      agents[i] = new Agent() { position = startPos, angle = angle, speed = speed, color = color };
    }
    ComputeHelper.CreateAndSetBuffer<Agent>(ref agentBuffer, agents, compute, "agents", simulationKernel);
    compute.SetBuffer(0, "agents", agentBuffer);

    compute.SetInt("width", settings.width);
    compute.SetInt("height", settings.height);

    transform.GetComponentInChildren<MeshRenderer>().material.mainTexture = renderTexture;
  }
示例#6
0
    void RunSimulation()
    {
        var speciesSettings = settings.speciesSettings;

        ComputeHelper.CreateStructuredBuffer(ref settingsBuffer, speciesSettings);
        compute.SetBuffer(0, "speciesSettings", settingsBuffer);


        // Assign textures
        compute.SetTexture(updateKernel, "TrailMap", trailMap);
        compute.SetTexture(diffuseMapKernel, "TrailMap", trailMap);
        compute.SetTexture(diffuseMapKernel, "DiffusedTrailMap", diffusedTrailMap);

        // Assign settings
        compute.SetFloat("deltaTime", Time.fixedDeltaTime);
        compute.SetFloat("time", Time.fixedTime);

        compute.SetFloat("trailWeight", settings.trailWeight);
        compute.SetFloat("decayRate", settings.decayRate);
        compute.SetFloat("diffuseRate", settings.diffuseRate);


        ComputeHelper.Dispatch(compute, settings.numAgents, 1, 1, kernelIndex: updateKernel);
        ComputeHelper.Dispatch(compute, settings.width, settings.height, 1, kernelIndex: diffuseMapKernel);

        ComputeHelper.CopyRenderTexture(diffusedTrailMap, trailMap);
    }
        private bool OptimizeBlock(BaseBlock bblock, HashSet <String> active_vars)
        {
            bool ret = false;


            HashSet <String> living = new HashSet <string>();

            for (int i = bblock.Code.Count - 1; i >= 0; --i)
            {
                var line = bblock.Code[i];
                if (ThreeAddrOpType.IsDefinition(line.OpType) & line.OpType != ThreeAddrOpType.Read)
                {
                    if (!living.Contains(line.Accum) && !active_vars.Contains(line.Accum))
                    {
                        line.OpType = ThreeAddrOpType.Nop;
                        ret         = true;
                        continue;
                    }
                }
                if (line.RightOp != null && !ComputeHelper.IsConst(line.RightOp))
                {
                    living.Add(line.RightOp);
                }
                if (line.LeftOp != null && !ComputeHelper.IsConst(line.LeftOp))
                {
                    living.Add(line.LeftOp);
                }
            }
            return(ret);
        }
        private bool Recognize(ThreeAddrLine line) // метод получает строку трехадресного кода, конвертирует операнты и записывает результат.
        {
            int  a = 0, b = 0;
            bool isaconst = int.TryParse(line.LeftOp, out a); // Получаем левый оперант.
            bool isbconst = int.TryParse(line.RightOp, out b);

            if (line.LeftOp == null)
            {
                isaconst = true;
                a        = 0;
            }

            if (!isaconst || !isbconst)
            {
                return(false);
            }
            // Получаем правый оперант.
            var res = ComputeHelper.Calculate(a, b, line.OpType).ToString(); // Записываем вправо вычисленное значение.

            if (res != null)
            {
                line.LeftOp  = null;                   // Просто зануляем.
                line.OpType  = ThreeAddrOpType.Assign; // записываем в тип операции assign.
                line.RightOp = res;
                return(true);
            }
            return(false);
        }
    protected override void Run()
    {
        var prng   = new PRNG(seed);
        var offset = new Vector4(prng.Value(), prng.Value(), prng.Value(), prng.Value()) * 10;

        ComputeHelper.CreateStructuredBuffer <int> (ref minMaxBuffer, 2);
        minMaxBuffer.SetData(new int[] { int.MaxValue, 0 });
        compute.SetBuffer(0, "minMax", minMaxBuffer);
        compute.SetBuffer(1, "minMax", minMaxBuffer);

        int threadGroupSize = ComputeHelper.GetThreadGroupSizes(compute, 0).x;
        int numThreadGroups = Mathf.CeilToInt((float)textureSize / threadGroupSize);

        compute.SetVector("offset", offset);
        compute.SetTexture(0, "Result", renderTexture);
        noiseSettings.SetComputeValues(compute, prng, "_simple");
        warpNoiseSettings.SetComputeValues(compute, prng, "_warp");

        compute.SetInt("resolution", (int)textureSize);
        compute.SetFloat("valueFloor", valueFloor);
        compute.Dispatch(0, numThreadGroups, numThreadGroups, 1);

        // Normalize
        if (normalize)
        {
            compute.SetTexture(1, "Result", renderTexture);
            compute.Dispatch(1, numThreadGroups, numThreadGroups, 1);
        }

        ComputeHelper.Release(minMaxBuffer);
    }
示例#10
0
        public string GenerateCode(string prefixName, string suffixName)
        {
            var prefixCode = string.Join(string.Empty, SanitizerHelper.ExtractAlpha(prefixName.ToUpperInvariant()).Take(3));
            var suffixCode = string.Join(string.Empty, SanitizerHelper.ExtractAlpha(suffixName.ToUpperInvariant()).Take(3));
            var code       = string.Format("{0}-{1}-{2}", prefixCode, ComputeHelper.GenerateRandomString(4, ComputeHelper.NaturalNumericChars), suffixCode).Trim('-');

            return(code);
        }
示例#11
0
    // Handles creation of celestial body in the editor
    // This allows for updating the shape/shading settings
    void HandleEditModeGeneration()
    {
        if (InEditMode)
        {
            ComputeHelper.shouldReleaseEditModeBuffers -= ReleaseAllBuffers;
            ComputeHelper.shouldReleaseEditModeBuffers += ReleaseAllBuffers;
        }

        if (CanGenerateMesh())
        {
            // Update shape settings and shading noise
            if (shapeSettingsUpdated)
            {
                shapeSettingsUpdated        = false;
                shadingNoiseSettingsUpdated = false;
                Dummy();

                var terrainMeshTimer = System.Diagnostics.Stopwatch.StartNew();
                heightMinMax = GenerateTerrainMesh(ref previewMesh, PickTerrainRes());

                LogTimer(terrainMeshTimer, "Generate terrain mesh");
                DrawEditModeMesh();
            }
            // If only shading noise has changed, update it separately from shape to save time
            else if (shadingNoiseSettingsUpdated)
            {
                shadingNoiseSettingsUpdated = false;
                ComputeHelper.CreateStructuredBuffer <Vector3> (ref vertexBuffer, previewMesh.vertices);
                body.shading.Initialize(body.shape);
                Vector4[] shadingData = body.shading.GenerateShadingData(vertexBuffer);
                previewMesh.SetUVs(0, shadingData);

                // Sometimes when changing a colour property, invalid data is returned from compute shader
                // Running the shading a second time fixes it.
                // Not sure if this is my bug, or Unity's (TODO: investigate)
                debug_numUpdates++;
                if (debugDoubleUpdate && debug_numUpdates < 2)
                {
                    shadingNoiseSettingsUpdated = true;
                    HandleEditModeGeneration();
                }
                if (debug_numUpdates == 2)
                {
                    debug_numUpdates = 0;
                }
            }
        }

        // Update shading
        if (body && body.shading)
        {
            // Set material properties
            body.shading.Initialize(body.shape);
            body.shading.SetTerrainProperties(body.shading.terrainMaterial, heightMinMax, BodyScale);
        }

        ReleaseAllBuffers();          //
    }
示例#12
0
 void Dummy()
 {
     // Crude fix for a problem I was having where the values in the vertex buffer were *occasionally* all zero at start of game
     // This function runs the compute shader once with single dummy input, after which it seems the problem doesn't occur
     // (Waiting until Time.frameCount > 3 before generating is another gross hack that seems to fix the problem)
     // I don't know why...
     Vector3[] vertices = new Vector3[] { Vector3.zero };
     ComputeHelper.CreateStructuredBuffer <Vector3> (ref vertexBuffer, vertices);
     body.shape.CalculateHeights(vertexBuffer);
 }
示例#13
0
        public void Npv()
        {
            // Arrange
            var helper = new ComputeHelper();

            // Act
            var result = helper.Npv(model, model.LowerBoundDiscountRate);

            // Assert
            Assert.AreEqual(-76182.26, result);
        }
示例#14
0
  // void LateUpdate()
  // {
  //   ComputeHelper.CopyRenderTexture(trailMap, renderTexture);
  // }


  void RunSimulation()
  {
    compute.SetTexture(simulationKernel, "renderTexture", renderTexture);

    // Assign settings
    compute.SetFloat("deltaTime", Time.fixedDeltaTime);
    compute.SetFloat("time", Time.fixedTime);

    // ComputeHelper.Dispatch(compute, settings.width, settings.height, 1, kernelIndex: simulationKernel);
    ComputeHelper.Dispatch(compute, settings.numAgents, 1, 1, kernelIndex: simulationKernel);
  }
示例#15
0
        private bool Update(ThreeAddrLine line, ValueSet vals)
        {
            if (!ThreeAddrOpType.IsDefinition(line.OpType))
            {
                return(false);
            }

            var ret = ReachingValues.Compute(line, vals);

            vals[line.Accum] = ret;
            bool ok = false;


            if (ComputeHelper.IsConst(ret))
            {
                if (ThreeAddrOpType.Assign == line.OpType && line.RightOp == ret)
                {
                    return(false);
                }

                line.OpType  = ThreeAddrOpType.Assign;
                line.LeftOp  = null;
                line.RightOp = ret;



                return(true);
            }



            if (line.LeftOp != null && vals.ContainsKey(line.LeftOp))
            {
                if (vals[line.LeftOp] != "NAC")
                {
                    line.LeftOp = vals[line.LeftOp];
                    ok          = true;
                }
            }


            if (line.RightOp != null && vals.ContainsKey(line.RightOp))
            {
                if (vals[line.RightOp] != "NAC")
                {
                    line.RightOp = vals[line.RightOp];
                    ok           = true;
                }
            }


            return(ok);
        }
示例#16
0
        public static String Compute(ThreeAddrLine line, ValueSet vals)
        {
            if (line.OpType == ThreeAddrOpType.Read)
            {
                return("NAC");
            }


            int  a = 0, b = 0;
            bool isaconst = true;
            bool isbconst = true;

            if (!ComputeHelper.IsConst(line.LeftOp))
            {
                if (line.LeftOp != null)
                {
                    isaconst = int.TryParse(vals[line.LeftOp], out a);
                }
            }
            else
            {
                a = int.Parse(line.LeftOp);
            }

            if (!ComputeHelper.IsConst(line.RightOp))
            {
                isbconst = int.TryParse(vals[line.RightOp], out b);
            }
            else
            {
                b = int.Parse(line.RightOp);
            }

            if (line.OpType == ThreeAddrOpType.Assign)
            {
                if (isbconst)
                {
                    return(b.ToString());
                }
                else
                {
                    return(vals[line.RightOp]);
                }
            }


            if (!isaconst || !isbconst)
            {
                return("NAC");
            }

            return(ComputeHelper.Calculate(a, b, line.OpType).ToString());
        }
示例#17
0
        public async Task NpvCollection()
        {
            // Arrange
            var helper = new ComputeHelper();

            // Act
            var result = await helper.NpvCollectionAsync(model);

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(3, result.Labels.Count);
            Assert.AreEqual(3, result.Values.Count);
        }
示例#18
0
    void LateUpdate()
    {
        if (showAgentsOnly)
        {
            ComputeHelper.ClearRenderTexture(displayTexture);

            drawAgentsCS.SetTexture(0, "TargetTexture", displayTexture);
            ComputeHelper.Dispatch(drawAgentsCS, settings.numAgents, 1, 1, 0);
        }
        else
        {
            ComputeHelper.CopyRenderTexture(trailMap, displayTexture);
        }
    }
示例#19
0
 void PrecomputeOutScattering()
 {
     if (!settingsUpToDate || opticalDepthTexture == null || !opticalDepthTexture.IsCreated())
     {
         ComputeHelper.CreateRenderTexture(ref opticalDepthTexture, textureSize, FilterMode.Bilinear);
         opticalDepthCompute.SetTexture(0, "Result", opticalDepthTexture);
         opticalDepthCompute.SetInt("textureSize", textureSize);
         opticalDepthCompute.SetInt("numOutScatteringSteps", opticalDepthPoints);
         opticalDepthCompute.SetFloat("atmosphereRadius", (1 + atmosphereScale));
         opticalDepthCompute.SetFloat("densityFalloff", densityFalloff);
         opticalDepthCompute.SetVector("params", testParams);
         ComputeHelper.Run(opticalDepthCompute, textureSize, textureSize);
     }
 }
示例#20
0
        public virtual float[] Download(TensorShape shape)
        {
            Assert.IsTrue(shape.Is4D());

            var count = shape.length;

            Profiler.BeginSample("Barracuda.DownloadDataFromGPU");
            Assert.IsTrue(maxCapacity >= count);
            count = Math.Min(maxCapacity, count);

            m_AsyncDownloadSchedulingFrame = -1;

            int w = Mathf.Min(shape.length, MaxTextureSize);
            int h = Mathf.Max(1, ComputeHelper.IDivC(shape.length, w));

            Texture2D     texture   = new Texture2D(w, h, TextureFormat.RFloat, false);
            RenderTexture rttexture = new RenderTexture(w, h, 0, RenderTextureFormat.RFloat);


            Material material = new Material(PixelShaderSingleton.Instance.FindShader("Barracuda/TensorToBuffer"));


            material.SetVector("XdeclShape", new Vector4(shape.batch, shape.height, shape.width, shape.channels));
            material.SetTexture("Xdata", bufferAsTexture);
            material.SetInt("_OutputWidth", w);
            material.SetInt("_OutputHeight", h);

            Graphics.Blit(null, rttexture, material);


            var previousActiveRT = RenderTexture.active;

            RenderTexture.active = rttexture;
            Rect rectReadPicture = new Rect(0, 0, w, h);

            texture.ReadPixels(rectReadPicture, 0, 0);
            texture.Apply();

            var data = new float[count];

            Buffer.BlockCopy(texture.GetRawTextureData(), 0, data, 0, count * sizeof(float));

            RenderTexture.active = previousActiveRT;

            return(data);
        }
    public virtual float[] CalculateHeights(ComputeBuffer vertexBuffer)
    {
        //Debug.Log (System.Environment.StackTrace);
        // Set data
        SetShapeData();
        heightMapCompute.SetInt("numVertices", vertexBuffer.count);
        heightMapCompute.SetBuffer(0, "vertices", vertexBuffer);
        ComputeHelper.CreateAndSetBuffer <float> (ref heightBuffer, vertexBuffer.count, heightMapCompute, "heights");

        // Run
        ComputeHelper.Run(heightMapCompute, vertexBuffer.count);

        // Get heights
        var heights = new float[vertexBuffer.count];

        heightBuffer.GetData(heights);
        return(heights);
    }
示例#22
0
    void GenerateCollisionMesh(int resolution)
    {
        var(vertices, triangles) = CreateSphereVertsAndTris(resolution);
        ComputeHelper.CreateStructuredBuffer <Vector3> (ref vertexBuffer, vertices);

        // Set heights
        float[] heights = body.shape.CalculateHeights(vertexBuffer);
        for (int i = 0; i < vertices.Length; i++)
        {
            float height = heights[i];
            vertices[i] *= height;
        }

        // Create mesh
        CreateMesh(ref collisionMesh, vertices.Length);
        collisionMesh.vertices  = vertices;
        collisionMesh.triangles = triangles;
    }
示例#23
0
        public TextureTensorData(TensorShape shape, string buffername, bool clearOnInit = true)
        {
            name = buffername;

            int c4  = ComputeHelper.IDivC(shape.channels, 4);
            int c4w = c4;
            int c4h = 1;

            if (c4w * shape.width > MaxTextureSize)
            {
                c4w = Mathf.FloorToInt(MaxTextureSize / ((float)shape.width));
                c4h = ComputeHelper.IDivC(c4, c4w);
                m_tensorChannelTilled = true;
            }

            int bh = shape.batch;
            int bw = 1;

            if (bh * c4h * shape.height > MaxTextureSize)
            {
                bh = Mathf.FloorToInt(MaxTextureSize / ((float)(c4h * shape.height)));
                bw = ComputeHelper.IDivC(shape.batch, bh);
                m_tensorBatchTilled = true;
            }

            int h = bh * c4h * shape.height;
            int w = bw * c4w * shape.width;

            m_BufferAsTexture = new RenderTexture(w, h, 0, RenderTextureFormat.ARGBFloat);
            m_BufferAsTexture.Create();

            if (clearOnInit)
            {
                var previousActiveRT = RenderTexture.active;
                RenderTexture.active = m_BufferAsTexture;
                GL.Clear(true, true, Color.clear);
                RenderTexture.active = previousActiveRT;
            }

            m_Shape = shape;
            m_DisposeBufferAfterUse = true;
        }
示例#24
0
    void SetRandomPoints()
    {
        Random.InitState(seed);

        int randomizedNumPoints = numBiomePoints;

        if (randomize)
        {
            randomizedNumPoints = Random.Range(15, 50);
        }
        Random.InitState(seed);
        var randomPoints = new Vector4[randomizedNumPoints];

        for (int i = 0; i < randomPoints.Length; i++)
        {
            var point  = Random.onUnitSphere;
            var radius = Mathf.Lerp(radiusMinMax.x, radiusMinMax.y, Random.value);
            randomPoints[i] = new Vector4(point.x, point.y, point.z, radius);
        }

        ComputeHelper.CreateAndSetBuffer <Vector4> (ref pointBuffer, randomPoints, shadingDataCompute, "points");
        shadingDataCompute.SetInt("numRandomPoints", randomPoints.Length);
    }
 public virtual void ReleaseBuffers()
 {
     ComputeHelper.Release(shadingBuffer);
 }
示例#26
0
    // Generates terrain mesh based on heights generated by the Shape object
    // Shading data from the Shading object is stored in the mesh uvs
    // Returns the min/max height of the terrain
    Vector2 GenerateTerrainMesh(ref Mesh mesh, int resolution)
    {
        var(vertices, triangles) = CreateSphereVertsAndTris(resolution);
        ComputeHelper.CreateStructuredBuffer <Vector3> (ref vertexBuffer, vertices);

        float edgeLength = (vertices[triangles[0]] - vertices[triangles[1]]).magnitude;

        // Set heights
        float[] heights = body.shape.CalculateHeights(vertexBuffer);

        // Perturb vertices to give terrain a less perfectly smooth appearance
        if (body.shape.perturbVertices && body.shape.perturbCompute)
        {
            ComputeShader perturbShader      = body.shape.perturbCompute;
            float         maxperturbStrength = body.shape.perturbStrength * edgeLength / 2;

            perturbShader.SetBuffer(0, "points", vertexBuffer);
            perturbShader.SetInt("numPoints", vertices.Length);
            perturbShader.SetFloat("maxStrength", maxperturbStrength);

            ComputeHelper.Run(perturbShader, vertices.Length);
            Vector3[] pertData = new Vector3[vertices.Length];
            vertexBuffer.GetData(vertices);
        }

        // Calculate terrain min/max height and set heights of vertices
        float minHeight = float.PositiveInfinity;
        float maxHeight = float.NegativeInfinity;

        for (int i = 0; i < heights.Length; i++)
        {
            float height = heights[i];
            vertices[i] *= height;
            minHeight    = Mathf.Min(minHeight, height);
            maxHeight    = Mathf.Max(maxHeight, height);
        }

        // Create mesh
        CreateMesh(ref mesh, vertices.Length);
        mesh.SetVertices(vertices);
        mesh.SetTriangles(triangles, 0, true);
        mesh.RecalculateNormals();          //

        // Shading noise data
        body.shading.Initialize(body.shape);
        Vector4[] shadingData = body.shading.GenerateShadingData(vertexBuffer);
        mesh.SetUVs(0, shadingData);

        // Create crude tangents (vectors perpendicular to surface normal)
        // This is needed (even though normal mapping is being done with triplanar)
        // because surfaceshader wants normals in tangent space
        var normals       = mesh.normals;
        var crudeTangents = new Vector4[mesh.vertices.Length];

        for (int i = 0; i < vertices.Length; i++)
        {
            Vector3 normal = normals[i];
            crudeTangents[i] = new Vector4(-normal.z, 0, normal.x, 1);
        }
        mesh.SetTangents(crudeTangents);

        return(new Vector2(minHeight, maxHeight));
    }
示例#27
0
 public void ReleaseBuffers()
 {
     ComputeHelper.Release(craterBuffer);
 }
示例#28
0
        private static void Collect()
        {
#if DEBUG
            var sw = new Stopwatch();
            sw.Start();
#endif
            var batchNo = DateTime.Now.ToString("yyyyMMddHHmm");
            CommunicateDevice.FindAll().ForEach(com =>
            {
                //var key = "{0}://{1}:{2}-{3}".F(com.CommunicateDeviceTypeName, com.Args1, com.Args2, com.Args3);
                TransportTypeEnum type;
                if (!Enum.TryParse(com.CommunicateDeviceTypeName, true, out type))
                {
                    type = TransportTypeEnum.Unknow;
                }
                var host    = com.Args1;
                var e       = Convert.ToInt32(com.Args2);
                var timeout = Convert.ToInt32(com.Args3);
                //获取Transport
                var transport = TransportFactory.GetTransport(type, host, e, timeout);

                var modulars = com.ModularDevices;
                if (modulars != null && modulars.Count > 0)
                {
                    modulars.ForEach(modular =>
                    {
                        var deviceUnits = modular.SensorDeviceUnits;
                        if (deviceUnits != null && deviceUnits.Count > 0)
                        {
                            //按Function分组
                            deviceUnits.ToList().GroupBy(s => s.Function).ToList().ForEach(functionGp =>
                            {
                                var function = functionGp.Key;

                                var dataType = modular.ProtocalTypeName;
                                if (!dataType.EqualIgnoreCase(ProtocalTypeEnum.MODBUS.ToString()))
                                {
                                    return;
                                }
                                var modbusFunction = (MBFunction)Convert.ToByte(function);
                                var collectDevice  = new ModbusCollectDevice(transport,
                                                                             Convert.ToByte(modular.Address), modbusFunction)
                                {
                                    Registers = functionGp.ToList().SelectMany(deviceUnit =>
                                    {
                                        var start = Convert.ToInt32(deviceUnit.RegisterAddress);
                                        var count = deviceUnit.RegisterSize;
                                        var addrs = Enumerable.Range(start, count);
                                        return(addrs);
                                    }).ToList()
                                };

                                var result = false;
                                try
                                {
                                    collectDevice.EnsureTransport(transport);
                                    result = collectDevice.Read();
                                    while (!result)
                                    {
                                        collectDevice.EnsureTransport(transport);
                                        result = collectDevice.Read();
                                        if (result == true)
                                        {
                                            break;
                                        }
                                    }
                                }
                                catch (ObjectDisposedException odx)
                                {
                                    LogHelper.Fatal(odx.ToString());

                                    //重新构建transport
                                    transport = TransportFactory.GetTransport(type, host, e, timeout);
                                }
                                catch (Exception ex)
                                {
                                    LogHelper.Fatal(ex.ToString());
                                }
                                //读数据,重试三次
                                //for (var i = 0; i < 3; i++)
                                //{
                                //    try
                                //    {
                                //        collectDevice.EnsureTransport(transport);
                                //        result = collectDevice.Read();
                                //        break;
                                //    }
                                //    catch (ObjectDisposedException odx)
                                //    {
                                //        ServiceLogger.Current.WriteException(odx);

                                //        //重新构建transport
                                //        transport = TransportFactory.GetTransport(type, host, e, timeout);
                                //    }
                                //    catch (Exception ex)
                                //    {
                                //        ServiceLogger.Current.WriteException(ex);
                                //    }
                                //    ServiceLogger.Current.WriteWarn("第{3}次读取{0}:{1}地址为{2}数据失败", host, e, modular.Address, (i + 1));
                                //}

                                if (result)
                                {
                                    //保存到数据库
                                    var minReg = collectDevice.Registers.Min();
                                    functionGp.ToList().ForEach(deviceUnit =>
                                    {
                                        var regAddr = Convert.ToInt32(deviceUnit.RegisterAddress);
                                        var size    = deviceUnit.RegisterSize;
                                        //根据起始地址和数量计算出数值
                                        var value =
                                            collectDevice.Values.Skip(regAddr - minReg)
                                            .Take(size)
                                            .Sum(Convert.ToInt32);

                                        //判断是否为负数,负数取反+1,气象站温度使用
                                        if ((value & 0x8000) > 0)
                                        {
                                            //此传感器值为负数,需特殊处理
                                            var val = ~(Convert.ToInt16(value & 0x7fff)) & 0x7fff;
                                            value   = Convert.ToInt16(val + 1) * (-1);
                                        }
                                        //根据传感器的计算公式,转换成实际值
                                        var sensor = deviceUnit.Sensor;
                                        if (sensor != null)
                                        {
                                            var compute      = sensor.ValueComputeString;
                                            var processValue = ComputeHelper.CalcValue(compute, value,
                                                                                       sensor.Accuracy);

                                            deviceUnit.OriginalValue = value;
                                            //异常数据显示处理
                                            //Random random = new Random(DateTime.Now.Millisecond);
                                            //if(processValue>deviceUnit.Sensor.ExperienceMax&&
                                            //    processValue<deviceUnit.Sensor.ExperienceMin)
                                            //{
                                            //    //deviceUnit.ProcessedValue = random.Next(Convert.ToInt32(processValue), Convert.ToInt32(processValue +2));//随机范围为上次处理值左右
                                            //    deviceUnit.ProcessedValue = processValue;
                                            //    deviceUnit.ShowValue = sensor.ValueComputeString.IsNullOrWhiteSpace()
                                            //    ? deviceUnit.ProcessedValue.ToString()
                                            //    : ComputeHelper.CalcString(sensor.ValueComputeString, value);
                                            //}
                                            deviceUnit.ProcessedValue = processValue;
                                            deviceUnit.ShowValue      = sensor.ValueComputeString.IsNullOrWhiteSpace()
                                                ? deviceUnit.ProcessedValue.ToString(CultureInfo.InvariantCulture)
                                                : ComputeHelper.CalcString(sensor.ValueComputeString, value);
                                            deviceUnit.UpdateTime = DateTime.Now;
                                            deviceUnit.Save();
                                            LogHelper.Debug("更新传感器实时数据 {0} {1}", deviceUnit.Name,
                                                            deviceUnit.ProcessedValue);

                                            var dd = new DeviceData
                                            {
                                                Code1 = deviceUnit.FacilitySensorDeviceUnits[0].Code1,
                                                //暂时设定一个传感器设备只属于一个设施
                                                SensorDeviceUnitID = deviceUnit.ID,
                                                OriginalValue      = deviceUnit.OriginalValue,
                                                ProcessedValue     = deviceUnit.ProcessedValue,
                                                ShowValue          = deviceUnit.ShowValue,
                                                Max        = sensor.ExperienceMax,
                                                Min        = sensor.ExperienceMin,
                                                Upload     = false,
                                                CreateTime = DateTime.Now,
                                                Remark     = batchNo
                                            };
                                            //测量值
                                            //if (dd.ProcessedValue > sensor.MaxValue || dd.ProcessedValue < sensor.MinValue)
                                            //    dd.IsException = true;
                                            //经验值:超过经验值即为超出设定上下限
                                            if (dd.ProcessedValue > sensor.ExperienceMax ||
                                                dd.ProcessedValue < sensor.ExperienceMin)
                                            {
                                                dd.IsException = true;
                                            }
                                            dd.Save();
                                            //ServiceLogger.Current.WriteDebugLog("添加历史数据 {0} {1}", deviceUnit.Name,
                                            //    deviceUnit.ProcessedValue);
                                        }
                                        else
                                        {
                                            LogHelper.Error("ID ={0} {1} 未配置传感器", deviceUnit.ID,
                                                            deviceUnit.Name);
                                        }
                                    });
                                }
                                else
                                {
                                    LogHelper.Error("读取设备数据失败");
                                }
                            });
                        }
                    });
                }
            });

#if DEBUG
            sw.Stop();
            LogHelper.Debug("传感器采集耗时" + sw.ElapsedMilliseconds.ToString() + "ms");
#endif
        }
示例#29
0
    void Init()
    {
        // Create render textures
        ComputeHelper.CreateRenderTexture(ref trailMap, settings.width, settings.height, filterMode, format);
        ComputeHelper.CreateRenderTexture(ref diffusedTrailMap, settings.width, settings.height, filterMode, format);
        ComputeHelper.CreateRenderTexture(ref displayTexture, settings.width, settings.height, filterMode, format);

        // Create agents with initial positions and angles
        Agent[] agents = new Agent[settings.numAgents];
        for (int i = 0; i < agents.Length; i++)
        {
            Vector2 centre      = new Vector2(settings.width / 2, settings.height / 2);
            Vector2 startPos    = Vector2.zero;
            float   randomAngle = Random.value * Mathf.PI * 2;
            float   angle       = 0;

            if (settings.spawnMode == SpawnMode.Point)
            {
                startPos = centre;
                angle    = randomAngle;
            }
            else if (settings.spawnMode == SpawnMode.Random)
            {
                startPos = new Vector2(Random.Range(0, settings.width), Random.Range(0, settings.height));
                angle    = randomAngle;
            }
            else if (settings.spawnMode == SpawnMode.InwardCircle)
            {
                startPos = centre + Random.insideUnitCircle * settings.height * 0.5f;
                angle    = Mathf.Atan2((centre - startPos).normalized.y, (centre - startPos).normalized.x);
            }
            else if (settings.spawnMode == SpawnMode.RandomCircle)
            {
                startPos = centre + Random.insideUnitCircle * settings.height * 0.15f;
                angle    = randomAngle;
            }

            Vector3Int speciesMask;
            int        speciesIndex = 0;
            int        numSpecies   = settings.speciesSettings.Length;

            if (numSpecies == 1)
            {
                speciesMask = Vector3Int.one;
            }
            else
            {
                int species = Random.Range(1, numSpecies + 1);
                speciesIndex = species - 1;
                speciesMask  = new Vector3Int((species == 1) ? 1 : 0, (species == 2) ? 1 : 0, (species == 3) ? 1 : 0);
            }



            agents[i] = new Agent()
            {
                position = startPos, angle = angle, speciesMask = speciesMask, speciesIndex = speciesIndex
            };
        }

        ComputeHelper.CreateAndSetBuffer <Agent>(ref agentBuffer, agents, compute, "agents", updateKernel);
        compute.SetInt("numAgents", settings.numAgents);
        drawAgentsCS.SetBuffer(0, "agents", agentBuffer);
        drawAgentsCS.SetInt("numAgents", settings.numAgents);


        compute.SetInt("width", settings.width);
        compute.SetInt("height", settings.height);
    }
示例#30
0
 void OnDestroy()
 {
     ComputeHelper.Release(agentBuffer, settingsBuffer);
 }