Merge pull request 'sceneLoaderCollisionMeshGen' (#129) from sceneLoaderCollisionMeshGen into master

Reviewed-on: https://git.austinwhoover.com/gitadmin/Renderer/pulls/129
This commit is contained in:
gitadmin 2022-12-12 00:27:08 -05:00
commit 9aa5cadb62
20 changed files with 308 additions and 44 deletions

View File

@ -21,6 +21,7 @@
],
"files" : [
"Data/objects/floatingisland.json"
"Data/objects/floatingisland.json",
"Data/objects/testscene1objects.json"
]
}

View File

@ -0,0 +1,47 @@
{
"objects" : [
{
"objectId" : "terrain1",
"modelPath" : "Models/startingarea1.fbx",
"tokens" : [
"DISABLE_COLLISION_REACTION",
"GENERATE_COLLISION_TERRAIN"
],
"collidable": null,
"graphicsTemplate": null
},
{
"objectId" : "smoke1",
"modelPath" : "Models/unitcube.fbx",
"tokens" : [
"DRAW_TRANSPARENT_PASS"
],
"collidable": null,
"graphicsTemplate": {
"shaderOverrideMeshList": [
"Cube"
],
"shaderMap": {
"Cube": {
"vertexPath": "Shaders/smoke1/smoke1.vs",
"geometryPath": null,
"fragmentPath": "Shaders/smoke1/smoke1.fs"
}
}
}
},
{
"objectId" : "geometrytest1",
"modelPath" : "Models/geometry1.fbx",
"tokens" : [
"DISABLE_COLLISION_REACTION",
"GENERATE_COLLISION_TERRAIN"
],
"collidable": null,
"graphicsTemplate": null
}
],
"files" : []
}

View File

@ -1,16 +0,0 @@
{
"terrainObjects" : [
{
"objectId" : "terrain1",
"modelPath" : "Models/startingarea1.fbx",
"tokens" : [
],
"collidable": null
}
],
"files" : [
"Data/objects/floatingisland.json"
]
}

BIN
assets/Models/geometry1.fbx Normal file

Binary file not shown.

Binary file not shown.

View File

@ -1,15 +1,15 @@
{
"entities": [
{
"type": "item",
"subtype": "Katana",
"posX": 3,
"posY": 5,
"posZ": 5,
"rotX": 0,
"type": "object",
"subtype": "terrain1",
"posX": 2,
"posY": 1,
"posZ": 2,
"rotX": -0.7071068,
"rotY": 0,
"rotZ": 0,
"rotW": 1
"rotW": 0.7071068
}
],
"scriptPaths": [

BIN
docs/phyicsForDummies.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

View File

@ -761,11 +761,11 @@ public class LoadingThread extends Thread {
// EntityUtils.getPosition(myCube).set(3,1,3);
//work on smoke shader
Entity myCube = EntityUtils.spawnDrawableEntity("Models/unitcube.fbx");
EntityUtils.getActor(myCube).maskShader("Cube", "Shaders/smoke1/smoke1.vs", "Shaders/smoke1/smoke1.fs");
Globals.assetManager.addShaderToQueue("Shaders/smoke1/smoke1.vs", "Shaders/smoke1/smoke1.fs");
myCube.putData(EntityDataStrings.DRAW_TRANSPARENT_PASS, true);
EntityUtils.getPosition(myCube).set(3,1,3);
// Entity myCube = EntityUtils.spawnDrawableEntity("Models/unitcube.fbx");
// EntityUtils.getActor(myCube).maskShader("Cube", "Shaders/smoke1/smoke1.vs", "Shaders/smoke1/smoke1.fs");
// Globals.assetManager.addShaderToQueue("Shaders/smoke1/smoke1.vs", "Shaders/smoke1/smoke1.fs");
// myCube.putData(EntityDataStrings.DRAW_TRANSPARENT_PASS, true);
// EntityUtils.getPosition(myCube).set(3,1,3);
SceneLoader loader = new SceneLoader();
loader.serverInstantiateSceneFile("Scenes/testscene1/testscene1.json");

View File

@ -1,6 +1,8 @@
package electrosphere.engine.assetmanager;
import electrosphere.audio.AudioBuffer;
import electrosphere.collision.dispatch.CollisionObject;
import electrosphere.game.collision.PhysicsUtils;
import electrosphere.renderer.Mesh;
import electrosphere.renderer.Model;
import electrosphere.renderer.ShaderProgram;
@ -15,6 +17,8 @@ import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import org.lwjgl.assimp.AIScene;
/**
*
* @author amaterasu
@ -34,8 +38,8 @@ public class AssetManager {
Map<String,ShaderProgram> shadersLoadedIntoMemory = new ConcurrentHashMap<String,ShaderProgram>();
List<ActorShaderMask> shadersInQueue = new CopyOnWriteArrayList<ActorShaderMask>();
Map<String,CollisionObject> physicsMeshesLoadedIntoMemory = new ConcurrentHashMap<String,CollisionObject>();
List<String> physicsMeshesToLoad = new CopyOnWriteArrayList<String>();
@ -47,7 +51,13 @@ public class AssetManager {
public void loadAssetsInQueue(){
for(String currentPath : modelsInQueue){
modelsInQueue.remove(currentPath);
modelsLoadedIntoMemory.put(currentPath, ModelLoader.load_Model_From_File(currentPath));
AIScene scene = ModelLoader.loadAIScene(currentPath);
modelsLoadedIntoMemory.put(currentPath, ModelLoader.createModelFromAiScene(scene,currentPath));
if(physicsMeshesToLoad.contains(currentPath)){
//create physics
physicsMeshesToLoad.remove(currentPath);
physicsMeshesLoadedIntoMemory.put(currentPath,PhysicsUtils.generateRigidBodyFromAIScene(scene));
}
}
for(String currentPath : texturesInQueue){
texturesInQueue.remove(currentPath);
@ -272,7 +282,19 @@ public class AssetManager {
//
//COLLISION MESH
//
public void addCollisionMeshToQueue(String path){
if(!physicsMeshesToLoad.contains(path) && !physicsMeshesLoadedIntoMemory.containsKey(path)){
physicsMeshesToLoad.add(path);
}
}
public CollisionObject fetchCollisionObject(String path){
return physicsMeshesLoadedIntoMemory.get(path);
}

View File

@ -4,6 +4,7 @@ import electrosphere.entity.Entity;
import electrosphere.entity.EntityUtils;
import electrosphere.entity.types.creature.CreatureUtils;
import electrosphere.entity.types.item.ItemUtils;
import electrosphere.entity.types.object.ObjectUtils;
import electrosphere.main.Globals;
import electrosphere.util.FileUtils;
@ -35,7 +36,11 @@ public class SceneLoader {
EntityUtils.getRotation(newEntity).set((float)descriptor.rotX, (float)descriptor.rotY, (float)descriptor.rotZ, (float)descriptor.rotW);
} break;
case EntityDescriptor.TYPE_OBJECT:
case EntityDescriptor.TYPE_OBJECT: {
Entity newEntity = ObjectUtils.spawnBasicObject(descriptor.subtype);
EntityUtils.getPosition(newEntity).set(descriptor.posX,descriptor.posY,descriptor.posZ);
EntityUtils.getRotation(newEntity).set((float)descriptor.rotX, (float)descriptor.rotY, (float)descriptor.rotZ, (float)descriptor.rotW);
} break;
default:
throw new UnsupportedOperationException();
}

View File

@ -37,7 +37,7 @@ public class GravityTree {
int fallFrame = 1;
float gravityVelocity = 0;
float gravityAccel = 0.0002f;
float gravityAccel = 0.0007f;
CollisionObject body;
Collidable collidable;

View File

@ -28,7 +28,7 @@ public class JumpTree implements BehaviorTree {
int jumpFrames = 0;
int currentFrame = 0;
float jumpForce = 1.0f;
float jumpForce = 10.0f;
float currentJumpForce = jumpForce;
static final float jumpFalloff = 0.99f;

View File

@ -169,6 +169,37 @@ public class CollisionObjUtils {
return rVal;
}
/**
* Attach a collision object to a provided entity
* @param entity The entity to attach a collision object to
* @param collisionObject The jBulletF collision object to attach to the entity
* @param mass The mass of the collidable
* @param collidableType The type of collidable we are attaching. For instance, "Terrain", "Creature", "Item", etc. Refer to Collidable class for options.
*/
public static void attachCollisionObjectToEntity(Entity entity, CollisionObject collisionObject, float mass, String collidableType){
Vector3d position = EntityUtils.getPosition(entity);
Vector3f scale = EntityUtils.getScale(entity);
Collidable collidable = new Collidable(entity, collidableType);
Globals.collisionEngine.registerCollisionObject(collisionObject, collidable);
Globals.collisionEngine.registerPhysicsEntity(entity);
entity.putData(EntityDataStrings.PHYSICS_COLLISION_BODY, collisionObject);
//update world transform of collision object
positionCharacter(entity,position);
entity.putData(EntityDataStrings.COLLISION_ENTITY_COLLISION_OBJECT, collisionObject);
entity.putData(EntityDataStrings.COLLISION_ENTITY_COLLIDABLE, collidable);
entity.putData(EntityDataStrings.PHYSICS_MASS, mass);
//inertia tensor
//https://scienceworld.wolfram.com/physics/MomentofInertiaCylinder.html
Matrix4f inertiaTensor = new Matrix4f();
inertiaTensor.m00(mass * scale.y * scale.y / 12.0f + mass * scale.x * scale.x / 4.0f);
inertiaTensor.m11(mass * scale.y * scale.y / 12.0f + mass * scale.x * scale.x / 4.0f);
inertiaTensor.m22(mass * scale.x * scale.x / 2.0f);
entity.putData(EntityDataStrings.PHYSICS_INVERSE_INERTIA_TENSOR, inertiaTensor.invert());
}
public static CollisionObject getCollisionBody(Entity e){
return (CollisionObject)e.getData(EntityDataStrings.PHYSICS_COLLISION_BODY);

View File

@ -7,6 +7,7 @@ import electrosphere.collision.dispatch.CollisionObject;
import electrosphere.entity.Entity;
import electrosphere.entity.EntityDataStrings;
import electrosphere.entity.EntityUtils;
import electrosphere.entity.state.BehaviorTree;
import electrosphere.entity.state.IdleTree;
import electrosphere.entity.state.collidable.CollidableTree;
import electrosphere.entity.state.gravity.GravityTree;
@ -36,6 +37,26 @@ public class ObjectUtils {
case "DISABLE_COLLISION_REACTION": {
collisionMakeDynamic = false;
} break;
case "GENERATE_COLLISION_OBJECT": {
Globals.assetManager.addCollisionMeshToQueue(rawType.getModelPath());
Globals.entityManager.registerBehaviorTree(new BehaviorTree() {public void simulate() {
CollisionObject collisionObject = Globals.assetManager.fetchCollisionObject(rawType.getModelPath());
if(collisionObject != null){
Globals.entityManager.removeBehaviorTree(this);
CollisionObjUtils.attachCollisionObjectToEntity(rVal, collisionObject, 0, Collidable.TYPE_OBJECT);
}
}});
} break;
case "GENERATE_COLLISION_TERRAIN": {
Globals.assetManager.addCollisionMeshToQueue(rawType.getModelPath());
Globals.entityManager.registerBehaviorTree(new BehaviorTree() {public void simulate() {
CollisionObject collisionObject = Globals.assetManager.fetchCollisionObject(rawType.getModelPath());
if(collisionObject != null){
Globals.entityManager.removeBehaviorTree(this);
CollisionObjUtils.attachCollisionObjectToEntity(rVal, collisionObject, 0, Collidable.TYPE_TERRAIN);
}
}});
} break;
}
}
//main entity construction

View File

@ -22,6 +22,11 @@ import java.nio.IntBuffer;
import org.joml.Quaternionf;
import org.joml.Vector3d;
import org.joml.Vector3f;
import org.lwjgl.PointerBuffer;
import org.lwjgl.assimp.AIFace;
import org.lwjgl.assimp.AIMesh;
import org.lwjgl.assimp.AIScene;
import org.lwjgl.assimp.AIVector3D;
/**
*
@ -171,6 +176,101 @@ public class PhysicsUtils {
return terrainRigidBody;
}
//
// This has to use arrays and I have no fucking clue why
// If you buffer one at a time it just breaks???????????
//
/**
* Generates a rigid body from an AIScene
* @param scene The AIScene to generate a rigid body off of
* @return A rigid body based on the AIScene
*/
public static RigidBody generateRigidBodyFromAIScene(AIScene scene){
//was 0.08
float collisionMargin = 0.08f;
//http://jbullet.advel.cz/javadoc/com/bulletphysics/collision/shpaes/TriangleIndexVertexArray.html
electrosphere.collision.shapes.TriangleIndexVertexArray triangleIndexArray = new electrosphere.collision.shapes.TriangleIndexVertexArray();
PointerBuffer meshesBuffer = scene.mMeshes();
while(meshesBuffer.hasRemaining()){
AIMesh aiMesh = AIMesh.create(meshesBuffer.get());
//create indexed mesh
//http://jbullet.advel.cz/javadoc/com/bulletphysics/collision/shapes/IndexedMesh.html
electrosphere.collision.shapes.IndexedMesh indexedMesh = new electrosphere.collision.shapes.IndexedMesh();
//allocate buffer for vertices
indexedMesh.vertexBase = ByteBuffer.allocateDirect(aiMesh.mNumVertices()*3*Float.BYTES).order(ByteOrder.nativeOrder());
indexedMesh.numVertices = aiMesh.mNumVertices();
indexedMesh.vertexStride = 3 * Float.BYTES;
float[] verts = new float[indexedMesh.numVertices * 3];
//read vertices
AIVector3D.Buffer vertexBuffer = aiMesh.mVertices();
int vertPos = 0;
while(vertexBuffer.hasRemaining()){
AIVector3D vector = vertexBuffer.get();
verts[vertPos+0] = vector.x();
verts[vertPos+1] = vector.y();
verts[vertPos+2] = vector.z();
vertPos = vertPos + 3;
}
indexedMesh.vertexBase.asFloatBuffer().put(verts);
//allocate buffer for indices
indexedMesh.triangleIndexBase = ByteBuffer.allocateDirect(aiMesh.mNumFaces()*3*Float.BYTES).order(ByteOrder.nativeOrder());
indexedMesh.numTriangles = aiMesh.mNumFaces();
indexedMesh.triangleIndexStride = 3 * Float.BYTES;
int[] indices = new int[indexedMesh.numTriangles * 3];
int indicesPos = 0;
//read faces
AIFace.Buffer faceBuffer = aiMesh.mFaces();
while(faceBuffer.hasRemaining()){
AIFace currentFace = faceBuffer.get();
IntBuffer indexBuffer = currentFace.mIndices();
while(indexBuffer.hasRemaining()){
int index = indexBuffer.get();
indices[indicesPos] = index;
indicesPos++;
}
}
indexedMesh.triangleIndexBase.asIntBuffer().put(indices);
//push indexed mesh into triangle index array
triangleIndexArray.addIndexedMesh(indexedMesh); //this assumes the scalar type is integer (assumes bytebuffer is actually integer
// triangleIndexArray.calculateAabbBruteForce(aabbMin, aabbMax);
}
//http://jbullet.advel.cz/javadoc/com/bulletphysics/collision/shapes/BvhTriangleMeshShape.html
electrosphere.collision.shapes.BvhTriangleMeshShape terrainShape = new electrosphere.collision.shapes.BvhTriangleMeshShape(
triangleIndexArray,
true // "useQuantizedAabbCompression" -- apparently means better memory usage ( http://jbullet.advel.cz/javadoc/com/bulletphysics/collision/shapes/BvhTriangleMeshShape.html )
);
//uncomment if we start falling through things again
terrainShape.setMargin(collisionMargin);
// terrainShape.localGetSupportingVertex(new javax.vecmath.Vector3f(1,0,0), aabbMin);
// terrainShape.recalcLocalAabb();
// terrainShape.getLocalAabbMin(aabbMin);
// terrainShape.getLocalAabbMax(aabbMax);
DefaultMotionState defaultMotionState = new DefaultMotionState(new Transform(new javax.vecmath.Matrix4f(new javax.vecmath.Quat4f(0,0,0,1),new javax.vecmath.Vector3f(0,0,0),1.0f)));
RigidBodyConstructionInfo terrainRigidBodyCI = new RigidBodyConstructionInfo(0, defaultMotionState, terrainShape);
RigidBody terrainRigidBody = new RigidBody(terrainRigidBodyCI);
return terrainRigidBody;
}
public static void addTestPlaneRigidBody(){

View File

@ -0,0 +1,21 @@
package electrosphere.game.data.graphics;
import java.util.List;
import java.util.Map;
public class GraphicsTemplate {
List<String> shaderOverrideMeshList;
Map<String,ShaderSet> shaderMap;
public List<String> getShaderOverrideMeshList(){
return shaderOverrideMeshList;
}
public Map<String,ShaderSet> getShaderMap(){
return shaderMap;
}
}

View File

@ -0,0 +1,21 @@
package electrosphere.game.data.graphics;
public class ShaderSet {
String vertexPath;
String geometryPath;
String fragmentPath;
public String getVertexPath(){
return vertexPath;
}
public String getGeometryPath(){
return geometryPath;
}
public String getFragmentPath(){
return fragmentPath;
}
}

View File

@ -2,6 +2,8 @@ package electrosphere.game.data.object.type;
import electrosphere.entity.types.hitbox.HitboxData;
import electrosphere.game.data.creature.type.CollidableTemplate;
import electrosphere.game.data.graphics.GraphicsTemplate;
import java.util.List;
public class ObjectData {
@ -10,6 +12,7 @@ public class ObjectData {
String modelPath;
List<String> tokens;
CollidableTemplate collidable;
GraphicsTemplate graphicsTemplate;
public String getObjectId() {
return objectId;
@ -26,5 +29,9 @@ public class ObjectData {
public CollidableTemplate getCollidable(){
return collidable;
}
public GraphicsTemplate getGraphicsTemplate(){
return graphicsTemplate;
}
}

View File

@ -11,6 +11,7 @@ import org.lwjgl.glfw.GLFWErrorCallback;
import electrosphere.audio.AudioEngine;
import electrosphere.auth.AuthenticationManager;
import electrosphere.collision.dispatch.CollisionObject;
import electrosphere.controls.CameraHandler;
import electrosphere.controls.ControlCallback;
import electrosphere.controls.ControlHandler;
@ -223,7 +224,6 @@ public class Globals {
//
//Engine - Main managers/variables
//

View File

@ -26,23 +26,27 @@ import static org.lwjgl.assimp.Assimp.*;
import static org.lwjgl.assimp.Assimp.aiImportFile;
public class ModelLoader {
public static Model load_Model_From_File(String fileName){
Model rVal;
AIScene scene;
public static AIScene loadAIScene(String path){
AIScene rVal;
// File file = new File(Thread.currentThread().getContextClassLoader().getResource(fileName).getFile());
// Main.class.getResourceAsStream(fileName).readAllBytes();
File toRead = FileUtils.getAssetFile(fileName);
scene = aiImportFile(toRead.getAbsolutePath(),
File toRead = FileUtils.getAssetFile(path);
rVal = aiImportFile(toRead.getAbsolutePath(),
aiProcess_GenSmoothNormals |
aiProcess_JoinIdenticalVertices |
aiProcess_Triangulate |
aiProcess_FixInfacingNormals |
aiProcess_LimitBoneWeights);
if(scene == null){
if(rVal == null){
throw new IllegalStateException(aiGetErrorString());
}
return rVal;
}
public static Model createModelFromAiScene(AIScene scene, String path){
Model rVal;
rVal = Model.createModelFromAiscene(scene);
attemptAddTexturesFromPathname(fileName, rVal);
attemptAddTexturesFromPathname(path, rVal);
return rVal;
}