Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using UnityEngine;
- namespace StylizedWaterShader
- {
- [RequireComponent(typeof(MeshFilter))]
- [ExecuteInEditMode]
- public class VertexColorBaker : MonoBehaviour
- {
- public Mesh sourceMesh;
- [Min(0.01f)]
- public float intersectionLength = 1f;
- [Min(0.01f)]
- public float depthExponent = 1f;
- private MeshFilter mf;
- private Mesh newMesh;
- private void Reset()
- {
- mf = GetComponent<MeshFilter>();
- if (mf)
- {
- sourceMesh = mf.sharedMesh;
- }
- }
- private void Start()
- {
- //Procedural meshes cannot be saved to prefabs. If it is missing, regenerate
- if(!newMesh) Bake();
- }
- private void OnValidate()
- {
- depthExponent = Mathf.Max(depthExponent, 0.01f);
- intersectionLength = Mathf.Max(intersectionLength, 0.01f);
- Bake();
- }
- [ContextMenu("BAKE")]
- void Bake()
- {
- if (!sourceMesh) return;
- newMesh = new Mesh();
- newMesh.name = "VertexColorMesh";
- Vector3[] verts = sourceMesh.vertices;
- Color[] colors = new Color[verts.Length];
- RaycastHit hit;
- float dist = 0;
- bool hasHitBelow = false;
- bool hasHitAbove = false;
- //Go over every vertex position, and raycast down to find the distance to the terrain
- for (int i = 0; i < verts.Length; i++)
- {
- Vector3 position = transform.TransformPoint(verts[i]);
- Vector3 rayOrigin = position;
- //Default value for missed hits
- dist = 0;
- hasHitAbove = false;
- hasHitBelow = false;
- rayOrigin.y += 100f;
- if ((Physics.Raycast(rayOrigin, Vector3.down, out hit, Mathf.Infinity, -1, QueryTriggerInteraction.Ignore)))
- {
- //Only accept hits from terrain colliders
- if (hit.collider.GetType() == typeof(TerrainCollider))
- {
- hasHitBelow = hit.point.y < position.y;
- hasHitAbove = hit.point.y >= position.y;
- dist = hit.point.y - position.y;
- }
- }
- //Normalized depth values
- float intersection = 1 - Mathf.Abs(dist / intersectionLength);
- float depthVal = 1 - Mathf.Clamp01((-dist) / depthExponent);
- intersection = hasHitBelow ? intersection : 0f;
- intersection = hasHitAbove ? 1f : intersection;
- depthVal = hasHitBelow ? depthVal : 0f;
- depthVal = hasHitAbove ? 1f : depthVal;
- colors[i] = new Color(intersection, depthVal, colors[i].b, colors[i].a);
- }
- newMesh.vertices = verts;
- newMesh.triangles = sourceMesh.triangles;
- newMesh.normals = sourceMesh.normals;
- newMesh.uv = sourceMesh.uv;
- newMesh.colors = colors;
- newMesh.RecalculateBounds();
- newMesh.RecalculateTangents();
- mf.sharedMesh = newMesh;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement