Search in sources :

Example 21 with BlenderFileException

use of com.jme3.scene.plugins.blender.file.BlenderFileException in project jmonkeyengine by jMonkeyEngine.

the class ConstraintDefinitionFactory method createConstraintDefinition.

/**
     * This method creates the constraint instance.
     * 
     * @param constraintStructure
     *            the constraint's structure (bConstraint clss in blender 2.49).
     *            If the value is null the NullConstraint is created.
     * @param blenderContext
     *            the blender context
     * @throws BlenderFileException
     *             this exception is thrown when the blender file is somehow
     *             corrupted
     */
public static ConstraintDefinition createConstraintDefinition(Structure constraintStructure, String constraintName, Long ownerOMA, BlenderContext blenderContext) throws BlenderFileException {
    if (constraintStructure == null) {
        return new ConstraintDefinitionNull(null, ownerOMA, blenderContext);
    }
    String constraintClassName = constraintStructure.getType();
    Class<? extends ConstraintDefinition> constraintDefinitionClass = CONSTRAINT_CLASSES.get(constraintClassName);
    if (constraintDefinitionClass != null) {
        try {
            ConstraintDefinition def = (ConstraintDefinition) constraintDefinitionClass.getDeclaredConstructors()[0].newInstance(constraintStructure, ownerOMA, blenderContext);
            def.setConstraintName(constraintName);
            return def;
        } catch (IllegalArgumentException e) {
            throw new BlenderFileException(e.getLocalizedMessage(), e);
        } catch (SecurityException e) {
            throw new BlenderFileException(e.getLocalizedMessage(), e);
        } catch (InstantiationException e) {
            throw new BlenderFileException(e.getLocalizedMessage(), e);
        } catch (IllegalAccessException e) {
            throw new BlenderFileException(e.getLocalizedMessage(), e);
        } catch (InvocationTargetException e) {
            throw new BlenderFileException(e.getLocalizedMessage(), e);
        }
    } else {
        String unsupportedConstraintClassName = UNSUPPORTED_CONSTRAINTS.get(constraintClassName);
        if (unsupportedConstraintClassName != null) {
            return new UnsupportedConstraintDefinition(unsupportedConstraintClassName);
        } else {
            throw new BlenderFileException("Unknown constraint type: " + constraintClassName);
        }
    }
}
Also used : BlenderFileException(com.jme3.scene.plugins.blender.file.BlenderFileException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 22 with BlenderFileException

use of com.jme3.scene.plugins.blender.file.BlenderFileException in project jmonkeyengine by jMonkeyEngine.

the class AbstractBlenderHelper method loadProperties.

/**
     * This method loads the properties if they are available and defined for the structure.
     * @param structure
     *            the structure we read the properties from
     * @param blenderContext
     *            the blender context
     * @return loaded properties or null if they are not available
     * @throws BlenderFileException
     *             an exception is thrown when the blend file is somehow corrupted
     */
protected Properties loadProperties(Structure structure, BlenderContext blenderContext) throws BlenderFileException {
    Properties properties = null;
    Structure id = (Structure) structure.getFieldValue("ID");
    if (id != null) {
        Pointer pProperties = (Pointer) id.getFieldValue("properties");
        if (pProperties.isNotNull()) {
            Structure propertiesStructure = pProperties.fetchData().get(0);
            properties = new Properties();
            properties.load(propertiesStructure, blenderContext);
        }
    }
    return properties;
}
Also used : Pointer(com.jme3.scene.plugins.blender.file.Pointer) Properties(com.jme3.scene.plugins.blender.objects.Properties) Structure(com.jme3.scene.plugins.blender.file.Structure)

Example 23 with BlenderFileException

use of com.jme3.scene.plugins.blender.file.BlenderFileException in project jmonkeyengine by jMonkeyEngine.

the class AbstractBlenderHelper method loadLibrary.

/**
     * The method loads library of a given ID from linked blender file.
     * @param id
     *            the ID of the linked feature (it contains its name and blender path)
     * @return loaded feature or null if none was found
     * @throws BlenderFileException
     *             and exception is throw when problems with reading a blend file occur
     */
protected Object loadLibrary(Structure id) throws BlenderFileException {
    Pointer pLib = (Pointer) id.getFieldValue("lib");
    if (pLib.isNotNull()) {
        // we need full name with the prefix
        String fullName = id.getFieldValue("name").toString();
        String nameOfFeatureToLoad = id.getName();
        Structure library = pLib.fetchData().get(0);
        String path = library.getFieldValue("filepath").toString();
        if (!blenderContext.getLinkedFeatures().keySet().contains(path)) {
            Spatial loadedAsset = null;
            BlenderKey blenderKey = new BlenderKey(path);
            blenderKey.setLoadUnlinkedAssets(true);
            try {
                loadedAsset = blenderContext.getAssetManager().loadAsset(blenderKey);
            } catch (AssetNotFoundException e) {
                LOGGER.log(Level.FINEST, "Cannot locate linked resource at path: {0}.", path);
            }
            if (loadedAsset != null) {
                Map<String, Map<String, Object>> linkedData = loadedAsset.getUserData("linkedData");
                for (Entry<String, Map<String, Object>> entry : linkedData.entrySet()) {
                    String linkedDataFilePath = "this".equals(entry.getKey()) ? path : entry.getKey();
                    blenderContext.getLinkedFeatures().put(linkedDataFilePath, entry.getValue());
                }
            } else {
                LOGGER.log(Level.WARNING, "No features loaded from path: {0}.", path);
            }
        }
        Object result = blenderContext.getLinkedFeature(path, fullName);
        if (result == null) {
            LOGGER.log(Level.WARNING, "Could NOT find asset named {0} in the library of path: {1}.", new Object[] { nameOfFeatureToLoad, path });
        } else {
            blenderContext.addLoadedFeatures(id.getOldMemoryAddress(), LoadedDataType.STRUCTURE, id);
            blenderContext.addLoadedFeatures(id.getOldMemoryAddress(), LoadedDataType.FEATURE, result);
        }
        return result;
    } else {
        LOGGER.warning("Library link points to nothing!");
    }
    return null;
}
Also used : Spatial(com.jme3.scene.Spatial) Pointer(com.jme3.scene.plugins.blender.file.Pointer) BlenderKey(com.jme3.asset.BlenderKey) AssetNotFoundException(com.jme3.asset.AssetNotFoundException) Structure(com.jme3.scene.plugins.blender.file.Structure) Map(java.util.Map)

Example 24 with BlenderFileException

use of com.jme3.scene.plugins.blender.file.BlenderFileException in project jmonkeyengine by jMonkeyEngine.

the class ObjectHelper method toObject.

/**
     * This method reads the given structure and createn an object that
     * represents the data.
     * 
     * @param objectStructure
     *            the object's structure
     * @param blenderContext
     *            the blender context
     * @return blener's object representation or null if its type is excluded from loading
     * @throws BlenderFileException
     *             an exception is thrown when the given data is inapropriate
     */
public Object toObject(Structure objectStructure, BlenderContext blenderContext) throws BlenderFileException {
    Object loadedResult = blenderContext.getLoadedFeature(objectStructure.getOldMemoryAddress(), LoadedDataType.FEATURE);
    if (loadedResult != null) {
        return loadedResult;
    }
    LOGGER.fine("Loading blender object.");
    if ("ID".equals(objectStructure.getType())) {
        Node object = (Node) this.loadLibrary(objectStructure);
        if (object.getParent() != null) {
            LOGGER.log(Level.FINEST, "Detaching object {0}, loaded from external file, from its parent.", object);
            object.getParent().detachChild(object);
        }
        return object;
    }
    int type = ((Number) objectStructure.getFieldValue("type")).intValue();
    ObjectType objectType = ObjectType.valueOf(type);
    LOGGER.log(Level.FINE, "Type of the object: {0}.", objectType);
    int lay = ((Number) objectStructure.getFieldValue("lay")).intValue();
    if ((lay & blenderContext.getBlenderKey().getLayersToLoad()) == 0) {
        LOGGER.fine("The layer this object is located in is not included in loading.");
        return null;
    }
    blenderContext.pushParent(objectStructure);
    String name = objectStructure.getName();
    LOGGER.log(Level.FINE, "Loading obejct: {0}", name);
    int restrictflag = ((Number) objectStructure.getFieldValue("restrictflag")).intValue();
    boolean visible = (restrictflag & 0x01) != 0;
    Pointer pParent = (Pointer) objectStructure.getFieldValue("parent");
    Object parent = blenderContext.getLoadedFeature(pParent.getOldMemoryAddress(), LoadedDataType.FEATURE);
    if (parent == null && pParent.isNotNull()) {
        Structure parentStructure = pParent.fetchData().get(0);
        parent = this.toObject(parentStructure, blenderContext);
    }
    Transform t = this.getTransformation(objectStructure, blenderContext);
    LOGGER.log(Level.FINE, "Importing object of type: {0}", objectType);
    Node result = null;
    try {
        switch(objectType) {
            case LATTICE:
            case METABALL:
            case TEXT:
            case WAVE:
                LOGGER.log(Level.WARNING, "{0} type is not supported but the node will be returned in order to keep parent - child relationship.", objectType);
            case EMPTY:
            case ARMATURE:
                // need to use an empty node to properly create
                // parent-children relationships between nodes
                result = new Node(name);
                break;
            case MESH:
                result = new Node(name);
                MeshHelper meshHelper = blenderContext.getHelper(MeshHelper.class);
                Pointer pMesh = (Pointer) objectStructure.getFieldValue("data");
                List<Structure> meshesArray = pMesh.fetchData();
                TemporalMesh temporalMesh = meshHelper.toTemporalMesh(meshesArray.get(0), blenderContext);
                if (temporalMesh != null) {
                    result.attachChild(temporalMesh);
                }
                break;
            case SURF:
            case CURVE:
                result = new Node(name);
                Pointer pCurve = (Pointer) objectStructure.getFieldValue("data");
                if (pCurve.isNotNull()) {
                    CurvesHelper curvesHelper = blenderContext.getHelper(CurvesHelper.class);
                    Structure curveData = pCurve.fetchData().get(0);
                    TemporalMesh curvesTemporalMesh = curvesHelper.toCurve(curveData, blenderContext);
                    if (curvesTemporalMesh != null) {
                        result.attachChild(curvesTemporalMesh);
                    }
                }
                break;
            case LAMP:
                Pointer pLamp = (Pointer) objectStructure.getFieldValue("data");
                if (pLamp.isNotNull()) {
                    LightHelper lightHelper = blenderContext.getHelper(LightHelper.class);
                    List<Structure> lampsArray = pLamp.fetchData();
                    Light light = lightHelper.toLight(lampsArray.get(0), blenderContext);
                    if (light == null) {
                        // probably some light type is not supported, just create a node so that we can maintain child-parent relationship for nodes
                        result = new Node(name);
                    } else {
                        result = new LightNode(name, light);
                    }
                }
                break;
            case CAMERA:
                Pointer pCamera = (Pointer) objectStructure.getFieldValue("data");
                if (pCamera.isNotNull()) {
                    CameraHelper cameraHelper = blenderContext.getHelper(CameraHelper.class);
                    List<Structure> camerasArray = pCamera.fetchData();
                    Camera camera = cameraHelper.toCamera(camerasArray.get(0), blenderContext);
                    if (camera == null) {
                        // just create a node so that we can maintain child-parent relationship for nodes
                        result = new Node(name);
                    } else {
                        result = new CameraNode(name, camera);
                    }
                }
                break;
            default:
                LOGGER.log(Level.WARNING, "Unsupported object type: {0}", type);
        }
        if (result != null) {
            LOGGER.fine("Storing loaded feature in blender context and applying markers (those will be removed before the final result is released).");
            Long oma = objectStructure.getOldMemoryAddress();
            blenderContext.addLoadedFeatures(oma, LoadedDataType.STRUCTURE, objectStructure);
            blenderContext.addLoadedFeatures(oma, LoadedDataType.FEATURE, result);
            blenderContext.addMarker(OMA_MARKER, result, objectStructure.getOldMemoryAddress());
            if (objectType == ObjectType.ARMATURE) {
                blenderContext.addMarker(ARMATURE_NODE_MARKER, result, Boolean.TRUE);
            }
            result.setLocalTransform(t);
            result.setCullHint(visible ? CullHint.Always : CullHint.Inherit);
            if (parent instanceof Node) {
                ((Node) parent).attachChild(result);
            }
            LOGGER.fine("Reading and applying object's modifiers.");
            ModifierHelper modifierHelper = blenderContext.getHelper(ModifierHelper.class);
            Collection<Modifier> modifiers = modifierHelper.readModifiers(objectStructure, blenderContext);
            for (Modifier modifier : modifiers) {
                modifier.apply(result, blenderContext);
            }
            if (result.getChildren() != null && result.getChildren().size() > 0) {
                if (result.getChildren().size() == 1 && result.getChild(0) instanceof TemporalMesh) {
                    LOGGER.fine("Converting temporal mesh into jme geometries.");
                    ((TemporalMesh) result.getChild(0)).toGeometries();
                }
                LOGGER.fine("Applying proper scale to the geometries.");
                for (Spatial child : result.getChildren()) {
                    if (child instanceof Geometry) {
                        this.flipMeshIfRequired((Geometry) child, child.getWorldScale());
                    }
                }
            }
            // I prefer do compute bounding box here than read it from the file
            result.updateModelBound();
            LOGGER.fine("Applying animations to the object if such are defined.");
            AnimationHelper animationHelper = blenderContext.getHelper(AnimationHelper.class);
            animationHelper.applyAnimations(result, blenderContext.getBlenderKey().getAnimationMatchMethod());
            LOGGER.fine("Loading constraints connected with this object.");
            ConstraintHelper constraintHelper = blenderContext.getHelper(ConstraintHelper.class);
            constraintHelper.loadConstraints(objectStructure, blenderContext);
            LOGGER.fine("Loading custom properties.");
            if (blenderContext.getBlenderKey().isLoadObjectProperties()) {
                Properties properties = this.loadProperties(objectStructure, blenderContext);
                // each value and set it to Spatial
                if (properties != null && properties.getValue() != null) {
                    this.applyProperties(result, properties);
                }
            }
        }
    } finally {
        blenderContext.popParent();
    }
    return result;
}
Also used : LightNode(com.jme3.scene.LightNode) Node(com.jme3.scene.Node) CameraNode(com.jme3.scene.CameraNode) CameraNode(com.jme3.scene.CameraNode) Pointer(com.jme3.scene.plugins.blender.file.Pointer) ModifierHelper(com.jme3.scene.plugins.blender.modifiers.ModifierHelper) LightNode(com.jme3.scene.LightNode) Light(com.jme3.light.Light) Camera(com.jme3.renderer.Camera) Structure(com.jme3.scene.plugins.blender.file.Structure) Modifier(com.jme3.scene.plugins.blender.modifiers.Modifier) CameraHelper(com.jme3.scene.plugins.blender.cameras.CameraHelper) AnimationHelper(com.jme3.scene.plugins.blender.animations.AnimationHelper) ConstraintHelper(com.jme3.scene.plugins.blender.constraints.ConstraintHelper) CullHint(com.jme3.scene.Spatial.CullHint) TemporalMesh(com.jme3.scene.plugins.blender.meshes.TemporalMesh) Geometry(com.jme3.scene.Geometry) Spatial(com.jme3.scene.Spatial) CurvesHelper(com.jme3.scene.plugins.blender.curves.CurvesHelper) Transform(com.jme3.math.Transform) LightHelper(com.jme3.scene.plugins.blender.lights.LightHelper) MeshHelper(com.jme3.scene.plugins.blender.meshes.MeshHelper)

Example 25 with BlenderFileException

use of com.jme3.scene.plugins.blender.file.BlenderFileException in project jmonkeyengine by jMonkeyEngine.

the class Properties method load.

/**
     * This method loads the property from the belnder file.
     * @param idPropertyStructure
     *            the ID structure constining the property
     * @param blenderContext
     *            the blender context
     * @throws BlenderFileException
     *             an exception is thrown when the belnder file is somehow invalid
     */
public void load(Structure idPropertyStructure, BlenderContext blenderContext) throws BlenderFileException {
    name = idPropertyStructure.getFieldValue("name").toString();
    if (name == null || name.length() == 0) {
        name = DEFAULT_NAME;
    }
    subType = ((Number) idPropertyStructure.getFieldValue("subtype")).intValue();
    type = ((Number) idPropertyStructure.getFieldValue("type")).intValue();
    // reading the data
    Structure data = (Structure) idPropertyStructure.getFieldValue("data");
    int len = ((Number) idPropertyStructure.getFieldValue("len")).intValue();
    switch(type) {
        case IDP_STRING:
            {
                Pointer pointer = (Pointer) data.getFieldValue("pointer");
                BlenderInputStream bis = blenderContext.getInputStream();
                FileBlockHeader dataFileBlock = blenderContext.getFileBlock(pointer.getOldMemoryAddress());
                bis.setPosition(dataFileBlock.getBlockPosition());
                value = bis.readString();
                break;
            }
        case IDP_INT:
            int intValue = ((Number) data.getFieldValue("val")).intValue();
            value = Integer.valueOf(intValue);
            break;
        case IDP_FLOAT:
            int floatValue = ((Number) data.getFieldValue("val")).intValue();
            value = Float.valueOf(Float.intBitsToFloat(floatValue));
            break;
        case IDP_ARRAY:
            {
                Pointer pointer = (Pointer) data.getFieldValue("pointer");
                BlenderInputStream bis = blenderContext.getInputStream();
                FileBlockHeader dataFileBlock = blenderContext.getFileBlock(pointer.getOldMemoryAddress());
                bis.setPosition(dataFileBlock.getBlockPosition());
                int elementAmount = dataFileBlock.getSize();
                switch(subType) {
                    case IDP_INT:
                        elementAmount /= 4;
                        int[] intList = new int[elementAmount];
                        for (int i = 0; i < elementAmount; ++i) {
                            intList[i] = bis.readInt();
                        }
                        value = intList;
                        break;
                    case IDP_FLOAT:
                        elementAmount /= 4;
                        float[] floatList = new float[elementAmount];
                        for (int i = 0; i < elementAmount; ++i) {
                            floatList[i] = bis.readFloat();
                        }
                        value = floatList;
                        break;
                    case IDP_DOUBLE:
                        elementAmount /= 8;
                        double[] doubleList = new double[elementAmount];
                        for (int i = 0; i < elementAmount; ++i) {
                            doubleList[i] = bis.readDouble();
                        }
                        value = doubleList;
                        break;
                    default:
                        throw new IllegalStateException("Invalid array subtype: " + subType);
                }
            }
        case IDP_GROUP:
            Structure group = (Structure) data.getFieldValue("group");
            List<Structure> dataList = group.evaluateListBase();
            List<Properties> subProperties = new ArrayList<Properties>(len);
            for (Structure d : dataList) {
                Properties properties = new Properties();
                properties.load(d, blenderContext);
                subProperties.add(properties);
            }
            value = subProperties;
            break;
        case IDP_DOUBLE:
            int doublePart1 = ((Number) data.getFieldValue("val")).intValue();
            int doublePart2 = ((Number) data.getFieldValue("val2")).intValue();
            long doubleVal = (long) doublePart2 << 32 | doublePart1;
            value = Double.valueOf(Double.longBitsToDouble(doubleVal));
            break;
        case IDP_IDPARRAY:
            {
                Pointer pointer = (Pointer) data.getFieldValue("pointer");
                List<Structure> arrays = pointer.fetchData();
                List<Object> result = new ArrayList<Object>(arrays.size());
                Properties temp = new Properties();
                for (Structure array : arrays) {
                    temp.load(array, blenderContext);
                    result.add(temp.value);
                }
                value = result;
                break;
            }
        case IDP_NUMTYPES:
            throw new UnsupportedOperationException();
        // return null;
        default:
            throw new IllegalStateException("Unknown custom property type: " + type);
    }
    this.completeLoading();
}
Also used : FileBlockHeader(com.jme3.scene.plugins.blender.file.FileBlockHeader) ArrayList(java.util.ArrayList) Pointer(com.jme3.scene.plugins.blender.file.Pointer) BlenderInputStream(com.jme3.scene.plugins.blender.file.BlenderInputStream) List(java.util.List) ArrayList(java.util.ArrayList) Structure(com.jme3.scene.plugins.blender.file.Structure)

Aggregations

Structure (com.jme3.scene.plugins.blender.file.Structure)31 Pointer (com.jme3.scene.plugins.blender.file.Pointer)26 ArrayList (java.util.ArrayList)19 BlenderFileException (com.jme3.scene.plugins.blender.file.BlenderFileException)10 Vector3f (com.jme3.math.Vector3f)7 FileBlockHeader (com.jme3.scene.plugins.blender.file.FileBlockHeader)7 List (java.util.List)7 DynamicArray (com.jme3.scene.plugins.blender.file.DynamicArray)6 TemporalMesh (com.jme3.scene.plugins.blender.meshes.TemporalMesh)5 Map (java.util.Map)5 Node (com.jme3.scene.Node)4 AnimationHelper (com.jme3.scene.plugins.blender.animations.AnimationHelper)4 MeshHelper (com.jme3.scene.plugins.blender.meshes.MeshHelper)4 ObjectHelper (com.jme3.scene.plugins.blender.objects.ObjectHelper)4 Texture (com.jme3.texture.Texture)4 HashMap (java.util.HashMap)4 BlenderKey (com.jme3.asset.BlenderKey)3 Light (com.jme3.light.Light)3 ColorRGBA (com.jme3.math.ColorRGBA)3 Spline (com.jme3.math.Spline)3