Search in sources :

Example 1 with WorldInfo

use of org.terasology.world.internal.WorldInfo 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 WorldInfo

use of org.terasology.world.internal.WorldInfo in project Terasology by MovingBlocks.

the class JoinGameScreen method getWorldText.

private String getWorldText(Future<ServerInfoMessage> info) {
    try {
        List<String> codedWorldInfo = new ArrayList<>();
        for (WorldInfo wi : info.get().getWorldInfoList()) {
            float timeInDays = wi.getTime() / (float) WorldTime.DAY_LENGTH;
            codedWorldInfo.add(String.format("%s (%.2f days)", wi.getTitle(), timeInDays));
        }
        return Joiner.on('\n').join(codedWorldInfo);
    } catch (ExecutionException | InterruptedException e) {
        return FontColor.getColored(translationSystem.translate("${engine:menu#connection-failed}"), Color.RED);
    }
}
Also used : ArrayList(java.util.ArrayList) WorldInfo(org.terasology.world.internal.WorldInfo) ExecutionException(java.util.concurrent.ExecutionException)

Example 3 with WorldInfo

use of org.terasology.world.internal.WorldInfo in project Terasology by MovingBlocks.

the class ServerInfoMessageImpl method getWorldInfoList.

@Override
public List<WorldInfo> getWorldInfoList() {
    List<WorldInfo> result = Lists.newArrayList();
    for (NetData.WorldInfo pbWorldInfo : info.getWorldInfoList()) {
        WorldInfo worldInfo = new WorldInfo();
        worldInfo.setTime(pbWorldInfo.getTime());
        worldInfo.setTitle(pbWorldInfo.getTitle());
        result.add(worldInfo);
    }
    return result;
}
Also used : NetData(org.terasology.protobuf.NetData) WorldInfo(org.terasology.world.internal.WorldInfo)

Example 4 with WorldInfo

use of org.terasology.world.internal.WorldInfo in project Terasology by MovingBlocks.

the class InitialiseWorld method step.

@Override
public boolean step() {
    BlockManager blockManager = context.get(BlockManager.class);
    BiomeManager biomeManager = context.get(BiomeManager.class);
    ModuleEnvironment environment = context.get(ModuleManager.class).getEnvironment();
    context.put(WorldGeneratorPluginLibrary.class, new DefaultWorldGeneratorPluginLibrary(environment, context));
    WorldInfo worldInfo = gameManifest.getWorldInfo(TerasologyConstants.MAIN_WORLD);
    if (worldInfo.getSeed() == null || worldInfo.getSeed().isEmpty()) {
        FastRandom random = new FastRandom();
        worldInfo.setSeed(random.nextString(16));
    }
    logger.info("World seed: \"{}\"", worldInfo.getSeed());
    // TODO: Separate WorldRenderer from world handling in general
    WorldGeneratorManager worldGeneratorManager = context.get(WorldGeneratorManager.class);
    WorldGenerator worldGenerator;
    try {
        worldGenerator = WorldGeneratorManager.createGenerator(worldInfo.getWorldGenerator(), context);
        // setting the world seed will create the world builder
        worldGenerator.setWorldSeed(worldInfo.getSeed());
        context.put(WorldGenerator.class, worldGenerator);
    } catch (UnresolvedWorldGeneratorException e) {
        logger.error("Unable to load world generator {}. Available world generators: {}", worldInfo.getWorldGenerator(), worldGeneratorManager.getWorldGenerators());
        context.get(GameEngine.class).changeState(new StateMainMenu("Failed to resolve world generator."));
        // We need to return true, otherwise the loading state will just call us again immediately
        return true;
    }
    // Init. a new world
    EngineEntityManager entityManager = (EngineEntityManager) context.get(EntityManager.class);
    boolean writeSaveGamesEnabled = context.get(Config.class).getSystem().isWriteSaveGamesEnabled();
    Path savePath = PathManager.getInstance().getSavePath(gameManifest.getTitle());
    StorageManager storageManager;
    try {
        storageManager = writeSaveGamesEnabled ? new ReadWriteStorageManager(savePath, environment, entityManager, blockManager, biomeManager) : new ReadOnlyStorageManager(savePath, environment, entityManager, blockManager, biomeManager);
    } catch (IOException e) {
        logger.error("Unable to create storage manager!", e);
        context.get(GameEngine.class).changeState(new StateMainMenu("Unable to create storage manager!"));
        // We need to return true, otherwise the loading state will just call us again immediately
        return true;
    }
    context.put(StorageManager.class, storageManager);
    LocalChunkProvider chunkProvider = new LocalChunkProvider(storageManager, entityManager, worldGenerator, blockManager, biomeManager);
    context.get(ComponentSystemManager.class).register(new RelevanceSystem(chunkProvider), "engine:relevanceSystem");
    Block unloadedBlock = blockManager.getBlock(BlockManager.UNLOADED_ID);
    WorldProviderCoreImpl worldProviderCore = new WorldProviderCoreImpl(worldInfo, chunkProvider, unloadedBlock, context);
    EntityAwareWorldProvider entityWorldProvider = new EntityAwareWorldProvider(worldProviderCore, context);
    WorldProvider worldProvider = new WorldProviderWrapper(entityWorldProvider);
    context.put(WorldProvider.class, worldProvider);
    chunkProvider.setBlockEntityRegistry(entityWorldProvider);
    context.put(BlockEntityRegistry.class, entityWorldProvider);
    context.get(ComponentSystemManager.class).register(entityWorldProvider, "engine:BlockEntityRegistry");
    DefaultCelestialSystem celestialSystem = new DefaultCelestialSystem(new BasicCelestialModel(), context);
    context.put(CelestialSystem.class, celestialSystem);
    context.get(ComponentSystemManager.class).register(celestialSystem);
    Skysphere skysphere = new Skysphere(context);
    BackdropProvider backdropProvider = skysphere;
    BackdropRenderer backdropRenderer = skysphere;
    context.put(BackdropProvider.class, backdropProvider);
    context.put(BackdropRenderer.class, backdropRenderer);
    RenderingSubsystemFactory engineSubsystemFactory = context.get(RenderingSubsystemFactory.class);
    WorldRenderer worldRenderer = engineSubsystemFactory.createWorldRenderer(context);
    context.put(WorldRenderer.class, worldRenderer);
    // TODO: These shouldn't be done here, nor so strongly tied to the world renderer
    context.put(LocalPlayer.class, new LocalPlayer());
    context.put(Camera.class, worldRenderer.getActiveCamera());
    return true;
}
Also used : WorldGenerator(org.terasology.world.generator.WorldGenerator) WorldGeneratorManager(org.terasology.world.generator.internal.WorldGeneratorManager) UnresolvedWorldGeneratorException(org.terasology.world.generator.UnresolvedWorldGeneratorException) LocalChunkProvider(org.terasology.world.chunks.localChunkProvider.LocalChunkProvider) LocalPlayer(org.terasology.logic.players.LocalPlayer) WorldProviderWrapper(org.terasology.world.internal.WorldProviderWrapper) ReadOnlyStorageManager(org.terasology.persistence.internal.ReadOnlyStorageManager) ReadWriteStorageManager(org.terasology.persistence.internal.ReadWriteStorageManager) StorageManager(org.terasology.persistence.StorageManager) ModuleManager(org.terasology.engine.module.ModuleManager) EntityAwareWorldProvider(org.terasology.world.internal.EntityAwareWorldProvider) BackdropProvider(org.terasology.rendering.backdrop.BackdropProvider) ComponentSystemManager(org.terasology.engine.ComponentSystemManager) DefaultWorldGeneratorPluginLibrary(org.terasology.world.generator.plugin.DefaultWorldGeneratorPluginLibrary) EntityAwareWorldProvider(org.terasology.world.internal.EntityAwareWorldProvider) WorldProvider(org.terasology.world.WorldProvider) WorldInfo(org.terasology.world.internal.WorldInfo) BiomeManager(org.terasology.world.biomes.BiomeManager) EngineEntityManager(org.terasology.entitySystem.entity.internal.EngineEntityManager) Path(java.nio.file.Path) FastRandom(org.terasology.utilities.random.FastRandom) IOException(java.io.IOException) WorldProviderCoreImpl(org.terasology.world.internal.WorldProviderCoreImpl) DefaultCelestialSystem(org.terasology.world.sun.DefaultCelestialSystem) RenderingSubsystemFactory(org.terasology.engine.subsystem.RenderingSubsystemFactory) WorldRenderer(org.terasology.rendering.world.WorldRenderer) BasicCelestialModel(org.terasology.world.sun.BasicCelestialModel) EntityManager(org.terasology.entitySystem.entity.EntityManager) EngineEntityManager(org.terasology.entitySystem.entity.internal.EngineEntityManager) BlockManager(org.terasology.world.block.BlockManager) ModuleEnvironment(org.terasology.module.ModuleEnvironment) StateMainMenu(org.terasology.engine.modes.StateMainMenu) Skysphere(org.terasology.rendering.backdrop.Skysphere) Block(org.terasology.world.block.Block) ReadWriteStorageManager(org.terasology.persistence.internal.ReadWriteStorageManager) ReadOnlyStorageManager(org.terasology.persistence.internal.ReadOnlyStorageManager) RelevanceSystem(org.terasology.world.chunks.localChunkProvider.RelevanceSystem) BackdropRenderer(org.terasology.rendering.backdrop.BackdropRenderer)

Example 5 with WorldInfo

use of org.terasology.world.internal.WorldInfo in project Terasology by MovingBlocks.

the class StorageManagerTest method setup.

@Before
public void setup() throws Exception {
    super.setup();
    JavaArchive homeArchive = ShrinkWrap.create(JavaArchive.class);
    FileSystem vfs = ShrinkWrapFileSystems.newFileSystem(homeArchive);
    PathManager.getInstance().useOverrideHomePath(temporaryFolder.getRoot().toPath());
    savePath = PathManager.getInstance().getSavePath("testSave");
    assert !Files.isRegularFile(vfs.getPath("global.dat"));
    entityManager = context.get(EngineEntityManager.class);
    moduleEnvironment = context.get(ModuleEnvironment.class);
    blockManager = context.get(BlockManager.class);
    biomeManager = context.get(BiomeManager.class);
    esm = new ReadWriteStorageManager(savePath, moduleEnvironment, entityManager, blockManager, biomeManager, false);
    context.put(StorageManager.class, esm);
    this.character = entityManager.create();
    Client client = createClientMock(PLAYER_ID, character);
    NetworkSystem networkSystem = mock(NetworkSystem.class);
    when(networkSystem.getMode()).thenReturn(NetworkMode.NONE);
    when(networkSystem.getPlayers()).thenReturn(Arrays.asList(client));
    context.put(NetworkSystem.class, networkSystem);
    AssetManager assetManager = context.get(AssetManager.class);
    BlockFamilyDefinitionData data = new BlockFamilyDefinitionData();
    data.setFamilyFactory(new SymmetricBlockFamilyFactory());
    assetManager.loadAsset(new ResourceUrn("test:testblock"), data, BlockFamilyDefinition.class);
    assetManager.loadAsset(new ResourceUrn("test:testblock2"), data, BlockFamilyDefinition.class);
    testBlock = context.get(BlockManager.class).getBlock("test:testblock");
    testBlock2 = context.get(BlockManager.class).getBlock("test:testblock2");
    context.put(ChunkProvider.class, mock(ChunkProvider.class));
    BiomeManager mockBiomeManager = mock(BiomeManager.class);
    when(mockBiomeManager.getBiomes()).thenReturn(Collections.<Biome>emptyList());
    context.put(BiomeManager.class, mockBiomeManager);
    WorldProvider worldProvider = mock(WorldProvider.class);
    when(worldProvider.getWorldInfo()).thenReturn(new WorldInfo());
    context.put(WorldProvider.class, worldProvider);
}
Also used : EngineEntityManager(org.terasology.entitySystem.entity.internal.EngineEntityManager) BiomeManager(org.terasology.world.biomes.BiomeManager) AssetManager(org.terasology.assets.management.AssetManager) NetworkSystem(org.terasology.network.NetworkSystem) JavaArchive(org.jboss.shrinkwrap.api.spec.JavaArchive) BlockFamilyDefinitionData(org.terasology.world.block.loader.BlockFamilyDefinitionData) ModuleEnvironment(org.terasology.module.ModuleEnvironment) BlockManager(org.terasology.world.block.BlockManager) FileSystem(java.nio.file.FileSystem) WorldProvider(org.terasology.world.WorldProvider) WorldInfo(org.terasology.world.internal.WorldInfo) Client(org.terasology.network.Client) ResourceUrn(org.terasology.assets.ResourceUrn) ChunkProvider(org.terasology.world.chunks.ChunkProvider) SymmetricBlockFamilyFactory(org.terasology.world.block.family.SymmetricBlockFamilyFactory) Before(org.junit.Before)

Aggregations

WorldInfo (org.terasology.world.internal.WorldInfo)8 ModuleManager (org.terasology.engine.module.ModuleManager)3 Module (org.terasology.module.Module)3 WorldProvider (org.terasology.world.WorldProvider)3 Set (java.util.Set)2 StateMainMenu (org.terasology.engine.modes.StateMainMenu)2 EngineEntityManager (org.terasology.entitySystem.entity.internal.EngineEntityManager)2 GameManifest (org.terasology.game.GameManifest)2 ModuleEnvironment (org.terasology.module.ModuleEnvironment)2 FastRandom (org.terasology.utilities.random.FastRandom)2 BiomeManager (org.terasology.world.biomes.BiomeManager)2 BlockManager (org.terasology.world.block.BlockManager)2 IOException (java.io.IOException)1 FileSystem (java.nio.file.FileSystem)1 Path (java.nio.file.Path)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 Map (java.util.Map)1 Entry (java.util.Map.Entry)1 ExecutionException (java.util.concurrent.ExecutionException)1