Ejemplo n.º 1
0
  public void InitScrollViewData(JSONArray mFriendList) {
    friendList = mFriendList;
    friendListRows = new JSONArray();
    JSONObject row = new JSONObject();
    for (int i = 0; i < friendList.Length; i++) {
      if (Utils.IsOdd(i)) {
        row.Add("right", friendList[i].Obj);
        friendListRows.Add(row);
      } else {
        row = new JSONObject();
        row.Add("left", friendList[i].Obj);
        if (i == friendList.Length - 1) {
          friendListRows.Add(row);
        }
      }
    }
    isLoading = false;
    wrapContent.ResetChildPositions();
    scrollview.currentMomentum = Vector3.zero;
    scrollview.ResetPosition();
    Transform tempGameObject;
    
    wrapContent.minIndex = -(friendListRows.Length - 1);
    wrapContent.onInitializeItem = UpdateRowDataOnScroll;
    bool canDrag = true;
    if (friendListRows.Length <= STOP_DRAG_NUMB_ROW) {
      canDrag = false;
      backgroundDragScrollView.enabled = false;
    } else {
      backgroundDragScrollView.enabled = true;
    }
    for (int i = 0; i < wrapContent.transform.childCount; i++) {
      tempGameObject = wrapContent.transform.GetChild(i);
      if (!tempGameObject.gameObject.activeSelf) {
				Utils.SetActive(tempGameObject.gameObject, true);
      }
      InviteRowScript tempRowScript = tempGameObject.GetComponent<InviteRowScript>();
      tempRowScript.Init(scrollview);
      
      if (canDrag) {
        tempRowScript.dragScrollView.enabled = true;
      } else {
        tempRowScript.dragScrollView.enabled = false;
      }
      if (i < friendListRows.Length) {
				Utils.SetActive(tempGameObject.gameObject, true);
        tempRowScript.UpdateRowData(friendListRows[i].Obj);
      } else {
				Utils.SetActive(tempGameObject.gameObject, false);
      }
    }
  }
Ejemplo n.º 2
0
    public void LoadFriendRank(Action callback)
    {
        JSONArray friendList = new JSONArray ();

        foreach(JSONValue item in UserSingleton.Instance.FriendList){
            JSONObject friend = item.Obj;
            friendList.Add (friend ["id"]);
        }

        JSONObject requestBody = new JSONObject ();
        requestBody.Add ("UserID", UserSingleton.Instance.UserID);
        requestBody.Add ("FriendList", friendList);

        HTTPClient.Instance.POST (Singleton.Instance.HOST + "/Rank/Friend", requestBody.ToString(), delegate(WWW www) {

            Debug.Log("LoadFriendRank" + www.text);

            string response = www.text;

            JSONObject obj = JSONObject.Parse(response);

            JSONArray arr = obj["Data"].Array;

            foreach(JSONValue item in arr){
                int rank = (int)item.Obj["Rank"].Number;
                if(FriendRank.ContainsKey(rank)){
                    FriendRank.Remove(rank);
                }
                FriendRank.Add(rank,item.Obj);
            }

            callback();

        });
    }
Ejemplo n.º 3
0
  public override void Init(object[] data) {
    base.Init(data);
    List<Buddy> buddyList = SmartfoxClient.Instance.GetBuddyList();
    if (buddyList.Count > 0) {
      Utils.SetActive(noFriendLabel, false);
      EventDelegate.Set(btnSendInvite.onClick, EventSendInvite);
			JSONObject friend;
			friendList = new JSONArray();
			for (int i = 0; i < buddyList.Count; i++) {
				friend = new JSONObject();
				if (buddyList[i].IsOnline) {
					friend.Add("displayName", buddyList[i].GetVariable("displayName").GetStringValue());
					friend.Add("cash", (long)buddyList[i].GetVariable("cash").GetDoubleValue());
					friend.Add("username", buddyList[i].Name);
					friendList.Add(friend);
				}
			}
			InitScrollViewData(friendList);
    } else {
			// TO DO - dont have friend message
      Utils.SetActive(scrollview.gameObject, false);
      Utils.SetActive(btnSendInvite.gameObject, false);
      Utils.SetActive(noFriendLabel, true);
      Debug.Log("----------- DONE HAVE ANY FRIEND ----------------");
    }
  }
Ejemplo n.º 4
0
  public override void Init(object[] data) {
    base.Init(data);
    EventDelegate.Set(tabInvite.onClick, EventTabInvite);
    EventDelegate.Set(tabFriends.onClick, EventTabFriends);
		
		// Get list friends from smartfox buddy list
    List<Buddy> buddyList = SmartfoxClient.Instance.GetBuddyList();
    if (buddyList.Count > 0) {
			JSONObject friend;
			friendList = new JSONArray();
			for (int i = 0; i < buddyList.Count; i++) {
				friend = new JSONObject();
				if (buddyList[i].IsOnline) {
					friend.Add("displayName", buddyList[i].GetVariable("displayName").GetStringValue());
					friend.Add("cash", (long)buddyList[i].GetVariable("cash").GetDoubleValue());
					friend.Add("avatar", buddyList[i].GetVariable("avatar").GetStringValue());
					friend.Add("facebookId", buddyList[i].GetVariable("facebookId").GetStringValue());
				} else {
					friend.Add("displayName", buddyList[i].GetVariable("$displayName").GetStringValue());
					friend.Add("cash", (long)buddyList[i].GetVariable("$cash").GetDoubleValue());
					friend.Add("avatar", buddyList[i].ContainsVariable("$avatar") ? buddyList[i].GetVariable("$avatar").GetStringValue() : string.Empty);
					friend.Add("facebookId", buddyList[i].ContainsVariable("$facebookId") ? buddyList[i].GetVariable("$facebookId").GetStringValue() : string.Empty);
				}
				friend.Add("username", buddyList[i].Name);
				friendList.Add(friend);
			}
			InitScrollViewData(friendList);
    } else {
      Utils.SetActive(scrollview.gameObject, false);
      Debug.Log("----------- DONE HAVE ANY FRIEND ----------------");
    }
  }
    public static JSONArray ExportData(this List<int> list)
    {
        var json_array = new JSONArray();

        foreach (var num in list)
            json_array.Add(num);

        return json_array;
    }
    public static JSONValue ExportData(this AnimationCurve curve)
    {
        var key_frame_data = new JSONArray();

        foreach (var key_frame in curve.keys)
            key_frame_data.Add(key_frame.ExportData());

        return key_frame_data;
    }
Ejemplo n.º 7
0
  void EventSendInvite() {
		if (listInviteUsers.Count > 0) {
			JSONArray arr = new JSONArray();
			for (int i = 0; i < listInviteUsers.Count; i++) {
				arr.Add(listInviteUsers[i]);
			}
	    Debug.Log("EventSendInvite " + arr.ToString());
			
	    UserExtensionRequest.Instance.InviteToGame(arr, ScreenManager.Instance.CurrentSlotScreen.GetCrtGameType(), ScreenManager.Instance.CurrentSlotScreen.GetRoomId());
			Close();
		}
  }
		// ================================================================================
		//  loading and saving
		// --------------------------------------------------------------------------------

		public JSONObject GetJSON()
		{
			JSONObject data = new JSONObject();

			JSONArray wasUsedArray = new JSONArray();
			foreach (var item in wasUsed)
			{
				wasUsedArray.Add(item);
			}
			data.Add("wasUsed", wasUsedArray);

			return data;
		}
 public void SavePlayerData()
 {
     JSONArray array = new JSONArray ();
     foreach (Player p in players) {
         JSONObject player = new JSONObject ();
         player.Add ("id", p.Id);
         player.Add ("name", p.Name);
         JSONArray levels = new JSONArray ();
         foreach (LevelData l in p.Levels.Values) {
             JSONObject jLevel = new JSONObject ();
             jLevel.Add ("id", l.Id);
             jLevel.Add ("stepCount", l.StepCount);
             levels.Add (jLevel);
         }
         player.Add ("levels", levels);
         array.Add (player);
     }
     PlayerPrefs.SetString ("players", array.ToString ());
     PlayerPrefs.Save ();
 }
Ejemplo n.º 10
0
        protected void JSCall(string method, params object[] argv)
        {
            //把参数转换成json
               // JSONObject jObj = new JSONObject();
            JSONArray param = new JSONArray();
            foreach (object o in argv)
            {
                param.Add(o);
            }
            //jObj.Add("Cmd", method);
               // jObj.Add("Param", argv);
            string script = string.Format("{0}({1})", method, JSONConvert.SerializeArray(param));

            //使用后台工作线程
            BackgroundWorker JSCallWorker = new BackgroundWorker();
            JSCallWorker.DoWork += new DoWorkEventHandler(JSCallWorker_DoWork);
            JSCallWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(JSCallWorker_RunWorkerCompleted);
            m_InvokeQueue.Enqueue(script);
            JSCallWorker.RunWorkerAsync();
        }
Ejemplo n.º 11
0
 private void getJSONstr(DataSet ds)
 {
     string s = base.Request.Params["start"];
     string str2 = base.Request.Params["limit"];
     JSONObject jsonObject = new JSONObject();
     JSONArray array = new JSONArray();
     for (int i = int.Parse(s); (i < ds.Tables[0].Rows.Count) && (i < (int.Parse(s) + int.Parse(str2))); i++)
     {
         JSONObject item = new JSONObject();
         for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
         {
             item.Add(ds.Tables[0].Columns[j].ColumnName, "'" + ds.Tables[0].Rows[i][j] + "'");
         }
         array.Add(item);
     }
     jsonObject.Add("totalProperty", ds.Tables[0].Rows.Count);
     jsonObject.Add("root", array);
     string str3 = JSONConvert.SerializeObject(jsonObject);
     base.Response.Write(str3);
 }
Ejemplo n.º 12
0
    public JSONValue ExportData()
    {
        var json_data = new JSONObject();

        var anchors_data = new JSONArray();
        JSONObject anchor_point_data;

        foreach (var anchor_point in m_anchor_points)
        {
            anchor_point_data = new JSONObject();
            anchor_point_data["m_anchor_point"] = anchor_point.m_anchor_point.ExportData();
            anchor_point_data["m_handle_point"] = anchor_point.m_handle_point.ExportData();

            anchors_data.Add(anchor_point_data);
        }

        json_data["ANCHORS_DATA"] = anchors_data;

        return new JSONValue(json_data);
    }
Ejemplo n.º 13
0
            public void AddFactoryObjects <T>(string key, List <T> list)
                where T : IFactoryObject
            {
                if (list == null || c_ == null)
                {
                    return;
                }

                if (list.Count > 0)
                {
                    var array = new JSONArray();

                    foreach (var element in list)
                    {
                        var n = element.ToJSON();
                        if (n?.Impl != null)
                        {
                            array.Add(n.Impl);
                        }
                    }

                    c_?.Add(key, array);
                }
            }
Ejemplo n.º 14
0
        public static string responseJson(Socket socket, string code, string requestId, params string[] data)
        {
            JSONClass response = new JSONClass();

            response.Add(ResponseKey.Code, code);
            JSONArray dataArray = new JSONArray();

            foreach (string item in data)
            {
                if (item != null)
                {
                    dataArray.Add(null, item);
                }
            }
            response.Add(ResponseKey.Data, dataArray);
            //response.Add(ResponseKey.Data, data);
            //response.Add(ResponseKey.Format, dataFormat);
            response.Add(ResponseKey.RequestId, requestId);
            string responseJson = response.ToString();

            socket.Send(HeaderCode.BYTES_JSON);
            sendTextFrame(socket, responseJson);
            return(responseJson);
        }
Ejemplo n.º 15
0
        public static void Write(string path, ref List <SongRequest> songs)
        {
            if (!Directory.Exists(Path.GetDirectoryName(path)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(path));
            }

            JSONArray arr = new JSONArray();

            foreach (SongRequest song in songs)
            {
                try
                {
                    var songData = song.ToJson();
                    arr.Add(songData);
                }
                catch (Exception)
                {
                    // silent ignore
                }
            }

            File.WriteAllText(path, arr.ToString());
        }
Ejemplo n.º 16
0
        void SerializeAndSave(TestConfigurationMeta meta)
        {
            JSONClass json = new JSONClass();

            json.Add("userId", new JSONData(meta.userId));
            json.Add("userName", new JSONData(meta.userName));
            json.Add("translation", new JSONData(translationToggle.isOn));

            JSONArray array = new JSONArray();

            foreach (TestChannelMeta metaChannel in meta.Channels)
            {
                JSONClass channelNode = new JSONClass();
                channelNode.Add("channelId", new JSONData(metaChannel.channelId));
                channelNode.Add("channelName", new JSONData(metaChannel.channelName));

                array.Add(channelNode);
            }

            json.Add("channels", array);

            PlayerPrefs.SetString("fizz-meta-143", json.ToString());
            PlayerPrefs.Save();
        }
Ejemplo n.º 17
0
    private void SavePersonMarks()
    {
        JSONObject personDATA      = new JSONObject();
        JSONArray  personMarksJSON = new JSONArray();

        if (personMarks.Count == 0)
        {
            File.Delete(fileForMarkSave);
        }
        else
        {
            for (int i = 0; i < personMarks.Count; i++)
            {
                personMarksJSON.Add(personMarks[i]);
            }

            personDATA.Add("personMarks", personMarksJSON);

            if (File.Exists(fileForMarkSave))
            {
                File.WriteAllText(fileForMarkSave, personDATA.ToString());
            }
        }
    }
Ejemplo n.º 18
0
    private void SavePersonBusket()
    {
        JSONObject personDATA       = new JSONObject();
        JSONArray  personBusketJSON = new JSONArray();

        if (personBusket.Count == 0)
        {
            File.Delete(fileForPersonBusket);
        }
        else
        {
            for (int i = 0; i < personBusket.Count; i++)
            {
                personBusketJSON.Add(personBusket[i]);
            }

            personDATA.Add("personBusket", personBusketJSON);

            if (File.Exists(fileForPersonBusket))
            {
                File.WriteAllText(fileForPersonBusket, personDATA.ToString());
            }
        }
    }
Ejemplo n.º 19
0
        public override string ToString()
        {
            var sj = new SimpleJSON.JSONClass();

            var jsonObj = new JSONClass();

            KeyValuePair <int, Actor>[] ad;
            lock (actorDict)
            {
                ad = actorDict.ToArray();
            }

            jsonObj.Add("ActorCount", new JSONData(ad.Length));
            var jsonArray = new JSONArray();

            foreach (var actor in ad)
            {
                var actorJson = new JSONClass();
                actorJson.Add("type", new JSONData(actor.Value.GetType().ToString()));
                var actorComponents = new JSONClass();

                /*
                 *  foreach (var compoent in actor.Value.GetComponents().Result)
                 *  {
                 *      actorComponents.Add("Component", new JSONData(compoent.GetType().ToString()));
                 *  }
                 */
                actorJson.Add("Components", actorComponents);
                actorJson.Add("Attribute", actor.Value.GetAttr());
                jsonArray.Add("Actor", actorJson);
            }
            jsonObj.Add("Actors", jsonArray);

            sj.Add("AtorStatus", jsonObj);
            return(sj.ToString());
        }
        public void Write(string path, IEnumerable <object> songs)
        {
            try {
                if (!Directory.Exists(Path.GetDirectoryName(path)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(path));
                }

                var arr = new JSONArray();
                foreach (var song in songs.Where(x => x != null).Select(x => x as SongRequest))
                {
                    try {
                        arr.Add(song.ToJson());
                    }
                    catch (Exception ex) {
                        Logger.Error($"{song}\r\n{ex}");
                    }
                }
                File.WriteAllText(path, arr.ToString());
            }
            catch (Exception ex) {
                Logger.Error(ex);
            }
        }
Ejemplo n.º 21
0
        public JSONObject ToJson()
        {
            JSONObject obj = new JSONObject();

            obj.Add(nameof(Id), new JSONString(Id));
            obj.Add(nameof(IsSystemMessage), new JSONBool(IsSystemMessage));
            obj.Add(nameof(IsActionMessage), new JSONBool(IsActionMessage));
            obj.Add(nameof(IsActionMessage), new JSONBool(IsActionMessage));
            obj.Add(nameof(IsHighlighted), new JSONBool(IsHighlighted));
            obj.Add(nameof(IsPing), new JSONBool(IsPing));
            obj.Add(nameof(Message), new JSONString(Message));
            obj.Add(nameof(Sender), Sender.ToJson());
            obj.Add(nameof(Channel), Channel.ToJson());
            JSONArray emotes = new JSONArray();

            foreach (var emote in Emotes)
            {
                emotes.Add(emote.ToJson());
            }
            obj.Add(nameof(Emotes), emotes);
            obj.Add(nameof(Type), new JSONString(Type));
            obj.Add(nameof(Bits), new JSONNumber(Bits));
            return(obj);
        }
Ejemplo n.º 22
0
    private void AppRequestsCallBack(IGraphResult result)
    {
        MyDebug.Log("AppRequestsCallBack: " + result.RawResult);

        // {"data":[{"application":{"category":"Games","link":"https:\/\/www.facebook.com\/games\/supertangramsaga\/?fbs=-1","name":"Tangram Saga HD - Puzzle Game","namespace":"supertangramsaga","id":"1795472404071895"},"created_time":"2017-04-28T10:03:23+0000","data":"{\"type\":\"sendlife\"}","from":{"name":"Dorothy Alaefbeababed Valtchanovsen","id":"112962892567881"},"message":"Here's a life! Have a great day!","to":{"name":"Mary Alafgjafiicac Huiberg","id":"106562559910467"},"id":"1895223444091310_106562559910467"}],"paging":{"cursors":{"before":"MTg5NTIyMzQ0NDA5MTMxMDoxMDAwMTY3MDE2OTkzMTMZD","after":"MTg5NTIyMzQ0NDA5MTMxMDoxMDAwMTY3MDE2OTkzMTMZD"}}}

        if (result != null && (result.Error == null || result.Error == ""))
        {
            JSONObject jsonObject = JSONObject.Parse(result.RawResult);
            JSONValue  dataArray  = jsonObject.GetArray("data");

            JSONArray arr = new JSONArray();

            foreach (JSONValue v in dataArray.Array)
            {
                if (!v.Obj.ContainsKey("data"))
                {
                    continue;
                }

                string     d    = v.Obj.GetString("data").Replace("\\", "");
                JSONObject data = JSONObject.Parse(d);

                if (!data.ContainsKey("type"))
                {
                    continue;
                }

                v.Obj.Add("data", data);

                arr.Add(v);
            }

            GameManager.SafeQueueMessage(new MessagesReceivedMessage(arr));
        }
    }
Ejemplo n.º 23
0
 void sendBetttingToServer(Bet b)
 {
     try {
         JSONClass number = new JSONClass();
         int       time   = (36 / b.number.Count) - 1;
         number.Add("TIMES", "" + time);
         number.Add("TAG", "ADD_COIN");
         number.Add("COIN", "" + b.coin);
         number.Add("BET_ID", "" + b.betID);
         number.Add("x", "" + b.coinPosition.x);
         number.Add("y", "" + b.coinPosition.y);
         number.Add("z", "" + b.coinPosition.z);
         number.Add("IMAGE", "" + b.coinImageName);
         JSONArray num = new JSONArray();
         foreach (int n in b.number)
         {
             num.Add("" + n);
         }
         number.Add("NUMBER", num.ToString());
         Roulette_AppWarpClass.add_coin(number);
     } catch (System.Exception ex) {
         // Debug.Log (ex.Message);
     }
 }
Ejemplo n.º 24
0
    public void doApprovalProcess(string objectId, string processId, string action, WindowHandler handler)
    {
        string comment = (action == "Approve") ? "Approved via VRpportunity!" : "Rejected via VRpportunity!";
        JSONObject request = new JSONObject();
        request.Add ("actionType", action);
        request.Add ("contextId", processId);
        request.Add ("comments", comment);

        JSONArray requestArray = new JSONArray();
        requestArray.Add (new JSONValue(request));

        JSONObject jsonBody = new JSONObject();
        jsonBody.Add ("requests", new JSONValue(requestArray));

        string jsonProcess = jsonBody.ToString();

        JSONObject chatter = new JSONObject();
        chatter.Add ("feedElementType", "FeedItem");
        chatter.Add ("subjectId", objectId);

        JSONObject chatterBody = new JSONObject();
        chatterBody.Add ("type", "Text");
        chatterBody.Add ("text", "Approval Process " + comment);

        JSONArray segments = new JSONArray();
        segments.Add (new JSONValue(chatterBody));

        JSONObject chatterSegments = new JSONObject();
        chatterSegments.Add ("messageSegments", new JSONValue(segments));

        chatter.Add ("body", new JSONValue(chatterSegments));

        string jsonChatter = chatter.ToString ();

        StartCoroutine(handleApprovalProcess(jsonProcess, jsonChatter, handler));
    }
        private void HandleWaypointRequest(IAsyncResult ar)
        {
            if (!_listener.IsListening)
            {
                return;
            }

            HttpListenerContext context = _listener.EndGetContext(ar);

            _listener.BeginGetContext(new AsyncCallback(HandleWaypointRequest), _listener);

            try
            {
                var request  = context.Request;
                var response = context.Response;

                if (request.HttpMethod == "OPTIONS")
                {
                    response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");
                    response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                    response.AddHeader("Access-Control-Max-Age", "1728000");
                }
                response.AppendHeader("Access-Control-Allow-Origin", "*");

                if (GameManager.Instance.World == null)
                {
                    response.StatusCode = 503;

                    return;
                }

                JSONArray waypointArray = new JSONArray();

                foreach (var wp in WaypointContainer.Instance.Waypoints)
                {
                    var pos = new JSONObject();

                    pos.Add("x", new JSONNumber(wp.WaypointPosition.x));
                    pos.Add("y", new JSONNumber(wp.WaypointPosition.y));
                    pos.Add("z", new JSONNumber(wp.WaypointPosition.z));

                    var point = new JSONObject();

                    point.Add("id", new JSONString(wp.Id.ToString()));
                    point.Add("name", new JSONString(wp.Name));
                    point.Add("ownerPlayerId", new JSONString(wp.OwnerPlayerId.ToString()));
                    point.Add("pos", pos);

                    waypointArray.Add(point);
                }

                StringBuilder stringBuilder = new StringBuilder();
                waypointArray.ToString(stringBuilder, false, 0);

                var bytes = Encoding.UTF8.GetBytes(stringBuilder.ToString());

                response.ContentLength64 = bytes.LongLength;
                response.ContentType     = "application/json";
                response.ContentEncoding = Encoding.UTF8;
                response.OutputStream.Write(bytes, 0, bytes.Length);
            } finally
            {
                if (context != null && !context.Response.SendChunked)
                {
                    context.Response.Close();
                }
            }
        }
Ejemplo n.º 26
0
    // add bookmark at
    void AddBookmark()
    {
        JSONObject newBookmark = CreateJSONBookmark(this.gameObject);

        bookmarks.Add(newBookmark);
    }
Ejemplo n.º 27
0
    public JSONValue ExportData()
    {
        var json_data = new JSONObject();

        json_data["m_letters_to_animate"] = m_letters_to_animate.ExportData();
        json_data["m_letters_to_animate_custom_idx"] = m_letters_to_animate_custom_idx;
        json_data["m_letters_to_animate_option"] = (int)m_letters_to_animate_option;

        if (m_loop_cycles.Count > 0)
        {
            var loops_data = new JSONArray();

            foreach (var action_loop in m_loop_cycles)
                loops_data.Add(action_loop.ExportData());

            json_data["LOOPS_DATA"] = loops_data;
        }

        var actions_data = new JSONArray();
        foreach (var action in m_letter_actions)
            actions_data.Add(action.ExportData());
        json_data["ACTIONS_DATA"] = actions_data;

        return new JSONValue(json_data);
    }
Ejemplo n.º 28
0
    public void SetTileSet(int id)
    {
        FileStream file;
        //file = File.Open (Application.dataPath + "/Resources/TileSets/EditorNameIDtileSet_" + id.ToString(), FileMode.Open);
        string jsonString = File.ReadAllText(Application.dataPath + "/Resources/TileSets/EditorNameIDtileSet_" + id.ToString() + ".txt");
        //Debug.Log(Application.dataPath);
        JSONNode jsonFile = JSON.Parse(jsonString);
        //Debug.Log (jsonFile ["maxID"]);

        int maxID = System.Int32.Parse(jsonFile ["maxID"]);
        //JSONArray array = jsonFile ["names"].AsArray;



        JSONNode idUVs = JSONNode.Parse("{}");



        //Dictionary<string, >

        Sprite[] sprites = Resources.LoadAll <Sprite> ("TileSets/" + "set_" + id.ToString());
        foreach (Sprite spr in sprites)
        {
            //JSONArray uvsArray;
            if (jsonFile ["names"] [spr.name] == null)
            {
                JSONArray uvsArray = JSONNode.Parse("{a:[]}")["a"].AsArray;

                foreach (Vector2 vector in ListElementsController.listElementsController.GetUvsByName(id.ToString(), spr.name.ToString()))
                {
                    JSONNode vectorNode = JSONNode.Parse("{}");
                    vectorNode ["x"] = vector.x;
                    vectorNode ["y"] = vector.y;

                    uvsArray.Add(vectorNode);
                }


                idUVs[maxID.ToString()] = uvsArray;
            }
            else
            {
                JSONArray uvsArray = JSONNode.Parse("{a:[]}")["a"].AsArray;

                foreach (Vector2 vector in ListElementsController.listElementsController.GetUvsByName(id.ToString(), spr.name.ToString()))
                {
                    JSONNode vectorNode = JSONNode.Parse("{}");
                    vectorNode ["x"] = vector.x;
                    vectorNode ["y"] = vector.y;

                    uvsArray.Add(vectorNode);
                }


                idUVs[jsonFile ["names"] [spr.name].Value] = uvsArray;


                /*idUVs [jsonFile ["names"] [spr.name].Value] ["x"] = vector.x;
                *  idUVs [jsonFile ["names"] [spr.name].Value] ["y"] = vector.y;*/
            }



            //Debug.Log(jsonFile ["names"] [spr.name]);
            if (jsonFile ["names"] [spr.name] == null)
            {
                jsonFile ["names"] [spr.name] = maxID;


                //ListElementsController.listElementsController.Get

                //Debug.Log (spr.name);


                maxID += 1;
                //idUVs[maxID] = maxID;
            }
        }

        jsonFile ["maxID"] = maxID;


        Debug.Log(idUVs.ToString());
        File.WriteAllText(Application.dataPath + "/Resources/TileSets/EditorNameIDtileSet_" + id.ToString() + ".txt", jsonFile.ToString());
        File.WriteAllText(Application.dataPath + "/Resources/TileSets/idUVsSet_" + id.ToString() + ".txt", idUVs.ToString());


        /*foreach (JSONNode node in jsonFile ["names"].AsArray) {
         *      Debug.Log (node.AsObject);
         * }*/
    }
Ejemplo n.º 29
0
        // TODO: Fix range computation to consider paddingOUter!!!
        // TODO: Fix range size.
        private void InferRange(ChannelEncoding channelEncoding, JSONNode specs, ref JSONObject scaleSpecsObj)
        {
            JSONArray range = new JSONArray();

            string channel = channelEncoding.channel;

            if (channel == "x" || channel == "width")
            {
                range.Add(new JSONString("0"));

                if (scaleSpecsObj["rangeStep"] == null)
                {
                    range.Add(new JSONString(specs["width"]));
                }
                else
                {
                    float rangeSize = float.Parse(scaleSpecsObj["rangeStep"]) * (float)scaleSpecsObj["domain"].Count;
                    range.Add(new JSONString(rangeSize.ToString()));
                    specs["width"] = rangeSize;
                }
            }
            else if (channel == "y" || channel == "height")
            {
                range.Add(new JSONString("0"));
                if (scaleSpecsObj["rangeStep"] == null)
                {
                    range.Add(new JSONString(specs["height"]));
                }
                else
                {
                    float rangeSize = float.Parse(scaleSpecsObj["rangeStep"]) * (float)scaleSpecsObj["domain"].Count;
                    range.Add(new JSONString(rangeSize.ToString()));
                    specs["height"] = rangeSize;
                }
            }
            else if (channel == "z" || channel == "depth")
            {
                range.Add(new JSONString("0"));
                if (scaleSpecsObj["rangeStep"] == null)
                {
                    range.Add(new JSONString(specs["depth"]));
                }
                else
                {
                    float rangeSize = float.Parse(scaleSpecsObj["rangeStep"]) * (float)scaleSpecsObj["domain"].Count;
                    range.Add(new JSONString(rangeSize.ToString()));
                    specs["depth"] = rangeSize;
                }
            }
            else if (channel == "opacity")
            {
                range.Add(new JSONString("0"));
                range.Add(new JSONString("1"));
            }
            else if (channel == "size" || channel == "length")
            {
                range.Add(new JSONString("0"));
                string maxDimSize = Math.Max(Math.Max(specs["width"].AsFloat, specs["height"].AsFloat),
                                             specs["depth"].AsFloat).ToString();

                range.Add(new JSONString(maxDimSize));
            }
            else if (channel == "color")
            {
                if (channelEncoding.fieldDataType == "nominal")
                {
                    scaleSpecsObj.Add("range", new JSONString("category"));
                }
                else if (channelEncoding.fieldDataType == "ordinal")
                {
                    scaleSpecsObj.Add("range", new JSONString("ordinal"));
                }
                else if (channelEncoding.fieldDataType == "quantitative" ||
                         channelEncoding.fieldDataType == "temporal")
                {
                    scaleSpecsObj.Add("range", new JSONString("ramp"));
                }
            }
            else if (channel == "shape")
            {
                range.Add(new JSONString("symbol"));
                throw new Exception("Not implemented yet.");
            }
            else if (channel == "xrotation" || channel == "yrotation" || channel == "zrotation")
            {
                range.Add(new JSONString("0"));
                range.Add(new JSONString("360"));
            }
            else if (channel == "xdirection" || channel == "ydirection" || channel == "zdirection")
            {
                range.Add(new JSONString("0"));
                range.Add(new JSONString("1"));
            }

            if (range.Count > 0)
            {
                scaleSpecsObj.Add("range", range);
            }
            // Debug.Log(scaleSpecsObj);
        }
Ejemplo n.º 30
0
    public JSONObject to_json()
    {
        JSONObject rtv = new JSONObject();

        JSONArray bullets = new JSONArray();
        foreach(SPBulletObject o in _bullets) {
            bullets.Add(o.to_json());
        }
        rtv.Add(SN.BULLETS,bullets);

        rtv.Add(SN.PLAYER,_player.to_json());
        return rtv;
    }
Ejemplo n.º 31
0
        void Save(string path)
        {
            JSONArray      obj   = new JSONArray();
            JSONArray      listR = new JSONArray();
            JSONArray      pos   = new JSONArray();
            JSONArray      typeO = new JSONArray();
            List <Vector3> rings = null;

            GameObject[] objs;
            objs = GameObject.FindGameObjectsWithTag("line");
            JSONArray transINfos = new JSONArray();
            JSONArray infosJSON  = new JSONArray();

            foreach (GameObject lineObj in objs)
            {
                listR = new JSONArray();
                rings = lineObj.GetComponent <SaveObjInfo>().coord;
                Vector4 colorInfo = lineObj.GetComponent <SaveObjInfo>().color;

                for (int i = 0; i < rings.Count; i++)
                {
                    pos = new JSONArray();
                    pos.Add(rings[i].x);
                    pos.Add(rings[i].y);
                    pos.Add(rings[i].z);
                    pos.Add(colorInfo[0]);
                    pos.Add(colorInfo[1]);
                    pos.Add(colorInfo[2]);
                    pos.Add(colorInfo[3]);
                    pos.Add(lineObj.GetComponent <SaveObjInfo>().trailSize);

                    listR.Add(pos);
                }

                //obj.Add(j);
                obj.Add(listR);
            }
            typeO.Add("Line", obj);


            objs       = GameObject.FindGameObjectsWithTag("Cube");
            transINfos = new JSONArray();
            infosJSON  = new JSONArray();
            obj        = new JSONArray();
            foreach (GameObject cubeObj in objs)
            {
                infosJSON = new JSONArray();

                pos = new JSONArray();
                pos.Add(cubeObj.transform.position.x);
                pos.Add(cubeObj.transform.position.y);
                pos.Add(cubeObj.transform.position.z);
                infosJSON.Add(pos);

                pos = new JSONArray();
                pos.Add(cubeObj.transform.localRotation.x);
                pos.Add(cubeObj.transform.localRotation.y);
                pos.Add(cubeObj.transform.localRotation.z);
                pos.Add(cubeObj.transform.localRotation.w);
                infosJSON.Add(pos);

                pos = new JSONArray();
                pos.Add(cubeObj.transform.localScale.x);
                pos.Add(cubeObj.transform.localScale.y);
                pos.Add(cubeObj.transform.localScale.z);
                infosJSON.Add(pos);
                obj.Add(infosJSON);

                pos = new JSONArray();
                Vector4 ColorInfo = cubeObj.GetComponent <Renderer>().material.color;
                pos.Add(ColorInfo.x);
                pos.Add(ColorInfo.y);
                pos.Add(ColorInfo.z);
                pos.Add(ColorInfo.w);
                infosJSON.Add(pos);


                pos = new JSONArray();
                pos.Add(cubeObj.GetComponent <Renderer>().material.shader.name.ToString());
                infosJSON.Add(pos);
            }
            typeO.Add(obj);

            objs       = GameObject.FindGameObjectsWithTag("Sphere");
            transINfos = new JSONArray();
            infosJSON  = new JSONArray();
            obj        = new JSONArray();
            foreach (GameObject cubeObj in objs)
            {
                infosJSON = new JSONArray();

                pos = new JSONArray();
                pos.Add(cubeObj.transform.position.x);
                pos.Add(cubeObj.transform.position.y);
                pos.Add(cubeObj.transform.position.z);
                infosJSON.Add(pos);

                pos = new JSONArray();
                pos.Add(cubeObj.transform.localRotation.x);
                pos.Add(cubeObj.transform.localRotation.y);
                pos.Add(cubeObj.transform.localRotation.z);
                pos.Add(cubeObj.transform.localRotation.w);
                infosJSON.Add(pos);

                pos = new JSONArray();
                pos.Add(cubeObj.transform.localScale.x);
                pos.Add(cubeObj.transform.localScale.y);
                pos.Add(cubeObj.transform.localScale.z);
                infosJSON.Add(pos);

                pos = new JSONArray();
                //Vector4 ColorInfo = cubeObj.GetComponent<Renderer>().material.color;
                Vector4 ColorInfo = cubeObj.GetComponent <Renderer>().material.color;
                pos.Add(ColorInfo.x);
                pos.Add(ColorInfo.y);
                pos.Add(ColorInfo.z);
                pos.Add(ColorInfo.w);
                infosJSON.Add(pos);
                obj.Add(infosJSON);

                pos = new JSONArray();
                pos.Add(cubeObj.GetComponent <Renderer>().material.shader.name.ToString());
                infosJSON.Add(pos);
            }
            typeO.Add(obj);



            pos = new JSONArray();
            pos.Add(cam.transform.position.x);
            pos.Add(cam.transform.position.z);
            pos.Add(cam.transform.localRotation.y);
            typeO.Add(pos);


            File.WriteAllText(path, typeO.ToString());
        }
Ejemplo n.º 32
0
	void LoadFBFriendsCallback(FBResult result) {
		if (result.Error != null)  {
      HUDManager.Instance.AddFlyText(Localization.Get("LoadFBFriend_Fail"), Vector3.zero, 40, Color.red, 0, 4f);
		} else {
			JSONObject friendsData = JSONObject.Parse(result.Text);
			JSONArray ids = friendsData.GetObject("friends").GetArray("data");
			JSONArray fbIds = new JSONArray();
			List<Buddy> buddyList = SmartfoxClient.Instance.GetBuddyList();
			for (int i = 0; i < ids.Length; i++) {
				string fbId = ids[i].Obj.GetString("id");
				bool added = false;
				for (int j = 0; j < buddyList.Count; j++) {
					if (fbId == buddyList[j].GetVariable("$facebookId").GetStringValue()) {
						added = true;
					}
				}
				if (!added) {
					fbIds.Add(fbId);
				}
			}
			if (fbIds.Length > 0) {
				UserExtensionRequest.Instance.AddFbFriends(fbIds);
			}
			friendsData = null;
			ids = null;
			fbIds = null;
		}        
	}
Ejemplo n.º 33
0
 private static JSONArray DeserializeSingletonArray(string text)
 {
     JSONArray array = new JSONArray();
     foreach (Match match in Regex.Matches(text, "(//\"(?<value>[^,//\"]+)\")|(?<value>[^,//[//]]+)"))
     {
         string key = match.Groups["value"].Value;
         array.Add(_json.ContainsKey(key) ? _json[key] : StrDecode(key));
     }
     return array;
 }
Ejemplo n.º 34
0
		private JSONObject CharactersJSON()
		{
			JSONObject obj = new JSONObject();
			JSONArray array = new JSONArray();
			foreach (PlayerCharacter character in mCharacters)
			{
				JSONArray tempArray = new JSONArray();
				tempArray.Add((int)character.Game);
				tempArray.Add(character.Serialize());
				array.Add(tempArray);
			}
			obj.Add(SerializableObject.CHARACTER_LIST, array);
			return obj;
		}
Ejemplo n.º 35
0
	public void logExpose(List<long> exposeList, WmInterfaceBroker.WmInterfaceBrokerDelegate callback){
		JSONObject jsonObject = new JSONObject();
		jsonObject.Add(JSON_KEY_URI,JSON_VALUE_PREFIX_URI+WM_HOST_PROMOTION_SEND_EXPOSELOG);
		JSONObject paramsObject = new JSONObject();
		JSONArray array = new JSONArray();
		foreach(long promoid in exposeList){
			array.Add(promoid);	
		}
		paramsObject.Add("promoIds",array);
		jsonObject.Add(JSON_KEY_PARAMS,paramsObject);
		WmInterfaceBroker.getInstance.requestAsync(jsonObject.ToString(),callback);
	}
Ejemplo n.º 36
0
        public void SanitizeText(IList <string> texts,
                                 Action <IList <string>, FizzException> callback)
        {
            IfOpened(() =>
            {
                if (texts == null)
                {
                    FizzUtils.DoCallback <IList <string> > (null, ERROR_INVALID_TEXT_LIST, callback);
                    return;
                }

                if (texts.Count > MAX_TEXT_LIST_SIZE)
                {
                    FizzUtils.DoCallback <IList <string> > (null, ERROR_INVALID_TEXT_LIST_SIZE, callback);
                    return;
                }

                foreach (string text in texts)
                {
                    if (text == null || text.Length > MAX_TEXT_LENGTH)
                    {
                        FizzUtils.DoCallback <IList <string> > (null, ERROR_INVALID_TEXT_LIST, callback);
                        return;
                    }
                }

                try
                {
                    string path    = FizzConfig.API_PATH_CONTENT_MODERATION;
                    JSONArray json = new JSONArray();
                    foreach (string text in texts)
                    {
                        json.Add(new JSONData(text));
                    }

                    _restClient.Post(FizzConfig.API_BASE_URL, path, json.ToString(), (response, ex) =>
                    {
                        if (ex != null)
                        {
                            FizzUtils.DoCallback <IList <string> > (null, ex, callback);
                        }
                        else
                        {
                            try
                            {
                                JSONArray textResultArr          = JSONNode.Parse(response).AsArray;
                                IList <string> moderatedTextList = new List <string> ();
                                foreach (JSONNode message in textResultArr.Childs)
                                {
                                    moderatedTextList.Add(message);
                                }
                                FizzUtils.DoCallback <IList <string> > (moderatedTextList, null, callback);
                            }
                            catch
                            {
                                FizzUtils.DoCallback <IList <string> > (null, ERROR_INVALID_RESPONSE_FORMAT, callback);
                            }
                        }
                    });
                }
                catch (FizzException ex)
                {
                    FizzUtils.DoCallback <IList <string> > (null, ex, callback);
                }
            });
        }
Ejemplo n.º 37
0
		public override JSONObject Serialize()
		{
			JSONObject obj = new JSONObject();
			obj.Add(NAME, Name);
			JSONArray tempArray = new JSONArray();
			foreach (string alt in AlternativeNames)
			{
				tempArray.Add(new JSONValue(alt));
			}
			obj.Add(cAltNames, tempArray);
			obj.Add(ALIGNMENT, (int)Alignment);
			tempArray = new JSONArray();
			foreach (DnDRace race in WorshippingRaces)
			{
				tempArray.Add(new JSONValue((int)race));
			}
			obj.Add(cRaces, tempArray);
			tempArray = new JSONArray();
			foreach (DnDCharClass charClass in WorshippingClasses)
			{
				tempArray.Add(new JSONValue((int)charClass));
			}
			obj.Add(cClasses, tempArray);
			tempArray = new JSONArray();
			foreach (DnDClericDomain domain in Domains)
			{
				tempArray.Add(new JSONValue((int)domain));
			}
			obj.Add(cDomains, tempArray);
			return obj;
		}
Ejemplo n.º 38
0
		public override JSONObject Serialize()
		{
			JSONObject obj = new JSONObject();
			obj.Add(LEVEL, mClassLevel);
			obj.Add(KNOWN_SPELLS, SerializeKnownSpells());
			obj.Add(MAIN_SPELLS, SerializeMainSpells());
			obj.Add(EXTRA_SPELLS, SerializeExtraSpells());
			obj.Add(SKILLS, mSkills.Serialize());
			// spec:
			JSONArray tempArray = new JSONArray();
			tempArray.Add((int)mSpecialization);
			foreach (var forbidden in mForbiddenSchools)
			{
				tempArray.Add((int)forbidden);
			}
			obj.Add(SPECIALIZATION, tempArray);
			return obj;
		}
Ejemplo n.º 39
0
    private void edit_gdxfx()
    {
        string responseError = "{success: false}";
        string sql1 = string.Format("select * from sq8szxlx.zpgl where id='{0}'", Request.Params["id"]);
        RowObject r1 = DBHelper.GetRow(sql1);
        if (r1 == null)
        {
            Response.Write(responseError);
            Response.End();
            return;
        }
        string gyy_mc = r1["所属工业园"].ToString();
        string fclx = r1["房产类型"].ToString();
        string htbh = r1["编码"].ToString();

        string sql2 = string.Format("select * from sq8szxlx.gyy_lb_fclx_lb_xflx where 工业园名称='{0}' and 房产类型='{1}' order by 序号 asc",
            gyy_mc, fclx);
        ResultObject r2 = DBHelper.GetResult(sql2);
        JSONArray ja = new JSONArray();
        int i = 1;
        foreach (RowObject item in r2)
        {
            JSONObject jo = new JSONObject();

            string xfxm = item["消费项目"].ToString();
            string rq = r1["合同开始时间"].ToString();
            string sql3 = string.Format("select * from sq8szxlx.zpgl_lx_lb where 合同编号='{0}' and 消费项目='{1}'", htbh, xfxm);
            RowObject r3 = DBHelper.GetRow(sql3);
            string sql4 = string.Format("select * from sq8szxlx.user_sf_lb where 合同编号='{0}' and 收费项目='{1}' and  日期='{2}'", htbh, xfxm, rq);
            RowObject r4 = DBHelper.GetRow(sql4);

            jo.Add("id", item["id"]);
            jo.Add("编号", i);
            jo.Add("消费项目", xfxm);
            jo.Add("消费类型", item["消费类型"]);
            jo.Add("值", (r3 == null) ? item["值"] : r3["值"]);
            jo.Add("倍率", (r3 == null) ? item["倍率"] : r3["倍率"]);
            jo.Add("损耗", (r3 == null) ? item["损耗"] : r3["损耗"]);
            jo.Add("滞纳金", (r3 == null) ? item["滞纳金"] : r3["滞纳金"]);
            jo.Add("前期读数", item["消费类型"].ToString() == "动态" ? r4["读数"] : "-");
            jo.Add("说明", (r3 == null) ? item["说明"] : r3["说明"]);
            jo.Add("读数导入", (r4 != null && r4["录入状态"].ToString() == "已录入") ? "√" : "×");
            jo.Add("项目导入", (r4 != null && r4["值"] != "") ? "√" : "×");
            i++;
            ja.Add(jo);
        }
        Response.Write(string.Format("{{'success': true, 'data':{0}}}", JSONConvert.SerializeArray(ja)));
    }
Ejemplo n.º 40
0
 private void EventFilterBet() {
   betFilterLabel.SetCurrentSelection();
   string crtSelect = UIPopupList.current.value;
   Debug.Log("EventFilterBet " + crtSelect);
   if (crtSelect == crtBetFilter) {
     return;
   }
   crtBetFilter = crtSelect;
   switch (crtSelect) {
     case "Bet_Filter_All":
       InitScrollViewData();
     break;
     case "Bet_Filter_under_50k":
       filteredRoomList = new JSONArray();
       for (int i = 0; i < roomList.Length; i++) {
         if (roomList[i].Obj.GetInt("minBet") <= 50000) {
           filteredRoomList.Add(roomList[i].Obj);
         }
       }
       InitScrollViewData(true);
     break;
     case "Bet_Filter_over_100k":
       filteredRoomList = new JSONArray();
       for (int i = 0; i < roomList.Length; i++) {
         if (roomList[i].Obj.GetInt("minBet") >= 100000) {
           filteredRoomList.Add(roomList[i].Obj);
         }
       }
       InitScrollViewData(true);
     break;
     case "Bet_Filter_over_500k":
       filteredRoomList = new JSONArray();
       for (int i = 0; i < roomList.Length; i++) {
         if (roomList[i].Obj.GetInt("minBet") >= 500000) {
           filteredRoomList.Add(roomList[i].Obj);
         }
       }
       InitScrollViewData(true);
     break;
     case "Bet_Filter_over_1m":
       filteredRoomList = new JSONArray();
       for (int i = 0; i < roomList.Length; i++) {
         if (roomList[i].Obj.GetInt("minBet") >= 1000000) {
           filteredRoomList.Add(roomList[i].Obj);
         }
       }
       InitScrollViewData(true);
     break;
   }
   scrollview.panel.alpha = 0.1f;
   TweenAlpha tween = TweenAlpha.Begin(scrollview.gameObject, 0.8f, 1.0f);
 }
Ejemplo n.º 41
0
    private readonly string kafkaURL    = "192.168.160.20:9093";  // "localhost:9092"

    void executeOrder()
    {
        if (GameObject.Find("Btn Open Session").GetComponent <Animator>().GetCurrentAnimatorStateInfo(0).IsName("press"))
        {
            print("open Session");             ///////////////////////////////////////////////////////////////////////////////////////////////////////////////

            TMP_InputField titleInput    = GameObject.Find("TitleInput").GetComponent <TMP_InputField>();
            TMP_InputField durationInput = GameObject.Find("DurationInput").GetComponent <TMP_InputField>();
            TMP_InputField wordsInput    = GameObject.Find("WordsInput").GetComponent <TMP_InputField>();

            titleInput.text    = "test01";
            durationInput.text = "600";
            wordsInput.text    = "tree,ball";

            if (int.TryParse(durationInput.text, out int durationInput_int))
            {
                JSONArray words     = new JSONArray();
                string[]  words_raw = wordsInput.text.Split(',');
                for (int i = 0; i < words_raw.Length; i++)
                {
                    words.Add(words_raw[i]);
                }

                JSONObject body = new JSONObject();
                body["title"]    = titleInput.text;
                body["duration"] = durationInput_int;
                body["words"]    = words;

                StartCoroutine(PostGameSession(baseURL + "session", body.ToString(), LoginData.Token, sessionIdStr => {
                    Debug.Log(sessionIdStr);
                    JSONNode sessionIdJSON = JSONObject.Parse(sessionIdStr);
                    int sessionId          = sessionIdJSON["id"];
                    Debug.Log(sessionId);
                    SessionData.SessionId = sessionId;
                }));
            }
        }
        else if (GameObject.Find("Btn Start").GetComponent <Animator>().GetCurrentAnimatorStateInfo(0).IsName("press"))
        {
            print("Start");                                                //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            StartCoroutine(GetGameSession(commandsURL + "session/" + SessionData.SessionId + "/action/start", authenticate(LoginData.Username, "12345678"), response => {
                SessionData.KafkaTopic = "esp54_" + SessionData.SessionId; //"esp54_1"; //"actor0002";
                SessionData.KafkaProps = new Dictionary <string, string> {
                    { "group.id", "test" },
                    { "bootstrap.servers", kafkaURL },
                    { "enable.auto.commit", "false" },
                    { "auto.offset.reset", "latest" }
                };
                changeScene("Actor_Scene");
            }));
        }
        else if (GameObject.Find("Btn Invite Player").GetComponent <Animator>().GetCurrentAnimatorStateInfo(0).IsName("press"))
        {
            print("Invite Player");             //////////////////////////////////////////////////////////////////////////////////////////////////////////////
        }
        else if (GameObject.Find("Btn Go Back").GetComponent <Animator>().GetCurrentAnimatorStateInfo(0).IsName("press"))
        {
            print("Go Back");
            changeScene("Main_Menu_Scene");              /////////////////////////////////////////////////////////////////////////////////////////////////////
        }
    }
        //  FIXME: Generic export when recieves ignore field parameters
        // Add attribute like IgnoreExport or similar
        // For linked types do similar
        public override string ExportData(NodeGraphData data, List <Type> referenceTypes)
        {
            JSONObject exportJSON = new JSONObject();

            JSONObject graph = new JSONObject();

            JSONArray graphNodesReferences = new JSONArray();

            referenceTypes.Add(typeof(Node));
            referenceTypes.Add(typeof(NodeGraph));
            referenceTypes.Add(typeof(NodePort));

            graph.Add("type", new JSONString(data.graph.GetType().AssemblyQualifiedName));
            graph.Add("name", new JSONString(data.graph.name));
            graph.Add("id", new JSONNumber(data.graph.GetHashCode()));
            NodeGraph g = data.graph;

            graph = (JSONObject)SimpleJSONExtension.ToJSON(g, graph, new List <string>()
            {
                "sceneVariables"
            }, referenceTypes);

            JSONArray connections = new JSONArray();

            for (int c = 0; c < data.connections.Count; c++)
            {
                JSONObject connection = new JSONObject();
                connection.Add("port1ID", data.connections[c].port1ID);
                connection.Add("port2ID", data.connections[c].port2ID);
                connections.Add(connection);
            }

            JSONArray nodes = new JSONArray();

            for (int n = 0; n < data.nodes.Count; n++)
            {
                Node       node     = data.nodes[n].node;
                JSONObject nodeJSON = new JSONObject();
                nodeJSON.Add("name", node.name);
                nodeJSON.Add("type", node.GetType().AssemblyQualifiedName);
                nodeJSON.Add("position", node.position);
                nodeJSON.Add("id", node.GetHashCode());

                JSONArray nodePorts = new JSONArray();

                for (int np = 0; np < data.nodes[n].ports.Count; np++)
                {
                    NodePort port = data.nodes[n].ports[np].port;

                    JSONObject nodePortJSON = new JSONObject();
                    nodePortJSON.Add("name", port.fieldName);
                    nodePortJSON.Add("id", port.GetHashCode());
                    nodePortJSON.Add("dynamic", port.IsDynamic);
                    nodePortJSON.Add("valueType", port.ValueType.AssemblyQualifiedName);
                    nodePortJSON.Add("typeConstraint", (int)port.typeConstraint);
                    nodePortJSON.Add("connectionType", (int)port.connectionType);
                    nodePortJSON.Add("direction", (int)port.direction);

                    nodePorts.Add(nodePortJSON);
                }

                nodeJSON.Add("ports", nodePorts);

                nodeJSON = (JSONObject)SimpleJSONExtension.ToJSON(node, nodeJSON, new List <string>(), referenceTypes);

                nodes.Add(nodeJSON);
            }

            exportJSON.Add("graph", graph);
            exportJSON.Add("connections", connections);
            exportJSON.Add("nodes", nodes);

            return(exportJSON.ToString());
        }
Ejemplo n.º 43
0
    public JSONObject to_json()
    {
        JSONObject rtv = new JSONObject();

        JSONArray players = new JSONArray();
        foreach(SPPlayerObject o in _players) {
            players.Add(o.to_json());
        }
        rtv.Add(SN.PLAYERS,players);

        JSONArray bullets = new JSONArray();
        foreach(SPBulletObject o in _bullets) {
            bullets.Add(o.to_json());
        }
        rtv.Add(SN.BULLETS,bullets);

        JSONArray events = new JSONArray();
        foreach(SPEvent o in _events) {
            events.Add(o.to_json());
        }
        rtv.Add(SN.EVENTS,events);

        return rtv;
    }
Ejemplo n.º 44
0
        public static JSONNode Deserialize(System.IO.BinaryReader aReader)
        {
            JSONBinaryTag type = (JSONBinaryTag)aReader.ReadByte();

            switch (type)
            {
            case JSONBinaryTag.Array:
            {
                int       count = aReader.ReadInt32();
                JSONArray tmp   = new JSONArray();
                for (int i = 0; i < count; i++)
                {
                    tmp.Add(Deserialize(aReader));
                }
                return(tmp);
            }

            case JSONBinaryTag.Class:
            {
                int       count = aReader.ReadInt32();
                JSONClass tmp   = new JSONClass();
                for (int i = 0; i < count; i++)
                {
                    string key = aReader.ReadString();
                    var    val = Deserialize(aReader);
                    tmp.Add(key, val);
                }
                return(tmp);
            }

            case JSONBinaryTag.Value:
            {
                return(new JSONData(aReader.ReadString()));
            }

            case JSONBinaryTag.IntValue:
            {
                return(new JSONData(aReader.ReadInt32()));
            }

            case JSONBinaryTag.DoubleValue:
            {
                return(new JSONData(aReader.ReadDouble()));
            }

            case JSONBinaryTag.BoolValue:
            {
                return(new JSONData(aReader.ReadBoolean()));
            }

            case JSONBinaryTag.FloatValue:
            {
                return(new JSONData(aReader.ReadSingle()));
            }

            default:
            {
                throw new Exception("Error deserializing JSON. Unknown tag: " + type);
            }
            }
        }
Ejemplo n.º 45
0
        private void InferDomain(ChannelEncoding channelEncoding, JSONNode specs, ref JSONObject scaleSpecsObj, Data data)
        {
            string sortType = "ascending";

            if (specs != null && specs["encoding"][channelEncoding.channel]["sort"] != null)
            {
                sortType = specs["encoding"][channelEncoding.channel]["sort"].Value.ToString();
            }

            string    channel = channelEncoding.channel;
            JSONArray domain  = new JSONArray();

            if (channelEncoding.fieldDataType == "quantitative" &&
                (channel == "x" || channel == "y" || channel == "z" ||
                 channel == "width" || channel == "height" || channel == "depth" || channel == "length" ||
                 channel == "color" || channel == "xrotation" || channel == "yrotation" ||
                 channel == "zrotation" || channel == "size" || channel == "xdirection") ||
                channel == "ydirection" || channel == "zdirection" || channel == "opacity")
            {
                List <float> minMax = new List <float>();
                GetExtent(data, channelEncoding.field, ref minMax);

                /*
                 * // For positive minimum values, set the baseline to zero.
                 * // TODO: Handle logarithmic scale with undefined 0 value.
                 * if(minMax[0] >= 0)
                 * {
                 *  minMax[0] = 0;
                 * }
                 *
                 * float roundedMaxDomain = RoundNice(minMax[1] - minMax[0]);
                 */

                if (sortType == "none" || sortType == "ascending")
                {
                    //domain.Add(new JSONString(minMax[0].ToString()));
                    domain.Add(new JSONString("0"));
                    domain.Add(new JSONString(minMax[1].ToString()));
                }
                else
                {
                    domain.Add(new JSONString(minMax[1].ToString()));
                    domain.Add(new JSONString("0"));
                    //domain.Add(new JSONString(minMax[0].ToString()));
                }
            }
            else
            {
                List <string> uniqueValues = new List <string>();
                GetUniqueValues(data, channelEncoding.field, ref uniqueValues);

                if (sortType == "ascending")
                {
                    uniqueValues.Sort();
                }
                else if (sortType == "descending")
                {
                    uniqueValues.Sort();
                    uniqueValues.Reverse();
                }

                foreach (string val in uniqueValues)
                {
                    domain.Add(val);
                }
            }

            scaleSpecsObj.Add("domain", domain);
        }
Ejemplo n.º 46
0
    public void Save()
    {
        JSONObject ObjectJson = new JSONObject();
        JSONArray  TypeJson   = new JSONArray();
        JSONArray  positionX  = new JSONArray();
        JSONArray  positionY  = new JSONArray();
        JSONArray  positionZ  = new JSONArray();

        /*JSONArray rotationX = new JSONArray();
        *  JSONArray rotationY = new JSONArray();
        *  JSONArray rotationZ = new JSONArray();*/
        for (int i = 0; i < 486; i++)
        {
            NowType[i] = Plane[i].GetComponent <MainCreateController>().Type;
            TypeJson.Add(NowType[i]);
            ObjectJson.Add("NowType", TypeJson);
            if (ObjectJson["NowType"][i] == 0)
            {
                positionX.Add(0);
                positionY.Add(0);
                positionZ.Add(0);

                /*rotationX.Add(0);
                *  rotationY.Add(0);
                *  rotationZ.Add(0);*/
                ObjectJson.Add("PositionX", positionX);
                ObjectJson.Add("PositionY", positionY);
                ObjectJson.Add("PositionZ", positionZ);

                /*ObjectJson.Add("RotationX", rotationX);
                *  ObjectJson.Add("RotationY", rotationY);
                *  ObjectJson.Add("RotationZ", rotationZ);*/
            }
            if (!Plane[i].GetComponent <MainCreateController>().IsEmpty)
            {
                /*if(i == 61)
                 * {
                 *  positionX.Add(0);
                 *  positionY.Add(0);
                 *  positionZ.Add(0);
                 *  ObjectJson.Add("PositionX", positionX);
                 *  ObjectJson.Add("PositionY", positionY);
                 *  ObjectJson.Add("PositionZ", positionZ);
                 * }*/
                //else
                //{
                positionX.Add(Plane[i].transform.GetChild(0).position.x);
                positionY.Add(Plane[i].transform.GetChild(0).position.y);
                positionZ.Add(Plane[i].transform.GetChild(0).position.z);

                /*rotationX.Add(Plane[i].transform.GetChild(0).rotation.x);
                *  rotationY.Add(Plane[i].transform.GetChild(0).rotation.y);
                *  rotationZ.Add(Plane[i].transform.GetChild(0).rotation.z);*/
                ObjectJson.Add("PositionX", positionX);
                ObjectJson.Add("PositionY", positionY);
                ObjectJson.Add("PositionZ", positionZ);

                /*ObjectJson.Add("RotationX", rotationX);
                *  ObjectJson.Add("RotationY", rotationY);
                *  ObjectJson.Add("RotationZ", rotationZ);*/
                //}
            }
        }
        string path = Application.dataPath + "/PlayerSave.json";

        File.WriteAllText(path, ObjectJson.ToString());
    }
Ejemplo n.º 47
0
        static IEnumerator _Check(string myUuid,
                                  int childId,    // childId == 0 ? Get Updated Child List and confirm Pairing
                                  int[] activities,
                                  resultClosure callback,
                                  bool log) // if set, then this is an autochecker and we drop it if we replace it. If null, it's adhoc, always return a value
        {
            if (!IsPaired)
            {
                callback(Allow2Error.NotPaired, null);
                yield break;
            }

            Debug.Log(userId);
            Debug.Log(pairToken);
            Debug.Log(_deviceToken);

            JSONNode body = new JSONObject();

            body.Add("userId", userId);
            body.Add("pairToken", pairToken);
            body.Add("deviceToken", _deviceToken);
            body.Add("tz", _timezone);
            JSONArray activityJson = new JSONArray();

            foreach (int activity in activities)
            {
                JSONNode activityParams = new JSONObject();
                activityParams.Add("id", activity);
                activityParams.Add("log", log);
                activityJson.Add(activityParams);
            }
            body.Add("activities", activityJson);
            body.Add("log", log);
            if (childId > 0)
            {
                body.Add("childId", childId);
            }
            string bodyStr = body.ToString();

            // check the cache first
            if (resultCache.ContainsKey(bodyStr))
            {
                Allow2CheckResult checkResult = resultCache[bodyStr];

                if (checkResult.Expires.CompareTo(new DateTime()) < 0)
                {
                    // not expired yet, use cached value
                    callback(null, checkResult);
                    yield break;
                }

                // clear cached value and ask the server again
                resultCache.Remove(bodyStr);
            }

            byte[] bytes = Encoding.UTF8.GetBytes(bodyStr);
            using (UnityWebRequest www = new UnityWebRequest(ServiceUrl + "/serviceapi/check"))
            {
                www.method                    = UnityWebRequest.kHttpVerbPOST;
                www.uploadHandler             = new UploadHandlerRaw(bytes);
                www.downloadHandler           = new DownloadHandlerBuffer();
                www.uploadHandler.contentType = "application/json";
                www.chunkedTransfer           = false;
                yield return(www.SendWebRequest());

                if ((myUuid != null) && (checkerUuid != myUuid))
                {
                    Debug.Log("drop response for check: " + myUuid);
                    yield break;    // this check is aborted, just drop the response and don't return;
                }

                Debug.Log(www.downloadHandler.text);
                var json = Allow2_SimpleJSON.JSON.Parse(www.downloadHandler.text);

                if ((www.responseCode == 401) ||
                    ((json["status"] == "error") &&
                     ((json["message"] == "Invalid user.") ||
                      (json["message"] == "invalid pairToken"))))
                {
                    // special case, no longer controlled
                    Debug.Log("No Longer Paired");
                    userId    = 0;
                    pairToken = null;
                    Persist();
                    //childId = 0;
                    //_children = []
                    //_dayTypes = []
                    var failOpen = new Allow2CheckResult();
                    failOpen.Add("subscription", new Allow2_SimpleJSON.JSONArray());
                    failOpen.Add("allowed", true);
                    failOpen.Add("activities", new Allow2_SimpleJSON.JSONArray());
                    failOpen.Add("dayTypes", new Allow2_SimpleJSON.JSONArray());
                    failOpen.Add("allDayTypes", new Allow2_SimpleJSON.JSONArray());
                    failOpen.Add("children", new Allow2_SimpleJSON.JSONArray());
                    callback(null, failOpen);
                    yield break;
                }

                if (www.isNetworkError || www.isHttpError)
                {
                    Debug.Log(www.error);
                    callback(www.error, null);
                    yield break;
                }

                if (json["allowed"] == null)
                {
                    callback(Allow2Error.InvalidResponse, null);
                    yield break;
                }

                var response = new Allow2CheckResult();
                response.Add("activities", json["activities"]);
                response.Add("subscription", json["subscription"]);
                response.Add("dayTypes", json["dayTypes"]);
                response.Add("children", json["children"]);
                var _dayTypes = json["allDayTypes"];
                response.Add("allDayTypes", _dayTypes);
                var oldChildIds = _children.Keys;
                var children    = json["children"];
                _children = ParseChildren(children);
                response.Add("children", children);

                if (oldChildIds != _children.Keys)
                {
                    Persist(); // only persist if the children change, this won't happen often.
                }

                // cache the response
                resultCache[bodyStr] = response;
                callback(null, response);
            }
        }
Ejemplo n.º 48
0
	public string ExportData(bool hard_copy = false)
	{
		var json_data = new JSONObject();

		json_data["TEXTFX_EXPORTER_VERSION"] = JSON_EXPORTER_VERSION;
		json_data["m_animate_per"] = (int)m_animate_per;
		json_data["m_display_axis"] = (int)m_display_axis;

		if (hard_copy)
		{
			json_data["m_begin_delay"] = m_begin_delay;
			json_data["m_begin_on_start"] = m_begin_on_start;
			json_data["m_character_size"] = m_character_size;
			json_data["m_line_height"] = m_line_height_factor;
			json_data["m_max_width"] = m_max_width;
			json_data["m_on_finish_action"] = (int)m_on_finish_action;
			json_data["m_px_offset"] = m_px_offset.Vector2ToJSON();
//			json_data["m_text"] = m_text;
			json_data["m_text_alignment"] = (int)m_text_alignment;
			json_data["m_text_anchor"] = (int)m_text_anchor;
			json_data["m_time_type"] = (int)m_time_type;
		}

		var letter_animations_data = new JSONArray();
		if (m_master_animations != null)
			foreach (var anim in m_master_animations)
				letter_animations_data.Add(anim.ExportData());
		json_data["LETTER_ANIMATIONS_DATA"] = letter_animations_data;

		return json_data.ToString();
	}
Ejemplo n.º 49
0
	public JSONValue ExportData()
	{
		var json_data = new JSONObject();

		json_data["m_action_type"] = (int)m_action_type;
		json_data["m_ease_type"] = (int)m_ease_type;
		json_data["m_use_gradient_start"] = m_use_gradient_start;
		json_data["m_use_gradient_end"] = m_use_gradient_end;
		json_data["m_force_same_start_time"] = m_force_same_start_time;
		json_data["m_letter_anchor_start"] = m_letter_anchor_start;
		json_data["m_letter_anchor_end"] = m_letter_anchor_end;
		json_data["m_letter_anchor_2_way"] = m_letter_anchor_2_way;
		json_data["m_offset_from_last"] = m_offset_from_last;
		json_data["m_position_axis_ease_data"] = m_position_axis_ease_data.ExportData();
		json_data["m_rotation_axis_ease_data"] = m_rotation_axis_ease_data.ExportData();
		json_data["m_scale_axis_ease_data"] = m_scale_axis_ease_data.ExportData();

		if (m_use_gradient_start)
			json_data["m_start_vertex_colour"] = m_start_vertex_colour.ExportData();
		else
			json_data["m_start_colour"] = m_start_colour.ExportData();
		json_data["m_start_euler_rotation"] = m_start_euler_rotation.ExportData();
		json_data["m_start_pos"] = m_start_pos.ExportData();
		json_data["m_start_scale"] = m_start_scale.ExportData();

		if (m_use_gradient_end)
			json_data["m_end_vertex_colour"] = m_end_vertex_colour.ExportData();
		else
			json_data["m_end_colour"] = m_end_colour.ExportData();
		json_data["m_end_euler_rotation"] = m_end_euler_rotation.ExportData();
		json_data["m_end_pos"] = m_end_pos.ExportData();
		json_data["m_end_scale"] = m_end_scale.ExportData();

		json_data["m_delay_progression"] = m_delay_progression.ExportData();
		json_data["m_duration_progression"] = m_duration_progression.ExportData();


		var audio_effects_data = new JSONArray();
		foreach (var effect_setup in m_audio_effects)
		{
			if (effect_setup.m_audio_clip == null)
				continue;

			audio_effects_data.Add(effect_setup.ExportData());
		}
		json_data["AUDIO_EFFECTS_DATA"] = audio_effects_data;

		var particle_effects_data = new JSONArray();
		foreach (var effect_setup in m_particle_effects)
		{
			if (effect_setup.m_legacy_particle_effect == null && effect_setup.m_shuriken_particle_effect == null)
				continue;

			particle_effects_data.Add(effect_setup.ExportData());
		}
		json_data["PARTICLE_EFFECTS_DATA"] = particle_effects_data;

		return new JSONValue(json_data);
	}
Ejemplo n.º 50
0
 public override JSONNode this[int aIndex]
 {
     get
     {
         return new JSONLazyCreator(this);
     }
     set
     {
         var tmp = new JSONArray();
         tmp.Add(value);
         Set(tmp);
     }
 }
Ejemplo n.º 51
0
    //autoWalkToNextWayPoint ();


    void SaveJson()
    {
        JSONObject json    = new JSONObject();
        JSONObject lvOne   = new JSONObject();
        JSONObject lvTwo   = new JSONObject();
        JSONObject lvThree = new JSONObject();
        JSONObject lvFour  = new JSONObject();

        JSONArray startOne   = new JSONArray();
        JSONArray endOne     = new JSONArray();
        JSONArray startTwo   = new JSONArray();
        JSONArray endTwo     = new JSONArray();
        JSONArray startThree = new JSONArray();
        JSONArray endThree   = new JSONArray();
        JSONArray startFour  = new JSONArray();
        JSONArray endFour    = new JSONArray();


        if (rooms == null)
        {
            rooms = GameObject.FindGameObjectsWithTag("Door");
        }
        //Debug.Log (rooms.Length);
        roomPosition = new Vector3[rooms.Length];
        int i = 0;

        foreach (GameObject room in rooms)
        {
            roomPosition [i] = new Vector3(room.transform.position.x, 2f, room.transform.position.z);
            Debug.Log(roomPosition[i]);
            i++;
        }

        /*Debug.Log (totalRoomPassedBy (startPoint, endPoint) + " rooms pass by. "
         + totalPossibleTurn (startPoint, endPoint) + " turns include."
         + DifficultWeight (startPoint, endPoint) + " turn weight."
         + totalDistance(startPoint, endPoint) + " Distance."
         + (totalRoomPassedBy (startPoint, endPoint) * 2 + totalPossibleTurn (startPoint, endPoint)* 2
         + DifficultWeight (startPoint, endPoint) * 10 + totalDistance(startPoint, endPoint)*0.1) + " DIfficutly.");
         */
        Vector3[] a = new Vector3[2];
        for (int j = 0; j < roomPosition.Length; j++)
        {
            for (int k = 0; k < roomPosition.Length; k++)
            {
                if (j != k)
                {
                    //Debug.Log ("start: " + roomPosition[j] + "End: " + roomPosition[k]);

                    /*Debug.Log (totalRoomPassedBy (roomPosition[j],roomPosition[k]) + " rooms pass by. "
                     + totalPossibleTurn (roomPosition[j],roomPosition[k]) + " turns include."
                     + DifficultWeight (roomPosition[j],roomPosition[k]) + " turn weight."
                     + totalDistance(roomPosition[j],roomPosition[k]) + " Distance."
                     + (totalRoomPassedBy (roomPosition[j],roomPosition[k]) * 2 + totalPossibleTurn (roomPosition[j],roomPosition[k])* 2
                     + DifficultWeight (roomPosition[j],roomPosition[k]) * 10 + totalDistance(roomPosition[j],roomPosition[k])*0.1) + " DIfficutly.");
                     */

                    difficulty = totalRoomPassedBy(roomPosition[j], roomPosition[k]) * 2
                                 + totalPossibleTurn(roomPosition[j], roomPosition[k]) * 2
                                 + DifficultWeight(roomPosition[j], roomPosition[k]) * 10
                                 + (totalDistance(roomPosition[j], roomPosition[k]) * 0.1);

                    Debug.Log(difficulty);
                    if (difficulty < 20 && difficulty >= 0)
                    {
                        //Debug.Log ("add success");
                        JSONArray posStart = new JSONArray();
                        JSONArray posEnd   = new JSONArray();

                        posStart.Add(roomPosition[j].x);
                        posStart.Add(roomPosition[j].y);
                        posStart.Add(roomPosition[j].z);
                        posEnd.Add(roomPosition[k].x);
                        posEnd.Add(roomPosition[k].y);
                        posEnd.Add(roomPosition[k].z);
                        startOne.Add(posStart);
                        endOne.Add(posEnd);
                        lvOne.Add("Start", startOne);
                        lvOne.Add("End", endOne);
                        //Debug.Log ("add success");
                    }
                    if (difficulty < 50 && difficulty >= 20)
                    {
                        JSONArray posStart = new JSONArray();
                        JSONArray posEnd   = new JSONArray();

                        posStart.Add(roomPosition[j].x);
                        posStart.Add(roomPosition[j].y);
                        posStart.Add(roomPosition[j].z);
                        posEnd.Add(roomPosition[k].x);
                        posEnd.Add(roomPosition[k].y);
                        posEnd.Add(roomPosition[k].z);
                        startTwo.Add(posStart);
                        endTwo.Add(posEnd);
                        lvTwo.Add("Start", startTwo);
                        lvTwo.Add("End", endTwo);
                    }
                    if (difficulty < 80 && difficulty >= 50)
                    {
                        JSONArray posStart = new JSONArray();
                        JSONArray posEnd   = new JSONArray();

                        posStart.Add(roomPosition[j].x);
                        posStart.Add(roomPosition[j].y);
                        posStart.Add(roomPosition[j].z);
                        posEnd.Add(roomPosition[k].x);
                        posEnd.Add(roomPosition[k].y);
                        posEnd.Add(roomPosition[k].z);
                        startThree.Add(posStart);
                        endThree.Add(posEnd);
                        lvThree.Add("Start", startThree);
                        lvThree.Add("End", endThree);
                    }
                    if (difficulty >= 80)
                    {
                        JSONArray posStart = new JSONArray();
                        JSONArray posEnd   = new JSONArray();

                        posStart.Add(roomPosition[j].x);
                        posStart.Add(roomPosition[j].y);
                        posStart.Add(roomPosition[j].z);
                        posEnd.Add(roomPosition[k].x);
                        posEnd.Add(roomPosition[k].y);
                        posEnd.Add(roomPosition[k].z);
                        startFour.Add(posStart);
                        endFour.Add(posEnd);
                        lvFour.Add("Start", startFour);
                        lvFour.Add("End", endFour);
                    }
                }
            }
        }
        //json.Add ("Level one", levelOne.ToArray());

        //Debug.Log(levelOne);

        //for (int j = 0; j < roomPosition.Length; j++)
        //Debug.Log (roomPosition[j]);
        json.Add("Level One", lvOne);
        json.Add("Level two", lvTwo);
        json.Add("Level three", lvThree);
        json.Add("Level four", lvFour);
        //Debug.Log (json.ToString());
        String path = Application.persistentDataPath + "/LevleSave.json";

        Debug.Log(Application.persistentDataPath + "/LevleSave.json");
        File.WriteAllText(path, json.ToString());
    }
Ejemplo n.º 52
0
 public override void Add(JSONNode aItem)
 {
     var tmp = new JSONArray();
     tmp.Add(aItem);
     Set(tmp);
 }
Ejemplo n.º 53
0
    public JSONObject Save(JSONObject jsonObject)
    {
        //save the data
        var isLastDialogueFinished = false;

        if (_currentDialogueMessages.Count != 0)
        {
            WrapAndSavePlotDialogues();
        }
        else
        {
            isLastDialogueFinished = true;
        }

        var dialogueLengthInfo = new List <int>();
        var dialogueMessages   = new List <MessageContent>();

        SerializeManager.Serialize2DArray(_dialogueMessages.ToArray(), out dialogueLengthInfo, out dialogueMessages);

        if (currentStory != null)
        {
            File.WriteAllText(Services.saveManager.inkjsonPath, Services.textManager.currentStory.state.ToJson(), Encoding.UTF8);
        }
        else
        {
            File.WriteAllText(Services.saveManager.inkjsonPath, "");
        }

        //write them in the json file
        var textJsonObj = new JSONObject();

        textJsonObj.Add("isLastDialogueFinished", isLastDialogueFinished);
        var jsonDialogueLengthInfo = new JSONArray();

        foreach (var lengthInfo in dialogueLengthInfo)
        {
            jsonDialogueLengthInfo.Add(lengthInfo);
        }
        textJsonObj.Add("dialogueLengthInfo", jsonDialogueLengthInfo);
        var jsonDialogueContent = new JSONArray();

        foreach (var msg in dialogueMessages)
        {
            var msgObj = new JSONObject();
            msgObj.Add("messageType", msg.messageType.ToString());
            msgObj.Add("content", msg.content);
            var shootTimeString = (SerializeManager.JsonDateTime)msg.shootTime;
            msgObj.Add("shootTime", shootTimeString.value.ToString());
            if (!ReferenceEquals(msg.fileBubbleName, null))
            {
                msgObj.Add("fileBubbleName", msg.fileBubbleName);
            }
            if (!ReferenceEquals(msg.fileContentName, null))
            {
                msgObj.Add("fileBubbleName", msg.fileContentName);
            }
            jsonDialogueContent.Add(msgObj);
        }
        textJsonObj.Add("dialogueMessages", jsonDialogueContent);
        if (_lastTimeStamp != DateTime.MinValue)
        {
            var stringTimeStamp = (SerializeManager.JsonDateTime)_lastTimeStamp;
            textJsonObj.Add("lastTimeStamp", stringTimeStamp.value.ToString());
        }


        jsonObject.Add("text", textJsonObj);
        return(jsonObject);
    }
Ejemplo n.º 54
0
        public static JSONNode Deserialize(System.IO.BinaryReader aReader)
        {
            JSONBinaryTag type = (JSONBinaryTag)aReader.ReadByte();
            switch (type)
            {
                case JSONBinaryTag.Array:
                    {
                        int count = aReader.ReadInt32();
                        JSONArray tmp = new JSONArray();
                        for (int i = 0; i < count; i++)
                            tmp.Add(Deserialize(aReader));
                        return tmp;
                    }
                case JSONBinaryTag.Class:
                    {
                        int count = aReader.ReadInt32();
                        JSONClass tmp = new JSONClass();
                        for (int i = 0; i < count; i++)
                        {
                            string key = aReader.ReadString();
                            var val = Deserialize(aReader);
                            tmp.Add(key, val);
                        }
                        return tmp;
                    }
                case JSONBinaryTag.Value:
                    {
                        return new JSONData(aReader.ReadString());
                    }
                case JSONBinaryTag.IntValue:
                    {
                        return new JSONData(aReader.ReadInt32());
                    }
                case JSONBinaryTag.DoubleValue:
                    {
                        return new JSONData(aReader.ReadDouble());
                    }
                case JSONBinaryTag.BoolValue:
                    {
                        return new JSONData(aReader.ReadBoolean());
                    }
                case JSONBinaryTag.FloatValue:
                    {
                        return new JSONData(aReader.ReadSingle());
                    }

                default:
                    {
                        throw new Exception("Error deserializing JSON. Unknown tag: " + type);
                    }
            }
        }
Ejemplo n.º 55
0
        // 获取匹配的 游戏服务列表
        private void Get(NetworkingPlayer player, JSONNode data)
        {
            // Pull the game id and the filters from request
            string gameId    = data["id"];
            string gameType  = data["type"];
            string gameMode  = data["mode"];
            int    playerElo = data["elo"].AsInt;

            if (_playerRequests.ContainsKey(player.Ip))
            {
                _playerRequests[player.Ip]++;
            }
            else
            {
                _playerRequests.Add(player.Ip, 1);
            }

            int delta = _playerRequests[player.Ip];

            // Get only the list that has the game ids
            List <Host> filter = (from host in hosts where host.Id == gameId select host).ToList();

            // If "any" is supplied use all the types for this game id otherwise select only matching types
            if (gameType != "any")
            {
                filter = (from host in filter where host.Type == gameType select host).ToList();
            }

            // If "all" is supplied use all the modes for this game id otherwise select only matching modes
            if (gameMode != "all")
            {
                filter = (from host in filter where host.Mode == gameMode select host).ToList();
            }

            // Prepare the data to be sent back to the client
            JSONNode  sendData    = JSONNode.Parse("{}");
            JSONArray filterHosts = new JSONArray();

            foreach (Host host in filter)
            {
                if (host.UseElo)
                {
                    if (host.PlayerCount >= host.MaxPlayers)                     //Ignore servers with max capacity
                    {
                        continue;
                    }

                    if (_eloRangeSet && (playerElo > host.Elo - (EloRange * delta) &&
                                         playerElo < host.Elo + (EloRange * delta)))
                    {
                        continue;
                    }
                }

                JSONClass hostData = new JSONClass();
                hostData.Add("name", host.Name);
                hostData.Add("address", host.Address);
                hostData.Add("port", new JSONData(host.Port));
                hostData.Add("comment", host.Comment);
                hostData.Add("type", host.Type);
                hostData.Add("mode", host.Mode);
                hostData.Add("players", new JSONData(host.PlayerCount));
                hostData.Add("maxPlayers", new JSONData(host.MaxPlayers));
                hostData.Add("protocol", host.Protocol);
                hostData.Add("elo", new JSONData(host.Elo));
                hostData.Add("useElo", new JSONData(host.UseElo));
                hostData.Add("eloDelta", new JSONData(delta));
                filterHosts.Add(hostData);
            }

            if (filterHosts.Count > 0)
            {
                _playerRequests.Remove(player.Ip);
            }

            sendData.Add("hosts", filterHosts);

            // Send the list of hosts (if any) back to the requesting client
            server.Send(player.TcpClientHandle, Text.CreateFromString(server.Time.Timestep, sendData.ToString(), false, Receivers.Target, MessageGroupIds.MASTER_SERVER_GET, true));
        }
Ejemplo n.º 56
0
    public bool Save()
    {
        try {
            /*
             * LISTS
             */

            //Just in case, I'm moving this up here
            System.Threading.Thread.CurrentThread.CurrentCulture   = CultureInfo.InvariantCulture;
            System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;

            _events       = _events.OrderBy(x => x._time).ToList();
            _notes        = _notes.OrderBy(x => x._time).ToList();
            _obstacles    = _obstacles.OrderBy(x => x._time).ToList();
            _BPMChanges   = _BPMChanges.OrderBy(x => x._time).ToList();
            _bookmarks    = _bookmarks.OrderBy(x => x._time).ToList();
            _customEvents = _customEvents.OrderBy(x => x._time).ThenBy(x => x._type).ToList();

            if (mainNode is null)
            {
                mainNode = new JSONObject();
            }

            mainNode["_version"] = _version;

            JSONArray events = new JSONArray();
            foreach (MapEvent e in _events)
            {
                events.Add(e.ConvertToJSON());
            }

            JSONArray notes = new JSONArray();
            foreach (BeatmapNote n in _notes)
            {
                notes.Add(n.ConvertToJSON());
            }

            JSONArray obstacles = new JSONArray();
            foreach (BeatmapObstacle o in _obstacles)
            {
                obstacles.Add(o.ConvertToJSON());
            }

            JSONArray bpm = new JSONArray();
            foreach (BeatmapBPMChange b in _BPMChanges)
            {
                bpm.Add(b.ConvertToJSON());
            }

            JSONArray bookmarks = new JSONArray();
            foreach (BeatmapBookmark b in _bookmarks)
            {
                bookmarks.Add(b.ConvertToJSON());
            }

            JSONArray customEvents = new JSONArray();
            foreach (BeatmapCustomEvent c in _customEvents)
            {
                customEvents.Add(c.ConvertToJSON());
            }

            mainNode["_notes"]     = notes;
            mainNode["_obstacles"] = obstacles;
            mainNode["_events"]    = events;

            /*
             * According to new the new BeatSaver schema, which will be enforced sometime soon™,
             * Bookmarks, Custom Events, and BPM Changes are now pushed to _customData instead of being on top level.
             *
             * Private MM should already has this updated, however public MM will need a PR by someone, or maybe squeaksies if he
             * wants to go against his own words and go back to that.
             *
             * Since these are editor only things, it's fine if I implement them now. Besides, CM reads both versions anyways.
             */
            mainNode["_customData"] = new JSONObject();
            if (_BPMChanges.Any())
            {
                mainNode["_customData"]["_BPMChanges"] = bpm;
            }
            if (_bookmarks.Any())
            {
                mainNode["_customData"]["_bookmarks"] = bookmarks;
            }
            if (_customEvents.Any())
            {
                mainNode["_customEvents"] = customEvents;
            }
            if (_time > 0)
            {
                mainNode["_customData"]["_time"] = Math.Round(_time, 3);
            }
            BeatSaberSong.CleanObject(mainNode["_customData"]);
            if (!mainNode["_customData"].Children.Any())
            {
                mainNode.Remove("_customData");
            }

            using (StreamWriter writer = new StreamWriter(directoryAndFile, false))
            {
                //Advanced users might want human readable JSON to perform easy modifications and reload them on the fly.
                //Thus, ChroMapper "beautifies" the JSON if you are in advanced mode.
                if (Settings.Instance.AdvancedShit)
                {
                    writer.Write(mainNode.ToString(2));
                }
                else
                {
                    writer.Write(mainNode.ToString());
                }
            }

            return(true);
        } catch (Exception e) {
            Debug.LogException(e);
            return(false);
        }
    }
Ejemplo n.º 57
0
        public void Execute(JSONNode args)
        {
            var uid = args["uid"].Value;
            var api = ApiManager.Instance;

            if (api.Agents.TryGetValue(uid, out GameObject obj))
            {
                List <SensorBase> sensors = obj.GetComponentsInChildren <SensorBase>(true).ToList();

                JSONArray result = new JSONArray();
                for (int i = 0; i < sensors.Count; i++)
                {
                    var        sensor     = sensors[i];
                    var        sensorType = sensor.GetType().GetCustomAttribute <SensorType>();
                    JSONObject j          = null;
                    switch (sensorType.Name)
                    {
                    case "Color Camera":
                        j = new JSONObject();
                        j.Add("type", "camera");
                        j.Add("name", sensor.Name);
                        j.Add("frequency", (int)sensor.GetType().GetField("Frequency").GetValue(sensor));
                        j.Add("width", (int)sensor.GetType().GetField("Width").GetValue(sensor));
                        j.Add("height", (int)sensor.GetType().GetField("Height").GetValue(sensor));
                        j.Add("fov", (float)sensor.GetType().GetField("FieldOfView").GetValue(sensor));
                        j.Add("near_plane", (float)sensor.GetType().GetField("MinDistance").GetValue(sensor));
                        j.Add("far_plane", (float)sensor.GetType().GetField("MaxDistance").GetValue(sensor));
                        j.Add("format", "RGB");
                        break;

                    case "Depth Camera":
                        j = new JSONObject();
                        j.Add("type", "camera");
                        j.Add("name", sensorType.Name);
                        j.Add("frequency", (int)sensor.GetType().GetField("Frequency").GetValue(sensor));
                        j.Add("width", (int)sensor.GetType().GetField("Width").GetValue(sensor));
                        j.Add("height", (int)sensor.GetType().GetField("Height").GetValue(sensor));
                        j.Add("fov", (float)sensor.GetType().GetField("FieldOfView").GetValue(sensor));
                        j.Add("near_plane", (float)sensor.GetType().GetField("MinDistance").GetValue(sensor));
                        j.Add("far_plane", (float)sensor.GetType().GetField("MaxDistance").GetValue(sensor));
                        j.Add("format", "DEPTH");
                        break;

                    case "Segmentation Camera":
                        j = new JSONObject();
                        j.Add("type", "camera");
                        j.Add("name", sensorType.Name);
                        j.Add("frequency", (int)sensor.GetType().GetField("Frequency").GetValue(sensor));
                        j.Add("width", (int)sensor.GetType().GetField("Width").GetValue(sensor));
                        j.Add("height", (int)sensor.GetType().GetField("Height").GetValue(sensor));
                        j.Add("fov", (float)sensor.GetType().GetField("FieldOfView").GetValue(sensor));
                        j.Add("near_plane", (float)sensor.GetType().GetField("MinDistance").GetValue(sensor));
                        j.Add("far_plane", (float)sensor.GetType().GetField("MaxDistance").GetValue(sensor));
                        j.Add("format", "SEGMENTATION");
                        break;

                    case "Lidar":
                        j = new JSONObject();
                        j.Add("type", "lidar");
                        j.Add("name", sensorType.Name);
                        j.Add("min_distance", (float)sensor.GetType().GetField("MinDistance").GetValue(sensor));
                        j.Add("max_distance", (float)sensor.GetType().GetField("MaxDistance").GetValue(sensor));
                        j.Add("rays", (int)sensor.GetType().GetField("LaserCount").GetValue(sensor));
                        j.Add("rotations", (float)sensor.GetType().GetField("RotationFrequency").GetValue(sensor));
                        j.Add("measurements", (int)sensor.GetType().GetField("MeasurementsPerRotation").GetValue(sensor));
                        j.Add("fov", (float)sensor.GetType().GetField("FieldOfView").GetValue(sensor));
                        j.Add("angle", (float)sensor.GetType().GetField("CenterAngle").GetValue(sensor));
                        j.Add("compensated", (bool)sensor.GetType().GetField("Compensated").GetValue(sensor));
                        break;

                    case "IMU":
                        j = new JSONObject();
                        j.Add("type", "imu");
                        j.Add("name", sensorType.Name);
                        break;

                    case "GPS":     // TODO: check if this sensor type name is still used, remove if not.
                    case "GPS Device":
                        j = new JSONObject();
                        j.Add("type", "gps");
                        j.Add("name", sensor.Name);
                        j.Add("frequency", (float)sensor.GetType().GetField("Frequency").GetValue(sensor));
                        break;

                    case "Radar":
                        j = new JSONObject();
                        j.Add("type", "radar");
                        j.Add("name", sensor.Name);
                        break;

                    case "CanBus":     // TODO: check if this sensor type name is still used, remove if not.
                    case "CAN-Bus":
                        j = new JSONObject();
                        j.Add("type", "canbus");
                        j.Add("name", sensor.Name);
                        j.Add("frequency", (float)sensor.GetType().GetField("Frequency").GetValue(sensor));
                        break;

                    case "Video Recording":
                        j = new JSONObject();
                        j.Add("type", "camera");
                        j.Add("name", sensor.Name);
                        j.Add("width", (int)sensor.GetType().GetField("Width").GetValue(sensor));
                        j.Add("height", (int)sensor.GetType().GetField("Height").GetValue(sensor));
                        j.Add("framerate", (int)sensor.GetType().GetField("Framerate").GetValue(sensor));
                        j.Add("fov", (float)sensor.GetType().GetField("FieldOfView").GetValue(sensor));
                        j.Add("near_plane", (float)sensor.GetType().GetField("MinDistance").GetValue(sensor));
                        j.Add("far_plane", (float)sensor.GetType().GetField("MaxDistance").GetValue(sensor));
                        j.Add("bitrate", (int)sensor.GetType().GetField("Bitrate").GetValue(sensor));
                        j.Add("max_bitrate", (int)sensor.GetType().GetField("MaxBitrate").GetValue(sensor));
                        j.Add("quality", (int)sensor.GetType().GetField("Quality").GetValue(sensor));
                        break;

                    case "Analysis":
                        j = new JSONObject();
                        j.Add("type", "analysis");
                        j.Add("name", sensor.Name);
                        j.Add("stucktravelthreshold", (float)sensor.GetType().GetField("StuckTravelThreshold").GetValue(sensor));
                        j.Add("stucktimethreshold", (float)sensor.GetType().GetField("StuckTimeThreshold").GetValue(sensor));
                        j.Add("stoplinethreshold", (float)sensor.GetType().GetField("StopLineThreshold").GetValue(sensor));
                        break;
                    }

                    if (j != null)
                    {
                        if (SimulatorManager.InstanceAvailable)
                        {
                            j.Add("uid", SimulatorManager.Instance.Sensors.GetSensorUid(sensor));
                        }
                        result.Add(j);
                    }
                }

                api.SendResult(this, result);
            }
            else
            {
                api.SendError(this, $"Agent '{uid}' not found");
            }
        }
Ejemplo n.º 58
0
    void Update()
    {
        if (dummyMessageTimer >= 0) {
            if(Mathf.Abs(dummyMessageTimer - Time.time) >= 0.3f) {
                string msgJson = "MESG{\"channel_id\": \"0\", \"message\": \"Dummy Text on Editor Mode - " + Time.time + "\", \"user\": {\"image\": \"http://url\", \"name\": \"Sender\"}, \"ts\": 1418979273365, \"scrap_id\": \"\"}";
                _OnMessageReceived(msgJson);
                dummyMessageTimer = Time.time;
            }
        }

        if (dummyChannelListFlag) {
            dummyChannelListFlag = false;
            JSONArray channels = new JSONArray();
            JSONClass channel = new JSONClass();

            channel.Add ("id", new JSONData(1));
            channel.Add ("channel_url", new JSONData("app_prefix.channel_url"));
            channel.Add ("name", new JSONData("Sample"));
            channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg"));
            channel.Add ("member_count", new JSONData(999));
            channels.Add(channel.ToString());

            channel.Add ("id", new JSONData(2));
            channel.Add ("channel_url", new JSONData("app_prefix.Unity3d"));
            channel.Add ("name", new JSONData("Unity3d"));
            channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg"));
            channel.Add ("member_count", new JSONData(999));
            channels.Add(channel.ToString());

            channel.Add ("id", new JSONData(3));
            channel.Add ("channel_url", new JSONData("app_prefix.Lobby"));
            channel.Add ("name", new JSONData("Lobby"));
            channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg"));
            channel.Add ("member_count", new JSONData(999));
            channels.Add(channel.ToString());

            channel.Add ("id", new JSONData(4));
            channel.Add ("channel_url", new JSONData("app_prefix.Cocos2d"));
            channel.Add ("name", new JSONData("Cocos2d"));
            channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg"));
            channel.Add ("member_count", new JSONData(999));
            channels.Add(channel.ToString());

            channel.Add ("id", new JSONData(5));
            channel.Add ("channel_url", new JSONData("app_prefix.GameInsight"));
            channel.Add ("name", new JSONData("GameInsight"));
            channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg"));
            channel.Add ("member_count", new JSONData(999));
            channels.Add(channel.ToString());

            channel.Add ("id", new JSONData(6));
            channel.Add ("channel_url", new JSONData("app_prefix.iOS"));
            channel.Add ("name", new JSONData("iOS"));
            channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg"));
            channel.Add ("member_count", new JSONData(999));
            channels.Add(channel.ToString());

            channel.Add ("id", new JSONData(7));
            channel.Add ("channel_url", new JSONData("app_prefix.Android"));
            channel.Add ("name", new JSONData("Android"));
            channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg"));
            channel.Add ("member_count", new JSONData(999));
            channels.Add(channel.ToString());

            channel.Add ("id", new JSONData(8));
            channel.Add ("channel_url", new JSONData("app_prefix.News"));
            channel.Add ("name", new JSONData("News"));
            channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg"));
            channel.Add ("member_count", new JSONData(999));
            channels.Add(channel.ToString());

            channel.Add ("id", new JSONData(9));
            channel.Add ("channel_url", new JSONData("app_prefix.Lobby"));
            channel.Add ("name", new JSONData("Lobby"));
            channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg"));
            channel.Add ("member_count", new JSONData(999));
            channels.Add(channel.ToString());

            channel.Add ("id", new JSONData(10));
            channel.Add ("channel_url", new JSONData("app_prefix.iPad"));
            channel.Add ("name", new JSONData("iPad"));
            channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg"));
            channel.Add ("member_count", new JSONData(999));
            channels.Add(channel.ToString());

            _OnQueryChannelList(channels.ToString());
        }
    }
        public JSONValue ExportData()
        {
            JSONObject json_data = new JSONObject();

            json_data["m_action_type"]             = (int)m_action_type;
            json_data["m_ease_type"]               = (int)m_ease_type;
            json_data["m_use_gradient_start"]      = m_use_gradient_start;
            json_data["m_use_gradient_end"]        = m_use_gradient_end;
            json_data["m_force_same_start_time"]   = m_force_same_start_time;
            json_data["m_letter_anchor_start"]     = m_letter_anchor_start;
            json_data["m_letter_anchor_end"]       = m_letter_anchor_end;
            json_data["m_letter_anchor_2_way"]     = m_letter_anchor_2_way;
            json_data["m_offset_from_last"]        = m_offset_from_last;
            json_data["m_position_axis_ease_data"] = m_position_axis_ease_data.ExportData();
            json_data["m_rotation_axis_ease_data"] = m_rotation_axis_ease_data.ExportData();
            json_data["m_scale_axis_ease_data"]    = m_scale_axis_ease_data.ExportData();

            if (m_use_gradient_start)
            {
                json_data["m_start_vertex_colour"] = m_start_vertex_colour.ExportData();
            }
            else
            {
                json_data["m_start_colour"] = m_start_colour.ExportData();
            }
            json_data["m_start_euler_rotation"] = m_start_euler_rotation.ExportData();
            json_data["m_start_pos"]            = m_start_pos.ExportData();
            json_data["m_start_scale"]          = m_start_scale.ExportData();

            if (m_use_gradient_end)
            {
                json_data["m_end_vertex_colour"] = m_end_vertex_colour.ExportData();
            }
            else
            {
                json_data["m_end_colour"] = m_end_colour.ExportData();
            }
            json_data["m_end_euler_rotation"] = m_end_euler_rotation.ExportData();
            json_data["m_end_pos"]            = m_end_pos.ExportData();
            json_data["m_end_scale"]          = m_end_scale.ExportData();

            json_data["m_delay_progression"]    = m_delay_progression.ExportData();
            json_data["m_duration_progression"] = m_duration_progression.ExportData();


            JSONArray audio_effects_data = new JSONArray();

            foreach (AudioEffectSetup effect_setup in m_audio_effects)
            {
                if (effect_setup.m_audio_clip == null)
                {
                    continue;
                }

                audio_effects_data.Add(effect_setup.ExportData());
            }
            json_data["AUDIO_EFFECTS_DATA"] = audio_effects_data;

            JSONArray particle_effects_data = new JSONArray();

            foreach (ParticleEffectSetup effect_setup in m_particle_effects)
            {
                if (effect_setup.m_legacy_particle_effect == null && effect_setup.m_shuriken_particle_effect == null)
                {
                    continue;
                }

                particle_effects_data.Add(effect_setup.ExportData());
            }
            json_data["PARTICLE_EFFECTS_DATA"] = particle_effects_data;

            return(new JSONValue(json_data));
        }
Ejemplo n.º 60
0
    public bool Save()
    {
        try {
            /*
             * LISTS
             */

            //Just in case, I'm moving this up here
            System.Threading.Thread.CurrentThread.CurrentCulture   = CultureInfo.InvariantCulture;
            System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;

            _events     = _events.OrderBy(x => x._time).ToList();
            _notes      = _notes.OrderBy(x => x._time).ToList();
            _obstacles  = _obstacles.OrderBy(x => x._time).ToList();
            _BPMChanges = _BPMChanges.OrderBy(x => x._time).ToList();
            _bookmarks  = _bookmarks.OrderBy(x => x._time).ToList();

            mainNode["_version"] = _version;

            JSONArray events = new JSONArray();
            foreach (MapEvent e in _events)
            {
                events.Add(e.ConvertToJSON());
            }

            JSONArray notes = new JSONArray();
            foreach (BeatmapNote n in _notes)
            {
                notes.Add(n.ConvertToJSON());
            }

            JSONArray obstacles = new JSONArray();
            foreach (BeatmapObstacle o in _obstacles)
            {
                obstacles.Add(o.ConvertToJSON());
            }

            JSONArray bpm = new JSONArray();
            foreach (BeatmapBPMChange b in _BPMChanges)
            {
                bpm.Add(b.ConvertToJSON());
            }

            JSONArray bookmarks = new JSONArray();
            foreach (BeatmapBookmark b in _bookmarks)
            {
                bookmarks.Add(b.ConvertToJSON());
            }

            mainNode["_notes"]      = notes;
            mainNode["_obstacles"]  = obstacles;
            mainNode["_events"]     = events;
            mainNode["_BPMChanges"] = bpm;
            mainNode["_bookmarks"]  = bookmarks;

            using (StreamWriter writer = new StreamWriter(directoryAndFile, false))
                writer.Write(mainNode.ToString());

            return(true);
        } catch (Exception e) {
            Debug.LogException(e);
            return(false);
        }
    }