Ejemplo n.º 1
0
 public void UndoRecordObject(UndoParentNode objectToUndo, string name)
 {
     UIUtils.MarkUndoAction();
     Undo.RegisterCompleteObjectUndo(UIUtils.CurrentWindow, name);
     Undo.RecordObject(objectToUndo, name);
 }
Ejemplo n.º 2
0
    void Update()
    {
        var player = Utils.ClientLocalPlayer();

        if (!player)
        {
            return;
        }

        // hotkey (not while typing in chat, etc.)
        if (Input.GetKeyDown(hotKey) && !UIUtils.AnyInputActive())
        {
            panel.SetActive(!panel.activeSelf);
        }

        // only update the panel if it's active
        if (panel.activeSelf)
        {
            // instantiate/destroy enough slots
            // (we only care about non status skills)
            var skills = player.skills.Where(s => !s.category.StartsWith("Status")).ToList();
            UIUtils.BalancePrefabs(slotPrefab.gameObject, skills.Count, content);

            // refresh all
            for (int i = 0; i < skills.Count; ++i)
            {
                var slot  = content.GetChild(i).GetComponent <UISkillSlot>();
                var skill = skills[i];

                // drag and drop name has to be the index in the real skill list,
                // not in the filtered list, otherwise drag and drop may fail
                int skillIndex = player.skills.FindIndex(s => s.name == skill.name);
                slot.dragAndDropable.name = skillIndex.ToString();

                // click event
                slot.button.interactable = skill.learned;
                slot.button.onClick.SetListener(() => {
                    if (skill.learned && skill.IsReady())
                    {
                        player.CmdUseSkill(skillIndex);
                    }
                });

                // set state
                slot.dragAndDropable.dragable = skill.learned;

                // image
                if (skill.learned)
                {
                    slot.image.color  = Color.white;
                    slot.image.sprite = skill.image;
                }

                // description
                slot.descriptionText.text = skill.ToolTip(showRequirements: !skill.learned);

                // learnable?
                if (!skill.learned)
                {
                    slot.learnButton.gameObject.SetActive(true);
                    slot.learnButton.GetComponentInChildren <Text>().text = "Learn";
                    slot.learnButton.interactable = player.level >= skill.requiredLevel &&
                                                    player.skillExperience >= skill.requiredSkillExperience;
                    slot.learnButton.onClick.SetListener(() => { player.CmdLearnSkill(skillIndex); });
                    // upgradeable?
                }
                else if (skill.level < skill.maxLevel)
                {
                    slot.learnButton.gameObject.SetActive(true);
                    slot.learnButton.GetComponentInChildren <Text>().text = "Upgrade";
                    slot.learnButton.interactable = player.level >= skill.upgradeRequiredLevel &&
                                                    player.skillExperience >= skill.upgradeRequiredSkillExperience;
                    slot.learnButton.onClick.SetListener(() => { player.CmdUpgradeSkill(skillIndex); });
                    // otherwise no button needed
                }
                else
                {
                    slot.learnButton.gameObject.SetActive(false);
                }

                // cooldown overlay
                float cooldown = skill.CooldownRemaining();
                slot.cooldownOverlay.SetActive(skill.learned && cooldown > 0);
                slot.cooldownText.text = cooldown.ToString("F0");
            }

            // skill experience
            skillExperienceText.text = player.skillExperience.ToString();
        }
    }
Ejemplo n.º 3
0
        void UpdateDisconnectedConnection(int portId)
        {
            if (m_extensibleInputPorts || m_allowMatrixCheck)
            {
                int higher       = 0;
                int groupOneType = 0;
                int groupTwoType = 0;
                for (int i = 0; i < m_inputPorts.Count; i++)
                {
                    if (m_inputPorts[i].IsConnected)
                    {
                        int currentPriority = UIUtils.GetPriority(m_inputPorts[i].DataType);
                        if (!m_vectorMatrixOps && currentPriority < 3)
                        {
                            currentPriority += 7;
                        }
                        if (currentPriority > higher && currentPriority > 2)
                        {
                            higher         = currentPriority;
                            m_mainDataType = m_inputPorts[i].DataType;
                        }
                        switch (m_inputPorts[i].DataType)
                        {
                        case WirePortDataType.FLOAT2:
                        case WirePortDataType.FLOAT3:
                        case WirePortDataType.FLOAT4:
                        case WirePortDataType.COLOR:
                        {
                            groupOneType++;
                            groupTwoType++;
                        }
                        break;

                        case WirePortDataType.FLOAT3x3:
                        {
                            groupOneType++;
                        }
                        break;

                        case WirePortDataType.FLOAT4x4:
                        {
                            groupTwoType++;
                        }
                        break;
                        }
                    }
                }

                for (int i = 0; i < m_inputPorts.Count; i++)
                {
                    if (!m_inputPorts[i].IsConnected)
                    {
                        m_inputPorts[i].ChangeType(m_mainDataType, false);
                    }
                }

                if (groupOneType > 0 && m_mainDataType == WirePortDataType.FLOAT4x4)
                {
                    m_errorMessageTooltip = "Doing this operation with FLOAT4x4 value only works against other FLOAT4x4 or FLOAT values";
                    m_showErrorMessage    = true;
                }
                else if (groupTwoType > 0 && m_mainDataType == WirePortDataType.FLOAT3x3)
                {
                    m_errorMessageTooltip = "Doing this operation with FLOAT3x3 value only works against other FLOAT3x3 or FLOAT values";
                    m_showErrorMessage    = true;
                }
                else
                {
                    m_showErrorMessage = false;
                }

                if (m_dynamicOutputType)
                {
                    m_outputPorts[0].ChangeType(m_mainDataType, false);
                }
            }
            else

            if (m_inputPorts[0].DataType != m_inputPorts[1].DataType)
            {
                int otherPortId = (portId + 1) % 2;
                if (m_inputPorts[otherPortId].IsConnected)
                {
                    m_mainDataType = m_inputPorts[otherPortId].DataType;
                    m_inputPorts[portId].ChangeType(m_mainDataType, false);
                    if (m_dynamicOutputType)
                    {
                        m_outputPorts[0].ChangeType(m_mainDataType, false);
                    }
                }
                else
                {
                    if (UIUtils.GetPriority(m_inputPorts[0].DataType) > UIUtils.GetPriority(m_inputPorts[1].DataType))
                    {
                        m_mainDataType = m_inputPorts[0].DataType;
                        m_inputPorts[1].ChangeType(m_mainDataType, false);
                    }
                    else
                    {
                        m_mainDataType = m_inputPorts[1].DataType;
                        m_inputPorts[0].ChangeType(m_mainDataType, false);
                    }

                    if (m_dynamicOutputType)
                    {
                        if (m_mainDataType != m_outputPorts[0].DataType)
                        {
                            m_outputPorts[0].ChangeType(m_mainDataType, false);
                        }
                    }
                }
            }
        }
Ejemplo n.º 4
0
    void Update()
    {
        Player player = Player.localPlayer;

        // only show and update while there are meeting members
        if (player != null)
        {
            if (player.meeting.InMeeting())
            {
                panel.SetActive(true);
                Meeting meeting = player.meeting.meeting;

                // get meeting members without self. no need to show self in HUD too.
                List <string> members = player.meeting.InMeeting() ? meeting.members.Where(m => m != player.name).ToList() : new List <string>();

                // instantiate/destroy enough slots
                UIUtils.BalancePrefabs(slotPrefab.gameObject, members.Count, memberContent);

                // refresh all members
                for (int i = 0; i < members.Count; ++i)
                {
                    UIMeetingHUDMemberSlot slot = memberContent.GetChild(i).GetComponent <UIMeetingHUDMemberSlot>();
                    string memberName           = members[i];
                    float  distance             = Mathf.Infinity;
                    float  visRange             = player.VisRange();

                    slot.nameText.text = memberName;
                    slot.masterIndicatorText.gameObject.SetActive(meeting.master == memberName);


                    if (Player.onlinePlayers.ContainsKey(memberName))
                    {
                        Player member = Player.onlinePlayers[memberName];
                        slot.icon.sprite = member.classIcon;
                        slot.backgroundButton.onClick.SetListener(() => {
                            if (member != null)
                            {
                                player.CmdSetTarget(member.netIdentity);
                            }
                        });

                        // distance color based on visRange ratio
                        distance = Vector3.Distance(player.transform.position, member.transform.position);
                        visRange = member.VisRange(); // visRange is always based on the other guy
                    }

                    // distance overlay alpha based on visRange ratio
                    // (because values are only up to date for members in observer
                    //  range)
                    float ratio = visRange > 0 ? distance / visRange : 1f;
                    float alpha = alphaCurve.Evaluate(ratio);

                    // icon alpha
                    Color iconColor = slot.icon.color;
                    iconColor.a     = alpha;
                    slot.icon.color = iconColor;
                }
            }
            else
            {
                panel.SetActive(false);
            }
        }
        else
        {
            panel.SetActive(false);
        }
    }
Ejemplo n.º 5
0
 public override void ForceClearConnection()
 {
     UIUtils.DeleteConnection(false, m_nodeId, m_portId, false, true);
 }
Ejemplo n.º 6
0
 public void FadeOut()
 {
     UIUtils.PlayAnimation(animator, "FullScreenFadeInOut_FadeOut", null);
 }
Ejemplo n.º 7
0
		public override void ForceUpdateFromMaterial( Material material )
		{
			if( UIUtils.IsProperty( m_currentParameterType ) && material.HasProperty( m_propertyName ) )
				m_materialValue = material.GetMatrix( m_propertyName ):
		}
    // -----------------------------------------------------------------------------------
    // Update
    // -----------------------------------------------------------------------------------
    private void Update()
    {
        if (gameObject.activeSelf && parentPanel.gameObject.activeSelf)
        {
            Player player = parentPanel.currentPlayer;
            if (!player)
            {
                return;
            }

            // -----

            traitPointsText.text = traitPoints.ToString() + "/" + player.UCE_TraitPoints.ToString();

            // ----- update trait list

            UIUtils.BalancePrefabs(slotPrefab.gameObject, traitPool.Count, content);

            for (int i = 0; i < traitPool.Count; ++i)
            {
                int icopy = i;

                UCE_UI_TraitSlot  slot = content.GetChild(icopy).GetComponent <UCE_UI_TraitSlot>();
                UCE_TraitTemplate tmpl = traitPool[icopy];

                bool bAllowed = true;

                // -- can afford
                if (traitPoints < tmpl.traitCost)
                {
                    bAllowed = false;
                }

                // -- not unique, not taken?
                if (currentTraits.Any(x => x.uniqueGroup == tmpl.uniqueGroup))
                {
                    bAllowed = false;
                }

                // -- not limited by class?
                if (tmpl.allowedClasses.Length > 0 && !tmpl.allowedClasses.Any(x => x == player.gameObject))
                {
                    bAllowed = false;
                }

                // -- enable/disable button add/remove trait
                if (currentTraits.Any(x => x == tmpl))
                {
                    slot.button.interactable = true;
                }
                else
                {
                    slot.button.interactable = bAllowed;
                }

                // -- trait exists already?
                if (currentTraits.Any(x => x == tmpl))
                {
                    slot.image.color = Color.black;
                }
                else
                {
                    slot.image.color = Color.white;
                }

                // -- set/unset trait per click
                slot.button.onClick.SetListener(() =>
                {
                    if (currentTraits.Any(x => x == tmpl))
                    {
                        currentTraits.Remove(tmpl);
                        traitPoints += tmpl.traitCost;
                    }
                    else
                    {
                        currentTraits.Add(tmpl);
                        traitPoints -= tmpl.traitCost;
                    }
                });

                slot.image.sprite    = tmpl.image;
                slot.tooltip.enabled = true;
                slot.tooltip.text    = tmpl.ToolTip();
            }
        }
        else
        {
            gameObject.SetActive(false);
        }
    }
Ejemplo n.º 9
0
        public override void Draw(DrawInfo drawInfo)
        {
            base.Draw(drawInfo);

            if (!m_isVisible)
            {
                return;
            }

            if (m_isEditingFields)
            {
                EditorGUI.BeginChangeCheck();
                for (int i = 0; i < 4; i++)
                {
                    m_propertyDrawPos.y = m_outputPorts[i + 1].Position.y - 2 * drawInfo.InvertedZoom;
                    if (m_materialMode && m_currentParameterType != PropertyType.Constant)
                    {
                        float val = m_materialValue[i];
                        UIUtils.DrawFloat(this, ref m_propertyDrawPos, ref val, LabelWidth * drawInfo.InvertedZoom);
                        m_materialValue[i] = val;
                    }
                    else
                    {
                        float val = m_defaultValue[i];
                        UIUtils.DrawFloat(this, ref m_propertyDrawPos, ref val, LabelWidth * drawInfo.InvertedZoom);
                        m_defaultValue[i] = val;
                    }
                }
                if (EditorGUI.EndChangeCheck())
                {
                    m_requireMaterialUpdate = m_materialMode;
                    BeginDelayedDirtyProperty();
                    //m_propertyNameIsDirty = true;
                }
            }
            else if (drawInfo.CurrentEventType == EventType.Repaint && ContainerGraph.LodLevel <= ParentGraph.NodeLOD.LOD4)
            {
                for (int i = 0; i < 4; i++)
                {
                    m_propertyDrawPos.y = m_outputPorts[i + 1].Position.y - 2 * drawInfo.InvertedZoom;

                    Rect fakeField = m_propertyDrawPos;
                    fakeField.xMin += LabelWidth * drawInfo.InvertedZoom;
                    Rect fakeLabel = m_propertyDrawPos;
                    fakeLabel.xMax = fakeField.xMin;
                    EditorGUIUtility.AddCursorRect(fakeLabel, MouseCursor.SlideArrow);
                    EditorGUIUtility.AddCursorRect(fakeField, MouseCursor.Text);

                    if (m_materialMode && m_currentParameterType != PropertyType.Constant)
                    {
                        if (m_previousValue[i] != m_materialValue[i])
                        {
                            m_previousValue[i] = m_materialValue[i];
                            m_fieldText[i]     = m_materialValue[i].ToString();
                        }
                    }
                    else
                    {
                        if (m_previousValue[i] != m_defaultValue[i])
                        {
                            m_previousValue[i] = m_defaultValue[i];
                            m_fieldText[i]     = m_defaultValue[i].ToString();
                        }
                    }

                    GUI.Label(fakeField, m_fieldText[i], UIUtils.MainSkin.textField);
                }
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Draw graphic components on screen like RemoteTech's ground-station marks
        /// </summary>
        public void OnGUI()
        {
            if (HighLogic.CurrentGame == null || !loadCompleted)
            {
                return;
            }

            if (!(HighLogic.LoadedScene == GameScenes.FLIGHT || HighLogic.LoadedScene == GameScenes.TRACKSTATION))
            {
                return;
            }

            if ((!HighLogic.CurrentGame.Parameters.CustomParams <CommNetParams>().enableGroundStations&& !this.isKSC) || !MapView.MapIsEnabled || MapView.MapCamera == null)
            {
                return;
            }

            if (CNCCommNetScenario.Instance == null || CNCCommNetScenario.Instance.hideGroundStations)
            {
                return;
            }

            Vector3d worldPos = ScaledSpace.LocalToScaledSpace(nodeTransform.transform.position);

            if (MapView.MapCamera.transform.InverseTransformPoint(worldPos).z < 0f)
            {
                return;
            }

            Vector3 position          = PlanetariumCamera.Camera.WorldToScreenPoint(worldPos);
            Rect    groundStationRect = new Rect((position.x - 8), (Screen.height - position.y) - 8, 16, 16);

            if (isOccluded(nodeTransform.transform.position, this.body))
            {
                return;
            }

            if (!isOccluded(nodeTransform.transform.position, this.body) && this.IsCamDistanceToWide(nodeTransform.transform.position))
            {
                return;
            }

            //draw the dot
            Color previousColor = GUI.color;

            GUI.color = this.Color;
            GUI.DrawTexture(groundStationRect, markTexture, ScaleMode.ScaleToFit, true);
            GUI.color = previousColor;

            //draw the headline above and below the dot
            if (UIUtils.ContainsMouse(groundStationRect))
            {
                Rect headlineRect = groundStationRect;

                //Name
                Vector2 nameDim = CNCCommNetHome.groundStationHeadline.CalcSize(new GUIContent(this.stationName));
                headlineRect.x     -= nameDim.x / 2 - 5;
                headlineRect.y     -= nameDim.y + 5;
                headlineRect.width  = nameDim.x;
                headlineRect.height = nameDim.y;
                GUI.Label(headlineRect, this.stationName, CNCCommNetHome.groundStationHeadline);

                //frequency list
                string freqStr = "No frequency assigned";

                if (Frequencies.Count > 0)
                {
                    freqStr = "Broadcasting in";
                    for (int i = 0; i < Frequencies.Count; i++)
                    {
                        freqStr += "\n~ frequency " + Frequencies[i];
                    }
                }

                headlineRect = groundStationRect;
                Vector2 freqDim = CNCCommNetHome.groundStationHeadline.CalcSize(new GUIContent(freqStr));
                headlineRect.x     -= freqDim.x / 2 - 5;
                headlineRect.y     += groundStationRect.height + 5;
                headlineRect.width  = freqDim.x;
                headlineRect.height = freqDim.y;
                GUI.Label(headlineRect, freqStr, CNCCommNetHome.groundStationHeadline);
            }
        }
Ejemplo n.º 11
0
        public override string GenerateShaderForOutput(int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar)
        {
            base.GenerateShaderForOutput(outputId, ref dataCollector, ignoreLocalvar);

            GeneratePOMfunction();

            string textcoords = m_uvPort.GenerateShaderForOutput(ref dataCollector, WirePortDataType.FLOAT2, false, true);
            string texture    = m_texPort.GenerateShaderForOutput(ref dataCollector, WirePortDataType.SAMPLER2D, false, true);
            string scale      = m_defaultScale.ToString();

            if (m_scalePort.IsConnected)
            {
                scale = m_scalePort.GenerateShaderForOutput(ref dataCollector, WirePortDataType.FLOAT, false, true);
            }

            string viewDirTan = "";

            if (!m_viewdirTanPort.IsConnected)
            {
                if (!dataCollector.DirtyNormal)
                {
                    dataCollector.ForceNormal = true;
                }


                if (dataCollector.IsTemplate)
                {
                    viewDirTan = dataCollector.TemplateDataCollectorInstance.GetTangentViewDir(m_currentPrecisionType);
                }
                else
                {
                    dataCollector.AddToInput(UniqueId, SurfaceInputs.VIEW_DIR, m_currentPrecisionType);
                    viewDirTan = Constants.InputVarStr + "." + UIUtils.GetInputValueFromType(SurfaceInputs.VIEW_DIR);
                }
            }
            else
            {
                viewDirTan = m_viewdirTanPort.GenerateShaderForOutput(ref dataCollector, WirePortDataType.FLOAT3, false, true);
            }

            //generate world normal
            string normalWorld = string.Empty;

            if (dataCollector.IsTemplate)
            {
                normalWorld = dataCollector.TemplateDataCollectorInstance.GetWorldNormal(m_currentPrecisionType);
            }
            else
            {
                dataCollector.AddToInput(UniqueId, SurfaceInputs.WORLD_NORMAL, m_currentPrecisionType);
                dataCollector.AddToInput(UniqueId, SurfaceInputs.INTERNALDATA, addSemiColon: false);
                normalWorld = GeneratorUtils.GenerateWorldNormal(ref dataCollector, UniqueId);
            }

            //string normalWorld = "WorldNormalVector( " + Constants.InputVarStr + ", float3( 0, 0, 1 ) )";

            //generate viewDir in world space

            string worldPos = string.Empty;

            if (dataCollector.IsTemplate)
            {
                worldPos = dataCollector.TemplateDataCollectorInstance.GetWorldPos();
            }
            else
            {
                dataCollector.AddToInput(UniqueId, SurfaceInputs.WORLD_POS);
                worldPos = Constants.InputVarStr + ".worldPos";
            }
            dataCollector.AddToLocalVariables(UniqueId, m_currentPrecisionType, WirePortDataType.FLOAT3, WorldDirVarStr, string.Format("normalize( UnityWorldSpaceViewDir( {0} ) )", worldPos));

            //dataCollector.AddToInput( m_uniqueId, string.Format( WorldDirVarDecStr, UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, WirePortDataType.FLOAT3 ), WorldDirVarStr ), false );
            //dataCollector.AddVertexInstruction( WorldDirVarDefStr, m_uniqueId );

            string dx = "ddx(" + textcoords + ")";
            string dy = "ddx(" + textcoords + ")";

            string refPlane = m_defaultRefPlane.ToString();

            if (m_refPlanePort.IsConnected)
            {
                refPlane = m_refPlanePort.GeneratePortInstructions(ref dataCollector);
            }


            string curvature = "float2(" + m_CurvatureVector.x + "," + m_CurvatureVector.y + ")";

            if (m_useCurvature)
            {
                dataCollector.AddToProperties(UniqueId, "[Header(Parallax Occlusion Mapping)]", 300);
                dataCollector.AddToProperties(UniqueId, "_CurvFix(\"Curvature Bias\", Range( 0 , 1)) = 1", 301);
                dataCollector.AddToUniforms(UniqueId, "uniform float _CurvFix;");

                if (m_curvaturePort.IsConnected)
                {
                    curvature = m_curvaturePort.GeneratePortInstructions(ref dataCollector);
                }
            }


            string localVarName = "OffsetPOM" + UniqueId;

            dataCollector.AddToUniforms(UniqueId, "uniform float4 " + texture + "_ST;");

            string arrayIndex = m_arrayIndexPort.GeneratePortInstructions(ref dataCollector);

            if (m_useTextureArray)
            {
                dataCollector.UsingArrayDerivatives = true;
            }

            string functionResult = dataCollector.AddFunctions(m_functionHeader, m_functionBody, (m_useTextureArray ? "UNITY_PASS_TEX2DARRAY(" + texture + ")": texture), textcoords, dx, dy, normalWorld, WorldDirVarStr, viewDirTan, m_minSamples, m_maxSamples, scale, refPlane, texture + "_ST.xy", curvature, arrayIndex);

            dataCollector.AddToLocalVariables(UniqueId, m_currentPrecisionType, m_pomUVPort.DataType, localVarName, functionResult);

            return(GetOutputVectorItem(0, outputId, localVarName));
        }
    void Update()
    {
        Player player = Utils.ClientLocalPlayer();

        if (!player)
        {
            return;
        }

        // use collider point(s) to also work with big entities
        if (player.target != null && player.target is Npc &&
            Utils.ClosestDistance(player.collider, player.target.collider) <= player.interactionRange)
        {
            Npc npc = (Npc)player.target;

            // items for sale
            UIUtils.BalancePrefabs(slotPrefab.gameObject, npc.saleItems.Length, content);
            for (int i = 0; i < npc.saleItems.Length; ++i)
            {
                UINpcTradingSlot slot     = content.GetChild(i).GetComponent <UINpcTradingSlot>();
                ScriptableItem   itemData = npc.saleItems[i];

                // show item in UI
                int icopy = i;
                slot.button.onClick.SetListener(() => {
                    buyIndex = icopy;
                });
                slot.image.color     = Color.white;
                slot.image.sprite    = itemData.image;
                slot.tooltip.enabled = true;
                slot.tooltip.text    = new Item(itemData).ToolTip();
            }

            // buy
            if (buyIndex != -1 && buyIndex < npc.saleItems.Length)
            {
                ScriptableItem itemData = npc.saleItems[buyIndex];

                // make valid amount, calculate price
                int amount = buyAmountInput.text.ToInt();
                amount = Mathf.Clamp(amount, 1, itemData.maxStack);
                long price = amount * itemData.buyPrice;

                // show buy panel with item in UI
                buyAmountInput.text = amount.ToString();
                buySlot.GetComponent <Image>().color           = Color.white;
                buySlot.GetComponent <Image>().sprite          = itemData.image;
                buySlot.GetComponent <UIShowToolTip>().enabled = true;
                buySlot.GetComponent <UIShowToolTip>().text    = new Item(itemData).ToolTip();
                buyCostsText.text      = price.ToString();
                buyButton.interactable = amount > 0 && price <= player.gold &&
                                         player.InventoryCanAdd(new Item(itemData), amount);
                buyButton.onClick.SetListener(() => {
                    player.CmdNpcBuyItem(buyIndex, amount);
                    buyIndex            = -1;
                    buyAmountInput.text = "1";
                });
            }
            else
            {
                // show default buy panel in UI
                buySlot.GetComponent <Image>().color           = Color.clear;
                buySlot.GetComponent <Image>().sprite          = null;
                buySlot.GetComponent <UIShowToolTip>().enabled = false;
                buyCostsText.text      = "0";
                buyButton.interactable = false;
            }

            // sell
            if (sellIndex != -1 && sellIndex < player.inventory.Count &&
                player.inventory[sellIndex].amount > 0)
            {
                ItemSlot itemSlot = player.inventory[sellIndex];

                // make valid amount, calculate price
                int amount = sellAmountInput.text.ToInt();
                amount = Mathf.Clamp(amount, 1, itemSlot.amount);
                long price = amount * itemSlot.item.sellPrice;

                // show sell panel with item in UI
                sellAmountInput.text = amount.ToString();
                sellSlot.GetComponent <Image>().color           = Color.white;
                sellSlot.GetComponent <Image>().sprite          = itemSlot.item.image;
                sellSlot.GetComponent <UIShowToolTip>().enabled = true;
                sellSlot.GetComponent <UIShowToolTip>().text    = itemSlot.ToolTip();
                sellCostsText.text      = price.ToString();
                sellButton.interactable = amount > 0;
                sellButton.onClick.SetListener(() => {
                    player.CmdNpcSellItem(sellIndex, amount);
                    sellIndex            = -1;
                    sellAmountInput.text = "1";
                });
            }
            else
            {
                // show default sell panel in UI
                sellSlot.GetComponent <Image>().color           = Color.clear;
                sellSlot.GetComponent <Image>().sprite          = null;
                sellSlot.GetComponent <UIShowToolTip>().enabled = false;
                sellCostsText.text      = "0";
                sellButton.interactable = false;
            }
        }
        else
        {
            panel.SetActive(false);  // hide
        }
    }
Ejemplo n.º 13
0
        public void ImportRatings()
        {
            mImportCancelled = false;

            var lRatedCsvItems     = new List <IMDbRateItem>();
            var lWatchlistCsvItems = new List <IMDbListItem>();
            var lCustomLists       = new Dictionary <string, List <IMDbListItem> >();

            #region Parse Ratings CSV
            UIUtils.UpdateStatus("Reading IMDb ratings export...");
            if (mImportCsvRatings)
            {
                mCsvConfiguration.RegisterClassMap <IMDbRatingCsvMap>();

                lRatedCsvItems = ParseCsvFile <IMDbRateItem>(mRatingsFileCsv);
                if (lRatedCsvItems == null)
                {
                    UIUtils.UpdateStatus("Failed to parse IMDb ratings file!", true);
                    Thread.Sleep(2000);
                    return;
                }
                mCsvConfiguration.UnregisterClassMap <IMDbRatingCsvMap>();
            }
            if (mImportCancelled)
            {
                return;
            }
            #endregion

            #region Parse Watchlist CSV
            UIUtils.UpdateStatus("Reading IMDb watchlist export...");
            if (mImportCsvWatchlist)
            {
                mCsvConfiguration.RegisterClassMap <IMDbListCsvMap>();

                lWatchlistCsvItems = ParseCsvFile <IMDbListItem>(mWatchlistFileCsv);
                if (lWatchlistCsvItems == null)
                {
                    UIUtils.UpdateStatus("Failed to parse IMDb watchlist file!", true);
                    Thread.Sleep(2000);
                    return;
                }
                mCsvConfiguration.UnregisterClassMap <IMDbListCsvMap>();
            }
            if (mImportCancelled)
            {
                return;
            }
            #endregion

            #region Parse Custom List CSVs
            UIUtils.UpdateStatus("Reading IMDb custom lists export...");
            if (mImportCsvCustomLists)
            {
                mCsvConfiguration.RegisterClassMap <IMDbListCsvMap>();

                foreach (var list in mCustomListsCsvs)
                {
                    UIUtils.UpdateStatus($"Reading IMDb custom list '{list}'");

                    var lListCsvItems = ParseCsvFile <IMDbListItem>(list);
                    if (lListCsvItems == null)
                    {
                        UIUtils.UpdateStatus("Failed to parse IMDb custom list file!", true);
                        Thread.Sleep(2000);
                        continue;
                    }
                    lCustomLists.Add(list, lListCsvItems);
                }
                mCsvConfiguration.UnregisterClassMap <IMDbListCsvMap>();
            }
            if (mImportCancelled)
            {
                return;
            }
            #endregion

            #region Import Rated Movies
            var lRatedCsvMovies = lRatedCsvItems.Where(r => r.Type.ItemType() == IMDbType.Movie && r.MyRating != null)
                                  .Select(s => s.ToTraktRatedMovie()).ToList();

            FileLog.Info($"Found {lRatedCsvMovies.Count} movie ratings in CSV file");
            if (lRatedCsvMovies.Any())
            {
                UIUtils.UpdateStatus("Retrieving existing movie ratings from trakt.tv");
                var lCurrentUserMovieRatings = TraktAPI.GetRatedMovies();

                if (lCurrentUserMovieRatings != null)
                {
                    UIUtils.UpdateStatus($"Found {lCurrentUserMovieRatings.Count()} user movie ratings on trakt.tv");
                    // Filter out movies to rate from existing ratings online
                    lRatedCsvMovies.RemoveAll(m => lCurrentUserMovieRatings.Any(c => c.Movie.Ids.ImdbId == m.Ids.ImdbId));
                }

                UIUtils.UpdateStatus($"Importing {lRatedCsvMovies.Count()} new movie ratings to trakt.tv");

                if (lRatedCsvMovies.Count > 0)
                {
                    int lPageSize = AppSettings.BatchSize;
                    int lPages    = (int)Math.Ceiling((double)lRatedCsvMovies.Count / lPageSize);
                    for (int i = 0; i < lPages; i++)
                    {
                        UIUtils.UpdateStatus($"Importing page {i + 1}/{lPages} IMDb rated movies...");

                        var lRatingsToSync = new TraktMovieRatingSync()
                        {
                            movies = lRatedCsvMovies.Skip(i * lPageSize).Take(lPageSize).ToList()
                        };

                        TraktSyncResponse lResponse = TraktAPI.AddMoviesToRatings(lRatingsToSync);
                        if (lResponse == null)
                        {
                            UIUtils.UpdateStatus("Error importing IMDb movie ratings to trakt.tv", true);
                            Thread.Sleep(2000);
                        }
                        else if (lResponse.NotFound.Movies.Count > 0)
                        {
                            UIUtils.UpdateStatus($"Unable to sync ratings for {lResponse.NotFound.Movies.Count} movies as they're not found on trakt.tv!");
                            Thread.Sleep(1000);
                        }

                        if (mImportCancelled)
                        {
                            return;
                        }
                    }
                }
            }
            if (mImportCancelled)
            {
                return;
            }
            #endregion

            #region Import Rated TV Shows
            var lRatedCsvShows = lRatedCsvItems.Where(r => r.Type.ItemType() == IMDbType.Show && r.MyRating != null)
                                 .Select(s => s.ToTraktRatedShow()).ToList();

            FileLog.Info($"Found {lRatedCsvShows.Count} tv show ratings in CSV file");
            if (lRatedCsvShows.Any())
            {
                UIUtils.UpdateStatus("Retrieving existing tv show ratings from trakt.tv");
                var lCurrentUserShowRatings = TraktAPI.GetRatedShows();

                if (lCurrentUserShowRatings != null)
                {
                    UIUtils.UpdateStatus($"Found {lCurrentUserShowRatings.Count()} user tv show ratings on trakt.tv");
                    // Filter out shows to rate from existing ratings online
                    lRatedCsvShows.RemoveAll(s => lCurrentUserShowRatings.Any(c => (c.Show.Ids.ImdbId == s.Ids.ImdbId) ||
                                                                              (c.Show.Title.ToLowerInvariant() == s.Title.ToLowerInvariant() && c.Show.Year == s.Year)));
                }

                UIUtils.UpdateStatus($"Importing {lRatedCsvShows.Count()} tv show ratings to trakt.tv");

                if (lRatedCsvShows.Count > 0)
                {
                    int lPageSize = AppSettings.BatchSize;
                    int lPages    = (int)Math.Ceiling((double)lRatedCsvShows.Count / lPageSize);
                    for (int i = 0; i < lPages; i++)
                    {
                        UIUtils.UpdateStatus($"Importing page {i + 1}/{lPages} IMDb rated shows...");

                        var lRatingsToSync = new TraktShowRatingSync()
                        {
                            shows = lRatedCsvShows.Skip(i * lPageSize).Take(lPageSize).ToList()
                        };

                        TraktSyncResponse lResponse = TraktAPI.AddShowsToRatings(lRatingsToSync);
                        if (lResponse == null)
                        {
                            UIUtils.UpdateStatus("Error importing IMDb tv show ratings to trakt.tv", true);
                            Thread.Sleep(2000);
                        }
                        else if (lResponse.NotFound.Shows.Count > 0)
                        {
                            UIUtils.UpdateStatus($"Unable to sync ratings for {lResponse.NotFound.Shows.Count} shows as they're not found on trakt.tv!");
                            Thread.Sleep(1000);
                        }

                        if (mImportCancelled)
                        {
                            return;
                        }
                    }
                }
            }
            if (mImportCancelled)
            {
                return;
            }
            #endregion

            #region Import Rated Episodes
            var lImdbRatedEpisodes    = new List <IMDbEpisode>();
            var lImdbRatedCsvEpisodes = lRatedCsvItems.Where(r => r.Type.ItemType() == IMDbType.Episode).ToList();

            FileLog.Info($"Found {lImdbRatedCsvEpisodes.Count} tv episode ratings in CSV file");
            if (lImdbRatedCsvEpisodes.Any())
            {
                // we can't rely on the episode imdb id as trakt most likely wont have that info at the episode level
                lImdbRatedEpisodes.AddRange(lImdbRatedCsvEpisodes.Select(Helper.GetIMDbEpisodeFromTrakt).Where(imdbEpisode => imdbEpisode != null));
                if (mImportCancelled)
                {
                    return;
                }

                UIUtils.UpdateStatus("Retrieving existing tv episode ratings from trakt.tv");
                var lCurrentUserEpisodeRatings = TraktAPI.GetRatedEpisodes();

                if (lCurrentUserEpisodeRatings != null)
                {
                    UIUtils.UpdateStatus($"Found {lCurrentUserEpisodeRatings.Count()} user tv episode ratings on trakt.tv");

                    // Filter out episodes to rate from existing ratings online
                    lImdbRatedEpisodes.RemoveAll(e => lCurrentUserEpisodeRatings.Any(c => c.Episode.Ids.Trakt == e.TraktId));
                }

                UIUtils.UpdateStatus($"Importing {lImdbRatedEpisodes.Count()} episode ratings to trakt.tv");

                if (lImdbRatedEpisodes.Count > 0)
                {
                    int lPageSize = AppSettings.BatchSize;
                    int lPages    = (int)Math.Ceiling((double)lImdbRatedEpisodes.Count / lPageSize);
                    for (int i = 0; i < lPages; i++)
                    {
                        var lEpisodesRated = Helper.GetTraktEpisodeRateData(lImdbRatedEpisodes.Skip(i * lPageSize).Take(lPageSize));

                        UIUtils.UpdateStatus($"Importing page {i + 1}/{lPages} IMDb rated episodes...");

                        var lResponse = TraktAPI.AddsEpisodesToRatings(lEpisodesRated);
                        if (lResponse == null)
                        {
                            UIUtils.UpdateStatus("Error importing IMDb episodes ratings to trakt.tv", true);
                            Thread.Sleep(2000);
                        }
                        else if (lResponse.NotFound.Episodes.Count > 0)
                        {
                            UIUtils.UpdateStatus($"Unable to sync ratings for {lResponse.NotFound.Episodes.Count} IMDb episodes as they're not found on trakt.tv!");
                            Thread.Sleep(1000);
                        }

                        if (mImportCancelled)
                        {
                            return;
                        }
                    }
                }
            }
            if (mImportCancelled)
            {
                return;
            }
            #endregion

            #region Mark Rated Items as Watched
            IEnumerable <TraktMoviePlays> lWatchedTraktMovies = null;

            if (AppSettings.MarkAsWatched)
            {
                #region Movies
                var lWatchedCsvMovies = lRatedCsvItems.Where(r => r.Type.ItemType() == IMDbType.Movie)
                                        .Select(s => s.ToTraktWatchedMovie()).ToList();

                FileLog.Info("Found {0} movies in CSV file", lWatchedCsvMovies.Count);

                // compare all movies rated against what's not watched on trakt
                if (lWatchedCsvMovies.Count > 0)
                {
                    // get watched movies from trakt.tv
                    UIUtils.UpdateStatus("Requesting watched movies from trakt...");
                    lWatchedTraktMovies = TraktAPI.GetWatchedMovies();
                    if (lWatchedTraktMovies == null)
                    {
                        UIUtils.UpdateStatus("Failed to get watched movies from trakt.tv, skipping watched movie import", true);
                        Thread.Sleep(2000);
                    }
                    else
                    {
                        if (mImportCancelled)
                        {
                            return;
                        }

                        UIUtils.UpdateStatus($"Found {lWatchedTraktMovies.Count()} watched movies on trakt");
                        UIUtils.UpdateStatus("Filtering out watched movies that are already watched on trakt.tv");

                        lWatchedCsvMovies.RemoveAll(w => lWatchedTraktMovies.FirstOrDefault(t => t.Movie.Ids.ImdbId == w.Ids.ImdbId ||
                                                                                            (t.Movie.Title.ToLowerInvariant() == w.Title.ToLowerInvariant() && t.Movie.Year == w.Year)) != null);

                        // mark all rated movies as watched
                        UIUtils.UpdateStatus($"Importing {lWatchedCsvMovies.Count} IMDb movies as watched...");

                        int lPageSize = AppSettings.BatchSize;
                        int lPages    = (int)Math.Ceiling((double)lRatedCsvMovies.Count / lPageSize);
                        for (int i = 0; i < lPages; i++)
                        {
                            UIUtils.UpdateStatus($"Importing page {i + 1}/{lPages} IMDb movies as watched...");

                            var lMoviesToSync = new TraktMovieWatchedSync()
                            {
                                Movies = lWatchedCsvMovies.Skip(i * lPageSize).Take(lPageSize).ToList()
                            };

                            var lResponse = TraktAPI.AddMoviesToWatchedHistory(lMoviesToSync);
                            if (lResponse == null)
                            {
                                UIUtils.UpdateStatus("Failed to send watched status for IMDb movies to trakt.tv", true);
                                Thread.Sleep(2000);
                            }
                            else if (lResponse.NotFound.Movies.Count > 0)
                            {
                                UIUtils.UpdateStatus($"Unable to sync watched states for {lResponse.NotFound.Movies.Count} movies as they're not found on trakt.tv!");
                                Thread.Sleep(1000);
                            }
                            if (mImportCancelled)
                            {
                                return;
                            }
                        }
                    }
                }
                #endregion

                #region Episodes
                if (lImdbRatedEpisodes != null && lImdbRatedEpisodes.Any())
                {
                    int lPageSize = AppSettings.BatchSize;
                    int lPages    = (int)Math.Ceiling((double)lImdbRatedEpisodes.Count / lPageSize);
                    for (int i = 0; i < lPages; i++)
                    {
                        var lEpisodesWatched = Helper.GetTraktEpisodeWatchedData(lImdbRatedEpisodes.Skip(i * lPageSize).Take(lPageSize));

                        UIUtils.UpdateStatus($"Importing page {i + 1}/{lPages} IMDb watched episodes...");

                        var lResponse = TraktAPI.AddEpisodesToWatchedHistory(lEpisodesWatched);
                        if (lResponse == null)
                        {
                            UIUtils.UpdateStatus("Error importing IMDb episodes as watched to trakt.tv", true);
                            Thread.Sleep(2000);
                        }
                        else if (lResponse.NotFound.Episodes.Count > 0)
                        {
                            UIUtils.UpdateStatus($"Unable to sync {lResponse.NotFound.Episodes.Count} IMDb episodes as watched, as they're not found on trakt.tv!");
                            Thread.Sleep(1000);
                        }

                        if (mImportCancelled)
                        {
                            return;
                        }
                    }
                }
                #endregion
            }
            #endregion

            #region Import Watchlist Movies
            var lWatchlistedCsvMovies = lWatchlistCsvItems.Where(r => r.Type.ItemType() == IMDbType.Movie)
                                        .Select(s => s.ToTraktMovie()).ToList();

            FileLog.Info($"Found {lWatchlistedCsvMovies.Count} movies watchlisted in CSV file");
            if (lWatchlistedCsvMovies.Any())
            {
                UIUtils.UpdateStatus("Requesting existing watchlisted movies from trakt...");
                var lWatchlistTraktMovies = TraktAPI.GetWatchlistMovies();
                if (lWatchlistTraktMovies != null)
                {
                    UIUtils.UpdateStatus($"Found {lWatchlistTraktMovies.Count()} watchlist movies on trakt");
                    UIUtils.UpdateStatus("Filtering out watchlist movies that are already in watchlist on trakt.tv");
                    lWatchlistedCsvMovies.RemoveAll(w => lWatchlistTraktMovies.FirstOrDefault(t => t.Movie.Ids.ImdbId == w.Ids.ImdbId ||
                                                                                              (t.Movie.Title.ToLowerInvariant() == w.Title.ToLowerInvariant() && t.Movie.Year == w.Year)) != null);
                }

                if (AppSettings.IgnoreWatchedForWatchlist && lWatchlistedCsvMovies.Count > 0)
                {
                    // get watched movies from trakt so we don't import movies into watchlist that are already watched
                    // we may already have this if we imported rated items as watched
                    if (lWatchedTraktMovies != null)
                    {
                        UIUtils.UpdateStatus("Requesting watched movies from trakt...");
                        lWatchedTraktMovies = TraktAPI.GetWatchedMovies();
                        if (lWatchedTraktMovies == null)
                        {
                            UIUtils.UpdateStatus("Failed to get watched movies from trakt.tv", true);
                            Thread.Sleep(2000);
                        }
                    }

                    if (lWatchedTraktMovies != null)
                    {
                        UIUtils.UpdateStatus($"Found {lWatchedTraktMovies.Count()} watched movies on trakt");
                        UIUtils.UpdateStatus("Filtering out watchlist movies that are watched on trakt.tv");

                        // remove movies from sync list which are watched already
                        lWatchlistedCsvMovies.RemoveAll(w => lWatchedTraktMovies.FirstOrDefault(t => t.Movie.Ids.ImdbId == w.Ids.ImdbId ||
                                                                                                (t.Movie.Title.ToLowerInvariant() == w.Title.ToLowerInvariant() && t.Movie.Year == w.Year)) != null);
                    }
                }

                // add movies to watchlist
                UIUtils.UpdateStatus($"Importing {lWatchlistedCsvMovies.Count()} IMDb watchlist movies to trakt.tv...");

                int lPageSize = AppSettings.BatchSize;
                int lPages    = (int)Math.Ceiling((double)lWatchlistedCsvMovies.Count / lPageSize);
                for (int i = 0; i < lPages; i++)
                {
                    UIUtils.UpdateStatus($"Importing page {i + 1}/{lPages} IMDb watchlist movies...");

                    var lWatchlistedToSync = new TraktMovieSync()
                    {
                        Movies = lWatchlistedCsvMovies.Skip(i * lPageSize).Take(lPageSize).ToList()
                    };

                    var lResponse = TraktAPI.AddMoviesToWatchlist(lWatchlistedToSync);
                    if (lResponse == null)
                    {
                        UIUtils.UpdateStatus("Failed to send watchlist for IMDb movies", true);
                        Thread.Sleep(2000);
                    }
                    else if (lResponse.NotFound.Movies.Count > 0)
                    {
                        UIUtils.UpdateStatus($"Unable to sync watchlist for {lResponse.NotFound.Movies.Count} movies as they're not found on trakt.tv!");
                        Thread.Sleep(1000);
                    }

                    if (mImportCancelled)
                    {
                        return;
                    }
                }
            }
            if (mImportCancelled)
            {
                return;
            }
            #endregion

            #region Import Watchlist TV Shows
            IEnumerable <TraktShowPlays> lWatchedTraktShows = null;
            var lWatchlistedCsvShows = lWatchlistCsvItems.Where(r => r.Type.ItemType() == IMDbType.Show)
                                       .Select(s => s.ToTraktShow()).ToList();

            FileLog.Info($"Found {lWatchlistedCsvShows.Count} tv shows watchlisted in CSV file");
            if (lWatchlistedCsvShows.Any())
            {
                UIUtils.UpdateStatus("Requesting existing watchlisted shows from trakt...");
                var lWatchlistTraktShows = TraktAPI.GetWatchlistShows();
                if (lWatchlistTraktShows != null)
                {
                    UIUtils.UpdateStatus($"Found {lWatchlistTraktShows.Count()} watchlist shows on trakt");
                    UIUtils.UpdateStatus("Filtering out watchlist shows that are already in watchlist on trakt.tv");
                    lWatchlistedCsvShows.RemoveAll(w => lWatchlistTraktShows.FirstOrDefault(t => t.Show.Ids.ImdbId == w.Ids.ImdbId ||
                                                                                            (t.Show.Title.ToLowerInvariant() == w.Title.ToLowerInvariant() && t.Show.Year == w.Year)) != null);
                }

                if (AppSettings.IgnoreWatchedForWatchlist && lWatchlistedCsvShows.Count > 0)
                {
                    UIUtils.UpdateStatus("Requesting watched shows from trakt...");

                    // get watched movies from trakt so we don't import shows into watchlist that are already watched
                    lWatchedTraktShows = TraktAPI.GetWatchedShows();
                    if (lWatchedTraktShows != null)
                    {
                        UIUtils.UpdateStatus($"Found {lWatchedTraktShows.Count()} watched shows on trakt");
                        UIUtils.UpdateStatus("Filtering out watchlist shows containing watched episodes on trakt.tv.");

                        // remove shows from sync list which are watched already
                        lWatchlistedCsvShows.RemoveAll(w => lWatchedTraktShows.FirstOrDefault(t => (t.Show.Ids.ImdbId == w.Ids.ImdbId) ||
                                                                                              (t.Show.Title.ToLowerInvariant() == w.Title.ToLowerInvariant() && t.Show.Year == w.Year)) != null);
                    }
                }

                // add shows to watchlist
                UIUtils.UpdateStatus($"Importing {lWatchlistedCsvShows.Count()} IMDb watchlist shows to trakt.tv...");

                int lPageSize = AppSettings.BatchSize;
                int lPages    = (int)Math.Ceiling((double)lWatchlistedCsvShows.Count / lPageSize);
                for (int i = 0; i < lPages; i++)
                {
                    UIUtils.UpdateStatus($"Importing page {i + 1}/{lPages} IMDb watchlist shows...");

                    var lWatchlistShowsToSync = new TraktShowSync
                    {
                        Shows = lWatchlistedCsvShows.Skip(i * lPageSize).Take(lPageSize).ToList()
                    };

                    var lResponse = TraktAPI.AddShowsToWatchlist(lWatchlistShowsToSync);
                    if (lResponse == null)
                    {
                        UIUtils.UpdateStatus("Failed to send watchlist for IMDb tv shows", true);
                        Thread.Sleep(2000);
                    }
                    else if (lResponse.NotFound.Shows.Count > 0)
                    {
                        UIUtils.UpdateStatus($"Unable to sync watchlist for {lResponse.NotFound.Shows.Count} shows as they're not found on trakt.tv!");
                        Thread.Sleep(1000);
                    }

                    if (mImportCancelled)
                    {
                        return;
                    }
                }
            }
            if (mImportCancelled)
            {
                return;
            }
            #endregion

            #region Import Watchlist Episodes
            var lImdbWatchlistedEpisodes    = new List <IMDbEpisode>();
            var lImdbWatchlistedCsvEpisodes = lWatchlistCsvItems.Where(r => r.Type.ItemType() == IMDbType.Episode).ToList();

            FileLog.Info($"Found {lImdbWatchlistedCsvEpisodes.Count} tv episodes watchlisted in CSV file");

            if (lImdbWatchlistedCsvEpisodes.Any())
            {
                UIUtils.UpdateStatus($"Found {lImdbWatchlistedCsvEpisodes.Count()} IMDb watchlisted episodes");

                lImdbWatchlistedEpisodes.AddRange(lImdbWatchlistedCsvEpisodes.Select(Helper.GetIMDbEpisodeFromTrakt).Where(imdbEpisode => imdbEpisode != null));
                if (mImportCancelled)
                {
                    return;
                }

                // filter out existing watchlist episodes
                UIUtils.UpdateStatus("Requesting existing watchlist episodes from trakt...");
                var lWatchlistedTraktEpisodes = TraktAPI.GetWatchlistEpisodes();
                if (lWatchlistedTraktEpisodes != null)
                {
                    UIUtils.UpdateStatus($"Found {lWatchlistedTraktEpisodes.Count()} watchlist episodes on trakt");
                    UIUtils.UpdateStatus("Filtering out watchlist episodes that are already in watchlist on trakt.tv");
                    lImdbWatchlistedEpisodes.RemoveAll(e => lWatchlistedTraktEpisodes.FirstOrDefault(w => w.Episode.Ids.Trakt == e.TraktId) != null);
                }

                if (AppSettings.IgnoreWatchedForWatchlist && lImdbWatchlistedEpisodes.Count > 0)
                {
                    // we already might have it from the shows sync
                    if (lWatchedTraktShows == null)
                    {
                        UIUtils.UpdateStatus("Requesting watched episodes from trakt...");

                        // get watched episodes from trakt so we don't import episodes into watchlist that are already watched
                        lWatchedTraktShows = TraktAPI.GetWatchedShows();
                    }

                    if (lWatchedTraktShows != null)
                    {
                        UIUtils.UpdateStatus("Filtering out watchlist episodes containing watched episodes on trakt.tv");

                        // this wont work atm due to show IMDb ID not being set in the IMDbEpisode object
                        lImdbWatchlistedEpisodes.RemoveAll(e => lWatchedTraktShows.Where(s => s.Show.Ids.ImdbId == e.ShowImdbId)
                                                           .Any(s => s.Seasons.Exists(se => se.Number == e.SeasonNumber &&
                                                                                      se.Episodes.Exists(ep => ep.Number == e.EpisodeNumber))));
                    }
                }

                UIUtils.UpdateStatus($"Importing {lImdbWatchlistedEpisodes.Count()} episodes in watchlist to trakt.tv");

                if (lImdbWatchlistedEpisodes.Count > 0)
                {
                    int lPageSize = AppSettings.BatchSize;
                    int lPages    = (int)Math.Ceiling((double)lImdbWatchlistedEpisodes.Count / lPageSize);
                    for (int i = 0; i < lPages; i++)
                    {
                        UIUtils.UpdateStatus($"Importing page {i + 1}/{lPages} IMDb watchlisted episodes...");

                        var lResponse = TraktAPI.AddEpisodesToWatchlist(Helper.GetTraktEpisodeData(lImdbWatchlistedEpisodes.Skip(i * lPageSize).Take(lPageSize)));
                        if (lResponse == null)
                        {
                            UIUtils.UpdateStatus("Error importing IMDb episode watchlist to trakt.tv", true);
                            Thread.Sleep(2000);
                        }
                        else if (lResponse.NotFound.Episodes.Count > 0)
                        {
                            UIUtils.UpdateStatus("Unable to sync watchlist for {0} IMDb episodes as they're not found on trakt.tv!", lResponse.NotFound.Episodes.Count);
                            Thread.Sleep(1000);
                        }

                        if (mImportCancelled)
                        {
                            return;
                        }
                    }
                }
            }
            #endregion

            #region Import Custom Lists
            if (lCustomLists.Count > 0)
            {
                UIUtils.UpdateStatus("Requesting custom lists from trakt...");
                var lTraktCustomLists = TraktAPI.GetCustomLists();
                if (lTraktCustomLists == null)
                {
                    UIUtils.UpdateStatus("Error requesting custom lists from trakt.tv", true);
                    Thread.Sleep(2000);
                    return;
                }

                UIUtils.UpdateStatus($"Found {lTraktCustomLists.Count()} custom lists on trakt.tv");

                foreach (var list in lCustomLists)
                {
                    bool   lListCreated = false;
                    string lListName    = Path.GetFileNameWithoutExtension(list.Key);

                    // create the list if we don't have it
                    TraktListDetail lTraktCustomList = lTraktCustomLists.FirstOrDefault(l => l.Name == lListName);

                    if (lTraktCustomList == null)
                    {
                        UIUtils.UpdateStatus($"Creating new custom list '{lListName}' on trakt.tv");
                        var lTraktList = new TraktList
                        {
                            Name           = lListName,
                            DisplayNumbers = true,
                        };

                        lTraktCustomList = TraktAPI.CreateCustomList(lTraktList);
                        if (lTraktCustomList == null)
                        {
                            UIUtils.UpdateStatus("Error creating custom list on trakt.tv, skipping list creation", true);
                            Thread.Sleep(2000);
                            continue;
                        }

                        lListCreated = true;
                    }

                    // get the CSV list items parsed
                    var lIMDbCsvListItems = list.Value;

                    var lImdbCsvListMovies = lIMDbCsvListItems.Where(l => l.Type.ItemType() == IMDbType.Movie).Select(m => m.ToTraktMovie()).ToList();
                    var lImdbCsvListShows  = lIMDbCsvListItems.Where(l => l.Type.ItemType() == IMDbType.Show).Select(m => m.ToTraktShow()).ToList();

                    FileLog.Info($"Found {lIMDbCsvListItems.Count} movies and {lImdbCsvListShows.Count} shows in IMDb {lListName} list", lListName);

                    // if the list already exists, get current items for list
                    if (!lListCreated)
                    {
                        lTraktCustomList = lTraktCustomLists.FirstOrDefault(l => l.Name == lListName);

                        UIUtils.UpdateStatus($"Requesting existing custom list '{lListName}' items from trakt...");
                        var lTraktListItems = TraktAPI.GetCustomListItems(lTraktCustomList.Ids.Trakt.ToString());
                        if (lTraktListItems == null)
                        {
                            UIUtils.UpdateStatus("Error requesting custom list items from trakt.tv, skipping list creation", true);
                            Thread.Sleep(2000);
                            continue;
                        }

                        // filter out existing items from CSV so we don't send again
                        FileLog.Info($"Filtering out existing items from IMDb list '{lListName}' so we don't send again to trakt.tv");
                        lImdbCsvListMovies.RemoveAll(i => lTraktListItems.FirstOrDefault(l => l.Movie.Ids.ImdbId == i.Ids.ImdbId) != null);
                        lImdbCsvListShows.RemoveAll(i => lTraktListItems.FirstOrDefault(l => l.Show.Ids.ImdbId == i.Ids.ImdbId) != null);
                    }

                    #region Movies

                    UIUtils.UpdateStatus($"Importing {lImdbCsvListMovies.Count} new movies into {lListName} custom list...");

                    int lPageSize = AppSettings.BatchSize;
                    int lPages    = (int)Math.Ceiling((double)lImdbCsvListMovies.Count / lPageSize);
                    for (int i = 0; i < lPages; i++)
                    {
                        UIUtils.UpdateStatus($"Importing page {i + 1}/{lPages} IMDb custom list movies...");

                        // create list sync object to hold list items
                        var lTraktMovieSync = new TraktSyncAll
                        {
                            Movies = lImdbCsvListMovies.Skip(i * lPageSize).Take(lPageSize).ToList()
                        };

                        var lResponse = TraktAPI.AddItemsToList(lTraktCustomList.Ids.Trakt.ToString(), lTraktMovieSync);
                        if (lResponse == null)
                        {
                            UIUtils.UpdateStatus("Failed to send custom list items for IMDb movies", true);
                            Thread.Sleep(2000);
                        }
                        else if (lResponse.NotFound.Movies.Count > 0)
                        {
                            UIUtils.UpdateStatus($"Unable to sync custom list items for {lResponse.NotFound.Movies.Count} movies as they're not found on trakt.tv!");
                            Thread.Sleep(1000);
                        }

                        if (mImportCancelled)
                        {
                            return;
                        }
                    }
                    #endregion

                    #region Shows

                    UIUtils.UpdateStatus("Importing {0} new shows into {1} custom list...", lImdbCsvListShows.Count(), lListName);

                    lPageSize = AppSettings.BatchSize;
                    lPages    = (int)Math.Ceiling((double)lImdbCsvListShows.Count / lPageSize);
                    for (int i = 0; i < lPages; i++)
                    {
                        UIUtils.UpdateStatus("Importing page {0}/{1} IMDb custom list shows...", i + 1, lPages);

                        // create list sync object to hold list items
                        var lTraktShowSync = new TraktSyncAll
                        {
                            Shows = lImdbCsvListShows.Skip(i * lPageSize).Take(lPageSize).ToList()
                        };

                        var lResponse = TraktAPI.AddItemsToList(lTraktCustomList.Ids.Trakt.ToString(), lTraktShowSync);
                        if (lResponse == null)
                        {
                            UIUtils.UpdateStatus("Failed to send custom list items for IMDb shows", true);
                            Thread.Sleep(2000);
                        }
                        else if (lResponse.NotFound.Shows.Count > 0)
                        {
                            UIUtils.UpdateStatus("Unable to sync custom list items for {0} shows as they're not found on trakt.tv!", lResponse.NotFound.Shows.Count);
                            Thread.Sleep(1000);
                        }

                        if (mImportCancelled)
                        {
                            return;
                        }
                    }

                    #endregion
                }
            }
            #endregion
        }
Ejemplo n.º 14
0
        public void Draw(ParentNode owner, GUIStyle toolbarstyle, Material mat)
        {
            Color cachedColor = GUI.color;

            GUI.color = new Color(cachedColor.r, cachedColor.g, cachedColor.b, 0.5f);
            EditorGUILayout.BeginHorizontal(toolbarstyle);
            GUI.color = cachedColor;
            owner.ContainerGraph.ParentWindow.InnerWindowVariables.OutlineActiveMode = owner.GUILayoutToggle(owner.ContainerGraph.ParentWindow.InnerWindowVariables.OutlineActiveMode, EditorVariablesManager.OutlineActiveMode.LabelName, UIUtils.MenuItemToggleStyle, GUILayout.ExpandWidth(true));
            EditorGUI.BeginChangeCheck();
            m_enabled = owner.EditorGUILayoutToggle(string.Empty, m_enabled, UIUtils.MenuItemEnableStyle, GUILayout.Width(16));
            if (EditorGUI.EndChangeCheck())
            {
                if (m_enabled)
                {
                    UpdateToMaterial(mat);
                }

                UIUtils.RequestSave();
            }
            EditorGUILayout.EndHorizontal();

            if (owner.ContainerGraph.ParentWindow.InnerWindowVariables.OutlineActiveMode)
            {
                cachedColor = GUI.color;
                GUI.color   = new Color(cachedColor.r, cachedColor.g, cachedColor.b, (EditorGUIUtility.isProSkin ? 0.5f : 0.25f));
                EditorGUILayout.BeginVertical(UIUtils.MenuItemBackgroundStyle);
                GUI.color = cachedColor;

                EditorGUILayout.Separator();
                EditorGUI.BeginDisabledGroup(!m_enabled);

                EditorGUI.indentLevel += 1;
                {
                    m_mode = (OutlineMode)owner.EditorGUILayoutEnumPopup(ModePropertyStr, m_mode);

                    EditorGUI.BeginChangeCheck();
                    m_outlineColor = owner.EditorGUILayoutColorField(OutlineColorLabel, m_outlineColor);
                    if (EditorGUI.EndChangeCheck() && mat != null)
                    {
                        if (mat.HasProperty(ColorPropertyName))
                        {
                            mat.SetColor(ColorPropertyName, m_outlineColor);
                        }
                    }

                    EditorGUI.BeginChangeCheck();
                    m_outlineWidth = owner.EditorGUILayoutFloatField(OutlineWidthLabel, m_outlineWidth);
                    if (EditorGUI.EndChangeCheck() && mat != null)
                    {
                        if (mat.HasProperty(WidthPropertyName))
                        {
                            mat.SetFloat(WidthPropertyName, m_outlineWidth);
                        }
                    }

                    m_noFog = owner.EditorGUILayoutToggle(NoFogStr, m_noFog);
                }

                EditorGUI.indentLevel -= 1;
                EditorGUI.EndDisabledGroup();
                EditorGUILayout.Separator();
                EditorGUILayout.EndVertical();
            }
        }
 public override void OnPropertyNameChanged()
 {
     base.OnPropertyNameChanged();
     UIUtils.UpdateTexturePropertyDataNode(UniqueId, PropertyInspectorName);
 }
Ejemplo n.º 16
0
        public override string GenerateShaderForOutput(int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar)
        {
            base.GenerateShaderForOutput(outputId, ref dataCollector, ignoreLocalvar);
            m_precisionString = UIUtils.FinalPrecisionWirePortToCgType(m_currentPrecisionType, m_outputPorts[0].DataType);

            if (m_currentParameterType != PropertyType.Constant)
            {
                return(GetOutputVectorItem(0, outputId, PropertyData));
            }

            if (m_outputPorts[outputId].IsLocalValue)
            {
                return(m_outputPorts[outputId].LocalValue);
            }

            if (CheckLocalVariable(ref dataCollector))
            {
                return(m_outputPorts[outputId].LocalValue);
            }

            Vector4 value  = m_defaultValue;
            string  result = string.Empty;

            switch (outputId)
            {
            case 0:
            {
                result = m_precisionString + "(" + value.x + "," + value.y + "," + value.z + "," + value.w + ")";
            }
            break;

            case 1:
            {
                result = value.x.ToString();
            }
            break;

            case 2:
            {
                result = value.y.ToString();
            }
            break;

            case 3:
            {
                result = value.z.ToString();
            }
            break;

            case 4:
            {
                result = value.w.ToString();
            }
            break;
            }

            if (result.Equals(string.Empty))
            {
                UIUtils.ShowMessage("Vector4Node generating empty code", MessageSeverity.Warning);
            }
            return(result);
        }
Ejemplo n.º 17
0
 public void FocusPane()
 {
     UIUtils.Focus(this.hexBox);
 }
    void Update()
    {
        Player player = Utils.ClientLocalPlayer();

        if (!player)
        {
            return;
        }

        // only if trading, otherwise set inactive
        if (player.state == "TRADING" && player.target != null && player.target is Player)
        {
            panel.SetActive(true);
            Player other = (Player)player.target;

            // OTHER ///////////////////////////////////////////////////////////
            // status text
            if (other.tradeStatus == TradeStatus.Accepted)
            {
                otherStatusText.text = "[ACCEPTED]";
            }
            else if (other.tradeStatus == TradeStatus.Locked)
            {
                otherStatusText.text = "[LOCKED]";
            }
            else
            {
                otherStatusText.text = "";
            }

            // gold input
            otherGoldInput.text = other.tradeOfferGold.ToString();

            // items
            UIUtils.BalancePrefabs(slotPrefab.gameObject, other.tradeOfferItems.Count, otherContent);
            for (int i = 0; i < other.tradeOfferItems.Count; ++i)
            {
                UIPlayerTradingSlot slot = otherContent.GetChild(i).GetComponent <UIPlayerTradingSlot>();
                int inventoryIndex       = other.tradeOfferItems[i];

                slot.dragAndDropable.dragable = false;
                slot.dragAndDropable.dropable = false;

                if (0 <= inventoryIndex && inventoryIndex < other.inventory.Count &&
                    other.inventory[inventoryIndex].amount > 0)
                {
                    ItemSlot itemSlot = other.inventory[inventoryIndex];

                    // refresh valid item
                    slot.tooltip.enabled = true;
                    slot.tooltip.text    = itemSlot.ToolTip();
                    slot.image.color     = Color.white;
                    slot.image.sprite    = itemSlot.item.image;
                    slot.amountOverlay.SetActive(itemSlot.amount > 1);
                    slot.amountText.text = itemSlot.amount.ToString();
                }
                else
                {
                    // refresh invalid item
                    slot.tooltip.enabled = false;
                    slot.image.color     = Color.clear;
                    slot.image.sprite    = null;
                    slot.amountOverlay.SetActive(false);
                }
            }

            // SELF ////////////////////////////////////////////////////////////
            // status text
            if (player.tradeStatus == TradeStatus.Accepted)
            {
                myStatusText.text = "[ACCEPTED]";
            }
            else if (player.tradeStatus == TradeStatus.Locked)
            {
                myStatusText.text = "[LOCKED]";
            }
            else
            {
                myStatusText.text = "";
            }

            // gold input
            if (player.tradeStatus == TradeStatus.Free)
            {
                myGoldInput.interactable = true;
                myGoldInput.onValueChanged.SetListener(val => {
                    long goldOffer   = Utils.Clamp(val.ToLong(), 0, player.gold);
                    myGoldInput.text = goldOffer.ToString();
                    player.CmdTradeOfferGold(goldOffer);
                });
            }
            else
            {
                myGoldInput.interactable = false;
                myGoldInput.text         = player.tradeOfferGold.ToString();
            }

            // items
            UIUtils.BalancePrefabs(slotPrefab.gameObject, player.tradeOfferItems.Count, myContent);
            for (int i = 0; i < player.tradeOfferItems.Count; ++i)
            {
                UIPlayerTradingSlot slot = myContent.GetChild(i).GetComponent <UIPlayerTradingSlot>();
                slot.dragAndDropable.name = i.ToString(); // drag and drop index
                int inventoryIndex = player.tradeOfferItems[i];

                if (0 <= inventoryIndex && inventoryIndex < player.inventory.Count &&
                    player.inventory[inventoryIndex].amount > 0)
                {
                    ItemSlot itemSlot = player.inventory[inventoryIndex];

                    // refresh valid item
                    slot.tooltip.enabled          = true;
                    slot.tooltip.text             = itemSlot.ToolTip();
                    slot.dragAndDropable.dragable = player.tradeStatus == TradeStatus.Free;
                    slot.image.color  = Color.white;
                    slot.image.sprite = itemSlot.item.image;
                    slot.amountOverlay.SetActive(itemSlot.amount > 1);
                    slot.amountText.text = itemSlot.amount.ToString();
                }
                else
                {
                    // refresh invalid item
                    slot.tooltip.enabled          = false;
                    slot.dragAndDropable.dragable = false;
                    slot.image.color  = Color.clear;
                    slot.image.sprite = null;
                    slot.amountOverlay.SetActive(false);
                }
            }

            // buttons /////////////////////////////////////////////////////////
            // lock
            lockButton.interactable = player.tradeStatus == TradeStatus.Free;
            lockButton.onClick.SetListener(() => {
                player.CmdTradeOfferLock();
            });

            // accept (only if both have locked the trade & if not accepted yet)
            // accept (if not accepted yet & other has locked or accepted)
            acceptButton.interactable = player.tradeStatus == TradeStatus.Locked &&
                                        other.tradeStatus != TradeStatus.Free;
            acceptButton.onClick.SetListener(() => {
                player.CmdTradeOfferAccept();
            });

            // cancel
            cancelButton.onClick.SetListener(() => {
                player.CmdTradeCancel();
            });
        }
        else
        {
            panel.SetActive(false);
#if !UNITY_2017_2                   // workaround for Unity 2017.2 UI bug #960900
            myGoldInput.text = "0"; // reset
#endif
        }
    }
Ejemplo n.º 19
0
		public override bool GetUniformData( out string dataType, out string dataName, ref bool fullValue )
		{
			dataType = UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, WirePortDataType.FLOAT4x4 ):
			dataName = m_propertyName:
			return true:
		}
Ejemplo n.º 20
0
    void Update()
    {
        Player player = Utils.ClientLocalPlayer();

        if (!player)
        {
            return;
        }

        // hotkey (not while typing in chat, etc.)
        if (Input.GetKeyDown(hotKey) && !UIUtils.AnyInputActive())
        {
            panel.SetActive(!panel.activeSelf);
        }

        // only update the panel if it's active
        if (panel.activeSelf)
        {
            // instantiate/destroy enough category slots
            UIUtils.BalancePrefabs(categorySlotPrefab.gameObject, player.itemMallCategories.Length, categoryContent);

            // refresh all category buttons
            for (int i = 0; i < player.itemMallCategories.Length; ++i)
            {
                Button button = categoryContent.GetChild(i).GetComponent <Button>();
                button.interactable = i != currentCategory;
                button.GetComponentInChildren <Text>().text = player.itemMallCategories[i].category;
                int icopy = i; // needed for lambdas, otherwise i is Count
                button.onClick.SetListener(() => {
                    // set new category and then scroll to the top again
                    currentCategory = icopy;
                    ScrollToBeginning();
                });
            }

            if (player.itemMallCategories.Length > 0)
            {
                // instantiate/destroy enough item slots for that category
                ScriptableItem[] items = player.itemMallCategories[currentCategory].items;
                UIUtils.BalancePrefabs(itemSlotPrefab.gameObject, items.Length, itemContent);

                // refresh all items in that category
                for (int i = 0; i < items.Length; ++i)
                {
                    UIItemMallSlot slot     = itemContent.GetChild(i).GetComponent <UIItemMallSlot>();
                    ScriptableItem itemData = items[i];

                    // refresh item
                    slot.tooltip.text              = new Item(itemData).ToolTip();
                    slot.image.color               = Color.white;
                    slot.image.sprite              = itemData.image;
                    slot.nameText.text             = itemData.name;
                    slot.priceText.text            = itemData.itemMallPrice.ToString();
                    slot.unlockButton.interactable = player.health > 0 && player.coins >= itemData.itemMallPrice;
                    int icopy = i; // needed for lambdas, otherwise i is Count
                    slot.unlockButton.onClick.SetListener(() => {
                        player.CmdUnlockItem(currentCategory, icopy);
                        inventoryPanel.SetActive(true); // better feedback
                    });
                }
            }

            // overview
            nameText.text           = player.name;
            levelText.text          = "Lv. " + player.level;
            currencyAmountText.text = player.coins.ToString();
            buyButton.onClick.SetListener(() => { Application.OpenURL(buyUrl); });
            couponInput.interactable  = NetworkTime.time >= player.nextRiskyActionTime;
            couponButton.interactable = NetworkTime.time >= player.nextRiskyActionTime;
            couponButton.onClick.SetListener(() => {
                if (!Utils.IsNullOrWhiteSpace(couponInput.text))
                {
                    player.CmdEnterCoupon(couponInput.text);
                }
                couponInput.text = "";
            });
        }
    }
Ejemplo n.º 21
0
    void Update()
    {
        GameObject player = Player.player;

        if (!player)
        {
            return;
        }

        PlayerCrafting crafting  = player.GetComponent <PlayerCrafting>();
        Inventory      inventory = player.GetComponent <Inventory>();

        // instantiate/destroy enough slots
        UIUtils.BalancePrefabs(ingredientSlotPrefab.gameObject, crafting.indices.Count, ingredientContent);

        // refresh all
        for (int i = 0; i < crafting.indices.Count; ++i)
        {
            UICraftingIngredientSlot slot = ingredientContent.GetChild(i).GetComponent <UICraftingIngredientSlot>();
            slot.dragAndDropable.name = i.ToString(); // drag and drop index
            int itemIndex = crafting.indices[i];

            if (0 <= itemIndex && itemIndex < inventory.slots.Count &&
                inventory.slots[itemIndex].amount > 0)
            {
                ItemSlot itemSlot = inventory.slots[itemIndex];

                // refresh valid item
                slot.tooltip.enabled          = true;
                slot.tooltip.text             = itemSlot.ToolTip();
                slot.dragAndDropable.dragable = true;
                slot.image.color  = Color.white;
                slot.image.sprite = itemSlot.item.image;
                slot.amountOverlay.SetActive(itemSlot.amount > 1);
                slot.amountText.text = itemSlot.amount.ToString();
            }
            else
            {
                // reset the index because it's invalid
                crafting.indices[i] = -1;

                // refresh invalid item
                slot.tooltip.enabled          = false;
                slot.dragAndDropable.dragable = false;
                slot.image.color  = Color.clear;
                slot.image.sprite = null;
                slot.amountOverlay.SetActive(false);
            }
        }

        // find valid indices => item templates => matching recipe
        List <int> validIndices = crafting.indices.Where(
            index => 0 <= index && index < inventory.slots.Count &&
            inventory.slots[index].amount > 0
            ).ToList();
        List <ItemSlot>  items  = validIndices.Select(index => inventory.slots[index]).ToList();
        ScriptableRecipe recipe = ScriptableRecipe.dict.Values.ToList().Find(r => r.CanCraftWith(items)); // good enough for now

        if (recipe != null)
        {
            // refresh valid recipe
            Item item = new Item(recipe.result);
            resultSlotToolTip.enabled = true;
            resultSlotToolTip.text    = new ItemSlot(item).ToolTip(); // ItemSlot so that {AMOUNT} is replaced too
            resultSlotImage.color     = Color.white;
            resultSlotImage.sprite    = recipe.result.image;
        }
        else
        {
            // refresh invalid recipe
            resultSlotToolTip.enabled = false;
            resultSlotImage.color     = Color.clear;
            resultSlotImage.sprite    = null;
        }

        // craft result
        // (no recipe != null check because it will be null if those were
        //  the last two ingredients in our inventory)
        if (crafting.craftingState == CraftingState.Success)
        {
            resultText.color = successColor;
            resultText.text  = "Success!";
        }
        else if (crafting.craftingState == CraftingState.Failed)
        {
            resultText.color = failedColor;
            resultText.text  = "Failed :(";
        }
        else
        {
            resultText.text = "";
        }

        // craft button with 'Try' prefix to let people know that it might fail
        // (disabled while in progress)
        craftButton.GetComponentInChildren <Text>().text = recipe != null &&
                                                           recipe.probability < 1 ? "Try Craft" : "Craft";
        craftButton.interactable = recipe != null &&
                                   crafting.craftingState != CraftingState.InProgress &&
                                   inventory.CanAdd(new Item(recipe.result), 1);
        craftButton.onClick.SetListener(() => {
            crafting.craftingState = CraftingState.InProgress; // wait for result
            crafting.Craft(validIndices.ToArray());
        });
    }
Ejemplo n.º 22
0
        //public override string PropertyName
        //{
        //	get
        //	{
        //		string propertyName = string.Empty;
        //		switch ( m_virtualChannel )
        //		{
        //			default:
        //			case VirtualChannel.Albedo:
        //			case VirtualChannel.Base:
        //				propertyName = "_MainTex";
        //				break;
        //			case VirtualChannel.Normal:
        //				propertyName = "_BumpMap";
        //				break;
        //			case VirtualChannel.SpecMet:
        //				propertyName = "_MetallicGlossMap";
        //				break;
        //			case VirtualChannel.Occlusion:
        //				propertyName = "_OcclusionMap";
        //				break;
        //		}
        //		return propertyName;
        //	}
        //}

        public override void Destroy()
        {
            base.Destroy();
            UIUtils.RemoveVirtualTextureCount();
        }
Ejemplo n.º 23
0
 private void InstallTransfferingService_Click(object sender, EventArgs e)
 {
     UIUtils.TryStartTransferringServiceAsync();
 }
        void DrawMainBody()
        {
            EditorGUILayout.Separator();
            int itemCount = m_availableTags.Count;

            if (itemCount == 0)
            {
                EditorGUILayout.HelpBox("Your list is Empty!\nUse the plus button to add one.", MessageType.Info);
            }

            int   markedToDelete     = -1;
            float originalLabelWidth = EditorGUIUtility.labelWidth;

            for (int i = 0; i < itemCount; i++)
            {
                m_availableTags[i].TagFoldout = m_currentOwner.EditorGUILayoutFoldout(m_availableTags[i].TagFoldout, string.Format("[{0}] - {1}", i, m_availableTags[i].TagName));
                if (m_availableTags[i].TagFoldout)
                {
                    EditorGUI.indentLevel      += 1;
                    EditorGUIUtility.labelWidth = 70;
                    //Tag Name
                    EditorGUI.BeginChangeCheck();
                    m_availableTags[i].TagName = EditorGUILayout.TextField(TagNameStr, m_availableTags[i].TagName);
                    if (EditorGUI.EndChangeCheck())
                    {
                        m_availableTags[i].TagName = UIUtils.RemoveShaderInvalidCharacters(m_availableTags[i].TagName);
                    }

                    //Tag Value
                    EditorGUI.BeginChangeCheck();
                    m_availableTags[i].TagValue = EditorGUILayout.TextField(TagValueStr, m_availableTags[i].TagValue);
                    if (EditorGUI.EndChangeCheck())
                    {
                        m_availableTags[i].TagValue = UIUtils.RemoveShaderInvalidCharacters(m_availableTags[i].TagValue);
                    }

                    EditorGUIUtility.labelWidth = originalLabelWidth;

                    EditorGUILayout.BeginHorizontal();
                    {
                        GUILayout.Label(" ");
                        // Add new port
                        if (m_currentOwner.GUILayoutButton(string.Empty, UIUtils.PlusStyle, GUILayout.Width(ShaderKeywordButtonLayoutWidth)))
                        {
                            m_availableTags.Insert(i + 1, new CustomTagData());
                            EditorGUI.FocusTextInControl(null);
                        }

                        //Remove port
                        if (m_currentOwner.GUILayoutButton(string.Empty, UIUtils.MinusStyle, GUILayout.Width(ShaderKeywordButtonLayoutWidth)))
                        {
                            markedToDelete = i;
                        }
                    }
                    EditorGUILayout.EndHorizontal();

                    EditorGUI.indentLevel -= 1;
                }
            }
            if (markedToDelete > -1)
            {
                if (m_availableTags.Count > markedToDelete)
                {
                    m_availableTags.RemoveAt(markedToDelete);
                    EditorGUI.FocusTextInControl(null);
                }
            }
            EditorGUILayout.Separator();
        }
Ejemplo n.º 25
0
 public override void FullDeleteConnections()
 {
     UIUtils.DeleteConnection(false, m_nodeId, m_portId, true, true);
 }
Ejemplo n.º 26
0
        public override string GenerateShaderForOutput(int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar)
        {
            if (dataCollector.PortCategory == MasterNodePortCategory.Fragment || dataCollector.PortCategory == MasterNodePortCategory.Debug)
            {
                dataCollector.AddToInput(UniqueId, UIUtils.GetInputDeclarationFromType(m_currentPrecisionType, AvailableSurfaceInputs.WORLD_NORMAL), true);
                //dataCollector.AddToInput( m_uniqueId, Constants.InternalData, false );
                string result = string.Empty;
                if (m_inputPorts[0].IsConnected)
                {
                    dataCollector.AddToInput(UniqueId, Constants.InternalData, false);
                    dataCollector.ForceNormal = true;

                    result = "WorldNormalVector( " + Constants.InputVarStr + " , " + m_inputPorts[0].GenerateShaderForOutput(ref dataCollector, WirePortDataType.FLOAT3, ignoreLocalvar) + " )";

                    if (m_outputPorts[0].ConnectionCount > 1)
                    {
                        dataCollector.AddToLocalVariables(UniqueId, string.Format(NormalVecDecStr, NormalVecValStr + UniqueId, result));
                        return(GetOutputVectorItem(0, outputId, NormalVecValStr + UniqueId));
                    }
                }
                else
                {
                    if (!dataCollector.DirtyNormal)
                    {
                        result = Constants.InputVarStr + ".worldNormal";
                    }
                    else
                    {
                        dataCollector.AddToInput(UniqueId, Constants.InternalData, false);
                        result = GeneratorUtils.GenerateWorldNormal(ref dataCollector, UniqueId);
                    }
                }

                return(GetOutputVectorItem(0, outputId, result));
            }
            else
            {
                if (m_inputPorts[0].IsConnected)
                {
                    string inputTangent = m_inputPorts[0].GeneratePortInstructions(ref dataCollector);

                    dataCollector.AddToVertexLocalVariables(UniqueId, "float3 normalWorld = UnityObjectToWorldNormal( " + Constants.VertexShaderInputStr + ".normal );");
                    dataCollector.AddToVertexLocalVariables(UniqueId, "float4 tangentWorld = float4( UnityObjectToWorldDir( " + Constants.VertexShaderInputStr + ".tangent.xyz ), " + Constants.VertexShaderInputStr + ".tangent.w );");
                    dataCollector.AddToVertexLocalVariables(UniqueId, "float3x3 tangentToWorld = CreateTangentToWorldPerVertex( normalWorld, tangentWorld.xyz, tangentWorld.w );");
                    dataCollector.AddToVertexLocalVariables(UniqueId, "float3 tangentNormal" + UniqueId + " = " + inputTangent + ";");
                    dataCollector.AddToVertexLocalVariables(UniqueId, "float3 modWorldtangent" + UniqueId + " = (tangentToWorld[0] * tangentNormal" + UniqueId + ".x + tangentToWorld[1] * tangentNormal" + UniqueId + ".y + tangentToWorld[2] * tangentNormal" + UniqueId + ".z);");
                    return(GetOutputVectorItem(0, outputId, "modWorldtangent" + UniqueId));
                }
                else
                {
                    dataCollector.AddToVertexLocalVariables(UniqueId, "float3 normalWorld = UnityObjectToWorldNormal( " + Constants.VertexShaderInputStr + ".normal );");
                    return(GetOutputVectorItem(0, outputId, "normalWorld"));
                    //if ( m_outputPorts[ 0 ].IsLocalValue )
                    //	return GetOutputVectorItem( 0, outputId, m_outputPorts[ 0 ].LocalValue );

                    //RegisterLocalVariable( 0, string.Format( "UnityObjectToWorldNormal( {0}.normal )", Constants.VertexShaderInputStr ), ref dataCollector, "normalWorld" );

                    //return GetOutputVectorItem( 0, outputId, m_outputPorts[ 0 ].LocalValue );
                }
                //half3 worldNormal = UnityObjectToWorldNormal( v.normal );
            }
        }
Ejemplo n.º 27
0
        public void UpdateC4(IMiniMapUiAdapter adapter, float rate)
        {
            if (!adapter.isBombMode)
            {
                return;
            }
            _rate     = rate;
            _isC4Drop = adapter.IsC4Drop;
            UIUtils.SetActive(c4Locate, adapter.IsC4Drop);
            if (adapter.IsC4Drop)
            {
                c4LocateRtf.anchoredPosition = new Vector2(adapter.C4DropPosition.x, adapter.C4DropPosition.z) * rate;                   //更新标记位置
            }
            UIUtils.SetActive(ALocateRtf, true);
            UIUtils.SetActive(BLocateRtf, true);
            ALocateRtf.anchoredPosition = new Vector2(adapter.APosition.x, adapter.APosition.z) * rate;
            BLocateRtf.anchoredPosition = new Vector2(adapter.BPosition.x, adapter.BPosition.z) * rate;

            int C4SetStatus = adapter.C4SetStatus;

            if (C4SetStatus == 0)
            {
                UIUtils.SetActive(Anormal, true);
                UIUtils.SetActive(Bnormal, true);
                UIUtils.SetActive(Ared, false);
                UIUtils.SetActive(Bred, false);
            }
            else if (C4SetStatus == 1)
            {
                if (adapter.IsCampPass())
                {
                    UIUtils.SetActive(Anormal, false);
                    UIUtils.SetActive(Bnormal, true);
                    UIUtils.SetActive(Ared, true);
                    UIUtils.SetActive(Bred, false);
                }
                else
                {
                    UIUtils.SetActive(Anormal, false);
                    UIUtils.SetActive(Bnormal, false);
                    UIUtils.SetActive(Ared, true);
                    UIUtils.SetActive(Bred, true);
                }
            }
            else if (C4SetStatus == 2)
            {
                if (adapter.IsCampPass())
                {
                    UIUtils.SetActive(Anormal, true);
                    UIUtils.SetActive(Bnormal, false);
                    UIUtils.SetActive(Ared, false);
                    UIUtils.SetActive(Bred, true);
                }
                else
                {
                    UIUtils.SetActive(Anormal, false);
                    UIUtils.SetActive(Bnormal, false);
                    UIUtils.SetActive(Ared, true);
                    UIUtils.SetActive(Bred, true);
                }
            }
        }
Ejemplo n.º 28
0
		public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalVar )
		{
			if( dataCollector.PortCategory == MasterNodePortCategory.Tessellation )
			{
				UIUtils.ShowMessage( m_nodeAttribs.Name + " cannot be used on Master Node Tessellation port" ):
				return "-1":
			}

			//bool isVertex = ( dataCollector.PortCategory == MasterNodePortCategory.Vertex || dataCollector.PortCategory == MasterNodePortCategory.Tessellation ):

			string tiling = string.Empty:
			string offset = string.Empty:

			string portProperty = string.Empty:
			if( m_texPort.IsConnected )
				portProperty = m_texPort.GeneratePortInstructions( ref dataCollector ):

			if( m_referenceArrayId > -1 )
			{
				TexturePropertyNode temp = UIUtils.GetTexturePropertyNode( m_referenceArrayId ):
				if( temp != null )
				{
					portProperty = temp.BaseGenerateShaderForOutput( outputId, ref dataCollector, ignoreLocalVar ):
				}
			}

			//TEMPLATES
			if( dataCollector.MasterNodeCategory == AvailableShaderTypes.Template )
			{
				if( m_outputPorts[ 0 ].IsLocalValue( dataCollector.PortCategory ) )
					return GetOutputVectorItem( 0, outputId, m_outputPorts[ 0 ].LocalValue( dataCollector.PortCategory ) ):

				string uvName = string.Empty:
				if( dataCollector.TemplateDataCollectorInstance.HasUV( m_textureCoordChannel ) )
				{
					uvName = dataCollector.TemplateDataCollectorInstance.GetUVName( m_textureCoordChannel, m_outputPorts[ 0 ].DataType ):
				}
				else
				{
					uvName = dataCollector.TemplateDataCollectorInstance.RegisterUV( m_textureCoordChannel, m_outputPorts[ 0 ].DataType ):
				}
				string currPropertyName = GetValidPropertyName():
				if( !string.IsNullOrEmpty( portProperty ) && portProperty != "0.0" )
				{
					currPropertyName = portProperty:
				}
				if( !string.IsNullOrEmpty( currPropertyName ) )
				{
					string finalTexCoordName = "uv" + m_textureCoordChannel + currPropertyName:
					string dummyPropertyTexcoords = currPropertyName + "_ST":

					if( m_texCoordsHelper == null )
					{
						m_texCoordsHelper = CreateInstance<Vector4Node>():
						m_texCoordsHelper.ContainerGraph = ContainerGraph:
						m_texCoordsHelper.SetBaseUniqueId( UniqueId, true ):
						m_texCoordsHelper.RegisterPropertyOnInstancing = false:
					}

					if( UIUtils.CurrentWindow.OutsideGraph.IsInstancedShader )
					{
						m_texCoordsHelper.CurrentParameterType = PropertyType.InstancedProperty:
					}
					else
					{
						m_texCoordsHelper.CurrentParameterType = PropertyType.Global:
					}
					m_texCoordsHelper.ResetOutputLocals():
					m_texCoordsHelper.SetRawPropertyName( dummyPropertyTexcoords ):
					dummyPropertyTexcoords = m_texCoordsHelper.GenerateShaderForOutput( 0, ref dataCollector, false ):

					if( m_texcoordSize > 2 )
					{
						dataCollector.AddLocalVariable( UniqueId, m_currentPrecisionType, m_outputPorts[ 0 ].DataType, finalTexCoordName, uvName ):
						dataCollector.AddLocalVariable( UniqueId, finalTexCoordName + ".xy", string.Format( Constants.TilingOffsetFormat, uvName + ".xy", dummyPropertyTexcoords + ".xy", dummyPropertyTexcoords + ".zw" ) + ":" ):
						m_outputPorts[ 0 ].SetLocalValue( finalTexCoordName, dataCollector.PortCategory ):
					}
					else
					{
						RegisterLocalVariable( 0, string.Format( Constants.TilingOffsetFormat, uvName, dummyPropertyTexcoords + ".xy", dummyPropertyTexcoords + ".zw" ), ref dataCollector, finalTexCoordName ):
					}
					//RegisterLocalVariable( 0, string.Format( Constants.TilingOffsetFormat, uvName, dummyPropertyTexcoords+".xy", dummyPropertyTexcoords+".zw" ), ref dataCollector, finalTexCoordName ):
				}
				else
				{
					string finalTexCoordName = "uv" + m_textureCoordChannel + OutputId:
					tiling = m_tilingPort.GeneratePortInstructions( ref dataCollector ):
					offset = m_offsetPort.GeneratePortInstructions( ref dataCollector ):

					if( m_texcoordSize > 2 )
					{
						dataCollector.AddLocalVariable( UniqueId, m_currentPrecisionType, m_outputPorts[ 0 ].DataType, finalTexCoordName, uvName ):
						dataCollector.AddLocalVariable( UniqueId, finalTexCoordName + ".xy", string.Format( Constants.TilingOffsetFormat, uvName + ".xy", tiling, offset ) + ":" ):
						m_outputPorts[ 0 ].SetLocalValue( finalTexCoordName, dataCollector.PortCategory ):
					}
					else
					{
						RegisterLocalVariable( 0, string.Format( Constants.TilingOffsetFormat, uvName, tiling, offset ), ref dataCollector, finalTexCoordName ):
					}
					//RegisterLocalVariable( 0, string.Format( Constants.TilingOffsetFormat, uvName, tiling, offset ), ref dataCollector, finalTexCoordName ):
				}
				return GetOutputVectorItem( 0, outputId, m_outputPorts[ 0 ].LocalValue( dataCollector.PortCategory ) ):
			}

			//SURFACE
			string propertyName = GetValidPropertyName():
			if( !string.IsNullOrEmpty( portProperty ) && portProperty != "0.0" )
			{
				propertyName = portProperty:
			}

			if( m_outputPorts[ 0 ].IsLocalValue( dataCollector.PortCategory ) )
				return GetOutputVectorItem( 0, outputId, m_outputPorts[ 0 ].LocalValue( dataCollector.PortCategory ) ):

			if( !m_tilingPort.IsConnected && m_tilingPort.Vector2InternalData == Vector2.one )
				tiling = null:
			else
				tiling = m_tilingPort.GeneratePortInstructions( ref dataCollector ):

			if( !m_offsetPort.IsConnected && m_offsetPort.Vector2InternalData == Vector2.zero )
				offset = null:
			else
				offset = m_offsetPort.GeneratePortInstructions( ref dataCollector ):

			if( !string.IsNullOrEmpty( propertyName ) /*m_referenceArrayId > -1*/ )
			{
				m_surfaceTexcoordName = GeneratorUtils.GenerateAutoUVs( ref dataCollector, UniqueId, m_textureCoordChannel, propertyName, m_outputPorts[ 0 ].DataType, tiling, offset, OutputId ):
			}
			else
			{
				m_surfaceTexcoordName = GeneratorUtils.GenerateAutoUVs( ref dataCollector, UniqueId, m_textureCoordChannel, null, m_outputPorts[ 0 ].DataType, tiling, offset, OutputId ):
			}

			m_outputPorts[ 0 ].SetLocalValue( m_surfaceTexcoordName, dataCollector.PortCategory ):
			return GetOutputVectorItem( 0, outputId, m_outputPorts[ 0 ].LocalValue( dataCollector.PortCategory ) ):
		}
Ejemplo n.º 29
0
    public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] properties)
    {
        IOUtils.Init();
        Material mat = materialEditor.target as Material;

        if (mat == null)
        {
            return;
        }

        m_instance = materialEditor;

        if (!m_initialized)
        {
            Init();
            m_initialized           = true;
            Undo.undoRedoPerformed += UndoRedoPerformed;
        }

        if (Event.current.type == EventType.Repaint &&
            mat.HasProperty(IOUtils.DefaultASEDirtyCheckId) &&
            mat.GetInt(IOUtils.DefaultASEDirtyCheckId) == 1)
        {
            mat.SetInt(IOUtils.DefaultASEDirtyCheckId, 0);
            UIUtils.ForceUpdateFromMaterial();
            //Event.current.Use();
        }



        if (materialEditor.isVisible)
        {
            GUILayout.BeginVertical();
            {
                GUILayout.Space(3);
                if (GUILayout.Button("Open in Shader Editor"))
                {
                    AmplifyShaderEditorWindow.LoadMaterialToASE(mat);
                }

                GUILayout.BeginHorizontal();
                {
                    if (GUILayout.Button(CopyButtonStr))
                    {
                        Shader shader        = mat.shader;
                        int    propertyCount = UnityEditor.ShaderUtil.GetPropertyCount(shader);
                        string allProperties = string.Empty;
                        for (int i = 0; i < propertyCount; i++)
                        {
                            UnityEditor.ShaderUtil.ShaderPropertyType type = UnityEditor.ShaderUtil.GetPropertyType(shader, i);
                            string name     = UnityEditor.ShaderUtil.GetPropertyName(shader, i);
                            string valueStr = string.Empty;
                            switch (type)
                            {
                            case UnityEditor.ShaderUtil.ShaderPropertyType.Color:
                            {
                                Color value = mat.GetColor(name);
                                valueStr = value.r.ToString() + IOUtils.VECTOR_SEPARATOR +
                                           value.g.ToString() + IOUtils.VECTOR_SEPARATOR +
                                           value.b.ToString() + IOUtils.VECTOR_SEPARATOR +
                                           value.a.ToString();
                            }
                            break;

                            case UnityEditor.ShaderUtil.ShaderPropertyType.Vector:
                            {
                                Vector4 value = mat.GetVector(name);
                                valueStr = value.x.ToString() + IOUtils.VECTOR_SEPARATOR +
                                           value.y.ToString() + IOUtils.VECTOR_SEPARATOR +
                                           value.z.ToString() + IOUtils.VECTOR_SEPARATOR +
                                           value.w.ToString();
                            }
                            break;

                            case UnityEditor.ShaderUtil.ShaderPropertyType.Float:
                            {
                                float value = mat.GetFloat(name);
                                valueStr = value.ToString();
                            }
                            break;

                            case UnityEditor.ShaderUtil.ShaderPropertyType.Range:
                            {
                                float value = mat.GetFloat(name);
                                valueStr = value.ToString();
                            }
                            break;

                            case UnityEditor.ShaderUtil.ShaderPropertyType.TexEnv:
                            {
                                Texture value = mat.GetTexture(name);
                                valueStr = AssetDatabase.GetAssetPath(value);
                            }
                            break;
                            }

                            allProperties += name + IOUtils.FIELD_SEPARATOR + type + IOUtils.FIELD_SEPARATOR + valueStr;

                            if (i < (propertyCount - 1))
                            {
                                allProperties += IOUtils.LINE_TERMINATOR;
                            }
                        }
                        EditorPrefs.SetString(IOUtils.MAT_CLIPBOARD_ID, allProperties);
                    }

                    if (GUILayout.Button(PasteButtonStr))
                    {
                        string propertiesStr = EditorPrefs.GetString(IOUtils.MAT_CLIPBOARD_ID, string.Empty);
                        if (!string.IsNullOrEmpty(propertiesStr))
                        {
                            string[] propertyArr = propertiesStr.Split(IOUtils.LINE_TERMINATOR);
                            bool     validData   = true;
                            try
                            {
                                for (int i = 0; i < propertyArr.Length; i++)
                                {
                                    string[] valuesArr = propertyArr[i].Split(IOUtils.FIELD_SEPARATOR);
                                    if (valuesArr.Length != 3)
                                    {
                                        Debug.LogWarning("Material clipboard data is corrupted");
                                        validData = false;
                                        break;
                                    }
                                    else if (mat.HasProperty(valuesArr[0]))
                                    {
                                        UnityEditor.ShaderUtil.ShaderPropertyType type = (UnityEditor.ShaderUtil.ShaderPropertyType)Enum.Parse(typeof(UnityEditor.ShaderUtil.ShaderPropertyType), valuesArr[1]);
                                        switch (type)
                                        {
                                        case UnityEditor.ShaderUtil.ShaderPropertyType.Color:
                                        {
                                            string[] colorVals = valuesArr[2].Split(IOUtils.VECTOR_SEPARATOR);
                                            if (colorVals.Length != 4)
                                            {
                                                Debug.LogWarning("Material clipboard data is corrupted");
                                                validData = false;
                                                break;
                                            }
                                            else
                                            {
                                                mat.SetColor(valuesArr[0], new Color(Convert.ToSingle(colorVals[0]),
                                                                                     Convert.ToSingle(colorVals[1]),
                                                                                     Convert.ToSingle(colorVals[2]),
                                                                                     Convert.ToSingle(colorVals[3])));
                                            }
                                        }
                                        break;

                                        case UnityEditor.ShaderUtil.ShaderPropertyType.Vector:
                                        {
                                            string[] vectorVals = valuesArr[2].Split(IOUtils.VECTOR_SEPARATOR);
                                            if (vectorVals.Length != 4)
                                            {
                                                Debug.LogWarning("Material clipboard data is corrupted");
                                                validData = false;
                                                break;
                                            }
                                            else
                                            {
                                                mat.SetVector(valuesArr[0], new Vector4(Convert.ToSingle(vectorVals[0]),
                                                                                        Convert.ToSingle(vectorVals[1]),
                                                                                        Convert.ToSingle(vectorVals[2]),
                                                                                        Convert.ToSingle(vectorVals[3])));
                                            }
                                        }
                                        break;

                                        case UnityEditor.ShaderUtil.ShaderPropertyType.Float:
                                        {
                                            mat.SetFloat(valuesArr[0], Convert.ToSingle(valuesArr[2]));
                                        }
                                        break;

                                        case UnityEditor.ShaderUtil.ShaderPropertyType.Range:
                                        {
                                            mat.SetFloat(valuesArr[0], Convert.ToSingle(valuesArr[2]));
                                        }
                                        break;

                                        case UnityEditor.ShaderUtil.ShaderPropertyType.TexEnv:
                                        {
                                            mat.SetTexture(valuesArr[0], AssetDatabase.LoadAssetAtPath <Texture>(valuesArr[2]));
                                        }
                                        break;
                                        }
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                Debug.LogException(e);
                                validData = false;
                            }


                            if (validData)
                            {
                                materialEditor.PropertiesChanged();
                                UIUtils.CopyValuesFromMaterial(mat);
                            }
                            else
                            {
                                EditorPrefs.SetString(IOUtils.MAT_CLIPBOARD_ID, string.Empty);
                            }
                        }
                    }
                }
                GUILayout.EndHorizontal();
                GUILayout.Space(5);
            }
            GUILayout.EndVertical();
        }
        EditorGUI.BeginChangeCheck();
        //base.OnGUI( materialEditor, properties );

        // Draw custom properties instead of calling BASE to use single line texture properties
        materialEditor.SetDefaultGUIWidths();

        if (m_infoField == null)
        {
            m_infoField = typeof(MaterialEditor).GetField("m_InfoMessage", BindingFlags.Instance | BindingFlags.NonPublic);
        }

        string info = m_infoField.GetValue(materialEditor) as string;

        if (!string.IsNullOrEmpty(info))
        {
            EditorGUILayout.HelpBox(info, MessageType.Info);
        }
        else
        {
            GUIUtility.GetControlID("EditorTextField".GetHashCode(), FocusType.Passive, new Rect(0f, 0f, 0f, 0f));
        }
        for (int i = 0; i < properties.Length; i++)
        {
            if ((properties[i].flags & (MaterialProperty.PropFlags.HideInInspector | MaterialProperty.PropFlags.PerRendererData)) == MaterialProperty.PropFlags.None)
            {
                if ((properties[i].flags & MaterialProperty.PropFlags.NoScaleOffset) == MaterialProperty.PropFlags.NoScaleOffset)
                {
                    materialEditor.TexturePropertySingleLine(new GUIContent(properties[i].displayName), properties[i]);
                }
                else
                {
                    float propertyHeight = materialEditor.GetPropertyHeight(properties[i], properties[i].displayName);
                    Rect  controlRect    = EditorGUILayout.GetControlRect(true, propertyHeight, EditorStyles.layerMaskField, new GUILayoutOption[0]);
                    materialEditor.ShaderProperty(controlRect, properties[i], properties[i].displayName);
                }
            }
        }

        EditorGUILayout.Space();
        materialEditor.RenderQueueField();
#if UNITY_5_6_OR_NEWER
        materialEditor.EnableInstancingField();
#endif
#if UNITY_5_6_2 || UNITY_5_6_3 || UNITY_5_6_4 || UNITY_2017_1_OR_NEWER
        materialEditor.DoubleSidedGIField();
#endif
        materialEditor.LightmapEmissionProperty();
        if (m_refreshOnUndo || EditorGUI.EndChangeCheck())
        {
            m_refreshOnUndo = false;

            string isEmissive = mat.GetTag("IsEmissive", false, "false");
            if (isEmissive.Equals("true"))
            {
                mat.globalIlluminationFlags &= (MaterialGlobalIlluminationFlags)3;
            }
            else
            {
                mat.globalIlluminationFlags |= MaterialGlobalIlluminationFlags.EmissiveIsBlack;
            }

            UIUtils.CopyValuesFromMaterial(mat);
        }

        if (materialEditor.RequiresConstantRepaint() && m_lastRenderedTime + 0.032999999821186066 < EditorApplication.timeSinceStartup)
        {
            this.m_lastRenderedTime = EditorApplication.timeSinceStartup;
            materialEditor.Repaint();
        }
    }
Ejemplo n.º 30
0
        private void StartMaintenance(MaintenanceSettings settings)
        {
            if (!CheckAccountDetails() || maintenanceRunning)
            {
                return;
            }

            // update file log with new name
            FileLog.LogFileName = DateTime.Now.ToString("yyyyMMdd_hhmmss") + ".log";

            var maintThread = new Thread(o =>
            {
                maintenanceRunning = true;
                Maintenance.Cancel = false;

                // only one import at a time
                SetControlState(false);

                // Clear Progress
                ClearProgress();

                // Login to trakt.tv
                if (!Login())
                {
                    return;
                }

                // Cleanup user data from trakt.tv
                if (settings.WatchedHistoryEpisodes)
                {
                    Maintenance.RemoveEpisodesFromWatchedHistory();
                }
                if (settings.WatchedHistoryMovies)
                {
                    Maintenance.RemoveMoviesFromWatchedHistory();
                }
                if (settings.CollectedEpisodes)
                {
                    Maintenance.RemoveEpisodesFromCollection();
                }
                if (settings.CollectedMovies)
                {
                    Maintenance.RemoveMoviesFromCollection();
                }
                if (settings.RatedEpisodes)
                {
                    Maintenance.RemoveEpisodesFromRatings();
                }
                if (settings.RatedShows)
                {
                    Maintenance.RemoveShowsFromRatings();
                }
                if (settings.RatedSeasons)
                {
                    Maintenance.RemoveSeasonsFromRatings();
                }
                if (settings.RatedMovies)
                {
                    Maintenance.RemoveMoviesFromRatings();
                }
                if (settings.WatchlistEpisodes)
                {
                    Maintenance.RemoveEpisodesFromWatchlist();
                }
                if (settings.WatchlistShows)
                {
                    Maintenance.RemoveShowsFromWatchlist();
                }
                if (settings.WatchlistSeasons)
                {
                    Maintenance.RemoveSeasonsFromWatchlist();
                }
                if (settings.WatchlistMovies)
                {
                    Maintenance.RemoveMoviesFromWatchlist();
                }

                // finished
                SetControlState(true);
                UIUtils.UpdateStatus("Maintenance Complete!");
                maintenanceRunning = false;
            });

            maintThread.Start();
        }