Search in sources :

Example 86 with JsonValue

use of com.badlogic.gdx.utils.JsonValue in project nhglib by VoidZombie.

the class Main method engineStarted.

@Override
public void engineStarted() {
    super.engineStarted();
    Nhg.debugLogs = true;
    Gdx.input.setCursorCatched(true);
    world = new NhgWorld(nhg.messaging, nhg.entities, nhg.assets, new DefaultWorldStrategy(), new Bounds(2f, 2f, 2f));
    fpsLogger = new FPSLogger();
    renderer20 = new ImmediateModeRenderer20(false, true, 0);
    nhg.input.addListener(this);
    nhg.assets.queueAsset(new Asset("scene", "myscene.nhs", Scene.class));
    nhg.assets.queueAsset(new Asset("inputMap", "input.nhc", JsonValue.class));
    GraphicsSystem graphicsSystem = nhg.entities.getEntitySystem(GraphicsSystem.class);
    graphicsSystem.setClearColor(Color.GRAY);
    Environment environment = graphicsSystem.getEnvironment();
    GammaCorrectionAttribute gammaCorrectionAttribute = new GammaCorrectionAttribute();
    gammaCorrectionAttribute.gammaCorrection = true;
    environment.set(gammaCorrectionAttribute);
    // Subscribe to asset events
    nhg.messaging.get(Strings.Events.assetLoaded, Strings.Events.assetLoadingFinished).subscribe(new Consumer<Message>() {

        @Override
        public void accept(Message message) throws Exception {
            if (message.is(Strings.Events.assetLoaded)) {
                Asset asset = (Asset) message.data.get(Strings.Defaults.assetKey);
                if (asset.is("scene")) {
                    scene = nhg.assets.get(asset);
                    world.loadScene(scene);
                    world.setReferenceEntity("camera");
                    ModelBuilder mb = new ModelBuilder();
                    Model planeModel = mb.createBox(2f, 0.01f, 20f, new Material(), VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal | VertexAttributes.Usage.TextureCoordinates);
                    int plane = scene.sceneGraph.createSceneEntity("plane");
                    scene.sceneGraph.addSceneEntity(plane);
                    ModelComponent modelComponent = nhg.entities.createComponent(plane, ModelComponent.class);
                    modelComponent.initWithModel(planeModel);
                    NodeComponent nodeComponent = nhg.entities.getComponent(plane, NodeComponent.class);
                    nodeComponent.setTranslation(0, 0, 0, true);
                    Integer cameraEntity = scene.sceneGraph.getSceneEntity("camera");
                    cameraNode = nhg.entities.getComponent(cameraEntity, NodeComponent.class);
                } else if (asset.is("inputMap")) {
                    nhg.input.fromJson((JsonValue) nhg.assets.get(asset));
                    nhg.input.setActiveContext("game", true);
                    nhg.input.setActiveContext("global", true);
                }
            }
        }
    });
}
Also used : NhgWorld(io.github.voidzombie.nhglib.graphics.worlds.NhgWorld) Message(io.github.voidzombie.nhglib.runtime.messaging.Message) GammaCorrectionAttribute(io.github.voidzombie.nhglib.graphics.shaders.attributes.GammaCorrectionAttribute) Bounds(io.github.voidzombie.nhglib.utils.data.Bounds) JsonValue(com.badlogic.gdx.utils.JsonValue) Material(com.badlogic.gdx.graphics.g3d.Material) Scene(io.github.voidzombie.nhglib.graphics.scenes.Scene) FPSLogger(com.badlogic.gdx.graphics.FPSLogger) ImmediateModeRenderer20(com.badlogic.gdx.graphics.glutils.ImmediateModeRenderer20) ModelBuilder(com.badlogic.gdx.graphics.g3d.utils.ModelBuilder) ModelComponent(io.github.voidzombie.nhglib.runtime.ecs.components.graphics.ModelComponent) DefaultWorldStrategy(io.github.voidzombie.nhglib.graphics.worlds.strategies.impl.DefaultWorldStrategy) Model(com.badlogic.gdx.graphics.g3d.Model) NodeComponent(io.github.voidzombie.nhglib.runtime.ecs.components.scenes.NodeComponent) Asset(io.github.voidzombie.nhglib.assets.Asset) GraphicsSystem(io.github.voidzombie.nhglib.runtime.ecs.systems.impl.GraphicsSystem) Environment(com.badlogic.gdx.graphics.g3d.Environment)

Example 87 with JsonValue

use of com.badlogic.gdx.utils.JsonValue in project bdx by GoranM.

the class GameObject method mesh.

public void mesh(Mesh mesh) {
    String meshName = mesh.name();
    if (// You're already set to the current mesh
    mesh == this.mesh)
        return;
    JsonValue mOrigin = null;
    JsonValue mDimNoScale = null;
    ArrayList<Scene> sceneList = new ArrayList<Scene>(Bdx.scenes);
    if (sceneList.indexOf(scene) >= 0)
        Collections.swap(sceneList, sceneList.indexOf(scene), 0);
    else
        sceneList.add(0, scene);
    for (Scene sce : sceneList) {
        if (sce.meshes.containsKey(meshName)) {
            mOrigin = sce.json.get("origins").get(meshName);
            mDimNoScale = sce.json.get("dimensions").get(meshName);
            break;
        }
    }
    origin = mOrigin == null ? new Vector3f() : new Vector3f(mOrigin.asFloatArray());
    dimensionsNoScale = mDimNoScale == null ? new Vector3f(1, 1, 1) : new Vector3f(mDimNoScale.asFloatArray());
    Matrix4 trans;
    if (modelInstance != null) {
        trans = modelInstance.transform;
        this.mesh.instances.remove(this);
    } else
        trans = new Matrix4();
    this.mesh = mesh;
    modelInstance = mesh.getInstance();
    modelInstance.transform.set(trans);
}
Also used : Vector3f(javax.vecmath.Vector3f) JsonValue(com.badlogic.gdx.utils.JsonValue) ArrayList(java.util.ArrayList) Matrix4(com.badlogic.gdx.math.Matrix4)

Example 88 with JsonValue

use of com.badlogic.gdx.utils.JsonValue in project bdx by GoranM.

the class Scene method cloneNoChildren.

private GameObject cloneNoChildren(GameObject gobj) {
    GameObject g = instantiator.newObject(gobj.json);
    g.json = gobj.json;
    g.name = gobj.name;
    g.visibleNoChildren(gobj.visible());
    g.scene = this;
    g.mesh(gobj.mesh());
    g.body = Bullet.cloneBody(gobj.body);
    g.currBodyType = gobj.currBodyType;
    g.currBoundsType = gobj.currBoundsType;
    g.origin = gobj.origin;
    g.dimensionsNoScale = gobj.dimensionsNoScale;
    g.body.setUserPointer(g);
    g.scale(gobj.scale());
    g.props = new HashMap<String, JsonValue>(gobj.props);
    if (g instanceof Camera) {
        Camera c = (Camera) g;
        Camera cobj = (Camera) gobj;
        c.initData(cobj.type);
        c.size(cobj.size());
        c.resolution(cobj.resolution());
        if (c.type == Camera.Type.PERSPECTIVE) {
            c.fov(cobj.fov());
        } else {
            c.zoom(cobj.zoom());
        }
        c.near(cobj.near());
        c.far(cobj.far());
        c.update();
        cameras.add(c);
    } else if (g instanceof Text) {
        Text t = (Text) g;
        Text tt = (Text) gobj;
        t.font = tt.font;
        t.text(tt.text());
        t.capacity = tt.capacity;
        t.mesh(t.mesh().copy());
        t.alignment(tt.alignment());
    } else if (g instanceof Light) {
        Light l = (Light) g;
        Light ll = (Light) gobj;
        l.energy(ll.energy());
        l.color(ll.color());
        l.spotSize(ll.spotSize());
        l.exponent(ll.exponent());
        l.type = ll.type;
        l.makeLightData();
        l.updateLight();
        l.on(true);
    }
    return g;
}
Also used : ArrayListGameObject(com.nilunder.bdx.GameObject.ArrayListGameObject) JsonValue(com.badlogic.gdx.utils.JsonValue)

Example 89 with JsonValue

use of com.badlogic.gdx.utils.JsonValue 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 90 with JsonValue

use of com.badlogic.gdx.utils.JsonValue in project bdx by GoranM.

the class Text method text.

public void text(String txt) {
    // Reform quads according to Angel Code font format
    Mesh mesh = modelInstance.model.meshes.first();
    int vertexSize = mesh.getVertexSize() / 4;
    int numVertices = mesh.getNumVertices();
    float[] verts = new float[numVertices * vertexSize];
    int vi = 0;
    // number of quads
    int capacity = (numVertices / 3) / 2;
    text = txt.substring(0, Math.min(txt.length(), capacity));
    JsonValue cm = font.get("common");
    float su = 1.f / cm.get("scaleW").asInt();
    float sv = 1.f / cm.get("scaleH").asInt();
    JsonValue char_data = font.get("char");
    JsonValue at_c = char_data.get(Integer.toString('O'));
    boolean builtin = font.get("info").get("face").asString().equals("Bfont");
    float scale = 0.0225f * (builtin ? 1.4f : 1f);
    float unit_height = at_c.get("height").asInt() * scale;
    int posX = 0;
    int posY = 0;
    float z = 0;
    int totalWidth = 0;
    String[] lines = text.split("[\n]");
    int cap = 0;
    int past_vi = 0;
    for (String l : lines) {
        for (int i = 0; i < Math.min(l.length(), capacity - cap); ++i) {
            // Write chars for the line or text object capacity, whichever's shorter
            char chr = ' ';
            if (i < l.length())
                chr = l.charAt(i);
            JsonValue c = char_data.get(Integer.toString(chr));
            if (c == null)
                c = char_data.get(Integer.toString(' '));
            int x = posX + c.get("xoffset").asInt();
            int y = posY - c.get("yoffset").asInt();
            int w = c.get("width").asInt();
            int h = c.get("height").asInt();
            posX += c.get("xadvance").asInt();
            if (i < l.length() && x + w > totalWidth)
                totalWidth = x + w;
            float u = c.get("x").asInt();
            float v = c.get("y").asInt();
            float[][] quad = { { x, y - h, z, 0, 0, 1, u, v + h }, { x + w, y - h, z, 0, 0, 1, u + w, v + h }, { x + w, y, z, 0, 0, 1, u + w, v }, { x + w, y, z, 0, 0, 1, u + w, v }, { x, y, z, 0, 0, 1, u, v }, { x, y - h, z, 0, 0, 1, u, v + h } };
            z += 0.0001;
            for (float[] vert : quad) {
                vert[0] *= scale;
                vert[1] *= scale;
                vert[0] -= 0.05 + (builtin ? 0.03 : 0);
                vert[1] += unit_height * (0.76 - (builtin ? 0.05 : 0));
                vert[6] *= su;
                vert[7] *= sv;
                for (float f : vert) {
                    verts[vi++] = f;
                }
            }
        }
        cap += l.length();
        // Set up the Y for the next text line
        posY -= (int) (cm.get("lineHeight").asInt() * this.lineHeight);
        posX = 0;
        for (int i = past_vi; i < vi; i += Bdx.VERT_STRIDE) {
            if (alignment == Alignment.CENTER)
                verts[i] -= (totalWidth / 2f) * scale;
            else if (alignment == Alignment.RIGHT)
                verts[i] -= totalWidth * scale;
        }
        past_vi = vi;
        totalWidth = 0;
    }
    mesh.setVertices(verts, 0, verts.length);
}
Also used : JsonValue(com.badlogic.gdx.utils.JsonValue)

Aggregations

JsonValue (com.badlogic.gdx.utils.JsonValue)148 JsonReader (com.badlogic.gdx.utils.JsonReader)27 IOException (java.io.IOException)21 Array (com.badlogic.gdx.utils.Array)20 Json (com.badlogic.gdx.utils.Json)15 GdxRuntimeException (com.badlogic.gdx.utils.GdxRuntimeException)14 FileHandle (com.badlogic.gdx.files.FileHandle)11 ReflectionException (com.badlogic.gdx.utils.reflect.ReflectionException)10 BladeJson (com.bladecoder.engine.serialization.BladeJson)9 HashMap (java.util.HashMap)8 Color (com.badlogic.gdx.graphics.Color)7 GraphBoxImpl (com.gempukku.libgdx.graph.ui.graph.GraphBoxImpl)7 ArrayList (java.util.ArrayList)7 Vector2 (com.badlogic.gdx.math.Vector2)6 Actor (com.badlogic.gdx.scenes.scene2d.Actor)6 ChangeListener (com.badlogic.gdx.scenes.scene2d.utils.ChangeListener)6 Action (com.bladecoder.engine.actions.Action)6 File (java.io.File)6 ObjectMap (com.badlogic.gdx.utils.ObjectMap)5 SerializationException (com.badlogic.gdx.utils.SerializationException)5