Advertisement
Earthcomputer

PhysicsSystem.java

Apr 18th, 2019
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.31 KB | None | 0 0
  1.     private void physicsTimeStep(Level level) {
  2.  
  3.         // Integrate forces
  4.         level.forEachComponent(PhysicsComponent.class, physComp -> {
  5.             physComp.momentum.add(physComp.force);
  6.             physComp.angularMomentum.add(physComp.torque);
  7.         });
  8.  
  9.         // Solve velocity constraints
  10.         level.forEachComponent(PhysicsComponent.class, component ->
  11.                 component.joints.forEach(joint ->
  12.                         joint.initVelocityConstraints(level)));
  13.  
  14.         for (int i = 0; i < Constants.VELOCITY_CONSTRAINT_ITERS; i++) {
  15.             level.forEachComponent(PhysicsComponent.class, component ->
  16.                     component.joints.forEach(joint ->
  17.                             joint.solveVelocityConstraints(level)));
  18.         }
  19.  
  20.         // Integrate velocities
  21.         level.forEachEntityWithComponent(PhysicsComponent.class, entity -> {
  22.             PositionComponent posComp = level.getComponent(entity, PositionComponent.class);
  23.             PhysicsComponent physComp = level.getComponent(entity, PhysicsComponent.class);
  24.  
  25.             Vector3f velocity = physComp.getVelocity();
  26.             Vector3fc pos = posComp.getPos();
  27.             posComp.setPos(pos.x() + velocity.x,
  28.                     pos.y() + velocity.y,
  29.                     pos.z() + velocity.z);
  30.  
  31.  
  32.             Vector3f angularVelocity = physComp.getAngularVelocity(posComp.getRot());
  33.             if (angularVelocity.lengthSquared() > 1E-6f)
  34.                 posComp.setRot(new Quaternionf(new AxisAngle4f(angularVelocity.length(), angularVelocity.normalize(new Vector3f())))
  35.                         .mul(posComp.getRot()).normalize());
  36.         });
  37.  
  38.         // Solve position constraints
  39.         boolean positionSolved = false;
  40.         for (int i = 0; i < Constants.POSITION_CONSTRAINT_ITERS; i++) {
  41.  
  42.             boolean jointsSolved = true;
  43.             for (BaseComponent baseComp : level.getComponentLists().get(PhysicsComponent.class).values()) {
  44.                 PhysicsComponent physComp = (PhysicsComponent) baseComp;
  45.                 for (Joint joint : physComp.joints) {
  46.                     jointsSolved &= joint.solvePositionConstraints(level);
  47.                 }
  48.             }
  49.  
  50.             if (jointsSolved) {
  51.                 positionSolved = true;
  52.                 break;
  53.             }
  54.         }
  55.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement