com.jme3.animation.Bone Java Examples

The following examples show how to use com.jme3.animation.Bone. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SkeletonInterBoneWire.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Creates buffers for points. Each line has POINT_AMOUNT of points.
 * @param skeleton
 *            the skeleton that will be showed
 * @param boneLengths
 *            the lengths of the bones
 */
public SkeletonInterBoneWire(Skeleton skeleton, Map<Integer, Float> boneLengths) {
    this.skeleton = skeleton;

    for (Bone bone : skeleton.getRoots()) {
        this.countConnections(bone);
    }

    this.setMode(Mode.Points);
    this.boneLengths = boneLengths;

    VertexBuffer pb = new VertexBuffer(Type.Position);
    FloatBuffer fpb = BufferUtils.createFloatBuffer(POINT_AMOUNT * connectionsAmount * 3);
    pb.setupData(Usage.Stream, 3, Format.Float, fpb);
    this.setBuffer(pb);

    this.updateCounts();
}
 
Example #2
Source File: RagdollUtils.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Updates a bone position and rotation.
 * if the child bones are not in the bone list this means, they are not associated with a physic shape.
 * So they have to be updated
 * @param bone the bone
 * @param pos the position
 * @param rot the rotation
 */
public static void setTransform(Bone bone, Vector3f pos, Quaternion rot, boolean restoreBoneControl, Set<String> boneList) {
    //we ensure that we have the control
    if (restoreBoneControl) {
        bone.setUserControl(true);
    }
    //we set te user transforms of the bone
    bone.setUserTransformsWorld(pos, rot);
    for (Bone childBone : bone.getChildren()) {
        //each child bone that is not in the list is updated
        if (!boneList.contains(childBone.getName())) {
            Transform t = childBone.getCombinedTransform(pos, rot);
            setTransform(childBone, t.getTranslation(), t.getRotation(), restoreBoneControl, boneList);
        }
    }
    //we give back the control to the keyframed animation
    if (restoreBoneControl) {
        bone.setUserControl(false);
    }
}
 
Example #3
Source File: KinematicRagdollControl.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void scanSpatial(Spatial model) {
    AnimControl animControl = model.getControl(AnimControl.class);
    Map<Integer, List<Float>> pointsMap = null;
    if (weightThreshold == -1.0f) {
        pointsMap = RagdollUtils.buildPointMap(model);
    }

    skeleton = animControl.getSkeleton();
    skeleton.resetAndUpdate();
    for (int i = 0; i < skeleton.getRoots().length; i++) {
        Bone childBone = skeleton.getRoots()[i];
        if (childBone.getParent() == null) {
            logger.log(Level.INFO, "Found root bone in skeleton {0}", skeleton);
            baseRigidBody = new PhysicsRigidBody(new BoxCollisionShape(Vector3f.UNIT_XYZ.mult(0.1f)), 1);
            baseRigidBody.setKinematic(mode == Mode.Kinetmatic);
            boneRecursion(model, childBone, baseRigidBody, 1, pointsMap);
        }
    }
}
 
Example #4
Source File: ModelPerformer.java    From OpenRTS with MIT License 6 votes vote down vote up
private void orientTurret(ModelActor actor) {
	for (Turret t : ((Unit) actor.getComp()).getTurrets()) {
		Bone turretBone = actor.getViewElements().spatial.getControl(AnimControl.class).getSkeleton().getBone(t.boneName);
		if (turretBone == null) {
			throw new RuntimeException("Can't find the bone " + t.boneName + " for turret.");
		}

		//			Vector3f axis;
		//			switch (t.boneAxis){
		//			case "X" : axis = Vector3f.UNIT_X; break;
		//			case "Y" : axis = Vector3f.UNIT_Y; break;
		//			case "Z" : axis = Vector3f.UNIT_Z; break;
		//			default : throw new IllegalArgumentException("Wrong bone axis for "+((Unit)actor.getComp()).builderID+" : "+t.boneAxis);
		//			}
		//			Quaternion r = new Quaternion().fromAngleAxis((float) t.yaw, axis);
		Quaternion r = new Quaternion().fromAngleAxis((float) t.yaw, Vector3f.UNIT_Y);
		turretBone.setUserControl(true);
		turretBone.setUserTransforms(Vector3f.ZERO, r, Vector3f.UNIT_XYZ);
	}
}
 
Example #5
Source File: KinematicRagdollControl.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Enable or disable the ragdoll behaviour.
 * if ragdollEnabled is true, the character motion will only be powerd by physics
 * else, the characted will be animated by the keyframe animation, 
 * but will be able to physically interact with its physic environnement
 * @param ragdollEnabled 
 */
protected void setMode(Mode mode) {
    this.mode = mode;
    AnimControl animControl = targetModel.getControl(AnimControl.class);
    animControl.setEnabled(mode == Mode.Kinetmatic);

    baseRigidBody.setKinematic(mode == Mode.Kinetmatic);
    TempVars vars = TempVars.get();
    
    for (PhysicsBoneLink link : boneLinks.values()) {
        link.rigidBody.setKinematic(mode == Mode.Kinetmatic);
        if (mode == Mode.Ragdoll) {
            Quaternion tmpRot1 = vars.quat1;
            Vector3f position = vars.vect1;
            //making sure that the ragdoll is at the correct place.
            matchPhysicObjectToBone(link, position, tmpRot1);
        }

    }
    vars.release();

    for (Bone bone : skeleton.getRoots()) {
        RagdollUtils.setUserControl(bone, mode == Mode.Ragdoll);
    }
}
 
Example #6
Source File: SkeletonWire.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * The method updates the geometry according to the poitions of the bones.
 */
public void updateGeometry() {
    VertexBuffer vb = this.getBuffer(Type.Position);
    FloatBuffer posBuf = this.getFloatBuffer(Type.Position);
    posBuf.clear();
    for (int i = 0; i < skeleton.getBoneCount(); ++i) {
        Bone bone = skeleton.getBone(i);
        Vector3f head = bone.getModelSpacePosition();

        posBuf.put(head.getX()).put(head.getY()).put(head.getZ());
        if (boneLengths != null) {
            Vector3f tail = head.add(bone.getModelSpaceRotation().mult(Vector3f.UNIT_Y.mult(boneLengths.get(i))));
            posBuf.put(tail.getX()).put(tail.getY()).put(tail.getZ());
        }
    }
    posBuf.flip();
    vb.updateData(posBuf);

    this.updateBound();
}
 
Example #7
Source File: KinematicRagdollControl.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Enable or disable the ragdoll behaviour.
 * if ragdollEnabled is true, the character motion will only be powerd by physics
 * else, the characted will be animated by the keyframe animation, 
 * but will be able to physically interact with its physic environnement
 * @param ragdollEnabled 
 */
protected void setMode(Mode mode) {
    this.mode = mode;
    AnimControl animControl = targetModel.getControl(AnimControl.class);
    animControl.setEnabled(mode == Mode.Kinetmatic);

    baseRigidBody.setKinematic(mode == Mode.Kinetmatic);
    TempVars vars = TempVars.get();
    
    for (PhysicsBoneLink link : boneLinks.values()) {
        link.rigidBody.setKinematic(mode == Mode.Kinetmatic);
        if (mode == Mode.Ragdoll) {
            Quaternion tmpRot1 = vars.quat1;
            Vector3f position = vars.vect1;
            //making sure that the ragdoll is at the correct place.
            matchPhysicObjectToBone(link, position, tmpRot1);
        }

    }
    vars.release();

    for (Bone bone : skeleton.getRoots()) {
        RagdollUtils.setUserControl(bone, mode == Mode.Ragdoll);
    }
}
 
Example #8
Source File: SkeletonInterBoneWire.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * The method updates the geometry according to the poitions of the bones.
 */
public void updateGeometry() {
    VertexBuffer vb = this.getBuffer(Type.Position);
    FloatBuffer posBuf = this.getFloatBuffer(Type.Position);
    posBuf.clear();
    for (int i = 0; i < skeleton.getBoneCount(); ++i) {
        Bone bone = skeleton.getBone(i);
        Vector3f parentTail = bone.getModelSpacePosition().add(bone.getModelSpaceRotation().mult(Vector3f.UNIT_Y.mult(boneLengths.get(i))));

        for (Bone child : bone.getChildren()) {
            Vector3f childHead = child.getModelSpacePosition();
            Vector3f v = childHead.subtract(parentTail);
            float pointDelta = v.length() / POINT_AMOUNT;
            v.normalizeLocal().multLocal(pointDelta);
            Vector3f pointPosition = parentTail.clone();
            for (int j = 0; j < POINT_AMOUNT; ++j) {
                posBuf.put(pointPosition.getX()).put(pointPosition.getY()).put(pointPosition.getZ());
                pointPosition.addLocal(v);
            }
        }
    }
    posBuf.flip();
    vb.updateData(posBuf);

    this.updateBound();
}
 
Example #9
Source File: SkeletonPoints.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * The method updates the geometry according to the positions of the bones.
 */
public void updateGeometry() {
    VertexBuffer vb = this.getBuffer(Type.Position);
    FloatBuffer posBuf = this.getFloatBuffer(Type.Position);
    posBuf.clear();
    for (int i = 0; i < skeleton.getBoneCount(); ++i) {
        Bone bone = skeleton.getBone(i);
        Vector3f head = bone.getModelSpacePosition();

        posBuf.put(head.getX()).put(head.getY()).put(head.getZ());
        if (boneLengths != null) {
            Vector3f tail = head.add(bone.getModelSpaceRotation().mult(Vector3f.UNIT_Y.mult(boneLengths.get(i))));
            posBuf.put(tail.getX()).put(tail.getY()).put(tail.getZ());
        }
    }
    posBuf.flip();
    vb.updateData(posBuf);

    this.updateBound();
}
 
Example #10
Source File: BoneContext.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * This method builds the bone. It recursively builds the bone's children.
 * 
 * @param bones
 *            a list of bones where the newly created bone will be added
 * @param objectToArmatureMatrix
 *            object to armature transformation matrix
 * @param blenderContext
 *            the blender context
 * @return newly created bone
 */
public Bone buildBone(List<Bone> bones, Matrix4f objectToArmatureMatrix, BlenderContext blenderContext) {
    Long boneOMA = boneStructure.getOldMemoryAddress();
    bone = new Bone(boneName);
    bones.add(bone);
    blenderContext.addLoadedFeatures(boneOMA, boneName, boneStructure, bone);

    Vector3f poseLocation = restMatrix.toTranslationVector();
    Quaternion rotation = restMatrix.toRotationQuat().normalizeLocal();
    Vector3f scale = restMatrix.toScaleVector();
    if (parent == null) {
        Quaternion rotationQuaternion = objectToArmatureMatrix.toRotationQuat().normalizeLocal();
        scale.multLocal(objectToArmatureMatrix.toScaleVector());
        rotationQuaternion.multLocal(poseLocation.addLocal(objectToArmatureMatrix.toTranslationVector()));
        rotation.multLocal(rotationQuaternion);
    }

    bone.setBindTransforms(poseLocation, rotation, scale);
    for (BoneContext child : children) {
        bone.addChild(child.buildBone(bones, objectToArmatureMatrix, blenderContext));
    }

    return bone;
}
 
Example #11
Source File: KinematicRagdollControl.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void scanSpatial(Spatial model) {
    AnimControl animControl = model.getControl(AnimControl.class);
    Map<Integer, List<Float>> pointsMap = null;
    if (weightThreshold == -1.0f) {
        pointsMap = RagdollUtils.buildPointMap(model);
    }

    skeleton = animControl.getSkeleton();
    skeleton.resetAndUpdate();
    for (int i = 0; i < skeleton.getRoots().length; i++) {
        Bone childBone = skeleton.getRoots()[i];
        if (childBone.getParent() == null) {
            logger.log(Level.INFO, "Found root bone in skeleton {0}", skeleton);
            baseRigidBody = new PhysicsRigidBody(new BoxCollisionShape(Vector3f.UNIT_XYZ.mult(0.1f)), 1);
            baseRigidBody.setKinematic(mode == Mode.Kinetmatic);
            boneRecursion(model, childBone, baseRigidBody, 1, pointsMap);
        }
    }
}
 
Example #12
Source File: ArmatureHelper.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * This method retuns the bone tracks for animation for blender version 2.49
 * (and probably several lower versions too).
 * 
 * @param actionStructure
 *            the structure containing the tracks
 * @param blenderContext
 *            the blender context
 * @return a list of tracks for the specified animation
 * @throws BlenderFileException
 *             an exception is thrown when there are problems with the blend
 *             file
 */
private BoneTrack[] getTracks249(Structure actionStructure, Skeleton skeleton, BlenderContext blenderContext) throws BlenderFileException {
    LOGGER.log(Level.FINE, "Getting tracks!");
    IpoHelper ipoHelper = blenderContext.getHelper(IpoHelper.class);
    int fps = blenderContext.getBlenderKey().getFps();
    Structure chanbase = (Structure) actionStructure.getFieldValue("chanbase");
    List<Structure> actionChannels = chanbase.evaluateListBase(blenderContext);// bActionChannel
    List<BoneTrack> tracks = new ArrayList<BoneTrack>();
    for (Structure bActionChannel : actionChannels) {
        String name = bActionChannel.getFieldValue("name").toString();
        int boneIndex = this.getBoneIndex(skeleton, name);
        if (boneIndex >= 0) {
            Pointer p = (Pointer) bActionChannel.getFieldValue("ipo");
            if (!p.isNull()) {
                Structure ipoStructure = p.fetchData(blenderContext.getInputStream()).get(0);

                Bone bone = skeleton.getBone(boneIndex);
                Ipo ipo = ipoHelper.fromIpoStructure(ipoStructure, blenderContext);
                if (ipo != null) {
                    tracks.add((BoneTrack) ipo.calculateTrack(boneIndex, bone.getLocalRotation(), 0, ipo.getLastFrame(), fps, false));
                }
            }
        }
    }
    return tracks.toArray(new BoneTrack[tracks.size()]);
}
 
Example #13
Source File: RagdollUtils.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Updates a bone position and rotation. if the child bones are not in the
 * bone list this means, they are not associated with a physics shape. So
 * they have to be updated
 *
 * @param bone the bone
 * @param pos the position
 * @param rot the rotation
 * @param restoreBoneControl true &rarr; user-control flag should be set
 * @param boneList the names of all bones without collision shapes (not
 * null, unaffected)
 */
public static void setTransform(Bone bone, Vector3f pos, Quaternion rot, boolean restoreBoneControl, Set<String> boneList) {
    //we ensure that we have the control
    if (restoreBoneControl) {
        bone.setUserControl(true);
    }
    //we set te user transforms of the bone
    bone.setUserTransformsInModelSpace(pos, rot);
    for (Bone childBone : bone.getChildren()) {
        //each child bone that is not in the list is updated
        if (!boneList.contains(childBone.getName())) {
            Transform t = childBone.getCombinedTransform(pos, rot);
            setTransform(childBone, t.getTranslation(), t.getRotation(), restoreBoneControl, boneList);
        }
    }
    //we give back the control to the keyframed animation
    if (restoreBoneControl) {
        bone.setUserControl(false);
    }
}
 
Example #14
Source File: RagdollUtils.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Updates a bone position and rotation.
 * if the child bones are not in the bone list this means, they are not associated with a physic shape.
 * So they have to be updated
 * @param bone the bone
 * @param pos the position
 * @param rot the rotation
 */
public static void setTransform(Bone bone, Vector3f pos, Quaternion rot, boolean restoreBoneControl, Set<String> boneList) {
    //we ensure that we have the control
    if (restoreBoneControl) {
        bone.setUserControl(true);
    }
    //we set te user transforms of the bone
    bone.setUserTransformsWorld(pos, rot);
    for (Bone childBone : bone.getChildren()) {
        //each child bone that is not in the list is updated
        if (!boneList.contains(childBone.getName())) {
            Transform t = childBone.getCombinedTransform(pos, rot);
            setTransform(childBone, t.getTranslation(), t.getRotation(), restoreBoneControl, boneList);
        }
    }
    //we give back the control to the keyframed animation
    if (restoreBoneControl) {
        bone.setUserControl(false);
    }
}
 
Example #15
Source File: TestOgreComplexAnim.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void simpleUpdate(float tpf){
    Bone b = control.getSkeleton().getBone("spinehigh");
    Bone b2 = control.getSkeleton().getBone("uparm.left");
    
    angle += tpf * rate;        
    if (angle > FastMath.HALF_PI / 2f){
        angle = FastMath.HALF_PI / 2f;
        rate = -1;
    }else if (angle < -FastMath.HALF_PI / 2f){
        angle = -FastMath.HALF_PI / 2f;
        rate = 1;
    }

    Quaternion q = new Quaternion();
    q.fromAngles(0, angle, 0);

    b.setUserControl(true);
    b.setUserTransforms(Vector3f.ZERO, q, Vector3f.UNIT_XYZ);
    
    b2.setUserControl(true);
    b2.setUserTransforms(Vector3f.ZERO, Quaternion.IDENTITY, new Vector3f(1+angle,1+ angle, 1+angle));
  
  
}
 
Example #16
Source File: ConstraintDefinitionDistLimit.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void bake(Transform ownerTransform, Transform targetTransform, float influence) {
    if (this.getOwner() instanceof Bone && ((Bone) this.getOwner()).getParent() != null) {
        // distance limit does not work on bones who have parent
        return;
    }

    Vector3f v = ownerTransform.getTranslation().subtract(targetTransform.getTranslation());
    float currentDistance = v.length();

    switch (mode) {
        case LIMITDIST_INSIDE:
            if (currentDistance >= dist) {
                v.normalizeLocal();
                v.multLocal(dist + (currentDistance - dist) * (1.0f - influence));
                ownerTransform.getTranslation().set(v.addLocal(targetTransform.getTranslation()));
            }
            break;
        case LIMITDIST_ONSURFACE:
            if (currentDistance > dist) {
                v.normalizeLocal();
                v.multLocal(dist + (currentDistance - dist) * (1.0f - influence));
                ownerTransform.getTranslation().set(v.addLocal(targetTransform.getTranslation()));
            } else if (currentDistance < dist) {
                v.normalizeLocal().multLocal(dist * influence);
                ownerTransform.getTranslation().set(targetTransform.getTranslation().add(v));
            }
            break;
        case LIMITDIST_OUTSIDE:
            if (currentDistance <= dist) {
                v = targetTransform.getTranslation().subtract(ownerTransform.getTranslation()).normalizeLocal().multLocal(dist * influence);
                ownerTransform.getTranslation().set(targetTransform.getTranslation().add(v));
            }
            break;
        default:
            throw new IllegalStateException("Unknown distance limit constraint mode: " + mode);
    }
}
 
Example #17
Source File: AnimationBoneTrackTreeNode.java    From jmonkeybuilder with Apache License 2.0 5 votes vote down vote up
@NotNull
@Override
protected String computeName() {
    final BoneTrack boneTrack = getElement();
    final AnimControl control = notNull(getControl());
    final Skeleton skeleton = control.getSkeleton();
    final Bone bone = skeleton.getBone(boneTrack.getTargetBoneIndex());
    return "Bone track : " + bone.getName();
}
 
Example #18
Source File: KinematicRagdollControl.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Smoothly blend from Ragdoll mode to Kinematic mode
 * This is useful to blend ragdoll actual position to a keyframe animation for example
 * @param blendTime the blending time between ragdoll to anim.
 */
public void blendToKinematicMode(float blendTime) {
    if (mode == Mode.Kinetmatic) {
        return;
    }
    blendedControl = true;
    this.blendTime = blendTime;
    mode = Mode.Kinetmatic;
    AnimControl animControl = targetModel.getControl(AnimControl.class);
    animControl.setEnabled(true);


    TempVars vars = TempVars.get();        
    for (PhysicsBoneLink link : boneLinks.values()) {

        Vector3f p = link.rigidBody.getMotionState().getWorldLocation();
        Vector3f position = vars.vect1;

        targetModel.getWorldTransform().transformInverseVector(p, position);

        Quaternion q = link.rigidBody.getMotionState().getWorldRotationQuat();
        Quaternion q2 = vars.quat1;
        Quaternion q3 = vars.quat2;

        q2.set(q).multLocal(link.initalWorldRotation).normalizeLocal();
        q3.set(targetModel.getWorldRotation()).inverseLocal().mult(q2, q2);
        q2.normalizeLocal();
        link.startBlendingPos.set(position);
        link.startBlendingRot.set(q2);
        link.rigidBody.setKinematic(true);
    }
    vars.release();

    for (Bone bone : skeleton.getRoots()) {
        RagdollUtils.setUserControl(bone, false);
    }

    blendStart = 0;
}
 
Example #19
Source File: IKControl.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
void updateWorldVectors(Bone bone) {
//        pmdNode.getSkeleton().updateWorldVectors();
        bone.updateWorldVectors();
        final ArrayList<Bone> children = bone.getChildren();
        final int size = children.size();
        for(int i=0;i<size;i++) {
            Bone childBone = children.get(i);
            updateWorldVectors(childBone);
        }
    }
 
Example #20
Source File: ConstraintDefinitionLocLimit.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void bake(Transform ownerTransform, Transform targetTransform, float influence) {
    if (this.getOwner() instanceof Bone && ((Bone) this.getOwner()).getParent() != null) {
        // location limit does not work on bones who have parent
        return;
    }

    Vector3f translation = ownerTransform.getTranslation();

    if ((flag & LIMIT_XMIN) != 0 && translation.x < limits[0][0]) {
        translation.x -= (translation.x - limits[0][0]) * influence;
    }
    if ((flag & LIMIT_XMAX) != 0 && translation.x > limits[0][1]) {
        translation.x -= (translation.x - limits[0][1]) * influence;
    }
    if ((flag & LIMIT_YMIN) != 0 && translation.y < limits[1][0]) {
        translation.y -= (translation.y - limits[1][0]) * influence;
    }
    if ((flag & LIMIT_YMAX) != 0 && translation.y > limits[1][1]) {
        translation.y -= (translation.y - limits[1][1]) * influence;
    }
    if ((flag & LIMIT_ZMIN) != 0 && translation.z < limits[2][0]) {
        translation.z -= (translation.z - limits[2][0]) * influence;
    }
    if ((flag & LIMIT_ZMAX) != 0 && translation.z > limits[2][1]) {
        translation.z -= (translation.z - limits[2][1]) * influence;
    }
}
 
Example #21
Source File: BoneUtil.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void setBoneModelPos(Bone bone, Vector3f pos, Vector3f tmpV1, Matrix4f tmp1, Matrix3f tmp2) {
    Bone parentBone = bone.getParent();
    if (parentBone != null) {
        getModelToBoneMatrix(bone.getParent(), tmp1, tmp2);
        tmp1.mult(pos, tmpV1);
        bone.getLocalPosition().set(tmpV1);
    } else {
        bone.getLocalPosition().set(pos);
    }
}
 
Example #22
Source File: PhysicsControl.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
void initRigidBodyArray() {
    Skeleton skeleton = pmdNode.getSkeleton();
    PMDModel pmdModel = pmdNode.getPmdModel();
    rigidBodyArray = new PMDRigidBody[pmdModel.getRigidBodyList().getRigidBodyArray().length];
    for (int i = 0; i < pmdModel.getRigidBodyList().getRigidBodyArray().length; i++) {
        projectkyoto.mmd.file.PMDRigidBody fileRigidBody =
                pmdModel.getRigidBodyList().getRigidBodyArray()[i];
        Bone bone = skeleton.getBone(fileRigidBody.getRelBoneIndex());
        PMDRigidBody rb = createRigidBody(fileRigidBody, bone);
        rigidBodyArray[i] = rb;
    }
}
 
Example #23
Source File: KinematicRagdollControl.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Smoothly blend from Ragdoll mode to Kinematic mode
 * This is useful to blend ragdoll actual position to a keyframe animation for example
 * @param blendTime the blending time between ragdoll to anim.
 */
public void blendToKinematicMode(float blendTime) {
    if (mode == Mode.Kinetmatic) {
        return;
    }
    blendedControl = true;
    this.blendTime = blendTime;
    mode = Mode.Kinetmatic;
    AnimControl animControl = targetModel.getControl(AnimControl.class);
    animControl.setEnabled(true);


    TempVars vars = TempVars.get();        
    for (PhysicsBoneLink link : boneLinks.values()) {

        Vector3f p = link.rigidBody.getMotionState().getWorldLocation();
        Vector3f position = vars.vect1;

        targetModel.getWorldTransform().transformInverseVector(p, position);

        Quaternion q = link.rigidBody.getMotionState().getWorldRotationQuat();
        Quaternion q2 = vars.quat1;
        Quaternion q3 = vars.quat2;

        q2.set(q).multLocal(link.initalWorldRotation).normalizeLocal();
        q3.set(targetModel.getWorldRotation()).inverseLocal().mult(q2, q2);
        q2.normalizeLocal();
        link.startBlendingPos.set(position);
        link.startBlendingRot.set(q2);
        link.rigidBody.setKinematic(true);
    }
    vars.release();

    for (Bone bone : skeleton.getRoots()) {
        RagdollUtils.setUserControl(bone, false);
    }

    blendStart = 0;
}
 
Example #24
Source File: PMDPhysicsWorld.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void addPMDNode(PMDNode pmdNode) {
        Skeleton skeleton = pmdNode.getSkeleton();
        skeleton.updateWorldVectors();
        PMDModel pmdModel = pmdNode.getPmdModel();
        PMDRigidBody[] rigidBodyArray = new PMDRigidBody[pmdModel.getRigidBodyList().getRigidBodyArray().length];
        rigidBodyMap.put(pmdNode, rigidBodyArray);
        for (int i = 0; i < pmdModel.getRigidBodyList().getRigidBodyArray().length; i++) {
            projectkyoto.mmd.file.PMDRigidBody fileRigidBody =
                    pmdModel.getRigidBodyList().getRigidBodyArray()[i];
            Bone bone = null;
            if (fileRigidBody.getRelBoneIndex() != 0xffff) {
                bone = skeleton.getBone(fileRigidBody.getRelBoneIndex());
            }
            PMDRigidBody rb = createRigidBody(pmdNode, fileRigidBody, bone);
            rigidBodyArray[i] = rb;

//            btWorld.addRigidBody(rb, (short) (1 << fileRigidBody.getRigidBodyGroupIndex()),
//                    (short) fileRigidBody.getRigidBodyGroupTarget());
            rb.setCollisionGroup(1 << (fileRigidBody.getRigidBodyGroupIndex()));
//            if (fileRigidBody.getRigidBodyName().contains("スカート")) {
//                rb.setCollideWithGroups(1 << 7);
//            } else {
                rb.setCollideWithGroups(fileRigidBody.getRigidBodyGroupTarget());
//            }
//                  rb.setCollideWithGroups(0 );
            physicsSpace.addCollisionObject(rb);
        }
        SixDofJoint constArray[] = new SixDofJoint[pmdModel.getJointList().getJointCount()];
        constraintMap.put(pmdNode, constArray);
        for (int i = 0; i < constArray.length; i++) {
            SixDofJoint constraint = createConstraint(pmdNode,
                    rigidBodyArray, pmdModel.getJointList().getJointArray()[i]);
            constArray[i] = constraint;
            physicsSpace.add(constraint);
        }
        nodeRigidBodyArray = rigidBodyMap.values().toArray(new PMDRigidBody[rigidBodyMap.size()][]);
//        physicsSpace.update(1 / 60f, 1);
    }
 
Example #25
Source File: PMDRigidBody.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public PMDRigidBody(PMDNode pmdNode, Bone bone, int rigidBodyType, Vector3f pos, Quaternion rot, CollisionShape cs, float f) {
        super(cs, f);
        this.pmdNode = pmdNode;
        this.bone = bone;
        this.rigidBodyType = rigidBodyType;
        this.pos.set(pos);
        this.rot.set(rot);

        invPos.set(pos);
        invPos.negateLocal();
        invRot.set(rot);
        invRot.inverseLocal();
        invM.setTransform(pos, new Vector3f(1f, 1f, 1f), rot.toRotationMatrix());
        m.set(invM);
        invM.invertLocal();
        m2.loadIdentity();
        centerBone = pmdNode.getSkeleton().getBone("センター");
        if (bone == centerBone) {
            centerFlag = true;
        } else {
            centerFlag = false;
        }
//        if (bone != null) {
//            if (!isKinematic()) {
//                bone.setUseModelSpaceVectors(true);
//            }else {
//                bone.setUseModelSpaceVectors(false);
//            }
//        }
    }
 
Example #26
Source File: SimulationNode.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Resets the node's feature to its starting transformation.
 */
private void reset() {
    if (spatial != null) {
        spatial.setLocalTransform(spatialStartTransform);
        for (SimulationNode child : children) {
            child.reset();
        }
    } else if (skeleton != null) {
        for (Entry<Bone, Transform> entry : boneStartTransforms.entrySet()) {
            Transform t = entry.getValue();
            entry.getKey().setBindTransforms(t.getTranslation(), t.getRotation(), t.getScale());
        }
        skeleton.reset();
    }
}
 
Example #27
Source File: ArmatureHelper.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * This method retuns the bone tracks for animation for blender version 2.50
 * and higher.
 * 
 * @param actionStructure
 *            the structure containing the tracks
 * @param blenderContext
 *            the blender context
 * @return a list of tracks for the specified animation
 * @throws BlenderFileException
 *             an exception is thrown when there are problems with the blend
 *             file
 */
private BoneTrack[] getTracks250(Structure actionStructure, Skeleton skeleton, BlenderContext blenderContext) throws BlenderFileException {
    LOGGER.log(Level.FINE, "Getting tracks!");
    IpoHelper ipoHelper = blenderContext.getHelper(IpoHelper.class);
    int fps = blenderContext.getBlenderKey().getFps();
    Structure groups = (Structure) actionStructure.getFieldValue("groups");
    List<Structure> actionGroups = groups.evaluateListBase(blenderContext);// bActionGroup
    List<BoneTrack> tracks = new ArrayList<BoneTrack>();
    for (Structure actionGroup : actionGroups) {
        String name = actionGroup.getFieldValue("name").toString();
        int boneIndex = this.getBoneIndex(skeleton, name);
        if (boneIndex >= 0) {
            List<Structure> channels = ((Structure) actionGroup.getFieldValue("channels")).evaluateListBase(blenderContext);
            BezierCurve[] bezierCurves = new BezierCurve[channels.size()];
            int channelCounter = 0;
            for (Structure c : channels) {
                int type = ipoHelper.getCurveType(c, blenderContext);
                Pointer pBezTriple = (Pointer) c.getFieldValue("bezt");
                List<Structure> bezTriples = pBezTriple.fetchData(blenderContext.getInputStream());
                bezierCurves[channelCounter++] = new BezierCurve(type, bezTriples, 2);
            }

            Bone bone = skeleton.getBone(boneIndex);
            Ipo ipo = new Ipo(bezierCurves, fixUpAxis, blenderContext.getBlenderVersion());
            tracks.add((BoneTrack) ipo.calculateTrack(boneIndex, bone.getLocalRotation(), 0, ipo.getLastFrame(), fps, false));
        }
    }
    return tracks.toArray(new BoneTrack[tracks.size()]);
}
 
Example #28
Source File: BlenderContext.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Returns bone by given name.
 * 
 * @param name
 *            the name of the bone
 * @return found bone or null if none bone of a given name exists
 */
public BoneContext getBoneByName(String name) {
    for (Entry<Long, BoneContext> entry : boneContexts.entrySet()) {
        Bone bone = entry.getValue().getBone();
        if (bone != null && name.equals(bone.getName())) {
            return entry.getValue();
        }
    }
    return null;
}
 
Example #29
Source File: BlenderContext.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Returns bone context for the given bone.
 * 
 * @param bone
 *            the bone
 * @return the bone's bone context
 */
public BoneContext getBoneContext(Bone bone) {
    for (Entry<Long, BoneContext> entry : boneContexts.entrySet()) {
        if (entry.getValue().getBone().equals(bone)) {
            return entry.getValue();
        }
    }
    throw new IllegalStateException("Cannot find context for bone: " + bone);
}
 
Example #30
Source File: SkeletonWire.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Th method couns the connections between bones.
 * @param bone
 *            the bone where counting starts
 */
private void countConnections(Bone bone) {
    for (Bone child : bone.getChildren()) {
        numConnections++;
        this.countConnections(child);
    }
}