Search in sources :

Example 56 with Vector2f

use of com.jme3.math.Vector2f in project jmonkeyengine by jMonkeyEngine.

the class MatParam method getValueAsString.

/**
     * Returns the material parameter value as it would appear in a J3M
     * file. E.g.<br/>
     * <code>
     * MaterialParameters {<br/>
     *     ABC : 1 2 3 4<br/>
     * }<br/>
     * </code>
     * Assuming "ABC" is a Vector4 parameter, then the value
     * "1 2 3 4" would be returned by this method.
     * <br/><br/>
     * @return material parameter value as it would appear in a J3M file.
     */
public String getValueAsString() {
    switch(type) {
        case Boolean:
        case Float:
        case Int:
            return value.toString();
        case Vector2:
            Vector2f v2 = (Vector2f) value;
            return v2.getX() + " " + v2.getY();
        /* 
This may get used at a later point of time
When arrays can be inserted in J3M files

            case Vector2Array:
                Vector2f[] v2Arr = (Vector2f[]) value;
                String v2str = "";
                for (int i = 0; i < v2Arr.length ; i++) {
                    v2str += v2Arr[i].getX() + " " + v2Arr[i].getY() + "\n";
                }
                return v2str;
*/
        case Vector3:
            Vector3f v3 = (Vector3f) value;
            return v3.getX() + " " + v3.getY() + " " + v3.getZ();
        /*
            case Vector3Array:
                Vector3f[] v3Arr = (Vector3f[]) value;
                String v3str = "";
                for (int i = 0; i < v3Arr.length ; i++) {
                    v3str += v3Arr[i].getX() + " "
                            + v3Arr[i].getY() + " "
                            + v3Arr[i].getZ() + "\n";
                }
                return v3str;
            case Vector4Array:
                // can be either ColorRGBA, Vector4f or Quaternion
                if (value instanceof Vector4f) {
                    Vector4f[] v4arr = (Vector4f[]) value;
                    String v4str = "";
                    for (int i = 0; i < v4arr.length ; i++) {
                        v4str += v4arr[i].getX() + " "
                                + v4arr[i].getY() + " "
                                + v4arr[i].getZ() + " "
                                + v4arr[i].getW() + "\n";
                    }
                    return v4str;
                } else if (value instanceof ColorRGBA) {
                    ColorRGBA[] colorArr = (ColorRGBA[]) value;
                    String colStr = "";
                    for (int i = 0; i < colorArr.length ; i++) {
                        colStr += colorArr[i].getRed() + " "
                                + colorArr[i].getGreen() + " "
                                + colorArr[i].getBlue() + " "
                                + colorArr[i].getAlpha() + "\n";
                    }
                    return colStr;
                } else if (value instanceof Quaternion) {
                    Quaternion[] quatArr = (Quaternion[]) value;
                    String quatStr = "";
                    for (int i = 0; i < quatArr.length ; i++) {
                        quatStr += quatArr[i].getX() + " "
                                + quatArr[i].getY() + " "
                                + quatArr[i].getZ() + " "
                                + quatArr[i].getW() + "\n";
                    }
                    return quatStr;
                } else {
                    throw new UnsupportedOperationException("Unexpected Vector4Array type: " + value);
                }
*/
        case Vector4:
            // can be either ColorRGBA, Vector4f or Quaternion
            if (value instanceof Vector4f) {
                Vector4f v4 = (Vector4f) value;
                return v4.getX() + " " + v4.getY() + " " + v4.getZ() + " " + v4.getW();
            } else if (value instanceof ColorRGBA) {
                ColorRGBA color = (ColorRGBA) value;
                return color.getRed() + " " + color.getGreen() + " " + color.getBlue() + " " + color.getAlpha();
            } else if (value instanceof Quaternion) {
                Quaternion quat = (Quaternion) value;
                return quat.getX() + " " + quat.getY() + " " + quat.getZ() + " " + quat.getW();
            } else {
                throw new UnsupportedOperationException("Unexpected Vector4 type: " + value);
            }
        case Texture2D:
        case Texture3D:
        case TextureArray:
        case TextureBuffer:
        case TextureCubeMap:
            Texture texVal = (Texture) value;
            TextureKey texKey = (TextureKey) texVal.getKey();
            if (texKey == null) {
                // often does as well, even implicitly. 
                return texVal + ":returned null key";
            }
            String ret = "";
            if (texKey.isFlipY()) {
                ret += "Flip ";
            }
            //Wrap mode
            ret += getWrapMode(texVal, Texture.WrapAxis.S);
            ret += getWrapMode(texVal, Texture.WrapAxis.T);
            ret += getWrapMode(texVal, Texture.WrapAxis.R);
            //Min and Mag filter
            Texture.MinFilter def = Texture.MinFilter.BilinearNoMipMaps;
            if (texVal.getImage().hasMipmaps() || texKey.isGenerateMips()) {
                def = Texture.MinFilter.Trilinear;
            }
            if (texVal.getMinFilter() != def) {
                ret += "Min" + texVal.getMinFilter().name() + " ";
            }
            if (texVal.getMagFilter() != Texture.MagFilter.Bilinear) {
                ret += "Mag" + texVal.getMagFilter().name() + " ";
            }
            return ret + "\"" + texKey.getName() + "\"";
        default:
            // parameter type not supported in J3M
            return null;
    }
}
Also used : TextureKey(com.jme3.asset.TextureKey) Texture(com.jme3.texture.Texture)

Example 57 with Vector2f

use of com.jme3.math.Vector2f in project jmonkeyengine by jMonkeyEngine.

the class SimpleWaterProcessor method initialize.

public void initialize(RenderManager rm, ViewPort vp) {
    this.rm = rm;
    this.vp = vp;
    loadTextures(manager);
    createTextures();
    applyTextures(material);
    createPreViews();
    material.setVector2("FrustumNearFar", new Vector2f(vp.getCamera().getFrustumNear(), vp.getCamera().getFrustumFar()));
    if (debug) {
        dispRefraction = new Picture("dispRefraction");
        dispRefraction.setTexture(manager, refractionTexture, false);
        dispReflection = new Picture("dispRefraction");
        dispReflection.setTexture(manager, reflectionTexture, false);
        dispDepth = new Picture("depthTexture");
        dispDepth.setTexture(manager, depthTexture, false);
    }
}
Also used : Picture(com.jme3.ui.Picture)

Example 58 with Vector2f

use of com.jme3.math.Vector2f in project jmonkeyengine by jMonkeyEngine.

the class CombinedTexture method flatten.

/**
	 * This method flattens the texture and creates a single result of Texture2D
	 * type.
	 * 
	 * @param geometry
	 *            the geometry the texture is created for
	 * @param geometriesOMA
	 *            the old memory address of the geometries list that the given
	 *            geometry belongs to (needed for bounding box creation)
	 * @param userDefinedUVCoordinates
	 *            the UV's defined by user (null or zero length table if none
	 *            were defined)
	 * @param blenderContext
	 *            the blender context
	 * @return the name of the user UV coordinates used (null if the UV's were
	 *         generated)
	 */
public String flatten(Geometry geometry, Long geometriesOMA, Map<String, List<Vector2f>> userDefinedUVCoordinates, BlenderContext blenderContext) {
    Mesh mesh = geometry.getMesh();
    Texture previousTexture = null;
    UVCoordinatesType masterUVCoordinatesType = null;
    String masterUserUVSetName = null;
    for (TextureData textureData : textureDatas) {
        // decompress compressed textures (all will be merged into one texture anyway)
        if (textureDatas.size() > 1 && textureData.texture.getImage().getFormat().isCompressed()) {
            textureData.texture.setImage(ImageUtils.decompress(textureData.texture.getImage()));
            textureData.textureBlender = TextureBlenderFactory.alterTextureType(textureData.texture.getImage().getFormat(), textureData.textureBlender);
        }
        if (previousTexture == null) {
            // the first texture will lead the others to its shape
            if (textureData.texture instanceof GeneratedTexture) {
                resultTexture = ((GeneratedTexture) textureData.texture).triangulate(mesh, geometriesOMA, textureData.uvCoordinatesType, blenderContext);
            } else if (textureData.texture instanceof Texture2D) {
                resultTexture = textureData.texture;
                if (textureData.uvCoordinatesType == UVCoordinatesType.TEXCO_UV && userDefinedUVCoordinates != null && userDefinedUVCoordinates.size() > 0) {
                    if (textureData.uvCoordinatesName == null) {
                        // get the first UV available
                        resultUVS = userDefinedUVCoordinates.values().iterator().next();
                    } else {
                        resultUVS = userDefinedUVCoordinates.get(textureData.uvCoordinatesName);
                    }
                    if (resultUVS == null && LOGGER.isLoggable(Level.WARNING)) {
                        LOGGER.warning("The texture " + textureData.texture.getName() + " has assigned non existing UV coordinates group: " + textureData.uvCoordinatesName + ".");
                    }
                    masterUserUVSetName = textureData.uvCoordinatesName;
                } else {
                    TemporalMesh temporalMesh = (TemporalMesh) blenderContext.getLoadedFeature(geometriesOMA, LoadedDataType.TEMPORAL_MESH);
                    resultUVS = UVCoordinatesGenerator.generateUVCoordinatesFor2DTexture(mesh, textureData.uvCoordinatesType, textureData.projectionType, temporalMesh);
                }
            }
            this.blend(resultTexture, textureData.textureBlender, blenderContext);
            previousTexture = resultTexture;
            masterUVCoordinatesType = textureData.uvCoordinatesType;
        } else {
            if (textureData.texture instanceof GeneratedTexture) {
                if (!(resultTexture instanceof TriangulatedTexture)) {
                    resultTexture = new TriangulatedTexture((Texture2D) resultTexture, resultUVS, blenderContext);
                    resultUVS = null;
                    previousTexture = resultTexture;
                }
                TriangulatedTexture triangulatedTexture = ((GeneratedTexture) textureData.texture).triangulate(mesh, geometriesOMA, textureData.uvCoordinatesType, blenderContext);
                triangulatedTexture.castToUVS((TriangulatedTexture) resultTexture, blenderContext);
                triangulatedTexture.blend(textureData.textureBlender, (TriangulatedTexture) resultTexture, blenderContext);
                resultTexture = previousTexture = triangulatedTexture;
            } else if (textureData.texture instanceof Texture2D) {
                if (this.isUVTypesMatch(masterUVCoordinatesType, masterUserUVSetName, textureData.uvCoordinatesType, textureData.uvCoordinatesName) && resultTexture instanceof Texture2D) {
                    this.scale((Texture2D) textureData.texture, resultTexture.getImage().getWidth(), resultTexture.getImage().getHeight());
                    ImageUtils.merge(resultTexture.getImage(), textureData.texture.getImage());
                    previousTexture = resultTexture;
                } else {
                    if (!(resultTexture instanceof TriangulatedTexture)) {
                        resultTexture = new TriangulatedTexture((Texture2D) resultTexture, resultUVS, blenderContext);
                        resultUVS = null;
                    }
                    // first triangulate the current texture
                    List<Vector2f> textureUVS = null;
                    if (textureData.uvCoordinatesType == UVCoordinatesType.TEXCO_UV && userDefinedUVCoordinates != null && userDefinedUVCoordinates.size() > 0) {
                        if (textureData.uvCoordinatesName == null) {
                            // get the first UV available
                            textureUVS = userDefinedUVCoordinates.values().iterator().next();
                        } else {
                            textureUVS = userDefinedUVCoordinates.get(textureData.uvCoordinatesName);
                        }
                    } else {
                        TemporalMesh geometries = (TemporalMesh) blenderContext.getLoadedFeature(geometriesOMA, LoadedDataType.TEMPORAL_MESH);
                        textureUVS = UVCoordinatesGenerator.generateUVCoordinatesFor2DTexture(mesh, textureData.uvCoordinatesType, textureData.projectionType, geometries);
                    }
                    TriangulatedTexture triangulatedTexture = new TriangulatedTexture((Texture2D) textureData.texture, textureUVS, blenderContext);
                    // then move the texture to different UV's
                    triangulatedTexture.castToUVS((TriangulatedTexture) resultTexture, blenderContext);
                    // merge triangulated textures
                    for (int i = 0; i < ((TriangulatedTexture) resultTexture).getFaceTextureCount(); ++i) {
                        ImageUtils.merge(((TriangulatedTexture) resultTexture).getFaceTextureElement(i).image, triangulatedTexture.getFaceTextureElement(i).image);
                    }
                }
            }
        }
    }
    if (resultTexture instanceof TriangulatedTexture) {
        if (mappingType == MaterialContext.MTEX_NOR) {
            for (int i = 0; i < ((TriangulatedTexture) resultTexture).getFaceTextureCount(); ++i) {
                TriangleTextureElement triangleTextureElement = ((TriangulatedTexture) resultTexture).getFaceTextureElement(i);
                // TODO: get proper strength factor
                triangleTextureElement.image = ImageUtils.convertToNormalMapTexture(triangleTextureElement.image, 1);
            }
        }
        resultUVS = ((TriangulatedTexture) resultTexture).getResultUVS();
        resultTexture = ((TriangulatedTexture) resultTexture).getResultTexture();
        masterUserUVSetName = null;
    }
    // setting additional data
    resultTexture.setWrap(WrapMode.Repeat);
    // the filters are required if generated textures are used because
    // otherwise ugly lines appear between the mesh faces
    resultTexture.setMagFilter(MagFilter.Nearest);
    resultTexture.setMinFilter(MinFilter.NearestNoMipMaps);
    return masterUserUVSetName;
}
Also used : TemporalMesh(com.jme3.scene.plugins.blender.meshes.TemporalMesh) Texture2D(com.jme3.texture.Texture2D) TriangleTextureElement(com.jme3.scene.plugins.blender.textures.TriangulatedTexture.TriangleTextureElement) UVCoordinatesType(com.jme3.scene.plugins.blender.textures.UVCoordinatesGenerator.UVCoordinatesType) TemporalMesh(com.jme3.scene.plugins.blender.meshes.TemporalMesh) Mesh(com.jme3.scene.Mesh) ArrayList(java.util.ArrayList) List(java.util.List) Texture(com.jme3.texture.Texture)

Example 59 with Vector2f

use of com.jme3.math.Vector2f in project jmonkeyengine by jMonkeyEngine.

the class TemporalMesh method prepareFacesGeometry.

/**
     * The method creates geometries from faces.
     * @param result
     *            the list where new geometries will be appended
     * @param meshHelper
     *            the mesh helper
     */
protected void prepareFacesGeometry(List<Geometry> result, MeshHelper meshHelper) {
    LOGGER.fine("Preparing faces geometries.");
    this.triangulate();
    Vector3f[] tempVerts = new Vector3f[3];
    Vector3f[] tempNormals = new Vector3f[3];
    byte[][] tempVertColors = new byte[3][];
    List<Map<Float, Integer>> boneBuffers = new ArrayList<Map<Float, Integer>>(3);
    LOGGER.log(Level.FINE, "Appending {0} faces to mesh buffers.", faces.size());
    Map<Integer, MeshBuffers> faceMeshes = new HashMap<Integer, MeshBuffers>();
    for (Face face : faces) {
        MeshBuffers meshBuffers = faceMeshes.get(face.getMaterialNumber());
        if (meshBuffers == null) {
            meshBuffers = new MeshBuffers(face.getMaterialNumber());
            faceMeshes.put(face.getMaterialNumber(), meshBuffers);
        }
        List<List<Integer>> triangulatedIndexes = face.getCurrentIndexes();
        List<byte[]> vertexColors = face.getVertexColors();
        for (List<Integer> indexes : triangulatedIndexes) {
            assert indexes.size() == 3 : "The mesh has not been properly triangulated!";
            Vector3f normal = null;
            if (!face.isSmooth()) {
                normal = FastMath.computeNormal(vertices.get(indexes.get(0)), vertices.get(indexes.get(1)), vertices.get(indexes.get(2)));
            }
            boneBuffers.clear();
            for (int i = 0; i < 3; ++i) {
                int vertIndex = indexes.get(i);
                tempVerts[i] = vertices.get(vertIndex);
                tempNormals[i] = normal != null ? normal : normals.get(vertIndex);
                tempVertColors[i] = vertexColors != null ? vertexColors.get(face.getIndexes().indexOf(vertIndex)) : null;
                if (boneIndexes.size() > 0 && vertexGroups.size() > 0) {
                    Map<Float, Integer> boneBuffersForVertex = new HashMap<Float, Integer>();
                    Map<String, Float> vertexGroupsForVertex = vertexGroups.get(vertIndex);
                    for (Entry<String, Integer> entry : boneIndexes.entrySet()) {
                        if (vertexGroupsForVertex.containsKey(entry.getKey())) {
                            float weight = vertexGroupsForVertex.get(entry.getKey());
                            if (weight > MINIMUM_BONE_WEIGHT) {
                                // only values of weight greater than MINIMUM_BONE_WEIGHT are used
                                // if all non zero weights were used, and they were samm enough, problems with normalisation would occur
                                // because adding a very small value to 1.0 will give 1.0
                                // so in order to avoid such errors, which can cause severe animation artifacts we need to use some minimum weight value
                                boneBuffersForVertex.put(weight, entry.getValue());
                            }
                        }
                    }
                    if (boneBuffersForVertex.size() == 0) {
                        // attach the vertex to zero-indexed bone so that it does not collapse to (0, 0, 0)
                        boneBuffersForVertex.put(1.0f, 0);
                    }
                    boneBuffers.add(boneBuffersForVertex);
                }
            }
            Map<String, List<Vector2f>> uvs = meshHelper.selectUVSubset(face, indexes.toArray(new Integer[indexes.size()]));
            meshBuffers.append(face.isSmooth(), tempVerts, tempNormals, uvs, tempVertColors, boneBuffers);
        }
    }
    LOGGER.fine("Converting mesh buffers to geometries.");
    Map<Geometry, MeshBuffers> geometryToBuffersMap = new HashMap<Geometry, MeshBuffers>();
    for (Entry<Integer, MeshBuffers> entry : faceMeshes.entrySet()) {
        MeshBuffers meshBuffers = entry.getValue();
        Mesh mesh = new Mesh();
        if (meshBuffers.isShortIndexBuffer()) {
            mesh.setBuffer(Type.Index, 1, (ShortBuffer) meshBuffers.getIndexBuffer());
        } else {
            mesh.setBuffer(Type.Index, 1, (IntBuffer) meshBuffers.getIndexBuffer());
        }
        mesh.setBuffer(meshBuffers.getPositionsBuffer());
        mesh.setBuffer(meshBuffers.getNormalsBuffer());
        if (meshBuffers.areVertexColorsUsed()) {
            mesh.setBuffer(Type.Color, 4, meshBuffers.getVertexColorsBuffer());
            mesh.getBuffer(Type.Color).setNormalized(true);
        }
        BoneBuffersData boneBuffersData = meshBuffers.getBoneBuffers();
        if (boneBuffersData != null) {
            mesh.setMaxNumWeights(boneBuffersData.maximumWeightsPerVertex);
            mesh.setBuffer(boneBuffersData.verticesWeights);
            mesh.setBuffer(boneBuffersData.verticesWeightsIndices);
            LOGGER.fine("Generating bind pose and normal buffers.");
            mesh.generateBindPose(true);
            // change the usage type of vertex and normal buffers from Static to Stream
            mesh.getBuffer(Type.Position).setUsage(Usage.Stream);
            mesh.getBuffer(Type.Normal).setUsage(Usage.Stream);
            // creating empty buffers for HW skinning; the buffers will be setup if ever used
            VertexBuffer verticesWeightsHW = new VertexBuffer(Type.HWBoneWeight);
            VertexBuffer verticesWeightsIndicesHW = new VertexBuffer(Type.HWBoneIndex);
            mesh.setBuffer(verticesWeightsHW);
            mesh.setBuffer(verticesWeightsIndicesHW);
        }
        Geometry geometry = new Geometry(name + (result.size() + 1), mesh);
        if (properties != null && properties.getValue() != null) {
            meshHelper.applyProperties(geometry, properties);
        }
        result.add(geometry);
        geometryToBuffersMap.put(geometry, meshBuffers);
    }
    LOGGER.fine("Applying materials to geometries.");
    for (Entry<Geometry, MeshBuffers> entry : geometryToBuffersMap.entrySet()) {
        int materialIndex = entry.getValue().getMaterialIndex();
        Geometry geometry = entry.getKey();
        if (materialIndex >= 0 && materials != null && materials.length > materialIndex && materials[materialIndex] != null) {
            materials[materialIndex].applyMaterial(geometry, meshStructure.getOldMemoryAddress(), entry.getValue().getUvCoords(), blenderContext);
        } else {
            Material defaultMaterial = blenderContext.getDefaultMaterial().clone();
            defaultMaterial.getAdditionalRenderState().setFaceCullMode(FaceCullMode.Off);
            geometry.setMaterial(defaultMaterial);
        }
    }
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) VertexBuffer(com.jme3.scene.VertexBuffer) ArrayList(java.util.ArrayList) BoneBuffersData(com.jme3.scene.plugins.blender.meshes.MeshBuffers.BoneBuffersData) ArrayList(java.util.ArrayList) List(java.util.List) Mesh(com.jme3.scene.Mesh) Material(com.jme3.material.Material) Geometry(com.jme3.scene.Geometry) Vector3f(com.jme3.math.Vector3f) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 60 with Vector2f

use of com.jme3.math.Vector2f in project jmonkeyengine by jMonkeyEngine.

the class TriangulatedTexture method castToUVS.

/**
     * This method alters the images to fit them into UV coordinates of the
     * given target texture.
     * 
     * @param targetTexture
     *            the texture to whose UV coordinates we fit current images
     * @param blenderContext
     *            the blender context
     */
public void castToUVS(TriangulatedTexture targetTexture, BlenderContext blenderContext) {
    int[] sourceSize = new int[2], targetSize = new int[2];
    ImageLoader imageLoader = new ImageLoader();
    TextureHelper textureHelper = blenderContext.getHelper(TextureHelper.class);
    for (TriangleTextureElement entry : faceTextures) {
        TriangleTextureElement targetFaceTextureElement = targetTexture.getFaceTextureElement(entry.faceIndex);
        Vector2f[] dest = targetFaceTextureElement.uv;
        // get the sizes of the source and target images
        sourceSize[0] = entry.image.getWidth();
        sourceSize[1] = entry.image.getHeight();
        targetSize[0] = targetFaceTextureElement.image.getWidth();
        targetSize[1] = targetFaceTextureElement.image.getHeight();
        // create triangle transformation
        AffineTransform affineTransform = textureHelper.createAffineTransform(entry.uv, dest, sourceSize, targetSize);
        // compute the result texture
        BufferedImage sourceImage = ImageToAwt.convert(entry.image, false, true, 0);
        BufferedImage targetImage = new BufferedImage(targetSize[0], targetSize[1], sourceImage.getType());
        Graphics2D g = targetImage.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.drawImage(sourceImage, affineTransform, null);
        g.dispose();
        Image output = imageLoader.load(targetImage, false);
        entry.image = output;
        entry.uv[0].set(dest[0]);
        entry.uv[1].set(dest[1]);
        entry.uv[2].set(dest[2]);
    }
}
Also used : Vector2f(com.jme3.math.Vector2f) AffineTransform(java.awt.geom.AffineTransform) Image(com.jme3.texture.Image) BufferedImage(java.awt.image.BufferedImage) BufferedImage(java.awt.image.BufferedImage) Graphics2D(java.awt.Graphics2D)

Aggregations

Vector2f (com.jme3.math.Vector2f)80 Vector3f (com.jme3.math.Vector3f)38 Geometry (com.jme3.scene.Geometry)22 Material (com.jme3.material.Material)20 Box (com.jme3.scene.shape.Box)17 ArrayList (java.util.ArrayList)14 Texture (com.jme3.texture.Texture)9 List (java.util.List)9 Node (com.jme3.scene.Node)8 Sphere (com.jme3.scene.shape.Sphere)8 FloatBuffer (java.nio.FloatBuffer)8 InputCapsule (com.jme3.export.InputCapsule)7 Spatial (com.jme3.scene.Spatial)7 DirectionalLight (com.jme3.light.DirectionalLight)6 Mesh (com.jme3.scene.Mesh)6 AmbientLight (com.jme3.light.AmbientLight)5 Quad (com.jme3.scene.shape.Quad)5 BoundingBox (com.jme3.bounding.BoundingBox)4 RigidBodyControl (com.jme3.bullet.control.RigidBodyControl)4 CollisionResult (com.jme3.collision.CollisionResult)4