void setDirectionVector(ServerElement element, Float x, Float y, Float z) { RigidBody rb = elementToRigidBody.get(element); rb.getOrientation(oriantation); rot.set(oriantation); directionVector.set(x, y, z); rot.transform(directionVector); }
void updateServerElements() { for (RigidBody rb : rigidBodies) { ServerElement element = rigidBodyToServerElement.get(rb); if (rb != null && rb.getMotionState() != null) { rb.getMotionState().getWorldTransform(tmpTrans); element.setTransform(tmpTrans); } if (!rb.isActive()) { rb.activate(); } // log.debug(" "+element.getPosition()); } for (Integer id : serverGameArea.getGameState().getDynamicElements().keySet()) { ServerElement elem = serverGameArea.getGameState().getDynamicElements().get(id); elem.getCollidees().clear(); } Integer nbManifold = dynamicsWorld.getDispatcher().getNumManifolds(); for (Integer i = 0; i < nbManifold; i++) { PersistentManifold pm = dynamicsWorld.getDispatcher().getManifoldByIndexInternal(i); RigidBody rb0 = (RigidBody) pm.getBody0(); RigidBody rb1 = (RigidBody) pm.getBody1(); ServerElement elem0 = rigidBodyToServerElement.get(rb0); ServerElement elem1 = rigidBodyToServerElement.get(rb1); if ((elem0 instanceof ServerBullet) || (elem1 instanceof ServerBullet)) { log.info("coll " + elem0 + " " + elem1); } elem0.addCollidee(elem1); elem1.addCollidee(elem0); } }
public void transform(Matrix4f mat, boolean updateLocal) { activate(); Transform t = new Transform(); t.set(mat); Vector3f v = new Vector3f(); for (int i = 0; i < 3; ++i) { t.basis.getColumn(i, v); v.normalize(); t.basis.setColumn(i, v); } body.setWorldTransform(t); // required for static objects: body.getMotionState().setWorldTransform(t); if (body.isInWorld() && body.isStaticOrKinematicObject()) { scene.world.updateSingleAabb(body); for (GameObject g : touchingObjects) g.activate(); } // updateChildTransforms(); if (parent != null && updateLocal) { updateLocalTransform(); } }
public void mass(float mass) { if (mass == 0) { throw new RuntimeException("no zero value allowed: use 'dynamics(false)' instead"); } Vector3f inertia = new Vector3f(); body.getCollisionShape().calculateLocalInertia(mass, inertia); body.setMassProps(mass, inertia); }
public void setElementRotation(ServerElement element, Float rot) { // log.debug("rot"); RigidBody rb = elementToRigidBody.get(element); synchronized (turnVector) { turnVector.set(0f, rot, 0f); rb.applyTorque(turnVector); // rb.setAngularVelocity(turnVector); } }
public void dynamics(boolean restore) { if (currBodyType.equals("DYNAMIC") || currBodyType.equals("RIGID_BODY")) { if (restore) { bodyType(currBodyType); } else { // suspend body.setCollisionFlags(body.getCollisionFlags() | CollisionFlags.KINEMATIC_OBJECT); } } }
public void ghostNoChildren(boolean ghost) { int flags = body.getCollisionFlags(); int noContact = CollisionFlags.NO_CONTACT_RESPONSE; if (ghost) flags |= noContact; else flags &= ~noContact; body.setCollisionFlags(flags); }
public void setServerElementStraf(ServerElement element, Float straf) { // log.debug("accel"); synchronized (directionVector) { setRightDirectionVector(element); directionVector.scale(straf); RigidBody rb = elementToRigidBody.get(element); rb.applyCentralForce(directionVector); // rb.setLinearVelocity(directionVector); } }
@Override public Element persist(Document doc, Element widgetNode, Widget widget) { CylinderWidget cylinder = (CylinderWidget) widget; RigidBody cylinderBody = cylinder.getRigidBody(); widgetNode.appendChild( persistParam( doc, "location", v3fToString(cylinderBody.getCenterOfMassPosition(new Vector3f())))); widgetNode.appendChild( persistParam( doc, "orientation", v3fToString( RenderableBase.toAngles( cylinderBody.getWorldTransform(new Transform()).getRotation(new Quat4f()))))); widgetNode.appendChild( persistParam( doc, "linearVeloctiy", v3fToString(cylinderBody.getLinearVelocity(new Vector3f())))); widgetNode.appendChild( persistParam( doc, "angularVelocity", v3fToString(cylinderBody.getAngularVelocity(new Vector3f())))); widgetNode.appendChild(persistParam(doc, "radius", "" + cylinder.getRadius())); widgetNode.appendChild(persistParam(doc, "height", "" + cylinder.getHeight())); widgetNode.appendChild(persistParam(doc, "mass", "" + (1f / cylinderBody.getInvMass()))); widgetNode.appendChild(persistParam(doc, "restitution", "" + cylinderBody.getRestitution())); widgetNode.appendChild(persistParam(doc, "friction", "" + cylinderBody.getFriction())); return widgetNode; }
public Vector3f velocityLocal() { Vector3f v = new Vector3f(); body.getLinearVelocity(v); Matrix3f invOri = orientation(); invOri.invert(); return invOri.mult(v); }
public void update(float deltaTime) { rigidBody.getMotionState().getWorldTransform(trans); this.getPosition().set(trans.origin.x, trans.origin.y, trans.origin.z); // Quat4f rotate = trans.getRotation(new Quat4f()); // float[] rotation = new float[] { 0, 0, 0, 0 }; // rotation = GPTransLation.translateQuatToAXYZ(rotate); // this.setRotation(rotation); }
/** * @param restitution反弹系数 * @param friction摩擦力系数 * @param mass */ public void init(float restitution, float friction, float mass) { this.restitution = restitution; this.friction = friction; this.mass = mass; intertia = new javax.vecmath.Vector3f(); RigidBodyConstructionInfo info; if (mass == 0) { info = new RigidBodyConstructionInfo(this.mass, state, shape); } else { shape.calculateLocalInertia(mass, intertia); info = new RigidBodyConstructionInfo(this.mass, state, shape, intertia); } rigidBody = new RigidBody(info); rigidBody.setFriction(friction); rigidBody.setRestitution(restitution); world.addRigidBody(rigidBody); }
public void setServerElementForce(ServerElement element) { // log.debug("accel"); synchronized (directionVector) { RigidBody rb = elementToRigidBody.get(element); Vector3f velocity = new Vector3f(); rb.getLinearVelocity(velocity); velocity.scale(-1f); rb.applyCentralForce(velocity); Vector3f angularVelocity = new Vector3f(); rb.getAngularVelocity(angularVelocity); angularVelocity.scale(-0.5f); rb.applyTorque(angularVelocity); // rb.setLinearVelocity(directionVector); } }
public void parent(GameObject p, boolean compound) { CompoundShape compShapeOld = null; if (parent != null) { parent.children.remove(this); if (compound) { compShapeOld = parent.compoundShape(); if (compShapeOld != null) { scene.world.removeRigidBody(parent.body); compShapeOld.removeChildShape(body.getCollisionShape()); scene.world.addRigidBody(parent.body); } } } else if (p == null) { return; } parent = p; if (parent != null) { parent.children.add(this); updateLocalTransform(); updateLocalScale(); if (compound) { CompoundShape compShape = parent.compoundShape(); if (compShape != null) { scene.world.removeRigidBody(body); compShape.addChildShape(new Transform(localTransform), body.getCollisionShape()); } } else { dynamics(false); } } else if (currBodyType.equals("STATIC") || currBodyType.equals("SENSOR")) { if (compound && compShapeOld != null) scene.world.addRigidBody(body); } else { dynamics(true); } }
private void updateRigidBodys() { for (RigidBody rb : rigidBodies) { ServerElement element = rigidBodyToServerElement.get(rb); if (rb != null && rb.getMotionState() != null) { if (element.isUpdatedByUser()) { /*rb.getMotionState().getWorldTransform(tmpTrans); tmpTrans.origin.x=element.getTransform().origin.x; tmpTrans.origin.y=element.getTransform().origin.y; tmpTrans.origin.z=element.getTransform().origin.z; */ rb.getMotionState().setWorldTransform(element.getTransform()); rb.setMotionState(rb.getMotionState()); element.resetUpdatedByUser(); } } } }
public void scale(float x, float y, float z, boolean updateLocal) { activate(); // Set unit scale Matrix4 t = modelInstance.transform; Matrix4 mat_scale = new Matrix4(); Vector3 s = new Vector3(); t.getScale(s); mat_scale.scl(1 / s.x, 1 / s.y, 1 / s.z); t.mul(mat_scale); // Set target scale mat_scale.idt(); mat_scale.scl(x, y, z); t.mul(mat_scale); // Relevant bullet body update CollisionShape cs = body.getCollisionShape(); cs.setLocalScaling(new Vector3f(x, y, z)); if (body.isInWorld() && body.isStaticOrKinematicObject()) scene.world.updateSingleAabb(body); // Child propagation Vector3f ps = scale(); Matrix4f pt = transform(); Matrix4f ct = new Matrix4f(); Matrix4f ms = new Matrix4f(); ms.setIdentity(); ms.m00 = ps.x; ms.m11 = ps.y; ms.m22 = ps.z; pt.mul(ms); for (GameObject c : children) { c.scale(scale().mul(c.localScale), false); ct.mul(pt, c.localTransform); c.transform(ct, false); } if (parent != null && updateLocal) { updateLocalScale(); } }
RigidBody createBody( float mass, Vector3f position, CollisionShape shape, Float initialVelocity, Matrix3f orientation) { // Create Dynamic Objects Transform startTransform = new Transform(); startTransform.setIdentity(); // rigidbody is dynamic if and only if mass is non zero, // otherwise static boolean isDynamic = (mass != 0f); Vector3f localInertia = new Vector3f(0, 0, 0); if (isDynamic) { shape.calculateLocalInertia(mass, localInertia); } if (orientation != null) { startTransform.set(orientation); } startTransform.origin.set(position); // using motionstate is recommended, it provides // interpolation capabilities, and only synchronizes // 'active' objects DefaultMotionState myMotionState = new DefaultMotionState(startTransform); RigidBodyConstructionInfo rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, shape, localInertia); RigidBody rb = new RigidBody(rbInfo); rb.setFriction(0.4f); // rb.setDamping(0.7f, 0.7f); if (initialVelocity != 0f && orientation != null) { synchronized (initialVelocityVector) { initialVelocityVector.set(0f, 0f, initialVelocity); orientation.transform(initialVelocityVector); rb.setLinearVelocity(initialVelocityVector); } } return rb; }
public boolean insideFrustum() { Vector3f min = new Vector3f(); Vector3f max = new Vector3f(); body.getAabb(min, max); Vector3f dimHalved = max.minus(min).mul(0.5f); Vector3f center; if (origin.length() == 0 || json.get("physics").get("bounds_type").asString().equals("CONVEX_HULL")) center = min.plus(dimHalved); else center = min.plus(dimHalved).plus(orientation().mult(origin).mul(scale())); return scene.cam.frustum.boundsInFrustum( center.x, center.y, center.z, dimHalved.x, dimHalved.y, dimHalved.z); }
public void addDynamicServerElement(ServerElement elem, Float initialVelocity) { RigidBody rb = createBody( elem.getMass(), elem.getPosition(), getCollisionShape(elem.getSize()), initialVelocity, elem.getOriantation()); dynamicsWorld.addRigidBody(rb); rigidBodyToServerElement.put(rb, elem); elementToRigidBody.put(elem, rb); rigidBodies.add(rb); // dynamicServerElements.put(elem.getId(),elem); if (elem instanceof ServerPlayer) { ServerPlayer p = (ServerPlayer) elem; players.add(p); rb.setAngularFactor(0.3f); } if (elem instanceof ServerBullet) { rb.setGravity(new Vector3f(0, -0.2f, 0)); } }
public void bodyType(String s) { int flags = body.getCollisionFlags(); if (body.isInWorld()) scene.world.removeRigidBody(body); if (s.equals("NO_COLLISION")) { for (GameObject g : touchingObjects) g.activate(); flags &= ~CollisionFlags.KINEMATIC_OBJECT; } else { if (s.equals("STATIC")) { flags |= CollisionFlags.KINEMATIC_OBJECT; } else if (s.equals("SENSOR")) { flags |= CollisionFlags.KINEMATIC_OBJECT; flags |= CollisionFlags.NO_CONTACT_RESPONSE; } else { // NO_COLLISION -> DYNAMIC or RIGID_BODY hack if (currBodyType.equals("NO_COLLISION")) { body.clearForces(); body.setLinearVelocity(new Vector3f()); } // kinematic initialization hack if (mass() == Float.POSITIVE_INFINITY) { mass(1); // Blender default flags &= ~CollisionFlags.KINEMATIC_OBJECT; body.setCollisionFlags(flags); } flags &= ~CollisionFlags.KINEMATIC_OBJECT; if (s.equals("DYNAMIC")) { body.setAngularVelocity(new Vector3f()); body.setAngularFactor(0); } else if (s.equals("RIGID_BODY")) { body.setAngularFactor(1); } else { throw new RuntimeException(s + " is no valid bodyType name."); } } scene.world.addRigidBody(body); activate(); } body.setCollisionFlags(flags); currBodyType = s; }
public Matrix4f transform() { Transform t = new Transform(); body.getWorldTransform(t); Vector3f v = new Vector3f(); for (int i = 0; i < 3; ++i) { t.basis.getColumn(i, v); v.normalize(); t.basis.setColumn(i, v); } Matrix4f m = new Matrix4f(); t.getMatrix(m); return m; }
public void drawSelf(float angle, float x, float y, float z) { // 制定使用某套shader程序 MatrixState.pushMatrix(); MySurfaceView.init = false; Transform trans = body.getMotionState().getWorldTransform(new Transform()); MatrixState.translate(trans.origin.x, trans.origin.y, trans.origin.z); Quat4f ro = trans.getRotation(new Quat4f()); if (ro.x != 0 || ro.y != 0 || ro.z != 0) { float[] fa = SYSUtil.fromSYStoAXYZ(ro); if (isNumber(fa[0] + "") && isNumber(fa[1] + "") && isNumber(fa[2] + "")) { MatrixState.rotate(fa[0], fa[1], fa[2], fa[3]); } } GLES20.glUseProgram(mProgram); MatrixState.rotate(angle, x, y, z); // 将最终变换矩阵传入shader程序 GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, MatrixState.getFinalMatrix(), 0); // 将位置、旋转变换矩阵传入着色器程序 GLES20.glUniformMatrix4fv(muMMatrixHandle, 1, false, MatrixState.currMatrix, 0); // 将光源位置传入着色器程序 GLES20.glUniform3fv(maLightLocationHandle, 1, MatrixState.lightPositionFBRed); // 将摄像机位置传入着色器程序 GLES20.glUniform3fv(maCameraHandle, 1, MatrixState.cameraFB); // 为画笔指定顶点位置数据 GLES20.glVertexAttribPointer(maPositionHandle, 3, GLES20.GL_FLOAT, false, 3 * 4, mVertexBuffer); // 为画笔指定顶点法向量数据 GLES20.glVertexAttribPointer(maNormalHandle, 4, GLES20.GL_FLOAT, false, 3 * 4, mNormalBuffer); // 允许顶点位置数据数组 GLES20.glEnableVertexAttribArray(maPositionHandle); GLES20.glEnableVertexAttribArray(maNormalHandle); // 绘制三角形 GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vCount); MatrixState.popMatrix(); }
public void addObjectsToCollisionDomain() { Iterator<Entry<MTComponent, ArrayList<MTTriangleMesh>>> groupIter = collisionGroups.entrySet().iterator(); int collidesWith = 0; while (groupIter.hasNext()) { collidesWith = ~groupId; Entry<MTComponent, ArrayList<MTTriangleMesh>> element = groupIter.next(); // CollisionShape shape = createMeshShapeFromMTMeshTriangle(element.getValue()); Iterator<MTTriangleMesh> iter = element.getValue().iterator(); while (iter.hasNext()) { MTComponent comp = iter.next(); CollisionShape shape = createMeshShapeFromMTMeshTriangle((MTTriangleMesh) comp); /* Transform startTransform = new Transform(); startTransform.setIdentity(); Vector3f vec = new Vector3f(); Vector3D translate = currentMesh.getCenterPointRelativeToParent(); vec.x = translate.x; vec.y = translate.y; vec.z = translate.z; startTransform.origin.set(vec);*/ Transform startTransform = new Transform(); startTransform.setIdentity(); Matrix mat = element.getKey().getGlobalMatrix(); Vector3f vec = new Vector3f(0.0f, 0.0f, 0.0f); vec.x = mat.m03; vec.y = mat.m13; vec.z = mat.m23; // startTransform.transform(vec); // Matrix4f mat = CollisionManager.convertMT4JMatrixToMatrix4f(mesh.get); // startTransform.set(mat); // startTransform.origin.set(vec); // mat4f.m03 = mat4f.m03 + vec.x; // mat4f.m13 = mat4f.m13 + vec.y; // mat4f.m23 = mat4f.m23 + vec.z; // mat4f.setTranslation(vec); startTransform.origin.set(vec); Vector3f scale = new Vector3f(); // get scale value of global matrix Vector3D xVec = new Vector3D(mat.m00, mat.m01, mat.m02); Vector3D yVec = new Vector3D(mat.m10, mat.m11, mat.m12); Vector3D zVec = new Vector3D(mat.m20, mat.m21, mat.m22); scale.x = xVec.length(); scale.y = yVec.length(); scale.z = zVec.length(); float[] scaleVals = new float[3]; scale.get(scaleVals); for (int i = 0; i < 3; i++) // get rotation value by extracting scalation { try { float[] colvals = mat.getRow(i); for (int j = 0; j < 3; j++) { colvals[j] = colvals[j] / scaleVals[i]; } startTransform.basis.setRow(i, colvals); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } // startTransform.set(mat4f); float mass = 5f; // fake mass value only needed correctly if used with dynamic engine shape.setLocalScaling(scale); GImpactMeshShape sh = (GImpactMeshShape) shape; sh.updateBound(); RigidBody body = localCreateRigidBody(mass, startTransform, shape); // get Center Of Mass of Triangle Mesh and write it to MTTriangleMesh Vector3f vecCOM = new Vector3f(); body.getCenterOfMassPosition(vecCOM); Vector3D vecComMT4J = new Vector3D(vecCOM.x, vecCOM.y, vecCOM.z); // mesh.setCenterOfMass(vecComMT4J); // mesh.setMass(100.0f); // add Object to Collision World collisionWorld.addCollisionObject(body, groupId, (short) collidesWith); colObjectToComponent.put(body, comp); addCollisionObjectToGroup( comp.getParent(), body); // save association between collision objects and groups } groupId = (short) (groupId << 1); // shift groupId so every group has a unique bit value } SimulatePreDrawAction calcDynamics = new SimulatePreDrawAction(collisionWorld, this, scene.getCanvas()); calcDynamics.setCurrentTimeStep(1.f / 1000000000000.0f); scene.registerPreDrawAction(calcDynamics); }
public void deactivate() { body.forceActivationState(2); }
public boolean ghost() { int noContact = body.getCollisionFlags() & CollisionFlags.NO_CONTACT_RESPONSE; return noContact != 0 ? true : false; }
public void activate() { if (dynamics()) body.activate(); }
public Vector3f scale() { Vector3f s = new Vector3f(); CollisionShape cs = body.getCollisionShape(); cs.getLocalScaling(s); return s; }
public void replaceModel(String modelName, boolean updateVisual, boolean updatePhysics) { if (modelName.equals(modelInstance.model.meshParts.get(0).id)) return; Model model = null; JsonValue mOrigin = null; JsonValue mDimNoScale = null; for (Scene sce : Bdx.scenes) { if (sce.models.containsKey(modelName)) { model = sce.models.get(modelName); mOrigin = sce.json.get("origins").get(modelName); mDimNoScale = sce.json.get("dimensions").get(modelName); break; } } if (model == null) { throw new RuntimeException("No model found with name: '" + modelName + "'"); } origin = mOrigin == null ? new Vector3f() : new Vector3f(mOrigin.asFloatArray()); dimensionsNoScale = mDimNoScale == null ? new Vector3f(1, 1, 1) : new Vector3f(mDimNoScale.asFloatArray()); Matrix4 trans = modelInstance.transform; if (updateVisual) { ModelInstance mi = new ModelInstance(model); mi.transform.set(trans); modelInstance = mi; } if (updatePhysics) { GameObject compParent = parent != null && parent.body.getCollisionShape().isCompound() ? parent : null; boolean isCompChild = compParent != null && !(currBodyType.equals("NO_COLLISION") || currBodyType.equals("SENSOR")); if (isCompChild) { parent(null); } Matrix4f transform = transform(); Vector3f scale = scale(); String boundsType = json.get("physics").get("bounds_type").asString(); float margin = json.get("physics").get("margin").asFloat(); boolean compound = json.get("physics").get("compound").asBoolean(); body.setCollisionShape(Bullet.makeShape(model.meshes.first(), boundsType, margin, compound)); if (boundsType.equals("CONVEX_HULL")) { Transform startTransform = new Transform(); body.getMotionState().getWorldTransform(startTransform); Matrix4f originMatrix = new Matrix4f(); originMatrix.set(origin); Transform centerOfMassTransform = new Transform(); centerOfMassTransform.set(originMatrix); centerOfMassTransform.mul(startTransform); body.setCenterOfMassTransform(centerOfMassTransform); } transform(transform); scale(scale); if (body.isInWorld()) { scene.world.updateSingleAabb(body); } else { // update Aabb hack for when not in world scene.world.addRigidBody(body); scene.world.updateSingleAabb(body); scene.world.removeRigidBody(body); } if (isCompChild) { parent(compParent); } } }
public float mass() { return 1 / body.getInvMass(); }
public boolean dynamics() { return body.isInWorld() && !body.isKinematicObject(); }