Search in sources :

Example 1 with Mesh

use of io.xol.chunkstories.api.mesh.Mesh in project chunkstories by Hugobros3.

the class ClientMeshStore method getRenderableMesh.

@Override
public RenderableMesh getRenderableMesh(String meshName) {
    RenderableMesh rm = renderableMeshes.get(meshName);
    if (rm == null) {
        Mesh mesh = this.getMesh(meshName);
        if (mesh == null) {
            // Really not found!
            return getRenderableMesh("./models/error.obj");
        }
        if (mesh instanceof AnimatableMesh)
            rm = new BonedRenderer((AnimatableMesh) mesh);
        else
            rm = new MeshRenderableImpl(mesh);
        renderableMeshes.put(meshName, rm);
    }
    return rm;
}
Also used : RenderableMesh(io.xol.chunkstories.api.rendering.mesh.RenderableMesh) BonedRenderer(io.xol.chunkstories.renderer.mesh.BonedRenderer) AnimatableMesh(io.xol.chunkstories.api.mesh.AnimatableMesh) AnimatableMesh(io.xol.chunkstories.api.mesh.AnimatableMesh) RenderableMesh(io.xol.chunkstories.api.rendering.mesh.RenderableMesh) Mesh(io.xol.chunkstories.api.mesh.Mesh)

Example 2 with Mesh

use of io.xol.chunkstories.api.mesh.Mesh in project chunkstories by Hugobros3.

the class ContentTests method testBasicContentInit.

@Test
public void testBasicContentInit() {
    TestGameContext testContext = new TestGameContext(null);
    Mesh m = testContext.getContent().meshes().getMesh("./models/human_all_animations.dae");
    System.out.println(m.getVerticesCount() + " lol:" + m.getClass());
    m = testContext.getContent().meshes().getMesh("./models/human.obj");
    System.out.println(m.getVerticesCount() + " lol:" + m.getClass());
    m = testContext.getContent().meshes().getMesh("./models/human.dae");
    System.out.println(m.getVerticesCount() + " lol:" + m.getClass());
    System.out.println(m.getVertices().get(0) + ":" + m.getVertices().get(1) + ":" + m.getVertices().get(2));
/*try {
			Asset a = testContext.getContent().getAsset("./models/human_all_animations.dae");
			//Asset a = testContext.getContent().getAsset("./animations/human/ded.bvh");
			
			new NativeAssimpMesh(a, testContext.getContent().meshes());
			new AssimpMeshLoader(a, testContext.getContent().meshes());
		} catch (MeshLoadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
}
Also used : Mesh(io.xol.chunkstories.api.mesh.Mesh) Test(org.junit.Test)

Example 3 with Mesh

use of io.xol.chunkstories.api.mesh.Mesh in project chunkstories by Hugobros3.

the class MeshStore method getMesh.

@Override
public Mesh getMesh(String meshName) {
    Mesh mesh = meshes.get(meshName);
    if (mesh == null) {
        Asset a = modsManager.getAsset(meshName);
        try {
            // mesh = loader.loadMeshFromAsset(a);
            mesh = loader.load(a);
        } catch (MeshLoadException e) {
            e.printStackTrace();
            logger().error("Mesh " + meshName + " couldn't be load using MeshLoader " + loader.getClass().getName() + " ,stack trace above.");
            return null;
        }
        meshes.put(meshName, mesh);
    }
    return mesh;
}
Also used : AnimatableMesh(io.xol.chunkstories.api.mesh.AnimatableMesh) Mesh(io.xol.chunkstories.api.mesh.Mesh) Asset(io.xol.chunkstories.api.content.Asset) MeshLoadException(io.xol.chunkstories.api.exceptions.content.MeshLoadException)

Example 4 with Mesh

use of io.xol.chunkstories.api.mesh.Mesh in project chunkstories by Hugobros3.

the class WavefrontLoader method loadMeshFromAsset.

public Mesh loadMeshFromAsset(Asset asset) throws MeshLoadException {
    List<float[]> vertices = new ArrayList<float[]>();
    List<float[]> texcoords = new ArrayList<float[]>();
    List<float[]> normals = new ArrayList<float[]>();
    /*
		// Reset values
		vertices.clear();
		texcoords.clear();
		normals.clear();*/
    Map<String, Integer> groupsSizesMap = new HashMap<String, Integer>();
    Map<String, List<float[]>> tempGroups = new HashMap<String, List<float[]>>();
    boolean hasGroups = false;
    int groupSize = 0;
    String group = "root";
    int totalVertices = 0;
    int line = 0;
    try {
        // Read the actual file
        BufferedReader reader = new BufferedReader(asset.reader());
        String[] splitted;
        String[] e;
        String l;
        float[] v, t, n;
        while ((l = reader.readLine()) != null) {
            line++;
            if (!l.startsWith("#")) {
                splitted = l.split(" ");
                // Parse the various vertices attributes
                if (l.startsWith("vt")) {
                    // Note that we invert Y texture coordinates from blender to ogl
                    texcoords.add(new float[] { Float.parseFloat(splitted[1]), (1 - Float.parseFloat(splitted[2])) });
                } else if (l.startsWith("vn")) {
                    normals.add(new float[] { Float.parseFloat(splitted[1]), Float.parseFloat(splitted[2]), Float.parseFloat(splitted[3]) });
                } else if (l.startsWith("v")) {
                    vertices.add(new float[] { Float.parseFloat(splitted[1]), Float.parseFloat(splitted[2]), Float.parseFloat(splitted[3]) });
                } else // Vertices group manager
                if (l.startsWith("g")) {
                    hasGroups = true;
                    // If the current group contains vertices, note the size and put it in the hashmap
                    if (groupSize > 0) {
                        // All is simple if this is the first time we are done with this group ...
                        if (!groupsSizesMap.containsKey(group))
                            groupsSizesMap.put(group, groupSize);
                        else // But if that group already exists it means that it's vertices are splitted arround the file and we need to add up
                        // the sizes and then write them in the correct order in the final buffer !
                        {
                            int i = groupsSizesMap.get(group) + groupSize;
                            groupsSizesMap.remove(group);
                            groupsSizesMap.put(group, i);
                        }
                    }
                    // Resets group size and change the current group name
                    groupSize = 0;
                    group = splitted[1];
                } else if (l.startsWith("f")) {
                    groupSize++;
                    // No support for quads, only triangles.
                    if (splitted.length == 4) {
                        for (// For each vertex of
                        int i = 1; // For each vertex of
                        i <= 3; // For each vertex of
                        i++) // the triangle.
                        {
                            e = splitted[i].split("/");
                            // Gets the various properties of the Obj file
                            v = vertices.get(Integer.parseInt(e[0]) - 1);
                            t = texcoords.get(Integer.parseInt(e[1]) - 1);
                            n = normals.get(Integer.parseInt(e[2]) - 1);
                            // Add the face to the current vertex group
                            if (!tempGroups.containsKey(group))
                                tempGroups.put(group, new ArrayList<float[]>());
                            tempGroups.get(group).add(new float[] { v[0], v[1], v[2], t[0], t[1], n[0], n[1], n[2] });
                        }
                        totalVertices += 3;
                    }
                }
            }
        }
        // Same logic as above, terminates the last group
        if (groupSize > 0) {
            if (!groupsSizesMap.containsKey(group))
                groupsSizesMap.put(group, groupSize);
            else {
                int i = groupsSizesMap.get(group) + groupSize;
                groupsSizesMap.remove(group);
                groupsSizesMap.put(group, i);
            }
        }
        reader.close();
        // BufferUtils.createFloatBuffer(3 * totalVertices);
        FloatBuffer verticesBuffer = ByteBuffer.allocateDirect(3 * totalVertices * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
        // BufferUtils.createFloatBuffer(2 * totalVertices);
        FloatBuffer textureCoordinatesBuffer = ByteBuffer.allocateDirect(2 * totalVertices * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
        // BufferUtils.createFloatBuffer(3 * totalVertices);
        FloatBuffer normalsBuffer = ByteBuffer.allocateDirect(3 * totalVertices * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
        // Iterates over each group name in order of apparition
        for (String gName : tempGroups.keySet()) {
            for (float[] gData : tempGroups.get(gName)) {
                verticesBuffer.put(gData[0]);
                verticesBuffer.put(gData[1]);
                verticesBuffer.put(gData[2]);
                textureCoordinatesBuffer.put(gData[3]);
                textureCoordinatesBuffer.put(gData[4]);
                normalsBuffer.put(gData[5]);
                normalsBuffer.put(gData[6]);
                normalsBuffer.put(gData[7]);
            // System.out.println(gData[0]);
            }
        }
        verticesBuffer.flip();
        textureCoordinatesBuffer.flip();
        normalsBuffer.flip();
        if (hasGroups)
            // new MultiPartMesh(verticesBuffer, textureCoordinatesBuffer, normalsBuffer, groupsSizesMap);
            return null;
        else
            return new Mesh(verticesBuffer, textureCoordinatesBuffer, normalsBuffer);
    // return new ObjMeshRenderable(totalVertices, verticesBuffer, textureCoordinatesBuffer, normalsBuffer, groupsSizesMap);
    /*}*/
    } catch (Exception e) {
        // God damnit
        logger().error("Error loading model at line " + line);
        e.printStackTrace();
    }
    return null;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Mesh(io.xol.chunkstories.api.mesh.Mesh) FloatBuffer(java.nio.FloatBuffer) MeshLoadException(io.xol.chunkstories.api.exceptions.content.MeshLoadException) BufferedReader(java.io.BufferedReader) ArrayList(java.util.ArrayList) List(java.util.List)

Example 5 with Mesh

use of io.xol.chunkstories.api.mesh.Mesh in project chunkstories by Hugobros3.

the class AssimpMeshLoader method load.

public Mesh load(Asset mainAsset) throws MeshLoadException {
    Importer im = new Importer();
    assimp.SettingsKt.setASSIMP_LOAD_TEXTURES(false);
    im.setIoHandler(new AssetIOSystem(store.parent()));
    AiScene scene = im.readFile(mainAsset.getName(), im.getIoHandler(), 0);
    /*System.out.println(scene);
		
		for(AiMesh mesh : scene.getMeshes()) {
			System.out.println(mesh.getName());
			System.out.println(mesh.getFaces().size());
			
			AiMaterial material = scene.getMaterials().get(mesh.getMaterialIndex());
			System.out.println("mat: "+material.getName());
			System.out.println(material.getTextures());
			
			System.out.println("bones: "+mesh.getNumBones());
			for(AiBone bone : mesh.getBones()) {
				System.out.println(bone.getName().substring(bone.getName().lastIndexOf('_') + 1));
				System.out.println(bone.getNumWeights());
				System.out.println(tomat4(bone.getOffsetMatrix()));
			}
		}*/
    if (scene == null) {
        logger.error("Could not load meshes from asset: " + mainAsset);
        return null;
    }
    if (scene.getMeshes() == null || scene.getMeshes().size() == 0) {
        logger.error("Loaded mesh did not contain any mesh data.");
        return null;
    }
    FloatArrayList vertices = new FloatArrayList();
    FloatArrayList normals = new FloatArrayList();
    FloatArrayList texcoords = new FloatArrayList();
    Map<String, Integer> boneNames = new HashMap<>();
    ByteArrayList boneIds = new ByteArrayList();
    ByteArrayList boneWeights = new ByteArrayList();
    boolean has_bones = scene.getMeshes().get(0).getHasBones();
    Map<Integer, VertexBoneWeights> boneWeightsForeachVertex = null;
    if (has_bones)
        boneWeightsForeachVertex = new HashMap<>();
    for (AiMesh mesh : scene.getMeshes()) {
        int existing_vertices = vertices.size() / 3;
        if (has_bones) {
            for (int i = 0; i < mesh.getNumVertices(); i++) {
                boneWeightsForeachVertex.put(i + existing_vertices, new VertexBoneWeights());
            }
            for (AiBone bone : mesh.getBones()) {
                String boneName = bone.getName().substring(bone.getName().lastIndexOf('_') + 1);
                int boneId = boneNames.getOrDefault(boneName, -1);
                if (boneId == -1) {
                    boneId = boneNames.size();
                    boneNames.put(boneName, boneId);
                }
                for (AiVertexWeight weight : bone.getWeights()) {
                    int vid = existing_vertices + weight.getVertexId();
                    VertexBoneWeights vw = boneWeightsForeachVertex.get(vid);
                    vw.bones[vw.slot] = boneId;
                    vw.weights[vw.slot] = weight.getWeight();
                    vw.slot++;
                    vw.totalWeight += weight.getWeight();
                    if (vw.totalWeight > 1.0f) {
                        logger.warn("Total weight > 1 for vertex #" + vid);
                    }
                    if (vw.slot >= 4) {
                        logger.error("More than 4 bones weighted against vertex #" + vid);
                        return null;
                    }
                }
            }
        }
        for (List<Integer> face : mesh.getFaces()) {
            if (face.size() == 3) {
                for (int i = 0; i < 3; i++) {
                    Vec3 vertex = mesh.getVertices().get(face.get(i));
                    Vec3 normal = mesh.getNormals().get(face.get(i));
                    float[] texcoord = mesh.getTextureCoords().get(0).get(face.get(i));
                    vertices.add(vertex.x, vertex.y, vertex.z);
                    normals.add(normal.x, normal.y, normal.z);
                    texcoords.add(texcoord[0], 1.0f - texcoord[1]);
                    if (has_bones) {
                        VertexBoneWeights boned = boneWeightsForeachVertex.get(existing_vertices + face.get(i));
                        boneIds.add((byte) boned.bones[0]);
                        boneIds.add((byte) boned.bones[1]);
                        boneIds.add((byte) boned.bones[2]);
                        boneIds.add((byte) boned.bones[3]);
                        boneWeights.add((byte) (boned.weights[0] * 255));
                        boneWeights.add((byte) (boned.weights[1] * 255));
                        boneWeights.add((byte) (boned.weights[2] * 255));
                        boneWeights.add((byte) (boned.weights[3] * 255));
                    }
                }
            } else
                logger.warn("Should triangulate! (face=" + face.size() + ")");
        }
    }
    FloatBuffer verticesBuffer = toFloatBuffer(vertices);
    FloatBuffer normalsBuffer = toFloatBuffer(normals);
    FloatBuffer texcoordsBuffer = toFloatBuffer(texcoords);
    ByteBuffer boneIdsBuffer = toByteBuffer(boneIds);
    ByteBuffer boneWeightsBuffer = toByteBuffer(boneWeights);
    String[] boneNamesArray = new String[boneNames.size()];
    for (Entry<String, Integer> e : boneNames.entrySet()) {
        boneNamesArray[e.getValue()] = e.getKey();
    }
    if (has_bones)
        return new AnimatableMesh(verticesBuffer, texcoordsBuffer, normalsBuffer, boneNamesArray, boneIdsBuffer, boneWeightsBuffer);
    else
        return new Mesh(verticesBuffer, texcoordsBuffer, normalsBuffer);
}
Also used : AiVertexWeight(assimp.AiVertexWeight) AiMesh(assimp.AiMesh) HashMap(java.util.HashMap) AiScene(assimp.AiScene) FloatBuffer(java.nio.FloatBuffer) ByteArrayList(com.carrotsearch.hppc.ByteArrayList) Vec3(glm_.vec3.Vec3) FloatArrayList(com.carrotsearch.hppc.FloatArrayList) Importer(assimp.Importer) AnimatableMesh(io.xol.chunkstories.api.mesh.AnimatableMesh) AnimatableMesh(io.xol.chunkstories.api.mesh.AnimatableMesh) Mesh(io.xol.chunkstories.api.mesh.Mesh) AiMesh(assimp.AiMesh) ByteBuffer(java.nio.ByteBuffer) AiBone(assimp.AiBone)

Aggregations

Mesh (io.xol.chunkstories.api.mesh.Mesh)5 AnimatableMesh (io.xol.chunkstories.api.mesh.AnimatableMesh)3 MeshLoadException (io.xol.chunkstories.api.exceptions.content.MeshLoadException)2 FloatBuffer (java.nio.FloatBuffer)2 HashMap (java.util.HashMap)2 AiBone (assimp.AiBone)1 AiMesh (assimp.AiMesh)1 AiScene (assimp.AiScene)1 AiVertexWeight (assimp.AiVertexWeight)1 Importer (assimp.Importer)1 ByteArrayList (com.carrotsearch.hppc.ByteArrayList)1 FloatArrayList (com.carrotsearch.hppc.FloatArrayList)1 Vec3 (glm_.vec3.Vec3)1 Asset (io.xol.chunkstories.api.content.Asset)1 RenderableMesh (io.xol.chunkstories.api.rendering.mesh.RenderableMesh)1 BonedRenderer (io.xol.chunkstories.renderer.mesh.BonedRenderer)1 BufferedReader (java.io.BufferedReader)1 ByteBuffer (java.nio.ByteBuffer)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1