Java Code Examples for com.jme3.scene.Geometry#getMaterial()

The following examples show how to use com.jme3.scene.Geometry#getMaterial() . 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: TestTransparentCartoonEdge.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void makeToonish(Spatial spatial){
        if (spatial instanceof Node){
            Node n = (Node) spatial;
            for (Spatial child : n.getChildren())
                makeToonish(child);
        }else if (spatial instanceof Geometry){
            Geometry g = (Geometry) spatial;
            Material m = g.getMaterial();
            if (m.getMaterialDef().getName().equals("Phong Lighting")){
                Texture t = assetManager.loadTexture("Textures/ColorRamp/toon.png");
//                t.setMinFilter(Texture.MinFilter.NearestNoMipMaps);
//                t.setMagFilter(Texture.MagFilter.Nearest);
                m.setTexture("ColorRamp", t);
                m.setBoolean("UseMaterialColors", true);
                m.setColor("Specular", ColorRGBA.Black);
                m.setColor("Diffuse", ColorRGBA.White);
                m.setBoolean("VertexLighting", true);
            }
        }
    }
 
Example 2
Source File: OpaqueComparator.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public int compare(Geometry o1, Geometry o2) {
    Material m1 = o1.getMaterial();
    Material m2 = o2.getMaterial();

    int sortId = m1.compareTo(m2);

    if (sortId == 0){
        // use the same shader.
        // sort front-to-back then.
        float d1 = distanceToCam(o1);
        float d2 = distanceToCam(o2);

        if (d1 == d2)
            return 0;
        else if (d1 < d2)
            return -1;
        else
            return 1;
    }else{
        return sortId;
    }
}
 
Example 3
Source File: TestCartoonEdge.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void makeToonish(Spatial spatial){
        if (spatial instanceof Node){
            Node n = (Node) spatial;
            for (Spatial child : n.getChildren())
                makeToonish(child);
        }else if (spatial instanceof Geometry){
            Geometry g = (Geometry) spatial;
            Material m = g.getMaterial();
            if (m.getMaterialDef().getName().equals("Phong Lighting")){
                Texture t = assetManager.loadTexture("Textures/ColorRamp/toon.png");
//                t.setMinFilter(Texture.MinFilter.NearestNoMipMaps);
//                t.setMagFilter(Texture.MagFilter.Nearest);
                m.setTexture("ColorRamp", t);
                m.setBoolean("UseMaterialColors", true);
                m.setColor("Specular", ColorRGBA.Black);
                m.setColor("Diffuse", ColorRGBA.White);
                m.setBoolean("VertexLighting", true);
            }
        }
    }
 
Example 4
Source File: TestTransparentCartoonEdge.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void makeToonish(Spatial spatial){
        if (spatial instanceof Node){
            Node n = (Node) spatial;
            for (Spatial child : n.getChildren())
                makeToonish(child);
        }else if (spatial instanceof Geometry){
            Geometry g = (Geometry) spatial;
            Material m = g.getMaterial();
            if (m.getMaterialDef().getName().equals("Phong Lighting")){
                Texture t = assetManager.loadTexture("Textures/ColorRamp/toon.png");
//                t.setMinFilter(Texture.MinFilter.NearestNoMipMaps);
//                t.setMagFilter(Texture.MagFilter.Nearest);
                m.setTexture("ColorRamp", t);
                m.setBoolean("UseMaterialColors", true);
                m.setColor("Specular", ColorRGBA.Black);
                m.setColor("Diffuse", ColorRGBA.White);
                m.setBoolean("VertexLighting", true);
            }
        }
    }
 
Example 5
Source File: OpaqueComparator.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public int compare(Geometry o1, Geometry o2) {
    Material m1 = o1.getMaterial();
    Material m2 = o2.getMaterial();
    
    int compareResult = Integer.compare(m1.getSortId(), m2.getSortId());
    if (compareResult == 0){
        // use the same shader.
        // sort front-to-back then.
        float d1 = distanceToCam(o1);
        float d2 = distanceToCam(o2);

        if (d1 == d2)
            return 0;
        else if (d1 < d2)
            return -1;
        else
            return 1;
    }else{
        return compareResult;
    }
}
 
Example 6
Source File: TestCartoonEdge.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void makeToonish(Spatial spatial){
        if (spatial instanceof Node){
            Node n = (Node) spatial;
            for (Spatial child : n.getChildren())
                makeToonish(child);
        }else if (spatial instanceof Geometry){
            Geometry g = (Geometry) spatial;
            Material m = g.getMaterial();
            if (m.getMaterialDef().getMaterialParam("UseMaterialColors") != null) {
                Texture t = assetManager.loadTexture("Textures/ColorRamp/toon.png");
//                t.setMinFilter(Texture.MinFilter.NearestNoMipMaps);
//                t.setMagFilter(Texture.MagFilter.Nearest);
                m.setTexture("ColorRamp", t);
                m.setBoolean("UseMaterialColors", true);
                m.setColor("Specular", ColorRGBA.Black);
                m.setColor("Diffuse", ColorRGBA.White);
                m.setBoolean("VertexLighting", true);
            }
        }
    }
 
Example 7
Source File: CreateSkyDialog.java    From jmonkeybuilder with Apache License 2.0 6 votes vote down vote up
/**
 * Create a material of the geometry as a file if need.
 *
 * @param geometry the sky geometry.
 */
@BackgroundThread
private @NotNull Material createMaterialFileIfNeed(@NotNull final Geometry geometry) {

    final TextField materialNameField = getMaterialNameField();
    final ChooseFolderControl materialFolderControl = getMaterialFolderControl();

    final Material material = geometry.getMaterial();
    final String content = MaterialSerializer.serializeToString(material);

    final Path folder = materialFolderControl.getFolder();
    final Path materialFile = folder.resolve(materialNameField.getText() + "." + FileExtensions.JME_MATERIAL);

    try {
        Files.write(materialFile, content.getBytes("UTF-8"), WRITE, TRUNCATE_EXISTING, CREATE);
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }

    final Path assetFile = EditorUtil.getAssetFile(materialFile);
    final String assetPath = EditorUtil.toAssetPath(assetFile);
    final AssetManager assetManager = EditorUtil.getAssetManager();
    return assetManager.loadMaterial(assetPath);
}
 
Example 8
Source File: AbstractModelFileConverter.java    From jmonkeybuilder with Apache License 2.0 6 votes vote down vote up
/**
 * Generate names for the materials.
 */
private void generateNames(@NotNull final ObjectDictionary<String, Geometry> mapping,
                           @NotNull final Geometry geometry) {

    final Material material = geometry.getMaterial();
    final String originalName = material.getName();
    final String name = StringUtils.isEmpty(geometry.getName()) ? "geom" : geometry.getName();

    String resultName = StringUtils.isEmpty(originalName) ? "embedded-mat-" + name : originalName;

    if (!mapping.containsKey(resultName)) {
        mapping.put(resultName, geometry);
    } else {
        for (int i = 1; mapping.containsKey(resultName); i++) {
            resultName = (StringUtils.isEmpty(originalName) ? "embedded-mat-" : originalName) + name + "_" + i;
        }
        mapping.put(resultName, geometry);
    }
}
 
Example 9
Source File: TextureLayerSettings.java    From jmonkeybuilder with Apache License 2.0 6 votes vote down vote up
@JmeThread
private void updateTexture(@Nullable final Texture texture, @NotNull final String paramName,
                           @NotNull final Geometry geometry) {

    final Material material = geometry.getMaterial();
    final MatParam matParam = material.getParam(paramName);
    if (matParam == null && texture == null) {
        return;
    }

    if (texture == null) {
        material.clearParam(matParam.getName());
    } else {
        material.setTexture(paramName, texture);
    }
}
 
Example 10
Source File: GeometryTreeNode.java    From jmonkeybuilder with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(@NotNull final ChangeConsumer changeConsumer, @NotNull final Object object,
                   final boolean isCopy) {

    final Geometry geometry = getElement();

    if (object instanceof Material) {

        final Material material = (Material) object;

        if (isCopy) {

            final Material clone = material.clone();
            final PropertyOperation<ChangeConsumer, Geometry, Material> operation =
                    new PropertyOperation<>(geometry, "Material", clone, geometry.getMaterial());
            operation.setApplyHandler(Geometry::setMaterial);

            changeConsumer.execute(operation);
        }
    }

    super.accept(changeConsumer, object, isCopy);
}
 
Example 11
Source File: GeometryTreeNode.java    From jmonkeybuilder with Apache License 2.0 6 votes vote down vote up
@Override
public @NotNull Array<TreeNode<?>> getChildren(@NotNull final NodeTree<?> nodeTree) {
    if (!(nodeTree instanceof ModelNodeTree)) return TreeNode.EMPTY_ARRAY;

    final Array<TreeNode<?>> result = ArrayFactory.newArray(TreeNode.class);

    final Geometry geometry = getElement();
    final Mesh mesh = geometry.getMesh();
    final Material material = geometry.getMaterial();

    if (mesh != null) result.add(FACTORY_REGISTRY.createFor(mesh));

    result.add(FACTORY_REGISTRY.createFor(material));
    result.addAll(super.getChildren(nodeTree));

    return result;
}
 
Example 12
Source File: AbstractModelFileConverter.java    From jmonkeybuilder with Apache License 2.0 5 votes vote down vote up
private void checkAndAdd(@NotNull final Array<Geometry> geometries, @NotNull final Geometry geometry) {

        final Material material = geometry.getMaterial();
        final AssetKey key = material.getKey();

        if (key == null) {
            geometries.add(geometry);
        }
    }
 
Example 13
Source File: AbstractModelFileConverter.java    From jmonkeybuilder with Apache License 2.0 5 votes vote down vote up
/**
 * Store the embedded materials.
 *
 * @param materialsFolder the materials destination folder.
 * @param canOverwrite    can we overwrite exists materials.
 * @param materialName    the material name.
 * @param geometry        the geometry.
 */
private void storeMaterials(@NotNull final Path materialsFolder, final boolean canOverwrite,
                            @NotNull final String materialName, @NotNull final Geometry geometry) {

    final Path resultFile = materialsFolder.resolve(normalizeName(materialName) + "." + FileExtensions.JME_MATERIAL);
    final Path assetFile = getAssetFile(resultFile);

    if (assetFile == null) {
        LOGGER.warning("Can't get asset file for the file " + resultFile);
        return;
    }

    final Material currentMaterial = geometry.getMaterial();

    if (!Files.exists(resultFile) || canOverwrite) {
        try (PrintWriter pout = new PrintWriter(Files.newOutputStream(resultFile, WRITE, TRUNCATE_EXISTING, CREATE))) {
            pout.println(MaterialSerializer.serializeToString(currentMaterial));
        } catch (final IOException e) {
            EditorUtil.handleException(LOGGER, this, e);
        }
    }

    final String assetPath = toAssetPath(assetFile);

    final AssetManager assetManager = EditorUtil.getAssetManager();
    geometry.setMaterial(assetManager.loadMaterial(assetPath));
}
 
Example 14
Source File: TextureAtlas.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static Texture getMaterialTexture(Geometry geometry, String mapName) {
    Material mat = geometry.getMaterial();
    if (mat == null || mat.getParam(mapName) == null || !(mat.getParam(mapName) instanceof MatParamTexture)) {
        return null;
    }
    MatParamTexture param = (MatParamTexture) mat.getParam(mapName);
    Texture texture = param.getTextureValue();
    if (texture == null) {
        return null;
    }
    return texture;


}
 
Example 15
Source File: RenderManager.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Preloads a scene for rendering.
 * <p>
 * After invocation of this method, the underlying
 * renderer would have uploaded any textures, shaders and meshes
 * used by the given scene to the video driver. 
 * Using this method is useful when wishing to avoid the initial pause
 * when rendering a scene for the first time. Note that it is not 
 * guaranteed that the underlying renderer will actually choose to upload
 * the data to the GPU so some pause is still to be expected.
 * 
 * @param scene The scene to preload
 */
public void preloadScene(Spatial scene) {
    if (scene instanceof Node) {
        // recurse for all children
        Node n = (Node) scene;
        List<Spatial> children = n.getChildren();
        for (int i = 0; i < children.size(); i++) {
            preloadScene(children.get(i));
        }
    } 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());
        }

        gm.getMaterial().preload(this);
        Mesh mesh = gm.getMesh();
        if (mesh != null) {
            for (Entry<VertexBuffer> entry : mesh.getBuffers()) {
                VertexBuffer buf = entry.getValue();
                if (buf.getData() != null) {
                    renderer.updateBufferData(buf);
                }
            }
        }
    }
}
 
Example 16
Source File: GeometryPropertyBuilder.java    From jmonkeybuilder with Apache License 2.0 4 votes vote down vote up
@Override
@FxThread
protected void buildForImpl(@NotNull final Object object, @Nullable final Object parent,
                            @NotNull final VBox container, @NotNull final ModelChangeConsumer changeConsumer) {

    if (!(object instanceof Geometry)) return;

    final Geometry geometry = (Geometry) object;
    final BoundingVolume modelBound = geometry.getModelBound();
    final int lodLevel = geometry.getLodLevel();

    final DefaultPropertyControl<ModelChangeConsumer, Geometry, BoundingVolume> boundingVolumeControl =
            new DefaultPropertyControl<>(modelBound, Messages.BOUNDING_VOLUME_MODEL_PROPERTY_CONTROL_NAME, changeConsumer);

    boundingVolumeControl.setToStringFunction(BOUNDING_VOLUME_TO_STRING);
    boundingVolumeControl.reload();
    boundingVolumeControl.setEditObject(geometry);

    if (canEditMaterial(geometry)) {

        final Material material = geometry.getMaterial();
        final MaterialKey materialKey = (MaterialKey) material.getKey();

        final MaterialKeyPropertyControl<ModelChangeConsumer, Geometry> materialControl =
                new MaterialKeyPropertyControl<>(materialKey, Messages.MODEL_PROPERTY_MATERIAL, changeConsumer);

        materialControl.setApplyHandler(MATERIAL_APPLY_HANDLER);
        materialControl.setSyncHandler(MATERIAL_SYNC_HANDLER);
        materialControl.setEditObject(geometry);

        FXUtils.addToPane(materialControl, container);
    }

    FXUtils.addToPane(boundingVolumeControl, container);

    buildSplitLine(container);

    final LodLevelPropertyControl<ModelChangeConsumer> lodLevelControl =
            new LodLevelPropertyControl<>(lodLevel, Messages.MODEL_PROPERTY_LOD, changeConsumer);

    lodLevelControl.setApplyHandler(Geometry::setLodLevel);
    lodLevelControl.setSyncHandler(Geometry::getLodLevel);
    lodLevelControl.setEditObject(geometry, true);

    FXUtils.addToPane(lodLevelControl, container);
}
 
Example 17
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 18
Source File: ModelImportDialog.java    From jmonkeybuilder with Apache License 2.0 4 votes vote down vote up
/**
 * Export all embedded materials from the external model.
 *
 * @param materialsFolder    the materials folder.
 * @param overwriteMaterials true if we can overwrite existing materials.
 * @param geometries         the found geometries in the model.
 */
@BackgroundThread
private void exportMaterials(@NotNull final Path materialsFolder, final boolean overwriteMaterials,
                             @NotNull final Array<Geometry> geometries) {

    if (geometries.isEmpty()) {
        return;
    }

    final ObjectDictionary<String, String> resultNameToKey = DictionaryFactory.newObjectDictionary();

    for (final Geometry geometry : geometries) {

        final Material material = geometry.getMaterial();
        final String originalName = material.getName();
        final String name = StringUtils.isEmpty(geometry.getName()) ? "geom" : geometry.getName();
        final String resultName = StringUtils.isEmpty(originalName) ? "embedded-mat-" + name : originalName;

        final String newKey = resultNameToKey.get(resultName);
        if (newKey != null) {
            material.setKey(new MaterialKey(newKey));
            continue;
        }

        final Path resultFile = materialsFolder.resolve(resultName + "." + FileExtensions.JME_MATERIAL);

        if (!Files.exists(resultFile) || overwriteMaterials) {
            try (PrintWriter pout = new PrintWriter(Files.newOutputStream(resultFile, WRITE, TRUNCATE_EXISTING, CREATE))) {
                pout.println(MaterialSerializer.serializeToString(material));
            } catch (final IOException e) {
                throw new RuntimeException(e);
            }
        }

        final Path assetFile = notNull(getAssetFile(resultFile));
        final String assetPath = toAssetPath(assetFile);

        material.setKey(new MaterialKey(assetPath));
        resultNameToKey.put(resultName, assetPath);
    }
}