Java Code Examples for com.jme3.material.Material

The following are top voted examples for showing how to use com.jme3.material.Material. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: JMELink-SP   File: PBRSubstance.java   View source code 6 votes vote down vote up
@Override
public MaterialMap toMaterial(AssetManager am, Substance substance, String substance_assets_path) {
	Material mat=new Material(am,"Common/MatDefs/Light/PBRLighting.j3md");
	mat.setName(substance.get("name").toString());
	Map<Object,Object> textures=(Map<Object,Object>)substance.get("textures");
	if(textures!=null){
		for(Entry e:textures.entrySet()){
			String tx=e.getKey().toString();
			if(!e.getValue().toString().isEmpty()){
				tx=tx.substring(tx.lastIndexOf("_")+1);
				String p=substance_assets_path+e.getValue();
				LOGGER.log(Level.FINE,"Set "+tx+"="+p);
				mat.setTexture(tx,am.loadTexture(p));
			}
		}
	}
	MaterialMap map=new MaterialMap();
	map.material=mat;
	map.render_bucket=Bucket.Opaque;
	return map;
}
 
Example 2
Project: JMELink-SP   File: SubstanceLinkAppState.java   View source code 6 votes vote down vote up
public void removeSpatial(Spatial s) {
	s.depthFirstTraversal(new SceneGraphVisitor(){
		@Override
		public void visit(Spatial sx) {
			if(sx instanceof Geometry){
				Geometry geo=(Geometry)sx;
				Material mat=geo.getMaterial();
				String mat_name=mat==null?null:mat.getName();
				if(mat_name==null){
					System.err.println("Invalid material or missing name");
				}else{
					Iterator<Entry> e_i=ENTRIES.iterator();
					while(e_i.hasNext()){
						if(e_i.next().geo==geo){
							e_i.remove();
							break;
						}
					}
				}
			}
		}
	});
}
 
Example 3
Project: ZayES-Bullet   File: ESDebugViewState.java   View source code 6 votes vote down vote up
@Override
protected Spatial addObject(Entity e) {
    Vector3f loc = e.get(PhysicsPosition.class).getLocation();
    Mesh mesh = MeshFactory.createSphere(0.25f);
    Material material = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
    material.setColor("Color", ColorRGBA.Orange);
    TextureKey key = new TextureKey("Interface/grid-shaded.png");
    key.setGenerateMips(true);
    Texture texture = assetManager.loadTexture(key);
    texture.setWrap(Texture.WrapMode.Repeat);
    material.setTexture("ColorMap", texture);
    Geometry geometry = new Geometry("PhysicsPosition: "+e.getId(), mesh);
    geometry.setMaterial(material);
    geometry.setLocalTranslation(loc);
    rootNode.attachChild(geometry);
    return geometry;
}
 
Example 4
Project: jmonkeybuilder   File: MaterialFileEditor.java   View source code 6 votes vote down vote up
/**
 * Reload the material.
 */
@FXThread
private void reload(@NotNull final Material material) {
    setCurrentMaterial(material);
    setIgnoreListeners(true);
    try {

        final MaterialEditor3DState editor3DState = getEditor3DState();
        editor3DState.updateMaterial(material);

        getSettingsTree().fill(new RootMaterialSettings(material));

        final ComboBox<String> materialDefinitionBox = getMaterialDefinitionBox();
        final ObservableList<String> items = materialDefinitionBox.getItems();
        items.clear();
        items.addAll(RESOURCE_MANAGER.getAvailableResources(FileExtensions.JME_MATERIAL_DEFINITION));

        final MaterialDef materialDef = material.getMaterialDef();
        materialDefinitionBox.getSelectionModel().select(materialDef.getAssetName());

    } finally {
        setIgnoreListeners(false);
    }
}
 
Example 5
Project: chordatlas   File: ProfileGen.java   View source code 6 votes vote down vote up
public void render( List<Prof> ofs, Tweed tweed, ColorRGBA col, Node n ) {

//		Random randy = new Random(ofs.hashCode());
		
		Material mat = new Material( tweed.getAssetManager(), "Common/MatDefs/Light/Lighting.j3md" );
		
//		ColorRGBA col = new ColorRGBA(
//				randy.nextFloat(), 
//				0.2f+ 0.5f * randy.nextFloat(), 
//				0.5f+ 0.5f * randy.nextFloat(), 1);
		
		mat.setColor( "Diffuse", col );
		mat.setColor( "Ambient", col.mult( 0.1f ) );
		mat.setBoolean( "UseMaterialColors", true );
		
		for (Prof p : ofs) {
			Geometry g = new Geometry();
			g.setMesh( p.renderStrip(  TweedSettings.settings.profileHSampleDist/2, null ) );
			g.setMaterial( mat );
			n.attachChild( g );
		}
	}
 
Example 6
Project: jmonkeybuilder   File: AbstractModelFileConverter.java   View source code 6 votes vote down vote up
/**
 * Generate names for 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 7
Project: jmonkeybuilder   File: BaseMaterialEditor3DState.java   View source code 6 votes vote down vote up
/**
 * Update the {@link Material} in the {@link EditorThread}.
 *
 * @param material the new material.
 */
@JMEThread
protected void updateMaterialImpl(@NotNull final Material material) {

    final Geometry testBox = getTestBox();
    testBox.setMaterial(material);

    final Geometry testQuad = getTestQuad();
    testQuad.setMaterial(material);

    final Geometry testSphere = getTestSphere();
    testSphere.setMaterial(material);

    final RenderManager renderManager = EDITOR.getRenderManager();
    try {
        renderManager.preloadScene(testBox);
    } catch (final RendererException | AssetNotFoundException | UnsupportedOperationException e) {
        handleMaterialException(e);
        testBox.setMaterial(EDITOR.getDefaultMaterial());
        testQuad.setMaterial(EDITOR.getDefaultMaterial());
        testSphere.setMaterial(EDITOR.getDefaultMaterial());
    }
}
 
Example 8
Project: jmonkeybuilder   File: AbstractSceneEditor3DState.java   View source code 6 votes vote down vote up
/**
 * Create collision plane.
 */
@FromAnyThread
private void createCollisionPlane() {

    final AssetManager assetManager = EDITOR.getAssetManager();

    final Material material = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
    final RenderState renderState = material.getAdditionalRenderState();
    renderState.setFaceCullMode(RenderState.FaceCullMode.Off);
    renderState.setWireframe(true);

    final float size = 20000;

    final Geometry geometry = new Geometry("plane", new Quad(size, size));
    geometry.setMaterial(material);
    geometry.setLocalTranslation(-size / 2, -size / 2, 0);

    collisionPlane = new Node();
    collisionPlane.attachChild(geometry);
}
 
Example 9
Project: jmonkeybuilder   File: AbstractSceneEditor3DState.java   View source code 6 votes vote down vote up
protected @NotNull Geometry createGeometry(@NotNull final ScenePresentable.PresentationType presentationType) {

        final Material material = new Material(EDITOR.getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md");
        material.setColor("Color", ColorRGBA.Yellow);
        material.getAdditionalRenderState().setWireframe(true);

        Geometry geometry;

        switch (presentationType) {
            case SPHERE: {
                geometry = new Geometry("Sphere", new Sphere(8, 8, 1));
                break;
            }
            default: {
                geometry = new Geometry("Box", new Box(1, 1, 1));
            }
        }

        geometry.setMaterial(material);
        return geometry;
    }
 
Example 10
Project: jmonkeybuilder   File: ParticlesAssetEditorDialog.java   View source code 6 votes vote down vote up
@Override
@FXThread
protected void processOpen(@NotNull final ResourceElement element) {
    super.processOpen(element);

    final ComboBox<String> textureParamNameBox = getTextureParamNameComboBox();
    final SingleSelectionModel<String> selectionModel = textureParamNameBox.getSelectionModel();
    final String textureParamName = selectionModel.getSelectedItem();

    final CheckBox transformBox = getApplyLightingTransformCheckBox();

    final AssetManager assetManager = EDITOR.getAssetManager();

    final Path file = element.getFile();
    final Path assetFile = getAssetFile(file);

    if (assetFile == null) {
        throw new RuntimeException("AssetFile can't be null.");
    }

    final Material material = assetManager.loadAsset(new MaterialKey(toAssetPath(assetFile)));

    final Consumer<ParticlesMaterial> consumer = getConsumer();
    consumer.accept(new ParticlesMaterial(material, textureParamName, transformBox.isSelected()));
}
 
Example 11
Project: jmonkeybuilder   File: MaterialEmitterPropertyControl.java   View source code 6 votes vote down vote up
@FXThread
@Override
protected void processEdit() {

    final ParticlesMaterial element = getPropertyValue();
    if (element == null) return;

    final Material material = element.getMaterial();
    final AssetKey<?> key = material.getKey();
    if (key == null) return;

    final Path assetFile = Paths.get(key.getName());
    final Path realFile = getRealFile(assetFile);
    if (realFile == null || !Files.exists(realFile)) return;

    final RequestedOpenFileEvent event = new RequestedOpenFileEvent();
    event.setFile(realFile);

    FX_EVENT_MANAGER.notify(event);
}
 
Example 12
Project: jmonkeybuilder   File: CreateSkyDialog.java   View source code 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 = EDITOR.getAssetManager();

    return assetManager.loadMaterial(assetPath);
}
 
Example 13
Project: jmonkeybuilder   File: AbstractCreateGeometryAction.java   View source code 6 votes vote down vote up
@Override
@FXThread
protected void process() {
    super.process();

    final NodeTree<ModelChangeConsumer> nodeTree = getNodeTree();
    final ModelChangeConsumer consumer = notNull(nodeTree.getChangeConsumer());
    final SceneLayer defaultLayer = getDefaultLayer(consumer);

    final AssetManager assetManager = EDITOR.getAssetManager();

    final Geometry geometry = createGeometry();
    geometry.setMaterial(new Material(assetManager, "Common/MatDefs/Light/Lighting.j3md"));

    final TreeNode<?> treeNode = getNode();
    final Node parent = (Node) treeNode.getElement();

    if (defaultLayer != null) {
        SceneLayer.setLayer(defaultLayer, geometry);
    }

    consumer.execute(new AddChildOperation(geometry, parent));
}
 
Example 14
Project: jmonkeybuilder   File: SaveAsMaterialAction.java   View source code 6 votes vote down vote up
/**
 * The process of saving the file.
 *
 * @param file the file to save
 */
@FXThread
private void processSave(@NotNull final Path file) {

    final TreeNode<?> node = getNode();
    final Material material = (Material) node.getElement();
    final String materialContent = MaterialSerializer.serializeToString(material);

    try (final PrintWriter out = new PrintWriter(Files.newOutputStream(file, WRITE, TRUNCATE_EXISTING, CREATE))) {
        out.print(materialContent);
    } catch (final IOException e) {
        EditorUtil.handleException(LOGGER, this, e);
        return;
    }

    final Path assetFile = notNull(getAssetFile(file));
    final AssetManager assetManager = EDITOR.getAssetManager();
    final Material savedMaterial = assetManager.loadMaterial(notNull(toAssetPath(assetFile)));

    final PropertyOperation<ChangeConsumer, Material, AssetKey> operation =
            new PropertyOperation<>(material, "AssetKey", savedMaterial.getKey(), null);
    operation.setApplyHandler(Material::setKey);

    final ChangeConsumer changeConsumer = notNull(getNodeTree().getChangeConsumer());
    changeConsumer.execute(operation);
}
 
Example 15
Project: jmonkeybuilder   File: MaterialTreeNode.java   View source code 6 votes vote down vote up
@Override
@FXThread
public void fillContextMenu(@NotNull final NodeTree<?> nodeTree, @NotNull final ObservableList<MenuItem> items) {
    super.fillContextMenu(nodeTree, items);

    final Material material = getElement();
    final TreeNode<?> parent = notNull(getParent());
    final Object parentElement = parent.getElement();
    final Object linkNode = parentElement instanceof Spatial ?
            NodeUtils.findParent((Spatial) parentElement, AssetLinkNode.class::isInstance) : null;

    if (linkNode == null) {
        items.add(new SaveAsMaterialAction(nodeTree, this));
    }

    if (material.getKey() != null) {
        items.add(new MakeAsEmbeddedMaterialAction(nodeTree, this));
    }
}
 
Example 16
Project: jmonkeybuilder   File: GeometryTreeNode.java   View source code 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 17
Project: jmonkeybuilder   File: GeometryTreeNode.java   View source code 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 18
Project: jmonkeybuilder   File: DeleteMaterialsModelFileDeleteHandler.java   View source code 6 votes vote down vote up
@Override
public void preDelete(@NotNull final Path file) {
    super.preDelete(file);

    final AssetManager assetManager = EDITOR.getAssetManager();
    final Path assetFile = notNull(getAssetFile(file));
    final String assetPath = toAssetPath(assetFile);

    final Spatial model = assetManager.loadModel(assetPath);

    NodeUtils.visitGeometry(model, geometry -> {
        final Material material = geometry.getMaterial();
        final String assetName = material.getAssetName();
        if (!StringUtils.isEmpty(assetName)) assetKeys.add(assetName);
    });
}
 
Example 19
Project: jmonkeybuilder   File: MaterialFileCreator.java   View source code 6 votes vote down vote up
@Override
@BackgroundThread
protected void writeData(@NotNull final VarTable vars, @NotNull final Path resultFile) throws IOException {
    super.writeData(vars, resultFile);

    final AssetManager assetManager = EDITOR.getAssetManager();
    final String matDef = vars.get(PROP_MAT_DEF);

    final Material material = new Material(assetManager, matDef);
    material.getAdditionalRenderState();

    final String materialContent = MaterialSerializer.serializeToString(material);

    try (final PrintWriter out = new PrintWriter(Files.newOutputStream(resultFile, WRITE, TRUNCATE_EXISTING, CREATE))) {
        out.print(materialContent);
    }
}
 
Example 20
Project: jmonkeybuilder   File: TextureLayerSettings.java   View source code 6 votes vote down vote up
/**
 * Get a diffuse texture of the level.
 *
 * @param layer the layer.
 * @return the diffuse texture or null.
 */
@FromAnyThread
public @Nullable Texture getDiffuse(final int layer) {

    final Function<Integer, String> layerToDiffuseName = getLayerToDiffuseName();
    if (layerToDiffuseName == null) return null;

    final Terrain terrain = getTerrain();
    final Material material = terrain.getMaterial();
    final MatParam matParam = material.getParam(layerToDiffuseName.apply(layer));

    if (matParam == null || matParam.getValue() == null) {
        return null;
    }

    return (Texture) matParam.getValue();
}
 
Example 21
Project: jmonkeybuilder   File: MaterialFileEditor.java   View source code 6 votes vote down vote up
@Override
@FXThread
protected void doOpenFile(@NotNull final Path file) throws IOException {
    super.doOpenFile(file);

    final Path assetFile = notNull(getAssetFile(file));
    final MaterialKey materialKey = new MaterialKey(toAssetPath(assetFile));

    final AssetManager assetManager = EDITOR.getAssetManager();
    final Material material = assetManager.loadAsset(materialKey);

    final MaterialEditor3DState editor3DState = getEditor3DState();
    editor3DState.changeMode(ModelType.BOX);

    reload(material);
}
 
Example 22
Project: jmonkeybuilder   File: TextureLayerSettings.java   View source code 6 votes vote down vote up
/**
 * Get a diffuse normal of the level.
 *
 * @param layer the layer.
 * @return the normal texture or null.
 */
@FromAnyThread
public @Nullable Texture getNormal(final int layer) {

    final Function<Integer, String> layerToNormalName = getLayerToNormalName();
    if (layerToNormalName == null) return null;

    final Terrain terrain = getTerrain();
    final Material material = terrain.getMaterial();
    final MatParam matParam = material.getParam(layerToNormalName.apply(layer));

    if (matParam == null || matParam.getValue() == null) {
        return null;
    }

    return (Texture) matParam.getValue();
}
 
Example 23
Project: jmonkeybuilder   File: TextureLayerSettings.java   View source code 6 votes vote down vote up
/**
 * Set a new normal texture to a level.
 *
 * @param texture the normal texture.
 * @param layer   the layer.
 */
@FromAnyThread
public void setNormal(@Nullable final Texture texture, final int layer) {

    final Function<Integer, String> layerToNormalName = getLayerToNormalName();
    if (layerToNormalName == null) return;

    final Terrain terrain = getTerrain();
    final Material material = terrain.getMaterial();
    final String paramName = layerToNormalName.apply(layer);
    final MatParam matParam = material.getParam(paramName);
    final Texture current = matParam == null ? null : (Texture) matParam.getValue();

    if (texture != null) {
        texture.setWrap(Texture.WrapMode.Repeat);
    }

    final PropertyOperation<ChangeConsumer, Node, Texture> operation =
            new PropertyOperation<>(getTerrainNode(), TERRAIN_PARAM, texture, current);

    operation.setApplyHandler((node, newTexture) ->
            NodeUtils.visitGeometry(node, geometry -> updateTexture(newTexture, paramName, geometry)));

    final ModelChangeConsumer changeConsumer = editingComponent.getChangeConsumer();
    changeConsumer.execute(operation);
}
 
Example 24
Project: jmonkeybuilder   File: TextureLayerSettings.java   View source code 6 votes vote down vote up
/**
 * Get a alpha texture of the level.
 *
 * @param layer the layer.
 * @return the alpha texture or null.
 */
@FromAnyThread
public @Nullable Texture getAlpha(final int layer) {

    final Function<Integer, String> layerToAlphaName = getLayerToAlphaName();
    if (layerToAlphaName == null) return null;

    final Terrain terrain = getTerrain();
    final Material material = terrain.getMaterial();
    final MatParam matParam = material.getParam(layerToAlphaName.apply(layer));

    if (matParam == null || matParam.getValue() == null) {
        return null;
    }

    return (Texture) matParam.getValue();
}
 
Example 25
Project: jmonkeybuilder   File: TerrainEditingComponent.java   View source code 6 votes vote down vote up
/**
 * Change the shininess value.
 */
@FromAnyThread
private void changePaintControlShininess(@NotNull final Float newValue) {
    if (isIgnoreListeners()) return;

    final TerrainQuad processedObject = getProcessedObject();
    final Material mat = processedObject.getMaterial();
    final MatParam param = mat.getParam("Shininess");
    final float shininess = param == null ? 0F : (float) param.getValue();

    final PropertyOperation<ChangeConsumer, TerrainQuad, Float> operation =
            new PropertyOperation<>(processedObject, TERRAIN_PARAM, newValue, shininess);

    operation.setApplyHandler((terrainQuad, value) -> {
        NodeUtils.visitGeometry(terrainQuad, geometry -> {
            final Material material = geometry.getMaterial();
            material.setFloat("Shininess", value);
        });
    });

    final ModelChangeConsumer changeConsumer = getChangeConsumer();
    changeConsumer.execute(operation);
}
 
Example 26
Project: jmonkeybuilder   File: TerrainEditingComponent.java   View source code 6 votes vote down vote up
/**
 * Change using tri-planar textures.
 */
@FromAnyThread
private void changePaintControlTriPlanar(@NotNull final Boolean newValue) {
    if (isIgnoreListeners()) return;

    final TerrainQuad processedObject = getProcessedObject();

    final PropertyOperation<ChangeConsumer, TerrainQuad, Boolean> operation =
            new PropertyOperation<>(processedObject, TERRAIN_PARAM, newValue, !newValue);

    operation.setApplyHandler((terrainQuad, value) -> {
        NodeUtils.visitGeometry(terrainQuad, geometry -> {
            final Material material = geometry.getMaterial();
            material.setBoolean("useTriPlanarMapping", value);
        });
    });

    final ModelChangeConsumer changeConsumer = getChangeConsumer();
    changeConsumer.execute(operation);
}
 
Example 27
Project: jmonkeybuilder   File: TerrainEditingComponent.java   View source code 6 votes vote down vote up
@Override
public void startProcessing(@NotNull final Object object) {
    super.startProcessing(object);

    final TextureLayerSettings settings = getTextureLayerSettings();

    final Terrain terrain = (Terrain) object;
    final Material material = terrain.getMaterial();
    final MaterialDef materialDef = material.getMaterialDef();

    if (materialDef.getAssetName().equals("Common/MatDefs/Terrain/TerrainLighting.j3md")) {
        settings.setLayerToScaleName(LAYER_TO_SCALE_NAME);
        settings.setLayerToAlphaName(LAYER_TO_ALPHA_NAME);
        settings.setLayerToDiffuseName(LAYER_TO_DIFFUSE_NAME);
        settings.setLayerToNormalName(LAYER_TO_NORMAL_NAME);
        settings.setMaxLevels(12);
    }

    refreshProperties();

    settings.refresh();
}
 
Example 28
Project: jmonkeybuilder   File: TerrainEditingComponent.java   View source code 6 votes vote down vote up
/**
 * Refresh terrain properties.
 */
private void refreshProperties() {
    setIgnoreListeners(true);
    try {

        final Terrain terrain = getProcessedObject();
        final Material material = terrain.getMaterial();
        final FloatTextField shininessField = getShininessField();
        final CheckBox triPlanarCheckBox = getTriPlanarCheckBox();
        final MatParam shininess = material.getParam("Shininess");
        final MatParam useTriPlanarMapping = material.getParam("useTriPlanarMapping");

        shininessField.setValue(shininess == null ? 0F : (float) shininess.getValue());
        triPlanarCheckBox.setSelected(useTriPlanarMapping != null && (boolean) useTriPlanarMapping.getValue());

    } finally {
        setIgnoreListeners(false);
    }
}
 
Example 29
Project: jmonkeybuilder   File: AbstractSceneFileEditor.java   View source code 6 votes vote down vote up
/**
 * Updating a material from the file.
 */
@FXThread
private void updateMaterial(@NotNull final Path file) {

    final Path assetFile = notNull(getAssetFile(file), "Not found asset file for " + file);
    final String assetPath = toAssetPath(assetFile);

    final M currentModel = getCurrentModel();

    final Array<Geometry> geometries = ArrayFactory.newArray(Geometry.class);
    NodeUtils.addGeometryWithMaterial(currentModel, geometries, assetPath);
    if (geometries.isEmpty()) return;

    final AssetManager assetManager = EDITOR.getAssetManager();
    final Material material = assetManager.loadMaterial(assetPath);
    geometries.forEach(geometry -> geometry.setMaterial(material));

    final TonegodTranslucentBucketFilter translucentBucketFilter = EDITOR.getTranslucentBucketFilter();
    translucentBucketFilter.refresh();
}
 
Example 30
Project: jmonkeybuilder   File: AbstractSceneFileEditor.java   View source code 6 votes vote down vote up
/**
 * Updating materials.
 */
@FXThread
private void updateMaterials(@NotNull final Path file) {

    final M currentModel = getCurrentModel();
    final AtomicInteger needRefresh = new AtomicInteger();

    NodeUtils.visitGeometry(currentModel, geometry -> {

        final Material material = geometry.getMaterial();
        final Material newMaterial = updateMaterialIdNeed(file, material);

        if (newMaterial != null) {
            geometry.setMaterial(newMaterial);
            needRefresh.incrementAndGet();
        }
    });

    if (needRefresh.get() < 1) {
        return;
    }

    final TonegodTranslucentBucketFilter translucentBucketFilter = EDITOR.getTranslucentBucketFilter();
    translucentBucketFilter.refresh();
}
 
Example 31
Project: jmonkeybuilder   File: MaterialFileEditor.java   View source code 6 votes vote down vote up
@Override
@FXThread
protected void handleExternalChanges() {
    super.handleExternalChanges();

    final Path assetFile = notNull(getAssetFile(getEditFile()));
    final MaterialKey materialKey = new MaterialKey(toAssetPath(assetFile));

    final AssetManager assetManager = EDITOR.getAssetManager();
    final Material material = assetManager.loadAsset(materialKey);

    reload(material);

    final EditorOperationControl operationControl = getOperationControl();
    operationControl.clear();
}
 
Example 32
Project: JMELink-SP   File: PhongSubstance.java   View source code 5 votes vote down vote up
@Override
public MaterialMap toMaterial(AssetManager am, Substance substance, String substance_assets_path) {
	Material mat=new Material(am,"Common/MatDefs/Light/Lighting.j3md");
	mat.setName(substance.get("name").toString());
	Map<Object,Object> textures=(Map<Object,Object>)substance.get("textures");
	if(textures!=null){
		for(Entry e:textures.entrySet()){
			String tx=e.getKey().toString();
			if(!e.getValue().toString().isEmpty()){
				tx=tx.substring(tx.lastIndexOf("_")+1);
				String p=substance_assets_path+e.getValue();
				LOGGER.log(Level.FINE,"Set "+tx+"="+p);
				mat.setTexture(tx,am.loadTexture(p));
			}
		}
	}
	
	Map parameters=(Map)substance.get("parameters");
	if(parameters!=null){
		Number fresnel=(Number)parameters.get("fresnel_str");
		if(fresnel!=null) mat.setFloat("Shininess",fresnel.floatValue());
	}
	
	MaterialMap map=new MaterialMap();
	map.material=mat;
	map.render_bucket=Bucket.Opaque;
	return map;
	
}
 
Example 33
Project: JMELink-SP   File: SubstanceLinkAppState.java   View source code 5 votes vote down vote up
public void addSpatial(Spatial s) {
	NEED_SUBSTANCES_UPDATE=true;
	s.depthFirstTraversal(new SceneGraphVisitor(){
		@Override
		public void visit(Spatial sx) {
			if(sx instanceof Geometry){
				Geometry geo=(Geometry)sx;
				Material mat=geo.getMaterial();
				String mat_name=mat==null?null:mat.getName();
				if(mat_name==null){
					System.err.println("Invalid material or missing name");
				}else{
					boolean exists=false;
					Iterator<Entry> e_i=ENTRIES.iterator();
					while(e_i.hasNext()){
						if(e_i.next().geo==geo){
							exists=true;
							break;
						}
					}
					if(!exists){
						Entry e=new Entry();
						e.geo=geo;
						ENTRIES.add(e);
					}
					// Apply substance
				}
			}
		}
	});
}
 
Example 34
Project: ZayES-Bullet   File: ESDebugViewState.java   View source code 5 votes vote down vote up
private Material createMaterial(ColorRGBA color){
    Material material = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
    material.setColor("Color", color);
    TextureKey key = new TextureKey("Interface/grid-shaded.png");
    key.setGenerateMips(true);
    Texture texture = assetManager.loadTexture(key);
    texture.setWrap(Texture.WrapMode.Repeat);
    material.setTexture("ColorMap", texture);
    return material;
}
 
Example 35
Project: ZayES-Bullet   File: CapsuleView.java   View source code 5 votes vote down vote up
@Override
protected Node addObject(Entity e) {
    Node capsule = new Node("ID: "+e.getId());
    refreshMesh(capsule, e);
    root.attachChild(capsule);
    Material dummy = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
    dummy.setColor("Color", ColorRGBA.White);
    capsule.setMaterial(dummy);
    return capsule;
}
 
Example 36
Project: ZayES-Bullet   File: ShapeContainer.java   View source code 5 votes vote down vote up
@Override
protected Geometry addObject(Entity e) {
    Geometry geom = new Geometry("ID: "+e.getId(), getMesh(e));
    //geom.setShadowMode(RenderQueue.ShadowMode.CastAndReceive);
    Material dummy = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
    dummy.setColor("Color", ColorRGBA.White);
    geom.setMaterial(dummy);
    root.attachChild(geom);
    return geom;
}
 
Example 37
Project: ZayES-Bullet   File: TestBrickWall.java   View source code 5 votes vote down vote up
@Override
public void simpleInitApp() {
    //init input
    initCrossHairs();
    this.cam.setLocation(new Vector3f(0, 6f, 6f));
    cam.lookAt(Vector3f.ZERO, new Vector3f(0, 1, 0));
    cam.setFrustumFar(15);
    inputManager.addMapping("shoot", new MouseButtonTrigger(MouseInput.BUTTON_LEFT));
    inputManager.addListener(actionListener, "shoot");

    //init shadow
    rootNode.setShadowMode(RenderQueue.ShadowMode.Off);
    bsr = new BasicShadowRenderer(assetManager, 256);
    bsr.setDirection(new Vector3f(-1, -1, -1).normalizeLocal());
    viewPort.addProcessor(bsr);

    //init data
    brickMat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
    brickMat.setColor("Color", ColorRGBA.Orange);
    bulletMat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
    bulletMat.setColor("Color", ColorRGBA.Blue);
    initFloor();
    initWall();

    //start view
    boxes = new BoxView(entityData);
    bullets = new BulletView(entityData);
    boxes.start();
    bullets.start();
}
 
Example 38
Project: chordatlas   File: DebugGen.java   View source code 5 votes vote down vote up
@Override
public void calculate() {

	for (Spatial s : gNode.getChildren())
		s.removeFromParent();
	
	Mesh mesh = new Mesh();
	mesh.setMode( Mode.Points );
	
	Vector3f[] verts = new Vector3f[cubes.size()];
	
	for (int i = 0; i < cubes.size(); i++) {
		verts[ i ] = new com.jme3.math.Vector3f( (float)cubes.get( i ).x, (float)cubes.get( i ).y, (float)cubes.get( i ).z );
	}
	
	mesh.setBuffer( VertexBuffer.Type.Position, 3, BufferUtils.createFloatBuffer( verts ) );
	
	Material mat1 = new Material( tweed.getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md" );
	mat1.setBoolean( "VertexColor", true );
	Geometry depth = new Geometry( "depth", mesh );
	depth.setMaterial( mat1 );
	
	depth.updateModelBound();
	depth.updateGeometricState();
	
	gNode.attachChild(depth);
	
	super.calculate();
}
 
Example 39
Project: chordatlas   File: PanoGen.java   View source code 5 votes vote down vote up
private void addCubes (List<float[]> cubes) {
	tweed.enqueue( new Runnable() {
		public void run() {
			
			Mesh mesh = new Mesh();
			mesh.setMode( Mode.Points );
			
			Vector3f[] verts = new Vector3f[cubes.size()];
			Vector4f[] cols  = new Vector4f[cubes.size()];
			
			for (int i = 0; i < cubes.size(); i++) {
				verts[ i ] = new com.jme3.math.Vector3f( cubes.get( i )[ 0 ], cubes.get( i )[ 1 ], cubes.get( i )[ 2 ] );
				cols[i] = new Vector4f( cubes.get( i )[ 3 ], cubes.get( i )[ 4 ], cubes.get( i )[ 5 ], 1 );
			}
			
			mesh.setBuffer( VertexBuffer.Type.Position, 3, BufferUtils.createFloatBuffer( verts ) );
			mesh.setBuffer( VertexBuffer.Type.Color   , 4, BufferUtils.createFloatBuffer( cols  ) );
			
			Material mat1 = new Material( tweed.getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md" );
			mat1.setBoolean( "VertexColor", true );
			Geometry depth = new Geometry( "depth", mesh );
			depth.setMaterial( mat1 );
			
			depth.updateModelBound();
			depth.updateGeometricState();
			
			
			tweed.frame.addGen( new JmeGen( "depth", tweed, depth ), true );
		}
	} );
}
 
Example 40
Project: Victorum   File: WorldAppState.java   View source code 5 votes vote down vote up
@Override
protected void initialize(Application application){
    chunkMaterial = new Material(getVictorum().getAssetManager(), "/Common/MatDefs/Misc/Unshaded.j3md");
    Texture textureAtlas = getVictorum().getAssetManager().loadTexture(new TextureKey("/atlas.png", false));
    textureAtlas.setMagFilter(Texture.MagFilter.Nearest);
    textureAtlas.setMinFilter(Texture.MinFilter.BilinearNearestMipMap);
    textureAtlas.setAnisotropicFilter(2);
    chunkMaterial.setTexture("ColorMap", textureAtlas);
    chunkMaterial.getAdditionalRenderState().setFaceCullMode(RenderState.FaceCullMode.Off);
}