Exemplo n.º 1
0
        public virtual void WriteEDATA(JSONNode inNode)
        {
            int currentVersion = Genie.TELEMETRY_VERSION;

            JSONNode eks = inNode["eks"] = new JSONClass();
            JSONNode ext = inNode["ext"] = new JSONClass();

            var fields = GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

            foreach (var f in fields)
            {
                JSONNode target = null;

                if (Attribute.IsDefined(f, typeof(EKSAttribute)))
                {
                    target = eks;
                }
                else if (Attribute.IsDefined(f, typeof(EXTAttribute)))
                {
                    target = ext;
                }
                else
                {
                    continue;
                }

                object value = f.GetValue(this);
                string name  = f.Name;

                bool bWriteOut = value != null;
                if (bWriteOut)
                {
                    RemovedInVersionAttribute[] removedVersions = TypeHelper.GetCustomAttributes <RemovedInVersionAttribute>(f);
                    foreach (var removedAttribute in removedVersions)
                    {
                        if (currentVersion >= removedAttribute.VersionRemoved && currentVersion < removedAttribute.VersionReinstated)
                        {
                            bWriteOut = false;
                            break;
                        }
                    }
                }
                if (bWriteOut)
                {
                    RenamedInVersionAttribute[] renamedVersions = TypeHelper.GetCustomAttributes <RenamedInVersionAttribute>(f);
                    int minProcessed = 0;
                    foreach (var renameAttribute in renamedVersions)
                    {
                        if (minProcessed < renameAttribute.Version)
                        {
                            minProcessed = renameAttribute.Version;
                            if (currentVersion >= renameAttribute.Version)
                            {
                                name = renameAttribute.Name;
                            }
                        }
                    }

                    target.Add(name, JSONUtils.Parse(value));
                }
            }
        }
Exemplo n.º 2
0
        // We have to lock api.ActionsSemaphore before the first continuation (await)
        // to make sure API calls are executed one after the other
        public async void Execute(JSONNode args)
        {
            var sim = SimulatorManager.Instance;
            var api = ApiManager.Instance;

            // instead of relying on ApiMAnager's exception handling,
            // we wrap the whole method since we are async
            try
            {
                if (sim == null)
                {
                    throw new Exception("SimulatorManager not found! Is scene loaded?");
                }

                var name             = args["name"].Value;
                var type             = args["type"].AsInt;
                var position         = args["state"]["transform"]["position"].ReadVector3();
                var rotation         = args["state"]["transform"]["rotation"].ReadVector3();
                var velocity         = args["state"]["velocity"].ReadVector3();
                var angular_velocity = args["state"]["angular_velocity"].ReadVector3();

                string uid;
                var    argsUid = args["uid"];
                if (argsUid == null)
                {
                    uid = System.Guid.NewGuid().ToString();
                    // Add uid key to arguments, as it will be distributed to the clients' simulations
                    if (Loader.Instance.Network.IsMaster)
                    {
                        args.Add("uid", uid);
                    }
                }
                else
                {
                    uid = argsUid.Value;
                }

                if (type == (int)AgentType.Ego)
                {
                    var        agents  = SimulatorManager.Instance.AgentManager;
                    GameObject agentGO = null;

                    VehicleDetailData vehicleData = await ConnectionManager.API.GetByIdOrName <VehicleDetailData>(name);

                    var config = new AgentConfig(vehicleData.ToVehicleData());

                    if (ApiManager.Instance.CachedVehicles.ContainsKey(vehicleData.Name))
                    {
                        config.Prefab = ApiManager.Instance.CachedVehicles[vehicleData.Name];
                    }
                    else
                    {
                        var progressUpdate = new Progress <Tuple <string, float> > (p => { ConnectionUI.instance.UpdateDownloadProgress(p.Item1, p.Item2); });
                        var assetModel     = await DownloadManager.GetAsset(BundleConfig.BundleTypes.Vehicle, vehicleData.AssetGuid, vehicleData.Name, progressUpdate);

                        config.Prefab = Loader.LoadVehicleBundle(assetModel.LocalPath);
                    }

                    if (config.Prefab == null)
                    {
                        throw new Exception($"failed to acquire ego prefab");
                    }

                    var downloads = new List <Task>();
                    List <SensorData> sensorsToDownload = new List <SensorData>();
                    ConcurrentDictionary <Task, string> assetDownloads = new ConcurrentDictionary <Task, string>();

                    if (config.Sensors != null)
                    {
                        foreach (var plugin in config.Sensors)
                        {
                            if (plugin.Plugin.AssetGuid != null && sensorsToDownload.FirstOrDefault(s => s.Plugin.AssetGuid == plugin.Plugin.AssetGuid) == null)
                            {
                                sensorsToDownload.Add(plugin);
                            }
                        }
                    }

                    foreach (var sensor in sensorsToDownload)
                    {
                        var pluginProgress = ConnectionUI.instance != null ?
                                             new Progress <Tuple <string, float> >(p => ConnectionUI.instance.UpdateDownloadProgress(p.Item1, p.Item2))
                        : new Progress <Tuple <string, float> >(p => Debug.Log($"Download: {p.Item1}: {p.Item2}"));

                        var pluginTask = DownloadManager.GetAsset(BundleConfig.BundleTypes.Sensor, sensor.Plugin.AssetGuid,
                                                                  sensor.Name, pluginProgress);
                        downloads.Add(pluginTask);
                        assetDownloads.TryAdd(pluginTask, sensor.Type);
                    }

                    await Task.WhenAll(downloads);

                    foreach (var download in downloads)
                    {
                        assetDownloads.TryRemove(download, out _);
                    }

                    agentGO = agents.SpawnAgent(config);
                    agentGO.transform.position = position;
                    agentGO.transform.rotation = Quaternion.Euler(rotation);

                    if (agents.ActiveAgents.Count == 1)
                    {
                        agents.SetCurrentActiveAgent(agentGO);
                    }

                    var rb = agentGO.GetComponent <Rigidbody>();
                    if (rb != null)
                    {
                        rb.velocity        = velocity;
                        rb.angularVelocity = angular_velocity;
                    }

                    Debug.Assert(agentGO != null);
                    api.Agents.Add(uid, agentGO);
                    api.AgentUID.Add(agentGO, uid);

                    var sensors = agentGO.GetComponentsInChildren <SensorBase>(true);

                    foreach (var sensor in sensors)
                    {
                        var sensorUid = System.Guid.NewGuid().ToString();
                        if (SimulatorManager.InstanceAvailable)
                        {
                            SimulatorManager.Instance.Sensors.AppendUid(sensor, sensorUid);
                        }
                    }

                    api.SendResult(this, new JSONString(uid));
                }
                else if (type == (int)AgentType.Npc)
                {
                    var colorData = args["color"].ReadVector3();
                    var template  = sim.NPCManager.NPCVehicles.Find(obj => obj.Prefab.name == name);
                    if (template.Prefab == null)
                    {
                        throw new Exception($"Unknown '{name}' NPC name");
                    }

                    var spawnData = new NPCManager.NPCSpawnData
                    {
                        Active   = true,
                        GenId    = uid,
                        Template = template,
                        Position = position,
                        Rotation = Quaternion.Euler(rotation),
                        Color    = colorData == new Vector3(-1, -1, -1) ? sim.NPCManager.GetWeightedRandomColor(template.NPCType) : new Color(colorData.x, colorData.y, colorData.z),
                        Seed     = sim.NPCManager.NPCSeedGenerator.Next(),
                    };

                    var npcController = SimulatorManager.Instance.NPCManager.SpawnNPC(spawnData);
                    npcController.IsUserSpecified = true;
                    npcController.SetBehaviour <NPCManualBehaviour>();

                    var body = npcController.GetComponent <Rigidbody>();
                    body.velocity        = velocity;
                    body.angularVelocity = angular_velocity;

                    uid = npcController.name;
                    api.Agents.Add(uid, npcController.gameObject);
                    api.AgentUID.Add(npcController.gameObject, uid);
                    api.SendResult(this, new JSONString(uid));

                    // Override the color argument as NPCController may change the NPC color
                    if (Loader.Instance.Network.IsMaster)
                    {
                        var colorVector = new Vector3(npcController.NPCColor.r, npcController.NPCColor.g, npcController.NPCColor.b);
                        args["color"].WriteVector3(colorVector);
                    }
                }
                else if (type == (int)AgentType.Pedestrian)
                {
                    var pedManager = SimulatorManager.Instance.PedestrianManager;
                    if (!pedManager.gameObject.activeSelf)
                    {
                        var sceneName = SceneManager.GetActiveScene().name;
                        throw new Exception($"{sceneName} is missing Pedestrian NavMesh");
                    }

                    var model = sim.PedestrianManager.PedestrianData.Find(obj => obj.Name == name).Prefab;
                    if (model == null)
                    {
                        throw new Exception($"Unknown '{name}' pedestrian name");
                    }

                    var spawnData = new PedestrianManager.PedSpawnData
                    {
                        Active   = true,
                        API      = true,
                        GenId    = uid,
                        Model    = model,
                        Position = position,
                        Rotation = Quaternion.Euler(rotation),
                        Seed     = sim.PedestrianManager.PEDSeedGenerator.Next(),
                    };

                    var pedController = pedManager.SpawnPedestrian(spawnData);
                    if (pedController == null)
                    {
                        throw new Exception($"Pedestrian controller error for '{name}'");
                    }

                    api.Agents.Add(uid, pedController.gameObject);
                    api.AgentUID.Add(pedController.gameObject, uid);
                    api.SendResult(this, new JSONString(uid));
                }
                else
                {
                    throw new Exception($"Unsupported '{args["type"]}' type");
                }
            }
            catch (Exception e)
            {
                api.SendError(this, e.Message);
            }
            finally
            {
                Executed?.Invoke(this);
            }
        }
Exemplo n.º 3
0
        public void MatchmakingServersFromMasterServer(string masterServerHost,
                                                       ushort masterServerPort,
                                                       int elo,
                                                       System.Action <MasterServerResponse> callback = null,
                                                       string gameId   = "myGame",
                                                       string gameType = "any",
                                                       string gameMode = "all")
        {
            // The Master Server communicates over TCP
            TCPMasterClient client = new TCPMasterClient();

            // Once this client has been accepted by the master server it should send it's get request
            client.serverAccepted += (sender) =>
            {
                try
                {
                    // Create the get request with the desired filters
                    JSONNode  sendData = JSONNode.Parse("{}");
                    JSONClass getData  = new JSONClass();
                    getData.Add("id", gameId);
                    getData.Add("type", gameType);
                    getData.Add("mode", gameMode);
                    getData.Add("elo", new JSONData(elo));

                    sendData.Add("get", getData);

                    // Send the request to the server
                    client.Send(Text.CreateFromString(client.Time.Timestep, sendData.ToString(), true, Receivers.Server, MessageGroupIds.MASTER_SERVER_GET, true));
                }
                catch
                {
                    // If anything fails, then this client needs to be disconnected
                    client.Disconnect(true);
                    client = null;

                    MainThreadManager.Run(() =>
                    {
                        if (callback != null)
                        {
                            callback(null);
                        }
                    });
                }
            };

            // An event that is raised when the server responds with hosts
            client.textMessageReceived += (player, frame, sender) =>
            {
                try
                {
                    // Get the list of hosts to iterate through from the frame payload
                    JSONNode data = JSONNode.Parse(frame.ToString());
                    MainThreadManager.Run(() =>
                    {
                        if (data["hosts"] != null)
                        {
                            MasterServerResponse response = new MasterServerResponse(data["hosts"].AsArray);
                            if (callback != null)
                            {
                                callback(response);
                            }
                        }
                        else
                        {
                            if (callback != null)
                            {
                                callback(null);
                            }
                        }
                    });
                }
                finally
                {
                    if (client != null)
                    {
                        // If we succeed or fail the client needs to disconnect from the Master Server
                        client.Disconnect(true);
                        client = null;
                    }
                }
            };

            try
            {
                client.Connect(masterServerHost, masterServerPort);
            }
            catch (System.Exception ex)
            {
                Debug.LogError(ex.Message);
                MainThreadManager.Run(() =>
                {
                    if (callback != null)
                    {
                        callback(null);
                    }
                });
            }
        }
Exemplo n.º 4
0
        private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (copyTarget == null)
            {
                return;
            }
            Panel target;

            if (nowSelectedNode == null)
            {
                target = (Panel)MainPanel.Controls[2];
            }
            else
            {
                JSONNode tmpnode = (JSONNode)nowSelectedNode.Tag;
                if (tmpnode is JSONObject || tmpnode is JSONArray)
                {
                    target = (Panel)nowSelectedNode.Controls[nowSelectedNode.Controls.Count - 1];
                }
                else
                {
                    MessageBox.Show("선택된 대상은 오브젝트나 배열이 아닙니다");
                    return;
                }
            }
            JSONNode node = (JSONNode)target.Tag;

            if (copyTarget.type != JSONType.Array && copyTarget.type != JSONType.Object)
            {
                JSONNode copied      = copyTarget.CloneNode();
                TreeNode t           = JSONFormUtil.FindTreeNode(tview_object.TopNode, node);
                string   key         = node.Add(copied);
                TreeNode newTreenode = new TreeNode();
                newTreenode.Tag  = copyTarget;
                newTreenode.Text = copyTarget.type.GetTypeString();
                t.Nodes.Add(newTreenode);

                CreateGroupChild(copied, key, target, target.Height, node.type == JSONType.Object ? true : false);

                PanelReSort(target);
            }
            else
            {
                if (JSONParseThread.Parsing)
                {
                    MessageBox.Show("다른 파싱이 진행중입니다");
                    return;
                }
                string parseString = copyTarget.Stringify();
                JSON.Parse((n) =>
                {
                    JSONNode copied      = n;
                    TreeNode t           = JSONFormUtil.FindTreeNode(tview_object.TopNode, node);
                    string key           = node.Add(copied);
                    TreeNode newTreenode = JSONFormUtil.TreeNodeMake(copied);
                    t.Nodes.Add(newTreenode);

                    CreateGroupChild(copied, key, target, target.Height, node.type == JSONType.Object ? true : false);

                    PanelReSort(target);
                    return(n);
                }, JSONExceptionCatch, parseString);
            }
        }
Exemplo n.º 5
0
 public override void SerializeProperties(JSONNode jsonData)
 {
     jsonData.Add("value", new JSONNumber(Value));
 }
Exemplo n.º 6
0
        public void Refresh()
        {
            // Clear out all the currently listed servers
            for (int i = content.childCount - 1; i >= 0; --i)
            {
                Destroy(content.GetChild(i).gameObject);
            }

            // The Master Server communicates over TCP
            client = new TCPMasterClient();

            // Once this client has been accepted by the master server it should sent it's get request
            client.serverAccepted += () =>
            {
                try
                {
                    // Create the get request with the desired filters
                    JSONNode  sendData = JSONNode.Parse("{}");
                    JSONClass getData  = new JSONClass();
                    getData.Add("id", gameId);
                    getData.Add("type", gameType);
                    getData.Add("mode", gameMode);

                    sendData.Add("get", getData);

                    // Send the request to the server
                    client.Send(Frame.Text.CreateFromString(client.Time.Timestep, sendData.ToString(), true, Receivers.Server, MessageGroupIds.MASTER_SERVER_GET, true));
                }
                catch
                {
                    // If anything fails, then this client needs to be disconnected
                    client.Disconnect(true);
                    client = null;
                }
            };

            // An event that is raised when the server responds with hosts
            client.textMessageReceived += (player, frame) =>
            {
                try
                {
                    // Get the list of hosts to iterate through from the frame payload
                    JSONNode data = JSONNode.Parse(frame.ToString());
                    if (data["hosts"] != null)
                    {
                        MasterServerResponse response = new MasterServerResponse(data["hosts"].AsArray);

                        if (response != null && response.serverResponse.Count > 0)
                        {
                            // Go through all of the available hosts and add them to the server browser
                            foreach (MasterServerResponse.Server server in response.serverResponse)
                            {
                                string protocol = server.Protocol;
                                string address  = server.Address;
                                ushort port     = server.Port;
                                string name     = server.Name;
                                // name, address, port, comment, type, mode, players, maxPlayers, protocol
                                CreateServerOption(name, () =>
                                {
                                    // Determine which protocol should be used when this client connects
                                    NetWorker socket = null;

                                    if (protocol == "udp")
                                    {
                                        // TODO:  Add NAT hole punching server
                                        socket = new UDPClient();
                                        ((UDPClient)socket).Connect(address, port);
                                    }
                                    else if (protocol == "tcp")
                                    {
                                        socket = new TCPClient();
                                        ((TCPClient)socket).Connect(address, port);
                                    }
                                    else if (protocol == "web")
                                    {
                                        socket = new TCPClientWebsockets();
                                        ((TCPClientWebsockets)socket).Connect(address, port);
                                    }

                                    if (socket == null)
                                    {
                                        throw new Exception("No socket of type " + protocol + " could be established");
                                    }

                                    Connected(socket);
                                });
                            }
                        }
                    }
                }
                finally
                {
                    if (client != null)
                    {
                        // If we succeed or fail the client needs to disconnect from the Master Server
                        client.Disconnect(true);
                        client = null;
                    }
                }
            };

            client.Connect(masterServerHost, (ushort)masterServerPort);
        }
Exemplo n.º 7
0
        public void Execute(JSONNode args)
        {
            var sim = Object.FindObjectOfType <SimulatorManager>();
            var api = ApiManager.Instance;

            if (sim == null)
            {
                api.SendError(this, "SimulatorManager not found! Is scene loaded?");
                return;
            }

            var name             = args["name"].Value;
            var type             = args["type"].AsInt;
            var position         = args["state"]["transform"]["position"].ReadVector3();
            var rotation         = args["state"]["transform"]["rotation"].ReadVector3();
            var velocity         = args["state"]["velocity"].ReadVector3();
            var angular_velocity = args["state"]["angular_velocity"].ReadVector3();

            string uid;
            var    argsUid = args["uid"];

            if (argsUid == null)
            {
                uid = System.Guid.NewGuid().ToString();
                // Add uid key to arguments, as it will be distributed to the clients' simulations
                if (Loader.Instance.Network.IsMaster)
                {
                    args.Add("uid", uid);
                }
            }
            else
            {
                uid = argsUid.Value;
            }

            if (type == (int)AgentType.Ego)
            {
                var        agents  = SimulatorManager.Instance.AgentManager;
                GameObject agentGO = null;

                using (var db = DatabaseManager.Open())
                {
                    var sql     = Sql.Builder.From("vehicles").Where("name = @0", name);
                    var vehicle = db.FirstOrDefault <VehicleModel>(sql);
                    if (vehicle == null)
                    {
                        var url = args["url"];
                        //Disable using url on master simulation
                        if (Loader.Instance.Network.IsMaster || string.IsNullOrEmpty(url))
                        {
                            api.SendError(this, $"Vehicle '{name}' is not available");
                            return;
                        }

                        DownloadVehicleFromUrl(args, name, url);
                        return;
                    }
                    else
                    {
                        var prefab = AquirePrefab(vehicle);
                        if (prefab == null)
                        {
                            return;
                        }

                        var config = new AgentConfig()
                        {
                            Name    = vehicle.Name,
                            Prefab  = prefab,
                            Sensors = vehicle.Sensors,
                        };

                        if (!string.IsNullOrEmpty(vehicle.BridgeType))
                        {
                            config.Bridge = Web.Config.Bridges.Find(bridge => bridge.Name == vehicle.BridgeType);
                            if (config.Bridge == null)
                            {
                                api.SendError(this, $"Bridge '{vehicle.BridgeType}' not available");
                                return;
                            }
                        }

                        agentGO = agents.SpawnAgent(config);
                        agentGO.transform.position = position;
                        agentGO.transform.rotation = Quaternion.Euler(rotation);

                        if (agents.ActiveAgents.Count == 1)
                        {
                            agents.SetCurrentActiveAgent(agentGO);
                        }

                        var rb = agentGO.GetComponent <Rigidbody>();
                        rb.velocity        = velocity;
                        rb.angularVelocity = angular_velocity;
                        // Add url key to arguments, as it will be distributed to the clients' simulations
                        if (Loader.Instance.Network.IsMaster)
                        {
                            args.Add("url", vehicle.Url);
                        }
                    }
                }

                Debug.Assert(agentGO != null);
                api.Agents.Add(uid, agentGO);
                api.AgentUID.Add(agentGO, uid);

                var sensors = agentGO.GetComponentsInChildren <SensorBase>(true);

                foreach (var sensor in sensors)
                {
                    var sensorUid = System.Guid.NewGuid().ToString();
                    if (SimulatorManager.InstanceAvailable)
                    {
                        SimulatorManager.Instance.Sensors.AppendUid(sensor, sensorUid);
                    }
                }

                api.SendResult(this, new JSONString(uid));
                SIM.LogAPI(SIM.API.AddAgentEgo, name);
            }
            else if (type == (int)AgentType.Npc)
            {
                var colorData = args["color"].ReadVector3();
                var color     = new Color();
                if (colorData != new Vector3(-1, -1, -1))
                {
                    color = new Color(colorData.x, colorData.y, colorData.z);
                }
                var go = SimulatorManager.Instance.NPCManager.SpawnVehicle(name, uid, position, Quaternion.Euler(rotation), color);

                var npc = go.GetComponent <NPCController>();
                npc.Control = NPCController.ControlType.Manual;

                var body = go.GetComponent <Rigidbody>();
                body.velocity        = velocity;
                body.angularVelocity = angular_velocity;

                uid = go.name;
                api.Agents.Add(uid, go);
                api.AgentUID.Add(go, uid);
                api.SendResult(this, new JSONString(go.name));
                SIM.LogAPI(SIM.API.AddAgentNPC, name);
                // Override the color argument as NPCController may change the NPC color
                if (Loader.Instance.Network.IsMaster)
                {
                    var colorVector = new Vector3(npc.NPCColor.r, npc.NPCColor.g, npc.NPCColor.b);
                    args["color"].WriteVector3(colorVector);
                }
            }
            else if (type == (int)AgentType.Pedestrian)
            {
                var pedManager = SimulatorManager.Instance.PedestrianManager;
                if (!pedManager.gameObject.activeSelf)
                {
                    var sceneName = SceneManager.GetActiveScene().name;
                    api.SendError(this, $"{sceneName} is missing Pedestrian NavMesh");
                    return;
                }
                var ped = pedManager.SpawnPedestrianApi(name, uid, position, Quaternion.Euler(rotation));
                if (ped == null)
                {
                    api.SendError(this, $"Unknown '{name}' pedestrian name");
                    return;
                }

                api.Agents.Add(uid, ped);
                api.AgentUID.Add(ped, uid);

                api.SendResult(this, new JSONString(uid));
                SIM.LogAPI(SIM.API.AddAgentPedestrian, name);
            }
            else
            {
                api.SendError(this, $"Unsupported '{args["type"]}' type");
            }
        }
 /// <inheritdoc/>
 public override void SerializeToJson(JSONNode agentNode)
 {
     agentNode.Add("sensorsConfigurationId", new JSONString(SensorsConfigurationId));
 }
Exemplo n.º 9
0
            static void AddElement(JSONNode ctx, string token, string tokenName, bool tokenIsString)
            {
                if (tokenIsString)
                {
                    if (ctx is JSONArray)
                        ctx.Add(token);
                    else
                        ctx.Add(tokenName, token); // assume dictionary/object
                }
                else
                {
                    JSONData number = Numberize(token);
                    if (ctx is JSONArray)
                        ctx.Add(number);
                    else
                        ctx.Add(tokenName, number);

                }
            }
Exemplo n.º 10
0
    private JSONNode CreateStatement(string trace)
    {
        string[] parts     = trace.Split(',');
        string   timestamp = new System.DateTime(1970, 1, 1, 0, 0, 0, System.DateTimeKind.Utc).AddMilliseconds(long.Parse(parts [0])).ToString("yyyy-MM-ddTHH:mm:ss.fffZ");

        JSONNode statement = JSONNode.Parse("{\"timestamp\": \"" + timestamp + "\"}");

        if (actor != null)
        {
            statement.Add("actor", actor);
        }
        statement.Add("verb", CreateVerb(parts [1]));


        statement.Add("object", CreateObject(parts));

        if (parts.Length > 4)
        {
            // Parse extensions

            int extCount = parts.Length - 4;
            if (extCount > 0 && extCount % 2 == 0)
            {
                // Extensions come in <key, value> pairs

                JSONClass extensions      = new JSONClass();
                JSONNode  extensionsChild = null;

                for (int i = 4; i < parts.Length; i += 2)
                {
                    string key   = parts[i];
                    string value = parts[i + 1];
                    if (key.Equals("") || value.Equals(""))
                    {
                        continue;
                    }
                    if (key.Equals(Tracker.Extension.Score.ToString().ToLower()))
                    {
                        JSONClass score       = new JSONClass();
                        float     valueResult = 0f;
                        float.TryParse(value, out valueResult);
                        score.Add("raw", new JSONData(valueResult));
                        extensions.Add("score", score);
                    }
                    else if (key.Equals(Tracker.Extension.Success.ToString().ToLower()))
                    {
                        bool valueResult = false;
                        bool.TryParse(value, out valueResult);
                        extensions.Add("success", new JSONData(valueResult));
                    }
                    else if (key.Equals(Tracker.Extension.Completion.ToString().ToLower()))
                    {
                        bool valueResult = false;
                        bool.TryParse(value, out valueResult);
                        extensions.Add("completion", new JSONData(valueResult));
                    }
                    else if (key.Equals(Tracker.Extension.Response.ToString().ToLower()))
                    {
                        extensions.Add("response", new JSONData(value));
                    }
                    else
                    {
                        if (extensionsChild == null)
                        {
                            extensionsChild = JSONNode.Parse("{}");
                            extensions.Add("extensions", extensionsChild);
                        }

                        string id = key;
                        bool   tbool;
                        int    tint;
                        float  tfloat;
                        double tdouble;

                        if (extensionIds.ContainsKey(key))
                        {
                            id = extensionIds[key];
                        }

                        if (int.TryParse(value, out tint))
                        {
                            extensionsChild.Add(id, new JSONData(tint));
                        }
                        else if (float.TryParse(value, out tfloat))
                        {
                            extensionsChild.Add(id, new JSONData(tfloat));
                        }
                        else if (double.TryParse(value, out tdouble))
                        {
                            extensionsChild.Add(id, new JSONData(tdouble));
                        }
                        else if (bool.TryParse(value, out tbool))
                        {
                            extensionsChild.Add(id, new JSONData(tbool));
                        }
                        else
                        {
                            extensionsChild.Add(id, new JSONData(value));
                        }
                    }
                }
                statement.Add("result", extensions);
            }
        }

        return(statement);
    }
Exemplo n.º 11
0
    public static void SetQuestionWasAnswered(string shieldNum, string key)
    {
        string values = PlayerPrefs.GetString("opened_questions");

        if (values != null && values.Length > 0)
        {
            var jsonStr = JSON.Parse(values);

            var listNode = jsonStr [key].AsArray;

            if (listNode != null)
            {
                foreach (JSONData i in listNode)
                {
                    if (i.Value == shieldNum)
                    {
                        return;
                    }
                }

                JSONNode jnod = new JSONNode();
                jnod.Add(shieldNum);

                listNode.Add(shieldNum);

                jsonStr [key] = listNode;
            }
            else
            {
                JSONArray listNode1 = new JSONArray();

                JSONNode jnod1 = new JSONNode();
                jnod1.Add(shieldNum);

                listNode1.Add(shieldNum);

                jsonStr.Add(key, listNode1);
            }



            //UserController.currentUser.Motto = jsonStr.ToString();
            //profile.SaveUser ();
            PlayerPrefs.SetString("opened_questions", jsonStr.ToString());

            return;
        }
        else
        {
            JSONArray listNode = new JSONArray();

            JSONNode jnod = new JSONNode();
            jnod.Add(shieldNum);

            listNode.Add(shieldNum);


            JSONClass rootNode = new JSONClass();
            rootNode.Add(key, listNode);

            //UserController.currentUser.Motto = rootNode.ToString();

            //profile.SaveUser ();
            PlayerPrefs.SetString("opened_questions", rootNode.ToString());

            return;
        }
    }
Exemplo n.º 12
0
        private JSONNode CreateStatement(string trace)
        {
            string[] parts     = Utils.parseCSV(trace);
            string   timestamp = new System.DateTime(1970, 1, 1, 0, 0, 0, System.DateTimeKind.Utc).AddMilliseconds(long.Parse(parts[0])).ToString("yyyy-MM-ddTHH:mm:ss.fffZ");

            JSONNode statement = JSONNode.Parse("{\"timestamp\": \"" + timestamp + "\"}");

            if (actor != null)
            {
                statement.Add("actor", actor);
            }
            statement.Add("verb", CreateVerb(parts[1]));


            statement.Add("object", CreateObject(parts));

            if (parts.Length > 4)
            {
                // Parse extensions

                int extCount = parts.Length - 4;
                if (extCount > 0 && extCount % 2 == 0)
                {
                    // Extensions come in <key, value> pairs

                    JSONClass extensions      = new JSONClass();
                    JSONNode  extensionsChild = null;

                    for (int i = 4; i < parts.Length; i += 2)
                    {
                        string key   = parts[i];
                        string value = parts[i + 1];
                        if (key.Equals("") || value.Equals(""))
                        {
                            continue;
                        }
                        if (key.Equals(Tracker.Extension.Score.ToString().ToLower()))
                        {
                            JSONClass score       = new JSONClass();
                            float     valueResult = 0f;

                            string msg = "Tracker-xAPI: Score isn't a number, ignoring.", smsg = "Tracker-xAPI: Score isn't a number.";
                            if (Utils.check <ExtensionXApiException> (value, msg, smsg) &&
                                Utils.isFloat <ExtensionXApiException>(value, msg, smsg, out valueResult))
                            {
                                score.Add("raw", new JSONData(valueResult));
                                extensions.Add("score", score);
                            }
                        }
                        else if (key.Equals(Tracker.Extension.Success.ToString().ToLower()))
                        {
                            bool   valueResult = false;
                            string msg = "Tracker-xAPI: Success isn't a bool value, ignoring.", smsg = "Tracker-xAPI: Success isn't a bool value.";
                            if (Utils.check <ExtensionXApiException> (value, msg, smsg) &&
                                Utils.isBool <ExtensionXApiException> (value, msg, smsg, out valueResult))
                            {
                                extensions.Add("success", new JSONData(valueResult));
                            }
                        }
                        else if (key.Equals(Tracker.Extension.Completion.ToString().ToLower()))
                        {
                            bool   valueResult = false;
                            string msg = "Tracker-xAPI: Completion isn't a bool value, ignoring.", smsg = "Tracker-xAPI: Completion isn't a bool value.";
                            if (Utils.check <ExtensionXApiException> (value, msg, smsg) &&
                                Utils.isBool <ExtensionXApiException> (value, msg, smsg, out valueResult))
                            {
                                extensions.Add("completion", new JSONData(valueResult));
                            }
                        }
                        else if (key.Equals(Tracker.Extension.Response.ToString().ToLower()))
                        {
                            extensions.Add("response", new JSONData(value));
                        }
                        else
                        {
                            if (extensionsChild == null)
                            {
                                extensionsChild = JSONNode.Parse("{}");
                                extensions.Add("extensions", extensionsChild);
                            }

                            string id = key;
                            bool   tbool;
                            int    tint;
                            float  tfloat;
                            double tdouble;

                            if (extensionIds.ContainsKey(key))
                            {
                                id = extensionIds [key];
                            }

                            if (int.TryParse(value, System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.InvariantCulture, out tint))
                            {
                                extensionsChild.Add(id, new JSONData(tint));
                            }
                            else if (float.TryParse(value, System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.InvariantCulture, out tfloat))
                            {
                                extensionsChild.Add(id, new JSONData(tfloat));
                            }
                            else if (double.TryParse(value, System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.InvariantCulture, out tdouble))
                            {
                                extensionsChild.Add(id, new JSONData(tdouble));
                            }
                            else if (bool.TryParse(value, out tbool))
                            {
                                extensionsChild.Add(id, new JSONData(tbool));
                            }
                            else
                            {
                                extensionsChild.Add(id, new JSONData(value));
                            }
                        }
                    }
                    statement.Add("result", extensions);
                }
            }

            return(statement);
        }
Exemplo n.º 13
0
        static JSONNode ToJson(List <JsonField> field, ref int index, JSONNode node)
        {
            if (index >= field.Count)
            {
                return(null);
            }

            JSONNode result = null;

            if (field[index].jsonType == JSON_TYPE.JSON_START)
            {
                JSONClass json = new JSONClass();

                if (node != null)
                {
                    if (!string.IsNullOrEmpty(field[index].value))
                    {
                        node.Add(field[index].value, json);
                    }
                    else
                    {
                        node.Add(json);
                    }
                }
                do
                {
                    index++;
                    result = ToJson(field, ref index, json);
                }while(result != null);

                return(json);
            }
            else if (field[index].jsonType == JSON_TYPE.JSON_ARRAY_START || field[index].jsonType == JSON_TYPE.JSON_TABLE_START)
            {
                JSONArray array = new JSONArray();

                if (!string.IsNullOrEmpty(field[index].value))
                {
                    node.Add(field[index].value, array);
                }
                else
                {
                    node.Add(array);
                }

                do
                {
                    index++;
                    result = ToJson(field, ref index, array);
                }while(result != null);

                return(array);
            }
            else if (field[index].jsonType == JSON_TYPE.JSON_VALUE)
            {
                node.Add(field[index].fieldName, field[index].value);
                return(node);
            }
            else if (field[index].jsonType == JSON_TYPE.JSON_END || field[index].jsonType == JSON_TYPE.JSON_ARRAY_END ||
                     field[index].jsonType == JSON_TYPE.JSON_TABLE_END)
            {
                return(null);
            }

            return(null);
        }
        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));
        }
Exemplo n.º 15
0
    public void Refresh()
    {
        ClearServers();

        if (lan)
        {
            NetWorker.RefreshLocalUdpListings(ushort.Parse(portNumber.text));
            return;
        }

        // The Master Server communicates over TCP
        TCPMasterClient client = new TCPMasterClient();

        // Once this client has been accepted by the master server it should sent it's get request
        client.serverAccepted += x =>
        {
            try
            {
                // The overall game id to select from
                string gameId = "myGame";

                // The game type to choose from, if "any" then all types will be returned
                string gameType = "any";

                // The game mode to choose from, if "all" then all game modes will be returned
                string gameMode = "all";

                // Create the get request with the desired filters
                JSONNode  sendData = JSONNode.Parse("{}");
                JSONClass getData  = new JSONClass();

                // The id of the game to get
                getData.Add("id", gameId);
                getData.Add("type", gameType);
                getData.Add("mode", gameMode);

                sendData.Add("get", getData);

                // Send the request to the server
                client.Send(BeardedManStudios.Forge.Networking.Frame.Text.CreateFromString(client.Time.Timestep, sendData.ToString(), true, Receivers.Server, MessageGroupIds.MASTER_SERVER_GET, true));
            }
            catch
            {
                // If anything fails, then this client needs to be disconnected
                client.Disconnect(true);
                client = null;
            }
        };

        // An event that is raised when the server responds with hosts
        client.textMessageReceived += (player, frame, sender) =>
        {
            try
            {
                // Get the list of hosts to iterate through from the frame payload
                JSONNode data = JSONNode.Parse(frame.ToString());
                if (data["hosts"] != null)
                {
                    // Create a C# object for the response from the master server
                    MasterServerResponse response = new MasterServerResponse(data["hosts"].AsArray);

                    if (response != null && response.serverResponse.Count > 0)
                    {
                        // Go through all of the available hosts and add them to the server browser
                        foreach (MasterServerResponse.Server server in response.serverResponse)
                        {
                            Debug.Log("Found server " + server.Name);

                            // Update UI

                            MainThreadManager.Run(() =>
                            {
                                AddServer(server.Name, server.Address, server.PlayerCount, server.Mode);
                            });
                        }
                    }
                }
            }
            finally
            {
                if (client != null)
                {
                    // If we succeed or fail the client needs to disconnect from the Master Server
                    client.Disconnect(true);
                    client = null;
                }
            }
        };

        client.Connect(masterServerHost, (ushort)masterServerPort);
    }
Exemplo n.º 16
0
 /// <inheritdoc/>
 public void SerializeToJson(JSONNode elementNode)
 {
     elementNode.Add("sensorsConfigurationId", new JSONString(SensorsConfigurationId));
 }
Exemplo n.º 17
0
    public static JSONNode Parse(string aJSON)
    {
        Stack <JSONNode> stack    = new Stack <JSONNode>();
        JSONNode         jSONNode = null;
        int    i     = 0;
        string text  = string.Empty;
        string text2 = string.Empty;
        bool   flag  = false;

        for (; i < aJSON.Length; i++)
        {
            switch (aJSON[i])
            {
            case '{':
                if (flag)
                {
                    text += aJSON[i];
                    break;
                }
                stack.Push(new JSONClass());
                if (jSONNode != null)
                {
                    text2 = text2.Trim();
                    if (jSONNode is JSONArray)
                    {
                        jSONNode.Add(stack.Peek());
                    }
                    else if (text2 != string.Empty)
                    {
                        jSONNode.Add(text2, stack.Peek());
                    }
                }
                text2    = string.Empty;
                text     = string.Empty;
                jSONNode = stack.Peek();
                break;

            case '[':
                if (flag)
                {
                    text += aJSON[i];
                    break;
                }
                stack.Push(new JSONArray());
                if (jSONNode != null)
                {
                    text2 = text2.Trim();
                    if (jSONNode is JSONArray)
                    {
                        jSONNode.Add(stack.Peek());
                    }
                    else if (text2 != string.Empty)
                    {
                        jSONNode.Add(text2, stack.Peek());
                    }
                }
                text2    = string.Empty;
                text     = string.Empty;
                jSONNode = stack.Peek();
                break;

            case ']':
            case '}':
                if (flag)
                {
                    text += aJSON[i];
                    break;
                }
                if (stack.Count == 0)
                {
                    throw new Exception("JSON Parse: Too many closing brackets");
                }
                stack.Pop();
                if (text != string.Empty)
                {
                    text2 = text2.Trim();
                    if (jSONNode is JSONArray)
                    {
                        jSONNode.Add(text);
                    }
                    else if (text2 != string.Empty)
                    {
                        jSONNode.Add(text2, text);
                    }
                }
                text2 = string.Empty;
                text  = string.Empty;
                if (stack.Count > 0)
                {
                    jSONNode = stack.Peek();
                }
                break;

            case ':':
                if (flag)
                {
                    text += aJSON[i];
                    break;
                }
                text2 = text;
                text  = string.Empty;
                break;

            case '"':
                flag ^= true;
                break;

            case ',':
                if (flag)
                {
                    text += aJSON[i];
                    break;
                }
                if (text != string.Empty)
                {
                    if (jSONNode is JSONArray)
                    {
                        jSONNode.Add(text);
                    }
                    else if (text2 != string.Empty)
                    {
                        jSONNode.Add(text2, text);
                    }
                }
                text2 = string.Empty;
                text  = string.Empty;
                break;

            case '\t':
            case ' ':
                if (flag)
                {
                    text += aJSON[i];
                }
                break;

            case '\\':
                i++;
                if (flag)
                {
                    char c = aJSON[i];
                    switch (c)
                    {
                    case 't':
                        text += '\t';
                        break;

                    case 'r':
                        text += '\r';
                        break;

                    case 'n':
                        text += '\n';
                        break;

                    case 'b':
                        text += '\b';
                        break;

                    case 'f':
                        text += '\f';
                        break;

                    case 'u':
                    {
                        string s = aJSON.Substring(i + 1, 4);
                        text += (char)int.Parse(s, NumberStyles.AllowHexSpecifier);
                        i    += 4;
                        break;
                    }

                    default:
                        text += c;
                        break;
                    }
                }
                break;

            default:
                text += aJSON[i];
                break;

            case '\n':
            case '\r':
                break;
            }
        }
        if (flag)
        {
            throw new Exception("JSON Parse: Quotation marks seems to be messed up.");
        }
        return(jSONNode);
    }
Exemplo n.º 18
0
        public static JSONNode Parse(string aJSON)
        {
            Stack <JSONNode> stack = new Stack <JSONNode>();
            JSONNode         ctx   = null;
            int    i         = 0;
            string Token     = "";
            string TokenName = "";
            bool   QuoteMode = false;

            while (i < aJSON.Length)
            {
                switch (aJSON[i])
                {
                case '{':
                    if (QuoteMode)
                    {
                        Token += aJSON[i];
                        break;
                    }
                    stack.Push(new JSONClass());
                    if (ctx != null)
                    {
                        TokenName = TokenName.Trim();
                        if (ctx is JSONArray)
                        {
                            ctx.Add(stack.Peek());
                        }
                        else if (TokenName != "")
                        {
                            ctx.Add(TokenName, stack.Peek());
                        }
                    }
                    TokenName = "";
                    Token     = "";
                    ctx       = stack.Peek();
                    break;

                case '[':
                    if (QuoteMode)
                    {
                        Token += aJSON[i];
                        break;
                    }

                    stack.Push(new JSONArray());
                    if (ctx != null)
                    {
                        TokenName = TokenName.Trim();
                        if (ctx is JSONArray)
                        {
                            ctx.Add(stack.Peek());
                        }
                        else if (TokenName != "")
                        {
                            ctx.Add(TokenName, stack.Peek());
                        }
                    }
                    TokenName = "";
                    Token     = "";
                    ctx       = stack.Peek();
                    break;

                case '}':
                case ']':
                    if (QuoteMode)
                    {
                        Token += aJSON[i];
                        break;
                    }
                    if (stack.Count == 0)
                    {
                        throw new Exception("JSON Parse: Too many closing brackets");
                    }

                    stack.Pop();
                    if (Token != "")
                    {
                        TokenName = TokenName.Trim();
                        if (ctx is JSONArray)
                        {
                            ctx.Add(Token);
                        }
                        else if (TokenName != "")
                        {
                            ctx.Add(TokenName, Token);
                        }
                    }
                    TokenName = "";
                    Token     = "";
                    if (stack.Count > 0)
                    {
                        ctx = stack.Peek();
                    }
                    break;

                case ':':
                    if (QuoteMode)
                    {
                        Token += aJSON[i];
                        break;
                    }
                    TokenName = Token;
                    Token     = "";
                    break;

                case '"':
                    QuoteMode ^= true;
                    break;

                case ',':
                    if (QuoteMode)
                    {
                        Token += aJSON[i];
                        break;
                    }
                    if (Token != "")
                    {
                        if (ctx is JSONArray)
                        {
                            ctx.Add(Token);
                        }
                        else if (TokenName != "")
                        {
                            ctx.Add(TokenName, Token);
                        }
                    }
                    TokenName = "";
                    Token     = "";
                    break;

                case '\r':
                case '\n':
                    break;

                case ' ':
                case '\t':
                    if (QuoteMode)
                    {
                        Token += aJSON[i];
                    }
                    break;

                case '\\':
                    ++i;
                    if (QuoteMode)
                    {
                        char C = aJSON[i];
                        switch (C)
                        {
                        case 't': Token += '\t'; break;

                        case 'r': Token += '\r'; break;

                        case 'n': Token += '\n'; break;

                        case 'b': Token += '\b'; break;

                        case 'f': Token += '\f'; break;

                        case 'u':
                        {
                            string s = aJSON.Substring(i + 1, 4);
                            Token += (char)int.Parse(s, System.Globalization.NumberStyles.AllowHexSpecifier);
                            i     += 4;
                            break;
                        }

                        default: Token += C; break;
                        }
                    }
                    break;

                default:
                    Token += aJSON[i];
                    break;
                }
                ++i;
            }
            if (QuoteMode)
            {
                throw new Exception("JSON Parse: Quotation marks seems to be messed up.");
            }
            return(ctx);
        }
Exemplo n.º 19
0
    public static JSONNode Parse(string aJSON)
    {
        Stack <JSONNode> stack      = new Stack <JSONNode>();
        JSONNode         ctx        = null;
        int           i             = 0;
        StringBuilder Token         = new StringBuilder();
        string        TokenName     = "";
        bool          QuoteMode     = false;
        bool          TokenIsQuoted = false;

        while (i < aJSON.Length)
        {
            switch (aJSON[i])
            {
            case '{':
                if (QuoteMode)
                {
                    Token.Append(aJSON[i]);
                    break;
                }
                stack.Push(new JSONObject());
                if (ctx != null)
                {
                    ctx.Add(TokenName, stack.Peek());
                }
                TokenName    = "";
                Token.Length = 0;
                ctx          = stack.Peek();
                break;

            case '[':
                if (QuoteMode)
                {
                    Token.Append(aJSON[i]);
                    break;
                }

                stack.Push(new JSONArray());
                if (ctx != null)
                {
                    ctx.Add(TokenName, stack.Peek());
                }
                TokenName    = "";
                Token.Length = 0;
                ctx          = stack.Peek();
                break;

            case '}':
            case ']':
                if (QuoteMode)
                {
                    Token.Append(aJSON[i]);
                    break;
                }
                if (stack.Count == 0)
                {
                    throw new Exception("JSON Parse: Too many closing brackets");
                }

                stack.Pop();
                if (Token.Length > 0 || TokenIsQuoted)
                {
                    ParseElement(ctx, Token.ToString(), TokenName, TokenIsQuoted);
                    TokenIsQuoted = false;
                }
                TokenName    = "";
                Token.Length = 0;
                if (stack.Count > 0)
                {
                    ctx = stack.Peek();
                }
                break;

            case ':':
                if (QuoteMode)
                {
                    Token.Append(aJSON[i]);
                    break;
                }
                TokenName     = Token.ToString();
                Token.Length  = 0;
                TokenIsQuoted = false;
                break;

            case '"':
                QuoteMode     ^= true;
                TokenIsQuoted |= QuoteMode;
                break;

            case ',':
                if (QuoteMode)
                {
                    Token.Append(aJSON[i]);
                    break;
                }
                if (Token.Length > 0 || TokenIsQuoted)
                {
                    ParseElement(ctx, Token.ToString(), TokenName, TokenIsQuoted);
                    TokenIsQuoted = false;
                }
                TokenName     = "";
                Token.Length  = 0;
                TokenIsQuoted = false;
                break;

            case '\r':
            case '\n':
                break;

            case ' ':
            case '\t':
                if (QuoteMode)
                {
                    Token.Append(aJSON[i]);
                }
                break;

            case '\\':
                ++i;
                if (QuoteMode)
                {
                    char C = aJSON[i];
                    switch (C)
                    {
                    case 't':
                        Token.Append('\t');
                        break;

                    case 'r':
                        Token.Append('\r');
                        break;

                    case 'n':
                        Token.Append('\n');
                        break;

                    case 'b':
                        Token.Append('\b');
                        break;

                    case 'f':
                        Token.Append('\f');
                        break;

                    case 'u':
                    {
                        string s = aJSON.Substring(i + 1, 4);
                        Token.Append((char)int.Parse(
                                         s,
                                         System.Globalization.NumberStyles.AllowHexSpecifier));
                        i += 4;
                        break;
                    }

                    default:
                        Token.Append(C);
                        break;
                    }
                }
                break;

            default:
                Token.Append(aJSON[i]);
                break;
            }
            ++i;
        }
        if (QuoteMode)
        {
            throw new Exception("JSON Parse: Quotation marks seems to be messed up.");
        }
        return(ctx);
    }
 public override void SerializeProperties(JSONNode jsonData)
 {
     jsonData.Add("maxDistance", new JSONNumber(MaxDistance));
 }
Exemplo n.º 21
0
        public void Execute(JSONNode args)
        {
            var api            = ApiManager.Instance;
            var controlManager = SimulatorManager.Instance.ControllableManager;

            var name             = args["name"].Value;
            var position         = args["state"]["transform"]["position"].ReadVector3();
            var rotation         = args["state"]["transform"]["rotation"].ReadVector3();
            var velocity         = args["state"]["velocity"].ReadVector3();
            var angular_velocity = args["state"]["angular_velocity"].ReadVector3();

            Web.Config.Controllables.TryGetValue(name, out IControllable prefab);
            if (prefab == null)
            {
                api.SendError(this, $"Unknown '{name}' controllable prefab");
                return;
            }

            string uid;
            var    argsUid = args["uid"];

            if (argsUid == null)
            {
                uid = System.Guid.NewGuid().ToString();
                // Add uid key to arguments, as it will be distributed to the clients' simulations
                if (Loader.Instance.Network.IsMaster)
                {
                    args.Add("uid", uid);
                }
            }
            else
            {
                uid = argsUid.Value;
            }

            var controllable = controlManager.SpawnControllable(prefab.gameObject, uid, position,
                                                                Quaternion.Euler(rotation), velocity, angular_velocity);

            if (controllable == null)
            {
                api.SendError(this, $"Failed to spawn '{name}' controllable");
                return;
            }

            JSONArray validActions = new JSONArray();

            if (controllable.ValidStates != null)
            {
                foreach (var state in controllable.ValidStates)
                {
                    validActions.Add(state);
                }
            }

            if (controllable.ValidActions != null)
            {
                foreach (var action in controllable.ValidActions)
                {
                    validActions.Add(action);
                }
            }

            JSONObject j = new JSONObject();

            j.Add("uid", new JSONString(controllable.UID));
            j.Add("position", controllable.transform.position);
            j.Add("rotation", controllable.transform.rotation.eulerAngles);
            j.Add("type", new JSONString(controllable.ControlType));
            j.Add("valid_actions", validActions);
            j.Add("default_control_policy", Utility.SerializeControlPolicy(controllable.DefaultControlPolicy));

            api.SendResult(this, j);
        }
Exemplo n.º 22
0
        private void InferAxisSpecsForChannel(ref ChannelEncoding channelEncoding, ref JSONNode specs, Data data)
        {
            string   channel      = channelEncoding.channel;
            JSONNode channelSpecs = specs["encoding"][channel];
            JSONNode axisSpecs    = channelSpecs["axis"];

            if (axisSpecs != null && axisSpecs.Value.ToString() == "none")
            {
                return;
            }

            JSONObject axisSpecsObj = (axisSpecs == null) ? new JSONObject() : axisSpecs.AsObject;

            if (axisSpecsObj["filter"] == null)
            {
                axisSpecsObj.Add("filter", new JSONBool(false));
            }

            if (axisSpecsObj["face"] == null)
            {
                if (channel == "x" || channel == "y")
                {
                    axisSpecsObj.Add("face", new JSONString("front"));
                }
                else if (channel == "z")
                {
                    axisSpecsObj.Add("face", new JSONString("left"));
                }
            }

            if (axisSpecsObj["orient"] == null)
            {
                if (channel == "x" || channel == "z")
                {
                    axisSpecsObj.Add("orient", new JSONString("bottom"));
                }
                else if (channel == "y")
                {
                    axisSpecsObj.Add("orient", new JSONString("left"));
                }
            }

            if (axisSpecsObj["title"] == null)
            {
                axisSpecsObj.Add("title", new JSONString(channelEncoding.field));
            }

            if (axisSpecsObj["length"] == null)
            {
                float axisLength = 0.0f;
                switch (channelEncoding.channel)
                {
                case "x":
                    //case "width":
                    axisLength = specs["width"].AsFloat;
                    break;

                case "y":
                    //case "height":
                    axisLength = specs["height"].AsFloat;
                    break;

                case "z":
                    //case "depth":
                    axisLength = specs["depth"].AsFloat;
                    break;

                default:
                    axisLength = 0.0f;
                    break;
                }

                axisSpecsObj.Add("length", new JSONNumber(axisLength));
            }

            if (axisSpecs["color"] == null)
            {
                axisSpecsObj.Add("color", new JSONString("#bebebe"));
            }

            /*
             * if(axisSpecs["color"] == null)
             * {
             *  string color = "";
             *  switch (channelEncoding.channel)
             *  {
             *      case "x":
             *          color = "#ff0000";
             *          break;
             *      case "y":
             *          color = "#00ff00";
             *          break;
             *      case "z":
             *          color = "#0000ff";
             *          break;
             *      default:
             *          break;
             *  }
             *
             *  axisSpecsObj.Add("color", new JSONString(color));
             * }
             */

            if (axisSpecsObj["grid"] == null)
            {
                axisSpecsObj.Add("grid", new JSONBool(false));
            }

            if (axisSpecs["ticks"] == null)
            {
                axisSpecsObj.Add("ticks", new JSONBool(true));
            }

            if (axisSpecsObj["values"] == null)
            {
                JSONArray tickValues = new JSONArray();
                JSONNode  domain     = specs["encoding"][channelEncoding.channel]["scale"]["domain"];
                JSONNode  values     = channelEncoding.fieldDataType == "quantitative" ? new JSONArray() : domain;

                if (channelEncoding.fieldDataType == "quantitative" &&
                    (channel == "x" || channel == "y" || channel == "z"))
                {
                    // Round domain into a nice number.
                    //float maxDomain = RoundNice(domain.AsArray[1].AsFloat - domain.AsArray[0].AsFloat);

                    int numDecimals = Math.Max(GetNumDecimalPlaces(domain.AsArray[0].AsFloat), GetNumDecimalPlaces(domain.AsArray[1].AsFloat));
                    //Debug.Log("NUM DEC " + numDecimals);
                    // Add number of ticks.
                    int   defaultNumTicks = 6;
                    int   numTicks        = axisSpecsObj["tickCount"] == null ? defaultNumTicks : axisSpecsObj["tickCount"].AsInt;
                    float intervals       = Math.Abs(domain.AsArray[1].AsFloat - domain.AsArray[0].AsFloat) / (numTicks - 1.0f);


                    for (int i = 0; i < numTicks; i++)
                    {
                        float tickVal = (float)Math.Round(domain.AsArray[0].AsFloat + (intervals * (float)(i)), numDecimals);
                        //Debug.Log(tickVal);
                        values.Add(new JSONString(tickVal.ToString()));
                    }
                }

                axisSpecsObj.Add("values", values.AsArray);
            }

            if (axisSpecsObj["tickCount"] == null)
            {
                axisSpecsObj.Add("tickCount", new JSONNumber(axisSpecsObj["values"].Count));
            }

            if (axisSpecsObj["labels"] == null)
            {
                axisSpecsObj.Add("labels", new JSONBool(true));
            }

            specs["encoding"][channelEncoding.channel].Add("axis", axisSpecsObj);
        }
Exemplo n.º 23
0
 public void SetData(string key, string value)
 {
     _dataClone.Add(key, value);
 }
Exemplo n.º 24
0
        private static void TextMessageReceived(NetworkingPlayer player, Text frame, NetWorker sender)
        {
            try
            {
                var json = JSON.Parse(frame.ToString());

                if (json["register"] != null)
                {
                    string address = player.IPEndPointHandle.Address.ToString();
                    ushort port    = json["register"]["port"].AsUShort;

                    if (!hosts.ContainsKey(address))
                    {
                        hosts.Add(address, new List <Host>());
                    }

                    foreach (Host host in hosts[address])
                    {
                        // This host is already registered
                        if (host.port == port)
                        {
                            return;
                        }
                    }

                    System.Console.Write("Hosted Server received: ");
                    System.Console.Write(address);
                    System.Console.Write(":");
                    System.Console.Write(port);
                    System.Console.Write(" received");
                    System.Console.Write(System.Environment.NewLine);

                    hosts[address].Add(new Host(player, address, port));
                }
                else if (json["host"] != null && json["port"] != null)
                {
                    server.Disconnect(player, false);

                    string addresss      = json["host"];
                    ushort port          = json["port"].AsUShort;
                    ushort listeningPort = json["clientPort"].AsUShort;

                    addresss = NetWorker.ResolveHost(addresss, port).Address.ToString();

                    if (!hosts.ContainsKey(addresss))
                    {
                        return;
                    }

                    Host foundHost = new Host();
                    foreach (Host iHost in hosts[addresss])
                    {
                        if (iHost.port == port)
                        {
                            foundHost = iHost;
                            break;
                        }
                    }


                    if (string.IsNullOrEmpty(foundHost.host))
                    {
                        return;
                    }

                    JSONNode obj = JSONNode.Parse("{}");
                    obj.Add("host", new JSONData(player.IPEndPointHandle.Address.ToString().Split(':')[0]));
                    obj.Add("port", new JSONData(listeningPort));

                    JSONClass sendObj = new JSONClass();
                    sendObj.Add("nat", obj);

                    Text notifyFrame = Text.CreateFromString(server.Time.Timestep, sendObj.ToString(), false, Receivers.Target, MessageGroupIds.NAT_ROUTE_REQUEST, false);

                    server.Send(foundHost.player, notifyFrame, true);
                }
            }
            catch
            {
                server.Disconnect(player, true);
            }
        }
Exemplo n.º 25
0
        private void InferAxisSpecsForChannel(ref ChannelEncoding channelEncoding, ref JSONNode sceneSpecs, Data data)
        {
            string   channel      = channelEncoding.channel;
            JSONNode channelSpecs = sceneSpecs["encoding"][channel];
            JSONNode axisSpecs    = channelSpecs["axis"];

            if (axisSpecs != null && axisSpecs.Value.ToString() == "none")
            {
                return;
            }

            JSONObject axisSpecsObj = (axisSpecs == null) ? new JSONObject() : axisSpecs.AsObject;

            if (axisSpecsObj["face"] == null)
            {
                if (channel == "x" || channel == "y" || channel == "width" || channel == "height")
                {
                    axisSpecsObj.Add("face", new JSONString("front"));
                }
                else if (channel == "z" || channel == "depth")
                {
                    axisSpecsObj.Add("face", new JSONString("left"));
                }
            }

            if (axisSpecsObj["orient"] == null)
            {
                if (channel == "x" || channel == "z" || channel == "width" || channel == "depth")
                {
                    axisSpecsObj.Add("orient", new JSONString("bottom"));
                }
                else if (channel == "y" || channel == "height")
                {
                    axisSpecsObj.Add("orient", new JSONString("left"));
                }
            }

            if (axisSpecsObj["title"] == null)
            {
                axisSpecsObj.Add("title", new JSONString(channelEncoding.field));
            }

            if (axisSpecsObj["grid"] == null)
            {
                axisSpecsObj.Add("grid", new JSONBool(false));
            }

            if (axisSpecs["ticks"] == null)
            {
                axisSpecsObj.Add("ticks", new JSONBool(true));
            }

            if (axisSpecsObj["values"] == null)
            {
                JSONArray tickValues = new JSONArray();
                JSONNode  domain     = sceneSpecs["encoding"][channelEncoding.channel]["scale"]["domain"];
                JSONNode  values     = channelEncoding.fieldDataType == "quantitative" ? new JSONArray() : domain;

                if (channelEncoding.fieldDataType == "quantitative" &&
                    (channel == "x" || channel == "y" || channel == "z" ||
                     channel == "width" || channel == "height" || channel == "depth"))
                {
                    // Round domain into a nice number.
                    // TODO: make robust rounding.
                    // HACK:
                    float maxDomain = RoundNice(domain.AsArray[1].AsFloat - domain.AsArray[0].AsFloat);

                    // Add number of ticks.
                    int   defaultNumTicks = 6;
                    int   numTicks        = axisSpecsObj["tickCount"] == null ? defaultNumTicks : axisSpecsObj["tickCount"].AsInt;
                    float intervals       = maxDomain / (numTicks - 1.0f);


                    for (int i = 0; i < numTicks; i++)
                    {
                        float tickVal = domain.AsArray[0].AsFloat + (intervals * (float)(i));
                        values.Add(new JSONNumber(tickVal));
                    }
                }

                axisSpecsObj.Add("values", values.AsArray);
            }

            if (axisSpecsObj["tickCount"] == null)
            {
                axisSpecsObj.Add("tickCount", new JSONNumber(axisSpecsObj["values"].Count));
            }

            if (axisSpecsObj["labels"] == null)
            {
                axisSpecsObj.Add("labels", new JSONBool(true));
            }

            sceneSpecs["encoding"][channelEncoding.channel].Add("axis", axisSpecsObj);
        }