diff --git a/leenkx/Sources/leenkx/trait/physics/PhysicsWorld.hx b/leenkx/Sources/leenkx/trait/physics/PhysicsWorld.hx index db6f28a..f8532e1 100644 --- a/leenkx/Sources/leenkx/trait/physics/PhysicsWorld.hx +++ b/leenkx/Sources/leenkx/trait/physics/PhysicsWorld.hx @@ -1,5 +1,7 @@ package leenkx.trait.physics; +import iron.object.Object; + #if (!lnx_physics) class Hit { } @@ -11,10 +13,63 @@ class PhysicsWorld extends iron.Trait { public function new() { super(); } } typedef PhysicsWorld = leenkx.trait.physics.bullet.PhysicsWorld; typedef Hit = leenkx.trait.physics.bullet.PhysicsWorld.Hit; + typedef RigidBody = leenkx.trait.physics.bullet.RigidBody; #else typedef PhysicsWorld = leenkx.trait.physics.oimo.PhysicsWorld; typedef Hit = leenkx.trait.physics.oimo.PhysicsWorld.Hit; + typedef RigidBody = leenkx.trait.physics.oimo.RigidBody; #end + typedef RigidBodyCacheEntry = { + var rb: RigidBody; + var traitCount: Int; + } + + class PhysicsCache { + + static var rigidBodyCache: Map = new Map(); + static var contactsCache: Map> = new Map(); + static var contactsCacheFrame: Int = 0; + + public static function getCachedRigidBody(object: Object): RigidBody { + if (object == null) return null; + + var entry = rigidBodyCache.get(object); + + if (entry == null || entry.traitCount != object.traits.length) { + var rb = object.getTrait(RigidBody); + rigidBodyCache.set(object, { rb: rb, traitCount: object.traits.length }); + return rb; + } + + return entry.rb; + } + + public static function getCachedContacts(rb: RigidBody): Array { + if (rb == null || PhysicsWorld.active == null) return null; + + var cached = contactsCache.get(rb); + if (cached != null) return cached; + + var contacts = PhysicsWorld.active.getContacts(rb); + contactsCache.set(rb, contacts); + return contacts; + } + + public static inline function hasContactWith(contacts: Array, target: RigidBody): Bool { + return contacts != null && target != null && contacts.indexOf(target) >= 0; + } + + public static function clearCache() { + rigidBodyCache.clear(); + contactsCache.clear(); + } + + public static function clearContactsCache() { + contactsCacheFrame++; + contactsCache.clear(); + } + } + #end