Наследование: MonoBehaviour, IDropHandler
Пример #1
0
 void BootstrapAllSlots()
 {
     foreach (KeyValuePair<string, SlotType> p in SlotType.all) {
       var slot = new Slot(p.Key);
       player.Slots[p.Key] = slot;
     }
 }
Пример #2
0
 public static PlayerItem CreatMainSlot(Slot slot, int levelResult)
 {
     var totalPoints = GetPointsByLvl(levelResult)*GetSlotCoef(slot);
     float diff = Utils.RandomNormal(0.5f, 1f);
     //Debug.Log("iffff " + diff);
     bool isRare = diff > 0.95f;
     totalPoints *= diff;
     float contest = UnityEngine.Random.Range(0.60f, 1f);
     if (contest > 0.9f)
         contest = 1f;
     var pparams = new Dictionary<ParamType,float>();
     var primary = Connections.GetPrimaryParamType(slot);
     var primaryValue = totalPoints*contest;
     pparams.Add(primary,primaryValue);
     if (contest < 0.95f)
     {
         var secondary = Connections.GetSecondaryParamType(slot);
         var secondaryValue = totalPoints*(1f - contest);
         pparams.Add(secondary, secondaryValue);
     }
     PlayerItem item = new PlayerItem(pparams,slot,isRare, totalPoints);
     if (contest < 0.85f && (slot == Slot.magic_weapon || slot == Slot.physical_weapon))//.65f
     {
         var spec = ShopController.AllSpecialAbilities.RandomElement();
         item.specialAbilities = spec;
         Debug.Log("WITH SPEC::: " + item.specialAbilities);
     }
     return item;
 }
        protected override void InitSimulation(int seed, LevelInfo level, PlayerInfo[] players, Slot[] slots)
        {
            simulation = new SecureSimulation(extensionPaths);

            // Settings aufbauen
            Setup settings = new Setup();
            settings.Seed = seed;
            settings.Level = level.Type;
            settings.Player = new TypeInfo[AntMe.Level.MAX_SLOTS];
            settings.Colors = new PlayerColor[AntMe.Level.MAX_SLOTS];

            for (int i = 0; i < AntMe.Level.MAX_SLOTS; i++)
            {
                // Farben übertragen
                settings.Colors[i] = slots[i].ColorKey;

                // KIs einladen
                if (players[i] != null)
                {
                    settings.Player[i] = players[i].Type;
                }
            }

            simulation.Start(settings);
        }
Пример #4
0
 //アイテム消費 個数を1へらす 残り1個のときは空にする
 void consumeItem(int inventoryIndex)
 {
     if (inventory [inventoryIndex].itemCount > 1)
         inventory [inventoryIndex].itemCount--;
     else
         inventory [inventoryIndex] = new Slot(inventoryIndex, SCREENSCALE);
 }
Пример #5
0
	void OnEnable() { 

		slot = GetComponent<Slot>();


		Slot.OnSlotStateChangeTo += OnSlotStateChangeTo;	
		Slot.OnSlotStateChangeFrom += OnSlotStateChangeFrom;	

		Slot.OnSpinBegin += OnSpinBegin;
		Slot.OnSpinInsufficentCredits += OnSpinInsufficentCredits;
		Slot.OnSpinSnap += OnSpinSnap;
		Slot.OnSpinDone += OnSpinDone;
		Slot.OnSpinDoneNoWins += OnSpinDoneNoWins;
		Slot.OnReelLand += OnReelLand;

		Slot.OnLineWinComputed += OnLineWinComputed;
		Slot.OnLineWinDisplayed += OnLineWinDisplayed;
		Slot.OnAllWinsComputed	+= OnAllWinsComputed;
		Slot.OnScatterSymbolHit += OnScatterSymbolHit;
		Slot.OnAnticipationScatterBegin += OnAnticipationScatterBegin;

		Slot.OnScatterSymbolLanded += OnScatterSymbolLanded;
		Slot.OnWinDisplayedCycle += OnWinDisplayedCycle;
		Slot.OnLinkedSymbolLanded += OnLinkedSymbolLanded;

		Slot.OnBeginCreditWinCountOff += OnBeginCreditWinCountOff;
		Slot.OnCompletedCreditCountOff += OnCompletedCreditCountOff;

		Slot.OnSymbolReturningToPool += OnSymbolReturningToPool;
	}
Пример #6
0
    public ScoreBox(Slot slot)
    {
        this.slot = slot;

        mathMode = new RXTweenable(0.0f,HandleMathModeChange);

        base.Init(slot.player);

        contentContainer.AddChild(_scoreLabel = new FLabel("Raleway",""));
        _scoreLabel.color = Color.black;

        _baseLabel = new FLabel("Raleway","123");
        _baseLabel.color = Color.black;

        _deltaLabel = new FLabel("Raleway","22");
        _deltaLabel.color = Color.black;

        _signIcon = new FSprite("Icons/Plus");
        _signIcon.color = Color.black;

        _equalsIcon = new FSprite("Icons/Equals");
        _equalsIcon.color = Color.black;

        _skullSprite = new FSprite("Icons/Skull");
        _skullSprite.color = Color.black;

        slot.player.SignalScoreChange += HandleScoreChange;

        ListenForUpdate(HandleUpdate);
        HandleMathModeChange();
        HandleScoreChange();
    }
Пример #7
0
	public override void Use (Slot slot, ItemScript item) {

        if (ItemName == "Energy Potion" && Stamina.Instance.currentStamina < Stamina.Instance.maxStamina){
            Debug.Log(ItemName);
            Stamina.Instance.currentStamina += Stamina.Instance.energyPot;
            Stamina.Instance.bar.fillAmount += Stamina.Instance.energyPot / 100f;
            Stamina.Instance.ManaColor();
            Stamina.Instance.ManaText();
                if(Stamina.Instance.currentStamina >= Stamina.Instance.maxStamina) {
                    Stamina.Instance.currentStamina = Stamina.Instance.maxStamina;
                }
            slot.RemoveItem();
        }
        if (ItemName == "Health Potion" && PlayerScript.Instance.currentHealth < PlayerScript.Instance.maxHealth) {
            Debug.Log(ItemName);
            PlayerScript.Instance.GetHealth();
            PlayerScript.Instance.HandleHealth();
            slot.RemoveItem();
        }
        if (ItemName == "Rage Potion" && Stamina.Instance.currentRage < Stamina.Instance.maxRage) {
            Debug.Log(ItemName);
            Stamina.Instance.RagePotion();
            slot.RemoveItem();
        }
    }
Пример #8
0
 public override void use(Slot slot)
 {
     GameObject.FindObjectOfType<KeyHandler>().EquipSetActive(true);
     if (slot.name.Equals("Slot") || slot.name.Equals("ResultSlot"))
     {
         Slot equipSlot = GameObject.Find(this.SubType.ToString()).GetComponent<Slot>();
         BaseItem tmp = equipSlot.SlotItems();
         equipSlot.ClearSlot();
         equipSlot.AddItem(this);
         slot.ClearSlot();
         if (slot.name.Equals("Slot"))
         {
             slot.AddItem(tmp);
         }
         else
         {
             GameControl.inventory.AddItemToInventory(tmp);
             GameControl.comboWindow.Created = false;
         }
         GameControl.player.Stats.TransferStats(this.Stats);
     }
     else
     {
         GameControl.inventory.AddItemToInventory(this);
         GameControl.player.Stats.RemoveStats(this.Stats);
         slot.ClearSlot();
     }
 }
Пример #9
0
 public Session(Slot slot, Room room, Speaker speaker, string title)
 {
     Slot = slot;
     Room = room;
     Speaker = speaker;
     Title = title;
 }
Пример #10
0
 public override bool GetDrop(ToolItem tool, out Slot[] drop)
 {
     drop = new Slot[0];
     if (tool is ShovelItem)
         drop = new[] { new Slot((ushort)new SnowballItem(), 1) };
     return tool is ShovelItem;
 }
Пример #11
0
    /// <summary>
    /// Swaps two items from one slot to another
    /// </summary>
    /// <param name="from">The slot that we are moving from</param>
    /// <param name="to">The slot that we are moving to</param>
    public static void SwapItems(Slot from, Slot to)
    {
        if (to != null && from != null)
        {
            bool calcStats = from.transform.parent == CharacterPanel.Instance.transform || to.transform.parent == CharacterPanel.Instance.transform;

            if (CanSwap(from, to))
            {
                Stack<ItemScript> tmpTo = new Stack<ItemScript>(to.Items); //Stores the items from the to slot, so that we can do a swap

                to.AddItems(from.Items); //Stores the items in the "from" slot in the "to" slot

                if (tmpTo.Count == 0) //If "to" slot if 0 then we dont need to move anything to the "from " slot.
                {
                    //FIX REMOVED SLOTS MINUSMINUS
                    from.ClearSlot(); //clears the from slot
                }
                else
                {
                    from.AddItems(tmpTo); //If the "to" slot contains items thne we need to move the to the "from" slot
                }

            }

            if (calcStats) //Calculates the stats if we need to
            {
                CharacterPanel.Instance.CalcStats();
            }
        }
    }
Пример #12
0
 public static void SwapItems(Slot from, Slot to)
 {
     ItemType movingType = from.currentItem.type;
     if (movingType == ItemType.BOOTS || movingType == ItemType.LEGS || movingType == ItemType.HEAD || movingType == ItemType.CHEST)
     {
         if (from.currentItem.isEquipped)
         {
             from.currentItem.isEquipped = false;
         }
     }
     //		print ("FROM NAME: " + from.name + " FROM ITEM: " + from.currentItem.itemName + " TO NAME: " + to.name + " TO ITEM#: " + to.items.Count);
     if (from != null && to != null)
     {
         if (to.canContain == ItemType.GENERIC || movingType == to.canContain)
         {
             Stack<ItemScript> tempTo = new Stack<ItemScript>(to.items);
             to.AddItems(from.items);
             if (tempTo.Count == 0)
             {
                 to.transform.parent.GetComponent<Inventory>().EmptySlots--;
                 from.ClearSlot();
             }
             else
             {
                 from.AddItems(tempTo);
             }
         }
     }
 }
Пример #13
0
 public void OpenServerView(Slot slot, ref Connection connection,
     string dbName, string dbOwner)
 {
     Views[(int)slot] = null;
     Views[(int)slot] = new ServerObjectView(ref connection, dbName, dbOwner);
     //Views[(int)slot].LoadObjects();
 }
Пример #14
0
 //加载关卡表
 void LoadTable()
 {
     TextAsset binAsset = Resources.Load<TextAsset>("Data/Level01");
     string[] lineArray = binAsset.text.Split('\n');
     //读取行数设置
     int RowCount = int.Parse(lineArray[0]);
     Tables = new Slot[RowCount][];
     //初始化列表
     for (byte i = 0; i < RowCount; i++)
     {
         //偶数行=10,奇数行=9
         int columnCount = (i % 2 == 0 ? 10 : 9);
         Tables[i] = new Slot[columnCount];
         //读取配置信息,不足空槽补齐
         if (i + 1 < lineArray.Length)
         {
             string columnArray = lineArray[i + 1].Trim();
             for (byte j = 0; j < columnCount; j++)
                 Tables[i][j] = new Slot(SlotContain, i, j, columnArray[j]);
         }
         else
         {
             for (byte j = 0; j < columnCount; j++)
                 Tables[i][j] = new Slot(SlotContain, i, j);
         }
     }
 }
Пример #15
0
 private static Slot OffsetSlot(Slot slot, TimeSpan offset)
 {
     var newSlot = new Slot(slot);
     newSlot.Start = slot.Start.Add(offset);
     newSlot.End = slot.End.Add(offset);
     return newSlot;
 }
Пример #16
0
	// Use this for initialization
	void Start () {
		slot = GetComponent<Slot>();

		if (linesEnabled)
			createPaylines();

	}
Пример #17
0
        public CLCreatePC(Stream stream)
        {
            // read size
            this.BodySize = ReadUInt32(stream);

            // read timestamp
            this.TimeStamp = ReadUInt32(stream);

            // read Name
            this.Name = ReadString(stream);

            // read Slot
            this.Slot = (Slot)stream.ReadByte();

            // read BitSet
            this.BitSet = (byte)stream.ReadByte();

            // read Colors
            this.ColorHair = ReadUInt16(stream);
            this.ColorSkin = ReadUInt16(stream);
            this.ColorShirt = ReadUInt16(stream);
            this.ColorShirt2 = ReadUInt16(stream);
            this.ColorJeans = ReadUInt16(stream);
            this.ColorJeans2 = ReadUInt16(stream);

            // read STR DEX & INT
            this.STR = ReadUInt16(stream);
            this.DEX = ReadUInt16(stream);
            this.INT = ReadUInt16(stream);

            // read PCType
            this.PCType = (PCType)stream.ReadByte();
        }
Пример #18
0
        private bool CheckAllOccurrencesDestinationSlots(Occurrence currentOccurrence, Slot currentDestinationSlot, Occurrence editedOccurrence)
        {
            var currentApp = currentOccurrence.Appointment as Appointment;

            var offsetOfTheOccurrence = currentApp.Start - currentOccurrence.Start;
            var destSlotOfMasterApp = OffsetSlot(currentDestinationSlot, offsetOfTheOccurrence);

            var occurrences = currentApp.GetOccurrences(scheduleView.VisibleRange.Start, scheduleView.VisibleRange.End);

            destinationSlot = null;
            foreach (var occ in occurrences)
            {
                var occurrenceDestinationSlot = OffsetSlot(destSlotOfMasterApp, occ.Start - currentApp.Start);

                var appsInOccurrenceDestinationSlot = scheduleView.AppointmentsSource
                    .OfType<IAppointment>()
                    .Where((IAppointment a) => a != occ.Appointment)
                    .All((IAppointment a) => !ConflictChecking.AreOverlapping(a, occurrenceDestinationSlot, editedOccurrence));

                if (!appsInOccurrenceDestinationSlot)
                {
                    ShowErrorWindow();
                    return true;
                }
            }

            return false;
        }
Пример #19
0
    public static void SwapItems(Slot source, Slot destination)
    {
        ItemType movingType = source.CurrentItem.Item.Type;

        if (source != null && destination != null) {
            bool needToRecalculateStats = source.transform.parent == CharacterPanel.Instance.transform || destination.transform.parent == CharacterPanel.Instance.transform;

            if(destination.canContain == ItemType.GENERIC || movingType == destination.canContain) {
                Stack<ItemHolder> tempDestination = new Stack<ItemHolder>(destination.Items);

                destination.AddItems(source.Items);

                if(tempDestination.Count == 0) {
                    if (source.type == SlotType.CHARACTER && destination.type == SlotType.INVENTORY)
                        GameObject.Find("Inventory").GetComponent<Inventory>().EmptySlots--;
                    else if (source.type == SlotType.INVENTORY && destination.type == SlotType.CHARACTER)
                        GameObject.Find("Inventory").GetComponent<Inventory>().EmptySlots++;
                    source.ClearSlot();
                } else {
                    source.AddItems(tempDestination);
                }
            }

            if (needToRecalculateStats) {
                CharacterPanel.Instance.CalculateStats();
            }
        }
    }
Пример #20
0
 public override void Use(Slot slot, ItemHolder item)
 {
     if (slot.type == SlotType.INVENTORY)
         CharacterPanel.Instance.EquipItem(slot, item, Equip);
     else if (slot.type == SlotType.CHARACTER)
         CharacterPanel.Instance.UnequipItem(slot, item);
 }
Пример #21
0
    // Update the slot details
    public void Update(Slot slot)
    {
        _slot = slot;

        // slot data has an attachment
        if(_slot != null && _slot.Attachment != null){

            // we already have an attachment, make sure it's visible and update with new slot data.
            if(_attachment != null){
                _attachment.isVisible = true;
                _attachment.Update(_slot);

            // else we do not have an attachment already set
            }else{
                _attachment = new GSpineAttachment(_slot);
                AddChild(_attachment);
            }

        // slot is empty
        }else{

            // we currently have an attachment, so hide it
            if(_attachment != null){
                _attachment.isVisible = false;
            }
        }
    }
 public static string CreateDescription(Slot slot)
 {
     return string.Format("{0} - {1}-{2}",
                          slot.Field.Description,
                          slot.StartDateTime.ToShortTimeString(),
                          slot.EndDateTime.ToShortTimeString());
 }
Пример #23
0
 public override int TryReadPacket(byte[] buffer, int length)
 {
     int offset = 1;
     double x, y, z;
     ushort id, metadata;
     byte count;
     if (!DataUtility.TryReadInt32(buffer, ref offset, length, out EntityId))
         return -1;
     if (!DataUtility.TryReadUInt16(buffer, ref offset, length, out id))
         return -1;
     if (!DataUtility.TryReadByte(buffer, ref offset, length, out count))
         return -1;
     if (!DataUtility.TryReadUInt16(buffer, ref offset, length, out metadata))
         return -1;
     if (!DataUtility.TryReadAbsoluteInteger(buffer, ref offset, length, out x))
         return -1;
     if (!DataUtility.TryReadAbsoluteInteger(buffer, ref offset, length, out y))
         return -1;
     if (!DataUtility.TryReadAbsoluteInteger(buffer, ref offset, length, out z))
         return -1;
     if (!DataUtility.TryReadPackedByte(buffer, ref offset, length, out Rotation))
         return -1;
     if (!DataUtility.TryReadPackedByte(buffer, ref offset, length, out Pitch))
         return -1;
     if (!DataUtility.TryReadPackedByte(buffer, ref offset, length, out Yaw))
         return -1;
     Item = new Slot(id, count, metadata);
     Position = new Vector3(x, y, z);
     return offset;
 }
Пример #24
0
	void setSlots(){
		inventorySlots = new Slot[inventoryStorageWidth,inventoryStorageHeight];
		for(int x = 0; x < inventoryStorageWidth ; x++){
			for(int y = 0; y < inventoryStorageHeight ; y++){
				inventorySlots[x,y] = new Slot(new Rect(slotsOffsetX + slotWidth*x, slotsOffsetY + slotHeight*y, slotWidth, slotHeight));
			}
		}
	}
Пример #25
0
    public HandleBox(Slot slot)
    {
        this.slot = slot;

        base.Init(slot.player);

        contentContainer.AddChild(new FLabel("Raleway","H"));
    }
Пример #26
0
 public override bool GetDrop(ToolItem tool, out Slot[] drop)
 {
     drop = new[] { new Slot(new RedstoneItem(), (sbyte)MathHelper.Random.Next(4, 5)) };
     return tool is PickaxeItem &&
         (tool.ToolMaterial == ToolMaterial.Iron ||
         tool.ToolMaterial == ToolMaterial.Gold ||
         tool.ToolMaterial == ToolMaterial.Diamond);
 }
Пример #27
0
 public void ComboSlot(Slot slot, bool charge = true)
 {
     foreach (Card c in Cards) {
         if (c != null && c.Slot == slot) {
             c.Charged = charge;
         }
     }
 }
Пример #28
0
 public override bool GetDrop(ToolItem tool, out Slot[] drop)
 {
     drop = new[] { new Slot((ushort)new RedstoneItem(), (byte)DataUtility.Random.Next(4, 5)) };
     return tool is PickaxeItem &&
         (tool.ToolMaterial == ToolMaterial.Iron ||
         tool.ToolMaterial == ToolMaterial.Gold ||
         tool.ToolMaterial == ToolMaterial.Diamond);
 }
Пример #29
0
 public override bool GetDrop(ToolItem tool, out Slot[] drop)
 {
     if ((Metadata & 0xC) <= 4)
         drop = new[] { new Slot((ushort)new CocoaBeanItem(), 1) };
     else
         drop = new[] { new Slot((ushort)new CocoaBeanItem(), 3) };
     return true;
 }
Пример #30
0
	void Start() {
		slot = GameObject.Find ("BeachDays").GetComponent<Slot>();

		nfi = new CultureInfo( "en-US", false ).NumberFormat;
		nfi.CurrencyDecimalDigits = 0;

		updateUI();
	}
    //Move an Item to a new slot
    private void UseForceps(Slot slot)
    {
        Item item;

        if (slot.GetItem(out item))
        {
            //If first selection
            if (currentSelection == null)
            {
                this.currentSelection = slot;
                MoveUp(slot);
                SFX.Play("Item_lifted", 1f, 1f, 0f, false, 0f);
                //If not finished the tool tutorial
                if (!GameManager.Instance.TutorialIntroComplete)
                {
                    // Second selection.
                    tutorialManager.NextInstruction();
                    //Get prefab instance
                    GameObject obj;
                    if (slot.GetPrefabInstance(out obj))
                    {
                        tutorialManager.DestroySpecificItemIndicator(obj);
                    }
                }
            }
            else
            {
                // If the same item is selected, put it back.
                if (currentSelection == slot)
                {
                    Debug.Log("Same slot.");
                    MoveDown(slot);
                    currentSelection = null;
                    if (!GameManager.Instance.TutorialIntroComplete)
                    {
                        tutorialManager.StartItemIndicators();
                        tutorialManager.PreviousInstruction();
                    }
                    return;
                }

                // Make things make more sense.
                Slot slot1 = this.currentSelection;
                Slot slot2 = slot;

                // Move objects to other slot.
                GameObject obj1;
                GameObject obj2;
                // Move 1 item.
                if (slot1.GetPrefabInstance(out obj1) && slot2.GetPrefabInstance(out obj2))
                {
                    // Don't let user select while we're moving.
                    // TODO: let user select while moving?
                    canSelect = false;

                    tutorialManager.DestroySpecificItemIndicator(obj2);

                    Transform t1 = obj1.transform,
                              t2 = obj2.transform;

                    //SFX.Play("item_lift");
                    SFX.Play("Item_shifted", 1f, 1f, 0f, false, 0f);
                    MoveUp(slot1)
                    .OnComplete(() => t1.DOMove(slot2.transform.position + Vector3.up, 0.6f)
                                .SetEase(Ease.OutBack)
                                .OnComplete(() => t1.DOMove(slot2.transform.position, 1f).SetEase(Ease.OutBounce)));
                    MoveUp(slot2)
                    .OnComplete(() => t2.DOMove(slot1.transform.position + Vector3.up, 0.6f)
                                .SetEase(Ease.OutBack)
                                .OnComplete(() =>
                                            t2.DOMove(slot1.transform.position, 1f).SetEase(Ease.OutBounce)
                                            .OnComplete(() => canSelect = true).OnComplete(() => FinishForceps())));

                    // This is a bit janky, but might be doing physics based inventory soon, so not bothering.
                    t1.GetComponent <Rotate>().Enable = false;
                    t2.GetComponent <Rotate>().Enable = false;
                    SFX.Play("item_down", 1, 1, 1.5f);

                    ItemInstance inst1, inst2;
                    if (slot1.GetItemInstance(out inst1) && slot2.GetItemInstance(out inst2))
                    {
                        slot1.SetItemInstantiated(inst2, obj2);
                        slot2.SetItemInstantiated(inst1, obj1);
                        Inventory.Instance.SwapItem(slot1.index, slot2.index);
                    }
                    SaveManager.SaveInventory();
                    currentSelection = null;
                }
            }

            //Else if selected one item and clicked on null slot
        }
        else if (currentSelection && !slot.GetItem(out item) && canSelect)
        {
            Slot slot1 = this.currentSelection;
            Slot slot2 = slot;

            GameObject obj1;
            // If the slot we selected has something in it.
            if (slot1.GetPrefabInstance(out obj1))
            {
                //&& currentSelection.GetItemInstance(out inst1) &&
                canSelect = false;
                Transform t1 = obj1.transform;

                SFX.Play("item_lift");
                MoveUp(slot1)
                .OnComplete(() => t1.DOMove(slot2.transform.position + Vector3.up, 0.6f).SetEase(Ease.OutBack)
                            .OnComplete(() =>
                                        t1.DOMove(slot2.transform.position, 1f).SetEase(Ease.OutBounce)
                                        .OnComplete(() => canSelect = true).OnComplete(() => FinishForceps())));
                t1.GetComponent <Rotate>().Enable = false;
                SFX.Play("item_down", 1, 1, 1.5f);

                ItemInstance inst1;
                if (slot1.GetItemInstance(out inst1))
                {
                    slot1.RemoveDontDestroy();
                    slot2.SetItemInstantiated(inst1, obj1);
                    Inventory.Instance.SwapItem(slot1.index, slot2.index);
                }
                SaveManager.SaveInventory();

                currentSelection = null;
            }

            currentSelection = null;
        }
    }
    private void UseWand(Slot slot)
    {
        Item         item;
        ItemInstance instance;

        // Minigame detection.
        if (!GameManager.Instance.TutorialIntroComplete)
        {
            tutorialManager.FinishWandUse();
        }

        if (currentSelection == null && slot.GetItemInstance(out instance) && slot.GetItem(out item) &&
            tutorialManager.InspectedAllItems())
        {
            PlayWandParticles(slot);
            GameManager.Instance.TutorialIntroComplete = true;
            Debug.Log("got something:" + instance.item);
            currentSelection = slot;
            _minigameType    = item.GetType().ToString();
            switch (item.GetType().ToString())
            {
            case "Gem":
                GameManager.Instance.GemTypeTransfer = (item as Gem).gemType;
                Initiate.Fade("Cutting", Color.black, 2f);
                MinigameTransition();
                break;

            case "Jewel":
                GameManager.Instance.GemTypeTransfer = (item as Jewel).gemType;
                GameManager.Instance.QualityTransfer = instance.Quality;
                Initiate.Fade("Polishing", Color.black, 2f);
                MinigameTransition();
                break;

            case "Ore":
                Initiate.Fade("Smelting", Color.black, 2f);
                MinigameTransition();
                break;

            case "Brick":
                GameManager.Instance.QualityTransfer = instance.Quality;
                Initiate.Fade("Tracing", Color.black, 2f);
                MinigameTransition();
                break;

            case "ChargedJewel":
                MoveUp(slot);
                if (TutorialProgressChecker.Instance.readyGolem && GameManager.Instance.InTutorial)
                {
                    tutorialManager.NextInstruction();
                }
                break;

            case "Shell":
                MoveUp(slot);
                if (TutorialProgressChecker.Instance.readyGolem && GameManager.Instance.InTutorial)
                {
                    tutorialManager.NextInstruction();
                }
                break;
            }
        }
        else if (currentSelection != null && currentSelection != slot)
        {
            Debug.Log("Wanting to combine...");
            Item item1, item2;
            if (currentSelection.GetItem(out item1) && slot.GetItem(out item2))
            {
                // TODO: could you do some xor magic here?
                if (item1.GetType() == typeof(Shell) && item2.GetType() == typeof(ChargedJewel) ||
                    item1.GetType() == typeof(ChargedJewel) && item2.GetType() == typeof(Shell))
                {
                    // Check for a free slot.
                    if (ShonkyInventory.Instance.FreeSlot())
                    {
                        //If in tutorial, remove the rune indicator
                        if (!GameManager.Instance.TutorialGolemMade)
                        {
                            GameObject obj1, obj2;
                            if (currentSelection.GetPrefabInstance(out obj1) && slot.GetPrefabInstance(out obj2))
                            {
                                tutorialManager.DestroySpecificItemIndicator(obj1);
                                tutorialManager.DestroySpecificItemIndicator(obj2);
                            }
                        }

                        tutorialManager.HideExposition();
                        golemCombiner.GolemAnimationSequence(currentSelection, item1, slot, item2);
                    }
                    else
                    {
                        GameObject itemObj;
                        if (currentSelection.GetPrefabInstance(out itemObj))
                        {
                            MoveDown(currentSelection);
                            currentSelection = null;
                        }
                    }
                }
                else
                {
                    HideInspector();
                }
            }
            else
            {
                HideInspector();
            }
        }
    }
    private void ResourcePouchOpen(Slot slot)
    {
        // Hard coded for now.  To do this dynamically, maybe put <names,chances> in a dictionary<string, float>.
        float gemChance = 0.4f,
              oreChance = 1.00f;
        int numberItems = UnityEngine.Random.Range(6, 12);

        SFX.Play("Res_pouch_open", 1f, 1f, 0f, false, 0f);

        //if (GameManager.Instance.OpenPouch)
        //tutorialManager.PouchText();

        //SFX.Play("sound");
        var drops = new List <ItemInstance>();

        for (int i = 0; i < numberItems; i++)
        {
            string dropName;
            string gem = DetermineGemToDrop(slot);
            Debug.Log("Gemtype to drop is " + gem);
            float spin = UnityEngine.Random.Range(0, 1f);
            if (spin < gemChance)
            {
                dropName = gem;
            }
            else if (spin < oreChance)
            {
                dropName = "Ore";
                //This was for testing and it does drop the correct gems
                //dropName = DetermineGemToDrop();
            }
            else
            {
                dropName = null;
            }

            // Item is not new for now.
            if (dropName != null)
            {
                drops.Add(new ItemInstance(dropName, 1, Quality.QualityGrade.Unset, false));
            }
        }

        Inventory inv = Inventory.Instance;

        slot.RemoveItem();
        inv.RemoveItem(slot.index);

        foreach (ItemInstance drop in drops)
        {
            int pos = inv.InsertItem(drop);
            // If found a slot to place item.
            if (pos != -1)
            {
                Slot       toSlot = tutInventory.GetSlotAtIndex(pos);
                GameObject clone  = Instantiate(drop.item.physicalRepresentation, slot.transform.position, slot.transform.rotation);

                // Kind of a placeholder animation.
                // TODO: randomize the Vector3.up a little so that the items separate when they go up.
                clone.transform.DOMove(clone.transform.position + Vector3.up, 0.7f).SetEase(Ease.OutBack)
                .OnComplete(() => clone.transform.DOMove(toSlot.transform.position + Vector3.up, 0.6f).SetEase(Ease.OutBack)
                            .OnComplete(() => clone.transform.DOMove(toSlot.transform.position, 1f).SetEase(Ease.OutBounce)));

                toSlot.SetItemInstantiated(drop, clone);
            }
        }
        if (GameManager.Instance.InTutorial)
        {
            Debug.Log("Finished phase 1 of tutorial");
            tutorialManager.FinishTutorial();
            GameManager.Instance.InTutorial = false;
            GameManager.Instance.InMap      = true;
        }
    }
Пример #34
0
 public static Color GetColor(this Slot s)
 {
     return(new Color(s.r, s.g, s.b, s.a));
 }
Пример #35
0
 public static Color GetColorTintBlack(this Slot s)
 {
     return(new Color(s.r2, s.g2, s.b2, 1f));
 }
        private void CreateFreeSpace()
        {
            Slot slot = _container.AllocateSlot(Size);

            _container.Free(slot);
        }
Пример #37
0
 protected void AddSlot(int i, Slot slot)
 {
     m_allSlots[i] = slot;
     m_freeSlots.AddLast(slot);
 }
Пример #38
0
        public void Start()
        {
            if (inv == null)
            {
                return;
            }

            var b = Instantiate(dragObj, canvas.transform);

            b.name = $"DRAGITEMOBJ_{name}_{UnityEngine.Random.Range(int.MinValue, int.MaxValue)}";
            b.AddComponent <DragSlot>();
            b.SetActive(false);
            if (hideDragObj)
            {
                b.hideFlags = HideFlags.HideInHierarchy;
            }
            dragObj = b;

            InventoryController.inventoriesUI.Add(this);
            if (!generateUIFromSlotPrefab)
            {
                for (int i = 0; i < slots.Count; i++)
                {
                    slots[i].name = i.ToString();
                    for (int j = 0; j < slots[i].transform.childCount; j++)
                    {
                        Image image;
                        if (slots[i].transform.GetChild(j).TryGetComponent <Image>(out image))
                        {
                            ItemDragHandler drag;
                            if (slots[i].transform.GetChild(j).TryGetComponent(out drag))
                            {
                                drag.canvas = canvas;
                                drag.invUI  = this;
                            }
                            else
                            {
                                drag        = slots[i].transform.GetChild(j).gameObject.AddComponent <ItemDragHandler>();
                                drag.canvas = canvas;
                                drag.invUI  = this;
                            }

                            Tooltip tooltip;
                            if (slots[i].transform.GetChild(j).TryGetComponent(out tooltip))
                            {
                                tooltip.canvas  = canvas;
                                tooltip.invUI   = this;
                                tooltip.slotNum = i;
                            }
                            else
                            {
                                tooltip         = slots[i].transform.GetChild(j).gameObject.AddComponent <Tooltip>();
                                tooltip.canvas  = canvas;
                                tooltip.invUI   = this;
                                tooltip.slotNum = i;
                            }
                        }
                    }
                }
            }

            if (!canvas.TryGetComponent(out ItemDropHandler _))
            {
                canvas.gameObject.AddComponent <ItemDropHandler>();
            }

            if (isCraftInventory)
            {
                for (int i = 0; i < gridSize.x * gridSize.y; i++)
                {
                    pattern.Add(null);
                    amount.Add(0);
                }

                for (int i = 0; i < productSlotsIndex.Length; i++)
                {
                    inv.slots[productSlotsIndex[i]] = Slot.SetSlotProperties(inv[i], true, SlotProtection.Remove | SlotProtection.Swap, null);
                }
            }
        }
Пример #39
0
 public MapSearchNode(AStarPathfinder _pathfinder)
 {
     start_point = new Slot(0, 0);
     pathfinder  = _pathfinder;
 }
Пример #40
0
        static void Main(string[] args)
        {
            try
            {
                // Инициализировать библиотеку
                Console.WriteLine("Library initialization");
                using (var pkcs11 = new Pkcs11(Settings.RutokenEcpDllDefaultPath, Settings.OsLockingDefault))
                {
                    // Получить доступный слот
                    Console.WriteLine("Checking tokens available");
                    Slot slot = Helpers.GetUsableSlot(pkcs11);

                    // Открыть RW сессию в первом доступном слоте
                    Console.WriteLine("Opening RW session");
                    using (Session session = slot.OpenSession(false))
                    {
                        // Выполнить аутентификацию Пользователя
                        Console.WriteLine("User authentication");
                        session.Login(CKU.CKU_USER, SampleConstants.NormalUserPin);

                        try
                        {
                            // Получить массив хэндлов объектов, соответствующих критериям поиска
                            Console.WriteLine("Getting key pairs...");
                            var foundObjects = new List <ObjectHandle>();
                            foreach (var keyPairAttributes in KeyPairsAttributes)
                            {
                                foundObjects.AddRange(session.FindAllObjects(keyPairAttributes));
                            }

                            // Удалить ключи
                            if (foundObjects.Count > 0)
                            {
                                Console.WriteLine("Destroying objects...");
                                int objectsCounter = 1;
                                foreach (var foundObject in foundObjects)
                                {
                                    Console.WriteLine($"   Object №{objectsCounter}");
                                    session.DestroyObject(foundObject);
                                    objectsCounter++;
                                }

                                Console.WriteLine("Objects have been destroyed successfully");
                            }
                            else
                            {
                                Console.WriteLine("No objects found");
                            }
                        }
                        finally
                        {
                            // Сбросить права доступа как в случае исключения,
                            // так и в случае успеха.
                            // Сессия закрывается автоматически.
                            session.Logout();
                        }
                    }
                }
            }
            catch (Pkcs11Exception ex)
            {
                Console.WriteLine($"Operation failed [Method: {ex.Method}, RV: {ex.RV}]");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Operation failed [Message: {ex.Message}]");
            }
        }
Пример #41
0
        public Mesh GenerateMesh(Skeleton skeleton)
        {
            int totalVertexCount   = 0;           // size of vertex arrays
            int totalTriangleCount = 0;           // size of index array

            // Step 1 : Count verts and tris to determine array sizes.
            //
            var drawOrderItems = skeleton.drawOrder.Items;
            int drawOrderCount = skeleton.drawOrder.Count;

            for (int i = 0; i < drawOrderCount; i++)
            {
                Slot       slot = drawOrderItems[i];
                Attachment attachment = slot.attachment;
                int        attachmentVertexCount, attachmentTriangleCount;
                var        regionAttachment = attachment as RegionAttachment;
                if (regionAttachment != null)
                {
                    attachmentVertexCount   = 4;
                    attachmentTriangleCount = 6;
                }
                else
                {
                    if (!renderMeshes)
                    {
                        continue;
                    }
                    var meshAttachment = attachment as MeshAttachment;
                    if (meshAttachment != null)
                    {
                        attachmentVertexCount   = meshAttachment.vertices.Length >> 1;
                        attachmentTriangleCount = meshAttachment.triangles.Length;
                    }
                    else
                    {
                        var skinnedMeshAttachment = attachment as WeightedMeshAttachment;
                        if (skinnedMeshAttachment != null)
                        {
                            attachmentVertexCount   = skinnedMeshAttachment.uvs.Length >> 1;
                            attachmentTriangleCount = skinnedMeshAttachment.triangles.Length;
                        }
                        else
                        {
                            continue;
                        }
                    }
                }
                totalTriangleCount += attachmentTriangleCount;
                totalVertexCount   += attachmentVertexCount;
            }


            // Step 2 : Prepare vertex arrays.
            //
            Vector3[] vertices        = this.vertices;
            bool      verticesDontFit = vertices == null || totalVertexCount > vertices.Length;

            if (verticesDontFit)
            {
                // Not enough space, increase size.
                this.vertices = vertices = new Vector3[totalVertexCount];
                this.colors   = new Color32[totalVertexCount];
                this.uvs      = new Vector2[totalVertexCount];
            }
            else
            {
                // Too many vertices, zero the extra.
                Vector3 zero = Vector3.zero;
                for (int i = totalVertexCount, n = vertices.Length; i < n; i++)
                {
                    vertices[i] = zero;
                }
            }


            // Step 3 : Push vertices to arrays
            //
            const float z = 0;
            const float zFauxHalfThickness = 0.01f;             // Somehow needs this thickness for bounds to work properly in some cases (eg, Unity UI clipping)

            float[]   tempVertices = this.tempVertices;
            Vector2[] uvs          = this.uvs;
            Color32[] colors       = this.colors;
            int       vertexIndex  = 0;
            Color32   color;
            float     a = skeleton.a * 255, r = skeleton.r, g = skeleton.g, b = skeleton.b;

            Vector3 meshBoundsMin;
            Vector3 meshBoundsMax;

            if (totalVertexCount == 0)
            {
                meshBoundsMin = new Vector3(0, 0, 0);
                meshBoundsMax = new Vector3(0, 0, 0);
            }
            else
            {
                meshBoundsMin.x = int.MaxValue;
                meshBoundsMin.y = int.MaxValue;
                meshBoundsMax.x = int.MinValue;
                meshBoundsMax.y = int.MinValue;
                meshBoundsMin.z = -zFauxHalfThickness;
                meshBoundsMax.z = zFauxHalfThickness;

                int i = 0;
                do
                {
                    Slot       slot             = drawOrderItems[i];
                    Attachment attachment       = slot.attachment;
                    var        regionAttachment = attachment as RegionAttachment;
                    if (regionAttachment != null)
                    {
                        regionAttachment.ComputeWorldVertices(slot.bone, tempVertices);

                        float x1 = tempVertices[RegionAttachment.X1], y1 = tempVertices[RegionAttachment.Y1];
                        float x2 = tempVertices[RegionAttachment.X2], y2 = tempVertices[RegionAttachment.Y2];
                        float x3 = tempVertices[RegionAttachment.X3], y3 = tempVertices[RegionAttachment.Y3];
                        float x4 = tempVertices[RegionAttachment.X4], y4 = tempVertices[RegionAttachment.Y4];
                        vertices[vertexIndex].x     = x1 * scale; vertices[vertexIndex].y = y1 * scale;     vertices[vertexIndex].z = z;
                        vertices[vertexIndex + 1].x = x4 * scale; vertices[vertexIndex + 1].y = y4 * scale; vertices[vertexIndex + 1].z = z;
                        vertices[vertexIndex + 2].x = x2 * scale; vertices[vertexIndex + 2].y = y2 * scale; vertices[vertexIndex + 2].z = z;
                        vertices[vertexIndex + 3].x = x3 * scale; vertices[vertexIndex + 3].y = y3 * scale; vertices[vertexIndex + 3].z = z;

                        color.a = (byte)(a * slot.a * regionAttachment.a);
                        color.r = (byte)(r * slot.r * regionAttachment.r * color.a);
                        color.g = (byte)(g * slot.g * regionAttachment.g * color.a);
                        color.b = (byte)(b * slot.b * regionAttachment.b * color.a);
                        if (slot.data.blendMode == BlendMode.additive)
                        {
                            color.a = 0;
                        }
                        colors[vertexIndex] = color; colors[vertexIndex + 1] = color; colors[vertexIndex + 2] = color; colors[vertexIndex + 3] = color;

                        float[] regionUVs = regionAttachment.uvs;
                        uvs[vertexIndex].x     = regionUVs[RegionAttachment.X1]; uvs[vertexIndex].y = regionUVs[RegionAttachment.Y1];
                        uvs[vertexIndex + 1].x = regionUVs[RegionAttachment.X4]; uvs[vertexIndex + 1].y = regionUVs[RegionAttachment.Y4];
                        uvs[vertexIndex + 2].x = regionUVs[RegionAttachment.X2]; uvs[vertexIndex + 2].y = regionUVs[RegionAttachment.Y2];
                        uvs[vertexIndex + 3].x = regionUVs[RegionAttachment.X3]; uvs[vertexIndex + 3].y = regionUVs[RegionAttachment.Y3];

                        // Calculate min/max X
                        if (x1 < meshBoundsMin.x)
                        {
                            meshBoundsMin.x = x1;
                        }
                        else if (x1 > meshBoundsMax.x)
                        {
                            meshBoundsMax.x = x1;
                        }
                        if (x2 < meshBoundsMin.x)
                        {
                            meshBoundsMin.x = x2;
                        }
                        else if (x2 > meshBoundsMax.x)
                        {
                            meshBoundsMax.x = x2;
                        }
                        if (x3 < meshBoundsMin.x)
                        {
                            meshBoundsMin.x = x3;
                        }
                        else if (x3 > meshBoundsMax.x)
                        {
                            meshBoundsMax.x = x3;
                        }
                        if (x4 < meshBoundsMin.x)
                        {
                            meshBoundsMin.x = x4;
                        }
                        else if (x4 > meshBoundsMax.x)
                        {
                            meshBoundsMax.x = x4;
                        }

                        // Calculate min/max Y
                        if (y1 < meshBoundsMin.y)
                        {
                            meshBoundsMin.y = y1;
                        }
                        else if (y1 > meshBoundsMax.y)
                        {
                            meshBoundsMax.y = y1;
                        }
                        if (y2 < meshBoundsMin.y)
                        {
                            meshBoundsMin.y = y2;
                        }
                        else if (y2 > meshBoundsMax.y)
                        {
                            meshBoundsMax.y = y2;
                        }
                        if (y3 < meshBoundsMin.y)
                        {
                            meshBoundsMin.y = y3;
                        }
                        else if (y3 > meshBoundsMax.y)
                        {
                            meshBoundsMax.y = y3;
                        }
                        if (y4 < meshBoundsMin.y)
                        {
                            meshBoundsMin.y = y4;
                        }
                        else if (y4 > meshBoundsMax.y)
                        {
                            meshBoundsMax.y = y4;
                        }

                        vertexIndex += 4;
                    }
                    else
                    {
                        if (!renderMeshes)
                        {
                            continue;
                        }
                        var meshAttachment = attachment as MeshAttachment;
                        if (meshAttachment != null)
                        {
                            int meshVertexCount = meshAttachment.vertices.Length;
                            if (tempVertices.Length < meshVertexCount)
                            {
                                this.tempVertices = tempVertices = new float[meshVertexCount];
                            }
                            meshAttachment.ComputeWorldVertices(slot, tempVertices);

                            color.a = (byte)(a * slot.a * meshAttachment.a);
                            color.r = (byte)(r * slot.r * meshAttachment.r * color.a);
                            color.g = (byte)(g * slot.g * meshAttachment.g * color.a);
                            color.b = (byte)(b * slot.b * meshAttachment.b * color.a);
                            if (slot.data.blendMode == BlendMode.additive)
                            {
                                color.a = 0;
                            }

                            float[] meshUVs = meshAttachment.uvs;
                            for (int ii = 0; ii < meshVertexCount; ii += 2, vertexIndex++)
                            {
                                float x = tempVertices[ii], y = tempVertices[ii + 1];
                                vertices[vertexIndex].x = x * scale; vertices[vertexIndex].y = y * scale; vertices[vertexIndex].z = z;
                                colors[vertexIndex]     = color;
                                uvs[vertexIndex].x      = meshUVs[ii]; uvs[vertexIndex].y = meshUVs[ii + 1];

                                if (x < meshBoundsMin.x)
                                {
                                    meshBoundsMin.x = x;
                                }
                                else if (x > meshBoundsMax.x)
                                {
                                    meshBoundsMax.x = x;
                                }

                                if (y < meshBoundsMin.y)
                                {
                                    meshBoundsMin.y = y;
                                }
                                else if (y > meshBoundsMax.y)
                                {
                                    meshBoundsMax.y = y;
                                }
                            }
                        }
                        else
                        {
                            var skinnedMeshAttachment = attachment as WeightedMeshAttachment;
                            if (skinnedMeshAttachment != null)
                            {
                                int meshVertexCount = skinnedMeshAttachment.uvs.Length;
                                if (tempVertices.Length < meshVertexCount)
                                {
                                    this.tempVertices = tempVertices = new float[meshVertexCount];
                                }
                                skinnedMeshAttachment.ComputeWorldVertices(slot, tempVertices);

                                color.a = (byte)(a * slot.a * skinnedMeshAttachment.a);
                                color.r = (byte)(r * slot.r * skinnedMeshAttachment.r * color.a);
                                color.g = (byte)(g * slot.g * skinnedMeshAttachment.g * color.a);
                                color.b = (byte)(b * slot.b * skinnedMeshAttachment.b * color.a);
                                if (slot.data.blendMode == BlendMode.additive)
                                {
                                    color.a = 0;
                                }

                                float[] meshUVs = skinnedMeshAttachment.uvs;
                                for (int ii = 0; ii < meshVertexCount; ii += 2, vertexIndex++)
                                {
                                    float x = tempVertices[ii], y = tempVertices[ii + 1];
                                    vertices[vertexIndex].x = x * scale; vertices[vertexIndex].y = y * scale; vertices[vertexIndex].z = z;
                                    colors[vertexIndex]     = color;
                                    uvs[vertexIndex].x      = meshUVs[ii]; uvs[vertexIndex].y = meshUVs[ii + 1];

                                    if (x < meshBoundsMin.x)
                                    {
                                        meshBoundsMin.x = x;
                                    }
                                    else if (x > meshBoundsMax.x)
                                    {
                                        meshBoundsMax.x = x;
                                    }

                                    if (y < meshBoundsMin.y)
                                    {
                                        meshBoundsMin.y = y;
                                    }
                                    else if (y > meshBoundsMax.y)
                                    {
                                        meshBoundsMax.y = y;
                                    }
                                }
                            }
                        }
                    }
                } while (++i < drawOrderCount);
            }


            // Step 3 : Ensure correct triangle array size
            //
            var  triangles        = this.triangles;
            bool trianglesDontFit = triangles == null || totalTriangleCount > triangles.Length;

            if (trianglesDontFit)
            {
                // Not enough space, increase size
                this.triangles = triangles = new int[totalTriangleCount];
            }
            else
            {
                // Too many indices, zero the extra.
                for (int i = totalTriangleCount, n = triangles.Length; i < n; i++)
                {
                    triangles[i] = 0;
                }
            }


            // Step 4 : Push triangles to triangle array.
            //
            int triangleArrayIndex    = 0;          // next triangle index. modified by loop
            int firstAttachmentVertex = 0;

            for (int i = 0, n = drawOrderCount; i < n; i++)
            {
                Attachment attachment = drawOrderItems[i].attachment;

                if (attachment is RegionAttachment)
                {
                    triangles[triangleArrayIndex]     = firstAttachmentVertex;
                    triangles[triangleArrayIndex + 1] = firstAttachmentVertex + 2;
                    triangles[triangleArrayIndex + 2] = firstAttachmentVertex + 1;
                    triangles[triangleArrayIndex + 3] = firstAttachmentVertex + 2;
                    triangles[triangleArrayIndex + 4] = firstAttachmentVertex + 3;
                    triangles[triangleArrayIndex + 5] = firstAttachmentVertex + 1;

                    triangleArrayIndex    += 6;
                    firstAttachmentVertex += 4;
                    continue;
                }
                else
                {
                    if (!renderMeshes)
                    {
                        continue;
                    }
                    int[] attachmentTriangles;
                    int   attachmentVertexCount;
                    var   meshAttachment = attachment as MeshAttachment;
                    if (meshAttachment != null)
                    {
                        attachmentVertexCount = meshAttachment.vertices.Length >> 1;                         //  length/2
                        attachmentTriangles   = meshAttachment.triangles;
                    }
                    else
                    {
                        var skinnedMeshAttachment = attachment as WeightedMeshAttachment;
                        if (skinnedMeshAttachment != null)
                        {
                            attachmentVertexCount = skinnedMeshAttachment.uvs.Length >> 1;                             // length/2
                            attachmentTriangles   = skinnedMeshAttachment.triangles;
                        }
                        else
                        {
                            continue;
                        }
                    }

                    for (int ii = 0, nn = attachmentTriangles.Length; ii < nn; ii++, triangleArrayIndex++)
                    {
                        triangles[triangleArrayIndex] = firstAttachmentVertex + attachmentTriangles[ii];
                    }

                    firstAttachmentVertex += attachmentVertexCount;
                }
            }


            // Step 5 : Push Data To Mesh
            //
            var mesh = doubleBufferedMesh.GetNextMesh();

            mesh.vertices = vertices;
            mesh.colors32 = colors;
            mesh.uv       = uvs;

            Vector3 meshBoundsExtents = (meshBoundsMax - meshBoundsMin) * scale;

            mesh.bounds = new Bounds(meshBoundsMin + meshBoundsExtents * 0.5f, meshBoundsExtents);

            mesh.SetTriangles(triangles, 0);

            return(mesh);
        }
Пример #42
0
 protected virtual void AssertSlot(Slot expected, Slot actual)
 {
     Assert.AreEqual(expected, actual);
 }
Пример #43
0
    private void Update()
    {
        if (ChangeSlot)
        {
            ChangePosition();
            if (Input.GetKeyDown(KeyCode.Mouse0))
            {
                Debug.Log(currentSlot.getPosition());
                currentSlot = null;
                ChangeSlot  = false;
            }
        }
        else
        if (Input.GetKeyDown(KeyCode.Mouse0))
        {
            Inventory inv = GameController.FindInventory();
            if (inv != null)
            {
                Vector2Int coord = FindSlot(inv); // Posição no Array2D
                Slot       slot  = inv.Get(coord.x, coord.y);
                if (slot != null)
                {
                    if (Input.GetKey(KeyCode.LeftControl) && (inv as ISizeFixed) != null)
                    {
                        ChangeSlot  = true;
                        currentSlot = slot;
                        //ChangePosition(slot);
                    }
                    Item       item     = slot.getItem();
                    Vector2Int position = slot.getPosition();

                    Slot current = GameController.currentHand;
                    // Não tem item no Slot && Tem  item na mão
                    if (item == null && current != null)
                    {
                        if (inv.Set(current.getItem(), coord, current.getAmount()))
                        {
                            GameController.currentHand = null;
                        }
                    }
                    else
                    // Tem item no Slot && Não tem item na mão
                    if (slot.itemExists && current == null)
                    {
                        GameController.currentHand = (Slot)slot.Clone();
                        slot.removeItem();
                    }
                    else
                    // Tem item no slot && Tem item na mão
                    if (slot.itemExists && current != null)
                    {
                        if (item.isItem(current.getItem().getID()))
                        {
                            slot.addAmount(current.getAmount());
                            GameController.currentHand = null;
                        }
                        else
                        {
                            if (inv.Set(current.getItem(), coord, current.getAmount()))
                            {
                                GameController.currentHand = slot;
                            }
                        }
                    }
                }
            }
        }
    }
Пример #44
0
        static void Main(string[] args)
        {
            try
            {
                // Инициализировать библиотеку
                Console.WriteLine("Library initialization");
                using (var pkcs11 = new Pkcs11(Settings.RutokenEcpDllDefaultPath, Settings.OsLockingDefault))
                {
                    // Получить доступный слот
                    Console.WriteLine("Checking tokens available");
                    Slot slot = Helpers.GetUsableSlot(pkcs11);

                    // Определение поддерживаемых токеном механизмов
                    Console.WriteLine("Checking mechanisms available");
                    List <CKM> mechanisms = slot.GetMechanismList();
                    Errors.Check(" No mechanisms available", mechanisms.Count > 0);
                    bool isGostR3410_512Supported    = mechanisms.Contains((CKM)Extended_CKM.CKM_GOSTR3410_512);
                    bool isGostR3411_12_512Supported = mechanisms.Contains((CKM)Extended_CKM.CKM_GOSTR3411_12_512);
                    Errors.Check(" CKM_GOSTR3410_512 isn`t supported!", isGostR3410_512Supported);
                    Errors.Check(" CKM_GOSTR3411_12_512 isn`t supported!", isGostR3411_12_512Supported);

                    // Открыть RW сессию в первом доступном слоте
                    Console.WriteLine("Opening RW session");
                    using (Session session = slot.OpenSession(false))
                    {
                        // Выполнить аутентификацию Пользователя
                        Console.WriteLine("User authentication");
                        session.Login(CKU.CKU_USER, SampleConstants.NormalUserPin);

                        try
                        {
                            // Получить данные для вычисления подписи
                            byte[] sourceData = SampleData.Digest_Gost3411_SourceData;

                            // Получить приватный ключ для генерации подписи
                            Console.WriteLine("Getting private key...");
                            List <ObjectHandle> privateKeys = session.FindAllObjects(PrivateKeyAttributes);
                            Errors.Check("No private keys found", privateKeys.Count > 0);

                            // Инициализировать операцию хэширования
                            var mechanism = new Mechanism((uint)Extended_CKM.CKM_GOSTR3411_12_512);

                            // Вычислить хэш-код данных
                            Console.WriteLine("Hashing data...");
                            byte[] hash = session.Digest(mechanism, sourceData);

                            // Распечатать буфер, содержащий хэш-код
                            Console.WriteLine(" Hashed buffer is:");
                            Helpers.PrintByteArray(hash);
                            Console.WriteLine("Hashing has been completed successfully");

                            // Инициализация операции подписи данных по алгоритму ГОСТ Р 34.10-2001
                            var signMechanism = new Mechanism((uint)Extended_CKM.CKM_GOSTR3410_512);

                            // Подписать данные
                            Console.WriteLine("Signing data...");
                            byte[] signature = session.Sign(signMechanism, privateKeys[0], hash);

                            // Распечатать буфер, содержащий подпись
                            Console.WriteLine(" Signature buffer is:");
                            Helpers.PrintByteArray(signature);
                            Console.WriteLine("Data has been signed successfully");

                            // Получить публичный ключ для проверки подписи
                            Console.WriteLine("Getting public key...");
                            List <ObjectHandle> publicKeys = session.FindAllObjects(PublicKeyAttributes);
                            Errors.Check("No public keys found", publicKeys.Count > 0);

                            // Проверка подписи для данных
                            Console.WriteLine("Verifying data...");
                            bool isSignatureValid = false;
                            session.Verify(signMechanism, publicKeys[0], hash, signature, out isSignatureValid);

                            if (isSignatureValid)
                            {
                                Console.WriteLine("Verifying has been completed successfully");
                            }
                            else
                            {
                                throw new InvalidOperationException("Invalid signature");
                            }
                        }
                        finally
                        {
                            // Сбросить права доступа как в случае исключения,
                            // так и в случае успеха.
                            // Сессия закрывается автоматически.
                            session.Logout();
                        }
                    }
                }
            }
            catch (Pkcs11Exception ex)
            {
                Console.WriteLine($"Operation failed [Method: {ex.Method}, RV: {ex.RV}]");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Operation failed [Message: {ex.Message}]");
            }
        }
Пример #45
0
        //private void OpenErrorPage(string error)
        //{
        //    UIBuilder uiBuilder = this.SwapPanel(NeosSwapCanvasPanel.Slide.Left, 0.5f);
        //    uiBuilder.VerticalLayout(4f, 0.0f, new Alignment?());
        //    uiBuilder.Style.PreferredHeight = 32f;
        //    uiBuilder.Style.MinHeight = 32f;
        //    uiBuilder.Style.FlexibleHeight = 100f;
        //    LocaleString text1 = (LocaleString)error;
        //    uiBuilder.Text(in text1, true, new Alignment?(), true, (string)null);
        //    uiBuilder.Style.FlexibleHeight = -1f;
        //    LocaleString text2 = "CameraControl.OBS.ReturnToConnect".AsLocaleKey((string)null, true, (Dictionary<string, IField>)null);
        //    uiBuilder.Button(in text2, new ButtonEventHandler(this.OnReturnToConnect));
        //}

        public void LinkUISlot()
        {
            UniLog.Log("Linking UI slot");
            //Slot slot = UISlot.Duplicate();
            Slot slot = UISlot ?? _uiTemplateRefField.Target.Reference.Target;

            UniLog.Log(slot);
            DynamicVariableSpace space = slot.FindSpace("UIVariables");

            if (space == null)
            {
                return;
            }
            UniLog.Log("Found dynamic variable space");

            ////Recording checkbox
            //Checkbox recording_checkbox;
            //space.TryReadValue<Checkbox>("recording_checkbox", out recording_checkbox);
            //this._recordUserCheckbox.Target = recording_checkbox;

            ////Data submission checkbox
            //Checkbox public_checkbox;
            //space.TryReadValue<Checkbox>("public_checkbox", out public_checkbox);
            //this._publicDomainCheckbox.Target = public_checkbox;

            //Recording time
            Text recording_time_text;

            space.TryReadValue <Text>("recording_time_text", out recording_time_text);
            this._recordingTime.Target = recording_time_text;

            //Animation checkbox
            Checkbox animation_checkbox;

            space.TryReadValue <Checkbox>("animation_checkbox", out animation_checkbox);
            this._animationsCheckbox.Target = animation_checkbox;

            //Generate Bvh checkbox
            Checkbox generate_bvh_checkbox;

            space.TryReadValue <Checkbox>("generate_bvh_checkbox", out generate_bvh_checkbox);
            this._generateBvhCheckbox.Target = generate_bvh_checkbox;

            //Record voices checkbox
            Checkbox record_voices_checkbox;

            space.TryReadValue <Checkbox>("record_voices_checkbox", out record_voices_checkbox);
            this._recordVoicesCheckbox.Target = record_voices_checkbox;

#if NOHL
            //Record voices checkbox
            Checkbox record_hearing_checkbox;
            space.TryReadValue <Checkbox>("record_hearing_checkbox", out record_hearing_checkbox);
            this._recordHearingCheckbox.Target = record_hearing_checkbox;
#endif

#if NOHL
            //Video checkbox
            Checkbox video_checkbox;
            space.TryReadValue <Checkbox>("video_checkbox", out video_checkbox);
            this._videoCheckbox.Target = video_checkbox;
#endif

            //Record button
            Button record_button;
            space.TryReadValue <Button>("record_button", out record_button);
            this._recordButton.Target = record_button;

            //Recording index
            TextField recording_index;
            space.TryReadValue <TextField>("recording_index", out recording_index);
            this._recordIndexField.Target = recording_index;

            //Voices checkbox
            Checkbox voices_checkbox;
            space.TryReadValue <Checkbox>("voices_checkbox", out voices_checkbox);
            this._voicesCheckbox.Target = voices_checkbox;

            //Hearing checkbox
            Checkbox hearing_checkbox;
            space.TryReadValue <Checkbox>("hearing_checkbox", out hearing_checkbox);
            this._hearingCheckbox.Target = hearing_checkbox;

            //External source checkbox
            Checkbox external_source_checkbox;
            space.TryReadValue <Checkbox>("external_source_checkbox", out external_source_checkbox);
            this._externalSourceCheckbox.Target = external_source_checkbox;

            //Animation checkbox2
            Checkbox animation_checkbox2;
            space.TryReadValue <Checkbox>("animation_checkbox2", out animation_checkbox2);
            this._animationsCheckbox2.Target = animation_checkbox2;

            //Generate Bvh checkbox
            Checkbox generate_bvh_checkbox2;
            space.TryReadValue <Checkbox>("generate_bvh_checkbox2", out generate_bvh_checkbox2);
            this._generateBvhCheckbox2.Target = generate_bvh_checkbox2;

            //Avatar ref
            ReferenceField <Slot> avatar_ref_field;
            space.TryReadValue <ReferenceField <Slot> >("avatar_ref_field", out avatar_ref_field);
            this._avatarRefField.Target = avatar_ref_field;

            //Play button
            Button play_button;
            space.TryReadValue <Button>("play_button", out play_button);
            this._playButton.Target = play_button;

            UniLog.Log("Finished linking UI slot");
        }
Пример #46
0
 public string GenerateName(Slot slot, IEnumerable <KeyValuePair <Attribute, int> > rawAttributes, IEnumerable <KeyValuePair <Modifier, int> > rawModifiers) =>
 GenerateNameAsync(slot, rawAttributes, rawModifiers).Result;
Пример #47
0
 void OnMouseOver()
 {
     Slot.currentHoveredSlot = this;
 }
Пример #48
0
        internal void PopulateEdges()
        {
            UdonNodeData data = ((UdonGraph)graph).data.FindNode(uid);
            //UdonNodeDefinition nodeDefinition = ((UdonGraph)graph).data.

            UdonNodeDefinition udonNodeDefinition;

            if (NodeDefinitionCache.ContainsKey(data.fullName))
            {
                udonNodeDefinition = NodeDefinitionCache[data.fullName];
            }
            else
            {
                udonNodeDefinition = UdonEditorManager.Instance.GetNodeDefinition(data.fullName);
                NodeDefinitionCache.Add(data.fullName, udonNodeDefinition);
            }

            for (int i = 0; i < udonNodeDefinition.inputs.Length; i++)
            {
                if (data.nodeUIDs.Length <= i)
                {
                    continue;
                }
                if (string.IsNullOrEmpty(data.nodeUIDs[i]))
                {
                    continue;
                }

                string[] splitUID   = data.nodeUIDs[i].Split('|');
                string   nodeUID    = splitUID[0];
                int      otherIndex = 0;
                if (splitUID.Length > 1)
                {
                    otherIndex = int.Parse(splitUID[1]);
                }

                if (string.IsNullOrEmpty(nodeUID))
                {
                    continue;
                }

                Node connectedNode = graph.nodes.FirstOrDefault(n => ((UdonNode)n).uid == nodeUID);
                if (connectedNode == null)
                {
                    Debug.LogError("Failed to connect node " + nodeUID);
                    data.nodeUIDs[i] = "";
                    ((UdonGraph)graph).ReSerializeData();
                    continue;
                }

                List <Slot> slots = inputDataSlots.ToList();
                if (slots.Count <= i)
                {
                    Debug.LogError($"Failed to find input data slot (index {i}) for node {uid} {data.fullName}");
                    continue;
                }

                Slot destSlot = slots[i];

                if (destSlot == null)
                {
                    Debug.LogError("Failed to find input data slot for node " + uid);
                    continue;
                }

                if (otherIndex < 0)
                {
                    otherIndex = 0;
                }

                if (connectedNode.outputDataSlots.Count() <= otherIndex)
                {
                    otherIndex = 0;
                }
                Slot sourceSlot = connectedNode.outputDataSlots.ToList()[otherIndex]; //.FirstOrDefault();
//
//                    catch
//                {
//                    Debug.LogError($"failed to connect node {uid} {data.fullName} to node {((UdonNode)connectedNode).uid} | otherindex is {otherIndex}");
//                }


                if (sourceSlot == null)
                {
                    Debug.LogError("Failed to find output data slot for node " + nodeUID);
                    continue;
                }

                graph.Connect(sourceSlot, destSlot);
            }

            for (int i = 0; i < data.flowUIDs.Length; i++)
            {
                string nodeUID = data.flowUIDs[i];
                if (string.IsNullOrEmpty(nodeUID))
                {
                    continue;
                }

                Node connectedNode = graph.nodes.FirstOrDefault(n => ((UdonNode)n).uid == nodeUID);
                if (connectedNode == null)
                {
                    Debug.LogError("Failed to connect flow node " + nodeUID);
                    continue;
                }

                if (uid == "4e2c7cdc-8134-4616-bc83-783dc495759f")
                {
                    Debug.Log(outputFlowSlots.Count());
                }

                Slot sourceSlot = outputFlowSlots.Count() > 1 ? outputFlowSlots.ToArray()[i] : outputFlowSlots.FirstOrDefault();
                if (sourceSlot == null)
                {
                    Debug.LogError("Failed to find output flow slot for node " + uid);
                    continue;
                }

                Slot destSlot = connectedNode.inputFlowSlots.FirstOrDefault();
                if (destSlot == null)
                {
                    Debug.LogError("Failed to find input flow slot for node " + nodeUID);
                    continue;
                }

                graph.Connect(sourceSlot, destSlot);
            }
        }
Пример #49
0
 /*
  * Notifies this storage that the given slot is free. The given slot can
  * then be allocated to store a new tile, i.e., it can be returned by a
  * subsequent call to newSlot.
  *
  * param t a slot that is no longer in use.
  */
 public void DeleteSlot(Slot t)
 {
     m_freeSlots.AddLast(t);
 }
Пример #50
0
        public void _02_GenerateKeyPairTest()
        {
            if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1)
            {
                Assert.Inconclusive("Test cannot be executed on this platform");
            }

            using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking))
            {
                // Find first slot with token present
                Slot slot = Helpers.GetUsableSlot(pkcs11);

                // Open RW session
                using (Session session = slot.OpenSession(false))
                {
                    // Login as normal user
                    session.Login(CKU.CKU_USER, Settings.NormalUserPin);

                    // The CKA_ID attribute is intended as a means of distinguishing multiple key pairs held by the same subject
                    byte[] ckaId = session.GenerateRandom(20);

                    // Prepare attribute template of new public key
                    List <ObjectAttribute> publicKeyAttributes = new List <ObjectAttribute>();
                    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_TOKEN, true));
                    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_PRIVATE, false));
                    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, Settings.ApplicationName));
                    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_ID, ckaId));
                    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_ENCRYPT, true));
                    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_VERIFY, true));
                    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_VERIFY_RECOVER, true));
                    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_WRAP, true));
                    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_MODULUS_BITS, 1024));
                    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_PUBLIC_EXPONENT, new byte[] { 0x01, 0x00, 0x01 }));

                    // Prepare attribute template of new private key
                    List <ObjectAttribute> privateKeyAttributes = new List <ObjectAttribute>();
                    privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_TOKEN, true));
                    privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_PRIVATE, true));
                    privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, Settings.ApplicationName));
                    privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_ID, ckaId));
                    privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_SENSITIVE, true));
                    privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_DECRYPT, true));
                    privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_SIGN, true));
                    privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_SIGN_RECOVER, true));
                    privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_UNWRAP, true));

                    // Specify key generation mechanism
                    Mechanism mechanism = new Mechanism(CKM.CKM_RSA_PKCS_KEY_PAIR_GEN);

                    // Generate key pair
                    ObjectHandle publicKeyHandle  = null;
                    ObjectHandle privateKeyHandle = null;
                    session.GenerateKeyPair(mechanism, publicKeyAttributes, privateKeyAttributes, out publicKeyHandle, out privateKeyHandle);

                    // Do something interesting with generated key pair

                    // Destroy keys
                    session.DestroyObject(privateKeyHandle);
                    session.DestroyObject(publicKeyHandle);

                    session.Logout();
                }
            }
        }
Пример #51
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (MallId != 0)
            {
                hash ^= MallId.GetHashCode();
            }
            if (CommodityType != 0)
            {
                hash ^= CommodityType.GetHashCode();
            }
            if (MallSort != 0)
            {
                hash ^= MallSort.GetHashCode();
            }
            if (MallName.Length != 0)
            {
                hash ^= MallName.GetHashCode();
            }
            if (MallDesc.Length != 0)
            {
                hash ^= MallDesc.GetHashCode();
            }
            if (GiftImage.Length != 0)
            {
                hash ^= GiftImage.GetHashCode();
            }
            if (Slot != 0)
            {
                hash ^= Slot.GetHashCode();
            }
            if (MallLabel != 0)
            {
                hash ^= MallLabel.GetHashCode();
            }
            if (LabelImage.Length != 0)
            {
                hash ^= LabelImage.GetHashCode();
            }
            if (RealPrice != 0)
            {
                hash ^= RealPrice.GetHashCode();
            }
            if (OriginalPrice != 0)
            {
                hash ^= OriginalPrice.GetHashCode();
            }
            if (BuyMax != 0)
            {
                hash ^= BuyMax.GetHashCode();
            }
            if (BuyRefreshDay != 0)
            {
                hash ^= BuyRefreshDay.GetHashCode();
            }
            hash ^= award_.GetHashCode();
            if (StartTime != 0L)
            {
                hash ^= StartTime.GetHashCode();
            }
            if (EndTime != 0L)
            {
                hash ^= EndTime.GetHashCode();
            }
            if (Special != false)
            {
                hash ^= Special.GetHashCode();
            }
            return(hash);
        }
Пример #52
0
        protected override async Task <BlockState> ConvertToBlock(IEntity entity, IGrainFactory grainFactory, IWorld world, BlockWorldPos position, Slot slot)
        {
            var facing = ChestBlockHandler.PlayerYawToFacing(await entity.GetYaw());

            return(BlockStates.Furnace(facing));
        }
Пример #53
0
    ///<summary>
    /// Create a child Slot or Component object.
    ///</summary>
    ///<param name="_isSlot">Device if it's a slot or a component to create</param>
    ///<param name="_data">Data for Slot/Component creation</param>
    ///<param name="_parent">The parent of the Slot/Component</param>
    ///<param name="_customColors">Custom colors to use</param>
    private void PopulateSlot(bool _isSlot, STemplateChild _data, OgreeObject _parent,
                              Dictionary <string, string> _customColors)
    {
        GameObject go = MonoBehaviour.Instantiate(GameManager.gm.labeledBoxModel);

        Vector2 parentSizeXZ = JsonUtility.FromJson <Vector2>(_parent.attributes["size"]);
        Vector3 parentSize   = new Vector3(parentSizeXZ.x, float.Parse(_parent.attributes["height"]), parentSizeXZ.y);

        if (_parent.attributes["sizeUnit"] == "mm")
        {
            parentSize /= 1000;
        }
        else if (_parent.attributes["sizeUnit"] == "cm")
        {
            parentSize /= 100;
        }

        go.name             = _data.location;
        go.transform.parent = _parent.transform;
        go.transform.GetChild(0).localScale = new Vector3(_data.elemSize[0], _data.elemSize[2], _data.elemSize[1]) / 1000;
        go.transform.localPosition          = parentSize / -2;
        go.transform.localPosition         += new Vector3(_data.elemPos[0], _data.elemPos[2], _data.elemPos[1]) / 1000;
        if (_data.elemOrient == "vertical")
        {
            go.transform.localEulerAngles = new Vector3(0, 0, 90);
            go.transform.localPosition   += new Vector3(go.transform.GetChild(0).localScale.y,
                                                        go.transform.GetChild(0).localScale.x,
                                                        go.transform.GetChild(0).localScale.z) / 2;
        }
        else
        {
            go.transform.localEulerAngles = Vector3.zero;
            go.transform.localPosition   += go.transform.GetChild(0).localScale / 2;
        }

        if (_isSlot)
        {
            Slot s = go.AddComponent <Slot>();
            s.orient = _data.elemOrient;
            if (_data.attributes != null && _data.attributes.ContainsKey("factor"))
            {
                s.formFactor = _data.attributes["factor"];
            }
            s.labelPos = _data.labelPos;

            go.transform.GetChild(0).GetComponent <Collider>().enabled = false;
        }
        else
        {
            OObject obj = go.AddComponent <OObject>();
            obj.name = go.name;
            // obj.id // ??
            obj.parentId    = _parent.id;
            obj.category    = "device";
            obj.domain      = _parent.domain;
            obj.description = new List <string>();
            obj.attributes  = new Dictionary <string, string>
            {
                ["deviceType"] = _data.type
            };
            if (_data.attributes != null)
            {
                foreach (KeyValuePair <string, string> kvp in _data.attributes)
                {
                    obj.attributes[kvp.Key] = kvp.Value;
                }
            }
            obj.UpdateHierarchyName();
        }

        DisplayObjectData dod = go.GetComponent <DisplayObjectData>();

        dod.PlaceTexts(_data.labelPos);
        dod.SetLabel("#name");

        go.transform.GetChild(0).GetComponent <Renderer>().material = GameManager.gm.defaultMat;
        Renderer rend = go.transform.GetChild(0).GetComponent <Renderer>();
        Color    myColor;

        if (_data.color != null && _data.color.StartsWith("@"))
        {
            ColorUtility.TryParseHtmlString($"#{_customColors[_data.color.Substring(1)]}", out myColor);
        }
        else
        {
            ColorUtility.TryParseHtmlString($"#{_data.color}", out myColor);
        }
        if (_isSlot)
        {
            rend.material       = GameManager.gm.alphaMat;
            rend.material.color = new Color(myColor.r, myColor.g, myColor.b, 0.33f);
        }
        else
        {
            rend.material.color = new Color(myColor.r, myColor.g, myColor.b, 1f);
            go.GetComponent <OObject>().color = rend.material.color;
        }
    }
        public void GetSigningCertificateTest()
        {
            // CKA_ID and CKA_LABEL of the temporary RSA key pair
            byte[] ckaId    = null;
            string ckaLabel = null;

            // Generate temporary RSA key pair
            using (Pkcs11 pkcs11 = new Pkcs11(_libraryPath, false))
            {
                Slot slot = FindSlot(pkcs11, _tokenSerial, _tokenLabel);
                if (slot == null)
                {
                    throw new TokenNotFoundException();
                }

                using (Session session = slot.OpenSession(false))
                {
                    session.Login(CKU.CKU_USER, _pin);

                    ckaId    = session.GenerateRandom(20);
                    ckaLabel = Guid.NewGuid().ToString();

                    List <ObjectAttribute> publicKeyAttributes = new List <ObjectAttribute>();
                    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_TOKEN, true));
                    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_PRIVATE, false));
                    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, ckaLabel));
                    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_ID, ckaId));
                    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_ENCRYPT, true));
                    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_VERIFY, true));
                    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_VERIFY_RECOVER, true));
                    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_WRAP, true));
                    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_MODULUS_BITS, 1024));
                    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_PUBLIC_EXPONENT, new byte[] { 0x01, 0x00, 0x01 }));

                    List <ObjectAttribute> privateKeyAttributes = new List <ObjectAttribute>();
                    privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_TOKEN, true));
                    privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_PRIVATE, true));
                    privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, ckaLabel));
                    privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_ID, ckaId));
                    privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_SENSITIVE, true));
                    privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_DECRYPT, true));
                    privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_SIGN, true));
                    privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_SIGN_RECOVER, true));
                    privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_UNWRAP, true));

                    ObjectHandle publicKeyHandle  = null;
                    ObjectHandle privateKeyHandle = null;
                    session.GenerateKeyPair(new Mechanism(CKM.CKM_RSA_PKCS_KEY_PAIR_GEN), publicKeyAttributes, privateKeyAttributes, out publicKeyHandle, out privateKeyHandle);

                    session.Logout();
                }
            }

            // Test Pkcs11RsaSignature with RSA key pair associated with certificate present on the token
            using (Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(_libraryPath, _tokenSerial, _tokenLabel, _pin, _ckaLabel, _ckaId, _hashAlgorithm))
            {
                byte[] cert = pkcs11RsaSignature.GetSigningCertificate();
                Assert.IsTrue(cert != null);
                Assert.IsTrue(ConvertUtils.BytesToBase64String(cert) == _certificate);
            }

            // Test Pkcs11RsaSignature with temporary RSA key pair that is not associated with any certificate present on the token
            using (Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(_libraryPath, _tokenSerial, _tokenLabel, _pin, ckaLabel, ConvertUtils.BytesToHexString(ckaId), _hashAlgorithm))
            {
                try
                {
                    pkcs11RsaSignature.GetSigningCertificate();
                    Assert.Fail("Exception expected but not thrown");
                }
                catch (Exception ex)
                {
                    Assert.IsTrue(ex is ObjectNotFoundException);
                }
            }

            // Delete temporary RSA key pair
            using (Pkcs11 pkcs11 = new Pkcs11(_libraryPath, false))
            {
                Slot slot = FindSlot(pkcs11, _tokenSerial, _tokenLabel);
                if (slot == null)
                {
                    throw new TokenNotFoundException();
                }

                using (Session session = slot.OpenSession(false))
                {
                    session.Login(CKU.CKU_USER, _pin);

                    List <ObjectAttribute> objectAttributes = new List <ObjectAttribute>();
                    objectAttributes.Add(new ObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_RSA));
                    objectAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, ckaLabel));
                    objectAttributes.Add(new ObjectAttribute(CKA.CKA_ID, ckaId));

                    List <ObjectHandle> foundObjects = session.FindAllObjects(objectAttributes);
                    foreach (ObjectHandle foundObject in foundObjects)
                    {
                        session.DestroyObject(foundObject);
                    }

                    session.Logout();
                }
            }
        }
Пример #55
0
        void DrawSlotList()
        {
            showSlotList = EditorGUILayout.Foldout(showSlotList, new GUIContent("Slots", SpineEditorUtilities.Icons.slotRoot));

            if (!showSlotList)
            {
                return;
            }
            if (m_skeletonAnimation == null || m_skeletonAnimation.skeleton == null)
            {
                return;
            }

            EditorGUI.indentLevel++;
            showAttachments = EditorGUILayout.ToggleLeft("Show Attachments", showAttachments);
            var  slotAttachments            = new List <Attachment>();
            var  slotAttachmentNames        = new List <string>();
            var  defaultSkinAttachmentNames = new List <string>();
            var  defaultSkin = m_skeletonData.Skins.Items[0];
            Skin skin        = m_skeletonAnimation.skeleton.Skin ?? defaultSkin;

            for (int i = m_skeletonAnimation.skeleton.Slots.Count - 1; i >= 0; i--)
            {
                Slot slot = m_skeletonAnimation.skeleton.Slots.Items[i];
                EditorGUILayout.LabelField(new GUIContent(slot.Data.Name, SpineEditorUtilities.Icons.slot));
                if (showAttachments)
                {
                    EditorGUI.indentLevel++;
                    slotAttachments.Clear();
                    slotAttachmentNames.Clear();
                    defaultSkinAttachmentNames.Clear();

                    skin.FindNamesForSlot(i, slotAttachmentNames);
                    skin.FindAttachmentsForSlot(i, slotAttachments);

                    if (skin != defaultSkin)
                    {
                        defaultSkin.FindNamesForSlot(i, defaultSkinAttachmentNames);
                        defaultSkin.FindNamesForSlot(i, slotAttachmentNames);
                        defaultSkin.FindAttachmentsForSlot(i, slotAttachments);
                    }
                    else
                    {
                        defaultSkin.FindNamesForSlot(i, defaultSkinAttachmentNames);
                    }

                    for (int a = 0; a < slotAttachments.Count; a++)
                    {
                        Attachment attachment     = slotAttachments[a];
                        string     attachmentName = slotAttachmentNames[a];

                        Texture2D icon = null;
                        var       type = attachment.GetType();

                        if (type == typeof(RegionAttachment))
                        {
                            icon = SpineEditorUtilities.Icons.image;
                        }
                        else if (type == typeof(MeshAttachment))
                        {
                            icon = SpineEditorUtilities.Icons.mesh;
                        }
                        else if (type == typeof(BoundingBoxAttachment))
                        {
                            icon = SpineEditorUtilities.Icons.boundingBox;
                        }
                        else if (type == typeof(PathAttachment))
                        {
                            icon = SpineEditorUtilities.Icons.boundingBox;
                        }
                        else
                        {
                            icon = SpineEditorUtilities.Icons.warning;
                        }
                        //JOHN: left todo: Icon for paths. Generic icon for unidentified attachments.

                        // MITCH: left todo:  Waterboard Nate
                        //if (name != attachment.Name)
                        //icon = SpineEditorUtilities.Icons.skinPlaceholder;

                        bool initialState = slot.Attachment == attachment;

                        bool toggled = EditorGUILayout.ToggleLeft(new GUIContent(attachmentName, icon), slot.Attachment == attachment);

                        if (!defaultSkinAttachmentNames.Contains(attachmentName))
                        {
                            Rect skinPlaceHolderIconRect = GUILayoutUtility.GetLastRect();
                            skinPlaceHolderIconRect.width  = SpineEditorUtilities.Icons.skinPlaceholder.width;
                            skinPlaceHolderIconRect.height = SpineEditorUtilities.Icons.skinPlaceholder.height;
                            GUI.DrawTexture(skinPlaceHolderIconRect, SpineEditorUtilities.Icons.skinPlaceholder);
                        }

                        if (toggled != initialState)
                        {
                            slot.Attachment  = toggled ? attachment : null;
                            m_requireRefresh = true;
                        }
                    }
                    EditorGUI.indentLevel--;
                }
            }
            EditorGUI.indentLevel--;
        }
Пример #56
0
 public override void Use(Slot slot, ItemScript item)
 {
     CharacterPanel.Instance.EquipItem(slot, item);
 }
Пример #57
0
 private void setSlotEventHandlers(Slot slot)
 {
     slot.evhSlotStateChanged += new SlotEventHandler(slot_evhSlotStateChanged);
 }
Пример #58
0
 private void removeSlotEventHandlers(Slot slot)
 {
     slot.evhSlotStateChanged -= slot_evhSlotStateChanged;
 }
Пример #59
0
    public override void OnUpdate()
    {
        //if (isPickedItem)
        //{
        //    //如果我们捡起了物品,我们就要让物品跟随鼠标
        //    Vector2 position;
        //    RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform, Input.mousePosition, null, out position);
        //    pickedItem.SetLocalPosition(position);
        //}

#if UNITY_EDITOR
        if (true)
        {
            if (isPickedItem)
            {
                //如果我们捡起了物品,我们就要让物品跟随鼠标
                Vector2 position;
                RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform,
                                                                        Input.mousePosition, null, out position);
                pickedItem.SetLocalPosition(position);
                if (Input.GetMouseButtonUp(0))
                {
#else
        if (Input.touchCount > 0)
        {
            Touch myTouch = Input.touches[0];
            if (isPickedItem)
            {
                //if (myTouch.phase != TouchPhase.Ended && myTouch.phase != TouchPhase.Canceled)
                //{
                //如果我们捡起了物品,我们就要让物品跟随鼠标
                Vector2 position;
                RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform,
                                                                        Input.touches[0].position, null, out position);
                pickedItem.SetLocalPosition(position);
                if (myTouch.phase == TouchPhase.Ended)
                {
#endif
                    isPickedItem = false;
                    PointerEventData pointerEventData = new PointerEventData(EventSystem.current);
                    pointerEventData.position = Input.mousePosition;
                    GraphicRaycaster     gr      = canvas.GetComponent <GraphicRaycaster>();
                    List <RaycastResult> results = new List <RaycastResult>();
                    gr.Raycast(pointerEventData, results);
                    if (results.Count <= 0)
                    {
                        isPickedItem = false;
                        PickedItem.Hide();
                        return;
                    }
                    GameObject go = results[0].gameObject;
                    if (go.tag == "Slot")
                    {
                        Slot slot = go.GetComponent <Slot>();
                        if (slot is EquipmentSlot)
                        {
                            EquipmentSlot equipmentSlot = slot as EquipmentSlot;
                            if (equipmentSlot.IsRightItem(pickedItem.Item))
                            {
                                if (slot.transform.childCount > 0)
                                {
                                    int  amount = slot.transform.GetChild(0).GetComponent <ItemUI>().Amount;
                                    Item item   = slot.transform.GetChild(0).GetComponent <ItemUI>().Item;
                                    for (int i = 0; i < pickedItem.Amount; i++)
                                    {
                                        GameObject.DestroyImmediate(slot.transform.GetChild(0).gameObject);
                                        slot.StoreItem(pickedItem.Item);
                                    }

                                    for (int i = 0; i < amount; i++)
                                    {
                                        knapsackPanel.StoreItem(item);
                                    }
                                }
                                else
                                {
                                    slot.StoreItem(pickedItem.Item);
                                }
                            }
                            else
                            {
                                knapsackPanel.StoreItem(pickedItem.Item);
                            }

                            isPickedItem = false;
                            PickedItem.Hide();
                        }
                        else if (slot is ShopSlot)
                        {
                            knapsackPanel.GetComponent <KnapsackPanel>().SellItem(pickedItem);
                            isPickedItem = false;
                            pickedItem.Hide();
                        }
                        else
                        {
                            if (slot.transform.childCount > 0)
                            {
                                int  amount = slot.transform.GetChild(0).GetComponent <ItemUI>().Amount;
                                Item item   = slot.transform.GetChild(0).GetComponent <ItemUI>().Item;
                                for (int i = 0; i < pickedItem.Amount; i++)
                                {
                                    GameObject.DestroyImmediate(slot.transform.GetChild(0).gameObject);
                                    slot.StoreItem(pickedItem.Item);
                                }

                                for (int i = 0; i < amount; i++)
                                {
                                    knapsackPanel.StoreItem(item);
                                }

                                isPickedItem = false;
                                PickedItem.Hide();
                            }
                            else
                            {
                                for (int i = 0; i < pickedItem.Amount; i++)
                                {
                                    slot.StoreItem(pickedItem.Item);
                                }

                                isPickedItem = false;
                                PickedItem.Hide();
                            }
                        }
                    }
                    else
                    {
                        if (go.tag == "ShopPanel")
                        {
                            knapsackPanel.SellItem(pickedItem);
                        }
                        else
                        {
                            for (int i = 0; i < pickedItem.Amount; i++)
                            {
                                knapsackPanel.StoreItem(pickedItem.Item);
                            }
                        }
                        isPickedItem = false;
                        PickedItem.Hide();
                    }
                }
            }
        }
    }
Пример #60
0
 private static string GetStatus(Slot slot)
 {
     return(slot.status.Equals("paused", StringComparison.InvariantCultureIgnoreCase) ? "Resume" : "Pause");
 }