74 lines
1.9 KiB
Kotlin
74 lines
1.9 KiB
Kotlin
package network.rs485.ben.computervision
|
|
|
|
import kotlinx.coroutines.coroutineScope
|
|
import kotlinx.coroutines.delay
|
|
import kotlinx.coroutines.launch
|
|
import org.opencv.core.Mat
|
|
import org.opencv.core.Scalar
|
|
import java.util.*
|
|
|
|
class Entity {
|
|
val lines: TreeSet<Line> = sortedSetOf(comparator = LineComparator)
|
|
|
|
fun color(color: Scalar, image: Mat) {
|
|
lines.forEach {
|
|
image.drawLine(it, color)
|
|
}
|
|
}
|
|
|
|
fun merge(other: Entity) {
|
|
lines.addAll(other.lines)
|
|
}
|
|
|
|
override fun equals(other: Any?): Boolean {
|
|
return this === other || other is Entity && lines == other.lines
|
|
}
|
|
|
|
override fun hashCode(): Int {
|
|
return lines.hashCode()
|
|
}
|
|
|
|
override fun toString(): String {
|
|
return "Entity(${lines.joinToString(limit = 3) { "${it.first} -- ${it.second}" }})"
|
|
}
|
|
}
|
|
|
|
fun MutableList<Entity>.merge(entity: Entity) {
|
|
val toMerge = mutableSetOf<Entity>()
|
|
entity.lines.forEach { line ->
|
|
toMerge.addAll(this.filter { otherEntity ->
|
|
otherEntity.lines.any(line::intersects)
|
|
})
|
|
}
|
|
if (toMerge.size == 0) {
|
|
add(entity)
|
|
} else {
|
|
val retainedEntity = toMerge.first()
|
|
retainedEntity.merge(entity)
|
|
toMerge.forEach {
|
|
if (it !== retainedEntity) {
|
|
this.remove(it)
|
|
retainedEntity.merge(it)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
suspend fun MutableList<Entity>.colorRanged(
|
|
start: Scalar,
|
|
end: Scalar,
|
|
image: Mat,
|
|
windowMgr: IWindowManager,
|
|
) = coroutineScope {
|
|
if (size == 0) return@coroutineScope
|
|
if (size == 1) get(0).color(start, image)
|
|
val direction = (end - start) * (1.0 / (size - 1))
|
|
forEachIndexed { index, entity ->
|
|
entity.color(start + (direction * index.toDouble()), image)
|
|
launch {
|
|
windowMgr.updateImage(image)
|
|
}
|
|
if (ANIMATION_DELAY.isPositive()) delay(ANIMATION_DELAY)
|
|
}
|
|
}
|