I played with this approach to drawing triangles, but I’m not sure if it makes things faster. It provides a triangle drawer with a maximum number of triangles (to avoid resizing the buffer). Then one can draw a variable amount of triangles on every frame (up to the maximum). It allows to specify a color per vertex, although one could simplify it to specify a color per triangle.
3-Color triangle drawer
imports
import org.openrndr.WindowMultisample
import org.openrndr.application
import org.openrndr.draw.*
import org.openrndr.extra.noise.Random
import org.openrndr.extra.noise.uniform
import org.openrndr.math.Vector2
import org.openrndr.math.Vector4
data class ColoredTriangle(
val p0: Vector2, val p1: Vector2, val p2: Vector2,
val c0: Vector4, val c1: Vector4, val c2: Vector4
)
class TriangleDrawer(private val drawer: Drawer, maxTriangles: Int) {
private val geom = vertexBuffer(vertexFormat {
position(3)
color(4)
}, 3 * maxTriangles)
fun draw(tris: List<ColoredTriangle>) {
geom.put {
tris.forEach { tri ->
write(tri.p0.x.toFloat(), tri.p0.y.toFloat(), 0f)
write(tri.c0)
write(tri.p1.x.toFloat(), tri.p1.y.toFloat(), 0f)
write(tri.c1)
write(tri.p2.x.toFloat(), tri.p2.y.toFloat(), 0f)
write(tri.c2)
}
}
val count = (tris.size * 3).coerceAtMost(geom.vertexCount)
drawer.shadeStyle = shadeStyle {
fragmentTransform = "x_fill = va_color;"
}
drawer.vertexBuffer(geom, DrawPrimitive.TRIANGLES, 0, count)
}
}
fun main() {
application {
//configure { multisample = WindowMultisample.SampleCount(8) }
program {
val triangleDrawer = TriangleDrawer(drawer, 1000)
val area = drawer.bounds.offsetEdges(-50.0)
extend {
val count = Random.int(1, 1000)
triangleDrawer.draw(List(count) {
ColoredTriangle(
Vector2.uniform(area),
Vector2.uniform(area),
Vector2.uniform(area),
Vector4.uniform(0.0, 1.0),
Vector4.uniform(0.0, 1.0),
Vector4.uniform(0.0, 1.0)
)
})
}
}
}
}
The size of the triangles does affect the performance, so drawing a thousand overlapping translucent triangles is quite heavy. One can get a high frame rate by drawing smaller triangles with less overlap.