예제 #1
0
    void Awake()
    {
        float gridPerTile = MetaInformation.Instance().numGridSquaresPerTile;

        gridXVec = MetaInformation.Instance().tileXVector / gridPerTile;
        gridYVec = MetaInformation.Instance().tileYVector / gridPerTile;

        if (attractedCustomers == null)
        {
            attractedCustomers = new List <uint> ();
        }
        if (attractedCustomersWeights == null)
        {
            attractedCustomersWeights = new List <float> ();
        }

        spriteRenderer = GetComponent <SpriteRenderer> ();
        myCollider     = GetComponent <Collider2D> ();
    }
예제 #2
0
 public void Register <Source, SourceData>(string contractName, Func <Source, SourceData> converter, Func <int, SourceData, Source> reverter)
     where Source : class, IDocument
     where SourceData : class
 {
     deserializers.Add(contractName,
                       (m) =>
     {
         SourceData data = Newtonsoft.Json.JsonConvert.DeserializeObject <SourceData>(m.Source.ToString());
         return(reverter(m.Id, data));
     });
     serializers.Add(typeof(Source),
                     (o) =>
     {
         var meta = new MetaInformation {
             Id = (o as IDocument).Id, Type = contractName, Source = converter((Source)o),
         };
         return(Newtonsoft.Json.JsonConvert.SerializeObject(meta));
     });
 }
예제 #3
0
        /// <summary>
        /// Executa o predicado.
        /// </summary>
        /// <param name="queryContext"></param>
        /// <param name="nextPredicate"></param>
        internal override void Execute(QueryContext queryContext, Predicate nextPredicate)
        {
            base.ChildPredicate.Execute(queryContext, nextPredicate);
            queryContext.Tree.Reduce();
            IComparable comparable = null;
            bool        flag       = false;
            Type        type       = null;

            foreach (string str in queryContext.Tree.LeftList)
            {
                MetaInformation metaInformation = queryContext.Cache.GetEntryInternal(str, true).MetaInformation;
                if ((metaInformation == null) || !metaInformation.IsAttributeIndexed(base.AttributeName))
                {
                    throw new Exception("Index is not defined for attribute '" + base.AttributeName + "'");
                }
                IComparable comparable2 = (IComparable)metaInformation[base.AttributeName];
                if (comparable2 != null)
                {
                    type = comparable2.GetType();
                    if (type == typeof(bool))
                    {
                        throw new Exception("MAX cannot be applied to Boolean data type.");
                    }
                    if (!flag)
                    {
                        comparable = comparable2;
                        flag       = true;
                    }
                    if (comparable2.CompareTo(comparable) > 0)
                    {
                        comparable = comparable2;
                    }
                }
            }
            if (((type != typeof(DateTime)) && (type != typeof(string))) && ((type != typeof(char)) && (comparable != null)))
            {
                base.SetResult(queryContext, AggregateFunctionType.MAX, Convert.ToDecimal(comparable));
            }
            else
            {
                base.SetResult(queryContext, AggregateFunctionType.MAX, comparable);
            }
        }
예제 #4
0
    public void RemoveMyIDMapping()
    {
        if (Application.isEditor)
        {
            if (myID != 0)
            {
                var info = MetaInformation.Instance();

                if (info == null)
                {
                    Debug.LogError("MetaInformation.Instance() returned null. The MetaInformation object is necessary.");
                }
                else
                {
                    Debug.LogFormat("Removing ID mapping for {0}", gameObject.name);
                    info.RemoveGeneralMappingForID(myID);
                }
            }
        }
    }
예제 #5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Title = ConfigurationSettings.AppSettings["AppName"].ToString() + " : MetaInformation";
            if (Request.QueryString["MetaInformationid"] != null)
            {
                if (!IsPostBack)
                {
                    hdnMetaInformationId.Value = Request.QueryString["MetaInformationid"].ToString();
                    int MetaInformationId = Convert.ToInt32(Request.QueryString["MetaInformationid"].ToString());

                    MetaInformation _MetaInformation = bMetaInformation.List().Where(m => m.Meta_Id == MetaInformationId).FirstOrDefault();

                    txtTitle.Text        = _MetaInformation.Meta_Title;
                    txtDescription.Text  = _MetaInformation.Meta_Description;
                    chkIsDefault.Checked = (_MetaInformation.Meta_Status == eStatus.Active.ToString()) ? true : false;
                    txtKeywords.Text     = _MetaInformation.Meta_KeyWords;
                    lblBcTitle.Text      = _MetaInformation.Meta_Title;
                }
            }
        }
예제 #6
0
    private void SwitchToEditPhase()
    {
        string validSceneName = "Edit Phase Scene";

        while (SceneManager.GetSceneByName(validSceneName).IsValid())
        {
            validSceneName = validSceneName + "1";
        }

        Scene newScene     = SceneManager.CreateScene(validSceneName);
        Scene currentScene = SceneManager.GetActiveScene();

        SceneManager.UnloadScene(currentScene);
        SceneManager.SetActiveScene(newScene);

        GameObject roomObj = GameObject.Instantiate(MetaInformation.Instance().roomPrefab) as GameObject;
        Shop       newShop = roomObj.GetComponent <Shop> ();

        shop = newShop;

        shopGrid = new ShopGrid(shopGridSizeX, shopGridSizeY, 0, 4);

        FurnitureInfo[] oldFurniture = new FurnitureInfo[furnitureInShop.Count];
        furnitureInShop.CopyTo(oldFurniture);
        furnitureInShop.Clear();

        foreach (FurnitureInfo f in oldFurniture)
        {
            var newFurnitureObj = Furniture.InstantiateFurnitureByID(f.furnitureID);
            var newFurniture    = newFurnitureObj.GetComponent <Furniture> ();

            if (!newFurniture.PlaceAtLocation(newShop, f.position))
            {
                Debug.Log("A furniture was in an invalid position in the savefile!");
                GameObject.Destroy(newFurnitureObj);
            }
        }

        GameObject.Instantiate(MetaInformation.Instance().shopPhaseEditCanvasPrefab);
    }
예제 #7
0
    private void DoGridHandles(ShopMoverGrid f)
    {
        Vector3 xvec = MetaInformation.Instance().tileXVector / MetaInformation.Instance().numGridSquaresPerTile;
        Vector3 yvec = MetaInformation.Instance().tileYVector / MetaInformation.Instance().numGridSquaresPerTile;

        var pos = f.transform.position + (Vector3)f.gridOffset;

        var xExtent = f.gridWidth * xvec;
        var yExtent = f.gridHeight * yvec;



        // Draw lines to handles
        Handles.DrawLine(pos, pos + xExtent);
        Handles.DrawLine(pos, pos + yExtent);


        GridEditor.DrawVec3Handle(pos + xExtent + yExtent, delegate(Vector3 newPos) {
            Undo.RecordObject(f, "Furniture Change Grid X");
            EditorUtility.SetDirty(target);


            IntPair offset     = MetaInformation.Instance().WorldToShopVector(newPos - pos);
            f.MyGrid.gridSizeX = offset.x;
            f.MyGrid.gridSizeY = offset.y;
        });



        // Draw grid
        for (int y = 0; y <= f.gridHeight; y++)
        {
            Handles.DrawLine(pos + y * yvec, pos + y * yvec + f.gridWidth * xvec);
        }
        for (int x = 0; x <= f.gridWidth; x++)
        {
            Handles.DrawLine(pos + x * xvec, pos + x * xvec + f.gridHeight * yvec);
        }
    }
예제 #8
0
    public void DisplayFurnitureItem(FurnitureStack stack)
    {
        MetaInformation info = MetaInformation.Instance();

        if (info != null)
        {
            GameObject furnitureObj = info.GetFurniturePrefabByID(stack.FurnitureID);

            if (furnitureObj != null)
            {
                Furniture furniture = furnitureObj.GetComponent <Furniture> ();

                if (furnitureIcon != null)
                {
                    furnitureIcon.sprite = furniture.GetIcon();
                }
                if (furnitureName != null)
                {
                    furnitureName.text = furnitureObj.name;
                }
                if (furnitureCount != null)
                {
                    furnitureCount.text = stack.Count.ToString();
                }

                representedStack = stack;
                okayToDrag       = true;
                hoverPrefab      = furniture.GetHoveringPrefab();
            }
            else
            {
                Debug.LogErrorFormat("Furniture doesn't exist! Something's wrong.");
            }
        }
        else
        {
            Debug.Log("MetaInformation is null.");
        }
    }
예제 #9
0
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            int             adminId           = Convert.ToInt32(Session[ConfigurationSettings.AppSettings["AdminSession"].ToString()].ToString());
            int             MetaInformationId = Convert.ToInt32(hdnMetaInformationId.Value);
            MetaInformation _otherStr         = bMetaInformation.List().Where(m => m.Meta_Id != MetaInformationId && m.Meta_Title == txtTitle.Text.Trim()).FirstOrDefault();

            if (_otherStr == null)
            {
                MetaInformation MetaInformation = bMetaInformation.List().Where(m => m.Meta_Id == MetaInformationId).FirstOrDefault();
                MetaInformation.Meta_Title        = txtTitle.Text;
                MetaInformation.Meta_Description  = txtDescription.Text;
                MetaInformation.Meta_Status       = (chkIsDefault.Checked) ? eStatus.Active.ToString() : eStatus.InActive.ToString();
                MetaInformation.Meta_UpdatedDate  = DateTime.Now;
                MetaInformation.Administrators_Id = adminId;

                MetaInformation = bMetaInformation.Update(MetaInformation);

                if (String.IsNullOrEmpty(MetaInformation.ErrorMessage))
                {
                    Response.Redirect("/administration/application/MetaInformation.aspx?id=100&redirecturl=admin-MetaInformation-rachna-teracotta");
                }
                else
                {
                    pnlErrorMessage.Attributes.Remove("class");
                    pnlErrorMessage.Attributes["class"] = "alert alert-danger alert-dismissable";
                    pnlErrorMessage.Visible             = true;
                    lblMessage.Text = "Failed!" + MetaInformation.ErrorMessage;
                }
            }
            else
            {
                pnlErrorMessage.Attributes.Remove("class");
                pnlErrorMessage.Attributes["class"] = "alert alert-danger alert-dismissable";
                pnlErrorMessage.Visible             = true;
                lblMessage.Text = "Oops!! MetaInformation detail not updated successfully, because MetaInformation name should not be same as other";
            }
        }
예제 #10
0
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        EditorGUI.BeginProperty(position, label, property);

        position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label);


        Rect dropDownRect = new Rect(position.x, position.y, position.width - 50, position.height);
        Rect countRect    = new Rect(dropDownRect.xMax, position.y, 50, position.height);


        SerializedProperty myItemProp  = property.FindPropertyRelative("itemType");
        SerializedProperty myCountProp = property.FindPropertyRelative("count");


        ItemType myItem  = (ItemType)myItemProp.objectReferenceValue;
        int      myCount = myCountProp.intValue;

        MetaInformation info = MetaInformation.Instance();


        var allItems     = info.GetItemTypeMappings().Select((kv) => kv.Value).ToList();
        var allItemNames = allItems.Select((item) => item.Name).ToArray();

        int myIndex = allItemNames.ToList().IndexOf(myItem.Name);


        EditorGUI.BeginChangeCheck();
        int newIndex = EditorGUI.Popup(dropDownRect, myIndex, allItemNames);

        if (EditorGUI.EndChangeCheck())
        {
        }


        EditorGUI.EndProperty();
    }
예제 #11
0
    public void Update()
    {
        if (gameObject.GetComponent <MetaInformation>() == null)
        {
            throw new System.Exception("Error: Unit with movement does not have MetaInformation script on it");
        }
        MetaInformation mi = gameObject.GetComponent <MetaInformation>();

        gameObject.GetComponent <MetaInformation>().x = (int)Mathf.Round(gameObject.transform.position.x);
        gameObject.GetComponent <MetaInformation>().z = (int)Mathf.Round(gameObject.transform.position.z);
        if (!ready)
        {
            return;
        }
        if (mq.q.Count == 0)
        {
            return;
        }
        Vector3 target = mq.ConsumeMove();

        ready = false;
        gameObject.GetComponent <State>().SetState(Constants.BUSY);
        StartCoroutine(MoveOverSpeed(gameObject, target, 1));
    }
예제 #12
0
        /*  // Implemented, but not used yet. Results are just as good as the method below at this time.
         *      public static MetaInformation GetUrlPreview(string url, string apikey)
         *      {
         *              try
         *              {
         *             using var httpClient = new HttpClient();
         *             httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", apikey);
         *
         *             using Stream s = httpClient.GetStreamAsync($"https://api.labs.cognitive.microsoft.com/urlpreview/v7.0/search?q={url}").Result;
         *             using StreamReader sr = new StreamReader(s);
         *             using JsonReader reader = new JsonTextReader(sr);
         *             var serializer = new JsonSerializer();
         *             var result = serializer.Deserialize<UrlPreviewResult>(reader);
         *
         *             return new MetaInformation(url, result.Name, result.Description, "", result.PrimaryImageOfPage?.ContentUrl, "");
         *         }
         *              catch (Exception ex)
         *              {
         *                      // TODO: We should probably log this somewhere...
         *                      return new MetaInformation(url)
         *                      {
         *                              HasError = true,
         *                              ExternalPageError = ex is WebException
         *                      };
         *              }
         *      }
         */

        /// <summary>
        /// Uses HtmlAgilityPack to get the meta information from a url
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static MetaInformation GetMetaDataFromUrl(string url)
        {
            Guard.IsNotNull(url, nameof(url));

            var metaInfo = new MetaInformation(url);

            try
            {
                // Get the URL specified
                var webGet   = new HtmlWeb();
                var document = webGet.Load(url);
                var metaTags = document.DocumentNode.SelectNodes("//meta");

                if (metaTags != null)
                {
                    foreach (var tag in metaTags)
                    {
                        var tagName     = tag.Attributes["name"];
                        var tagContent  = tag.Attributes["content"];
                        var tagProperty = tag.Attributes["property"];

                        if (tagName != null && tagContent != null)
                        {
                            switch (tagName.Value.ToLower())
                            {
                            case "title":
                                metaInfo.Title = tagContent.Value;
                                break;

                            case "description":
                                metaInfo.Description = tagContent.Value;
                                break;

                            case "twitter:title":
                                metaInfo.Title = string.IsNullOrEmpty(metaInfo.Title) ? tagContent.Value : metaInfo.Title;
                                break;

                            case "twitter:description":
                                metaInfo.Description = string.IsNullOrEmpty(metaInfo.Description) ? tagContent.Value : metaInfo.Description;
                                break;

                            case "keywords":
                                metaInfo.Keywords = tagContent.Value;
                                break;

                            case "twitter:image":
                                metaInfo.ImageUrl = string.IsNullOrEmpty(metaInfo.ImageUrl) ? tagContent.Value : metaInfo.ImageUrl;
                                break;
                            }
                        }
                        else if (tagProperty != null && tagContent != null)
                        {
                            switch (tagProperty.Value.ToLower())
                            {
                            case "og:title":
                                metaInfo.Title = string.IsNullOrEmpty(metaInfo.Title) ? tagContent.Value : metaInfo.Title;
                                break;

                            case "og:description":
                                metaInfo.Description = string.IsNullOrEmpty(metaInfo.Description) ? tagContent.Value : metaInfo.Description;
                                break;

                            case "og:image":
                                metaInfo.ImageUrl = string.IsNullOrEmpty(metaInfo.ImageUrl) ? tagContent.Value : metaInfo.ImageUrl;
                                break;
                            }
                        }
                    }

                    if (string.IsNullOrWhiteSpace(metaInfo.Title))
                    {
                        metaInfo.Title = GetTitle(document.ParsedText);
                    }
                }
            }
            catch (Exception ex)
            {
                // TODO: We should probably log this somewhere...
                metaInfo.HasError = true;

                metaInfo.ExternalPageError = ex is WebException;
            }

            return(metaInfo);
        }
예제 #13
0
 public void SetYVector(Vector3 v)
 {
     MetaInformation.Instance().tileYVector = (Vector2)v;
 }
예제 #14
0
 public Vector3 GetYVector()
 {
     return((Vector3)MetaInformation.Instance().tileYVector);
 }
예제 #15
0
    public override void OnInspectorGUI()
    {
        CraftingWorkbench workbench = target as CraftingWorkbench;
        MetaInformation   info      = MetaInformation.Instance();

        uint[] currentCraftableIDs = workbench.craftableItemIDs;

        bool madeChange = false;


        // Display current items
        for (int i = 0; i < currentCraftableIDs.Length; i++)
        {
            ItemType newItem;
            ItemType currentItem = info.GetItemTypeByID(currentCraftableIDs [i]);

            if (currentItem == null)
            {
                currentCraftableIDs [i] = 0;
                madeChange = true;
            }
            else if (ItemDisplayEditorUtility.DisplayEditableItemSelection(info, currentItem, out newItem))
            {
                if (newItem != null)
                {
                    currentCraftableIDs [i] = newItem.ItemTypeID;
                }
                else
                {
                    currentCraftableIDs [i] = 0;
                }
                madeChange = true;
            }
        }


        // Have an add button
        if (GUILayout.Button("Add Craftable Item"))
        {
            uint[] newCraftableIDs = new uint[currentCraftableIDs.Length + 1];
            Array.Copy(currentCraftableIDs, newCraftableIDs, currentCraftableIDs.Length);

            var kv = info.GetItemTypeMappings().FirstOrDefault();

            if (kv.Key != default(uint))             // TODO probably wrong
            {
                newCraftableIDs [newCraftableIDs.Length - 1] = kv.Key;
            }
            else
            {
                newCraftableIDs [newCraftableIDs.Length - 1] = 0;
            }

            currentCraftableIDs = newCraftableIDs;

            madeChange = true;
        }


        // Remove all null entries and save
        if (madeChange)
        {
            uint[] finalCraftable = currentCraftableIDs.Where((itemID) => itemID != 0).ToArray();
            workbench.craftableItemIDs = finalCraftable;

            Undo.RecordObject(workbench, "CraftingWorkbench Change Craftable Items");
            EditorUtility.SetDirty(workbench);
        }
    }
예제 #16
0
    private GameObject InstantiateACustomer()
    {
        Game g = Game.current;

        if (g != null)
        {
            Dictionary <uint, float> weights = new Dictionary <uint, float> ();

            foreach (var finfo in g.furnitureInShop)
            {
                var fref = finfo.furnitureRef;

                if (fref != null)
                {
                    foreach (var kv in fref.GetAttractedCustomers())
                    {
                        if (!weights.ContainsKey(kv.Key))
                        {
                            weights [kv.Key] = kv.Value;
                        }
                        else
                        {
                            weights [kv.Key] += kv.Value;
                        }
                    }
                }
            }

            if (weights.Count == 0)
            {
                return(null);
            }


            float totalWeight = weights.Aggregate(0, (float total, KeyValuePair <uint, float> wgt) => total + wgt.Value);

            List <uint>  ids           = weights.Select((kv) => kv.Key).ToList();
            List <float> probabilities = weights.Select((kv) => kv.Value / totalWeight).ToList();


            float value = Random.value;

            float accumulated = 0;
            for (int i = 1; i < ids.Count; i++)
            {
                float nextCutoff = accumulated + probabilities [i - 1];
                if (value >= accumulated && value < nextCutoff)
                {
                    var prefab = MetaInformation.Instance().GetCustomerPrefabByID(ids [i - 1]);
                    if (prefab != null)
                    {
                        return(GameObject.Instantiate(prefab));
                    }
                    else
                    {
                        Debug.LogFormat("Customer with ID {0} does not exist!", ids [i - 1]);
                    }
                }

                accumulated = nextCutoff;
            }

            var lastPrefab = MetaInformation.Instance().GetCustomerPrefabByID(ids [ids.Count - 1]);
            if (lastPrefab != null)
            {
                return(GameObject.Instantiate(lastPrefab));
            }
            else
            {
                Debug.LogFormat("Customer with ID {0} does not exist!", ids [ids.Count - 1]);
                return(null);
            }
        }
        else
        {
            return(null);
        }
    }
예제 #17
0
    public void MouseGridCommands()
    {
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hit;
            Ray        ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if (Physics.Raycast(ray, out hit))
            {
                GameObject objectHit = hit.transform.gameObject;

                Select(objectHit);
            }
        }

        if (Input.GetMouseButtonDown(1))
        {
            RaycastHit hit;
            Ray        ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if (Physics.Raycast(ray, out hit))
            {
                int x;
                int z;
                grid.GetXY(hit.transform.position, out x, out z);
                // Only allow this flag setting to occur if the targeted game object is a tile
                if (selected.GetComponent <Unit>())
                {
                    MetaInformation mi = selected.GetComponent <MetaInformation>();
                    Debug.Log(selected);
                    selected.GetComponent <MoveQueue>().Clear();
                    selected.GetComponent <Highlight>().RemoveFlag();
                    if (grid.pathNodes[x, z].isWalkable)
                    {
                        if (pf.FindPath(mi.x, mi.z, x, z) != null)
                        {
                            selected.GetComponent <Highlight>().PlaceFlag(x, grid.gridArray[x, z].height, z, flagPrefab);
                        }
                    }
                }
            }
        }

        foreach (var unitClone in units)
        {
            if (unitClone.GetComponent <Unit>() && unitClone.GetComponent <MoveQueue>())
            {
                MoveQueue mq = unitClone.GetComponent <MoveQueue>();
                if (unitClone.GetComponent <State>().GetState() == Constants.BUSY)
                {
                    return;
                }
                if (mq.q.Count > 0)
                {
                    return;
                }
                if (unitClone.GetComponent <Highlight>() == null)
                {
                    return;
                }
                if (unitClone.GetComponent <Highlight>().rallyPoint == null)
                {
                    return;
                }
                int             x  = unitClone.GetComponent <Highlight>().rallyPoint.x;
                int             z  = unitClone.GetComponent <Highlight>().rallyPoint.z;
                MetaInformation mi = unitClone.GetComponent <MetaInformation>();
                if (x == mi.x && z == mi.z)
                {
                    unitClone.GetComponent <Highlight>().RemoveFlag();
                }
                List <PathNode> path = pf.FindPath(mi.x, mi.z, x, z);

                if (path == null)
                {
                    Debug.Log("No route to the target!");
                }

                foreach (PathNode node in path)
                {
                    unitClone.GetComponent <MoveQueue>().AddMove(new Vector3(node.x, grid.gridArray[node.x, node.z].height, node.z));
                }
            }
        }
    }
    private IEnumerator BeginAI()
    {
        while (true)
        {
            switch (Random.Range(0, 2))
            {
            case 0:
                // Offer a trade.
                var info = MetaInformation.Instance();

                if (info != null)
                {
                    int numMappings = info.GetNumberOfRegisteredItems();

                    if (numMappings != 0)
                    {
                        ItemType offType = info.GetItemTypeMappings().ElementAt(Random.Range(0, numMappings)).Value;
                        ItemType reqType = info.GetItemTypeMappings().ElementAt(Random.Range(0, numMappings)).Value;

                        int numOfferedItem = Random.Range(1, 10);
                        int numRequestItem = Random.Range(1, 10);

                        TradingOffer offer = TradingOffer.MakeOffer(
                            new ItemStack(offType, numOfferedItem),
                            new ItemStack(reqType, numRequestItem));

                        bool didSucceed = false;
                        yield return(TradingDialogUtility.OfferTrade(offer, (result) => {
                            didSucceed = result == TradingResult.SUCCEED;
                        }));


                        if (didSucceed)
                        {
                            NotificationSystem.ShowNotificationIfPossible("Trade succeeded.");
                        }
                        else
                        {
                            NotificationSystem.ShowNotificationIfPossible("Trade failed.");
                        }


                        break;
                    }
                    else
                    {
                        goto case 1;
                    }
                }
                else
                {
                    Debug.Log("No MetaInformation instance found. AI will not make a random trade offer.");
                    goto case 1;
                }


            case 1:
                // Move to a random piece of furniture in the shop.
                Shop shop = myShopMover.GetShop();

                Furniture target = shop.GetFurnitureAtIndex(Random.Range(0, shop.GetFurnitureAmount()));

                yield return(myShopMover.MoveToPosition(target.GetStandingPosition(), (succ) => {}));

                break;
            }
        }
    }
예제 #19
0
        private ConstructorInformation FindSelectedConstructor(RegistrationContextData registrationContextData, MetaInformation metaInfo)
        {
            if (registrationContextData.SelectedConstructor == null)
            {
                return(null);
            }

            var length = metaInfo.Constructors.Length;

            for (var i = 0; i < length; i++)
            {
                var current = metaInfo.Constructors[i];
                if (current.Constructor == registrationContextData.SelectedConstructor)
                {
                    return(current);
                }
            }

            return(null);
        }
예제 #20
0
        public MetaInformation GetMetaData(string url)
        {
            // Get the URL specified
            MetaInformation metaInfo = null;

            try
            {
                var webGet   = new HtmlWeb();
                var document = webGet.Load(url);
                var metaTags = document.DocumentNode.SelectNodes("//meta");
                metaInfo = new MetaInformation(url);
                if (metaTags != null)
                {
                    int matchCount = 0;
                    foreach (var tag in metaTags)
                    {
                        var tagName     = tag.Attributes["name"];
                        var tagContent  = tag.Attributes["content"];
                        var tagProperty = tag.Attributes["property"];
                        if (tagName != null && tagContent != null)
                        {
                            switch (tagName.Value.ToLower())
                            {
                            case "title":
                                metaInfo.Title = tagContent.Value;
                                matchCount++;
                                break;

                            case "description":
                                metaInfo.Description = tagContent.Value;
                                matchCount++;
                                break;

                            case "twitter:title":
                                metaInfo.Title = string.IsNullOrEmpty(metaInfo.Title) ? tagContent.Value : metaInfo.Title;
                                matchCount++;
                                break;

                            case "twitter:description":
                                metaInfo.Description = string.IsNullOrEmpty(metaInfo.Description) ? tagContent.Value : metaInfo.Description;
                                matchCount++;
                                break;

                            case "keywords":
                                metaInfo.Keywords = tagContent.Value;
                                matchCount++;
                                break;

                            case "twitter:image":
                                metaInfo.ImageUrl = string.IsNullOrEmpty(metaInfo.ImageUrl) ? tagContent.Value : metaInfo.ImageUrl;
                                matchCount++;
                                break;
                            }
                        }
                        else if (tagProperty != null && tagContent != null)
                        {
                            switch (tagProperty.Value.ToLower())
                            {
                            case "og:title":
                                metaInfo.Title = string.IsNullOrEmpty(metaInfo.Title) ? tagContent.Value : metaInfo.Title;
                                matchCount++;
                                break;

                            case "og:description":
                                metaInfo.Description = string.IsNullOrEmpty(metaInfo.Description) ? tagContent.Value : metaInfo.Description;
                                matchCount++;
                                break;

                            case "og:image":
                                metaInfo.ImageUrl = string.IsNullOrEmpty(metaInfo.ImageUrl) ? tagContent.Value : metaInfo.ImageUrl;
                                matchCount++;
                                break;
                            }
                        }
                    }
                    metaInfo.HasData = matchCount > 0;
                }
            } catch (Exception ex)
            {
                metaInfo = new MetaInformation(url);
                return(metaInfo);
            }

            return(metaInfo);
        }
예제 #21
0
        public virtual void AddToIndex(object key, object value, OperationContext operationContext)
        {
            CacheEntry entry     = (CacheEntry)value;
            Hashtable  queryInfo = entry.QueryInfo["query-info"] as Hashtable;

            if (queryInfo == null)
            {
                return;
            }


            lock (_indexMap.SyncRoot)
            {
                IDictionaryEnumerator queryInfoEnumerator = queryInfo.GetEnumerator();

                while (queryInfoEnumerator.MoveNext())
                {
                    int    handleId = (int)queryInfoEnumerator.Key;
                    string type     = _typeMap.GetTypeName(handleId);
                    if (_indexMap.Contains(type))
                    {
                        Hashtable indexAttribs    = new Hashtable();
                        Hashtable metaInfoAttribs = new Hashtable();

                        ArrayList values = (ArrayList)queryInfoEnumerator.Value;

                        ArrayList attribList = _typeMap.GetAttribList(handleId);
                        for (int i = 0; i < attribList.Count; i++)
                        {
                            string attribute = attribList[i].ToString();
                            string val       = _typeMap.GetAttributes(handleId)[attribList[i]] as string;
                            if (Common.Util.JavaClrTypeMapping.JavaToClr(val) != null)
                            {
                                val = Common.Util.JavaClrTypeMapping.JavaToClr(val);
                            }
                            Type t1 = Type.GetType(val, true, true);

                            object obj = null;

                            if (values[i] != null)
                            {
                                try
                                {
                                    if (t1 == typeof(System.DateTime))
                                    {
                                        obj = new DateTime(Convert.ToInt64(values[i]));
                                    }
                                    else
                                    {
                                        obj = Convert.ChangeType(values[i], t1);
                                    }
                                }
                                catch (Exception)
                                {
                                    throw new System.FormatException("Cannot convert '" + values[i] + "' to " + t1.ToString());
                                }

                                indexAttribs.Add(attribute, obj);
                            }
                            else
                            {
                                indexAttribs.Add(attribute, null);
                            }


                            metaInfoAttribs.Add(attribute, obj);
                        }

                        MetaInformation metaInformation = new MetaInformation(metaInfoAttribs);
                        metaInformation.CacheKey = key as string;
                        metaInformation.Type     = _typeMap.GetTypeName(handleId);

                        operationContext.Add(OperationContextFieldName.IndexMetaInfo, metaInformation);

                        entry.ObjectType = _typeMap.GetTypeName(handleId);

                        IQueryIndex index    = (IQueryIndex)_indexMap[type];
                        long        prevSize = index.IndexInMemorySize;
                        index.AddToIndex(key, new QueryItemContainer(entry, indexAttribs));

                        this._queryIndexMemorySize += index.IndexInMemorySize - prevSize;
                    }
                }
            }
        }
예제 #22
0
    public void CombineItems()
    {
        CraftingSlot[] slots = GetComponentsInChildren <CraftingSlot> ();

        List <ItemType> items = new List <ItemType> ();

        foreach (var slot in slots)
        {
            var item = slot.GetItem();
            if (item != null)
            {
                items.Add(item);
                slot.Clear();
            }
        }

        if (items.Any((item) => !Game.current.inventory.HasItem(item)))
        {
            NotificationSystem.ShowNotificationIfPossible("You do not have enough of at least one of the items.");
        }
        else
        {
            ItemType bestCandidate = null;
            int      bestMatch     = 0;


            // try to find a matching crafting recipe by looping through all known items and their recipes
            foreach (var kv in MetaInformation.Instance().GetItemTypeMappings())
            {
                if (kv.Value.Recipe.CanBeCraftedGiven(items))
                {
                    int    matchStrength = 0;
                    bool[] matched       = new bool[items.Count];

                    foreach (var stack in kv.Value.Recipe.GetRequiredItems())
                    {
                        int numMatches = 0;
                        for (int i = 0; i < items.Count && numMatches < stack.Count; i++)
                        {
                            if (!matched [i] && stack.ItemTypeID == items [i].ItemTypeID)
                            {
                                matched [i] = true;
                                numMatches++;
                            }
                        }
                    }

                    matchStrength = matched.Select((b) => b ? 1 : 0).Sum();

                    if (matchStrength > bestMatch)
                    {
                        bestCandidate = kv.Value;
                        bestMatch     = matchStrength;
                    }
                }
            }

            if (bestCandidate == null)
            {
                NotificationSystem.ShowNotificationIfPossible("Didn't match any recipes.");

                PlaySound(craftingFailedSound);
            }
            else
            {
                bestCandidate.Recipe.UseIngredientsFrom(Game.current.inventory);
                Game.current.inventory.AddItem(bestCandidate);

                NotificationSystem.ShowNotificationIfPossible(string.Format("You made {0}", bestCandidate.Name));

                PlaySound(craftingSuccessfulSound);
            }

            RemakeInventory(Game.current.inventory);
        }
    }
예제 #23
0
 public void Start()
 {
     this.mi = gameObject.GetComponent <MetaInformation>();
 }
예제 #24
0
 public void SetCurrent()
 {
     instance = this;
 }
예제 #25
0
        public static MetaInformation ReadExifData(MemoryStream sourceStream)
        {
            sourceStream.Seek(0, SeekOrigin.Begin);
            using (var reader = new ExifReader(sourceStream)) {
                var meta = new MetaInformation();
                var exif = new ExifData();

                exif.Make              = SetExifData <string>(reader, ExifTags.Make);
                exif.Model             = SetExifData <string>(reader, ExifTags.Model);
                exif.CaptureDate       = SetExifData <DateTime>(reader, ExifTags.DateTimeOriginal);
                exif.Description       = SetExifData <string>(reader, ExifTags.ImageDescription);
                exif.Artist            = SetExifData <string>(reader, ExifTags.Artist);
                exif.Copyright         = SetExifData <string>(reader, ExifTags.Copyright);
                exif.Software          = SetExifData <string>(reader, ExifTags.Software);
                exif.FocalLength       = SetExifData <double>(reader, ExifTags.FocalLength);
                exif.FNumber           = SetExifData <double>(reader, ExifTags.FNumber);
                exif.ApertureValue     = SetExifData <double>(reader, ExifTags.ApertureValue);
                exif.MaxApertureValue  = SetExifData <double>(reader, ExifTags.MaxApertureValue);
                exif.ExposureTime      = SetExifData <double>(reader, ExifTags.ExposureTime);
                exif.ExposureBiasValue = SetExifData <double>(reader, ExifTags.ExposureBiasValue);
                exif.ExposureProgram   = SetExifData <ushort>(reader, ExifTags.ExposureProgram);
                exif.ExposureMode      = SetExifData <ushort>(reader, ExifTags.ExposureMode);
                exif.ISOSpeedRatings   = SetExifData <ushort>(reader, ExifTags.ISOSpeedRatings);
                exif.MeteringMode      = SetExifData <ushort>(reader, ExifTags.MeteringMode);

                double x = SetExifData <double>(reader, ExifTags.XResolution);
                double y = SetExifData <double>(reader, ExifTags.YResolution);
                exif.XResolution    = x;
                exif.YResolution    = y;
                exif.ResolutionUnit = SetExifData <ushort>(reader, ExifTags.ResolutionUnit);

                var image = new Bitmap(sourceStream);
                exif.Width       = image.Width;
                exif.Height      = image.Height;
                exif.AspectRatio = (double)image.Width / (double)image.Height;
                exif.Orientation = image.Width == image.Height ? "square" : (image.Width > image.Height ? "landscape" : "portrait");

                double[] lat    = SetExifData <double[]>(reader, ExifTags.GPSLatitude);
                double[] lng    = SetExifData <double[]>(reader, ExifTags.GPSLongitude);
                string   latRef = SetExifData <string>(reader, ExifTags.GPSLatitudeRef);
                string   lngRef = SetExifData <string>(reader, ExifTags.GPSLongitudeRef);

                if (lat != null)
                {
                    double latitude  = 0;
                    double longitude = 0;
                    latitude = lat[0] +
                               lat[1] / 60.0 +
                               lat[2] / 3600.0;
                    if (latRef == "S")
                    {
                        latitude = -latitude;
                    }
                    longitude = lng[0] +
                                lng[1] / 60.0 +
                                lng[2] / 3600.0;
                    if (lngRef == "W")
                    {
                        longitude = -longitude;
                    }

                    exif.Latitude  = latitude;
                    exif.Longitude = longitude;
                }

                meta.Exif = exif;
                return(meta);
            }
        }
예제 #26
0
        private MemberInformation[] ConstructInjectionMembers(RegistrationContextData registrationContextData, MetaInformation metaInfo)
        {
            if (registrationContextData.InjectionMemberNames.Count == 0)
            {
                return(metaInfo.InjectionMembers);
            }

            var length  = metaInfo.InjectionMembers.Length;
            var members = new MemberInformation[length];

            for (var i = 0; i < length; i++)
            {
                var member = metaInfo.InjectionMembers[i];
                if (registrationContextData.InjectionMemberNames.TryGetValue(member.MemberInfo.Name,
                                                                             out var dependencyName))
                {
                    var copy = member.Clone();
                    copy.TypeInformation.ForcedDependency = true;
                    copy.TypeInformation.DependencyName   = dependencyName;
                    members[i] = copy;
                }
                else
                {
                    members[i] = member;
                }
            }

            return(members);
        }
예제 #27
0
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();


        Furniture furniture = target as Furniture;

        EditorGUILayout.LabelField("Attracted Customers");


        var attractedCustomerList = furniture.GetAttractedCustomers().ToList();

        foreach (var kv in attractedCustomerList)
        {
            var customerPrefab = MetaInformation.Instance().GetCustomerPrefabByID(kv.Key);
            var name           = customerPrefab.name;
            var weight         = kv.Value;


            EditorGUILayout.BeginHorizontal();

            EditorGUI.BeginChangeCheck();
            var newID = CustomerDisplayEditorUtility.CustomerDropdown(kv.Key);
            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(furniture, "Furniture Change Customer");

                furniture.RemoveAttractedCustomer(kv.Key);
                furniture.AddAttractedCustomer(newID, weight);
            }

            EditorGUI.BeginChangeCheck();
            var newWeight = EditorGUILayout.FloatField(weight);
            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(furniture, "Furniture Change Customer Weight");
                EditorUtility.SetDirty(furniture);

                furniture.SetAttractedCustomerWeight(newID, newWeight);
            }

            if (GUILayout.Button("-", GUILayout.ExpandWidth(false)))
            {
                Undo.RecordObject(furniture, "Furniture Remove Customer");
                EditorUtility.SetDirty(furniture);

                furniture.RemoveAttractedCustomer(newID);
            }

            EditorGUILayout.EndHorizontal();
        }


        if (GUILayout.Button("+", GUILayout.ExpandWidth(false)))
        {
            Undo.RecordObject(furniture, "Furniture Add Customer");
            EditorUtility.SetDirty(furniture);


            uint anyID = MetaInformation.Instance().GetCustomerIDMappings().FirstOrDefault().Key;

            if (anyID == default(uint))
            {
                EditorWindow.focusedWindow.ShowNotification(new GUIContent("No registered customers!"));
            }
            else
            {
                furniture.AddAttractedCustomer(anyID, 1);
            }
        }
    }
예제 #28
0
    public override void OnInspectorGUI()
    {
        MetaInformation info = target as MetaInformation;

        info.SetCurrent();


        if (GUILayout.Button("Save to default file"))
        {
            info.Save();
        }

        if (GUILayout.Button("Load from default file"))
        {
            info.Load();
            EditorUtility.SetDirty(target);
        }


        EditorGUI.BeginChangeCheck();
        var newTileX = EditorGUILayout.Vector2Field("Tile X Vector", info.tileXVector);

        if (EditorGUI.EndChangeCheck())
        {
            Undo.RecordObject(info, "MetaInformation Change Tile X Vector");
            EditorUtility.SetDirty(target);
            info.tileXVector = newTileX;
        }


        EditorGUI.BeginChangeCheck();
        var newTileY = EditorGUILayout.Vector2Field("Tile Y Vector", info.tileYVector);

        if (EditorGUI.EndChangeCheck())
        {
            Undo.RecordObject(info, "MetaInformation Change Tile Y Vector");
            EditorUtility.SetDirty(target);
            info.tileYVector = newTileY;
        }

        EditorGUI.BeginChangeCheck();
        var newNumGridSquaresPerTile = EditorGUILayout.IntField("# Grid Squares / Tile", info.numGridSquaresPerTile);

        if (EditorGUI.EndChangeCheck())
        {
            Undo.RecordObject(info, "MetaInformation Change Num Grid Squares Per Tile");
            EditorUtility.SetDirty(target);
            info.numGridSquaresPerTile = newNumGridSquaresPerTile;
        }


        GameObjectFieldFor(info.playerPrefab, "Player Prefab", (newPlayer) => {
            Undo.RecordObject(info, "MetaInformation Change Player Prefab");
            EditorUtility.SetDirty(target);
            info.playerPrefab = newPlayer;
        });

        GameObjectFieldFor(info.roomPrefab, "Room Prefab", (newRoom) => {
            Undo.RecordObject(info, "MetaInformation Change Room Prefab");
            EditorUtility.SetDirty(target);
            info.roomPrefab = newRoom;
        });

        GameObjectFieldFor(info.eventSystemPrefab, "Event System Prefab", (newES) => {
            Undo.RecordObject(info, "MetaInformation Change Event System Prefab");
            EditorUtility.SetDirty(target);
            info.eventSystemPrefab = newES;
        });

        GameObjectFieldFor(info.shopEditorCanvasPrefab, "Shop Editor Canvas Prefab", (newES) => {
            Undo.RecordObject(info, "MetaInformation Change Shop Editor Canvas Prefab");
            EditorUtility.SetDirty(target);
            info.shopEditorCanvasPrefab = newES;
        });

        GameObjectFieldFor(info.shopPhaseDayCanvasPrefab, "Shop Phase Day Canvas Prefab", (newES) => {
            Undo.RecordObject(info, "MetaInformation Change Shop Phase Day Canvas Prefab");
            EditorUtility.SetDirty(target);
            info.shopPhaseDayCanvasPrefab = newES;
        });

        GameObjectFieldFor(info.shopPhaseEditCanvasPrefab, "Shop Phase Edit Canvas Prefab", (newES) => {
            Undo.RecordObject(info, "MetaInformation Change Shop Phase Edit Canvas Prefab");
            EditorUtility.SetDirty(target);
            info.shopPhaseEditCanvasPrefab = newES;
        });



        GUILayout.Space(5);
        GUILayout.Label("Known Furniture");

        var oldFurnitureMappings = info.GetFurnitureMappings().ToList();

        foreach (var kv in oldFurnitureMappings)
        {
            EditorGUI.BeginChangeCheck();
            var newValue = EditorGUILayout.ObjectField(kv.Key.ToString(), kv.Value, typeof(GameObject), false) as GameObject;
            if (EditorGUI.EndChangeCheck() && newValue.GetComponent <Furniture> () != null)
            {
                Undo.RecordObject(info, "MetaInformation Change Furniture ID Mapping");
                EditorUtility.SetDirty(info);
                info.AddMappingForFurniture(kv.Key, newValue);
            }
        }

        EditorGUI.BeginChangeCheck();
        var newFurniturePrefab = EditorGUILayout.ObjectField("Add New Furniture", null, typeof(GameObject), false) as GameObject;

        if (EditorGUI.EndChangeCheck() && newFurniturePrefab.GetComponent <Furniture> () != null)
        {
            Undo.RecordObject(info, "MetaInformation Add Furniture ID Mapping");
            EditorUtility.SetDirty(info);
            info.AddMappingForFurniture(info.GetUnusedCustomerID(), newFurniturePrefab);
        }



        GUILayout.Space(5);
        GUILayout.Label("Known Customers");

        var oldCustomerMappings = info.GetCustomerIDMappings().ToList();

        foreach (var kv in oldCustomerMappings)
        {
            EditorGUI.BeginChangeCheck();
            var newValue = EditorGUILayout.ObjectField(kv.Key.ToString(), kv.Value, typeof(GameObject), false);
            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(info, "MetaInformation Change Customer ID Mapping");
                EditorUtility.SetDirty(info);
                info.AddMappingForCustomerPrefab(kv.Key, newValue as GameObject);
            }
        }

        EditorGUI.BeginChangeCheck();
        var newCustomerPrefab = EditorGUILayout.ObjectField("Add New Customer", null, typeof(GameObject), false);

        if (EditorGUI.EndChangeCheck())
        {
            Undo.RecordObject(info, "MetaInformation Add Customer ID Mapping");
            EditorUtility.SetDirty(info);
            info.AddMappingForCustomerPrefab(info.GetUnusedCustomerID(), newCustomerPrefab as GameObject);
        }



        GUILayout.Space(5);
        GUILayout.Label("Known Item Types");


        // Necessary because DisplayItem may modify item mappings
        var allItemMappings = info.GetItemTypeMappings().ToList();

        foreach (var kv in allItemMappings)
        {
            DisplayItem(info, kv.Key, kv.Value);
            GUILayout.Space(5);
        }

        if (GUILayout.Button("Load Items from Assets/Items/"))
        {
            string itemsPath = System.IO.Path.Combine(Application.dataPath, "Items/");

            string[] allFiles = System.IO.Directory.GetFiles(itemsPath);

            foreach (string fileName in allFiles)
            {
                string relativeFileName = fileName.Substring(fileName.IndexOf("Assets/Items/"));

                var itemType = AssetDatabase.LoadAssetAtPath <ItemType> (relativeFileName);

                if (itemType != null)
                {
                    uint itemID = itemType.ItemTypeID;

                    if (info.GetItemTypeByID(itemID) != null)
                    {
                        Debug.LogFormat("{0} and {1} have the same ID: {2}", info.GetItemTypeByID(itemID).Name, itemType.Name, itemID);
                    }
                    else
                    {
                        info.AddMappingForItemType(itemID, itemType);
                    }
                }
            }
        }


        GUILayout.Space(5);
        GUILayout.Label("Other ID Mappings");

        foreach (var kv in info.GetGeneralIDMappings())
        {
            GUILayout.Label(string.Format("Prefab Name: {0}\t| ID: {1}", kv.Value.name, kv.Key));
        }
    }