Search in sources :

Example 6 with Key

use of net.glowstone.chunk.GlowChunk.Key in project Glowstone by GlowstoneMC.

the class GlowPlayer method pulse.

@Override
public void pulse() {
    super.pulse();
    if (usageItem != null) {
        if (usageItem == getItemInHand()) {
            if (--usageTime == 0) {
                ItemType item = ItemTable.instance().getItem(usageItem.getType());
                if (item instanceof ItemFood) {
                    ((ItemFood) item).eat(this, usageItem);
                }
            }
        } else {
            usageItem = null;
            usageTime = 0;
        }
    }
    if (digging != null) {
        pulseDigging();
    }
    if (exhaustion > 4.0f) {
        exhaustion -= 4.0f;
        if (saturation > 0f) {
            saturation = Math.max(saturation - 1f, 0f);
            sendHealth();
        } else if (world.getDifficulty() != Difficulty.PEACEFUL) {
            FoodLevelChangeEvent event = EventFactory.callEvent(new FoodLevelChangeEvent(this, Math.max(food - 1, 0)));
            if (!event.isCancelled()) {
                food = event.getFoodLevel();
            }
            sendHealth();
        }
    }
    if (getHealth() < getMaxHealth() && !isDead()) {
        if (food > 18 && ticksLived % 80 == 0 || world.getDifficulty() == Difficulty.PEACEFUL) {
            EntityRegainHealthEvent event1 = new EntityRegainHealthEvent(this, 1f, RegainReason.SATIATED);
            EventFactory.callEvent(event1);
            if (!event1.isCancelled()) {
                setHealth(getHealth() + 1);
            }
            exhaustion = Math.min(exhaustion + 3.0f, 40.0f);
            saturation -= 3;
        }
    }
    if (food == 0 && getHealth() > 1 && ticksLived % 80 == 0) {
        damage(1, DamageCause.STARVATION);
    }
    // stream world
    streamBlocks();
    processBlockChanges();
    // add to playtime
    incrementStatistic(Statistic.PLAY_ONE_TICK);
    if (isSneaking()) {
        incrementStatistic(Statistic.SNEAK_TIME);
    }
    // update inventory
    for (InventoryMonitor.Entry entry : invMonitor.getChanges()) {
        sendItemChange(entry.slot, entry.item);
    }
    // send changed metadata
    List<MetadataMap.Entry> changes = metadata.getChanges();
    if (!changes.isEmpty()) {
        session.send(new EntityMetadataMessage(SELF_ID, changes));
    }
    // update or remove entities
    List<Integer> destroyIds = new LinkedList<>();
    for (Iterator<GlowEntity> it = knownEntities.iterator(); it.hasNext(); ) {
        GlowEntity entity = it.next();
        if (!isWithinDistance(entity) || entity.isRemoved()) {
            destroyIds.add(entity.getEntityId());
            it.remove();
        } else {
            entity.createUpdateMessage().forEach(session::send);
        }
    }
    if (!destroyIds.isEmpty()) {
        session.send(new DestroyEntitiesMessage(destroyIds));
    }
    // add entities
    knownChunks.parallelStream().forEach(key -> {
        GlowChunk chunk = world.getChunkAt(key.getX(), key.getZ());
        chunk.getRawEntities().stream().filter(entity -> this != entity).filter(this::isWithinDistance).filter(entity -> !entity.isDead()).filter(entity -> !knownEntities.contains(entity)).filter(entity -> !hiddenEntities.contains(entity.getUniqueId())).forEach((entity) -> {
            knownEntities.add(entity);
            entity.createSpawnMessage().forEach(session::send);
        });
    });
    if (passengerChanged) {
        session.send(new SetPassengerMessage(SELF_ID, getPassengers().stream().mapToInt(Entity::getEntityId).toArray()));
    }
    getAttributeManager().sendMessages(session);
}
Also used : Plugin(org.bukkit.plugin.Plugin) GlowBlock(net.glowstone.block.GlowBlock) StatusFlags(net.glowstone.entity.meta.MetadataIndex.StatusFlags) ItemTable(net.glowstone.block.ItemTable) GlowTeam(net.glowstone.scoreboard.GlowTeam) AttributeInstance(org.bukkit.attribute.AttributeInstance) Entry(net.glowstone.net.message.play.game.UserListItemMessage.Entry) BlockFace(org.bukkit.block.BlockFace) Player(org.bukkit.entity.Player) net.glowstone.net.message.play.entity(net.glowstone.net.message.play.entity) MaterialData(org.bukkit.material.MaterialData) Unpooled(io.netty.buffer.Unpooled) org.bukkit(org.bukkit) Conversation(org.bukkit.conversations.Conversation) org.bukkit.inventory(org.bukkit.inventory) Scoreboard(org.bukkit.scoreboard.Scoreboard) StatisticMap(net.glowstone.util.StatisticMap) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) Block(org.bukkit.block.Block) net.glowstone.net.message.play.game(net.glowstone.net.message.play.game) PlayerReader(net.glowstone.io.PlayerDataService.PlayerReader) SignEntity(net.glowstone.block.entity.SignEntity) GlowInventory(net.glowstone.inventory.GlowInventory) Position(net.glowstone.util.Position) DamageCause(org.bukkit.event.entity.EntityDamageEvent.DamageCause) org.bukkit.event.player(org.bukkit.event.player) Entity(org.bukkit.entity.Entity) ByteBufUtils(com.flowpowered.network.util.ByteBufUtils) GlowChunk(net.glowstone.chunk.GlowChunk) GlowEffect(net.glowstone.constants.GlowEffect) Property(org.bukkit.inventory.InventoryView.Property) Reason(net.glowstone.net.message.play.game.StateChangeMessage.Reason) ChatMessageType(net.md_5.bungee.api.ChatMessageType) DelegateDeserialization(org.bukkit.configuration.serialization.DelegateDeserialization) BlockVector(org.bukkit.util.BlockVector) EntityType(org.bukkit.entity.EntityType) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Villager(org.bukkit.entity.Villager) ComponentSerializer(net.md_5.bungee.chat.ComponentSerializer) MetadataIndex(net.glowstone.entity.meta.MetadataIndex) JSONObject(org.json.simple.JSONObject) Action(net.glowstone.net.message.play.game.TitleMessage.Action) UseBedMessage(net.glowstone.net.message.play.player.UseBedMessage) RegainReason(org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason) ChunkLock(net.glowstone.chunk.ChunkManager.ChunkLock) Key(net.glowstone.chunk.GlowChunk.Key) InventoryMonitor(net.glowstone.inventory.InventoryMonitor) GlowAchievement(net.glowstone.constants.GlowAchievement) CompoundTag(net.glowstone.util.nbt.CompoundTag) ConversationAbandonedEvent(org.bukkit.conversations.ConversationAbandonedEvent) Setter(lombok.Setter) BlockBed(net.glowstone.block.blocktype.BlockBed) java.util(java.util) Title(com.destroystokyo.paper.Title) GlowBlockEntity(net.glowstone.constants.GlowBlockEntity) Convert(net.glowstone.util.Convert) Getter(lombok.Getter) MetadataMap(net.glowstone.entity.meta.MetadataMap) Message(com.flowpowered.network.Message) net.glowstone(net.glowstone) Level(java.util.logging.Level) BaseComponent(net.md_5.bungee.api.chat.BaseComponent) Environment(org.bukkit.World.Environment) ByteBuf(io.netty.buffer.ByteBuf) net.glowstone.net.message.play.inv(net.glowstone.net.message.play.inv) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) GlowSession(net.glowstone.net.GlowSession) ClientSettings(net.glowstone.entity.meta.ClientSettings) GlowItem(net.glowstone.entity.objects.GlowItem) PlayerAbilitiesMessage(net.glowstone.net.message.play.player.PlayerAbilitiesMessage) MapView(org.bukkit.map.MapView) GlowScoreboard(net.glowstone.scoreboard.GlowScoreboard) TextMessage(net.glowstone.util.TextMessage) Type(org.bukkit.Effect.Type) ResourcePackSendMessage(net.glowstone.net.message.play.player.ResourcePackSendMessage) Attribute(org.bukkit.attribute.Attribute) StandardMessenger(org.bukkit.plugin.messaging.StandardMessenger) TeleportCause(org.bukkit.event.player.PlayerTeleportEvent.TeleportCause) ItemType(net.glowstone.block.itemtype.ItemType) EntityRegainHealthEvent(org.bukkit.event.entity.EntityRegainHealthEvent) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) IOException(java.io.IOException) GlowParticle(net.glowstone.constants.GlowParticle) Vector(org.bukkit.util.Vector) FoodLevelChangeEvent(org.bukkit.event.entity.FoodLevelChangeEvent) ItemFood(net.glowstone.block.itemtype.ItemFood) Preconditions(com.google.common.base.Preconditions) BlockEntity(net.glowstone.block.entity.BlockEntity) PlayerProfile(net.glowstone.entity.meta.profile.PlayerProfile) EntityRegainHealthEvent(org.bukkit.event.entity.EntityRegainHealthEvent) ItemType(net.glowstone.block.itemtype.ItemType) ItemFood(net.glowstone.block.itemtype.ItemFood) Entry(net.glowstone.net.message.play.game.UserListItemMessage.Entry) InventoryMonitor(net.glowstone.inventory.InventoryMonitor) FoodLevelChangeEvent(org.bukkit.event.entity.FoodLevelChangeEvent) GlowChunk(net.glowstone.chunk.GlowChunk)

Example 7 with Key

use of net.glowstone.chunk.GlowChunk.Key in project Glowstone by GlowstoneMC.

the class GlowWorld method setKeepSpawnInMemory.

@Override
public void setKeepSpawnInMemory(boolean keepLoaded) {
    keepSpawnLoaded = keepLoaded;
    if (spawnChunkLock != null) {
        // update the chunk lock as needed
        spawnChunkLock.clear();
        if (keepSpawnLoaded) {
            int centerX = spawnLocation.getBlockX() >> 4;
            int centerZ = spawnLocation.getBlockZ() >> 4;
            int radius = 4 * server.getViewDistance() / 3;
            long loadTime = System.currentTimeMillis();
            int total = ((radius << 1) + 1) * ((radius << 1) + 1), current = 0;
            for (int x = centerX - radius; x <= centerX + radius; ++x) {
                for (int z = centerZ - radius; z <= centerZ + radius; ++z) {
                    ++current;
                    if (populateAnchoredChunks) {
                        getChunkManager().forcePopulation(x, z);
                    } else {
                        loadChunk(x, z);
                    }
                    spawnChunkLock.acquire(new Key(x, z));
                    if (System.currentTimeMillis() >= loadTime + 1000) {
                        int progress = 100 * current / total;
                        GlowServer.logger.info("Preparing spawn for " + name + ": " + progress + "%");
                        loadTime = System.currentTimeMillis();
                    }
                }
            }
        } else {
            // attempt to immediately unload the spawn
            chunks.unloadOldChunks();
        }
    }
}
Also used : Key(net.glowstone.chunk.GlowChunk.Key)

Example 8 with Key

use of net.glowstone.chunk.GlowChunk.Key in project Glowstone by GlowstoneMC.

the class GlowWorld method updateBlocksInActiveChunks.

private void updateBlocksInActiveChunks() {
    for (Key key : activeChunksSet) {
        int cx = key.getX();
        int cz = key.getZ();
        // check the chunk is loaded
        if (isChunkLoaded(cx, cz)) {
            GlowChunk chunk = getChunkAt(cx, cz);
            // thunder
            maybeStrikeLightningInChunk(cx, cz);
            // block ticking
            // we will choose 3 blocks per chunk's section
            ChunkSection[] sections = chunk.getSections();
            for (int i = 0; i < sections.length; i++) {
                updateBlocksInSection(chunk, sections[i], i);
            }
        }
    }
}
Also used : ChunkSection(net.glowstone.chunk.ChunkSection) Key(net.glowstone.chunk.GlowChunk.Key) GlowChunk(net.glowstone.chunk.GlowChunk)

Example 9 with Key

use of net.glowstone.chunk.GlowChunk.Key in project Glowstone by GlowstoneMC.

the class BlockEntity method updateInRange.

/**
     * Update this BlockEntity's visible state to all players in range.
     */
public final void updateInRange() {
    Key key = new Key(block.getChunk().getX(), block.getChunk().getZ());
    block.getWorld().getRawPlayers().stream().filter(player -> player.canSeeChunk(key)).forEach(this::update);
}
Also used : CompoundTag(net.glowstone.util.nbt.CompoundTag) GlowBlock(net.glowstone.block.GlowBlock) Block(org.bukkit.block.Block) Key(net.glowstone.chunk.GlowChunk.Key) GlowPlayer(net.glowstone.entity.GlowPlayer) GlowBlockState(net.glowstone.block.GlowBlockState) Key(net.glowstone.chunk.GlowChunk.Key)

Example 10 with Key

use of net.glowstone.chunk.GlowChunk.Key in project Glowstone by GlowstoneMC.

the class NbtStructureDataService method readStructuresData.

@Override
public Map<Integer, GlowStructure> readStructuresData() {
    Map<Integer, GlowStructure> structures = new HashMap<>();
    for (StructureStore<?> store : StructureStorage.getStructureStores()) {
        File structureFile = new File(structureDir, store.getId() + ".dat");
        if (structureFile.exists()) {
            try (NBTInputStream in = new NBTInputStream(new FileInputStream(structureFile))) {
                CompoundTag data = new CompoundTag();
                data = in.readCompound();
                if (data.isCompound("data")) {
                    data = data.getCompound("data");
                    if (data.isCompound("Features")) {
                        CompoundTag features = data.getCompound("Features");
                        features.getValue().keySet().stream().filter(features::isCompound).forEach(key -> {
                            GlowStructure structure = StructureStorage.loadStructure(world, features.getCompound(key));
                            structures.put(new Key(structure.getChunkX(), structure.getChunkZ()).hashCode(), structure);
                        });
                    }
                } else {
                    server.getLogger().log(Level.SEVERE, "No data tag in " + structureFile);
                }
            } catch (IOException e) {
                server.getLogger().log(Level.SEVERE, "Failed to read structure data from " + structureFile, e);
            }
        }
    }
    return structures;
}
Also used : GlowStructure(net.glowstone.generator.structures.GlowStructure) HashMap(java.util.HashMap) NBTInputStream(net.glowstone.util.nbt.NBTInputStream) IOException(java.io.IOException) File(java.io.File) FileInputStream(java.io.FileInputStream) CompoundTag(net.glowstone.util.nbt.CompoundTag) Key(net.glowstone.chunk.GlowChunk.Key)

Aggregations

Key (net.glowstone.chunk.GlowChunk.Key)15 GlowBlock (net.glowstone.block.GlowBlock)4 GlowChunk (net.glowstone.chunk.GlowChunk)4 Message (com.flowpowered.network.Message)3 Preconditions.checkNotNull (com.google.common.base.Preconditions.checkNotNull)3 IOException (java.io.IOException)3 BlockEntity (net.glowstone.block.entity.BlockEntity)3 GlowBlockEntity (net.glowstone.constants.GlowBlockEntity)3 MetadataMap (net.glowstone.entity.meta.MetadataMap)3 CompoundTag (net.glowstone.util.nbt.CompoundTag)3 Title (com.destroystokyo.paper.Title)2 ByteBufUtils (com.flowpowered.network.util.ByteBufUtils)2 Preconditions (com.google.common.base.Preconditions)2 Preconditions.checkArgument (com.google.common.base.Preconditions.checkArgument)2 ByteBuf (io.netty.buffer.ByteBuf)2 Unpooled (io.netty.buffer.Unpooled)2 InetSocketAddress (java.net.InetSocketAddress)2 StandardCharsets (java.nio.charset.StandardCharsets)2 java.util (java.util)2 ThreadLocalRandom (java.util.concurrent.ThreadLocalRandom)2