Headless/CLI LibGDX

谁说胖子不能爱 提交于 2019-12-08 23:50:13

问题


I'm coding the server-side for a small LibGDX powered game, and have stumbled across an issue. Every time I try and use any Gdx.files.* methods, I'm met with a NullPointerException.

Apparently this is because I'm not implementing the ApplicationListener, so LibGDX has not been initialized.

Is there any way of initializing LibGDX in a headless/CLI way? I need to be able to load TiledMap objects on the server-side.

MapLoader(Request request)
{
    TiledMap tmp = new TmxMapLoader().load("maps/" + request.name + ".tmx");
}

Exception in thread "Server" java.lang.NullPointerException at com.tester.Example.server.ExampleServer$2.received(MapLoader.java:83) at com.esotericsoftware.kryonet.Server$1.received(Server.java:60) at com.esotericsoftware.kryonet.Connection.notifyReceived(Connection.java:246) at com.esotericsoftware.kryonet.Server.update(Server.java:202) at com.esotericsoftware.kryonet.Server.run(Server.java:350) at java.lang.Thread.run(Thread.java:722)


回答1:


I would not recommend using libGDX for a headless environment, it was simply not designed to be used that way and you may encounter issues in the future as the libGDX team changes the framework. However, as Rod pointed out, it is entirely possible to do so and below is a snippet of how you would go about it. To initialize the Gdx.files global you will need to create a class in the backend package and setup the globals yourself:

package com.badlogic.gdx.backends.lwjgl;

import com.badlogic.gdx.Gdx;

public class Headless {
    public static void loadHeadless() {
        LwjglNativesLoader.load();
        Gdx.files = new LwjglFiles();
    }
}

The rest should be fairly simple. Just call Headless.loadHeadless(); at the start and then you should be able to use parts of the framework you require.

As I stated before, I would not suggest doing this, but I haven't found any nice solutions for using libgdx with a client/server architecture.

Edit:

A little while back (after I wrote this answer originally) libgdx added a headless backend which is designed for this kind of purpose. It is the correct and proper way to use libgdx in a headless environment and works very well for creating a server with libgdx.




回答2:


As of Dec 23, 2013 (pull request #1018), libGDX has a headless backend that you can use for this purpose.




回答3:


Take a look at the LWJGL back end, specifically LwjglApplication.java. The constructor for LwjglApplication initializes all of the Gdx.* globals such as Gdx.files.

If you were to invoke the steps run in the constructor from your own code, except for the call to initialize(), then that should get you what you want.



来源:https://stackoverflow.com/questions/16068468/headless-cli-libgdx

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!