Search in sources :

Example 41 with Vector3

use of com.badlogic.gdx.math.Vector3 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 42 with Vector3

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

the class Scene method init.

public void init() {
    requestedRestart = false;
    requestedEnd = false;
    paused = false;
    visible = true;
    if (shapeRenderer == null)
        shapeRenderer = new ShapeRenderer();
    drawCommands = new ArrayList<ArrayList<Object>>();
    lastFrameBuffer = new RenderBuffer(null);
    environment = new Environment();
    environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0, 0, 0, 1));
    environment.set(new PointLightsAttribute());
    environment.set(new SpotLightsAttribute());
    environment.set(new DirectionalLightsAttribute());
    screenShaders = new ArrayList<ScreenShader>();
    defaultMaterial = new Material("__BDX_DEFAULT");
    defaultMaterial.set(new ColorAttribute(ColorAttribute.AmbientLight, 1, 1, 1, 1));
    defaultMaterial.set(new ColorAttribute(ColorAttribute.Diffuse, 1, 1, 1, 1));
    defaultMaterial.set(new BlendingAttribute());
    defaultMaterial.set(new BDXColorAttribute(BDXColorAttribute.Tint, 0, 0, 0));
    defaultMesh = new Mesh(new ModelBuilder().createBox(1.0f, 1.0f, 1.0f, defaultMaterial, Usage.Position | Usage.Normal | Usage.TextureCoordinates), this);
    meshes = new HashMap<String, Mesh>();
    textures = new HashMap<String, Texture>();
    materials = new HashMap<String, Material>();
    modelToFrame = new HashMap<>();
    materials.put(defaultMaterial.id, defaultMaterial);
    BroadphaseInterface broadphase = new DbvtBroadphase();
    DefaultCollisionConfiguration collisionConfiguration = new DefaultCollisionConfiguration();
    SequentialImpulseConstraintSolver solver = new SequentialImpulseConstraintSolver();
    CollisionDispatcher dispatcher = new CollisionDispatcher(collisionConfiguration);
    toBeAdded = new ArrayList<GameObject>();
    toBeRemoved = new ArrayList<GameObject>();
    objects = new LinkedListNamed<GameObject>();
    lights = new LinkedListNamed<Light>();
    templates = new HashMap<String, GameObject>();
    json = new JsonReader().parse(scene);
    name = json.get("name").asString();
    world = new DiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
    world.setDebugDrawer(new Bullet.DebugDrawer(json.get("physviz").asBoolean()));
    gravity(new Vector3f(0, 0, -json.get("gravity").asFloat()));
    float[] ac = json.get("ambientColor").asFloatArray();
    ambientLight(new Color(ac[0], ac[1], ac[2], 1));
    if (!clearColorDefaultSet) {
        float[] cc = json.get("clearColor").asFloatArray();
        Bdx.display.clearColor.set(cc[0], cc[1], cc[2], 0);
        clearColorDefaultSet = true;
    }
    if (json.get("framerateProfile").asBoolean()) {
        Bdx.profiler.init();
    }
    float[] fc = json.get("clearColor").asFloatArray();
    fogColor = new Color(fc[0], fc[1], fc[2], 1);
    fog(json.get("mistOn").asBoolean());
    fogRange(json.get("mistStart").asFloat(), json.get("mistDepth").asFloat());
    for (JsonValue mat : json.get("materials")) {
        String texName = mat.get("texture").asString();
        boolean hasAlpha = mat.get("alpha_blend").asString().equals("ALPHA");
        float opacity = hasAlpha ? mat.get("opacity").asFloat() : 1;
        Material material = new Material(mat.name);
        float[] c = mat.get("color").asFloatArray();
        material.set(ColorAttribute.createDiffuse(c[0], c[1], c[2], opacity));
        float[] s = mat.get("spec_color").asFloatArray();
        material.set(ColorAttribute.createSpecular(s[0], s[1], s[2], 1));
        material.set(FloatAttribute.createShininess(mat.get("shininess").asFloat()));
        material.set(new BDXColorAttribute(BDXColorAttribute.Tint, 0, 0, 0));
        IntAttribute shadeless = (IntAttribute) new BDXIntAttribute();
        if (mat.get("shadeless").asBoolean())
            shadeless.value = 1;
        material.set(shadeless);
        float emitStrength = mat.get("emit").asFloat();
        material.set(new BDXColorAttribute(BDXColorAttribute.Emit, emitStrength, emitStrength, emitStrength));
        if (mat.get("backface_culling").asBoolean())
            material.set(new IntAttribute(IntAttribute.CullFace, GL20.GL_BACK));
        else
            material.set(new IntAttribute(IntAttribute.CullFace, GL20.GL_NONE));
        if (texName != null) {
            Texture texture = textures.get(texName);
            if (texture == null) {
                texture = new Texture(Gdx.files.internal("bdx/textures/" + texName));
                textures.put(texName, texture);
            }
            texture.setWrap(TextureWrap.Repeat, TextureWrap.Repeat);
            material.texture(texture);
        }
        material.set(new DepthTestAttribute());
        if (hasAlpha) {
            BlendingAttribute ba = new BlendingAttribute(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
            ba.opacity = opacity;
            material.set(ba);
            // Discard pixels that fail this alpha test (sub-1% alpha)
            material.set(FloatAttribute.createAlphaTest(0.01f));
            // Turn on back-to-front sorting for alpha-enabled objects by default
            material.backToFrontSorting(true);
        } else {
            BlendingAttribute ba = new BlendingAttribute();
            ba.blended = false;
            material.set(ba);
        }
        materials.put(mat.name, material);
    }
    for (JsonValue model : json.get("models")) {
        meshes.put(model.name, new Mesh(createModel(model), this, model.name));
    }
    HashMap<String, JsonValue> fonts = new HashMap<>();
    for (JsonValue fontj : json.get("fonts")) {
        String font = fontj.asString();
        fonts.put(font, new JsonReader().parse(Gdx.files.internal("bdx/fonts/" + font + ".fntx")));
    }
    FAnim.loadActions(json.get("actions"));
    for (JsonValue gobj : json.get("objects")) {
        GameObject g = instantiator.newObject(gobj);
        g.json = gobj;
        g.name = gobj.name;
        g.scene = this;
        g.props = new HashMap<String, JsonValue>();
        for (JsonValue prop : gobj.get("properties")) {
            g.props.put(prop.name, prop);
        }
        String meshName = gobj.get("mesh_name").asString();
        if (meshName != null) {
            g.visibleNoChildren(gobj.get("visible").asBoolean());
            g.mesh(meshName);
        } else {
            g.visibleNoChildren(false);
            g.mesh(defaultMesh);
        }
        com.badlogic.gdx.graphics.Mesh mesh = g.modelInstance.model.meshes.first();
        float[] trans = gobj.get("transform").asFloatArray();
        JsonValue origin = json.get("origins").get(meshName);
        JsonValue dimensions = json.get("dimensions").get(meshName);
        g.origin = origin == null ? new Vector3f() : new Vector3f(origin.asFloatArray());
        g.dimensionsNoScale = dimensions == null ? new Vector3f(1, 1, 1) : new Vector3f(dimensions.asFloatArray());
        JsonValue physics = gobj.get("physics");
        g.currBodyType = GameObject.BodyType.valueOf(physics.get("body_type").asString());
        g.currBoundsType = GameObject.BoundsType.valueOf(physics.get("bounds_type").asString());
        g.body = Bullet.makeBody(mesh, trans, g.origin, g.currBodyType, g.currBoundsType, physics);
        g.body.setUserPointer(g);
        g.scale(getGLMatrixScale(trans));
        String type = gobj.get("type").asString();
        if (type.equals("FONT")) {
            Text t = (Text) g;
            t.font = fonts.get(gobj.get("font").asString());
            t.text(gobj.get("text").asString());
            t.capacity = t.text().length();
            String align = gobj.get("alignment").asString();
            if (align.equals("RIGHT"))
                t.alignment(Text.Alignment.RIGHT);
            else if (align.equals("CENTER"))
                t.alignment(Text.Alignment.CENTER);
            else
                t.alignment(Text.Alignment.LEFT);
        } else if (type.equals("LAMP")) {
            JsonValue settings = gobj.get("lamp");
            Light l = (Light) g;
            if (settings.getString("type").equals("SUN"))
                l.type = Light.Type.SUN;
            else if (settings.getString("type").equals("SPOT"))
                l.type = Light.Type.SPOT;
            else
                // POINT lamps; HEMI and AREA aren't supported, so they're turned into POINTs
                l.type = Light.Type.POINT;
            l.energy(settings.getFloat("energy"));
            float[] c = settings.get("color").asFloatArray();
            l.color(new Color(c[0], c[1], c[2], c[3]));
            if (l.type.equals(Light.Type.SPOT)) {
                l.spotSize(settings.getFloat("spot_size"));
            }
        } else if (type.equals("CAMERA")) {
            Camera c = (Camera) g;
            float[] projection = gobj.get("camera").get("projection").asFloatArray();
            Vector2f resolution = new Vector2f(json.get("resolution").asFloatArray());
            if (gobj.get("camera").get("type").asString().equals("PERSP")) {
                c.initData(Camera.Type.PERSPECTIVE);
                c.size(resolution);
                c.resolution(resolution);
                c.projection(new Matrix4f(projection));
                c.fov(c.fov());
            } else {
                c.initData(Camera.Type.ORTHOGRAPHIC);
                c.size(resolution);
                c.resolution(resolution);
                c.zoom(2 / projection[0]);
            }
            Matrix4 pm = new Matrix4(projection);
            pm.inv();
            Vector3 vec = new Vector3(0, 0, -1);
            vec.prj(pm);
            c.near(-vec.z);
            vec.set(0, 0, 1);
            vec.prj(pm);
            c.far(-vec.z);
        }
        templates.put(g.name, g);
    }
    hookParentChild();
    cameras = new ArrayListNamed<Camera>();
    addInstances();
    camera = (Camera) objects.get(json.get("cameras").asStringArray()[0]);
    String frameType = json.get("frame_type").asString();
    Viewport.Type viewportType;
    if (frameType.equals("LETTERBOX")) {
        viewportType = Viewport.Type.LETTERBOX;
    } else if (frameType.equals("EXTEND")) {
        viewportType = Viewport.Type.EXTEND;
    } else {
        // "SCALE"
        viewportType = Viewport.Type.SCALE;
    }
    viewport = new Viewport(this, viewportType);
    for (GameObject g : sortByPriority(new ArrayList<GameObject>(objects))) {
        initGameObject(g);
    }
    valid = true;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) com.badlogic.gdx.graphics(com.badlogic.gdx.graphics) ModelBuilder(com.badlogic.gdx.graphics.g3d.utils.ModelBuilder) ArrayListGameObject(com.nilunder.bdx.GameObject.ArrayListGameObject) CollisionDispatcher(com.bulletphysics.collision.dispatch.CollisionDispatcher) Color(com.nilunder.bdx.utils.Color) JsonValue(com.badlogic.gdx.utils.JsonValue) Mesh(com.nilunder.bdx.gl.Mesh) ShapeRenderer(com.badlogic.gdx.graphics.glutils.ShapeRenderer) Matrix4(com.badlogic.gdx.math.Matrix4) SequentialImpulseConstraintSolver(com.bulletphysics.dynamics.constraintsolver.SequentialImpulseConstraintSolver) Environment(com.badlogic.gdx.graphics.g3d.Environment) BroadphaseInterface(com.bulletphysics.collision.broadphase.BroadphaseInterface) JsonReader(com.badlogic.gdx.utils.JsonReader) DefaultCollisionConfiguration(com.bulletphysics.collision.dispatch.DefaultCollisionConfiguration) DbvtBroadphase(com.bulletphysics.collision.broadphase.DbvtBroadphase) Vector3(com.badlogic.gdx.math.Vector3) DiscreteDynamicsWorld(com.bulletphysics.dynamics.DiscreteDynamicsWorld)

Example 43 with Vector3

use of com.badlogic.gdx.math.Vector3 in project libgdx by libgdx.

the class OcclusionCullingTest method addRandomOccludee.

/** Adds an occludee entity of random type at a random place on the ground.
	 *
	 * @param dynamic If true, entity body will be dynamic (mass > 0)
	 * @return The added entity */
private BulletEntity addRandomOccludee(boolean dynamic) {
    // Add occludee to world
    BulletEntity entity = world.add(getRandomOccludeeType(dynamic), 0, 0, 0);
    entity.setColor(Color.WHITE);
    // Random rotation
    float rotationY = rng.nextFloat() * 360f;
    // Random ground position
    Vector3 position = tmpV1;
    int maxDstX = (int) (GROUND_DIM.x * 0.49f);
    position.x = rng.nextInt(maxDstX) * ((rng.nextBoolean()) ? 1 : -1);
    position.z = rng.nextInt(maxDstX) * ((rng.nextBoolean()) ? 1 : -1);
    position.y = entity.boundingBox.getDimensions(tmpV2).y * 0.5f;
    entity.modelInstance.transform.setToRotation(Vector3.Y, rotationY).setTranslation(position);
    entity.body.setWorldTransform(entity.modelInstance.transform);
    return entity;
}
Also used : Vector3(com.badlogic.gdx.math.Vector3)

Example 44 with Vector3

use of com.badlogic.gdx.math.Vector3 in project libgdx by libgdx.

the class SoftBodyTest method create.

@Override
public void create() {
    super.create();
    world.add("ground", 0f, 0f, 0f).setColor(0.25f + 0.5f * (float) Math.random(), 0.25f + 0.5f * (float) Math.random(), 0.25f + 0.5f * (float) Math.random(), 1f);
    float x0 = -2f, y0 = 6f, z0 = -2f;
    float x1 = 8f, y1 = 6f, z1 = 8f;
    Vector3 patch00 = new Vector3(x0, y0, z0);
    Vector3 patch10 = new Vector3(x1, y1, z0);
    Vector3 patch01 = new Vector3(x0, y0, z1);
    Vector3 patch11 = new Vector3(x1, y1, z1);
    softBody = btSoftBodyHelpers.CreatePatch(worldInfo, patch00, patch10, patch01, patch11, 15, 15, 15, false);
    softBody.takeOwnership();
    softBody.setTotalMass(100f);
    ((btSoftRigidDynamicsWorld) (world.collisionWorld)).addSoftBody(softBody);
    final int vertCount = softBody.getNodeCount();
    final int faceCount = softBody.getFaceCount();
    mesh = new Mesh(false, vertCount, faceCount * 3, new VertexAttribute(Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE), new VertexAttribute(Usage.Normal, 3, ShaderProgram.NORMAL_ATTRIBUTE), new VertexAttribute(Usage.TextureCoordinates, 2, ShaderProgram.TEXCOORD_ATTRIBUTE + "0"));
    final int vertSize = mesh.getVertexSize() / 4;
    mesh.getVerticesBuffer().position(0);
    mesh.getVerticesBuffer().limit(vertCount * vertSize);
    mesh.getIndicesBuffer().position(0);
    mesh.getIndicesBuffer().limit(faceCount * 3);
    softBody.getVertices(mesh.getVerticesBuffer(), vertCount, mesh.getVertexSize(), 0);
    softBody.getIndices(mesh.getIndicesBuffer(), faceCount);
    final float[] verts = new float[vertCount * vertSize];
    final int uvOffset = mesh.getVertexAttribute(Usage.TextureCoordinates).offset / 4;
    final int normalOffset = mesh.getVertexAttribute(Usage.Normal).offset / 4;
    mesh.getVertices(verts);
    for (int i = 0; i < vertCount; i++) {
        verts[i * vertSize + normalOffset] = 0f;
        verts[i * vertSize + normalOffset + 1] = 1f;
        verts[i * vertSize + normalOffset + 2] = 0f;
        verts[i * vertSize + uvOffset] = (verts[i * vertSize] - x0) / (x1 - x0);
        verts[i * vertSize + uvOffset + 1] = (verts[i * vertSize + 2] - z0) / (z1 - z0);
    }
    mesh.setVertices(verts);
    texture = new Texture(Gdx.files.internal("data/badlogic.jpg"));
    ModelBuilder builder = new ModelBuilder();
    builder.begin();
    builder.part(new MeshPart("", mesh, 0, mesh.getNumIndices(), GL20.GL_TRIANGLES), new Material(TextureAttribute.createDiffuse(texture), ColorAttribute.createSpecular(Color.WHITE), FloatAttribute.createShininess(64f), IntAttribute.createCullFace(0)));
    model = builder.end();
    instance = new ModelInstance(model);
    world.add(new BulletEntity(instance, null));
}
Also used : com.badlogic.gdx.physics.bullet.softbody.btSoftRigidDynamicsWorld(com.badlogic.gdx.physics.bullet.softbody.btSoftRigidDynamicsWorld) Mesh(com.badlogic.gdx.graphics.Mesh) Vector3(com.badlogic.gdx.math.Vector3) Material(com.badlogic.gdx.graphics.g3d.Material) MeshPart(com.badlogic.gdx.graphics.g3d.model.MeshPart) Texture(com.badlogic.gdx.graphics.Texture) ModelInstance(com.badlogic.gdx.graphics.g3d.ModelInstance) ModelBuilder(com.badlogic.gdx.graphics.g3d.utils.ModelBuilder) VertexAttribute(com.badlogic.gdx.graphics.VertexAttribute)

Example 45 with Vector3

use of com.badlogic.gdx.math.Vector3 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)

Aggregations

Vector3 (com.badlogic.gdx.math.Vector3)64 Matrix4 (com.badlogic.gdx.math.Matrix4)10 Quaternion (com.badlogic.gdx.math.Quaternion)9 Vector2 (com.badlogic.gdx.math.Vector2)6 Node (com.badlogic.gdx.graphics.g3d.model.Node)5 Texture (com.badlogic.gdx.graphics.Texture)4 Model (com.badlogic.gdx.graphics.g3d.Model)4 NodeKeyframe (com.badlogic.gdx.graphics.g3d.model.NodeKeyframe)4 BoundingBox (com.badlogic.gdx.math.collision.BoundingBox)4 VertexAttribute (com.badlogic.gdx.graphics.VertexAttribute)3 SpriteBatch (com.badlogic.gdx.graphics.g2d.SpriteBatch)3 Material (com.badlogic.gdx.graphics.g3d.Material)3 ModelNode (com.badlogic.gdx.graphics.g3d.model.data.ModelNode)3 ModelBuilder (com.badlogic.gdx.graphics.g3d.utils.ModelBuilder)3 Mesh (com.badlogic.gdx.graphics.Mesh)2 OrthographicCamera (com.badlogic.gdx.graphics.OrthographicCamera)2 ModelInstance (com.badlogic.gdx.graphics.g3d.ModelInstance)2 Animation (com.badlogic.gdx.graphics.g3d.model.Animation)2 MeshPart (com.badlogic.gdx.graphics.g3d.model.MeshPart)2 NodeAnimation (com.badlogic.gdx.graphics.g3d.model.NodeAnimation)2