private EntityRef createResultItem(String itemResult) {
    String resultText = itemResult;
    int count = 1;
    int starIndex = resultText.indexOf("*");
    if (starIndex > -1) {
      count = Integer.parseInt(resultText.substring(0, starIndex));
      resultText = resultText.substring(starIndex + 1);
    }

    EntityManager entityManager = CoreRegistry.get(EntityManager.class);
    BlockManager blockManager = CoreRegistry.get(BlockManager.class);
    PrefabManager prefabManager = CoreRegistry.get(PrefabManager.class);
    Prefab prefab = prefabManager.getPrefab(resultText);

    EntityRef result;
    if (prefab != null) {
      result = entityManager.create(prefab);
      ItemComponent item = result.getComponent(ItemComponent.class);
      item.stackCount = (byte) count;
      result.saveComponent(item);
    } else {
      BlockItemFactory blockItemFactory = new BlockItemFactory(entityManager);
      BlockFamily blockFamily = blockManager.getBlockFamily(resultText);
      result = blockItemFactory.newInstance(blockFamily, count);
    }
    return result;
  }
  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);
  }
 @Override
 public BlockFamily deserialize(EntityData.Value value) {
   if (value.getStringCount() > 0) {
     return blockManager.getBlockFamily(value.getString(0));
   }
   return null;
 }
 @Override
 public List<BlockFamily> deserializeCollection(EntityData.Value value) {
   List<BlockFamily> result = Lists.newArrayListWithCapacity(value.getStringCount());
   for (String item : value.getStringList()) {
     result.add(blockManager.getBlockFamily(item));
   }
   return result;
 }
 @Test
 public void testEntityBecomesTemporaryWhenChangedFromAKeepActiveBlock() {
   worldProvider.setBlock(Vector3i.zero(), keepActiveBlock);
   EntityRef blockEntity = worldProvider.getBlockEntityAt(new Vector3i(0, 0, 0));
   worldProvider.setBlock(Vector3i.zero(), BlockManager.getAir());
   worldProvider.update(1.0f);
   assertFalse(blockEntity.isActive());
 }
  @Test
  public void allComponentsNotMarkedAsRetainedRemovedOnBlockChange() {
    worldStub.setBlock(Vector3i.zero(), blockWithString);
    EntityRef entity = worldProvider.getBlockEntityAt(new Vector3i(0, 0, 0));
    entity.addComponent(new ForceBlockActiveComponent());
    entity.addComponent(new RetainedOnBlockChangeComponent(2));

    worldProvider.setBlock(Vector3i.zero(), BlockManager.getAir());

    assertTrue(entity.hasComponent(RetainedOnBlockChangeComponent.class));
    assertFalse(entity.hasComponent(ForceBlockActiveComponent.class));
  }
 private ChunkViewCore createWorldView(Region3i region, Vector3i offset) {
   Chunk[] chunks = new Chunk[region.sizeX() * region.sizeY() * region.sizeZ()];
   for (Vector3i chunkPos : region) {
     Chunk chunk = nearCache.get(chunkPos);
     if (chunk == null || !chunk.isReady()) {
       return null;
     }
     chunkPos.sub(region.minX(), region.minY(), region.minZ());
     int index = TeraMath.calculate3DArrayIndex(chunkPos, region.size());
     chunks[index] = chunk;
   }
   return new ChunkViewCoreImpl(
       chunks, region, offset, blockManager.getBlock(BlockManager.AIR_ID));
 }
  @Test
  public void testComponentsDeactivatedAndRemovedWhenBlockChanged() {
    worldProvider.setBlock(Vector3i.zero(), blockWithString);

    LifecycleEventChecker checker =
        new LifecycleEventChecker(entityManager.getEventSystem(), StringComponent.class);

    worldProvider.setBlock(Vector3i.zero(), BlockManager.getAir());
    EntityRef blockEntity = worldProvider.getBlockEntityAt(new Vector3i(0, 0, 0));
    assertTrue(blockEntity.exists());

    assertEquals(
        Lists.newArrayList(
            new EventInfo(BeforeDeactivateComponent.newInstance(), blockEntity),
            new EventInfo(BeforeRemoveComponent.newInstance(), blockEntity)),
        checker.receivedEvents);
  }
  private TShortObjectMap<TIntList> createBatchBlockEventMappings(Chunk chunk) {
    TShortObjectMap<TIntList> batchBlockMap = new TShortObjectHashMap<>();
    for (Block block : blockManager.listRegisteredBlocks()) {
      if (block.isLifecycleEventsRequired()) {
        batchBlockMap.put(block.getId(), new TIntArrayList());
      }
    }

    ChunkBlockIterator i = chunk.getBlockIterator();
    while (i.next()) {
      if (i.getBlock().isLifecycleEventsRequired()) {
        TIntList positionList = batchBlockMap.get(i.getBlock().getId());
        positionList.add(i.getBlockPos().x);
        positionList.add(i.getBlockPos().y);
        positionList.add(i.getBlockPos().z);
      }
    }
    return batchBlockMap;
  }
  @Override
  public void preBegin() {
    createSeasonsChapter();

    StaticJournalChapterHandler chapterHandler = new StaticJournalChapterHandler();

    Prefab stoneItem = prefabManager.getPrefab("WoodAndStone:Stone");
    Prefab toolStoneItem = prefabManager.getPrefab("WoodAndStone:ToolStone");
    Prefab axeHammerHeadItem = prefabManager.getPrefab("WoodAndStone:AxeHammerHead");
    Prefab stickItem = prefabManager.getPrefab("WoodAndStone:Stick");
    Prefab twigItem = prefabManager.getPrefab("WoodAndStone:Twig");
    Prefab resinItem = prefabManager.getPrefab("WoodAndStone:Resin");
    Prefab unlitTorchItem = prefabManager.getPrefab("WoodAndStone:UnlitTorch");
    Prefab flintItem = prefabManager.getPrefab("WoodAndStone:Flint");

    Prefab crudeAxeHammerItem = prefabManager.getPrefab("WoodAndStone:CrudeAxeHammer");
    Prefab stoneHammerItem = prefabManager.getPrefab("WoodAndStone:StoneHammer");

    Block litTorchBlock = blockManager.getBlockFamily("WoodAndStone:LitTorch").getArchetypeBlock();

    List<JournalManager.JournalEntryPart> firstEntry =
        Arrays.asList(
            new TitleJournalPart("Wood and Stone"),
            new TextJournalPart(
                "Where am I? How did I get here? ...\nWhat am I going to do now? ...\n"
                    + "How am I going to survive the night? ...\n\nI should probably start off with building a safe shelter. "
                    + "I need some tools for that.\n\nI should get some sticks from the nearby tree branches and dig in the ground for some "
                    + "stones I might have a use for.\n\nWhile I'm at it, I will probably need something to bind the stick and stone together - "
                    + "twigs, should be good for that.\n\nOnce I get two stones, I should be able to make a Tool Stone (press G to open crafting window)."),
            new RecipeJournalPart(
                new Block[2], new Prefab[] {stoneItem, stoneItem}, null, toolStoneItem, 1),
            new TextJournalPart(
                "Once I get the Tool Stone, by using the Tool Stone on another stone I should be able "
                    + "to make an Axe-Hammer Head."),
            new RecipeJournalPart(
                new Block[2], new Prefab[] {toolStoneItem, stoneItem}, null, axeHammerHeadItem, 1),
            new TextJournalPart(
                "Then I can combine the Axe-Hammer Head with a Stick and a Twig to create a Crude Axe-Hammer."),
            new RecipeJournalPart(
                new Block[3],
                new Prefab[] {axeHammerHeadItem, stickItem, twigItem},
                null,
                crudeAxeHammerItem,
                1));

    chapterHandler.registerJournalEntry("1", firstEntry);

    chapterHandler.registerJournalEntry(
        "2",
        true,
        "Excellent! I got the Axe-Hammer, I should be able to cut some of the trees with it. "
            + "I can also use it to dig stone to get some more Stones for my crafting. It's not perfect but will have to do until I get my hands on a "
            + "better hammer or a pick.");

    chapterHandler.registerJournalEntry(
        "3",
        true,
        "These are big, there is no way I could handle them in my hands. "
            + "I have to build a place where I could work on them. I should place two of the logs on the ground next to each other "
            + "and then place my Axe on it (right-click your Axe-Hammer on the top face of one of the logs).");

    chapterHandler.registerJournalEntry(
        "4",
        true,
        "Now I can work on the logs (to open the interface, press 'E' while pointing "
            + "on the station).\n\nI can store some ingredients in the left-top corner of the station and my axe in the bottom-center "
            + "of the station. It's very crude and won't let me do much, but once I gather 10 Wood Planks I should be able to upgrade it. "
            + "(to upgrade place the ingredients into lower-left corner of the interface and press the 'Upgrade' button)");

    chapterHandler.registerJournalEntry(
        "5",
        true,
        "Finally I can make something more useful than just planks. "
            + "Not only that, but I can also create planks more efficiently! Quality of the workspace speaks for itself.\n\n"
            + "But I still can't make any tools. Hard to make it just out of wood, haha. I should probably find a good place "
            + "to work on stone materials. I should make two tables using planks and sticks.\n\nOnce I get the tables I should place them "
            + "on the ground next to each other and put my Axe-Hammer on top of one of them (same as before).");

    List<JournalManager.JournalEntryPart> stoneHammer =
        Arrays.asList(
            new TimestampJournalPart(),
            new TextJournalPart(
                "Now! On this workstation I should be able to create more durable tools. "
                    + "I should get myself a couple of hammers and finally go mining!"),
            new RecipeJournalPart(
                new Block[3],
                new Prefab[] {stoneItem, twigItem, stickItem},
                null,
                stoneHammerItem,
                1),
            new TextJournalPart(
                "It is going to be dark out there in the mines, I should prepare some torches in advance. "
                    + "I can use some of the Resin found while cutting trees with stick in a crafting window (press G) to "
                    + "create Unlit Torches."),
            new RecipeJournalPart(
                new Block[2], new Prefab[] {resinItem, stickItem}, null, unlitTorchItem, 1),
            new TextJournalPart(
                "Once I get them I should be able to light them up using flint in a crafting window. "
                    + "Just need to make sure not to light too many of them, as the torches last only for a bit of time."),
            new RecipeJournalPart(
                new Block[2], new Prefab[] {unlitTorchItem, flintItem}, litTorchBlock, null, 1));
    chapterHandler.registerJournalEntry("6", stoneHammer);

    journalManager.registerJournalChapter(
        wasChapterId,
        Assets.getTextureRegion("WoodAndStone:journalIcons.WoodAndStone"),
        "Wood and Stone",
        chapterHandler);
  }
 @Override
 public Block getFromString(String representation) {
   return blockManager.getBlock(representation);
 }
  @Override
  public void initialise() {
    final BlockManager blockManager = CoreRegistry.get(BlockManager.class);
    lampTurnedOff = blockManager.getBlock("signalling:SignalLampOff");
    lampTurnedOn = blockManager.getBlock("signalling:SignalLampOn");
    signalTransformer = blockManager.getBlock("signalling:SignalTransformer");
    signalPressurePlate = blockManager.getBlock("signalling:SignalPressurePlate");
    signalSwitch = blockManager.getBlock("signalling:SignalSwitch");
    signalLimitedSwitch = blockManager.getBlock("signalling:SignalLimitedSwitch");
    signalButton = blockManager.getBlock("signalling:SignalButton");

    signalOrGate = blockManager.getBlockFamily("signalling:SignalOrGate");
    signalAndGate = blockManager.getBlockFamily("signalling:SignalAndGate");
    signalXorGate = blockManager.getBlockFamily("signalling:SignalXorGate");
    signalNandGate = blockManager.getBlockFamily("signalling:SignalNandGate");

    signalOnDelayGate = blockManager.getBlockFamily("signalling:SignalOnDelayGate");
    signalOffDelayGate = blockManager.getBlockFamily("signalling:SignalOffDelayGate");

    signalSetResetGate = blockManager.getBlockFamily("signalling:SignalSetResetGate");
  }
  @Before
  public void setup() {
    GameThread.setGameThread();
    AssetManager assetManager =
        CoreRegistry.put(
            AssetManager.class,
            new AssetManager(new ModuleManagerImpl(new ModuleSecurityManager())));
    assetManager.setAssetFactory(
        AssetType.PREFAB,
        new AssetFactory<PrefabData, Prefab>() {

          @Override
          public Prefab buildAsset(AssetUri uri, PrefabData data) {
            return new PojoPrefab(uri, data);
          }
        });
    EntitySystemBuilder builder = new EntitySystemBuilder();

    CoreRegistry.put(ComponentSystemManager.class, mock(ComponentSystemManager.class));

    blockManager =
        CoreRegistry.put(
            BlockManager.class,
            new BlockManagerImpl(mock(WorldAtlas.class), new DefaultBlockFamilyFactoryRegistry()));
    NetworkSystem networkSystem = mock(NetworkSystem.class);
    when(networkSystem.getMode()).thenReturn(NetworkMode.NONE);
    entityManager = builder.build(moduleManager, networkSystem, new ReflectionReflectFactory());
    worldStub = new WorldProviderCoreStub(BlockManager.getAir());
    worldProvider = new EntityAwareWorldProvider(worldStub, entityManager);

    plainBlock = new Block();
    blockManager.addBlockFamily(
        new SymmetricFamily(new BlockUri("test:plainBlock"), plainBlock), true);

    blockWithString = new Block();
    PrefabData prefabData = new PrefabData();
    prefabData.addComponent(new StringComponent("Test"));
    Assets.generateAsset(
        new AssetUri(AssetType.PREFAB, "test:prefabWithString"), prefabData, Prefab.class);
    blockWithString.setPrefab("test:prefabWithString");
    blockManager.addBlockFamily(
        new SymmetricFamily(new BlockUri("test:blockWithString"), blockWithString), true);

    blockWithDifferentString = new Block();
    prefabData = new PrefabData();
    prefabData.addComponent(new StringComponent("Test2"));
    Assets.generateAsset(
        new AssetUri(AssetType.PREFAB, "test:prefabWithDifferentString"), prefabData, Prefab.class);
    blockWithDifferentString.setPrefab("test:prefabWithDifferentString");
    blockManager.addBlockFamily(
        new SymmetricFamily(
            new BlockUri("test:blockWithDifferentString"), blockWithDifferentString),
        true);

    blockWithRetainedComponent = new Block();
    prefabData = new PrefabData();
    prefabData.addComponent(new RetainedOnBlockChangeComponent(3));
    Assets.generateAsset(
        new AssetUri(AssetType.PREFAB, "test:prefabWithRetainedComponent"),
        prefabData,
        Prefab.class);
    blockWithRetainedComponent.setPrefab("test:prefabWithRetainedComponent");
    blockManager.addBlockFamily(
        new SymmetricFamily(
            new BlockUri("test:blockWithRetainedComponent"), blockWithRetainedComponent),
        true);

    blockInFamilyOne = new Block();
    blockInFamilyOne.setKeepActive(true);
    blockInFamilyOne.setPrefab("test:prefabWithString");
    blockInFamilyTwo = new Block();
    blockInFamilyTwo.setPrefab("test:prefabWithString");
    blockInFamilyTwo.setKeepActive(true);
    blockManager.addBlockFamily(
        new HorizontalBlockFamily(
            new BlockUri("test:blockFamily"),
            ImmutableMap.<Side, Block>of(
                Side.FRONT,
                blockInFamilyOne,
                Side.LEFT,
                blockInFamilyTwo,
                Side.RIGHT,
                blockInFamilyTwo,
                Side.BACK,
                blockInFamilyOne),
            Collections.<String>emptyList()),
        true);

    keepActiveBlock = new Block();
    keepActiveBlock.setKeepActive(true);
    keepActiveBlock.setPrefab("test:prefabWithString");
    blockManager.addBlockFamily(
        new SymmetricFamily(new BlockUri("test:keepActiveBlock"), keepActiveBlock), true);

    worldProvider.initialise();
  }