Search in sources :

Example 6 with BoundingBox

use of com.badlogic.gdx.math.collision.BoundingBox in project libgdx-inGameConsole by StrongJoshua.

the class Box2DTest method createExplosion.

/**
	 * Creates an explosion that applies forces to the bodies relative to their
	 * position and the given x and y values.
	 * 
	 * @param maxForce
	 *            The maximum force to be applied to the bodies (diminishes as
	 *            distance from touch increases).
	 */
private void createExplosion(float x, float y, float maxForce) {
    float force;
    Vector2 touch = new Vector2(x, y);
    for (int i = 0; i < bodies.length; i++) {
        Body b = bodies[i];
        Vector2 v = b.getPosition();
        float dist = v.dst2(touch);
        if (dist == 0)
            force = maxForce;
        else
            force = MathUtils.clamp(maxForce / dist, 0, maxForce);
        float angle = v.cpy().sub(touch).angle();
        float xForce = force * MathUtils.cosDeg(angle);
        float yForce = force * MathUtils.sinDeg(angle);
        Vector3 touch3, v3, boundMin, boundMax, intersection;
        touch3 = new Vector3(touch.x, touch.y, 0);
        v3 = new Vector3(v.x, v.y, 0);
        boundMin = new Vector3(v.x - 1, v.y - 1, 0);
        boundMax = new Vector3(v.x + 1, v.y + 1, 0);
        intersection = Vector3.Zero;
        Intersector.intersectRayBounds(new Ray(touch3, v3), new BoundingBox(boundMin, boundMax), intersection);
        b.applyForce(new Vector2(xForce, yForce), new Vector2(intersection.x, intersection.y), true);
    }
}
Also used : Vector2(com.badlogic.gdx.math.Vector2) BoundingBox(com.badlogic.gdx.math.collision.BoundingBox) Vector3(com.badlogic.gdx.math.Vector3) Ray(com.badlogic.gdx.math.collision.Ray) Body(com.badlogic.gdx.physics.box2d.Body)

Example 7 with BoundingBox

use of com.badlogic.gdx.math.collision.BoundingBox in project bdx by GoranM.

the class GameObject method join.

public void join(HashMap<Mesh, ArrayList<Matrix4f>> map) {
    // Collect transformed vertex arrays for each material & calculate number of indices
    int VERT_STRIDE = Bdx.VERT_STRIDE;
    HashMap<Material, ArrayList<float[]>> tvaMap = new HashMap<Material, ArrayList<float[]>>();
    HashMap<Material, Integer> lenMap = new HashMap<Material, Integer>();
    Mesh m;
    Node node;
    Material mat;
    MeshPart meshPart;
    float[] va, tva;
    int numIndices, numVertices, offset, j, len;
    Vector3f p = new Vector3f();
    Vector3f s = new Vector3f();
    Matrix3f o = new Matrix3f();
    Vector3f vP = new Vector3f();
    Vector3f nP = new Vector3f();
    Vector3f vPT = new Vector3f();
    Vector3f nPT = new Vector3f();
    Vector3f pos = position();
    Vector3f sca = scale();
    Matrix3f oriInv = orientation().inverted();
    for (Map.Entry<Mesh, ArrayList<Matrix4f>> e : map.entrySet()) {
        m = e.getKey();
        node = m.model.nodes.get(0);
        for (Matrix4f t : e.getValue()) {
            t.get(p);
            p.sub(pos);
            p = oriInv.mult(p.div(sca));
            t.getRotationScale(o);
            o = oriInv.mult(o);
            s.set(t.m30, t.m31, t.m32);
            if (s.length() == 0) {
                s.set(1, 1, 1);
            }
            s = s.div(sca);
            for (NodePart nodePart : node.parts) {
                meshPart = nodePart.meshPart;
                numIndices = meshPart.size;
                numVertices = numIndices * VERT_STRIDE;
                offset = meshPart.offset * VERT_STRIDE;
                va = meshPart.mesh.getVertices(offset, numVertices, new float[numVertices]);
                tva = new float[numVertices];
                j = 0;
                for (int i = 0; i < numIndices; i++) {
                    vP.set(va[j], va[j + 1], va[j + 2]);
                    nP.set(va[j + 3], va[j + 4], va[j + 5]);
                    vPT.set(o.mult(vP.mul(s)));
                    vPT.add(p);
                    nPT.set(o.mult(vP.plus(nP)));
                    nPT.sub(o.mult(vP));
                    tva[j] = vPT.x;
                    tva[j + 1] = vPT.y;
                    tva[j + 2] = vPT.z;
                    tva[j + 3] = nPT.x;
                    tva[j + 4] = nPT.y;
                    tva[j + 5] = nPT.z;
                    tva[j + 6] = va[j + 6];
                    tva[j + 7] = va[j + 7];
                    j += VERT_STRIDE;
                }
                mat = m.materials.get(nodePart.material.id);
                ArrayList<float[]> l;
                if (tvaMap.containsKey(mat)) {
                    l = tvaMap.get(mat);
                    len = lenMap.get(mat);
                } else {
                    l = new ArrayList<float[]>();
                    tvaMap.put(mat, l);
                    len = 0;
                }
                l.add(tva);
                lenMap.put(mat, len + tva.length);
            }
        }
    }
    // Build a unique model out of meshparts for each material
    ModelBuilder builder = new ModelBuilder();
    builder.begin();
    short idx = 0;
    MeshPartBuilder mpb;
    for (Map.Entry<Material, ArrayList<float[]>> e : tvaMap.entrySet()) {
        mat = e.getKey();
        len = lenMap.get(mat);
        tva = new float[len];
        j = 0;
        for (float[] verts : e.getValue()) {
            numVertices = verts.length;
            for (int i = 0; i < numVertices; i++) {
                tva[i + j] = verts[i];
            }
            j += numVertices;
        }
        mpb = builder.part(mat.name(), GL20.GL_TRIANGLES, Usage.Position | Usage.Normal | Usage.TextureCoordinates, mat);
        mpb.vertex(tva);
        try {
            for (short i = 0; i < len / VERT_STRIDE; i++) {
                mpb.index(idx);
                idx += 1;
            }
        } catch (Error error) {
            throw new RuntimeException("MODEL ERROR: Models with more than 32767 vertices are not supported. Decrease the number of objects to join.");
        }
    }
    Model finishedModel = builder.end();
    // Update mesh
    mesh(new Mesh(finishedModel, scene));
    // Update dimensionsNoScale and origin
    com.badlogic.gdx.graphics.Mesh mesh = finishedModel.meshes.first();
    BoundingBox bbox = mesh.calculateBoundingBox();
    Vector3 dimensions = bbox.getDimensions(new Vector3());
    Vector3 center = bbox.getCenter(new Vector3());
    dimensionsNoScale = new Vector3f(dimensions.x, dimensions.y, dimensions.z);
    origin = new Vector3f(center.x, center.y, center.z);
    // Update body
    updateBody();
    if (json.get("mesh_name").asString() == null) {
        visible = json.get("visible").asBoolean();
    }
}
Also used : HashMap(java.util.HashMap) Node(com.badlogic.gdx.graphics.g3d.model.Node) ArrayList(java.util.ArrayList) MeshPartBuilder(com.badlogic.gdx.graphics.g3d.utils.MeshPartBuilder) MeshPart(com.badlogic.gdx.graphics.g3d.model.MeshPart) ModelBuilder(com.badlogic.gdx.graphics.g3d.utils.ModelBuilder) Matrix3f(javax.vecmath.Matrix3f) BoundingBox(com.badlogic.gdx.math.collision.BoundingBox) Mesh(com.nilunder.bdx.gl.Mesh) Material(com.nilunder.bdx.gl.Material) Vector3(com.badlogic.gdx.math.Vector3) ManifoldPoint(com.bulletphysics.collision.narrowphase.ManifoldPoint) Matrix4f(javax.vecmath.Matrix4f) Vector3f(javax.vecmath.Vector3f) Model(com.badlogic.gdx.graphics.g3d.Model) NodePart(com.badlogic.gdx.graphics.g3d.model.NodePart) HashMap(java.util.HashMap) Map(java.util.Map)

Example 8 with BoundingBox

use of com.badlogic.gdx.math.collision.BoundingBox in project libgdx by libgdx.

the class OcclusionCullingTest method create.

@Override
public void create() {
    Gdx.input.setOnscreenKeyboardVisible(true);
    super.create();
    GLProfiler.enable();
    StringBuilder sb = new StringBuilder();
    sb.append("Swipe for next test\n");
    sb.append("Long press to toggle debug mode\n");
    sb.append("Ctrl+drag to rotate\n");
    sb.append("Scroll to zoom\n");
    sb.append("Tap to spawn dynamic entity, press\n");
    sb.append("'0' to spawn ").append(KEY_SPAWN_OCCLUDEE_AMOUNT).append(" static entities\n");
    sb.append("'1' to set normal/disabled/occlusion-culling\n");
    sb.append("'2' to change camera\n");
    sb.append("'3' to toggle camera movement\n");
    sb.append("'4' to cycle occlusion buffer sizes\n");
    sb.append("'5' to toggle occlusion buffer image\n");
    sb.append("'6' to toggle shadows\n");
    instructions = sb.toString();
    AssetManager assets = new AssetManager();
    disposables.add(assets);
    for (String modelName : OCCLUDEE_PATHS_DYNAMIC) assets.load(modelName, Model.class);
    assets.load(DEFAULT_TEX_PATH, Texture.class);
    Camera shadowCamera = ((DirectionalShadowLight) light).getCamera();
    shadowCamera.viewportWidth = shadowCamera.viewportHeight = 120;
    // User controlled camera
    overviewCam = camera;
    overviewCam.position.set(overviewCam.direction).nor().scl(-100);
    overviewCam.lookAt(Vector3.Zero);
    overviewCam.far = camera.far *= 2;
    overviewCam.update(true);
    // Animated frustum camera model
    frustumCam = new PerspectiveCamera(FRUSTUM_CAMERA_FOV, camera.viewportWidth, camera.viewportHeight);
    frustumCam.far = FRUSTUM_CAMERA_FAR;
    frustumCam.update(true);
    final Model frustumModel = FrustumCullingTest.createFrustumModel(frustumCam.frustum.planePoints);
    frustumModel.materials.first().set(new ColorAttribute(ColorAttribute.AmbientLight, Color.WHITE));
    disposables.add(frustumModel);
    frustumInstance = new ModelInstance(frustumModel);
    spriteBatch = new SpriteBatch();
    disposables.add(spriteBatch);
    shapeRenderer = new ShapeRenderer();
    disposables.add(shapeRenderer);
    oclBuffer = new OcclusionBuffer(OCL_BUFFER_EXTENTS[0], OCL_BUFFER_EXTENTS[0]);
    disposables.add(oclBuffer);
    occlusionCuller = new OcclusionCuller() {

        @Override
        public boolean isOccluder(btCollisionObject object) {
            return (object.getCollisionFlags() & CF_OCCLUDER_OBJECT) != 0;
        }

        @Override
        public void onObjectVisible(btCollisionObject object) {
            visibleEntities.add(world.entities.get(object.getUserValue()));
        }
    };
    disposables.add(occlusionCuller);
    // Add occluder walls
    final Model occluderModel = modelBuilder.createBox(OCCLUDER_DIM.x, OCCLUDER_DIM.y, OCCLUDER_DIM.z, new Material(ColorAttribute.createDiffuse(Color.WHITE)), VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal);
    disposables.add(occluderModel);
    world.addConstructor("wall", new BulletConstructor(occluderModel, 0, new btBoxShape(tmpV1.set(OCCLUDER_DIM).scl(0.5f))));
    float y = OCCLUDER_DIM.y * 0.5f;
    addOccluder("wall", 0, tmpV1.set(20, y, 0));
    addOccluder("wall", -60, tmpV1.set(10, y, 20));
    addOccluder("wall", 60, tmpV1.set(10, y, -20));
    addOccluder("wall", 0, tmpV1.set(-20, y, 0));
    addOccluder("wall", 60, tmpV1.set(-10, y, 20));
    addOccluder("wall", -60, tmpV1.set(-10, y, -20));
    // Add ground
    final Model groundModel = modelBuilder.createBox(GROUND_DIM.x, GROUND_DIM.y, GROUND_DIM.z, new Material(ColorAttribute.createDiffuse(Color.WHITE)), VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal);
    btCollisionShape groundShape = new btBoxShape(tmpV1.set(GROUND_DIM).scl(0.5f));
    world.addConstructor("big_ground", new BulletConstructor(groundModel, 0, groundShape));
    BulletEntity e = world.add("big_ground", 0, -GROUND_DIM.y * 0.5f, 0f);
    e.body.setFriction(1f);
    e.setColor(Color.FOREST);
    // Occludee entity constructors. Scale models uniformly and set a default diffuse texture.
    BoundingBox bb = new BoundingBox();
    assets.finishLoadingAsset(DEFAULT_TEX_PATH);
    TextureAttribute defaultTexture = new TextureAttribute(TextureAttribute.Diffuse, assets.get(DEFAULT_TEX_PATH, Texture.class));
    for (int i = 0; i < OCCLUDEE_PATHS_DYNAMIC.length; i++) {
        String modelPath = OCCLUDEE_PATHS_DYNAMIC[i];
        OCCLUDEE_PATHS_STATIC[i] = "static" + modelPath;
        assets.finishLoadingAsset(modelPath);
        Model model = assets.get(modelPath, Model.class);
        if (!model.materials.first().has(TextureAttribute.Diffuse))
            model.materials.first().set(defaultTexture);
        Vector3 dim = model.calculateBoundingBox(bb).getDimensions(tmpV1);
        float scaleFactor = OCCLUDEE_MAX_EXTENT / Math.max(dim.x, Math.max(dim.y, dim.z));
        for (Node node : model.nodes) node.scale.scl(scaleFactor);
        btCollisionShape shape = new btBoxShape(dim.scl(scaleFactor * 0.5f));
        world.addConstructor(modelPath, new BulletConstructor(model, 1, shape));
        world.addConstructor(OCCLUDEE_PATHS_STATIC[i], new BulletConstructor(model, 0, shape));
    }
    // Add occludees
    for (int i = 0; i < STARTING_OCCLUDEE_AMOUNT; i++) addRandomOccludee(false);
}
Also used : com.badlogic.gdx.physics.bullet.collision.btBoxShape(com.badlogic.gdx.physics.bullet.collision.btBoxShape) DirectionalShadowLight(com.badlogic.gdx.graphics.g3d.environment.DirectionalShadowLight) StringBuilder(com.badlogic.gdx.utils.StringBuilder) Node(com.badlogic.gdx.graphics.g3d.model.Node) PerspectiveCamera(com.badlogic.gdx.graphics.PerspectiveCamera) SpriteBatch(com.badlogic.gdx.graphics.g2d.SpriteBatch) Texture(com.badlogic.gdx.graphics.Texture) com.badlogic.gdx.physics.bullet.collision.btCollisionShape(com.badlogic.gdx.physics.bullet.collision.btCollisionShape) BoundingBox(com.badlogic.gdx.math.collision.BoundingBox) PerspectiveCamera(com.badlogic.gdx.graphics.PerspectiveCamera) Camera(com.badlogic.gdx.graphics.Camera) com.badlogic.gdx.physics.bullet.collision.btCollisionObject(com.badlogic.gdx.physics.bullet.collision.btCollisionObject) TextureAttribute(com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute) AssetManager(com.badlogic.gdx.assets.AssetManager) Material(com.badlogic.gdx.graphics.g3d.Material) Vector3(com.badlogic.gdx.math.Vector3) ShapeRenderer(com.badlogic.gdx.graphics.glutils.ShapeRenderer) ModelInstance(com.badlogic.gdx.graphics.g3d.ModelInstance) Model(com.badlogic.gdx.graphics.g3d.Model) ColorAttribute(com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute)

Example 9 with BoundingBox

use of com.badlogic.gdx.math.collision.BoundingBox in project libgdx by libgdx.

the class ParticleEffect method getBoundingBox.

/** Returns the bounding box for all active particles. z axis will always be zero. */
public BoundingBox getBoundingBox() {
    if (bounds == null)
        bounds = new BoundingBox();
    BoundingBox bounds = this.bounds;
    bounds.inf();
    for (ParticleEmitter emitter : this.emitters) bounds.ext(emitter.getBoundingBox());
    return bounds;
}
Also used : BoundingBox(com.badlogic.gdx.math.collision.BoundingBox)

Example 10 with BoundingBox

use of com.badlogic.gdx.math.collision.BoundingBox in project libgdx by libgdx.

the class Mesh method calculateBoundingBox.

/** Calculates the {@link BoundingBox} of the vertices contained in this mesh. In case no vertices are defined yet a
	 * {@link GdxRuntimeException} is thrown. This method creates a new BoundingBox instance.
	 * 
	 * @return the bounding box. */
public BoundingBox calculateBoundingBox() {
    BoundingBox bbox = new BoundingBox();
    calculateBoundingBox(bbox);
    return bbox;
}
Also used : BoundingBox(com.badlogic.gdx.math.collision.BoundingBox)

Aggregations

BoundingBox (com.badlogic.gdx.math.collision.BoundingBox)10 Model (com.badlogic.gdx.graphics.g3d.Model)4 Vector3 (com.badlogic.gdx.math.Vector3)4 Texture (com.badlogic.gdx.graphics.Texture)2 Material (com.badlogic.gdx.graphics.g3d.Material)2 ModelInstance (com.badlogic.gdx.graphics.g3d.ModelInstance)2 Node (com.badlogic.gdx.graphics.g3d.model.Node)2 com.badlogic.gdx.physics.bullet.collision.btBoxShape (com.badlogic.gdx.physics.bullet.collision.btBoxShape)2 AssetManager (com.badlogic.gdx.assets.AssetManager)1 Camera (com.badlogic.gdx.graphics.Camera)1 PerspectiveCamera (com.badlogic.gdx.graphics.PerspectiveCamera)1 SpriteBatch (com.badlogic.gdx.graphics.g2d.SpriteBatch)1 BlendingAttribute (com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute)1 ColorAttribute (com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute)1 TextureAttribute (com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute)1 DirectionalShadowLight (com.badlogic.gdx.graphics.g3d.environment.DirectionalShadowLight)1 Animation (com.badlogic.gdx.graphics.g3d.model.Animation)1 MeshPart (com.badlogic.gdx.graphics.g3d.model.MeshPart)1 NodePart (com.badlogic.gdx.graphics.g3d.model.NodePart)1 AnimationController (com.badlogic.gdx.graphics.g3d.utils.AnimationController)1