Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.olhcim.engine; import java.io.FileReader; import java.io.IOException; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.lwjgl.util.vector.Vector3f; import org.lwjgl.util.vector.Vector4f; public class Mesh { public String name; public Vector4f[] vertices; public Vector3f[] faces; public Vector4f position = new Vector4f(0, 0, 0, 1); public Vector4f rotation = new Vector4f(0, 0, 0, 0); public Vector4f scale = new Vector4f(1, 1, 1, 1); public Mesh(String name, int verticesCount, int facesCount) { this.vertices = new Vector4f[verticesCount]; this.faces = new Vector3f[facesCount]; this.name = name; } public static Mesh loadMeshFile(String fileName) { //load and parse file JSONParser parser = new JSONParser(); Object obj = null; try { obj = parser.parse(new FileReader(AppMain.class.getResource(fileName).getFile().replace("%20", " "))); } catch (IOException ex) { } catch (ParseException ex) { } JSONObject jObj = (JSONObject) obj; //load and convert to double array Object[] verticesObj = ((JSONArray) jObj.get("positions")).toArray(); double[] vertices = new double[verticesObj.length]; for (int i = 0; i < verticesObj.length; i++) { vertices[i] = (double) verticesObj[i]; } //load and convert to long array Object[] indicesObj = ((JSONArray) jObj.get("indices")).toArray(); long[] indices = new long[indicesObj.length]; for (int i = 0; i < indicesObj.length; i++) { indices[i] = (long) indicesObj[i]; } int verticesCount = vertices.length / 3; int facesCount = indices.length / 3; System.out.println("Vertices: " + verticesCount + " Faces: " + facesCount); Mesh mesh = new Mesh("", verticesCount, facesCount); // Filling the Vertices array of our mesh first for (int index = 0; index < verticesCount; index++) { float x = (float) vertices[index * 3]; float y = (float) vertices[index * 3 + 1]; float z = (float) vertices[index * 3 + 2]; mesh.vertices[index] = new Vector4f(x, y, z, 1); } // Then filling the Faces array for (int index = 0; index < facesCount; index++) { float a = (int) indices[index * 3]; float b = (int) indices[index * 3 + 1]; float c = (int) indices[index * 3 + 2]; mesh.faces[index] = new Vector3f(a, b, c); } return mesh; } }