public override WorldInteraction[] GetPlacedBlockInteractionHelp(IWorldAccessor world, BlockSelection selection, IPlayer forPlayer) { return(new WorldInteraction[] { new WorldInteraction() { ActionLangCode = "blockhelp-firewoodpile-addlog", MouseButton = EnumMouseButton.Right, HotKeyCode = "sneak", Itemstacks = new ItemStack[] { new ItemStack(world.GetItem(new AssetLocation("firewood")), 2) } }, new WorldInteraction() { ActionLangCode = "blockhelp-firewoodpile-removelog", MouseButton = EnumMouseButton.Right, HotKeyCode = null }, new WorldInteraction() { ActionLangCode = "blockhelp-firewoodpile-8addlog", MouseButton = EnumMouseButton.Right, HotKeyCodes = new string[] { "sprint", "sneak" }, Itemstacks = new ItemStack[] { new ItemStack(world.GetItem(new AssetLocation("firewood")), 8) } }, new WorldInteraction() { ActionLangCode = "blockhelp-firewoodpile-8removelog", HotKeyCode = "sprint", MouseButton = EnumMouseButton.Right } }.Append(base.GetPlacedBlockInteractionHelp(world, selection, forPlayer))); }
public override void OnBlockBroken(IWorldAccessor world, BlockPos pos, IPlayer byPlayer, float dropQuantityMultiplier = 1f) { if (world.Side == EnumAppSide.Server && (byPlayer == null || byPlayer.WorldData.CurrentGameMode != EnumGameMode.Creative)) { ItemStack drop = null; if (Variant["state"] == "normal") { drop = new ItemStack(world.GetItem(new AssetLocation("reeds")), 10); } else { drop = new ItemStack(world.GetItem(new AssetLocation("giantreedsroot"))); } if (drop != null) { world.SpawnItemEntity(drop, new Vec3d(pos.X + 0.5, pos.Y + 0.5, pos.Z + 0.5), null); } } if (byPlayer != null && Variant["state"] == "normal" && byPlayer.InventoryManager.ActiveTool == EnumTool.Knife) { world.BlockAccessor.SetBlock(world.GetBlock(CodeWithParts("harvested")).BlockId, pos); return; } if (Variant["habitat"] != "free") { world.BlockAccessor.SetBlock(world.GetBlock(new AssetLocation("water-still-7")).BlockId, pos); } else { world.BlockAccessor.SetBlock(0, pos); } }
/// <summary> /// Add the specific parts of this Pulverizer, to the block drops (the caps will drop anyhow as they are in inventory) /// </summary> public ItemStack[] getDrops(IWorldAccessor world, ItemStack pulvFrame) { int pounders = 0; if (hasLPounder) { pounders++; } if (hasRPounder) { pounders++; } ItemStack[] result = new ItemStack[pounders + (hasAxle ? 2 : 1)]; int index = 0; result[index++] = pulvFrame; for (int i = 0; i < pounders; i++) { result[index++] = new ItemStack(world.GetItem(pounderName)); } if (hasAxle) { result[index] = new ItemStack(world.GetItem(toggleName)); } return(result); }
public override WorldInteraction[] GetPlacedBlockInteractionHelp(IWorldAccessor world, BlockSelection selection, IPlayer forPlayer) { if (!Repaired) { return(new WorldInteraction[] { new WorldInteraction() { ActionLangCode = "blockhelp-translocator-repair-1", Itemstacks = new ItemStack[] { new ItemStack(world.GetBlock(new AssetLocation("metal-parts")), 2) }, MouseButton = EnumMouseButton.Right } }); } else { BlockEntityStaticTranslocator be = world.BlockAccessor.GetBlockEntity(selection.Position) as BlockEntityStaticTranslocator; if (be == null) { return(base.GetPlacedBlockInteractionHelp(world, selection, forPlayer)); } if (!be.FullyRepaired) { return(new WorldInteraction[] { new WorldInteraction() { ActionLangCode = "blockhelp-translocator-repair-2", Itemstacks = new ItemStack[] { new ItemStack(world.GetItem(new AssetLocation("gear-temporal"))) }, MouseButton = EnumMouseButton.Right } }); } if (!be.Activated) { return(new WorldInteraction[] { new WorldInteraction() { ActionLangCode = "blockhelp-translocator-activate", Itemstacks = new ItemStack[] { new ItemStack(world.GetItem(new AssetLocation("gear-rusty"))) }, MouseButton = EnumMouseButton.Right } }); } } return(base.GetPlacedBlockInteractionHelp(world, selection, forPlayer)); }
internal void Resolve(IWorldAccessor world) { if (Type == EnumItemClass.Block) { Block block = world.GetBlock(new AssetLocation(Code)); if (block == null) { world.Logger.Error("Cannot resolve stack randomizer block with code {0}, wrong code?", Code); return; } ResolvedStack = new ItemStack(block); if (Attributes != null) { ResolvedStack.Attributes = Attributes.ToAttribute() as ITreeAttribute; } } else { Item item = world.GetItem(new AssetLocation(Code)); if (item == null) { world.Logger.Error("Cannot resolve stack randomizer item with code {0}, wrong code?", Code); return; } ResolvedStack = new ItemStack(item); if (Attributes != null) { ResolvedStack.Attributes = Attributes.ToAttribute() as ITreeAttribute; } } }
public ItemStack GetItemStack(IWorldAccessor world, int variant) { ItemStack stack = null; AssetLocation code = codes[variant % codes.Length]; int quantity = (int)minQuantity + (int)(world.Rand.NextDouble() * (maxQuantity - (int)minQuantity)); if (type == EnumItemClass.Block) { Block block = world.GetBlock(code); if (block != null) { stack = new ItemStack(block, quantity); } else { world.Logger.Warning("BlockLootVessel: Failed resolving block code {0}", code); } } else { Item item = world.GetItem(code); if (item != null) { stack = new ItemStack(item, quantity); } else { world.Logger.Warning("BlockLootVessel: Failed resolving item code {0}", code); } } return(stack); }
/// <summary> /// Sets itemstack.block or itemstack.item /// </summary> /// <param name="resolver"></param> /// <param name="sourceForErrorLogging"></param> /// <returns></returns> public bool Resolve(IWorldAccessor resolver, string sourceForErrorLogging) { if (Type == EnumItemClass.Block) { Block block = resolver.GetBlock(Code); if (block == null) { resolver.Logger.Warning("Failed resolving a blocks block drop or smeltedstack with code {0} in {1}", Code, sourceForErrorLogging); return(false); } ResolvedItemstack = new ItemStack(block); } else { Item item = resolver.GetItem(Code); if (item == null) { resolver.Logger.Warning("Failed resolving a blocks item drop or smeltedstack with code {0} in {1}", Code, sourceForErrorLogging); return(false); } ResolvedItemstack = new ItemStack(item); } if (Attributes != null) { IAttribute attributes = Attributes.ToAttribute(); if (attributes is ITreeAttribute) { ResolvedItemstack.Attributes = (ITreeAttribute)attributes; } } return(true); }
public override WorldInteraction[] GetPlacedBlockInteractionHelp(IWorldAccessor world, BlockSelection selection, IPlayer forPlayer) { if (LastCodePart() == "broken") { return(new WorldInteraction[] { new WorldInteraction() { ActionLangCode = "blockhelp-translocator-repair-2", Itemstacks = new ItemStack[] { new ItemStack(world.GetItem(new AssetLocation("gear-temporal")), 1) }, MouseButton = EnumMouseButton.Right } }); } if (LastCodePart() == "normal") { return(new WorldInteraction[] { new WorldInteraction() { ActionLangCode = ConstantsCore.ModId + ":blockhelp-teleport-rename", MouseButton = EnumMouseButton.Right, HotKeyCode = "sneak" } }); } return(base.GetPlacedBlockInteractionHelp(world, selection, forPlayer)); }
public bool RemoveResource(IWorldAccessor world, IPlayer byplayer, BlockSelection blockSel, string stype, int quant) { if (storedType == "" || storedtypes[stype] <= 0) { return(false); } if (quant > storedtypes[stype]) { quant = storedtypes[stype]; } ItemStack givestack; if (stype == "sand" || stype == "gravel") { Block filler = world.GetBlock(new AssetLocation("game", stype + "-" + storedType)); givestack = new ItemStack(filler, Math.Min(filler.MaxStackSize, quant)); } else { Item filler = world.GetItem(new AssetLocation("game", stype + "-" + storedType)); givestack = new ItemStack(filler, Math.Min(filler.MaxStackSize, quant)); } if (!byplayer.InventoryManager.TryGiveItemstack(givestack.Clone())) { world.SpawnItemEntity(givestack.Clone(), blockSel.HitPosition + (blockSel.HitPosition.Normalize() * .5) + blockSel.Position.ToVec3d(), blockSel.HitPosition.Normalize() * .05); } storedtypes[stype] -= givestack.StackSize; return(true); }
public override void OnBlockBroken(IWorldAccessor world, BlockPos pos, IPlayer byPlayer, float dropQuantityMultiplier = 1f) { if (world.Side == EnumAppSide.Server && (byPlayer == null || byPlayer.WorldData.CurrentGameMode != EnumGameMode.Creative)) { ItemStack drop = null; if (Variant["state"] == "normal") { drop = new ItemStack(world.GetItem(new AssetLocation("cattailtops"))); } else { if (Variant["type"] == "coopersreed") { drop = new ItemStack(world.GetItem(new AssetLocation("cattailroot"))); } if (Variant["type"] == "papyrus") { drop = new ItemStack(world.GetItem(new AssetLocation("papyrusroot"))); } } if (drop != null) { world.SpawnItemEntity(drop, new Vec3d(pos.X + 0.5, pos.Y + 0.5, pos.Z + 0.5), null); } world.PlaySoundAt(Sounds.GetBreakSound(byPlayer), pos.X, pos.Y, pos.Z, byPlayer); } if (byPlayer != null && Variant["state"] == "normal" && (byPlayer.InventoryManager.ActiveTool == EnumTool.Knife || byPlayer.InventoryManager.ActiveTool == EnumTool.Sickle || byPlayer.InventoryManager.ActiveTool == EnumTool.Scythe)) { world.BlockAccessor.SetBlock(world.GetBlock(this.habitat == EnumReedsHabitat.Ice ? CodeWithVariants(new string[] { "habitat", "state" }, new string[] { "water", "harvested" }) : CodeWithVariant("state", "harvested")).BlockId, pos); return; } if (habitat != 0) { world.BlockAccessor.SetBlock(world.GetBlock(new AssetLocation("water-still-7")).BlockId, pos); world.BlockAccessor.GetBlock(pos).OnNeighbourBlockChange(world, pos, pos); } else { world.BlockAccessor.SetBlock(0, pos); } }
/// <summary> /// Create a new itemstack from a byte serialized stream (with resolving the block/item) /// </summary> /// <param name="reader"></param> /// <param name="resolver"></param> public ItemStack(BinaryReader reader, IWorldAccessor resolver) { FromBytes(reader); if (Class == EnumItemClass.Block) { block = resolver.GetBlock((ushort)this.Id); } else { item = resolver.GetItem(Id); } }
public override void OnHeldInteractStop(float secondsUsed, ItemSlot slot, EntityAgent byEntity, BlockSelection blockSel, EntitySelection entitySel) { if (blockSel == null) { return; } if (secondsUsed < 1.9f) { return; } IWorldAccessor world = byEntity.World; Block block = byEntity.World.BlockAccessor.GetBlock(blockSel.Position); if (!CanSqueezeInto(block)) { return; } BlockBucket blockbucket = block as BlockBucket; if (blockbucket != null) { if (blockbucket.TryPutContent(world, blockSel.Position, new ItemStack(world.GetItem(new AssetLocation("honeyportion"))), 1) == 0) { return; } } else { AssetLocation loc = new AssetLocation(block.Attributes["contentItem2BlockCodes"]["honeyportion"].AsString()); world.BlockAccessor.SetBlock(world.GetBlock(loc).BlockId, blockSel.Position); } slot.TakeOut(1); slot.MarkDirty(); IPlayer byPlayer = null; if (byEntity is EntityPlayer) { byPlayer = world.PlayerByUid(((EntityPlayer)byEntity).PlayerUID); } ItemStack stack = new ItemStack(world.GetItem(new AssetLocation("beeswax"))); if (byPlayer?.InventoryManager.TryGiveItemstack(stack) == false) { byEntity.World.SpawnItemEntity(stack, byEntity.SidedPos.XYZ); } }
public override void OnBlockBroken(IWorldAccessor world, BlockPos pos, IPlayer byPlayer, float dropQuantityMultiplier = 1f) { if (world.Side == EnumAppSide.Server && (byPlayer == null || byPlayer.WorldData.CurrentGameMode != EnumGameMode.Creative)) { ItemStack drop = null; if (LastCodePart() == "normal") { drop = new ItemStack(world.GetItem(new AssetLocation("cattailtops"))); } else { drop = new ItemStack(world.GetItem(new AssetLocation("cattailroot"))); } if (drop != null) { world.SpawnItemEntity(drop, new Vec3d(pos.X + 0.5, pos.Y + 0.5, pos.Z + 0.5), null); } world.PlaySoundAt(Sounds.GetBreakSound(byPlayer), pos.X, pos.Y, pos.Z, byPlayer); } if (byPlayer != null && LastCodePart() == "normal" && byPlayer.InventoryManager.ActiveTool == EnumTool.Knife) { world.BlockAccessor.SetBlock(world.GetBlock(CodeWithParts("harvested")).BlockId, pos); return; } if (LastCodePart(1) != "free") { world.BlockAccessor.SetBlock(world.GetBlock(new AssetLocation("water-still-7")).BlockId, pos); world.BlockAccessor.GetBlock(pos).OnNeighourBlockChange(world, pos, pos); } else { world.BlockAccessor.SetBlock(0, pos); } }
public static ItemStack GetItemStack(this IWorldAccessor worldAccessor, string itemType, string itemCode, int amount) { switch (itemType) { case "block": return(new ItemStack(worldAccessor.GetBlock(new AssetLocation(itemCode)), amount)); case "item": return(new ItemStack(worldAccessor.GetItem(new AssetLocation(itemCode)), amount)); default: // TODO: null or empty itemstack? return(new ItemStack()); } }
/// <summary> /// Create a new itemstack with given collectible id, itemclass, stacksize, attributes and a resolver to turn the collectibe + itemclass into an Item/Block /// </summary> /// <param name="id"></param> /// <param name="itemClass"></param> /// <param name="stacksize"></param> /// <param name="stackAttributes"></param> /// <param name="resolver"></param> public ItemStack(int id, EnumItemClass itemClass, int stacksize, TreeAttribute stackAttributes, IWorldAccessor resolver) { this.Id = id; this.Class = itemClass; this.stacksize = stacksize; this.stackAttributes = stackAttributes; if (Class == EnumItemClass.Block) { block = resolver.GetBlock((ushort)this.Id); } else { item = resolver.GetItem(Id); } }
public override WorldInteraction[] GetPlacedBlockInteractionHelp(IWorldAccessor world, BlockSelection selection, IPlayer forPlayer) { if (CandleCount == 8) { return(null); } return(new WorldInteraction[] { new WorldInteraction() { ActionLangCode = "blockhelp-chandelier-addcandle", MouseButton = EnumMouseButton.Right, Itemstacks = new ItemStack[] { new ItemStack(world.GetItem(new AssetLocation("candle"))) } } }.Append(base.GetPlacedBlockInteractionHelp(world, selection, forPlayer))); }
/// <summary> /// Turns Type, Code and Attributes into an IItemStack /// </summary> /// <param name="resolver"></param> public bool Resolve(IWorldAccessor resolver, string sourceForErrorLogging) { if (ReturnedStack != null) { ReturnedStack.Resolve(resolver, sourceForErrorLogging + " recipe with output " + Code); } if (Code.Path.Contains("*")) { IsWildCard = true; return(true); } if (Type == EnumItemClass.Block) { Block block = resolver.GetBlock(Code); if (block == null || block.IsMissing) { resolver.Logger.Warning("Failed resolving crafting recipe ingredient with code {0} in {1}", Code, sourceForErrorLogging); return(false); } ResolvedItemstack = new ItemStack(block, Quantity); } else { Item item = resolver.GetItem(Code); if (item == null || item.IsMissing) { resolver.Logger.Warning("Failed resolving crafting recipe ingredient with code {0} in {1}", Code, sourceForErrorLogging); return(false); } ResolvedItemstack = new ItemStack(item, Quantity); } if (Attributes != null) { IAttribute attributes = Attributes.ToAttribute(); if (attributes is ITreeAttribute) { ResolvedItemstack.Attributes = (ITreeAttribute)attributes; } } return(true); }
public override void OnHeldInteractStop(float secondsUsed, IItemSlot slot, IEntityAgent byEntity, BlockSelection blockSel, EntitySelection entitySel) { if (blockSel == null) { return; } if (secondsUsed < 1.9f) { return; } IWorldAccessor world = byEntity.World; Block block = byEntity.World.BlockAccessor.GetBlock(blockSel.Position); if (!CanSqueezeInto(block)) { return; } BlockBucket blockbucket = block as BlockBucket; if (blockbucket != null) { if (blockbucket.TryAddContent(world, blockSel.Position, new ItemStack(world.GetItem(new AssetLocation("honeyportion"))), 1) == 0) { return; } } else { world.BlockAccessor.SetBlock(world.GetBlock(new AssetLocation("bowl-honey")).BlockId, blockSel.Position); } slot.TakeOut(1); slot.MarkDirty(); IPlayer byPlayer = null; if (byEntity is IEntityPlayer) { byPlayer = world.PlayerByUid(((IEntityPlayer)byEntity).PlayerUID); } byPlayer?.InventoryManager.TryGiveItemstack(new ItemStack(world.GetItem(new AssetLocation("beeswax")))); }
/// <summary> /// Sets the item/block based on the currently set itemclass + id /// </summary> /// <param name="resolver"></param> /// <returns></returns> public bool ResolveBlockOrItem(IWorldAccessor resolver) { if (Class == EnumItemClass.Block) { block = resolver.GetBlock((ushort)Id); if (block == null) { return(false); } } else { item = resolver.GetItem(Id); if (item == null) { return(false); } } return(true); }
public override WorldInteraction[] GetPlacedBlockInteractionHelp(IWorldAccessor world, BlockSelection selection, IPlayer forPlayer) { BEBehaviorWindmillRotor be = world.BlockAccessor.GetBlockEntity(selection.Position)?.GetBehavior <BEBehaviorWindmillRotor>(); if (be != null && be.SailLength >= 3) { return(new WorldInteraction[0]); } return(new WorldInteraction[] { new WorldInteraction() { ActionLangCode = "heldhelp-addsails", MouseButton = EnumMouseButton.Right, Itemstacks = new ItemStack[] { new ItemStack(world.GetItem(new AssetLocation("sail")), 4) } } }); }
public override bool OnBlockInteractStart(IWorldAccessor world, IPlayer byPlayer, BlockSelection blockSel, ref EnumHandling handling) { ClothSystem cs = cm.GetClothSystemAttachedToBlock(blockSel.Position); if (cs != null) { Entity byEntity = byPlayer.Entity; ItemSlot slot = byPlayer.InventoryManager.ActiveHotbarSlot; Vec3d lpos = new Vec3d(0, byEntity.LocalEyePos.Y - 0.25f, 0); Vec3d aheadPos = lpos.AheadCopy(0.25f, byEntity.SidedPos.Pitch, byEntity.SidedPos.Yaw); // Already handled by ItemRope if (!slot.Empty && slot.Itemstack.Collectible.Code.Path == "rope" && (cs.FirstPoint.PinnedToEntity?.EntityId == byPlayer.Entity.EntityId || cs.LastPoint.PinnedToEntity?.EntityId == byPlayer.Entity.EntityId)) { return(base.OnBlockInteractStart(world, byPlayer, blockSel, ref handling)); } ClothPoint targetPoint = cs.FirstPoint.PinnedToBlockPos == blockSel.Position ? cs.FirstPoint : cs.LastPoint; ItemStack stack = new ItemStack(world.GetItem(new AssetLocation("rope"))); stack.Attributes.SetInt("clothId", cs.ClothId); stack.Attributes.SetLong("ropeHeldByEntityId", byEntity.EntityId); if (byPlayer.InventoryManager.TryGiveItemstack(stack, true)) { targetPoint.PinTo(byPlayer.Entity, aheadPos.ToVec3f()); } else { Entity ei = world.SpawnItemEntity(stack, blockSel.Position.ToVec3d().Add(0.5, 0.5, 0.5)); targetPoint.PinTo(ei, new Vec3f(0, 0.1f, 0)); } handling = EnumHandling.PreventDefault; return(true); } return(base.OnBlockInteractStart(world, byPlayer, blockSel, ref handling)); }
/// <summary> /// This method should always be called when an itemstack got loaded from the savegame or when it got imported. /// When this method return false, you should discard the itemstack because it could not get resolved and a warning will be logged. /// </summary> /// <param name="oldBlockMapping"></param> /// <param name="oldItemMapping"></param> /// <param name="worldForNewMapping"></param> public bool FixMapping(Dictionary <int, AssetLocation> oldBlockMapping, Dictionary <int, AssetLocation> oldItemMapping, IWorldAccessor worldForNewMapping) { AssetLocation code; if (Class == EnumItemClass.Item) { if (oldItemMapping.TryGetValue(Id, out code)) { item = worldForNewMapping.GetItem(code); if (item == null) { worldForNewMapping.Logger.Warning("Cannot fix itemstack mapping, item code {0} not found item registry. Will delete stack.", code); return(false); } Id = item.Id; return(true); } } else { if (oldBlockMapping.TryGetValue(Id, out code)) { block = worldForNewMapping.GetBlock(code); if (block == null) { worldForNewMapping.Logger.Warning("Cannot fix itemstack mapping, block code {0} not found block registry. Will delete stack.", code); return(false); } Id = block.Id; return(true); } } worldForNewMapping.Logger.Warning("Cannot fix itemstack mapping, item/block id {0} not found in old mapping list. Will delete stack. ({1})", Id, this.Collectible); return(false); }
public virtual ItemStack CreateItemStackFromJson(ITreeAttribute stackAttr, IWorldAccessor world, string domain) { CollectibleObject collObj; var loc = AssetLocation.Create(stackAttr.GetString("code"), domain); if (stackAttr.GetString("type") == "item") { collObj = world.GetItem(loc); } else { collObj = world.GetBlock(loc); } ItemStack stack = new ItemStack(collObj, stackAttr.GetInt("quantity")); var attr = (stackAttr["attributes"] as TreeAttribute)?.Clone(); if (attr != null) { stack.Attributes = attr; } return(stack); }
public override ItemStack[] GetDrops(IWorldAccessor world, BlockPos pos, IPlayer byPlayer, float dropQuantityMultiplier = 1) { ItemStack[] stacks = base.GetDrops(world, pos, byPlayer, dropQuantityMultiplier); var be = api.World.BlockAccessor.GetBlockEntity(pos) as BlockEntityFruitTreeBranch; bool alive = be != null && be.FoliageState != EnumFoliageState.Dead; for (int i = 0; i < stacks.Length; i++) { var stack = stacks[i]; if (stack.Collectible is BlockFruitTreeBranch) { stack.Attributes.SetString("type", be?.TreeType); } if (stack.Collectible.Variant["type"] == "cutting" && !alive) { stacks[i] = new ItemStack(world.GetItem(new AssetLocation("firewood")), 2); } } return(stacks); }
protected override void ActivateSlotLeftClick(ItemSlot sourceSlot, ref ItemStackMoveOperation op) { if (sourceSlot.Empty) { base.ActivateSlotLeftClick(sourceSlot, ref op); return; } IWorldAccessor world = inventory.Api.World; if (sourceSlot.Itemstack.Collectible is ILiquidSource) { ItemSlot liquidSlot = inventory[1]; ILiquidSource source = sourceSlot.Itemstack.Collectible as ILiquidSource; ItemStack bucketContents = source.GetContent(world, sourceSlot.Itemstack); bool stackable = !liquidSlot.Empty && liquidSlot.Itemstack.Equals(world, bucketContents, GlobalConstants.IgnoredStackAttributes); if ((liquidSlot.Empty || stackable) && bucketContents != null) { ItemStack bucketStack = sourceSlot.Itemstack; ItemStack takenContent = source.TryTakeContent(world, bucketStack, 1); sourceSlot.Itemstack = bucketStack; takenContent.StackSize += liquidSlot.StackSize; liquidSlot.Itemstack = takenContent; liquidSlot.MarkDirty(); op.MovedQuantity = 1; return; } return; } string contentItemCode = sourceSlot.Itemstack?.ItemAttributes?["contentItemCode"].AsString(); if (contentItemCode != null) { ItemSlot liquidSlot = inventory[1]; ItemStack contentStack = new ItemStack(world.GetItem(new AssetLocation(contentItemCode))); bool stackable = !liquidSlot.Empty && liquidSlot.Itemstack.Equals(world, contentStack, GlobalConstants.IgnoredStackAttributes); if ((liquidSlot.Empty || stackable) && contentStack != null) { if (stackable) { liquidSlot.Itemstack.StackSize++; } else { liquidSlot.Itemstack = contentStack; } liquidSlot.MarkDirty(); ItemStack bowlStack = new ItemStack(world.GetBlock(new AssetLocation(sourceSlot.Itemstack.ItemAttributes["emptiedBlockCode"].AsString()))); if (sourceSlot.StackSize == 1) { sourceSlot.Itemstack = bowlStack; } else { sourceSlot.Itemstack.StackSize--; if (!op.ActingPlayer.InventoryManager.TryGiveItemstack(bowlStack)) { world.SpawnItemEntity(bowlStack, op.ActingPlayer.Entity.Pos.XYZ); } } sourceSlot.MarkDirty(); } return; } base.ActivateSlotLeftClick(sourceSlot, ref op); }
public override void OnHeldInteractStop(float secondsUsed, ItemSlot slot, EntityAgent byEntity, BlockSelection blockSel, EntitySelection entitySel) { if (blockSel == null) { return; } if (secondsUsed < 1.9f) { return; } IWorldAccessor world = byEntity.World; Block block = byEntity.World.BlockAccessor.GetBlock(blockSel.Position); if (!CanSqueezeInto(block, blockSel.Position)) { return; } ItemStack honeyStack = new ItemStack(world.GetItem(new AssetLocation("honeyportion")), 99999); BlockLiquidContainerTopOpened blockCnt = block as BlockLiquidContainerTopOpened; if (blockCnt != null) { if (blockCnt.TryPutLiquid(blockSel.Position, honeyStack, ContainedHoneyLitres) == 0) { return; } } else { var beg = api.World.BlockAccessor.GetBlockEntity(blockSel.Position) as BlockEntityGroundStorage; if (beg != null) { ItemSlot squeezeIntoSlot = beg.Inventory.FirstOrDefault(gslot => gslot.Itemstack?.Block != null && CanSqueezeInto(gslot.Itemstack.Block, null)); if (squeezeIntoSlot != null) { blockCnt = squeezeIntoSlot.Itemstack.Block as BlockLiquidContainerTopOpened; blockCnt.TryPutLiquid(squeezeIntoSlot.Itemstack, honeyStack, ContainedHoneyLitres); beg.MarkDirty(true); } } } slot.TakeOut(1); slot.MarkDirty(); IPlayer byPlayer = null; if (byEntity is EntityPlayer) { byPlayer = world.PlayerByUid(((EntityPlayer)byEntity).PlayerUID); } ItemStack stack = new ItemStack(world.GetItem(new AssetLocation("beeswax"))); if (byPlayer?.InventoryManager.TryGiveItemstack(stack) == false) { byEntity.World.SpawnItemEntity(stack, byEntity.SidedPos.XYZ); } }
public IAttribute ToAttribute(IWorldAccessor resolver) { if (type == EnumAttributeType.Unknown) { if (elems != null) { type = EnumAttributeType.Tree; } else if (values != null) { type = EnumAttributeType.StringArray; } else { type = EnumAttributeType.String; } } switch (type) { case EnumAttributeType.Bool: { return(new BoolAttribute(value == "true")); } case EnumAttributeType.Int: { int val = 0; int.TryParse(value, out val); return(new IntAttribute(val)); } case EnumAttributeType.Double: { double val = 0; double.TryParse(value, out val); return(new DoubleAttribute(val)); } case EnumAttributeType.Float: { float val = 0; float.TryParse(value, NumberStyles.Any, GlobalConstants.DefaultCultureInfo, out val); return(new FloatAttribute(val)); } case EnumAttributeType.String: return(new StringAttribute(value)); case EnumAttributeType.StringArray: return(new StringArrayAttribute(values)); case EnumAttributeType.Tree: ITreeAttribute tree = new TreeAttribute(); if (elems == null) { return(tree); } foreach (var val in elems) { IAttribute attribute = val.Value.ToAttribute(resolver); if (attribute == null) { continue; } tree[val.Key] = attribute; } return(tree); case EnumAttributeType.Itemstack: if (elems == null) { return(null); } bool haveClass = elems.ContainsKey("class") && elems["class"].type == EnumAttributeType.String; bool haveItemCode = elems.ContainsKey("code") && elems["code"].type == EnumAttributeType.String; bool haveStackSize = elems.ContainsKey("quantity") && elems["quantity"].type == EnumAttributeType.Int; if (!haveClass || !haveItemCode || !haveStackSize) { return(null); } EnumItemClass itemclass; try { itemclass = (EnumItemClass)Enum.Parse(typeof(EnumItemClass), elems["class"].value); } catch (Exception) { return(null); } int quantity = 0; if (!int.TryParse(elems["quantity"].value, out quantity)) { return(null); } ItemStack itemstack; if (itemclass == EnumItemClass.Block) { Block block = resolver.GetBlock(new AssetLocation(elems["code"].value)); if (block == null) { return(null); } itemstack = new ItemStack(block, quantity); } else { Item item = resolver.GetItem(new AssetLocation(elems["code"].value)); if (item == null) { return(null); } itemstack = new ItemStack(item, quantity); } if (elems.ContainsKey("attributes")) { IAttribute attributes = elems["attributes"].ToAttribute(resolver); if (attributes is ITreeAttribute) { itemstack.Attributes = (ITreeAttribute)attributes; } } return(new ItemstackAttribute(itemstack)); } return(null); }
protected override void ActivateSlotLeftClick(ItemSlot sourceSlot, ref ItemStackMoveOperation op) { IWorldAccessor world = inventory.Api.World; BlockBucket bucketblock = sourceSlot.Itemstack?.Block as BlockBucket; if (bucketblock != null) { ItemStack bucketContents = bucketblock.GetContent(world, sourceSlot.Itemstack); bool stackable = !Empty && itemstack.Equals(world, bucketContents, GlobalConstants.IgnoredStackAttributes); if ((Empty || stackable) && bucketContents != null) { ItemStack bucketStack = sourceSlot.Itemstack; ItemStack takenContent = bucketblock.TryTakeContent(world, bucketStack, op.ActingPlayer?.Entity?.Controls.Sneak == true ? 10 : 1); sourceSlot.Itemstack = bucketStack; takenContent.StackSize += StackSize; this.itemstack = takenContent; MarkDirty(); return; } return; } string contentItemCode = sourceSlot.Itemstack?.ItemAttributes?["contentItemCode"].AsString(); if (contentItemCode != null) { ItemStack contentStack = new ItemStack(world.GetItem(AssetLocation.Create(contentItemCode, sourceSlot.Itemstack.Collectible.Code.Domain))); bool stackable = !Empty && itemstack.Equals(world, contentStack, GlobalConstants.IgnoredStackAttributes); if ((Empty || stackable) && contentStack != null) { if (stackable) { this.itemstack.StackSize++; } else { this.itemstack = contentStack; } MarkDirty(); ItemStack bowlStack = new ItemStack(world.GetBlock(AssetLocation.Create(sourceSlot.Itemstack.ItemAttributes["emptiedBlockCode"].AsString(), sourceSlot.Itemstack.Collectible.Code.Domain))); if (sourceSlot.StackSize == 1) { sourceSlot.Itemstack = bowlStack; } else { sourceSlot.Itemstack.StackSize--; if (!op.ActingPlayer.InventoryManager.TryGiveItemstack(bowlStack)) { world.SpawnItemEntity(bowlStack, op.ActingPlayer.Entity.Pos.XYZ); } } sourceSlot.MarkDirty(); } return; } if (sourceSlot.Itemstack?.ItemAttributes?["contentItem2BlockCodes"].Exists == true) { return; } base.ActivateSlotLeftClick(sourceSlot, ref op); }
protected override void ActivateSlotLeftClick(ItemSlot sourceSlot, ref ItemStackMoveOperation op) { if (sourceSlot.Empty) { base.ActivateSlotLeftClick(sourceSlot, ref op); return; } IWorldAccessor world = inventory.Api.World; if (sourceSlot.Itemstack.Collectible is ILiquidSource source && source.AllowHeldLiquidTransfer) { ItemSlotLiquidOnly liquidSlot = inventory[1] as ItemSlotLiquidOnly; ItemStack bucketContents = source.GetContent(sourceSlot.Itemstack); bool stackable = !liquidSlot.Empty && liquidSlot.Itemstack.Equals(world, bucketContents, GlobalConstants.IgnoredStackAttributes); if ((liquidSlot.Empty || stackable) && bucketContents != null) { ItemStack bucketStack = sourceSlot.Itemstack; var lprops = BlockLiquidContainerBase.GetContainableProps(bucketContents); float toMoveLitres = op.CtrlDown ? source.TransferSizeLitres : source.CapacityLitres; float curSourceLitres = bucketContents.StackSize / lprops.ItemsPerLitre * bucketStack.StackSize; float curDestLitres = liquidSlot.StackSize / lprops.ItemsPerLitre; // Cap by source amount toMoveLitres = Math.Min(toMoveLitres, curSourceLitres); // Cap by target capacity toMoveLitres = Math.Min(toMoveLitres, liquidSlot.CapacityLitres - curDestLitres); if (toMoveLitres > 0) { int moveQuantity = (int)(toMoveLitres * lprops.ItemsPerLitre); ItemStack takenContentStack = source.TryTakeContent(bucketStack, moveQuantity / bucketStack.StackSize); takenContentStack.StackSize *= bucketStack.StackSize; takenContentStack.StackSize += liquidSlot.StackSize; liquidSlot.Itemstack = takenContentStack; liquidSlot.MarkDirty(); op.MovedQuantity = moveQuantity; var pos = op.ActingPlayer?.Entity?.Pos; if (pos != null) { op.World.PlaySoundAt(lprops.FillSound, pos.X, pos.Y, pos.Z); } } return; } return; } string contentItemCode = sourceSlot.Itemstack?.ItemAttributes?["contentItemCode"].AsString(); if (contentItemCode != null) { ItemSlot liquidSlot = inventory[1]; ItemStack contentStack = new ItemStack(world.GetItem(new AssetLocation(contentItemCode))); bool stackable = !liquidSlot.Empty && liquidSlot.Itemstack.Equals(world, contentStack, GlobalConstants.IgnoredStackAttributes); if ((liquidSlot.Empty || stackable) && contentStack != null) { if (stackable) { liquidSlot.Itemstack.StackSize++; } else { liquidSlot.Itemstack = contentStack; } liquidSlot.MarkDirty(); ItemStack bowlStack = new ItemStack(world.GetBlock(new AssetLocation(sourceSlot.Itemstack.ItemAttributes["emptiedBlockCode"].AsString()))); if (sourceSlot.StackSize == 1) { sourceSlot.Itemstack = bowlStack; } else { sourceSlot.Itemstack.StackSize--; if (!op.ActingPlayer.InventoryManager.TryGiveItemstack(bowlStack)) { world.SpawnItemEntity(bowlStack, op.ActingPlayer.Entity.Pos.XYZ); } } sourceSlot.MarkDirty(); } return; } base.ActivateSlotLeftClick(sourceSlot, ref op); }
/// <summary> /// Loads the meta information for each block in the schematic. /// </summary> /// <param name="blockAccessor"></param> /// <param name="worldForResolve"></param> /// <param name="fileNameForLogging"></param> public void LoadMetaInformationAndValidate(IBlockAccessor blockAccessor, IWorldAccessor worldForResolve, string fileNameForLogging) { List <BlockPos> undergroundPositions = new List <BlockPos>(); Queue <BlockPos> pathwayPositions = new Queue <BlockPos>(); HashSet <AssetLocation> missingBlocks = new HashSet <AssetLocation>(); for (int i = 0; i < Indices.Count; i++) { uint index = Indices[i]; int storedBlockid = BlockIds[i]; int dx = (int)(index & 0x1ff); int dy = (int)((index >> 20) & 0x1ff); int dz = (int)((index >> 10) & 0x1ff); AssetLocation blockCode = BlockCodes[storedBlockid]; Block newBlock = blockAccessor.GetBlock(blockCode); if (newBlock == null) { missingBlocks.Add(blockCode); } if (newBlock != pathwayBlock && newBlock != undergroundBlock) { continue; } BlockPos pos = new BlockPos(dx, dy, dz); if (newBlock == pathwayBlock) { pathwayPositions.Enqueue(pos); } else { undergroundPositions.Add(pos); } } if (missingBlocks.Count > 0) { worldForResolve.Logger.Warning("Block schematic file {0} uses blocks that could no longer be found. These will turn into air blocks! (affected: {1})", fileNameForLogging, string.Join(",", missingBlocks)); } HashSet <AssetLocation> missingItems = new HashSet <AssetLocation>(); foreach (var val in ItemCodes) { if (worldForResolve.GetItem(val.Value) == null) { missingItems.Add(val.Value); } } if (missingItems.Count > 0) { worldForResolve.Logger.Warning("Block schematic file {0} uses items that could no longer be found. These will turn into unknown items! (affected: {1})", fileNameForLogging, string.Join(",", missingItems)); } UndergroundCheckPositions = undergroundPositions.ToArray(); List <List <BlockPos> > pathwayslist = new List <List <BlockPos> >(); if (pathwayPositions.Count == 0) { this.PathwayStarts = new BlockPos[0]; this.PathwayOffsets = new BlockPos[0][]; this.PathwaySides = new BlockFacing[0]; return; } while (pathwayPositions.Count > 0) { List <BlockPos> pathway = new List <BlockPos>() { pathwayPositions.Dequeue() }; pathwayslist.Add(pathway); int i = pathwayPositions.Count; while (i-- > 0) { BlockPos pos = pathwayPositions.Dequeue(); bool found = false; for (int j = 0; j < pathway.Count; j++) { BlockPos ppos = pathway[j]; int distance = Math.Abs(pos.X - ppos.X) + Math.Abs(pos.Y - ppos.Y) + Math.Abs(pos.Z - ppos.Z); if (distance == 1) { found = true; pathway.Add(pos); break; } } if (!found) { pathwayPositions.Enqueue(pos); } else { i = pathwayPositions.Count; } } } PathwayStarts = new BlockPos[pathwayslist.Count]; PathwayOffsets = new BlockPos[pathwayslist.Count][]; PathwaySides = new BlockFacing[pathwayslist.Count]; for (int i = 0; i < PathwayStarts.Length; i++) { // Concept to determine on which side the door is: // 1. Iterate over every pathway block // 2. Calculate the vector between the schematic center point an the pathway block // 3. Get the average vector by summing up + divide by count // => this is now basically the centerpoint of the door! // 4. This final vector can now be used to determine the block facing Vec3f dirToMiddle = new Vec3f(); List <BlockPos> pathway = pathwayslist[i]; for (int j = 0; j < pathway.Count; j++) { BlockPos pos = pathway[j]; dirToMiddle.X += pos.X - SizeX / 2f; dirToMiddle.Y += pos.Y - SizeY / 2f; dirToMiddle.Z += pos.Z - SizeZ / 2f; } dirToMiddle.Normalize(); PathwaySides[i] = BlockFacing.FromNormal(dirToMiddle); BlockPos start = PathwayStarts[i] = pathwayslist[i][0].Copy(); PathwayOffsets[i] = new BlockPos[pathwayslist[i].Count]; for (int j = 0; j < pathwayslist[i].Count; j++) { PathwayOffsets[i][j] = pathwayslist[i][j].Sub(start); } } }