Search Unity

Convert C# script to compute shader to run on gpu instead of cpu

Discussion in 'Scripting' started by TheOtherUserName, Feb 3, 2021.

  1. TheOtherUserName

    TheOtherUserName

    Joined:
    May 30, 2020
    Posts:
    136
    Hi so I feel kinda dumb saying that but I have no idea how compute shaders work. All I know is that they run on gpu instead of cpu and here I shot myself in the foot. I have downloaded a low poly water model from the asset store but after some backtracking I noticed it the waves are generated using a c# script. I an attempt to optimize I wanted to open a new thread though I can't read the position then, so now I am here. If someone could optimize it or post resources for me I would love that.

    This is the asset I use and here is the code for the waves:
    Code (CSharp):
    1. for (int i = 0; i < vertices.Length; i++)
    2.             {
    3.                 Vector3 v = vertices[i];
    4.  
    5.                 //Initially set the wave height to 0
    6.                 v.y = 0.0f;
    7.  
    8.                 //Get the distance between wave origin position and the current vertex
    9.                 float distance = Vector3.Distance(v, waveOriginPosition);
    10.                 distance = (distance % waveLength) / waveLength;
    11.  
    12.                 //Oscilate the wave height via sine to create a wave effect
    13.                 v.y = waveHeight * Mathf.Sin(Time.time * Mathf.PI * 2.0f * waveFrequency
    14.                 + (Mathf.PI * 2.0f * distance));
    15.                
    16.                 //Update the vertex
    17.                 vertices[i] = v;
    18.             }
    19.  
    20.             //Update the mesh properties
    21.             mesh.vertices = vertices;
    22.             mesh.RecalculateNormals();
    23.             mesh.MarkDynamic();
    24.             meshFilter.mesh = mesh;
    Thats the entire wave code thats causing trouble. In Update is nothing but this method.
     
  2. csofranz

    csofranz

    Joined:
    Apr 29, 2017
    Posts:
    1,556
    Above code simply modifies the water mesh based on position, sine and time. It's a very nice demonstration of how to manipulate a mesh with your code. Of course it's not optimized, and is not in any way parallel. You can either try and stuff this into a compute shader (should work, requires some painful learning if you have never done massively parallel programming before), or you can write your own shader (as demonstrated here) to do this (requires even more painful learning if you have never touched shader programming before).
     
    TheOtherUserName likes this.
  3. TheOtherUserName

    TheOtherUserName

    Joined:
    May 30, 2020
    Posts:
    136
    Thanks for the url I think that will help. I guess I just have to learn shaders at some point in time :)