Skip to content

Commit 519714b

Browse files
committed
Added iterator property to entity utils
1 parent bcd4d5a commit 519714b

File tree

1 file changed

+19
-12
lines changed

1 file changed

+19
-12
lines changed

common/src/main/kotlin/com/lambda/util/world/EntityUtils.kt

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -22,20 +22,23 @@ object EntityUtils {
2222
range: Double = 6.0,
2323
noinline predicate: (T) -> Boolean = { true },
2424
): T? {
25+
var closest: T? = null
26+
var closestDistance = Double.MAX_VALUE
27+
28+
val iterator: (T) -> Any = {
29+
val distance = it.squaredDistanceTo(pos)
30+
if (distance < closestDistance) {
31+
closest = it
32+
closestDistance = distance
33+
}
34+
}
35+
2536
// Speculative execution trolling
2637
val entities = ArrayList<T>()
27-
if (range > 64) getEntities(entities, predicate)
28-
// I have an idea for optimization.
29-
//
30-
// Since the search operates linearly, eventually it will reach the midpoint.
31-
// Calculate the distance between the first and last entities.
32-
// Obtain the delta value.
33-
// Theoretically, the closest entity should be within a cubic space of delta^3 blocks.
34-
// If there are no entities within this delta box, examine the outer box. (Although this is unlikely given the fact that the closest entity is within the delta box.)
35-
// The performance improvement is relative to the initial state.
36-
else getFastEntities(pos, range, entities, predicate)
38+
if (range > 64) getEntities(entities, predicate, iterator)
39+
else getFastEntities(pos, range, entities, predicate, iterator)
3740

38-
return entities.minByOrNull { it.squaredDistanceTo(pos) }
41+
return closest
3942
}
4043

4144
/**
@@ -71,6 +74,7 @@ object EntityUtils {
7174
distance: Double,
7275
pointer: MutableList<T>,
7376
noinline predicate: (T) -> Boolean = { true },
77+
noinline iterator: (T) -> Unit = { },
7478
) {
7579
val chunks = ceil(distance / 16).toInt()
7680
val sectionX = pos.x.toInt() shr 4
@@ -85,6 +89,7 @@ object EntityUtils {
8589
for (z in sectionZ - chunks..sectionZ + chunks) {
8690
val section = world.entityManager.cache.findTrackingSection(ChunkSectionPos.asLong(x, y, z)) ?: continue
8791
section.collection.filterIsInstanceTo(pointer) { entity ->
92+
iterator(entity)
8893
entity != player && entity.squaredDistanceTo(pos) <= distance * distance && predicate(entity)
8994
}
9095
}
@@ -103,9 +108,11 @@ object EntityUtils {
103108
*/
104109
inline fun <reified T : Entity> SafeContext.getEntities(
105110
pointer: MutableList<T>,
106-
noinline predicate: (T) -> Boolean = { true }
111+
noinline predicate: (T) -> Boolean = { true },
112+
noinline iterator: (T) -> Unit = { },
107113
) {
108114
world.entities.filterIsInstanceTo(pointer) { entity ->
115+
iterator(entity)
109116
entity != player && predicate(entity)
110117
}
111118
}

0 commit comments

Comments
 (0)