Skip to content

Instantly share code, notes, and snippets.

@but80
Created May 13, 2015 15:40
Show Gist options
  • Save but80/0ffcfb33a14a6164fd3c to your computer and use it in GitHub Desktop.
Save but80/0ffcfb33a14a6164fd3c to your computer and use it in GitHub Desktop.
Water4Simpleのインスタンスにくっつける。computeShader には https://gist.github.com/but80/8c5f9fc872d56a3a4673 を指定。FX4WaterSimple.shader を https://gist.github.com/but80/3038a735543087b5fe6a のように改造する。
using UnityEngine;
using System.Runtime.InteropServices;
struct OceanParticle {
public Vector3 position;
public float velocity;
public float force;
public OceanParticle(Vector3 position) {
this.position = position;
this.velocity = 0f;
this.force = 0f;
}
}
//[ExecuteInEditMode]
public class OceanSurfaceRenderer : MonoBehaviour {
public ComputeShader computeShader;
int cols = 150;
int rows = 100;
float sizeX = 30f;
float sizeZ = 20f;
float tension = 5f;
float friction = .01f;
float fadeRadius = 1e10f;//15f;
float fadeCurve = 4f;
float density = 1f;
float initialWidth = 1f;
float initialHeight = 5f;
ComputeBuffer computeBuffer;
int computeForceKID;
void OnDisable() {
computeBuffer.Release();
}
void Start() {
InitializeComputeBuffer();
}
void Update() {
computeShader.SetBuffer(0, "Particles", computeBuffer);
computeShader.SetFloats("Tension", new float[2]{ tension, tension });
computeShader.SetFloat("Friction", friction);
computeShader.SetFloat("FadeRadius", fadeRadius);
computeShader.SetFloat("FadeCurve", fadeCurve);
computeShader.SetFloat("Mass", density * sizeX * sizeZ / ((cols+1) * (rows+1)));
computeShader.SetInts("Division", new int[2]{ cols, rows });
computeShader.SetInt("XCount", cols+1);
computeShader.SetFloats("Pitch", new float[2]{ sizeX/cols, sizeZ/rows });
computeShader.SetFloat("DeltaTime", Time.deltaTime);
computeShader.Dispatch(computeForceKID, computeBuffer.count / 8 + 1, 1, 1);
}
void InitializeComputeBuffer() {
computeBuffer = new ComputeBuffer((cols+1)*(rows+1), Marshal.SizeOf(typeof(OceanParticle)));
OceanParticle[] bullets = new OceanParticle[computeBuffer.count];
int k = 0;
for (int i=0; i<=rows; i++) {
float ip = (float)i/rows;
float z = Mathf.Lerp(-sizeZ*.5f, sizeZ*.5f, ip);
for (int j=0; j<=cols; j++) {
float jp = (float)j/cols;
float x = Mathf.Lerp(-sizeX*.5f, sizeX*.5f, jp);
float h = initialHeight * Mathf.Exp(-(x*x+z*z) / (2f*initialWidth*initialWidth));
bullets[k++] = new OceanParticle(new Vector3(x, h, z));
}
}
computeBuffer.SetData(bullets);
computeForceKID = computeShader.FindKernel("ComputeForce");
}
void OnRenderObject() {
var renderers = GetComponentsInChildren<MeshRenderer> ();
foreach (var renderer in renderers) {
var material = renderer.materials[0];
material.SetBuffer ("Particles", computeBuffer);
material.SetInt ("XDivision", cols);
material.SetInt ("ZDivision", rows);
material.SetInt ("XCount", cols + 1);
material.SetInt ("ZCount", rows + 1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment