public static Texture2D Paint(Vector2 pos, float rad, Color col, float hardness, Texture2D tex) { var start = new Vector2(Mathf.Clamp(pos.x - rad, 0, tex.width), Mathf.Clamp(pos.y - rad, 0, tex.height)); //var width = rad * 2; var end = new Vector2(Mathf.Clamp(pos.x + rad, 0, tex.width), Mathf.Clamp(pos.y + rad, 0, tex.height)); var widthX = Mathf.Round(end.x - start.x); var widthY = Mathf.Round(end.y - start.y); //var sqrRad = rad * rad; var sqrRad2 = (rad + 1) * (rad + 1); Color[] pixels = tex.GetPixels((int)start.x, (int)start.y, (int)widthX, (int)widthY, 0); for (var y = 0; y < widthY; y++) { for (var x = 0; x < widthX; x++) { var p = new Vector2(x, y) + start; var center = p + new Vector2(0.5f, 0.5f); float dist = (center - pos).sqrMagnitude; if (dist > sqrRad2) { continue; } var samples = Sample(p); var c = Color.black; for (var i = 0; i < samples.Length; i++) { dist = Mathfx.GaussFalloff(Vector2.Distance(samples[i], pos), rad) * hardness; if (dist > 0) { c += Color.Lerp(pixels[y * (int)widthX + x], col, dist); } else { c += pixels[y * (int)widthX + x]; } } c /= samples.Length; pixels[y * (int)widthX + x] = c; } } tex.SetPixels((int)start.x, (int)start.y, (int)widthX, (int)widthY, pixels, 0); return(tex); }
public static void PaintLine(Stroke stroke, ref Texture2D tex) { //var width = stroke.width * 2; var extent = stroke.width; var stY = Mathf.Clamp(Mathf.Min(stroke.start.y, stroke.end.y) - extent, 0, tex.height); var stX = Mathf.Clamp(Mathf.Min(stroke.start.x, stroke.end.x) - extent, 0, tex.width); var endY = Mathf.Clamp(Mathf.Max(stroke.start.y, stroke.end.y) + extent, 0, tex.height); var endX = Mathf.Clamp(Mathf.Max(stroke.start.x, stroke.end.x) + extent, 0, tex.width); var lengthX = endX - stX; var lengthY = endY - stY; //var sqrRad = stroke.width * stroke.width; var sqrRad2 = (stroke.width + 1) * (stroke.width + 1); var start = new Vector2(stX, stY); Vector2 p = new Vector2(); Vector2 center = new Vector2(); float dist; for (int y = 0; y < (int)lengthY; y++) { for (int x = 0; x < (int)lengthX; x++) { p.Set(x, y); p += start; center = p + Vector2.one * 0.5f; dist = (center - Mathfx.NearestPointStrict(stroke.start, stroke.end, center)).sqrMagnitude; if (dist > sqrRad2) { continue; } dist = Mathfx.GaussFalloff(Mathf.Sqrt(dist), stroke.width) * stroke.hardness; if (dist > 0) { tex.SetPixel(x + (int)stX, y + (int)stY, stroke.color); } } } tex.Apply(false); }