public override void OnBlockBroken(IPlayer byPlayer = null)
        {
            base.OnBlockBroken(byPlayer);

            if (FoliageState == EnumFoliageState.Ripe)
            {
                var loc   = AssetLocation.Create(Block.Attributes["branchBlock"].AsString(), Block.Code.Domain);
                var block = Api.World.GetBlock(loc) as BlockFruitTreeBranch;
                var drops = block.TypeProps[TreeType].FruitStacks;
                foreach (var drop in drops)
                {
                    ItemStack stack = drop.GetNextItemStack(1);
                    if (stack == null)
                    {
                        continue;
                    }

                    Api.World.SpawnItemEntity(stack, Pos.ToVec3d().Add(0.5, 0.5, 0.5));
                    if (drop.LastDrop)
                    {
                        break;
                    }
                }
            }
        }
        public bool Exchange(IPlayer byPlayer)
        {
            if (Api.Side.IsServer())
            {
                foreach (var val in Exchanges)
                {
                    ItemSlot active = byPlayer.InventoryManager.ActiveHotbarSlot;
                    if (ExchangePossible(val, active, out ItemSlot exchangeSlot, out ItemSlot emptySlot))
                    {
                        if (active.TryPutInto(Api.World, emptySlot, val.Input.StackSize) == val.Input.StackSize)
                        {
                            DummySlot dummy = new DummySlot();
                            if (exchangeSlot.TryPutInto(Api.World, dummy, val.Output.StackSize) == val.Output.StackSize)
                            {
                                if (!byPlayer.InventoryManager.TryGiveItemstack(dummy.Itemstack))
                                {
                                    byPlayer.Entity.World.SpawnItemEntity(dummy.Itemstack, Pos.ToVec3d());
                                }
                                Api.World.PlaySoundAt(AssetLocation.Create("sounds/effect/cashregister"), Pos.X, Pos.Y, Pos.Z);
                                inventory.Sort(Api, EnumSortMode.ID);
                                return(true);
                            }
                        }
                    }
                }
            }
            else
            {
                return(true);
            }

            return(false);
        }
Beispiel #3
0
        public override void Initialize(ICoreAPI api, JsonObject properties)
        {
            base.Initialize(api, properties);

            if (Api.Side == EnumAppSide.Server)
            {
                listenerId = Blockentity.RegisterGameTickListener(OnTick, callbackTimeMs + Api.World.Rand.Next(callbackTimeMs));
            }

            stemBlock   = Api.World.GetBlock(ownBe.Block.CodeWithVariant("type", "stem"));
            branchBlock = Api.World.GetBlock(ownBe.Block.CodeWithVariant("type", "branch")) as BlockFruitTreeBranch;
            leavesBlock = Api.World.GetBlock(AssetLocation.Create(ownBe.Block.Attributes["foliageBlock"].AsString(), ownBe.Block.Code.Domain)) as BlockFruitTreeFoliage;

            if (ownBe.Block == leavesBlock)
            {
                ownBe.PartType = EnumTreePartType.Leaves;
            }
            if (ownBe.Block == branchBlock)
            {
                ownBe.PartType = EnumTreePartType.Branch;
            }

            if (ownBe.lastGrowthAttemptTotalDays == 0)
            {
                ownBe.lastGrowthAttemptTotalDays = api.World.Calendar.TotalDays;
            }
        }
        public MeshData GenMesh(ICoreClientAPI capi, string type, string shapename, ITesselatorAPI tesselator = null, Vec3f rotation = null)
        {
            if (shapename == null)
            {
                return(new MeshData());
            }
            if (tesselator == null)
            {
                tesselator = capi.Tesselator;
            }

            tmpTextureSource = tesselator.GetTexSource(this);

            AssetLocation shapeloc = AssetLocation.Create(shapename, Code.Domain).WithPathPrefix("shapes/");
            Shape         shape    = capi.Assets.TryGet(shapeloc + ".json")?.ToObject <Shape>();

            if (shape == null)
            {
                shape = capi.Assets.TryGet(shapeloc + "1.json")?.ToObject <Shape>();
            }
            if (shape == null)
            {
                return(new MeshData());
            }

            curType = type;
            MeshData mesh;

            tesselator.TesselateShape("typedcontainer", shape, out mesh, this, rotation == null ? new Vec3f(Shape.rotateX, Shape.rotateY, Shape.rotateZ) : rotation);
            return(mesh);
        }
        public override void OnHeldInteractStart(ItemSlot slot, EntityAgent interactingEntity, BlockSelection blockSel, EntitySelection entitySel, bool firstEvent, ref EnumHandHandling handling)
        {
            // api.Logger.Error("interactStart");
            checkStillLoaded(slot, interactingEntity);
            ItemSlot invslot = GetNextAmmo(interactingEntity);

            if (invslot == null)
            {
                return;
            }

            // Not ideal to code the aiming controls this way. Needs an elegant solution - maybe an event bus?
            interactingEntity.Attributes.SetInt("aimingCancel", 0);
            if (!Attributes["stayLoaded"].AsBool(false) || slot.Itemstack.Attributes.GetBool("loaded", false))
            {
                interactingEntity.Attributes.SetInt("aiming", 1);
            }

            if (slot.Itemstack.Attributes.GetBool("loaded", false))
            {
                interactingEntity.AnimManager.StartAnimation(Attributes["loadedAimAnimation"].AsString("bowaim"));
                if (Attributes["aimSound"].AsString("").Length > 0)
                {
                    interactingEntity.World.PlaySoundAt(AssetLocation.Create(Attributes["aimSound"].AsString(""), Code.Domain), interactingEntity, (interactingEntity as EntityPlayer)?.Player, false, 8);
                }
            }
            else
            {
                if (interactingEntity.World is IClientWorldAccessor)
                {
                    slot.Itemstack.TempAttributes.SetInt("renderVariant", 1);
                }

                slot.Itemstack.Attributes.SetInt("renderVariant", 1);

                interactingEntity.AnimManager.StartAnimation(Attributes["aimAnimation"].AsString("bowaim"));

                IPlayer player = null;
                if (interactingEntity is EntityPlayer)
                {
                    player = interactingEntity.World.PlayerByUid(((EntityPlayer)interactingEntity).PlayerUID);
                }

                if (Attributes["stayLoaded"].AsBool(false))
                {
                    if (Attributes["loadSound"].AsString("").Length > 0)
                    {
                        interactingEntity.World.PlaySoundAt(AssetLocation.Create(Attributes["loadSound"].AsString(""), Code.Domain), interactingEntity, player, false, 8);
                    }
                }
                else
                {
                    if (Attributes["drawSound"].AsString("").Length > 0)
                    {
                        interactingEntity.World.PlaySoundAt(AssetLocation.Create(Attributes["drawSound"].AsString(""), Code.Domain), interactingEntity, player, false, 8);
                    }
                }
            }
            handling = EnumHandHandling.PreventDefault;
        }
Beispiel #6
0
        public override void OnLoaded(ICoreAPI api)
        {
            base.OnLoaded(api);

            notSnowCovered = api.World.GetBlock(AssetLocation.Create(FirstCodePart(), Code.Domain));
            snowCovered1   = api.World.GetBlock(AssetLocation.Create(FirstCodePart() + "-snow", Code.Domain));
            snowCovered2   = api.World.GetBlock(AssetLocation.Create(FirstCodePart() + "-snow2", Code.Domain));
            snowCovered3   = api.World.GetBlock(AssetLocation.Create(FirstCodePart() + "-snow3", Code.Domain));
            if (this == snowCovered1)
            {
                snowLevel = 1;
            }
            if (this == snowCovered2)
            {
                snowLevel = 2;
            }
            if (this == snowCovered3)
            {
                snowLevel = 3;
            }


            snowLayerBlockId = api.World.GetBlock(new AssetLocation("snowlayer-1")).Id;

            IsSnowCovered = this.Id != notSnowCovered.Id;
        }
        public override void OnLoaded(ICoreAPI api)
        {
            base.OnLoaded(api);

            capi = api as ICoreClientAPI;

            branchBlock  = api.World.GetBlock(CodeWithVariant("type", "branch"));
            foliageBlock = api.World.GetBlock(AssetLocation.Create(Attributes["foliageBlock"].AsString(), Code.Domain)) as BlockFruitTreeFoliage;

            TypeProps = Attributes["fruittreeProperties"].AsObject <Dictionary <string, FruitTreeTypeProperties> >();
            var shapeFiles = Attributes["shapes"].AsObject <Dictionary <string, CompositeShape> >();

            WorldGenConds = Attributes["worldgen"].AsObject <FruitTreeWorldGenConds[]>();

            foreach (var val in shapeFiles)
            {
                IAsset asset = api.Assets.TryGet(val.Value.Base.WithPathAppendixOnce(".json").WithPathPrefixOnce("shapes/"), true);
                Shapes[val.Key] = new FruitTreeShape()
                {
                    Shape = asset?.ToObject <Shape>(), CShape = val.Value
                };
            }

            foreach (var prop in TypeProps)
            {
                foreach (var bdstack in prop.Value.FruitStacks)
                {
                    bdstack.Resolve(api.World, "fruit tree FruitStacks");
                }

                (api as ICoreServerAPI)?.RegisterTreeGenerator(new AssetLocation("fruittree-" + prop.Key), (blockAccessor, pos, skipForestFloor, s, v, o, t) => GrowTree(blockAccessor, pos, prop.Key));
            }
        }
        public void OnBlockInteractStop(float secondsUsed, IPlayer byPlayer, BlockSelection blockSel)
        {
            if (secondsUsed > 1.1 && FoliageState == EnumFoliageState.Ripe)
            {
                FoliageState = EnumFoliageState.Plain;
                MarkDirty(true);

                var loc   = AssetLocation.Create(Block.Attributes["branchBlock"].AsString(), Block.Code.Domain);
                var block = Api.World.GetBlock(loc) as BlockFruitTreeBranch;

                var drops = block.TypeProps[TreeType].FruitStacks;

                foreach (var drop in drops)
                {
                    ItemStack stack = drop.GetNextItemStack(1);
                    if (stack == null)
                    {
                        continue;
                    }

                    if (!byPlayer.InventoryManager.TryGiveItemstack(stack, true))
                    {
                        Api.World.SpawnItemEntity(stack, byPlayer.Entity.Pos.XYZ.Add(0, 0.5, 0));
                    }

                    if (drop.LastDrop)
                    {
                        break;
                    }
                }
            }
        }
Beispiel #9
0
        public Shape GetShape(ICoreClientAPI capi, string type, string shapename, ITesselatorAPI tesselator = null, int altTexNumber = 0)
        {
            if (shapename == null)
            {
                return(null);
            }
            if (tesselator == null)
            {
                tesselator = capi.Tesselator;
            }

            tmpTextureSource = tesselator.GetTexSource(this, altTexNumber);

            AssetLocation shapeloc = AssetLocation.Create(shapename, Code.Domain).WithPathPrefix("shapes/");
            Shape         shape    = capi.Assets.TryGet(shapeloc + ".json")?.ToObject <Shape>();

            if (shape == null)
            {
                shape = capi.Assets.TryGet(shapeloc + "1.json")?.ToObject <Shape>();
            }

            curType = type;

            return(shape);
        }
Beispiel #10
0
        public override void OnReceivedServerPacket(int packetid, byte[] data)
        {
            IClientWorldAccessor clientWorld = (IClientWorldAccessor)Api.World;

            if (packetid == (int)EnumBlockContainerPacketId.OpenInventory)
            {
                if (invDialog != null)
                {
                    if (invDialog?.IsOpened() == true)
                    {
                        invDialog.TryClose();
                    }
                    invDialog?.Dispose();
                    invDialog = null;
                    return;
                }

                string        dialogClassName;
                string        dialogTitle;
                int           cols;
                TreeAttribute tree = new TreeAttribute();

                using (MemoryStream ms = new MemoryStream(data))
                {
                    BinaryReader reader = new BinaryReader(ms);
                    dialogClassName = reader.ReadString();
                    dialogTitle     = reader.ReadString();
                    cols            = reader.ReadByte();
                    tree.FromBytes(reader);
                }

                Inventory.FromTreeAttributes(tree);
                Inventory.ResolveBlocksOrItems();

                invDialog = new GuiDialogBlockEntityInventory(dialogTitle, Inventory, Pos, cols, Api as ICoreClientAPI);

                Block         block      = Api.World.BlockAccessor.GetBlock(Pos);
                string        os         = block.Attributes?["openSound"]?.AsString();
                string        cs         = block.Attributes?["closeSound"]?.AsString();
                AssetLocation opensound  = os == null ? null : AssetLocation.Create(os, block.Code.Domain);
                AssetLocation closesound = cs == null ? null : AssetLocation.Create(cs, block.Code.Domain);

                invDialog.OpenSound  = opensound ?? this.OpenSound;
                invDialog.CloseSound = closesound ?? this.CloseSound;

                invDialog.TryOpen();
            }

            if (packetid == (int)EnumBlockEntityPacketId.Close)
            {
                clientWorld.Player.InventoryManager.CloseInventory(Inventory);
                if (invDialog?.IsOpened() == true)
                {
                    invDialog?.TryClose();
                }
                invDialog?.Dispose();
                invDialog = null;
            }
        }
        public void CmdCollectibleExchange(IServerPlayer byPlayer, int id, CmdArgs args)
        {
            BlockPos pos = byPlayer?.CurrentBlockSelection?.Position;
            string   arg = args.PopWord();

            switch (arg)
            {
            case "create":
                if (pos != null)
                {
                    if (!sapi.World.Claims.TryAccess(byPlayer, pos, EnumBlockAccessFlags.Use))
                    {
                        break;
                    }
                    BlockEntityGenericTypedContainer be = (sapi.World.BlockAccessor.GetBlockEntity(pos) as BlockEntityGenericTypedContainer);
                    if (be != null)
                    {
                        List <Exchange> exchanges = GetExchanges(be.Inventory);
                        sapi.World.BlockAccessor.RemoveBlockEntity(pos);
                        sapi.World.BlockAccessor.SpawnBlockEntity("Shop", pos);
                        BlockEntityShop beShop = (sapi.World.BlockAccessor.GetBlockEntity(pos) as BlockEntityShop);
                        beShop.inventory = (InventoryGeneric)be.Inventory;
                        beShop.Exchanges = exchanges;
                        sapi.World.PlaySoundAt(AssetLocation.Create("sounds/effect/latch"), pos.X, pos.Y, pos.Z);
                    }
                }
                break;

            case "update":
                if (!sapi.World.Claims.TryAccess(byPlayer, pos, EnumBlockAccessFlags.Use))
                {
                    break;
                }
                BlockEntityShop shop = (sapi.World.BlockAccessor.GetBlockEntity(pos) as BlockEntityShop);
                if (shop != null)
                {
                    shop.Exchanges = GetExchanges(shop.inventory);
                }
                sapi.World.PlaySoundAt(AssetLocation.Create("sounds/effect/latch"), pos.X, pos.Y, pos.Z);
                break;

            case "list":
                if (sapi.World.BlockAccessor.GetBlockEntity(pos) is BlockEntityShop)
                {
                    StringBuilder builder = new StringBuilder();
                    ((BlockEntityShop)sapi.World.BlockAccessor.GetBlockEntity(pos)).GetBlockInfo(byPlayer, builder);
                    byPlayer.SendMessage(GlobalConstants.GeneralChatGroup, builder.ToString(), EnumChatType.OwnMessage);
                }
                break;

            case "trade":
                ExchangeEvent(byPlayer, byPlayer.CurrentBlockSelection);
                break;

            default:
                byPlayer.SendMessage(GlobalConstants.GeneralChatGroup, syntaxMsg, EnumChatType.OwnMessage);
                break;
            }
        }
Beispiel #12
0
        private void ReplaceWithHarvested(BlockPos blockPos)
        {
            Block         leakingBlock          = Api.World.BlockAccessor.GetBlock(blockPos);
            AssetLocation harvestedLogBlockCode = AssetLocation.Create(HarvestBlockCode, leakingBlock.Code.Domain);
            Block         harvestedLogBlock     = Api.World.GetBlock(harvestedLogBlockCode);

            Api.World.BlockAccessor.SetBlock(harvestedLogBlock.BlockId, blockPos);
        }
Beispiel #13
0
        public override void Initialize(JsonObject properties)
        {
            base.Initialize(properties);

            dropsPickupMode = properties["dropsPickupMode"].AsBool(false);
            string strloc = properties["sound"].AsString();

            pickupSound = strloc == null ? null : AssetLocation.Create(strloc, block.Code.Domain);
        }
Beispiel #14
0
        public override bool OnPlayerInteractStart(IPlayer player, BlockSelection bs)
        {
            ItemSlot hotbarSlot = player.InventoryManager.ActiveHotbarSlot;

            if (hotbarSlot.Empty)
            {
                return(false);
            }

            if (currentBuildStage < buildStages.Length)
            {
                BuildStage           stage = buildStages[currentBuildStage];
                BuildStageMaterial[] mats  = stage.Materials;

                for (int i = 0; i < mats.Length; i++)
                {
                    var stack = mats[i].ItemStack;

                    if (stack.Equals(Api.World, hotbarSlot.Itemstack, GlobalConstants.IgnoredStackAttributes) && stack.StackSize <= hotbarSlot.StackSize)
                    {
                        if (!isSameMatAsPreviouslyAdded(stack))
                        {
                            continue;
                        }

                        int toMove = stack.StackSize;
                        for (int j = 4; j < invSlotCount && toMove > 0; j++)
                        {
                            toMove -= hotbarSlot.TryPutInto(Api.World, inventory[j], toMove);
                        }

                        hotbarSlot.MarkDirty();

                        currentBuildStage++;
                        mesh = null;
                        MarkDirty(true);
                        updateSelectiveElements();
                        (player as IClientPlayer)?.TriggerFpAnimation(EnumHandInteract.HeldItemInteract);

                        if (stack.Collectible.Attributes?["placeSound"].Exists == true)
                        {
                            AssetLocation sound = AssetLocation.Create(stack.Collectible.Attributes["placeSound"].AsString(), stack.Collectible.Code.Domain);
                            if (sound != null)
                            {
                                Api.World.PlaySoundAt(sound.WithPathPrefixOnce("sounds/"), Pos.X + 0.5, Pos.Y + 0.1, Pos.Z + 0.5, player, true, 12);
                            }
                        }
                    }
                }
            }


            DetermineStorageProperties(null);

            return(true);
        }
Beispiel #15
0
        public ItemStack GetBaseMaterial(ItemStack stack)
        {
            Item item = api.World.GetItem(AssetLocation.Create("ingot-" + Variant["metal"], Attributes?["baseMaterialDomain"].AsString("game")));

            if (item == null)
            {
                throw new Exception(string.Format("Base material for {0} not found, there is no item with code 'ingot-{1}'", stack.Collectible.Code, Variant["metal"]));
            }
            return(new ItemStack(item));
        }
Beispiel #16
0
        public void UpdateAsset()
        {
            string codePath = (!Inventory.Empty)
                ? Block.Code.Path.Replace("empty", "filled")
                : Block.Code.Path.Replace("filled", "empty");
            AssetLocation filledBlockAsset = AssetLocation.Create(codePath, Block.Code.Domain);
            Block         filledBlock      = Api.World.GetBlock(filledBlockAsset);

            Api.World.BlockAccessor.ExchangeBlock(filledBlock.BlockId, Pos);
        }
Beispiel #17
0
        public override void LoadConfig(JsonObject taskConfig, JsonObject aiConfig)
        {
            base.LoadConfig(taskConfig, aiConfig);

            spawnRange         = taskConfig["spawnRange"]?.AsInt(12) ?? 12;
            spawnIntervalMsMin = taskConfig["spawnIntervalMsMin"]?.AsInt(2000) ?? 2000;
            spawnIntervalMsMax = taskConfig["spawnIntervalMsMax"]?.AsInt(15000) ?? 15000;
            spawnMaxQuantity   = taskConfig["spawnMaxQuantity"]?.AsInt(5) ?? 5;
            seekingRange       = taskConfig["seekingRange"]?.AsFloat(12) ?? 12;

            var spawnMobLocs = taskConfig["spawnMobs"]?.AsObject <AssetLocation[]>() ?? new AssetLocation[0];
            List <EntityProperties> props = new List <EntityProperties>();

            foreach (var val in spawnMobLocs)
            {
                var etype = sapi.World.GetEntityType(val);
                if (etype == null)
                {
                    sapi.World.Logger.Warning("AiTaskBellAlarm defined spawnmob {0}, but no such entity type found, will ignore.", val);
                    continue;
                }

                props.Add(etype);
            }

            spawnMobs = props.ToArray();

            repeatSoundLoc = taskConfig["repeatSound"] == null ? null : AssetLocation.Create(taskConfig["repeatSound"].AsString(), entity.Code.Domain).WithPathPrefixOnce("sounds/");

            if (taskConfig["onNearbyEntityCodes"] != null)
            {
                string[] codes = taskConfig["onNearbyEntityCodes"].AsArray <string>(new string[] { "player" });

                List <string> exact      = new List <string>();
                List <string> beginswith = new List <string>();

                for (int i = 0; i < codes.Length; i++)
                {
                    string code = codes[i];
                    if (code.EndsWith("*"))
                    {
                        beginswith.Add(code.Substring(0, code.Length - 1));
                    }
                    else
                    {
                        exact.Add(code);
                    }
                }

                seekEntityCodesExact      = exact.ToArray();
                seekEntityCodesBeginsWith = beginswith.ToArray();
            }

            cooldownUntilTotalHours = entity.World.Calendar.TotalHours + mincooldownHours + entity.World.Rand.NextDouble() * (maxcooldownHours - mincooldownHours);
        }
        public override void OnLoaded(ICoreAPI api)
        {
            // This figures out what item types are valid ammo and shows them as an interaction help.
            if (api.Side != EnumAppSide.Client)
            {
                return;
            }
            List <AssetLocation> locs = new List <AssetLocation>();
            string codeNames          = "";

            if (Attributes.KeyExists("ammos"))
            {
                //foreach (string s in Attributes["ammos"].AsArray<string>())
                foreach (string s in Attributes["ammos"].AsStringArray()) // Yes, this is deprecated, but the other one compiles wrong.
                {
                    locs.Add(AssetLocation.Create(s, Code.Domain));
                    codeNames += "_" + s;
                }
            }
            else
            {
                locs.Add(AssetLocation.Create(Attributes["ammo"].AsString("arrow-*"), Code.Domain));
                codeNames = Attributes["ammo"].AsString("arrow-*");
            }
            ICoreClientAPI capi = api as ICoreClientAPI;

            interactions = ObjectCacheUtil.GetOrCreate(api, "ranged" + codeNames + "Interactions", () =>
            {
                List <ItemStack> stacks = new List <ItemStack>();
                foreach (CollectibleObject obj in api.World.Collectibles)
                {
                    foreach (AssetLocation loc in locs)
                    {
                        if (WildcardUtil.Match(loc, obj.Code))
                        {
                            // api.Logger.Error("stack " + obj.Code);
                            stacks.Add(new ItemStack(obj));
                            break;
                        }
                    }
                }

                return(new WorldInteraction[]
                {
                    new WorldInteraction()
                    {
                        ActionLangCode = Attributes["heldhelp"].AsString("heldhelp-chargebow"),
                        MouseButton = EnumMouseButton.Right,
                        Itemstacks = stacks.ToArray()
                    }
                });
            });
        }
Beispiel #19
0
 public ItemStack[] GetDrops()
 {
     if (stage == EnumTreeGrowthStage.Seed)
     {
         Item item = Api.World.GetItem(AssetLocation.Create("treeseed-" + Block.Variant["wood"], Block.Code.Domain));
         return(new ItemStack[] { new ItemStack(item) });
     }
     else
     {
         return(new ItemStack[] { new ItemStack(Block) });
     }
 }
Beispiel #20
0
        public override void Initialize(ICoreAPI api)
        {
            blockFoliage = Block as BlockFruitTreeFoliage;
            string code = Block.Attributes?["branchBlock"]?.AsString();

            if (code == null)
            {
                api.World.BlockAccessor.SetBlock(0, Pos); return;
            }
            blockBranch = api.World.GetBlock(AssetLocation.Create(code, Block.Code.Domain)) as BlockFruitTreeBranch;

            base.Initialize(api);
        }
        public override void Initialize(JsonObject properties)
        {
            base.Initialize(properties);


            attachableFaces = new BlockFacing[] { BlockFacing.DOWN };

            if (properties["attachableFaces"].Exists)
            {
                string[] faces = properties["attachableFaces"].AsArray <string>();
                attachableFaces = new BlockFacing[faces.Length];

                for (int i = 0; i < faces.Length; i++)
                {
                    attachableFaces[i] = BlockFacing.FromCode(faces[i]);
                }
            }

            var areas = properties["attachmentAreas"].AsObject <Dictionary <string, RotatableCube> >(null);

            attachmentAreas = new Dictionary <string, Cuboidi>();
            if (areas != null)
            {
                foreach (var val in areas)
                {
                    val.Value.Origin.Set(8, 8, 8);
                    attachmentAreas[val.Key] = val.Value.RotatedCopy().ConvertToCuboidi();
                }
            }
            else
            {
                attachmentAreas["up"] = properties["attachmentArea"].AsObject <Cuboidi>(null);
            }

            ignorePlaceTest = properties["ignorePlaceTest"].AsBool(false);
            exceptions      = properties["exceptions"].AsObject(new AssetLocation[0], block.Code.Domain);
            fallSideways    = properties["fallSideways"].AsBool(false);
            dustIntensity   = properties["dustIntensity"].AsFloat(0);

            fallSidewaysChance = properties["fallSidewaysChance"].AsFloat(0.3f);
            string sound = properties["fallSound"].AsString(null);

            if (sound != null)
            {
                fallSound = AssetLocation.Create(sound, block.Code.Domain);
            }

            impactDamageMul = properties["impactDamageMul"].AsFloat(1f);
        }
        public MeshData GenMesh(ICoreClientAPI capi, AssetLocation labelLoc, Vec3f rot = null)
        {
            var   tesselator = capi.Tesselator;
            Shape baseshape  = capi.Assets.TryGet(AssetLocation.Create("shapes/block/clay/crock/base.json", Code.Domain)).ToObject <Shape>();
            Shape labelshape = capi.Assets.TryGet(labelLoc).ToObject <Shape>();

            MeshData mesh, labelmesh;

            tesselator.TesselateShape(this, baseshape, out mesh, rot);
            tesselator.TesselateShape(this, labelshape, out labelmesh, rot);

            mesh.AddMeshData(labelmesh);

            return(mesh);
        }
Beispiel #23
0
        public override void Initialize(ICoreAPI api)
        {
            base.Initialize(api);

            Inventory.LateInitialize(InventoryClassName + "-" + Pos.X + "/" + Pos.Y + "/" + Pos.Z, api);
            Inventory.ResolveBlocksOrItems();

            string        os         = Block.Attributes?["openSound"]?.AsString();
            string        cs         = Block.Attributes?["closeSound"]?.AsString();
            AssetLocation opensound  = os == null ? null : AssetLocation.Create(os, Block.Code.Domain);
            AssetLocation closesound = cs == null ? null : AssetLocation.Create(cs, Block.Code.Domain);

            OpenSound  = opensound ?? this.OpenSound;
            CloseSound = closesound ?? this.CloseSound;
        }
        public override void Initialize(JsonObject properties)
        {
            string[] blockCodes = properties["exchangeStates"].AsArray <string>();

            this.blockCodes = new AssetLocation[blockCodes.Length];

            for (int i = 0; i < blockCodes.Length; i++)
            {
                this.blockCodes[i] = AssetLocation.Create(blockCodes[i], block.Code.Domain);
            }

            sound          = properties["sound"].AsString();
            actionlangcode = properties["actionLangCode"].AsString();
            base.Initialize(properties);
        }
        public override void OnHeldInteractStart(ItemSlot itemslot, EntityAgent byEntity, BlockSelection blockSel, EntitySelection entitySel, bool firstEvent, ref EnumHandHandling handHandling)
        {
            if (blockSel == null || !byEntity.Controls.Sneak)
            {
                base.OnHeldInteractStart(itemslot, byEntity, blockSel, entitySel, firstEvent, ref handHandling);
                return;
            }

            string treetype = Variant["type"];

            Block saplBlock = byEntity.World.GetBlock(AssetLocation.Create("sapling-" + treetype + "-free", Code.Domain));

            if (saplBlock != null)
            {
                IPlayer byPlayer = null;
                if (byEntity is EntityPlayer)
                {
                    byPlayer = byEntity.World.PlayerByUid(((EntityPlayer)byEntity).PlayerUID);
                }

                blockSel = blockSel.Clone();
                blockSel.Position.Up();

                string failureCode = "";
                if (!saplBlock.TryPlaceBlock(api.World, byPlayer, itemslot.Itemstack, blockSel, ref failureCode))
                {
                    if (api is ICoreClientAPI capi && failureCode != null && failureCode != "__ignore__")
                    {
                        capi.TriggerIngameError(this, failureCode, Lang.Get("placefailure-" + failureCode));
                    }
                }
                else
                {
                    byEntity.World.PlaySoundAt(new AssetLocation("sounds/block/dirt1"), blockSel.Position.X + 0.5f, blockSel.Position.Y, blockSel.Position.Z + 0.5f, byPlayer);

                    ((byEntity as EntityPlayer)?.Player as IClientPlayer)?.TriggerFpAnimation(EnumHandInteract.HeldItemInteract);

                    if (byPlayer?.WorldData?.CurrentGameMode != EnumGameMode.Creative)
                    {
                        itemslot.TakeOut(1);
                        itemslot.MarkDirty();
                    }
                }

                handHandling = EnumHandHandling.PreventDefault;
            }
        }
Beispiel #26
0
        protected virtual void InitInventory(Block block)
        {
            if (block?.Attributes != null)
            {
                collisionSelectionBoxes = block.Attributes["collisionSelectionBoxes"]?[type]?.AsObject <Cuboidf[]>();

                inventoryClassName = block.Attributes["inventoryClassName"].AsString(inventoryClassName);

                dialogTitleLangCode = block.Attributes["dialogTitleLangCode"][type].AsString(dialogTitleLangCode);
                quantitySlots       = block.Attributes["quantitySlots"][type].AsInt(quantitySlots);
                quantityColumns     = block.Attributes["quantityColumns"][type].AsInt(4);

                retrieveOnly = block.Attributes["retrieveOnly"][type].AsBool(false);

                if (block.Attributes["typedOpenSound"][type].Exists)
                {
                    OpenSound = AssetLocation.Create(block.Attributes["typedOpenSound"][type].AsString(OpenSound.ToShortString()), block.Code.Domain);
                }
                if (block.Attributes["typedCloseSound"][type].Exists)
                {
                    CloseSound = AssetLocation.Create(block.Attributes["typedCloseSound"][type].AsString(CloseSound.ToShortString()), block.Code.Domain);
                }
            }

            inventory                       = new InventoryGeneric(quantitySlots, null, null, null);
            inventory.BaseWeight            = 1f;
            inventory.OnGetSuitability      = (sourceSlot, targetSlot, isMerge) => (isMerge ? (inventory.BaseWeight + 3) : (inventory.BaseWeight + 1)) + (sourceSlot.Inventory is InventoryBasePlayer ? 1 : 0);
            inventory.OnGetAutoPullFromSlot = GetAutoPullFromSlot;


            if (block?.Attributes != null)
            {
                if (block.Attributes["spoilSpeedMulByFoodCat"][type].Exists == true)
                {
                    inventory.PerishableFactorByFoodCategory = block.Attributes["spoilSpeedMulByFoodCat"][type].AsObject <Dictionary <EnumFoodCategory, float> >();
                }

                if (block.Attributes["transitionSpeedMulByType"][type].Exists == true)
                {
                    inventory.TransitionableSpeedMulByType = block.Attributes["transitionSpeedMulByType"][type].AsObject <Dictionary <EnumTransitionType, float> >();
                }
            }

            inventory.PutLocked          = retrieveOnly;
            inventory.OnInventoryClosed += OnInvClosed;
            inventory.OnInventoryOpened += OnInvOpened;
        }
        public override void Initialize(JsonObject properties)
        {
            base.Initialize(properties);
            if (!block.Code.Path.Contains("log-grown-pine-"))
            {
                return;
            }

            scoreTime = properties["scoreTime"].AsFloat(0);

            string code = properties["scoringSound"].AsString("game:sounds/block/chop3");

            if (code != null)
            {
                scoringSound = AssetLocation.Create(code, block.Code.Domain);
            }
        }
Beispiel #28
0
        public AssetLocation LabelForContents(string recipeCode, ItemStack[] contents)
        {
            if (recipeCode != null && recipeCode.Length > 0)
            {
                return(AssetLocation.Create("shapes/block/clay/crock/label-meal.json", Code.Domain));
            }
            if (contents == null || contents.Length == 0 || contents[0] == null)
            {
                return(AssetLocation.Create("shapes/block/clay/crock/label-empty.json", Code.Domain));
            }

            string contentCode = contents[0].Collectible.Code.Path;
            string type        = "empty";

            if (contentCode.Contains("carrot"))
            {
                type = "carrot";
            }
            else if (contentCode.Contains("cabbage"))
            {
                type = "cabbage";
            }
            else if (contentCode.Contains("onion"))
            {
                type = "onion";
            }
            else if (contentCode.Contains("parsnip"))
            {
                type = "parsnip";
            }
            else if (contentCode.Contains("turnip"))
            {
                type = "turnip";
            }
            else if (contentCode.Contains("pumpkin"))
            {
                type = "pumpkin";
            }
            else if (contentCode.Contains("soybean"))
            {
                type = "soybean";
            }

            return(AssetLocation.Create("shapes/block/clay/crock/label-" + type + ".json", Code.Domain));
        }
        public override void Initialize(ICoreAPI api)
        {
            blockFoliage = api.World.GetBlock(AssetLocation.Create(Block.Attributes["foliageBlock"].AsString(), Block.Code.Domain)) as BlockFruitTreeFoliage;
            blockBranch  = Block as BlockFruitTreeBranch;

            initCustomBehaviors(null, false);

            base.Initialize(api);

            if (InitAfterWorldGen && Api.Side == EnumAppSide.Server)
            {
                lastGrowthAttemptTotalDays = Api.World.Calendar.TotalDays - 20 - Api.World.Rand.Next(600);
                InitTreeRoot(TreeType, true);
                InitAfterWorldGen = false;
            }

            updateProperties();
        }
Beispiel #30
0
        public override void Initialize(JsonObject properties)
        {
            base.Initialize(properties);

            ignorePlaceTest = properties["ignorePlaceTest"].AsBool(false);
            exceptions      = properties["exceptions"].AsObject(new AssetLocation[0], block.Code.Domain);
            fallSideways    = properties["fallSideways"].AsBool(false);
            dustIntensity   = properties["dustIntensity"].AsFloat(0);
            attachmentArea  = properties["attachmentArea"].AsObject <Cuboidi>(null);

            fallSidewaysChance = properties["fallSidewaysChance"].AsFloat(0.25f);
            string sound = properties["fallSound"].AsString(null);

            if (sound != null)
            {
                fallSound = AssetLocation.Create(sound, block.Code.Domain);
            }
            impactDamageMul = properties["impactDamageMul"].AsFloat(1f);
        }