예제 #1
0
 @Override
 public boolean step() {
   NetworkSystemImpl networkSystem = (NetworkSystemImpl) context.get(NetworkSystem.class);
   EntityRef client = networkSystem.getServer().getClientEntity();
   if (client.exists()) {
     context.get(LocalPlayer.class).setClientEntity(client);
     return true;
   }
   return false;
 }
예제 #2
0
  @Override
  public boolean step() {
    NetworkSystem networkSystem = context.get(NetworkSystem.class);
    WorldAtlas atlas =
        new WorldAtlasImpl(context.get(Config.class).getRendering().getMaxTextureAtlasResolution());
    context.put(WorldAtlas.class, atlas);

    BlockManagerImpl blockManager;
    if (networkSystem.getMode().isAuthority()) {
      blockManager = new BlockManagerImpl(atlas, context.get(AssetManager.class), true);
      blockManager.subscribe(context.get(NetworkSystem.class));
    } else {
      blockManager = new BlockManagerImpl(atlas, context.get(AssetManager.class), false);
    }
    context.put(BlockManager.class, blockManager);
    context
        .get(TypeSerializationLibrary.class)
        .add(Block.class, new BlockTypeHandler(blockManager));
    context
        .get(TypeSerializationLibrary.class)
        .add(BlockFamily.class, new BlockFamilyTypeHandler(blockManager));

    blockManager.initialise(
        gameManifest.getRegisteredBlockFamilies(), gameManifest.getBlockIdMap());

    return true;
  }
  @Override
  public boolean step() {
    EntityManager entityManager = context.get(EntityManager.class);
    WorldRenderer worldRenderer = context.get(WorldRenderer.class);

    Iterator<EntityRef> worldEntityIterator =
        entityManager.getEntitiesWith(WorldComponent.class).iterator();
    // TODO: Move the world renderer bits elsewhere
    if (worldEntityIterator.hasNext()) {
      EntityRef worldEntity = worldEntityIterator.next();
      worldRenderer.getChunkProvider().setWorldEntity(worldEntity);

      // get the world generator config from the world entity
      // replace the world generator values from the components in the world entity
      WorldGenerator worldGenerator = context.get(WorldGenerator.class);
      WorldConfigurator worldConfigurator = worldGenerator.getConfigurator();
      Map<String, Component> params = worldConfigurator.getProperties();
      for (Map.Entry<String, Component> entry : params.entrySet()) {
        Class<? extends Component> clazz = entry.getValue().getClass();
        Component comp = worldEntity.getComponent(clazz);
        if (comp != null) {
          worldConfigurator.setProperty(entry.getKey(), comp);
        }
      }
    } else {
      EntityRef worldEntity = entityManager.create();
      worldEntity.addComponent(new WorldComponent());
      worldRenderer.getChunkProvider().setWorldEntity(worldEntity);

      // transfer all world generation parameters from Config to WorldEntity
      WorldGenerator worldGenerator = context.get(WorldGenerator.class);
      SimpleUri generatorUri = worldGenerator.getUri();
      Config config = context.get(Config.class);

      // get the map of properties from the world generator.
      // Replace its values with values from the config set by the UI.
      // Also set all the components to the world entity.
      WorldConfigurator worldConfigurator = worldGenerator.getConfigurator();
      Map<String, Component> params = worldConfigurator.getProperties();
      for (Map.Entry<String, Component> entry : params.entrySet()) {
        Class<? extends Component> clazz = entry.getValue().getClass();
        Component comp = config.getModuleConfig(generatorUri, entry.getKey(), clazz);
        if (comp != null) {
          worldEntity.addComponent(comp);
          worldConfigurator.setProperty(entry.getKey(), comp);
        } else {
          worldEntity.addComponent(entry.getValue());
        }
      }
    }

    return true;
  }
예제 #4
0
  /**
   * Runs the engine, including its main loop. This method is called only once per application
   * startup, which is the reason the GameState provided is the -initial- state rather than a
   * generic game state.
   *
   * @param initialState In at least one context (the PC facade) the GameState implementation
   *     provided as input may vary, depending if the application has or hasn't been started
   *     headless.
   */
  @Override
  public synchronized void run(GameState initialState) {
    Preconditions.checkState(!running);
    running = true;
    initialize();
    changeStatus(StandardGameStatus.RUNNING);

    try {
      rootContext.put(GameEngine.class, this);
      changeState(initialState);

      mainLoop(); // -THE- MAIN LOOP. Most of the application time and resources are spent here.
    } catch (RuntimeException e) {
      logger.error("Uncaught exception, attempting clean game shutdown", e);
      throw e;
    } finally {
      try {
        cleanup();
      } catch (RuntimeException t) {
        logger.error("Clean game shutdown after an uncaught exception failed", t);
      }
      running = false;
      shutdownRequested = false;
      changeStatus(StandardGameStatus.UNSTARTED);
    }
  }
예제 #5
0
 @Override
 public boolean step() {
   if (worldRenderer.pregenerateChunks()) {
     return true;
   }
   EngineTime time = (EngineTime) context.get(Time.class);
   long totalTime = time.getRawTimeInMs() - startTime;
   return totalTime > 5000;
 }
예제 #6
0
 private void switchState(GameState newState) {
   if (currentState != null) {
     currentState.dispose();
   }
   currentState = newState;
   LoggingContext.setGameState(newState);
   newState.init(this);
   for (StateChangeSubscriber subscriber : stateChangeSubscribers) {
     subscriber.onStateChange();
   }
   // drain input queues
   InputSystem inputSystem = rootContext.get(InputSystem.class);
   inputSystem.getMouseDevice().getInputQueue();
   inputSystem.getKeyboard().getInputQueue();
 }
예제 #7
0
 /**
  * Updates a config with any binds that it may be missing, through reflection over
  * RegisterBindButton annotations
  */
 public void updateForChangedMods(Context context) {
   ModuleManager moduleManager = context.get(ModuleManager.class);
   DependencyResolver resolver = new DependencyResolver(moduleManager.getRegistry());
   for (Name moduleId : moduleManager.getRegistry().getModuleIds()) {
     if (moduleManager.getRegistry().getLatestModuleVersion(moduleId).isCodeModule()) {
       ResolutionResult result = resolver.resolve(moduleId);
       if (result.isSuccess()) {
         try (ModuleEnvironment environment =
             moduleManager.loadEnvironment(result.getModules(), false)) {
           updateInputsFor(
               moduleId,
               environment.getTypesAnnotatedWith(
                   RegisterBindButton.class, new FromModule(environment, moduleId)));
         }
       }
     }
   }
 }
예제 #8
0
  private void initialize() {
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    Stopwatch totalInitTime = Stopwatch.createStarted();
    try {
      logger.info("Initializing Terasology...");
      logEnvironmentInfo();

      // TODO: Need to get everything thread safe and get rid of the concept of "GameThread" as much
      // as possible.
      GameThread.setToCurrentThread();

      preInitSubsystems();

      initManagers();

      initSubsystems();

      changeStatus(TerasologyEngineStatus.INITIALIZING_ASSET_MANAGEMENT);
      initAssets();

      EnvironmentSwitchHandler environmentSwitcher = new EnvironmentSwitchHandler();
      rootContext.put(EnvironmentSwitchHandler.class, environmentSwitcher);

      environmentSwitcher.handleSwitchToGameEnvironment(rootContext);

      postInitSubsystems();

      verifyInitialisation();

      /**
       * Prevent objects being put in engine context after init phase. Engine states should
       * use/create a child context.
       */
      CoreRegistry.setContext(null);
    } catch (RuntimeException e) {
      logger.error("Failed to initialise Terasology", e);
      cleanup();
      throw e;
    }

    double seconds = 0.001 * totalInitTime.elapsed(TimeUnit.MILLISECONDS);
    logger.info("Initialization completed in {}sec.", String.format("%.2f", seconds));
  }
예제 #9
0
 /**
  * @return A new BindsConfig, with inputs set from the DefaultBinding annotations on bind classes
  */
 public static BindsConfig createDefault(Context context) {
   ModuleManager moduleManager = context.get(ModuleManager.class);
   BindsConfig config = new BindsConfig();
   DependencyResolver resolver = new DependencyResolver(moduleManager.getRegistry());
   for (Name moduleId : moduleManager.getRegistry().getModuleIds()) {
     if (moduleManager.getRegistry().getLatestModuleVersion(moduleId).isCodeModule()) {
       ResolutionResult result = resolver.resolve(moduleId);
       if (result.isSuccess()) {
         try (ModuleEnvironment environment =
             moduleManager.loadEnvironment(result.getModules(), false)) {
           config.addDefaultsFor(
               moduleId,
               environment.getTypesAnnotatedWith(
                   RegisterBindButton.class, new FromModule(environment, moduleId)));
         }
       }
     }
   }
   return config;
 }
예제 #10
0
 /**
  * Updates a config with any binds that it may be missing, through reflection over
  * RegisterBindButton annotations
  */
 public void updateForChangedMods(Context context) {
   ModuleManager moduleManager = context.get(ModuleManager.class);
   DependencyResolver resolver = new DependencyResolver(moduleManager.getRegistry());
   for (Name moduleId : moduleManager.getRegistry().getModuleIds()) {
     if (moduleManager.getRegistry().getLatestModuleVersion(moduleId).isCodeModule()) {
       ResolutionResult result = resolver.resolve(moduleId);
       if (result.isSuccess()) {
         try (ModuleEnvironment environment =
             moduleManager.loadEnvironment(result.getModules(), false)) {
           FromModule filter = new FromModule(environment, moduleId);
           Iterable<Class<?>> buttons =
               environment.getTypesAnnotatedWith(RegisterBindButton.class, filter);
           Iterable<Class<?>> axes =
               environment.getTypesAnnotatedWith(RegisterRealBindAxis.class, filter);
           updateButtonInputsFor(moduleId, buttons);
           updateAxisInputsFor(moduleId, axes);
         }
       }
     }
   }
 }
예제 #11
0
  private void initAssets() {
    DefaultBlockFamilyFactoryRegistry familyFactoryRegistry =
        new DefaultBlockFamilyFactoryRegistry();
    rootContext.put(BlockFamilyFactoryRegistry.class, familyFactoryRegistry);

    // cast lambdas explicitly to avoid inconsistent compiler behavior wrt. type inference
    assetTypeManager.registerCoreAssetType(
        Prefab.class, (AssetFactory<Prefab, PrefabData>) PojoPrefab::new, false, "prefabs");
    assetTypeManager.registerCoreAssetType(
        BlockShape.class, (AssetFactory<BlockShape, BlockShapeData>) BlockShapeImpl::new, "shapes");
    assetTypeManager.registerCoreAssetType(
        BlockSounds.class,
        (AssetFactory<BlockSounds, BlockSoundsData>) BlockSounds::new,
        "blockSounds");
    assetTypeManager.registerCoreAssetType(
        BlockTile.class, (AssetFactory<BlockTile, TileData>) BlockTile::new, "blockTiles");
    assetTypeManager.registerCoreAssetType(
        BlockFamilyDefinition.class,
        (AssetFactory<BlockFamilyDefinition, BlockFamilyDefinitionData>) BlockFamilyDefinition::new,
        "blocks");
    assetTypeManager.registerCoreFormat(
        BlockFamilyDefinition.class,
        new BlockFamilyDefinitionFormat(assetTypeManager.getAssetManager(), familyFactoryRegistry));
    assetTypeManager.registerCoreAssetType(
        UISkin.class, (AssetFactory<UISkin, UISkinData>) UISkin::new, "skins");
    assetTypeManager.registerCoreAssetType(
        BehaviorTree.class,
        (AssetFactory<BehaviorTree, BehaviorTreeData>) BehaviorTree::new,
        false,
        "behaviors");
    assetTypeManager.registerCoreAssetType(
        UIElement.class, (AssetFactory<UIElement, UIData>) UIElement::new, "ui");

    for (EngineSubsystem subsystem : allSubsystems) {
      subsystem.registerCoreAssetTypes(assetTypeManager);
    }
  }
예제 #12
0
  private void initManagers() {

    changeStatus(TerasologyEngineStatus.INITIALIZING_MODULE_MANAGER);
    ModuleManager moduleManager = new ModuleManagerImpl();
    rootContext.put(ModuleManager.class, moduleManager);

    changeStatus(TerasologyEngineStatus.INITIALIZING_LOWLEVEL_OBJECT_MANIPULATION);
    ReflectFactory reflectFactory = new ReflectionReflectFactory();
    rootContext.put(ReflectFactory.class, reflectFactory);

    CopyStrategyLibrary copyStrategyLibrary = new CopyStrategyLibrary(reflectFactory);
    rootContext.put(CopyStrategyLibrary.class, copyStrategyLibrary);
    rootContext.put(
        TypeSerializationLibrary.class,
        new TypeSerializationLibrary(reflectFactory, copyStrategyLibrary));

    changeStatus(TerasologyEngineStatus.INITIALIZING_ASSET_TYPES);
    assetTypeManager = new ModuleAwareAssetTypeManager();
    rootContext.put(ModuleAwareAssetTypeManager.class, assetTypeManager);
    rootContext.put(AssetManager.class, assetTypeManager.getAssetManager());
  }
예제 #13
0
 /**
  * Allows it to obtain objects directly from the context of the game engine. It exists only for
  * situations in which no child context exists yet. If there is a child context then it
  * automatically contains the objects of the engine context. Thus normal code should just work
  * with the (child) context that is available to it instead of using this method.
  *
  * @return a object directly from the context of the game engine
  */
 public <T> T getFromEngineContext(Class<? extends T> type) {
   return rootContext.get(type);
 }
예제 #14
0
 @Override
 public void initialise(GameEngine engine, Context rootContext) {
   rootContext.put(ParameterAdapterManager.class, ParameterAdapterManager.createCore());
 }
예제 #15
0
 @Override
 public void begin() {
   worldRenderer = context.get(WorldRenderer.class);
   EngineTime time = (EngineTime) context.get(Time.class);
   startTime = time.getRawTimeInMs();
 }
 public EntityAwareWorldProvider(WorldProviderCore base, Context context) {
   super(base);
   entityManager = (EngineEntityManager) context.get(EntityManager.class);
   context.get(ComponentSystemManager.class).register(getTime());
 }
예제 #17
0
 /**
  * Verifies that a required class is available through the core registry.
  *
  * @param clazz The required type, i.e. Time.class
  * @throws IllegalStateException Details the required system that has not been registered.
  */
 private void verifyRequiredSystemIsRegistered(Class<?> clazz) {
   if (rootContext.get(clazz) == null) {
     throw new IllegalStateException(clazz.getSimpleName() + " not registered as a core system.");
   }
 }
 public StunAlterationEffect(Context context) {
   this.delayManager = context.get(DelayManager.class);
 }