Search in sources :

Example 1 with GameManifest

use of org.terasology.game.GameManifest in project Terasology by MovingBlocks.

the class CreateGameScreen method initialise.

@Override
@SuppressWarnings("unchecked")
public void initialise() {
    setAnimationSystem(MenuAnimationSystems.createDefaultSwipeAnimation());
    UILabel gameTypeTitle = find("gameTypeTitle", UILabel.class);
    if (gameTypeTitle != null) {
        gameTypeTitle.bindText(new ReadOnlyBinding<String>() {

            @Override
            public String get() {
                if (loadingAsServer) {
                    return translationSystem.translate("${engine:menu#select-multiplayer-game-sub-title}");
                } else {
                    return translationSystem.translate("${engine:menu#select-singleplayer-game-sub-title}");
                }
            }
        });
    }
    final UIText worldName = find("worldName", UIText.class);
    setGameName(worldName);
    final UIText seed = find("seed", UIText.class);
    if (seed != null) {
        seed.setText(new FastRandom().nextString(32));
    }
    final UIDropdownScrollable<Module> gameplay = find("gameplay", UIDropdownScrollable.class);
    gameplay.setOptions(getGameplayModules());
    gameplay.setVisibleOptions(3);
    gameplay.bindSelection(new Binding<Module>() {

        Module selected;

        @Override
        public Module get() {
            return selected;
        }

        @Override
        public void set(Module value) {
            setSelectedGameplayModule(value);
            selected = value;
        }
    });
    gameplay.setOptionRenderer(new StringTextRenderer<Module>() {

        @Override
        public String getString(Module value) {
            return value.getMetadata().getDisplayName().value();
        }

        @Override
        public void draw(Module value, Canvas canvas) {
            canvas.getCurrentStyle().setTextColor(validateModuleDependencies(value.getId()) ? Color.WHITE : Color.RED);
            super.draw(value, canvas);
            canvas.getCurrentStyle().setTextColor(Color.WHITE);
        }
    });
    UILabel gameplayDescription = find("gameplayDescription", UILabel.class);
    gameplayDescription.bindText(new ReadOnlyBinding<String>() {

        @Override
        public String get() {
            Module selectedModule = gameplay.getSelection();
            if (selectedModule != null) {
                return selectedModule.getMetadata().getDescription().value();
            } else {
                return "";
            }
        }
    });
    final UIDropdownScrollable<WorldGeneratorInfo> worldGenerator = find("worldGenerator", UIDropdownScrollable.class);
    if (worldGenerator != null) {
        worldGenerator.bindOptions(new ReadOnlyBinding<List<WorldGeneratorInfo>>() {

            @Override
            public List<WorldGeneratorInfo> get() {
                // grab all the module names and their dependencies
                // This grabs modules from `config.getDefaultModSelection()` which is updated in SelectModulesScreen
                Set<Name> enabledModuleNames = getAllEnabledModuleNames().stream().collect(Collectors.toSet());
                List<WorldGeneratorInfo> result = Lists.newArrayList();
                for (WorldGeneratorInfo option : worldGeneratorManager.getWorldGenerators()) {
                    if (enabledModuleNames.contains(option.getUri().getModuleName())) {
                        result.add(option);
                    }
                }
                return result;
            }
        });
        worldGenerator.setVisibleOptions(3);
        worldGenerator.bindSelection(new Binding<WorldGeneratorInfo>() {

            @Override
            public WorldGeneratorInfo get() {
                // get the default generator from the config. This is likely to have a user triggered selection.
                WorldGeneratorInfo info = worldGeneratorManager.getWorldGeneratorInfo(config.getWorldGeneration().getDefaultGenerator());
                if (info != null && getAllEnabledModuleNames().contains(info.getUri().getModuleName())) {
                    return info;
                }
                // just use the first available generator
                for (WorldGeneratorInfo worldGenInfo : worldGeneratorManager.getWorldGenerators()) {
                    if (getAllEnabledModuleNames().contains(worldGenInfo.getUri().getModuleName())) {
                        set(worldGenInfo);
                        return worldGenInfo;
                    }
                }
                return null;
            }

            @Override
            public void set(WorldGeneratorInfo value) {
                if (value != null) {
                    config.getWorldGeneration().setDefaultGenerator(value.getUri());
                }
            }
        });
        worldGenerator.setOptionRenderer(new StringTextRenderer<WorldGeneratorInfo>() {

            @Override
            public String getString(WorldGeneratorInfo value) {
                if (value != null) {
                    return value.getDisplayName();
                }
                return "";
            }
        });
        final UIButton playButton = find("play", UIButton.class);
        playButton.bindEnabled(new Binding<Boolean>() {

            @Override
            public Boolean get() {
                return validateModuleDependencies(gameplay.getSelection().getId());
            }

            @Override
            public void set(Boolean value) {
                playButton.setEnabled(value);
            }
        });
    }
    WidgetUtil.trySubscribe(this, "close", button -> triggerBackAnimation());
    WidgetUtil.trySubscribe(this, "play", button -> {
        if (worldGenerator.getSelection() == null) {
            MessagePopup errorMessagePopup = getManager().pushScreen(MessagePopup.ASSET_URI, MessagePopup.class);
            if (errorMessagePopup != null) {
                errorMessagePopup.setMessage("No World Generator Selected", "Select a world generator (you may need to activate a mod with a generator first).");
            }
        } else {
            GameManifest gameManifest = new GameManifest();
            gameManifest.setTitle(worldName.getText());
            gameManifest.setSeed(seed.getText());
            DependencyResolver resolver = new DependencyResolver(moduleManager.getRegistry());
            ResolutionResult result = resolver.resolve(config.getDefaultModSelection().listModules());
            if (!result.isSuccess()) {
                MessagePopup errorMessagePopup = getManager().pushScreen(MessagePopup.ASSET_URI, MessagePopup.class);
                if (errorMessagePopup != null) {
                    errorMessagePopup.setMessage("Invalid Module Selection", "Please review your module seleciton and try again");
                }
                return;
            }
            for (Module module : result.getModules()) {
                gameManifest.addModule(module.getId(), module.getVersion());
            }
            // Time at dawn + little offset to spawn in a brighter env.
            float timeOffset = 0.25f + 0.025f;
            WorldInfo worldInfo = new WorldInfo(TerasologyConstants.MAIN_WORLD, gameManifest.getSeed(), (long) (WorldTime.DAY_LENGTH * timeOffset), worldGenerator.getSelection().getUri());
            gameManifest.addWorld(worldInfo);
            gameEngine.changeState(new StateLoading(gameManifest, (loadingAsServer) ? NetworkMode.DEDICATED_SERVER : NetworkMode.NONE));
        }
    });
    UIButton previewSeed = find("previewSeed", UIButton.class);
    ReadOnlyBinding<Boolean> worldGeneratorSelected = new ReadOnlyBinding<Boolean>() {

        @Override
        public Boolean get() {
            return worldGenerator != null && worldGenerator.getSelection() != null;
        }
    };
    previewSeed.bindEnabled(worldGeneratorSelected);
    PreviewWorldScreen screen = getManager().createScreen(PreviewWorldScreen.ASSET_URI, PreviewWorldScreen.class);
    WidgetUtil.trySubscribe(this, "previewSeed", button -> {
        if (screen != null) {
            screen.bindSeed(BindHelper.bindBeanProperty("text", seed, String.class));
            try {
                screen.setEnvironment();
                triggerForwardAnimation(screen);
            } catch (Exception e) {
                String msg = "Unable to load world for a 2D preview:\n" + e.toString();
                getManager().pushScreen(MessagePopup.ASSET_URI, MessagePopup.class).setMessage("Error", msg);
                logger.error("Unable to load world for a 2D preview", e);
            }
        }
    });
    WidgetUtil.trySubscribe(this, "mods", w -> triggerForwardAnimation(SelectModulesScreen.ASSET_URI));
}
Also used : Set(java.util.Set) ResolutionResult(org.terasology.module.ResolutionResult) WorldGeneratorInfo(org.terasology.world.generator.internal.WorldGeneratorInfo) UIButton(org.terasology.rendering.nui.widgets.UIButton) UIText(org.terasology.rendering.nui.widgets.UIText) WorldInfo(org.terasology.world.internal.WorldInfo) List(java.util.List) UILabel(org.terasology.rendering.nui.widgets.UILabel) StateLoading(org.terasology.engine.modes.StateLoading) ReadOnlyBinding(org.terasology.rendering.nui.databinding.ReadOnlyBinding) Canvas(org.terasology.rendering.nui.Canvas) FastRandom(org.terasology.utilities.random.FastRandom) DependencyResolver(org.terasology.module.DependencyResolver) GameManifest(org.terasology.game.GameManifest) Module(org.terasology.module.Module)

Example 2 with GameManifest

use of org.terasology.game.GameManifest in project Terasology by MovingBlocks.

the class GameProvider method getSavedGames.

public static List<GameInfo> getSavedGames() {
    Path savedGames = PathManager.getInstance().getSavesPath();
    SortedMap<FileTime, Path> savedGamePaths = Maps.newTreeMap(Collections.reverseOrder());
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(savedGames)) {
        for (Path entry : stream) {
            if (Files.isRegularFile(entry.resolve(GameManifest.DEFAULT_FILE_NAME))) {
                savedGamePaths.put(Files.getLastModifiedTime(entry.resolve(GameManifest.DEFAULT_FILE_NAME)), entry);
            }
        }
    } catch (IOException e) {
        logger.error("Failed to read saved games path", e);
    }
    List<GameInfo> result = Lists.newArrayListWithCapacity(savedGamePaths.size());
    for (Map.Entry<FileTime, Path> world : savedGamePaths.entrySet()) {
        Path gameManifest = world.getValue().resolve(GameManifest.DEFAULT_FILE_NAME);
        if (!Files.isRegularFile(gameManifest)) {
            continue;
        }
        try {
            GameManifest info = GameManifest.load(gameManifest);
            try {
                if (!info.getTitle().isEmpty()) {
                    Date date = new Date(world.getKey().toMillis());
                    result.add(new GameInfo(info, date));
                }
            } catch (NullPointerException npe) {
                logger.error("The save file was corrupted for: " + world.toString() + ". The manifest can be found and restored at: " + gameManifest.toString(), npe);
            }
        } catch (IOException e) {
            logger.error("Failed reading world data object.", e);
        }
    }
    return result;
}
Also used : Path(java.nio.file.Path) GameManifest(org.terasology.game.GameManifest) FileTime(java.nio.file.attribute.FileTime) IOException(java.io.IOException) Map(java.util.Map) SortedMap(java.util.SortedMap) Date(java.util.Date)

Example 3 with GameManifest

use of org.terasology.game.GameManifest in project Terasology by MovingBlocks.

the class ReadWriteStorageManager method addGameManifestToSaveTransaction.

private void addGameManifestToSaveTransaction(SaveTransactionBuilder saveTransactionBuilder) {
    BlockManager blockManager = CoreRegistry.get(BlockManager.class);
    BiomeManager biomeManager = CoreRegistry.get(BiomeManager.class);
    WorldProvider worldProvider = CoreRegistry.get(WorldProvider.class);
    Time time = CoreRegistry.get(Time.class);
    Game game = CoreRegistry.get(Game.class);
    GameManifest gameManifest = new GameManifest(game.getName(), game.getSeed(), time.getGameTimeInMs());
    for (Module module : CoreRegistry.get(ModuleManager.class).getEnvironment()) {
        gameManifest.addModule(module.getId(), module.getVersion());
    }
    List<String> registeredBlockFamilies = Lists.newArrayList();
    for (BlockFamily family : blockManager.listRegisteredBlockFamilies()) {
        registeredBlockFamilies.add(family.getURI().toString());
    }
    gameManifest.setRegisteredBlockFamilies(registeredBlockFamilies);
    gameManifest.setBlockIdMap(blockManager.getBlockIdMap());
    List<Biome> biomes = biomeManager.getBiomes();
    Map<String, Short> biomeIdMap = new HashMap<>(biomes.size());
    for (Biome biome : biomes) {
        short shortId = biomeManager.getBiomeShortId(biome);
        String id = biomeManager.getBiomeId(biome);
        biomeIdMap.put(id, shortId);
    }
    gameManifest.setBiomeIdMap(biomeIdMap);
    gameManifest.addWorld(worldProvider.getWorldInfo());
    saveTransactionBuilder.setGameManifest(gameManifest);
}
Also used : BiomeManager(org.terasology.world.biomes.BiomeManager) HashMap(java.util.HashMap) Time(org.terasology.engine.Time) ModuleManager(org.terasology.engine.module.ModuleManager) Game(org.terasology.game.Game) Biome(org.terasology.world.biomes.Biome) GameManifest(org.terasology.game.GameManifest) BlockManager(org.terasology.world.block.BlockManager) WorldProvider(org.terasology.world.WorldProvider) BlockFamily(org.terasology.world.block.family.BlockFamily) Module(org.terasology.module.Module)

Example 4 with GameManifest

use of org.terasology.game.GameManifest in project Terasology by MovingBlocks.

the class Terasology method main.

public static void main(String[] args) {
    handlePrintUsageRequest(args);
    handleLaunchArguments(args);
    SplashScreen splashScreen = splashEnabled ? configureSplashScreen() : SplashScreenBuilder.createStub();
    splashScreen.post("Java Runtime " + System.getProperty("java.version") + " loaded");
    setupLogging();
    try {
        TerasologyEngineBuilder builder = new TerasologyEngineBuilder();
        populateSubsystems(builder);
        TerasologyEngine engine = builder.build();
        engine.subscribe(newStatus -> {
            if (newStatus == StandardGameStatus.RUNNING) {
                splashScreen.close();
            } else {
                splashScreen.post(newStatus.getDescription());
            }
        });
        if (isHeadless) {
            engine.subscribeToStateChange(new HeadlessStateChangeListener(engine));
            engine.run(new StateHeadlessSetup());
        } else {
            if (loadLastGame) {
                engine.getFromEngineContext(ThreadManager.class).submitTask("loadGame", () -> {
                    GameManifest gameManifest = getLatestGameManifest();
                    if (gameManifest != null) {
                        engine.changeState(new StateLoading(gameManifest, NetworkMode.NONE));
                    }
                });
            }
            engine.run(new StateMainMenu());
        }
    } catch (Throwable e) {
        // also catch Errors such as UnsatisfiedLink, NoSuchMethodError, etc.
        splashScreen.close();
        reportException(e);
    }
}
Also used : GameManifest(org.terasology.game.GameManifest) StateLoading(org.terasology.engine.modes.StateLoading) HeadlessStateChangeListener(org.terasology.engine.subsystem.headless.mode.HeadlessStateChangeListener) StateMainMenu(org.terasology.engine.modes.StateMainMenu) SplashScreen(org.terasology.splash.SplashScreen) StateHeadlessSetup(org.terasology.engine.subsystem.headless.mode.StateHeadlessSetup) ThreadManager(org.terasology.engine.subsystem.common.ThreadManager)

Example 5 with GameManifest

use of org.terasology.game.GameManifest in project Terasology by MovingBlocks.

the class StateHeadlessSetup method init.

@Override
public void init(GameEngine gameEngine) {
    context = gameEngine.createChildContext();
    CoreRegistry.setContext(context);
    // let's get the entity event system running
    EntitySystemSetupUtil.addEntityManagementRelatedClasses(context);
    entityManager = context.get(EngineEntityManager.class);
    eventSystem = context.get(EventSystem.class);
    context.put(Console.class, new ConsoleImpl(context));
    NUIManager nuiManager = new NUIManagerInternal(context.get(CanvasRenderer.class), context);
    context.put(NUIManager.class, nuiManager);
    componentSystemManager = new ComponentSystemManager(context);
    context.put(ComponentSystemManager.class, componentSystemManager);
    componentSystemManager.register(new ConsoleSystem(), "engine:ConsoleSystem");
    componentSystemManager.register(new CoreCommands(), "engine:CoreCommands");
    componentSystemManager.register(context.get(InputSystem.class), "engine:InputSystem");
    EntityRef localPlayerEntity = entityManager.create(new ClientComponent());
    LocalPlayer localPlayer = new LocalPlayer();
    context.put(LocalPlayer.class, localPlayer);
    localPlayer.setClientEntity(localPlayerEntity);
    componentSystemManager.initialise();
    GameManifest gameManifest = null;
    List<GameInfo> savedGames = GameProvider.getSavedGames();
    if (savedGames.size() > 0) {
        gameManifest = savedGames.get(0).getManifest();
    } else {
        gameManifest = createGameManifest();
    }
    gameEngine.changeState(new StateLoading(gameManifest, NetworkMode.LISTEN_SERVER));
}
Also used : EngineEntityManager(org.terasology.entitySystem.entity.internal.EngineEntityManager) GameInfo(org.terasology.rendering.nui.layers.mainMenu.savedGames.GameInfo) StateLoading(org.terasology.engine.modes.StateLoading) ConsoleImpl(org.terasology.logic.console.ConsoleImpl) CanvasRenderer(org.terasology.rendering.nui.internal.CanvasRenderer) LocalPlayer(org.terasology.logic.players.LocalPlayer) InputSystem(org.terasology.input.InputSystem) CoreCommands(org.terasology.logic.console.commands.CoreCommands) ClientComponent(org.terasology.network.ClientComponent) NUIManagerInternal(org.terasology.rendering.nui.internal.NUIManagerInternal) ComponentSystemManager(org.terasology.engine.ComponentSystemManager) ConsoleSystem(org.terasology.logic.console.ConsoleSystem) GameManifest(org.terasology.game.GameManifest) EventSystem(org.terasology.entitySystem.event.internal.EventSystem) NUIManager(org.terasology.rendering.nui.NUIManager) EntityRef(org.terasology.entitySystem.entity.EntityRef)

Aggregations

GameManifest (org.terasology.game.GameManifest)7 StateLoading (org.terasology.engine.modes.StateLoading)4 Module (org.terasology.module.Module)3 ModuleManager (org.terasology.engine.module.ModuleManager)2 IOException (java.io.IOException)1 Path (java.nio.file.Path)1 FileTime (java.nio.file.attribute.FileTime)1 Date (java.util.Date)1 HashMap (java.util.HashMap)1 List (java.util.List)1 Map (java.util.Map)1 Set (java.util.Set)1 SortedMap (java.util.SortedMap)1 Config (org.terasology.config.Config)1 WorldGenerationConfig (org.terasology.config.WorldGenerationConfig)1 ComponentSystemManager (org.terasology.engine.ComponentSystemManager)1 GameEngine (org.terasology.engine.GameEngine)1 SimpleUri (org.terasology.engine.SimpleUri)1 Time (org.terasology.engine.Time)1 StateMainMenu (org.terasology.engine.modes.StateMainMenu)1