1 package com.jme3.bullet.collision.shapes; 2 3 import com.bulletphysics.collision.shapes.ConvexHullShape; 4 import com.bulletphysics.util.ObjectArrayList; 5 import com.jme3.bullet.util.Converter; 6 import com.jme3.export.InputCapsule; 7 import com.jme3.export.JmeExporter; 8 import com.jme3.export.JmeImporter; 9 import com.jme3.export.OutputCapsule; 10 import com.jme3.scene.Mesh; 11 import com.jme3.scene.VertexBuffer.Type; 12 import java.io.IOException; 13 import java.nio.FloatBuffer; 14 import javax.vecmath.Vector3f; 15 16 public class HullCollisionShape extends CollisionShape { 17 18 private float[] points; 19 HullCollisionShape()20 public HullCollisionShape() { 21 } 22 HullCollisionShape(Mesh mesh)23 public HullCollisionShape(Mesh mesh) { 24 this.points = getPoints(mesh); 25 createShape(this.points); 26 } 27 HullCollisionShape(float[] points)28 public HullCollisionShape(float[] points) { 29 this.points = points; 30 createShape(this.points); 31 } 32 33 @Override write(JmeExporter ex)34 public void write(JmeExporter ex) throws IOException { 35 super.write(ex); 36 37 OutputCapsule capsule = ex.getCapsule(this); 38 capsule.write(points, "points", null); 39 } 40 41 @Override read(JmeImporter im)42 public void read(JmeImporter im) throws IOException { 43 super.read(im); 44 InputCapsule capsule = im.getCapsule(this); 45 46 // for backwards compatability 47 Mesh mesh = (Mesh) capsule.readSavable("hullMesh", null); 48 if (mesh != null) { 49 this.points = getPoints(mesh); 50 } else { 51 this.points = capsule.readFloatArray("points", null); 52 53 } 54 createShape(this.points); 55 } 56 createShape(float[] points)57 protected void createShape(float[] points) { 58 ObjectArrayList<Vector3f> pointList = new ObjectArrayList<Vector3f>(); 59 for (int i = 0; i < points.length; i += 3) { 60 pointList.add(new Vector3f(points[i], points[i + 1], points[i + 2])); 61 } 62 cShape = new ConvexHullShape(pointList); 63 cShape.setLocalScaling(Converter.convert(getScale())); 64 cShape.setMargin(margin); 65 } 66 getPoints(Mesh mesh)67 protected float[] getPoints(Mesh mesh) { 68 FloatBuffer vertices = mesh.getFloatBuffer(Type.Position); 69 vertices.rewind(); 70 int components = mesh.getVertexCount() * 3; 71 float[] pointsArray = new float[components]; 72 for (int i = 0; i < components; i += 3) { 73 pointsArray[i] = vertices.get(); 74 pointsArray[i + 1] = vertices.get(); 75 pointsArray[i + 2] = vertices.get(); 76 } 77 return pointsArray; 78 } 79 } 80