/Assets/Scripts/InGameVertexPaint.cs
https://bitbucket.org/lostfictions/vertexpainting · C# · 101 lines · 64 code · 24 blank · 13 comment · 14 complexity · d00223b86e1d92e9befe4ba634c8a8ee MD5 · raw file
- using UnityEngine;
- using System;
- using System.Collections.Generic;
- using Debug = UnityEngine.Debug;
- using Object = UnityEngine.Object;
- using Random = UnityEngine.Random;
- public class InGameVertexPaint : MonoBehaviour
- {
- public Color32 color;
- [Range(1f, 100f)]
- public float strength = 2f;
- //if true, checks if shader has "VertexPaint" tag set.
- public bool checkVertexPaintable = true;
- public bool drawDebugInfo = true;
- public Material autoConvertFrom;
- public Material autoConvertTo;
- void Start()
- {
-
- }
-
- void Update()
- {
- //TODO: should start checking within selection on mouse down, not
- //just checking continuously
- // if(!Input.GetMouseButton(0))
- // return;
- Ray ray = camera.ScreenPointToRay(Input.mousePosition);
- RaycastHit hit;
- if(!Physics.Raycast(ray, out hit))
- return;
- //TODO: at this point check cached transform
- // var mf = hit.transform.GetComponent<MeshFilter>();
- // if(!ren
- // || !mf
- // || !mf.mesh)
- // return;
- Renderer ren = hit.transform.renderer;
- MeshCollider mc = hit.collider as MeshCollider;
- if(mc == null
- || mc.sharedMesh == null
- || !ren.sharedMaterial)
- return;
- if(ren.sharedMaterial == autoConvertFrom)
- {
- ren.sharedMaterial = autoConvertTo;
- //HACK
- // mc.sharedMesh.colors32 = new Color32[mc.sharedMesh.vertices.Length];
- }
- else if(checkVertexPaintable && ren.sharedMaterial.GetTag("VertexPaint", false, "") == "")
- return;
-
- Mesh mesh = mc.sharedMesh;
- int[] triangles = mesh.triangles;
- var colors = mesh.colors32 ?? new Color32[mesh.vertices.Length];
- int i0 = triangles[hit.triangleIndex * 3 + 0];
- int i1 = triangles[hit.triangleIndex * 3 + 1];
- int i2 = triangles[hit.triangleIndex * 3 + 2];
- Vector3 bary = hit.barycentricCoordinate;
- colors[i0] = Color32.Lerp(colors[i0], color, bary.x * strength / 100f);
- colors[i1] = Color32.Lerp(colors[i1], color, bary.y * strength / 100f);
- colors[i2] = Color32.Lerp(colors[i2], color, bary.z * strength / 100f);
- mesh.colors32 = colors;
-
- if(drawDebugInfo)
- {
- var vertices = mesh.vertices;
- Transform hitTransform = hit.transform;
- Vector3 p0 = hitTransform.TransformPoint(vertices[i0]);
- Vector3 p1 = hitTransform.TransformPoint(vertices[i1]);
- Vector3 p2 = hitTransform.TransformPoint(vertices[i2]);
- Debug.DrawLine(p0, p1, Color.red, 0, false);
- Debug.DrawLine(p1, p2, Color.red, 0, false);
- Debug.DrawLine(p2, p0, Color.red, 0, false);
- if(Input.GetKeyDown("f"))
- {
- Debug.Log(hit.triangleIndex + "/" + triangles.Length / 3 + " (" + vertices.Length + " verts)");
- }
- }
- }
- }