Java Code Examples for com.jme3.scene.Spatial#getParent()

The following examples show how to use com.jme3.scene.Spatial#getParent() . 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: CollisionShapeFactory.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * returns the correct transform for a collisionshape in relation
 * to the ancestor for which the collisionshape is generated
 * @param spat
 * @param parent
 * @return
 */
private static Transform getTransform(Spatial spat, Spatial parent) {
    Transform shapeTransform = new Transform();
    Spatial parentNode = spat.getParent() != null ? spat.getParent() : spat;
    Spatial currentSpatial = spat;
    //if we have parents combine their transforms
    while (parentNode != null) {
        if (parent == currentSpatial) {
            //real parent -> only apply scale, not transform
            Transform trans = new Transform();
            trans.setScale(currentSpatial.getLocalScale());
            shapeTransform.combineWithParent(trans);
            parentNode = null;
        } else {
            shapeTransform.combineWithParent(currentSpatial.getLocalTransform());
            parentNode = currentSpatial.getParent();
            currentSpatial = parentNode;
        }
    }
    return shapeTransform;
}
 
Example 2
Source File: SceneEditorController.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void doMoveSpatial(Spatial selected, Vector3f translation) {
    Vector3f localTranslation = selected.getLocalTranslation();
    Vector3f before = new Vector3f(localTranslation);
    Node parent = selected.getParent();
    if (parent != null) {
        localTranslation.set(translation).subtractLocal(parent.getWorldTranslation());
        localTranslation.divideLocal(parent.getWorldScale());
        //TODO: reuse quaternion..
        new Quaternion().set(parent.getWorldRotation()).inverseLocal().multLocal(localTranslation);
    } else {
        localTranslation.set(translation);
    }
    Vector3f after = new Vector3f(localTranslation);
    selected.setLocalTranslation(localTranslation);
    AbstractSceneExplorerNode selectedSpat = this.selectedSpat;
    moveUndo(selected, before, after, selectedSpat);
}
 
Example 3
Source File: RigidBodyMotionState.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * applies the current transform to the given jme Node if the location has been updated on the physics side
 * @param spatial
 */
public synchronized boolean applyTransform(Spatial spatial) {
    if (!physicsLocationDirty) {
        return false;
    }
    if (!applyPhysicsLocal && spatial.getParent() != null) {
        localLocation.set(worldLocation).subtractLocal(spatial.getParent().getWorldTranslation());
        localLocation.divideLocal(spatial.getParent().getWorldScale());
        tmp_inverseWorldRotation.set(spatial.getParent().getWorldRotation()).inverseLocal().multLocal(localLocation);

        localRotationQuat.set(worldRotationQuat);
        tmp_inverseWorldRotation.set(spatial.getParent().getWorldRotation()).inverseLocal().mult(localRotationQuat, localRotationQuat);

        spatial.setLocalTranslation(localLocation);
        spatial.setLocalRotation(localRotationQuat);
    } else {
        spatial.setLocalTranslation(worldLocation);
        spatial.setLocalRotation(worldRotationQuat);
    }
    physicsLocationDirty = false;
    return true;
}
 
Example 4
Source File: NodeUtils.java    From jmonkeybuilder with Apache License 2.0 6 votes vote down vote up
/**
 * Find a parent of the model.
 *
 * @param <T>       the node's type.
 * @param spatial   the spatial.
 * @param condition the condition.
 * @return the optional result.
 */
@FromAnyThread
public static <T> @NotNull Optional<T> findParentOpt(
        @NotNull Spatial spatial,
        @NotNull Predicate<Spatial> condition
) {

    if (condition.test(spatial)) {
        return Optional.of(unsafeCast(spatial));
    }

    var parent = spatial.getParent();
    if (parent == null) {
        return Optional.empty();
    }

    return findParentOpt(parent, condition);
}
 
Example 5
Source File: AbstractPhysicsDebugControl.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Apply the specified location and orientation to the specified spatial.
 *
 * @param worldLocation location vector (in physics-space coordinates, not
 * null, unaffected)
 * @param worldRotation orientation (in physics-space coordinates, not null,
 * unaffected)
 * @param spatial where to apply (may be null)
 */
protected void applyPhysicsTransform(Vector3f worldLocation, Quaternion worldRotation, Spatial spatial) {
    if (spatial != null) {
        Vector3f localLocation = spatial.getLocalTranslation();
        Quaternion localRotationQuat = spatial.getLocalRotation();
        if (spatial.getParent() != null) {
            localLocation.set(worldLocation).subtractLocal(spatial.getParent().getWorldTranslation());
            localLocation.divideLocal(spatial.getParent().getWorldScale());
            tmp_inverseWorldRotation.set(spatial.getParent().getWorldRotation()).inverseLocal().multLocal(localLocation);
            localRotationQuat.set(worldRotation);
            tmp_inverseWorldRotation.set(spatial.getParent().getWorldRotation()).inverseLocal().mult(localRotationQuat, localRotationQuat);
            spatial.setLocalTranslation(localLocation);
            spatial.setLocalRotation(localRotationQuat);
        } else {
            spatial.setLocalTranslation(worldLocation);
            spatial.setLocalRotation(worldRotation);
        }
    }

}
 
Example 6
Source File: CollisionShapeFactory.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * returns the correct transform for a collisionshape in relation
 * to the ancestor for which the collisionshape is generated
 * @param spat
 * @param parent
 * @return
 */
private static Transform getTransform(Spatial spat, Spatial parent) {
    Transform shapeTransform = new Transform();
    Spatial parentNode = spat.getParent() != null ? spat.getParent() : spat;
    Spatial currentSpatial = spat;
    //if we have parents combine their transforms
    while (parentNode != null) {
        if (parent == currentSpatial) {
            //real parent -> only apply scale, not transform
            Transform trans = new Transform();
            trans.setScale(currentSpatial.getLocalScale());
            shapeTransform.combineWithParent(trans);
            parentNode = null;
        } else {
            shapeTransform.combineWithParent(currentSpatial.getLocalTransform());
            parentNode = currentSpatial.getParent();
            currentSpatial = parentNode;
        }
    }
    return shapeTransform;
}
 
Example 7
Source File: NodeTreeNode.java    From jmonkeybuilder with Apache License 2.0 5 votes vote down vote up
@Override
@FxThread
public void accept(@NotNull final ChangeConsumer changeConsumer, @NotNull final Object object,
                   final boolean isCopy) {

    final T newParent = getElement();

    if (object instanceof Spatial) {

        final Spatial spatial = (Spatial) object;

        if (isCopy) {

            final Spatial clone = spatial.clone();
            final SceneLayer layer = SceneLayer.getLayer(spatial);

            if (layer != null) {
                SceneLayer.setLayer(layer, clone);
            }

            changeConsumer.execute(new AddChildOperation(clone, newParent, true));

        } else {
            final Node parent = spatial.getParent();
            final int childIndex = parent.getChildIndex(spatial);
            changeConsumer.execute(new MoveChildOperation(spatial, parent, newParent, childIndex));
        }
    }

    super.accept(changeConsumer, object, isCopy);
}
 
Example 8
Source File: SpatialSelector.java    From OpenRTS with MIT License 5 votes vote down vote up
public long getEntityId() {
	Spatial s = getGeometry(view.getRootNode());
	while (s != null && s.getName() != null) {
		Object o = s.getUserData(ModelPerformer.ENTITYID_USERDATA);
		if (o != null && EntityManager.isValidId((long) o)) {
			return (long) o;
		}
		s = s.getParent();
	}
	return EntityManager.NOT_VALID_ID;
}
 
Example 9
Source File: BillboardControl.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void fixRefreshFlags(){
    // force transforms to update below this node
    spatial.updateGeometricState();
    
    // force world bound to update
    Spatial rootNode = spatial;
    while (rootNode.getParent() != null){
        rootNode = rootNode.getParent();
    }
    rootNode.getWorldBound(); 
}
 
Example 10
Source File: RigidBodyMotionState.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
     * If the motion state has been updated, apply the new transform to the
     * specified spatial.
     *
     * @param spatial where to apply the physics transform (not null, modified)
     * @return true if changed
     */
    public boolean applyTransform(Spatial spatial) {
        Vector3f localLocation = spatial.getLocalTranslation();
        Quaternion localRotationQuat = spatial.getLocalRotation();
        boolean physicsLocationDirty = applyTransform(motionStateId, localLocation, localRotationQuat);
        if (!physicsLocationDirty) {
            return false;
        }
        if (!applyPhysicsLocal && spatial.getParent() != null) {
            localLocation.subtractLocal(spatial.getParent().getWorldTranslation());
            localLocation.divideLocal(spatial.getParent().getWorldScale());
            tmp_inverseWorldRotation.set(spatial.getParent().getWorldRotation()).inverseLocal().multLocal(localLocation);

//            localRotationQuat.set(worldRotationQuat);
            tmp_inverseWorldRotation.mult(localRotationQuat, localRotationQuat);

            spatial.setLocalTranslation(localLocation);
            spatial.setLocalRotation(localRotationQuat);
        } else {
            spatial.setLocalTranslation(localLocation);
            spatial.setLocalRotation(localRotationQuat);
//            spatial.setLocalTranslation(worldLocation);
//            spatial.setLocalRotation(worldRotationQuat);
        }
        if (vehicle != null) {
            vehicle.updateWheels();
        }
        return true;
    }
 
Example 11
Source File: FocusManagerState.java    From Lemur with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected List<Spatial> getHierarchy( Spatial s ) {
    if( s == null ) {
        return Collections.emptyList();
    }
    List<Spatial> result = new ArrayList<Spatial>();
    for( ; s != null; s = s.getParent() ) {
        result.add(0, s);
    }
    return result;
}
 
Example 12
Source File: NodeUtils.java    From jmonkeybuilder with Apache License 2.0 5 votes vote down vote up
/**
 * Find a parent of the model by the steps.
 *
 * @param spatial the spatial.
 * @param count   the count of steps.
 * @return the result parent.
 */
@FromAnyThread
public static @Nullable Spatial findParent(@NotNull Spatial spatial, int count) {

    Spatial parent = spatial;

    while (count-- > 0 && parent != null) {
        parent = parent.getParent();
    }

    return parent;
}
 
Example 13
Source File: GeomUtils.java    From jmonkeybuilder with Apache License 2.0 5 votes vote down vote up
/**
 * Get the index of the object in the model.
 *
 * @param model  the model.
 * @param object the object.
 * @return the index.
 */
@FromAnyThread
public static int getIndex(@NotNull Spatial model, @NotNull Object object) {

    Spatial parent = model;
    int parentIndex = 0;

    while (parent != null) {
        if (Objects.equals(parent, object)) return parentIndex;
        parent = parent.getParent();
        parentIndex--;
    }

    if (!(model instanceof Node)) {
        return -1;
    }

    var counter = new AtomicInteger(0);
    var node = (Node) model;
    var children = node.getChildren();

    for (var child : children) {
        if (getIndex(child, object, counter)) {
            return counter.get();
        }
    }

    return -1;
}
 
Example 14
Source File: KinematicRagdollControl.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Create spatial-dependent data. Invoked when this control is added to a
 * scene.
 *
 * @param model the controlled spatial (not null)
 */
@Override
protected void createSpatialData(Spatial model) {
    targetModel = model;
    Node parent = model.getParent();


    Vector3f initPosition = model.getLocalTranslation().clone();
    Quaternion initRotation = model.getLocalRotation().clone();
    initScale = model.getLocalScale().clone();

    model.removeFromParent();
    model.setLocalTranslation(Vector3f.ZERO);
    model.setLocalRotation(Quaternion.IDENTITY);
    model.setLocalScale(1);
    //HACK ALERT change this
    //I remove the skeletonControl and readd it to the spatial to make sure it's after the ragdollControl in the stack
    //Find a proper way to order the controls.
    SkeletonControl sc = model.getControl(SkeletonControl.class);
    if(sc == null){
        throw new IllegalArgumentException("The root node of the model should have a SkeletonControl. Make sure the control is there and that it's not on a sub node.");
    }
    model.removeControl(sc);
    model.addControl(sc);

    if (boneList.isEmpty()) {
        // add all bones to the list
        skeleton = sc.getSkeleton();
        for (int boneI = 0; boneI < skeleton.getBoneCount(); boneI++) {
            String boneName = skeleton.getBone(boneI).getName();
            boneList.add(boneName);
        }
    }
    // filter out bones without vertices
    filterBoneList(sc);

    if (boneList.isEmpty()) {
        throw new IllegalArgumentException(
                "No suitable bones were found in the model's skeleton.");
    }

    // put into bind pose and compute bone transforms in model space
    // maybe don't reset to ragdoll out of animations?
    scanSpatial(model);


    if (parent != null) {
        parent.attachChild(model);

    }
    model.setLocalTranslation(initPosition);
    model.setLocalRotation(initRotation);
    model.setLocalScale(initScale);

    if (added) {
        addPhysics(space);
    }
    logger.log(Level.FINE, "Created physics ragdoll for skeleton {0}", skeleton);
}
 
Example 15
Source File: RenderManager.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Flattens the given scene graph into the ViewPort's RenderQueue,
 * checking for culling as the call goes down the graph recursively.
 * <p>
 * First, the scene is checked for culling based on the <code>Spatial</code>s
 * {@link Spatial#setCullHint(com.jme3.scene.Spatial.CullHint) cull hint},
 * if the camera frustum contains the scene, then this method is recursively
 * called on its children.
 * <p>
 * When the scene's leaves or {@link Geometry geometries} are reached,
 * they are each enqueued into the 
 * {@link ViewPort#getQueue() ViewPort's render queue}.
 * <p>
 * In addition to enqueuing the visible geometries, this method
 * also scenes which cast or receive shadows, by putting them into the
 * RenderQueue's 
 * {@link RenderQueue#addToShadowQueue(com.jme3.scene.Geometry, com.jme3.renderer.queue.RenderQueue.ShadowMode) 
 * shadow queue}. Each Spatial which has its 
 * {@link Spatial#setShadowMode(com.jme3.renderer.queue.RenderQueue.ShadowMode) shadow mode}
 * set to not off, will be put into the appropriate shadow queue, note that
 * this process does not check for frustum culling on any 
 * {@link ShadowMode#Cast shadow casters}, as they don't have to be
 * in the eye camera frustum to cast shadows on objects that are inside it.
 * 
 * @param scene The scene to flatten into the queue
 * @param vp The ViewPort provides the {@link ViewPort#getCamera() camera}
 * used for culling and the {@link ViewPort#getQueue() queue} used to 
 * contain the flattened scene graph.
 */
public void renderScene(Spatial scene, ViewPort vp) {
    if (scene.getParent() == null) {
        vp.getCamera().setPlaneState(0);
    }
    // check culling first.
    if (!scene.checkCulling(vp.getCamera())) {
        // move on to shadow-only render
        if ((scene.getShadowMode() != RenderQueue.ShadowMode.Off || scene instanceof Node) && scene.getCullHint()!=Spatial.CullHint.Always) {
            renderShadow(scene, vp.getQueue());
        }
        return;
    }

    scene.runControlRender(this, vp);
    if (scene instanceof Node) {
        // recurse for all children
        Node n = (Node) scene;
        List<Spatial> children = n.getChildren();
        //saving cam state for culling
        int camState = vp.getCamera().getPlaneState();
        for (int i = 0; i < children.size(); i++) {
            //restoring cam state before proceeding children recusively
            vp.getCamera().setPlaneState(camState);
            renderScene(children.get(i), vp);

        }
    } else if (scene instanceof Geometry) {

        // add to the render queue
        Geometry gm = (Geometry) scene;
        if (gm.getMaterial() == null) {
            throw new IllegalStateException("No material is set for Geometry: " + gm.getName());
        }

        vp.getQueue().addToQueue(gm, scene.getQueueBucket());

        // add to shadow queue if needed
        RenderQueue.ShadowMode shadowMode = scene.getShadowMode();
        if (shadowMode != RenderQueue.ShadowMode.Off) {
            vp.getQueue().addToShadowQueue(gm, shadowMode);
        }
    }
}
 
Example 16
Source File: AnimationEvent.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void initEvent(Application app, Cinematic cinematic) {
    super.initEvent(app, cinematic);
    this.cinematic = cinematic;
    if (channel == null) {
        Object s = cinematic.getEventData(MODEL_CHANNELS, model);
        if (s == null) {
            s = new HashMap<Integer, AnimChannel>();
            int numChannels = model.getControl(AnimControl.class).getNumChannels();
            for(int i = 0; i < numChannels; i++){
                ((HashMap<Integer, AnimChannel>)s).put(i, model.getControl(AnimControl.class).getChannel(i));
            }
            cinematic.putEventData(MODEL_CHANNELS, model, s);
        }

        Map<Integer, AnimChannel> map = (Map<Integer, AnimChannel>) s;
        this.channel = map.get(channelIndex);
        if (this.channel == null) {
            if (model == null) {
                //the model is null we try to find it according to the name
                //this should occur only when loading an old saved cinematic
                //othewise it's an error
                model = cinematic.getScene().getChild(modelName);
            }
            if (model != null) {
                if(cinematic.getScene() != null){
                    Spatial sceneModel = cinematic.getScene().getChild(model.getName());
                    if(sceneModel != null){
                        Node parent = sceneModel.getParent();
                        parent.detachChild(sceneModel);
                        sceneModel = model;
                        parent.attachChild(sceneModel);
                    } else {
                        cinematic.getScene().attachChild(model);
                    }
                }
                
                channel = model.getControl(AnimControl.class).createChannel();
                map.put(channelIndex, channel);
            } else {
                //it's an error
                throw new UnsupportedOperationException("model should not be null");
            }
        } 

    }
}
 
Example 17
Source File: KinematicRagdollControl.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void setSpatial(Spatial model) {
    if (model == null) {
        removeFromPhysicsSpace();
        clearData();
        return;
    }
    targetModel = model;
    Node parent = model.getParent();


    Vector3f initPosition = model.getLocalTranslation().clone();
    Quaternion initRotation = model.getLocalRotation().clone();
    initScale = model.getLocalScale().clone();

    model.removeFromParent();
    model.setLocalTranslation(Vector3f.ZERO);
    model.setLocalRotation(Quaternion.IDENTITY);
    model.setLocalScale(1);
    //HACK ALERT change this
    //I remove the skeletonControl and readd it to the spatial to make sure it's after the ragdollControl in the stack
    //Find a proper way to order the controls.
    SkeletonControl sc = model.getControl(SkeletonControl.class);
    model.removeControl(sc);
    model.addControl(sc);
    //---- 

    removeFromPhysicsSpace();
    clearData();
    // put into bind pose and compute bone transforms in model space
    // maybe dont reset to ragdoll out of animations?
    scanSpatial(model);


    if (parent != null) {
        parent.attachChild(model);

    }
    model.setLocalTranslation(initPosition);
    model.setLocalRotation(initRotation);
    model.setLocalScale(initScale);

    logger.log(Level.INFO, "Created physics ragdoll for skeleton {0}", skeleton);
}
 
Example 18
Source File: KinematicRagdollControl.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void setSpatial(Spatial model) {
    if (model == null) {
        removeFromPhysicsSpace();
        clearData();
        return;
    }
    targetModel = model;
    Node parent = model.getParent();


    Vector3f initPosition = model.getLocalTranslation().clone();
    Quaternion initRotation = model.getLocalRotation().clone();
    initScale = model.getLocalScale().clone();

    model.removeFromParent();
    model.setLocalTranslation(Vector3f.ZERO);
    model.setLocalRotation(Quaternion.IDENTITY);
    model.setLocalScale(1);
    //HACK ALERT change this
    //I remove the skeletonControl and readd it to the spatial to make sure it's after the ragdollControl in the stack
    //Find a proper way to order the controls.
    SkeletonControl sc = model.getControl(SkeletonControl.class);
    model.removeControl(sc);
    model.addControl(sc);
    //---- 

    removeFromPhysicsSpace();
    clearData();
    // put into bind pose and compute bone transforms in model space
    // maybe dont reset to ragdoll out of animations?
    scanSpatial(model);


    if (parent != null) {
        parent.attachChild(model);

    }
    model.setLocalTranslation(initPosition);
    model.setLocalRotation(initRotation);
    model.setLocalScale(initScale);

    logger.log(Level.INFO, "Created physics ragdoll for skeleton {0}", skeleton);
}
 
Example 19
Source File: BlenderLoader.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 3 votes vote down vote up
/**
 * This method indicates if the given spatial is a root object. It means it
 * has no parent or is directly attached to one of the already loaded scene
 * nodes.
 * 
 * @param loadingResults
 *            loading results containing the scene nodes
 * @param spatial
 *            spatial object
 * @return <b>true</b> if the given spatial is a root object and
 *         <b>false</b> otherwise
 */
protected boolean isRootObject(LoadingResults loadingResults, Spatial spatial) {
    if (spatial.getParent() == null) {
        return true;
    }
    for (Node scene : loadingResults.getScenes()) {
        if (spatial.getParent().equals(scene)) {
            return true;
        }
    }
    return false;
}
 
Example 20
Source File: ApplyScaleToPhysicsControlsHandler.java    From jmonkeybuilder with Apache License 2.0 2 votes vote down vote up
/**
 * The condition to find a model root.
 *
 * @param spatial the model.
 * @return true if the node is model root.
 */
@FromAnyThread
protected static boolean isModelRoot(@NotNull final Spatial spatial) {
    final Node parent = spatial.getParent();
    return parent == null || parent.getUserData(AbstractSceneEditor3DPart.KEY_MODEL_NODE) != null;
}