Search in sources :

Example 81 with Quaternion

use of com.jme3.math.Quaternion in project jmonkeyengine by jMonkeyEngine.

the class TestBetterCharacter method simpleInitApp.

@Override
public void simpleInitApp() {
    //setup keyboard mapping
    setupKeys();
    // activate physics
    bulletAppState = new BulletAppState();
    stateManager.attach(bulletAppState);
    bulletAppState.setDebugEnabled(true);
    // init a physics test scene
    PhysicsTestHelper.createPhysicsTestWorldSoccer(rootNode, assetManager, bulletAppState.getPhysicsSpace());
    PhysicsTestHelper.createBallShooter(this, rootNode, bulletAppState.getPhysicsSpace());
    setupPlanet();
    // Create a node for the character model
    characterNode = new Node("character node");
    characterNode.setLocalTranslation(new Vector3f(4, 5, 2));
    // Add a character control to the node so we can add other things and
    // control the model rotation
    physicsCharacter = new BetterCharacterControl(0.3f, 2.5f, 8f);
    characterNode.addControl(physicsCharacter);
    getPhysicsSpace().add(physicsCharacter);
    // Load model, attach to character node
    Node model = (Node) assetManager.loadModel("Models/Jaime/Jaime.j3o");
    model.setLocalScale(1.50f);
    characterNode.attachChild(model);
    // Add character node to the rootNode
    rootNode.attachChild(characterNode);
    // Set forward camera node that follows the character, only used when
    // view is "locked"
    camNode = new CameraNode("CamNode", cam);
    camNode.setControlDir(ControlDirection.SpatialToCamera);
    camNode.setLocalTranslation(new Vector3f(0, 2, -6));
    Quaternion quat = new Quaternion();
    // These coordinates are local, the camNode is attached to the character node!
    quat.lookAt(Vector3f.UNIT_Z, Vector3f.UNIT_Y);
    camNode.setLocalRotation(quat);
    characterNode.attachChild(camNode);
    // Disable by default, can be enabled via keyboard shortcut
    camNode.setEnabled(false);
}
Also used : Quaternion(com.jme3.math.Quaternion) BulletAppState(com.jme3.bullet.BulletAppState) Node(com.jme3.scene.Node) CameraNode(com.jme3.scene.CameraNode) Vector3f(com.jme3.math.Vector3f) CameraNode(com.jme3.scene.CameraNode) BetterCharacterControl(com.jme3.bullet.control.BetterCharacterControl)

Example 82 with Quaternion

use of com.jme3.math.Quaternion in project jmonkeyengine by jMonkeyEngine.

the class TestHoveringTank method buildPlayer.

private void buildPlayer() {
    spaceCraft = assetManager.loadModel("Models/HoverTank/Tank2.mesh.xml");
    CollisionShape colShape = CollisionShapeFactory.createDynamicMeshShape(spaceCraft);
    spaceCraft.setShadowMode(ShadowMode.CastAndReceive);
    spaceCraft.setLocalTranslation(new Vector3f(-140, 50, -23));
    spaceCraft.setLocalRotation(new Quaternion(new float[] { 0, 0.01f, 0 }));
    hoverControl = new PhysicsHoverControl(colShape, 500);
    spaceCraft.addControl(hoverControl);
    rootNode.attachChild(spaceCraft);
    getPhysicsSpace().add(hoverControl);
    hoverControl.setCollisionGroup(PhysicsCollisionObject.COLLISION_GROUP_02);
    ChaseCamera chaseCam = new ChaseCamera(cam, inputManager);
    spaceCraft.addControl(chaseCam);
    flyCam.setEnabled(false);
}
Also used : BoxCollisionShape(com.jme3.bullet.collision.shapes.BoxCollisionShape) CollisionShape(com.jme3.bullet.collision.shapes.CollisionShape) ChaseCamera(com.jme3.input.ChaseCamera)

Example 83 with Quaternion

use of com.jme3.math.Quaternion in project jmonkeyengine by jMonkeyEngine.

the class SimulationNode method simulateSkeleton.

/**
     * Simulates the bone node.
     */
private void simulateSkeleton() {
    LOGGER.fine("Simulating skeleton.");
    Set<Long> alteredOmas = new HashSet<Long>();
    if (animations != null) {
        TempVars vars = TempVars.get();
        AnimChannel animChannel = animControl.createChannel();
        for (Animation animation : animations) {
            float[] animationTimeBoundaries = this.computeAnimationTimeBoundaries(animation);
            int maxFrame = (int) animationTimeBoundaries[0];
            float maxTime = animationTimeBoundaries[1];
            Map<Integer, VirtualTrack> tracks = new HashMap<Integer, VirtualTrack>();
            for (int frame = 0; frame < maxFrame; ++frame) {
                // this MUST be done here, otherwise setting next frame of animation will
                // lead to possible errors
                this.reset();
                // first set proper time for all bones in all the tracks ...
                for (Track track : animation.getTracks()) {
                    float time = ((BoneTrack) track).getTimes()[frame];
                    track.setTime(time, 1, animControl, animChannel, vars);
                    skeleton.updateWorldVectors();
                }
                // ... and then apply constraints from the root bone to the last child ...
                Set<Long> applied = new HashSet<Long>();
                for (Bone rootBone : skeleton.getRoots()) {
                    // ignore the 0-indexed bone
                    if (skeleton.getBoneIndex(rootBone) > 0) {
                        this.applyConstraints(rootBone, alteredOmas, applied, frame, new Stack<Bone>());
                    }
                }
                // ... add virtual tracks if neccessary, for bones that were altered but had no tracks before ...
                for (Long boneOMA : alteredOmas) {
                    BoneContext boneContext = blenderContext.getBoneContext(boneOMA);
                    int boneIndex = skeleton.getBoneIndex(boneContext.getBone());
                    if (!tracks.containsKey(boneIndex)) {
                        tracks.put(boneIndex, new VirtualTrack(boneContext.getBone().getName(), maxFrame, maxTime));
                    }
                }
                alteredOmas.clear();
                // ... and fill in another frame in the result track
                for (Entry<Integer, VirtualTrack> trackEntry : tracks.entrySet()) {
                    Bone bone = skeleton.getBone(trackEntry.getKey());
                    Transform startTransform = boneStartTransforms.get(bone);
                    // track contains differences between the frame position and bind positions of bones/spatials
                    Vector3f bonePositionDifference = bone.getLocalPosition().subtract(startTransform.getTranslation());
                    Quaternion boneRotationDifference = startTransform.getRotation().inverse().mult(bone.getLocalRotation()).normalizeLocal();
                    Vector3f boneScaleDifference = bone.getLocalScale().divide(startTransform.getScale());
                    trackEntry.getValue().setTransform(frame, new Transform(bonePositionDifference, boneRotationDifference, boneScaleDifference));
                }
            }
            for (Entry<Integer, VirtualTrack> trackEntry : tracks.entrySet()) {
                Track newTrack = trackEntry.getValue().getAsBoneTrack(trackEntry.getKey());
                if (newTrack != null) {
                    boolean trackReplaced = false;
                    for (Track track : animation.getTracks()) {
                        if (((BoneTrack) track).getTargetBoneIndex() == trackEntry.getKey().intValue()) {
                            animation.removeTrack(track);
                            animation.addTrack(newTrack);
                            trackReplaced = true;
                            break;
                        }
                    }
                    if (!trackReplaced) {
                        animation.addTrack(newTrack);
                    }
                }
            }
        }
        vars.release();
        animControl.clearChannels();
        this.reset();
    }
}
Also used : HashMap(java.util.HashMap) Quaternion(com.jme3.math.Quaternion) AnimChannel(com.jme3.animation.AnimChannel) TempVars(com.jme3.util.TempVars) BoneContext(com.jme3.scene.plugins.blender.animations.BoneContext) Vector3f(com.jme3.math.Vector3f) Animation(com.jme3.animation.Animation) Bone(com.jme3.animation.Bone) Transform(com.jme3.math.Transform) SpatialTrack(com.jme3.animation.SpatialTrack) BoneTrack(com.jme3.animation.BoneTrack) Track(com.jme3.animation.Track) HashSet(java.util.HashSet)

Example 84 with Quaternion

use of com.jme3.math.Quaternion in project jmonkeyengine by jMonkeyEngine.

the class Ipo method calculateTrack.

/**
     * This method calculates the value of the curves as a bone track between
     * the specified frames.
     * 
     * @param targetIndex
     *            the index of the target for which the method calculates the
     *            tracks IMPORTANT! Aet to -1 (or any negative number) if you
     *            want to load spatial animation.
     * @param localTranslation
     *            the local translation of the object/bone that will be animated by
     *            the track
     * @param localRotation
     *            the local rotation of the object/bone that will be animated by
     *            the track
     * @param localScale
     *            the local scale of the object/bone that will be animated by
     *            the track
     * @param startFrame
     *            the first frame of tracks (inclusive)
     * @param stopFrame
     *            the last frame of the tracks (inclusive)
     * @param fps
     *            frame rate (frames per second)
     * @param spatialTrack
     *            this flag indicates if the track belongs to a spatial or to a
     *            bone; the difference is important because it appears that bones
     *            in blender have the same type of coordinate system (Y as UP)
     *            as jme while other features have different one (Z is UP)
     * @return bone track for the specified bone
     */
public Track calculateTrack(int targetIndex, BoneContext boneContext, Vector3f localTranslation, Quaternion localRotation, Vector3f localScale, int startFrame, int stopFrame, int fps, boolean spatialTrack) {
    if (calculatedTrack == null) {
        // preparing data for track
        int framesAmount = stopFrame - startFrame;
        float timeBetweenFrames = 1.0f / fps;
        float[] times = new float[framesAmount + 1];
        Vector3f[] translations = new Vector3f[framesAmount + 1];
        float[] translation = new float[3];
        Quaternion[] rotations = new Quaternion[framesAmount + 1];
        float[] quaternionRotation = new float[] { localRotation.getX(), localRotation.getY(), localRotation.getZ(), localRotation.getW() };
        float[] eulerRotation = localRotation.toAngles(null);
        Vector3f[] scales = new Vector3f[framesAmount + 1];
        float[] scale = new float[] { localScale.x, localScale.y, localScale.z };
        float degreeToRadiansFactor = 1;
        if (blenderVersion < 250) {
            // in blender earlier than 2.50 the values are stored in degrees
            // the values in blender are divided by 10, so we need to mult it here
            degreeToRadiansFactor *= FastMath.DEG_TO_RAD * 10;
        }
        int yIndex = 1, zIndex = 2;
        boolean swapAxes = spatialTrack && fixUpAxis;
        if (swapAxes) {
            yIndex = 2;
            zIndex = 1;
        }
        boolean eulerRotationUsed = false, queternionRotationUsed = false;
        // calculating track data
        for (int frame = startFrame; frame <= stopFrame; ++frame) {
            boolean translationSet = false;
            translation[0] = translation[1] = translation[2] = 0;
            int index = frame - startFrame;
            // start + (frame - 1) * timeBetweenFrames;
            times[index] = index * timeBetweenFrames;
            for (int j = 0; j < bezierCurves.length; ++j) {
                double value = bezierCurves[j].evaluate(frame, BezierCurve.Y_VALUE);
                switch(bezierCurves[j].getType()) {
                    // LOCATION
                    case AC_LOC_X:
                        translation[0] = (float) value;
                        translationSet = true;
                        break;
                    case AC_LOC_Y:
                        if (swapAxes && value != 0) {
                            value = -value;
                        }
                        translation[yIndex] = (float) value;
                        translationSet = true;
                        break;
                    case AC_LOC_Z:
                        translation[zIndex] = (float) value;
                        translationSet = true;
                        break;
                    // EULER ROTATION
                    case OB_ROT_X:
                        eulerRotationUsed = true;
                        eulerRotation[0] = (float) value * degreeToRadiansFactor;
                        break;
                    case OB_ROT_Y:
                        eulerRotationUsed = true;
                        if (swapAxes && value != 0) {
                            value = -value;
                        }
                        eulerRotation[yIndex] = (float) value * degreeToRadiansFactor;
                        break;
                    case OB_ROT_Z:
                        eulerRotationUsed = true;
                        eulerRotation[zIndex] = (float) value * degreeToRadiansFactor;
                        break;
                    // SIZE
                    case AC_SIZE_X:
                        scale[0] = (float) value;
                        break;
                    case AC_SIZE_Y:
                        scale[yIndex] = (float) value;
                        break;
                    case AC_SIZE_Z:
                        scale[zIndex] = (float) value;
                        break;
                    // QUATERNION ROTATION (used with bone animation)
                    case AC_QUAT_W:
                        queternionRotationUsed = true;
                        quaternionRotation[3] = (float) value;
                        break;
                    case AC_QUAT_X:
                        queternionRotationUsed = true;
                        quaternionRotation[0] = (float) value;
                        break;
                    case AC_QUAT_Y:
                        queternionRotationUsed = true;
                        if (swapAxes && value != 0) {
                            value = -value;
                        }
                        quaternionRotation[yIndex] = (float) value;
                        break;
                    case AC_QUAT_Z:
                        quaternionRotation[zIndex] = (float) value;
                        break;
                    default:
                        LOGGER.log(Level.WARNING, "Unknown ipo curve type: {0}.", bezierCurves[j].getType());
                }
            }
            if (translationSet) {
                translations[index] = localRotation.multLocal(new Vector3f(translation[0], translation[1], translation[2]));
            } else {
                translations[index] = new Vector3f();
            }
            if (boneContext != null) {
                if (boneContext.getBone().getParent() == null && boneContext.is(BoneContext.NO_LOCAL_LOCATION)) {
                    float temp = translations[index].z;
                    translations[index].z = -translations[index].y;
                    translations[index].y = temp;
                }
            }
            if (queternionRotationUsed) {
                rotations[index] = new Quaternion(quaternionRotation[0], quaternionRotation[1], quaternionRotation[2], quaternionRotation[3]);
            } else {
                rotations[index] = new Quaternion().fromAngles(eulerRotation);
            }
            scales[index] = new Vector3f(scale[0], scale[1], scale[2]);
        }
        if (spatialTrack) {
            calculatedTrack = new SpatialTrack(times, translations, rotations, scales);
        } else {
            calculatedTrack = new BoneTrack(targetIndex, times, translations, rotations, scales);
        }
        if (queternionRotationUsed && eulerRotationUsed) {
            LOGGER.warning("Animation uses both euler and quaternion tracks for rotations. Quaternion rotation is applied. Make sure that this is what you wanted!");
        }
    }
    return calculatedTrack;
}
Also used : SpatialTrack(com.jme3.animation.SpatialTrack) BoneTrack(com.jme3.animation.BoneTrack) Quaternion(com.jme3.math.Quaternion) Vector3f(com.jme3.math.Vector3f)

Example 85 with Quaternion

use of com.jme3.math.Quaternion in project jmonkeyengine by jMonkeyEngine.

the class ConstraintDefinitionRotLike method bake.

@Override
public void bake(Space ownerSpace, Space targetSpace, Transform targetTransform, float influence) {
    if (influence == 0 || targetTransform == null || !trackToBeChanged) {
        // no need to do anything
        return;
    }
    Transform ownerTransform = this.getOwnerTransform(ownerSpace);
    Quaternion ownerRotation = ownerTransform.getRotation();
    ownerAngles = ownerRotation.toAngles(ownerAngles);
    targetAngles = targetTransform.getRotation().toAngles(targetAngles);
    Quaternion startRotation = ownerRotation.clone();
    Quaternion offset = Quaternion.IDENTITY;
    if ((flag & ROTLIKE_OFFSET) != 0) {
        // we add the original rotation to
        // the copied rotation
        offset = startRotation;
    }
    if ((flag & ROTLIKE_X) != 0) {
        ownerAngles[0] = targetAngles[0];
        if ((flag & ROTLIKE_X_INVERT) != 0) {
            ownerAngles[0] = -ownerAngles[0];
        }
    }
    if ((flag & ROTLIKE_Y) != 0) {
        ownerAngles[1] = targetAngles[1];
        if ((flag & ROTLIKE_Y_INVERT) != 0) {
            ownerAngles[1] = -ownerAngles[1];
        }
    }
    if ((flag & ROTLIKE_Z) != 0) {
        ownerAngles[2] = targetAngles[2];
        if ((flag & ROTLIKE_Z_INVERT) != 0) {
            ownerAngles[2] = -ownerAngles[2];
        }
    }
    ownerRotation.fromAngles(ownerAngles).multLocal(offset);
    if (influence < 1.0f) {
    // startLocation.subtractLocal(ownerLocation).normalizeLocal().mult(influence);
    // ownerLocation.addLocal(startLocation);
    // TODO
    }
    this.applyOwnerTransform(ownerTransform, ownerSpace);
}
Also used : Quaternion(com.jme3.math.Quaternion) Transform(com.jme3.math.Transform)

Aggregations

Quaternion (com.jme3.math.Quaternion)115 Vector3f (com.jme3.math.Vector3f)100 Geometry (com.jme3.scene.Geometry)42 DirectionalLight (com.jme3.light.DirectionalLight)37 Material (com.jme3.material.Material)36 Node (com.jme3.scene.Node)30 FilterPostProcessor (com.jme3.post.FilterPostProcessor)26 Spatial (com.jme3.scene.Spatial)26 KeyTrigger (com.jme3.input.controls.KeyTrigger)22 Box (com.jme3.scene.shape.Box)21 TempVars (com.jme3.util.TempVars)16 ActionListener (com.jme3.input.controls.ActionListener)15 ColorRGBA (com.jme3.math.ColorRGBA)15 Quad (com.jme3.scene.shape.Quad)15 AmbientLight (com.jme3.light.AmbientLight)14 Sphere (com.jme3.scene.shape.Sphere)11 Bone (com.jme3.animation.Bone)9 PointLight (com.jme3.light.PointLight)8 AnimControl (com.jme3.animation.AnimControl)7 SpotLight (com.jme3.light.SpotLight)7