com.jme3.animation.Animation Java Examples

The following examples show how to use com.jme3.animation.Animation. 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: SimulationNode.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Computes the maximum frame and time for the animation. Different tracks
 * can have different lengths so here the maximum one is being found.
 * 
 * @param animation
 *            the animation
 * @return maximum frame and time of the animation
 */
private float[] computeAnimationTimeBoundaries(Animation animation) {
    int maxFrame = Integer.MIN_VALUE;
    float maxTime = Float.MIN_VALUE;
    for (Track track : animation.getTracks()) {
        if (track instanceof BoneTrack) {
            maxFrame = Math.max(maxFrame, ((BoneTrack) track).getTranslations().length);
            maxTime = Math.max(maxTime, ((BoneTrack) track).getTimes()[((BoneTrack) track).getTimes().length - 1]);
        } else if (track instanceof SpatialTrack) {
            maxFrame = Math.max(maxFrame, ((SpatialTrack) track).getTranslations().length);
            maxTime = Math.max(maxTime, ((SpatialTrack) track).getTimes()[((SpatialTrack) track).getTimes().length - 1]);
        } else {
            throw new IllegalStateException("Unsupported track type for simuation: " + track);
        }
    }
    return new float[] { maxFrame, maxTime };
}
 
Example #2
Source File: RemoveElementsOperation.java    From jmonkeybuilder with Apache License 2.0 6 votes vote down vote up
@Override
@JmeThread
protected void redoImpl(@NotNull final ModelChangeConsumer editor) {
    EXECUTOR_MANAGER.addJmeTask(() -> {

        for (final Element element : elements) {

            final Object toRemove = element.getElement();

            if (toRemove instanceof Spatial) {
                removeSpatial(element, (Spatial) toRemove);
            } else if (toRemove instanceof Light) {
                removeLight(element, (Light) toRemove);
            } else if (toRemove instanceof Animation) {
                removeAnimation(element, (Animation) toRemove);
            } else if (toRemove instanceof Control) {
                removeControl(element, (Control) toRemove);
            }
        }

        EXECUTOR_MANAGER.addFxTask(() -> {
            elements.forEach(editor, (element, consumer) ->
                    consumer.notifyFxRemovedChild(element.getParent(), element.getElement()));
        });
    });
}
 
Example #3
Source File: RemoveElementsOperation.java    From jmonkeybuilder with Apache License 2.0 6 votes vote down vote up
@Override
@JmeThread
protected void undoImpl(@NotNull final ModelChangeConsumer editor) {
    EXECUTOR_MANAGER.addJmeTask(() -> {

        for (final Element element : elements) {

            final Object toRestore = element.getElement();

            if (toRestore instanceof Spatial) {
                restoreSpatial(element, (Spatial) toRestore);
            } else if (toRestore instanceof Light) {
                restoreLight(element, (Light) toRestore);
            } else if (toRestore instanceof Animation) {
                restoreAnimation(element, (Animation) toRestore);
            } else if (toRestore instanceof Control) {
                restoreControl(element, (Control) toRestore);
            }
        }

        EXECUTOR_MANAGER.addFxTask(() -> {
            elements.forEach(editor, (element, consumer) ->
                    consumer.notifyFxAddedChild(element.getParent(), element.getElement(), element.getIndex(), false));
        });
    });
}
 
Example #4
Source File: ExtractSubAnimationDialog.java    From jmonkeybuilder with Apache License 2.0 6 votes vote down vote up
public ExtractSubAnimationDialog(@NotNull final NodeTree<?> nodeTree, @NotNull final AnimationTreeNode node) {
    this.nodeTree = nodeTree;
    this.node = node;

    final Animation animation = node.getElement();
    final AnimControl control = notNull(node.getControl());
    final int frameCount = AnimationUtils.getFrameCount(animation);

    final TextField nameField = getNameField();
    nameField.setText(AnimationUtils.findFreeName(control, Messages.MANUAL_EXTRACT_ANIMATION_DIALOG_NAME_EXAMPLE));

    final IntegerTextField startFrameField = getStartFrameField();
    startFrameField.setMinMax(0, frameCount - 2);
    startFrameField.setValue(0);

    final IntegerTextField endFrameField = getEndFrameField();
    endFrameField.setMinMax(1, frameCount - 1);
    endFrameField.setValue(frameCount - 1);
}
 
Example #5
Source File: RemoveAnimationAction.java    From jmonkeybuilder with Apache License 2.0 6 votes vote down vote up
@Override
@FxThread
protected void process() {
    super.process();

    final TreeNode<?> node = getNode();
    final Object element = node.getElement();

    if (!(element instanceof Animation)) return;
    final Animation animation = (Animation) element;

    final NodeTree<ModelChangeConsumer> nodeTree = getNodeTree();
    final TreeNode<?> parentNode = nodeTree.findParent(node);

    if (parentNode == null) {
        LOGGER.warning("not found parent node for " + node);
        return;
    }

    final AnimControl parent = (AnimControl) parentNode.getElement();

    final ModelChangeConsumer changeConsumer = notNull(nodeTree.getChangeConsumer());
    changeConsumer.execute(new RemoveAnimationNodeOperation(animation, parent));
}
 
Example #6
Source File: RenameAnimationNodeOperation.java    From jmonkeybuilder with Apache License 2.0 5 votes vote down vote up
@Override
protected void undoImpl(@NotNull final ModelChangeConsumer editor) {
    EXECUTOR_MANAGER.addJmeTask(() -> {
        final Animation anim = control.getAnim(newName);
        AnimationUtils.changeName(control, anim, newName, oldName);
        EXECUTOR_MANAGER.addFxTask(() -> editor.notifyFxChangeProperty(control, anim, "name"));
    });
}
 
Example #7
Source File: CinematicTest.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * No ClassCastException when clear() a Cinematic with AnimationEvent
 */
@Test
public void clearAnimationEvent() {
    Cinematic sut = new Cinematic();
    Node model = new Node("model");
    AnimControl ac = new AnimControl();
    ac.addAnim(new Animation("animName", 1.0f));
    model.addControl(ac);
    sut.enqueueCinematicEvent(new AnimationEvent(model, "animName"));
    sut.initialize(null, null);
    sut.clear();
}
 
Example #8
Source File: AnimationUtils.java    From jmonkeybuilder with Apache License 2.0 5 votes vote down vote up
/**
 * Get frame count of the animation.
 *
 * @param animation the animation.
 * @return the frame count or -1.
 */
@FromAnyThread
public static int getFrameCount(@NotNull Animation animation) {

    var min = Integer.MAX_VALUE;

    var tracks = animation.getTracks();
    for (var track : tracks) {
        if (track instanceof BoneTrack) {
            min = Math.min(min, ((BoneTrack) track).getTimes().length);
        }
    }

    return min == Integer.MAX_VALUE ? -1 : min;
}
 
Example #9
Source File: AnimationUtils.java    From jmonkeybuilder with Apache License 2.0 5 votes vote down vote up
/**
 * Change the name of the animation.
 *
 * @param control   the animation control.
 * @param animation the animation.
 * @param oldName   the old name.
 * @param newName   the new name.
 */
@FromAnyThread
public static void changeName(
        @NotNull AnimControl control,
        @NotNull Animation animation,
        @NotNull String oldName,
        @NotNull String newName
) {
    try {

        var animationMap = ClassUtils.<Map<String, Animation>>unsafeCast(ANIMATIONS_MAP_FIELD.get(control));

        if (!animationMap.containsKey(oldName)) {
            throw new IllegalArgumentException("Given animation does not exist " + "in this AnimControl");
        }

        if (animationMap.containsKey(newName)) {
            throw new IllegalArgumentException("The same animation exist " + "in this AnimControl");
        }

        ANIMATION_NAME_FIELD.set(animation, newName);

        animationMap.remove(oldName);
        animationMap.put(newName, animation);

    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}
 
Example #10
Source File: AnimationUtils.java    From jmonkeybuilder with Apache License 2.0 5 votes vote down vote up
/**
 * Extract an animation from a source animation.
 *
 * @param source     the source animation.
 * @param newName    the new name of a sub animation.
 * @param startFrame the start frame.
 * @param endFrame   the end frame.
 * @return the new sub animation.
 */
@FromAnyThread
public static @NotNull Animation extractAnimation(
        @NotNull Animation source,
        @NotNull String newName,
        int startFrame,
        int endFrame
) {

    var sourceTracks = source.getTracks();
    var firstSourceTrack = (BoneTrack) sourceTracks[0];
    var sourceTimes = firstSourceTrack.getTimes();

    var newLength = (source.getLength() / (float) sourceTimes.length) * (float) (endFrame - startFrame);
    var result = new Animation(newName, newLength);
    var newTracks = ArrayFactory.<Track>newArray(Track.class);

    for (var sourceTrack : sourceTracks) {
        if (sourceTrack instanceof BoneTrack) {
            newTracks.add(extractBoneTrack((BoneTrack) sourceTrack, startFrame, endFrame));
        }
    }

    result.setTracks(newTracks.toArray(Track.class));

    return result;
}
 
Example #11
Source File: AnimationTreeNode.java    From jmonkeybuilder with Apache License 2.0 5 votes vote down vote up
@Override
@FxThread
public @NotNull Array<TreeNode<?>> getChildren(@NotNull final NodeTree<?> nodeTree) {

    final Animation element = getElement();
    final Track[] tracks = element.getTracks();

    final Array<TreeNode<?>> result = ArrayFactory.newArray(TreeNode.class, tracks.length);
    ArrayUtils.forEach(tracks, track -> result.add(FACTORY_REGISTRY.createFor(track)));

    return result;
}
 
Example #12
Source File: AnimationTreeNode.java    From jmonkeybuilder with Apache License 2.0 5 votes vote down vote up
@Override
@FxThread
public boolean hasChildren(@NotNull final NodeTree<?> nodeTree) {

    final Animation element = getElement();
    final Track[] tracks = element.getTracks();

    return tracks != null && tracks.length > 0 && nodeTree instanceof ModelNodeTree;
}
 
Example #13
Source File: AnimationTreeNode.java    From jmonkeybuilder with Apache License 2.0 5 votes vote down vote up
@Override
@FxThread
public void fillContextMenu(@NotNull final NodeTree<?> nodeTree,
                            @NotNull final ObservableList<MenuItem> items) {

    final Animation animation = getElement();
    final AnimationControlTreeNode controlModelNode = notNull(getControlModelNode());
    final AnimControl control = controlModelNode.getElement();

    final int frameCount = AnimationUtils.getFrameCount(animation);

    if (getChannel() < 0 && control.getNumChannels() < 1) {
        items.add(new PlayAnimationAction(nodeTree, this));
        items.add(new RemoveAnimationAction(nodeTree, this));
        items.add(new RenameNodeAction(nodeTree, this));
    } else if (getChannel() >= 0 && control.getChannel(getChannel()).getSpeed() < 0.0001F) {
        items.add(new PlayAnimationAction(nodeTree, this));
        items.add(new StopAnimationAction(nodeTree, this));
    } else if (getChannel() >= 0) {
        items.add(new PauseAnimationAction(nodeTree, this));
        items.add(new StopAnimationAction(nodeTree, this));
    }

    if (getChannel() < 0 && frameCount > 0) {
        items.add(new ManualExtractSubAnimationAction(nodeTree, this));
    }

    super.fillContextMenu(nodeTree, items);
}
 
Example #14
Source File: ExtractSubAnimationDialog.java    From jmonkeybuilder with Apache License 2.0 5 votes vote down vote up
/**
 * Process of extraction a sub animation.
 */
@BackgroundThread
private void processExtract() {

    final AnimationTreeNode node = getNode();
    final AnimControl control = notNull(node.getControl());
    final Animation animation = node.getElement();

    final TextField nameField = getNameField();
    final IntegerTextField startFrameField = getStartFrameField();
    final IntegerTextField endFrameField = getEndFrameField();

    int startFrame = startFrameField.getValue();
    int endFrame = endFrameField.getValue();

    if (startFrame >= endFrame) {
        startFrame = endFrame - 1;
    }

    final Animation subAnimation = extractAnimation(animation, nameField.getText(), startFrame, endFrame);

    final NodeTree<?> nodeTree = getNodeTree();
    final ChangeConsumer changeConsumer = notNull(nodeTree.getChangeConsumer());
    changeConsumer.execute(new AddAnimationNodeOperation(subAnimation, control));

    EXECUTOR_MANAGER.addFxTask(UiUtils::decrementLoading);
}
 
Example #15
Source File: RenameAnimationNodeOperation.java    From jmonkeybuilder with Apache License 2.0 5 votes vote down vote up
@Override
protected void redoImpl(@NotNull final ModelChangeConsumer editor) {
    EXECUTOR_MANAGER.addJmeTask(() -> {
        final Animation anim = control.getAnim(oldName);
        AnimationUtils.changeName(control, anim, oldName, newName);
        EXECUTOR_MANAGER.addFxTask(() -> editor.notifyFxChangeProperty(control, anim, "name"));
    });
}
 
Example #16
Source File: AnimationTreeNode.java    From jmonkeybuilder with Apache License 2.0 4 votes vote down vote up
public AnimationTreeNode(@NotNull final Animation element, final long objectId) {
    super(element, objectId);
    this.channel = -1;
}
 
Example #17
Source File: RemoveElementsOperation.java    From jmonkeybuilder with Apache License 2.0 4 votes vote down vote up
@JmeThread
private void restoreAnimation(@NotNull final Element element, @NotNull final Animation toRestore) {
    final AnimControl parent = (AnimControl) element.getParent();
    parent.addAnim(toRestore);
}
 
Example #18
Source File: RemoveElementsOperation.java    From jmonkeybuilder with Apache License 2.0 4 votes vote down vote up
@JmeThread
private void removeAnimation(@NotNull final Element element, @NotNull final Animation toRemove) {
    final AnimControl parent = (AnimControl) element.getParent();
    parent.removeAnim(toRemove);
}
 
Example #19
Source File: RemoveAnimationNodeOperation.java    From jmonkeybuilder with Apache License 2.0 4 votes vote down vote up
public RemoveAnimationNodeOperation(@NotNull final Animation animation, @NotNull final AnimControl control) {
    this.animation = animation;
    this.control = control;
}
 
Example #20
Source File: AnimationData.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public AnimationData(List<Animation> anims) {
    this.anims = anims;
    skeleton = null;
}
 
Example #21
Source File: AnimationData.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public AnimationData(Skeleton skeleton, List<Animation> anims) {
    this.skeleton = skeleton;
    this.anims = anims;
}
 
Example #22
Source File: ObjectAnimationModifier.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * This constructor reads animation of the object itself (without bones) and
 * stores it as an ArmatureModifierData modifier. The animation is returned
 * as a modifier. It should be later applied regardless other modifiers. The
 * reason for this is that object may not have modifiers added but it's
 * animation should be working. The stored modifier is an anim data and
 * additional data is given object's OMA.
 * 
 * @param ipo
 *            the object's interpolation curves
 * @param objectAnimationName
 *            the name of object's animation
 * @param objectOMA
 *            the OMA of the object
 * @param blenderContext
 *            the blender context
 * @throws BlenderFileException
 *             this exception is thrown when the blender file is somehow
 *             corrupted
 */
public ObjectAnimationModifier(Ipo ipo, String objectAnimationName, Long objectOMA, BlenderContext blenderContext) throws BlenderFileException {
    int fps = blenderContext.getBlenderKey().getFps();

    Spatial object = (Spatial) blenderContext.getLoadedFeature(objectOMA, LoadedFeatureDataType.LOADED_FEATURE);
    // calculating track
    SpatialTrack track = (SpatialTrack) ipo.calculateTrack(-1, object.getLocalRotation(), 0, ipo.getLastFrame(), fps, true);

    Animation animation = new Animation(objectAnimationName, ipo.getLastFrame() / (float) fps);
    animation.setTracks(new SpatialTrack[] { track });
    ArrayList<Animation> animations = new ArrayList<Animation>(1);
    animations.add(animation);

    animationData = new AnimationData(animations);
    blenderContext.setAnimData(objectOMA, animationData);
}
 
Example #23
Source File: TestSpatialAnim.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
  public void simpleInitApp() {

      AmbientLight al = new AmbientLight();
      rootNode.addLight(al);

      DirectionalLight dl = new DirectionalLight();
      dl.setDirection(Vector3f.UNIT_XYZ.negate());
      rootNode.addLight(dl);

      // Create model
      Box box = new Box(1, 1, 1);
      Geometry geom = new Geometry("box", box);
      geom.setMaterial(assetManager.loadMaterial("Textures/Terrain/BrickWall/BrickWall.j3m"));
      Node model = new Node("model");
      model.attachChild(geom);

      Box child = new Box(0.5f, 0.5f, 0.5f);
      Geometry childGeom = new Geometry("box", child);
      childGeom.setMaterial(assetManager.loadMaterial("Textures/Terrain/BrickWall/BrickWall.j3m"));
      Node childModel = new Node("childmodel");
      childModel.setLocalTranslation(2, 2, 2);
      childModel.attachChild(childGeom);
      model.attachChild(childModel);
      
      //animation parameters
      float animTime = 5;
      int fps = 25;
      float totalXLength = 10;
      
      //calculating frames
      int totalFrames = (int) (fps * animTime);
      float dT = animTime / totalFrames, t = 0;
      float dX = totalXLength / totalFrames, x = 0;
      float[] times = new float[totalFrames];
      Vector3f[] translations = new Vector3f[totalFrames];
      Quaternion[] rotations = new Quaternion[totalFrames];
      Vector3f[] scales = new Vector3f[totalFrames];
for (int i = 0; i < totalFrames; ++i) {
      	times[i] = t;
      	t += dT;
      	translations[i] = new Vector3f(x, 0, 0);
      	x += dX;
      	rotations[i] = Quaternion.IDENTITY;
      	scales[i] = Vector3f.UNIT_XYZ;
      }
      SpatialTrack spatialTrack = new SpatialTrack(times, translations, rotations, scales);
      
      //creating the animation
      Animation spatialAnimation = new Animation("anim", animTime);
      spatialAnimation.setTracks(new SpatialTrack[] { spatialTrack });
      
      //create spatial animation control
      AnimControl control = new AnimControl();
      HashMap<String, Animation> animations = new HashMap<String, Animation>();
      animations.put("anim", spatialAnimation);
      control.setAnimations(animations);
      model.addControl(control);

      rootNode.attachChild(model);
      
      //run animation
      control.createChannel().setAnim("anim");
  }
 
Example #24
Source File: AnimData.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public AnimData(Skeleton skeleton, ArrayList<Animation> anims) {
    this.skeleton = skeleton;
    this.anims = anims;
}
 
Example #25
Source File: AddAnimationNodeOperation.java    From jmonkeybuilder with Apache License 2.0 2 votes vote down vote up
/**
 * Instantiates a new Add animation node operation.
 *
 * @param animation the animation
 * @param control   the control
 */
public AddAnimationNodeOperation(@NotNull final Animation animation, @NotNull final AnimControl control) {
    this.animation = animation;
    this.control = control;
}