Search in sources :

Example 21 with Control

use of com.jme3.scene.control.Control in project jmonkeyengine by jMonkeyEngine.

the class AnimationHelper method applyAnimations.

/**
     * The method applies animations to the given node. The names of the animations should be the same as actions names in the blender file.
     * @param node
     *            the node to whom the animations will be applied
     * @param animationMatchMethod
     *            the way animation should be matched with node
     */
public void applyAnimations(Node node, AnimationMatchMethod animationMatchMethod) {
    List<BlenderAction> actions = this.getActions(node, animationMatchMethod);
    if (actions.size() > 0) {
        List<Animation> animations = new ArrayList<Animation>();
        for (BlenderAction action : actions) {
            SpatialTrack[] tracks = action.toTracks(node, blenderContext);
            if (tracks != null && tracks.length > 0) {
                Animation spatialAnimation = new Animation(action.getName(), action.getAnimationTime());
                spatialAnimation.setTracks(tracks);
                animations.add(spatialAnimation);
                blenderContext.addAnimation((Long) node.getUserData(ObjectHelper.OMA_MARKER), spatialAnimation);
            }
        }
        if (animations.size() > 0) {
            AnimControl control = new AnimControl();
            HashMap<String, Animation> anims = new HashMap<String, Animation>(animations.size());
            for (int i = 0; i < animations.size(); ++i) {
                Animation animation = animations.get(i);
                anims.put(animation.getName(), animation);
            }
            control.setAnimations(anims);
            node.addControl(control);
        }
    }
}
Also used : SpatialTrack(com.jme3.animation.SpatialTrack) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Animation(com.jme3.animation.Animation) AnimControl(com.jme3.animation.AnimControl)

Example 22 with Control

use of com.jme3.scene.control.Control in project jmonkeyengine by jMonkeyEngine.

the class AnimationHelper method applyAnimations.

/**
     * The method applies skeleton animations to the given node.
     * @param node
     *            the node where the animations will be applied
     * @param skeleton
     *            the skeleton of the node
     * @param animationMatchMethod
     *            the way animation should be matched with skeleton
     */
public void applyAnimations(Node node, Skeleton skeleton, AnimationMatchMethod animationMatchMethod) {
    node.addControl(new SkeletonControl(skeleton));
    blenderContext.setNodeForSkeleton(skeleton, node);
    List<BlenderAction> actions = this.getActions(skeleton, animationMatchMethod);
    if (actions.size() > 0) {
        List<Animation> animations = new ArrayList<Animation>();
        for (BlenderAction action : actions) {
            BoneTrack[] tracks = action.toTracks(skeleton, blenderContext);
            if (tracks != null && tracks.length > 0) {
                Animation boneAnimation = new Animation(action.getName(), action.getAnimationTime());
                boneAnimation.setTracks(tracks);
                animations.add(boneAnimation);
                Long animatedNodeOMA = ((Number) blenderContext.getMarkerValue(ObjectHelper.OMA_MARKER, node)).longValue();
                blenderContext.addAnimation(animatedNodeOMA, boneAnimation);
            }
        }
        if (animations.size() > 0) {
            AnimControl control = new AnimControl(skeleton);
            HashMap<String, Animation> anims = new HashMap<String, Animation>(animations.size());
            for (int i = 0; i < animations.size(); ++i) {
                Animation animation = animations.get(i);
                anims.put(animation.getName(), animation);
            }
            control.setAnimations(anims);
            node.addControl(control);
            // make sure that SkeletonControl is added AFTER the AnimControl
            SkeletonControl skeletonControl = node.getControl(SkeletonControl.class);
            if (skeletonControl != null) {
                node.removeControl(SkeletonControl.class);
                node.addControl(skeletonControl);
            }
        }
    }
}
Also used : BoneTrack(com.jme3.animation.BoneTrack) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) SkeletonControl(com.jme3.animation.SkeletonControl) AnimControl(com.jme3.animation.AnimControl) Animation(com.jme3.animation.Animation)

Example 23 with Control

use of com.jme3.scene.control.Control in project jmonkeyengine by jMonkeyEngine.

the class CurvesTemporalMesh method loadNurbSurface.

/**
     * This method loads the NURBS curve or surface.
     * @param nurb
     *            the NURBS data structure
     * @throws BlenderFileException
     *             an exception is thrown when problems with reading occur
     */
@SuppressWarnings("unchecked")
private void loadNurbSurface(Structure nurb, int materialIndex) throws BlenderFileException {
    // loading the knots
    List<Float>[] knots = new List[2];
    Pointer[] pKnots = new Pointer[] { (Pointer) nurb.getFieldValue("knotsu"), (Pointer) nurb.getFieldValue("knotsv") };
    for (int i = 0; i < knots.length; ++i) {
        if (pKnots[i].isNotNull()) {
            FileBlockHeader fileBlockHeader = blenderContext.getFileBlock(pKnots[i].getOldMemoryAddress());
            BlenderInputStream blenderInputStream = blenderContext.getInputStream();
            blenderInputStream.setPosition(fileBlockHeader.getBlockPosition());
            int knotsAmount = fileBlockHeader.getCount() * fileBlockHeader.getSize() / 4;
            knots[i] = new ArrayList<Float>(knotsAmount);
            for (int j = 0; j < knotsAmount; ++j) {
                knots[i].add(Float.valueOf(blenderInputStream.readFloat()));
            }
        }
    }
    // loading the flags and orders (basis functions degrees)
    int flag = ((Number) nurb.getFieldValue("flag")).intValue();
    boolean smooth = (flag & FLAG_SMOOTH) != 0;
    int flagU = ((Number) nurb.getFieldValue("flagu")).intValue();
    int flagV = ((Number) nurb.getFieldValue("flagv")).intValue();
    int orderU = ((Number) nurb.getFieldValue("orderu")).intValue();
    int orderV = ((Number) nurb.getFieldValue("orderv")).intValue();
    // loading control points and their weights
    int pntsU = ((Number) nurb.getFieldValue("pntsu")).intValue();
    int pntsV = ((Number) nurb.getFieldValue("pntsv")).intValue();
    List<Structure> bPoints = ((Pointer) nurb.getFieldValue("bp")).fetchData();
    List<List<Vector4f>> controlPoints = new ArrayList<List<Vector4f>>(pntsV);
    for (int i = 0; i < pntsV; ++i) {
        List<Vector4f> uControlPoints = new ArrayList<Vector4f>(pntsU);
        for (int j = 0; j < pntsU; ++j) {
            DynamicArray<Float> vec = (DynamicArray<Float>) bPoints.get(j + i * pntsU).getFieldValue("vec");
            if (blenderContext.getBlenderKey().isFixUpAxis()) {
                uControlPoints.add(new Vector4f(vec.get(0).floatValue(), vec.get(2).floatValue(), -vec.get(1).floatValue(), vec.get(3).floatValue()));
            } else {
                uControlPoints.add(new Vector4f(vec.get(0).floatValue(), vec.get(1).floatValue(), vec.get(2).floatValue(), vec.get(3).floatValue()));
            }
        }
        if ((flagU & 0x01) != 0) {
            for (int k = 0; k < orderU - 1; ++k) {
                uControlPoints.add(uControlPoints.get(k));
            }
        }
        controlPoints.add(uControlPoints);
    }
    if ((flagV & 0x01) != 0) {
        for (int k = 0; k < orderV - 1; ++k) {
            controlPoints.add(controlPoints.get(k));
        }
    }
    int originalVerticesAmount = vertices.size();
    int resolu = ((Number) nurb.getFieldValue("resolu")).intValue();
    if (knots[1] == null) {
        // creating the NURB curve
        Curve curve = new Curve(new Spline(controlPoints.get(0), knots[0]), resolu);
        FloatBuffer vertsBuffer = (FloatBuffer) curve.getBuffer(Type.Position).getData();
        beziers.add(new BezierLine(BufferUtils.getVector3Array(vertsBuffer), materialIndex, smooth, false));
    } else {
        // creating the NURB surface
        int resolv = ((Number) nurb.getFieldValue("resolv")).intValue();
        int uSegments = resolu * controlPoints.get(0).size() - 1;
        int vSegments = resolv * controlPoints.size() - 1;
        Surface nurbSurface = Surface.createNurbsSurface(controlPoints, knots, uSegments, vSegments, orderU, orderV, smooth);
        FloatBuffer vertsBuffer = (FloatBuffer) nurbSurface.getBuffer(Type.Position).getData();
        vertices.addAll(Arrays.asList(BufferUtils.getVector3Array(vertsBuffer)));
        FloatBuffer normalsBuffer = (FloatBuffer) nurbSurface.getBuffer(Type.Normal).getData();
        normals.addAll(Arrays.asList(BufferUtils.getVector3Array(normalsBuffer)));
        IndexBuffer indexBuffer = nurbSurface.getIndexBuffer();
        for (int i = 0; i < indexBuffer.size(); i += 3) {
            int index1 = indexBuffer.get(i) + originalVerticesAmount;
            int index2 = indexBuffer.get(i + 1) + originalVerticesAmount;
            int index3 = indexBuffer.get(i + 2) + originalVerticesAmount;
            faces.add(new Face(new Integer[] { index1, index2, index3 }, smooth, materialIndex, null, null, this));
        }
    }
}
Also used : ArrayList(java.util.ArrayList) Pointer(com.jme3.scene.plugins.blender.file.Pointer) FloatBuffer(java.nio.FloatBuffer) Spline(com.jme3.math.Spline) Surface(com.jme3.scene.shape.Surface) IndexBuffer(com.jme3.scene.mesh.IndexBuffer) Vector4f(com.jme3.math.Vector4f) ArrayList(java.util.ArrayList) List(java.util.List) BlenderInputStream(com.jme3.scene.plugins.blender.file.BlenderInputStream) Structure(com.jme3.scene.plugins.blender.file.Structure) Face(com.jme3.scene.plugins.blender.meshes.Face) FileBlockHeader(com.jme3.scene.plugins.blender.file.FileBlockHeader) Curve(com.jme3.scene.shape.Curve) DynamicArray(com.jme3.scene.plugins.blender.file.DynamicArray)

Example 24 with Control

use of com.jme3.scene.control.Control in project jmonkeyengine by jMonkeyEngine.

the class AndroidJoystickJoyInput14 method loadJoysticks.

public List<Joystick> loadJoysticks(int joyId, InputManager inputManager) {
    logger.log(Level.INFO, "loading Joystick devices");
    ArrayList<Joystick> joysticks = new ArrayList<Joystick>();
    joysticks.clear();
    joystickIndex.clear();
    ArrayList gameControllerDeviceIds = new ArrayList();
    int[] deviceIds = InputDevice.getDeviceIds();
    for (int deviceId : deviceIds) {
        InputDevice dev = InputDevice.getDevice(deviceId);
        int sources = dev.getSources();
        logger.log(Level.FINE, "deviceId[{0}] sources: {1}", new Object[] { deviceId, sources });
        // Verify that the device has gamepad buttons, control sticks, or both.
        if (((sources & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD) || ((sources & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK)) {
            // This device is a game controller. Store its device ID.
            if (!gameControllerDeviceIds.contains(deviceId)) {
                gameControllerDeviceIds.add(deviceId);
                logger.log(Level.FINE, "Attempting to create joystick for device: {0}", dev);
                // Create an AndroidJoystick and store the InputDevice so we
                // can later correspond the input from the InputDevice to the
                // appropriate jME Joystick event
                AndroidJoystick joystick = new AndroidJoystick(inputManager, joyInput, dev, joyId + joysticks.size(), dev.getName());
                joystickIndex.put(deviceId, joystick);
                joysticks.add(joystick);
                // Each analog input is reported as a MotionRange
                // The axis number corresponds to the type of axis
                // The AndroidJoystick.addAxis(MotionRange) converts the axis
                // type reported by Android into the jME Joystick axis
                List<MotionRange> motionRanges = dev.getMotionRanges();
                for (MotionRange motionRange : motionRanges) {
                    logger.log(Level.INFO, "motion range: {0}", motionRange.toString());
                    logger.log(Level.INFO, "axis: {0}", motionRange.getAxis());
                    JoystickAxis axis = joystick.addAxis(motionRange);
                    logger.log(Level.INFO, "added axis: {0}", axis);
                }
                // device, but I haven't found a better way yet.
                for (int keyCode : AndroidGamepadButtons) {
                    logger.log(Level.INFO, "button[{0}]: {1}", new Object[] { keyCode, KeyCharacterMap.deviceHasKey(keyCode) });
                    if (KeyCharacterMap.deviceHasKey(keyCode)) {
                        // add button even though we aren't sure if the button
                        // actually exists on this InputDevice
                        logger.log(Level.INFO, "button[{0}] exists somewhere", keyCode);
                        JoystickButton button = joystick.addButton(keyCode);
                        logger.log(Level.INFO, "added button: {0}", button);
                    }
                }
            }
        }
    }
    loaded = true;
    return joysticks;
}
Also used : DefaultJoystickButton(com.jme3.input.DefaultJoystickButton) JoystickButton(com.jme3.input.JoystickButton) InputDevice(android.view.InputDevice) AbstractJoystick(com.jme3.input.AbstractJoystick) Joystick(com.jme3.input.Joystick) ArrayList(java.util.ArrayList) JoystickAxis(com.jme3.input.JoystickAxis) DefaultJoystickAxis(com.jme3.input.DefaultJoystickAxis) MotionRange(android.view.InputDevice.MotionRange)

Example 25 with Control

use of com.jme3.scene.control.Control in project jmonkeyengine by jMonkeyEngine.

the class TestBoneRagdoll method simpleInitApp.

public void simpleInitApp() {
    initCrossHairs();
    initMaterial();
    cam.setLocation(new Vector3f(0.26924422f, 6.646658f, 22.265987f));
    cam.setRotation(new Quaternion(-2.302544E-4f, 0.99302495f, -0.117888905f, -0.0019395084f));
    bulletAppState = new BulletAppState();
    bulletAppState.setEnabled(true);
    stateManager.attach(bulletAppState);
    bullet = new Sphere(32, 32, 1.0f, true, false);
    bullet.setTextureMode(TextureMode.Projected);
    bulletCollisionShape = new SphereCollisionShape(1.0f);
    //        bulletAppState.getPhysicsSpace().enableDebug(assetManager);
    PhysicsTestHelper.createPhysicsTestWorld(rootNode, assetManager, bulletAppState.getPhysicsSpace());
    setupLight();
    model = (Node) assetManager.loadModel("Models/Sinbad/Sinbad.mesh.xml");
    //  model.setLocalRotation(new Quaternion().fromAngleAxis(FastMath.HALF_PI, Vector3f.UNIT_X));
    //debug view
    AnimControl control = model.getControl(AnimControl.class);
    SkeletonDebugger skeletonDebug = new SkeletonDebugger("skeleton", control.getSkeleton());
    Material mat2 = new Material(getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md");
    mat2.getAdditionalRenderState().setWireframe(true);
    mat2.setColor("Color", ColorRGBA.Green);
    mat2.getAdditionalRenderState().setDepthTest(false);
    skeletonDebug.setMaterial(mat2);
    skeletonDebug.setLocalTranslation(model.getLocalTranslation());
    //Note: PhysicsRagdollControl is still TODO, constructor will change
    ragdoll = new KinematicRagdollControl(0.5f);
    setupSinbad(ragdoll);
    ragdoll.addCollisionListener(this);
    model.addControl(ragdoll);
    float eighth_pi = FastMath.PI * 0.125f;
    ragdoll.setJointLimit("Waist", eighth_pi, eighth_pi, eighth_pi, eighth_pi, eighth_pi, eighth_pi);
    ragdoll.setJointLimit("Chest", eighth_pi, eighth_pi, 0, 0, eighth_pi, eighth_pi);
    //Oto's head is almost rigid
    //    ragdoll.setJointLimit("head", 0, 0, eighth_pi, -eighth_pi, 0, 0);
    getPhysicsSpace().add(ragdoll);
    speed = 1.3f;
    rootNode.attachChild(model);
    // rootNode.attachChild(skeletonDebug);
    flyCam.setMoveSpeed(50);
    animChannel = control.createChannel();
    animChannel.setAnim("Dance");
    control.addListener(this);
    inputManager.addListener(new ActionListener() {

        public void onAction(String name, boolean isPressed, float tpf) {
            if (name.equals("toggle") && isPressed) {
                Vector3f v = new Vector3f();
                v.set(model.getLocalTranslation());
                v.y = 0;
                model.setLocalTranslation(v);
                Quaternion q = new Quaternion();
                float[] angles = new float[3];
                model.getLocalRotation().toAngles(angles);
                q.fromAngleAxis(angles[1], Vector3f.UNIT_Y);
                model.setLocalRotation(q);
                if (angles[0] < 0) {
                    animChannel.setAnim("StandUpBack");
                    ragdoll.blendToKinematicMode(0.5f);
                } else {
                    animChannel.setAnim("StandUpFront");
                    ragdoll.blendToKinematicMode(0.5f);
                }
            }
            if (name.equals("bullet+") && isPressed) {
                bulletSize += 0.1f;
            }
            if (name.equals("bullet-") && isPressed) {
                bulletSize -= 0.1f;
            }
            if (name.equals("stop") && isPressed) {
                ragdoll.setEnabled(!ragdoll.isEnabled());
                ragdoll.setRagdollMode();
            }
            if (name.equals("shoot") && !isPressed) {
                Geometry bulletg = new Geometry("bullet", bullet);
                bulletg.setMaterial(matBullet);
                bulletg.setLocalTranslation(cam.getLocation());
                bulletg.setLocalScale(bulletSize);
                bulletCollisionShape = new SphereCollisionShape(bulletSize);
                RigidBodyControl bulletNode = new RigidBodyControl(bulletCollisionShape, bulletSize * 10);
                bulletNode.setCcdMotionThreshold(0.001f);
                bulletNode.setLinearVelocity(cam.getDirection().mult(80));
                bulletg.addControl(bulletNode);
                rootNode.attachChild(bulletg);
                getPhysicsSpace().add(bulletNode);
            }
            if (name.equals("boom") && !isPressed) {
                Geometry bulletg = new Geometry("bullet", bullet);
                bulletg.setMaterial(matBullet);
                bulletg.setLocalTranslation(cam.getLocation());
                bulletg.setLocalScale(bulletSize);
                bulletCollisionShape = new SphereCollisionShape(bulletSize);
                BombControl bulletNode = new BombControl(assetManager, bulletCollisionShape, 1);
                bulletNode.setForceFactor(8);
                bulletNode.setExplosionRadius(20);
                bulletNode.setCcdMotionThreshold(0.001f);
                bulletNode.setLinearVelocity(cam.getDirection().mult(180));
                bulletg.addControl(bulletNode);
                rootNode.attachChild(bulletg);
                getPhysicsSpace().add(bulletNode);
            }
        }
    }, "toggle", "shoot", "stop", "bullet+", "bullet-", "boom");
    inputManager.addMapping("toggle", new KeyTrigger(KeyInput.KEY_SPACE));
    inputManager.addMapping("shoot", new MouseButtonTrigger(MouseInput.BUTTON_LEFT));
    inputManager.addMapping("boom", new MouseButtonTrigger(MouseInput.BUTTON_RIGHT));
    inputManager.addMapping("stop", new KeyTrigger(KeyInput.KEY_H));
    inputManager.addMapping("bullet-", new KeyTrigger(KeyInput.KEY_COMMA));
    inputManager.addMapping("bullet+", new KeyTrigger(KeyInput.KEY_PERIOD));
}
Also used : SphereCollisionShape(com.jme3.bullet.collision.shapes.SphereCollisionShape) Quaternion(com.jme3.math.Quaternion) KeyTrigger(com.jme3.input.controls.KeyTrigger) Material(com.jme3.material.Material) KinematicRagdollControl(com.jme3.bullet.control.KinematicRagdollControl) RigidBodyControl(com.jme3.bullet.control.RigidBodyControl) Sphere(com.jme3.scene.shape.Sphere) Geometry(com.jme3.scene.Geometry) SkeletonDebugger(com.jme3.scene.debug.SkeletonDebugger) ActionListener(com.jme3.input.controls.ActionListener) Vector3f(com.jme3.math.Vector3f) BulletAppState(com.jme3.bullet.BulletAppState) MouseButtonTrigger(com.jme3.input.controls.MouseButtonTrigger)

Aggregations

Vector3f (com.jme3.math.Vector3f)51 DirectionalLight (com.jme3.light.DirectionalLight)24 Material (com.jme3.material.Material)23 Quaternion (com.jme3.math.Quaternion)21 Node (com.jme3.scene.Node)19 TerrainLodControl (com.jme3.terrain.geomipmap.TerrainLodControl)18 Texture (com.jme3.texture.Texture)16 AnimControl (com.jme3.animation.AnimControl)15 ColorRGBA (com.jme3.math.ColorRGBA)15 TerrainQuad (com.jme3.terrain.geomipmap.TerrainQuad)15 RigidBodyControl (com.jme3.bullet.control.RigidBodyControl)14 Geometry (com.jme3.scene.Geometry)14 Spatial (com.jme3.scene.Spatial)13 DistanceLodCalculator (com.jme3.terrain.geomipmap.lodcalc.DistanceLodCalculator)13 BulletAppState (com.jme3.bullet.BulletAppState)12 AbstractHeightMap (com.jme3.terrain.heightmap.AbstractHeightMap)11 ImageBasedHeightMap (com.jme3.terrain.heightmap.ImageBasedHeightMap)11 ArrayList (java.util.ArrayList)10 Box (com.jme3.scene.shape.Box)7 Animation (com.jme3.animation.Animation)5