// Use this for initialization
	void Start () {
        Messenger.AddListener<float>("Simulate Activity", UpdateEvents);
        Messenger.AddListener<SCPData>("New SCP Loaded", AddSCPEvent);

        if (redHerringJson == null)
        {
            //Read event data from system files.
            string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, redHerringEventFileName + ".txt");
            redHerringJson = JSONNode.Parse(System.IO.File.ReadAllText(filePath));
            filePath = System.IO.Path.Combine(Application.streamingAssetsPath, anomalousEventFileName + ".txt");
            anomalousEventJson = JSONNode.Parse(System.IO.File.ReadAllText(filePath));
            filePath = System.IO.Path.Combine(Application.streamingAssetsPath, "flavorMarquee.txt");
            flavorMarqueeJson = JSONNode.Parse(System.IO.File.ReadAllText(filePath));
        }

        EventList = new Dictionary<int, AnomalousEvent>();

        if (GlobalPlayerData.preLoadedData != null && !GlobalPlayerData.preLoadedData.Equals(""))
        {
            Load(GlobalPlayerData.preLoadedData["AnomalousEventManager"]);
        } else
        {
            StepsSinceLastSpawn = 0;
            StepsUntilNextSpawn = 0;
            IDGenerator = 0;
        }
	}
Ejemplo n.º 2
0
    public LevelTarget(JSONNode json)
    {
        switch (json["limit_type"])
        {
            case "Time":
                LimitType = LimitType.Time;
                TimeSpan = json["limit"].AsInt;
                break;
            case "Moves":
                LimitType = LimitType.Moves;
                Moves = json["limit"].AsInt;
                break;
        }

        StarsLevels = new List<int>();
        for (var i = 0; i < json["stars_levels"].AsArray.Count; i++)
        {
            StarsLevels.Add(json["stars_levels"][i].AsInt);
        }

        _prices = new List<KeyValuePair<int, int>>();
        for (int i = 0; i < json["prices"].AsArray.Count; i++)
        {
            KeyValuePair<int, int> pair = 
                new KeyValuePair<int, int>(json["prices"][i]["index"].AsInt, json["prices"][i]["price"].AsInt);
            _prices.Add(pair);
        }
    }
Ejemplo n.º 3
0
 public IEnumerator LoadActuator(JSONNode actuator)
 {
     //foreach Actuator
         // Create Actuator
         // yield return InitializeActuator
     yield return null;
 }
    private bool GetJsonFile(string path)
    {
        _json = null;
        _json = JSON.Parse(Resources.Load(path, typeof(object)).ToString());

        return _json != null;
    }
Ejemplo n.º 5
0
 public void WriteToStream(JSONNode pNode, Stream s)
 {
     using (textWriter = new StreamWriter(s))
     {
         WriteToStream(pNode, textWriter);
     }
 }
Ejemplo n.º 6
0
 public Level(JSONNode docLevel)
 {
     initRooms(docLevel["rooms"]);
     initPositions(docLevel["positions"]);
     initLinks(docLevel["links"]);
     initPlayer(docLevel["player"]);
 }
Ejemplo n.º 7
0
    public IEnumerator assess(string p_action, JSONNode p_values, Action<JSONNode> callback)
    {
        print("--- assess action (" + p_action + ") ---");

        string putDataString =
            "{" +
                "\"action\": \"" + p_action + "\"" +
                ", \"values\": " + p_values.ToString() +
                "}";

        string URL = baseURL + "/gameplay/" + idGameplay + "/assessAndScore";

        WWW www = new WWW(URL, Encoding.UTF8.GetBytes(putDataString), headers);

        // wait for the requst to finish
        yield return www;

        JSONNode returnAssess = JSON.Parse(www.text);

        feedback = returnAssess["feedback"].AsArray;
        scores = returnAssess["scores"].AsArray;
        print("Action " + putDataString + " assessed! returned: " + returnAssess.ToString());
        foreach (JSONNode f in feedback)
        {
            // log badge
            if (string.Equals(f["type"], "BADGE"))
            {
                badgesWon.Add(f);
            }
        }

        callback(returnAssess);
    }
Ejemplo n.º 8
0
 void ApplyData(JSONNode masterJSON)
 {
     Debug.Log("Appling Data from JSON");
     SetTitle(masterJSON[0]);
     SetMaxObjects(masterJSON[1]);
     SetButtonData(masterJSON[2]);
 }
Ejemplo n.º 9
0
	public CountryData(JSONNode N) {
        cityList = new List<CityData>();
        gridSquares = new List<int>();

		name = N["name"];
		foundationRelationship = 5;
		fundingLevel = 0;
		fundingMultiplier = N["fundingMultiplier"].AsFloat;
		militaryMultiplier = N["militaryMultiplier"].AsFloat;
		population = N["population"].AsInt;
        if (N["picture"] != null) {
            spriteLocation = N["picture"];
            countryPicture = Resources.Load<Sprite>(spriteLocation);
        }
        
        //remove this check once data is complete
        if (N["gridSquares"] != null)
            gridSquares = GameUtils.ParseIntList(N["gridSquares"]);

        if (N["cities"] != null) {
            foreach (JSONNode city in N["cities"].AsArray) {
                cityList.Add(new CityData(city));
            }
        }
	}
Ejemplo n.º 10
0
    public void cargarJsonEscena()
    {

        //Compruebo en que escena estamos y cargo el json correspondiente.
        switch (SceneManager.GetActiveScene().name)
        {

            case "Main":
                sceneJson = JSONNode.Parse(jsons[0].text);
                break;
            case "Bar":
                sceneJson = JSONNode.Parse(jsons[1].text);
                break;
            case "Estanco":
                sceneJson = JSONNode.Parse(jsons[2].text);
                break;
            case "Oficina":
                sceneJson = JSONNode.Parse(jsons[3].text);
                break;
            case "Iglesia":
                sceneJson = JSONNode.Parse(jsons[4].text);
                break;
                //case "Main":
                //break;
                //case "Main":
                //break;

        }

    }
Ejemplo n.º 11
0
    public IEnumerator Initialize(string URL)
    {
        // Query URL, parse
        url = URL.Replace(System.Environment.NewLine, "");
        WWW www = new WWW (url);
        yield return www;

        node = JSON.Parse (www.text);

        row = node ["row"].AsInt;
        col = node ["col"].AsInt;
        transform.name = "Site " + row + "-" + col;

        // Set scale, then parent, then position

        float scalar = Mathf.Min (myTray.rowScale / 2.0f, myTray.colScale / 2.0f);
        Vector3 scale = new Vector3 (scalar, scalar/2f, scalar);
        Vector3 pos = new Vector3 (-0.5f + myTray.colOffset + (1.0f * col + 0.5f) * myTray.colScale,
                                   0.5f,
                                   -0.5f + myTray.rowOffset + (1.0f * row + 0.5f) * myTray.rowScale);

        transform.localScale = scale;
        transform.SetParent (myTray.transform);
        transform.localPosition = pos;

        yield return StartCoroutine ("LoadPlant");

        yield return null;
    }
Ejemplo n.º 12
0
    public void moveVertices(JSONNode positions)
    {
        Mesh mesh = GetComponent<MeshFilter> ().mesh;
        Vector3[] vertices = mesh.vertices;

        Vector3 invertY = new Vector3 (1, -1, 1);

        // Set top left
        JSONNode tl = positions["top_left"];
        Vector3 tlverts = new Vector3 (tl["x"].AsFloat, tl["y"].AsFloat, 0);
        vertices [3] = Vector3.Scale (tlverts, invertY);

        // Set top right
        JSONNode tr = positions["top_right"];
        Vector3 trverts = new Vector3 (tr["x"].AsFloat, tr["y"].AsFloat, 0);
        vertices [1] = Vector3.Scale (trverts, invertY);

        // Set top left
        JSONNode bl = positions["bottom_left"];
        Vector3 blverts = new Vector3 (bl["x"].AsFloat, bl["y"].AsFloat, 0);
        vertices [0] = Vector3.Scale (blverts, invertY);

        // Set top left
        JSONNode br = positions["bottom_right"];
        Vector3 brverts = new Vector3 (br["x"].AsFloat, br["y"].AsFloat, 0);
        vertices [2] = Vector3.Scale (brverts, invertY);

        mesh.vertices = vertices;
        mesh.RecalculateNormals ();
    }
Ejemplo n.º 13
0
    public TimedWeaponEvent(JSONNode N) : base(N)
    {
        interceptTargetID = N["interceptTargetID"].AsInt;
        currentDistance = N["currentDistance"].AsFloat;
        interceptTarget = GeoscapeVariables.TEM.EventList[interceptTargetID].icon;

    }
Ejemplo n.º 14
0
	// Use this for initialization
	void Awake () {
		game = this;
		for (int i = 0; i < categories.Length; i++) {
			categoryLists.Add (categories [i], new List<int> ());
		}

		recipeList = JSON.Parse((Resources.Load("recipes") as TextAsset).text)["recipes"];

		for (int i = 0; i < recipeList.Count; i++) {
			categoryLists[recipeList [i] ["category"].Value].Add(i);
		}
		/*
		for (int i = 0; i < recipeList.Count; i++) {
			itemUnlock [i] = 1;
		}*/
		if (File.Exists (Application.persistentDataPath + "/savedData.json")) {
			Load ();
		}
		else{
			setInitData ();
		}


		if (discovered < levelOneCriteria) {
			currentCircle = Instantiate (circleThree);
		}
		else if (discovered < levelTwoCriteria) {
			currentCircle = Instantiate (circleFour);
		} else {
			currentCircle = Instantiate (circleFive);
		}
	}
Ejemplo n.º 15
0
	void Update () {
		if (canStart) {
			if (Input.GetKeyDown(KeyCode.RightArrow)) {
				Advance();
			} else if (Input.GetKeyDown (KeyCode.LeftArrow)) {
				Reverse();
			}
			if (_outro < 2f) {
				_outro += Time.deltaTime;
				if (_outro > 1.1f) {
					Destroy(myoHub);
				}
				if (_outro > 1.5f) {
					Application.LoadLevel("Scene2");
				}
			}
		} else if (www != null && www.isDone) {
			slides = JSONNode.Parse(www.text);
			carousel.AddToCarousel(slides["slides"][slideMax]);
			carousel.RotateCarousel();
			slideMax++;
			slideIndex++;
			_locked = true;
			canStart = true;
		}
	}
Ejemplo n.º 16
0
    // Use this for initialization
    public void Init(JSONNode nodeData)
    {
        node = nodeData;

        spriteRenderer.sprite = Resources.Load<Sprite>("Images/Buildings/" + node["buildingImage"]);
        keyString = node["keyString"];
        type = node["type"];
        float buildingPosX = node["x"].AsFloat;
        float buildingPosY = node["y"].AsFloat;

        Vector3 buildingTransform = transform.position;
        buildingTransform.x = buildingPosX;
        buildingTransform.y = -buildingPosY;

        transform.position = buildingTransform;
        spriteRenderer.sortingOrder = 2;

        if (type.Equals ("MOA")) {
            spriteRenderer.sortingOrder = 1;
        } else if (type.Equals ("GAT")) {
            spriteRenderer.sortingOrder = 3;
        } else {
            spriteRenderer.sortingOrder = 2;
        }
    }
Ejemplo n.º 17
0
 IEnumerator getScore(string user)
 {
     WWW www = new WWW (HTTP.server + "/scores/?id=" + user);
     yield return www;
     JSONNode N = new JSONNode ();
     N = JSON.Parse (www.text);
     try {
         if (N ["success"].ToString() == "\"true\"") {
             if (N ["result"] [0] != null) {
                 string highScore = (string)N ["result"] [0] ["scores"] [0] ["score"];
                 float highScore_val = float.Parse (highScore);
                 if (highScore == null && score != null) {
                     best_score.text = "Best score: " + Time.timeSinceLevelLoad.ToString ("#.##");
                 } else if (score != null) {
                     if (highScore_val >= final_score) {
                         best_score.text = "Best score: " + highScore;
                     } else {
                         best_score.text = "Best score: " + final_score.ToString ("#.##");
                     }
                 }
             } else if (best_score.text != null) {
                 best_score.text = final_score.ToString ("#.##");
                 StartCoroutine (createUser (HTTP.identifier));
             }
         }
         else{
             best_score.text= " ";
         }
     } catch {
         best_score.text = " ";
     }
 }
Ejemplo n.º 18
0
 public BuildItem(JSONNode jd)
 {
     id = jd["id"].AsInt;
     name = jd["name"];
     resourceName = jd["resources_name"];
     type = (EBuildItemType)jd["type"].AsInt;
 }
Ejemplo n.º 19
0
 public void SaveState(JSONNode data)
 {
     if (saveState)
     {
         data[gameObject.name]["enabled"].AsBool = triggerEnabled;
     }
 }
Ejemplo n.º 20
0
    public void Load(JSONNode N) {
        if (GoIList.Count > 0) {
            foreach (DictionaryEntry goi in GoIList) {
                ((GoIBase)goi.Value).Clear();
            }
        }

        foreach (JSONNode node in N.Children) {
            try {
                GoIBase newGOI = (GoIBase)System.Activator.CreateInstance(System.Type.GetType(node["className"]), node);
                GoIList.Add(newGOI.name, newGOI);
            }
            catch (System.Exception e) {
                Debug.Log("Non-Existent GOI Type Declared: " + node["className"] + " Error: " + e.InnerException);
                Debug.Log(e.Message);
                Debug.Log(e.StackTrace);
            }
        }

        //set default relationships
        foreach (DictionaryEntry goi in GoIList) {
            foreach (string key in GoIList.Keys) {
                if (goi.Value.GetType() != typeof(EventGeneratingGoI) && !goi.Key.Equals(key) && GoIList[key].GetType() != typeof(EventGeneratingGoI)) {
                    if (!((GoIBase)goi.Value).relationshipMap.ContainsKey(key)) {
                        //Debug.Log(key);
                        ((GoIBase)goi.Value).relationshipMap.Add(key, 5);
                    }
                }
            }
        }

        GameObject.Find("UIManager").GetComponent<UIManagerScript>().CreateRelationsButtons();
    }
Ejemplo n.º 21
0
    public static void AddCurveIngredients(JSONNode ingredientDictionary, string prefix)
    {
        //in case there is curveN, grab the data if more than 4 points
        //use the given PDB for the representation.
        var numCurves = ingredientDictionary["nbCurve"].AsInt;
        var curveIngredientName = prefix + "_" + ingredientDictionary["name"].Value;
        var pdbName = ingredientDictionary["source"]["pdb"].Value.Replace(".pdb", "");

        SceneManager.Instance.AddCurveIngredient(curveIngredientName, pdbName);

        for (int i = 0; i < numCurves; i++)
        {
            //if (i < nCurve-10) continue;
            var controlPoints = new List<Vector4>();
            if (ingredientDictionary["curve" + i.ToString()].Count < 4) continue;

            for (int k = 0; k < ingredientDictionary["curve" + i.ToString()].Count; k++)
            {
                var p = ingredientDictionary["curve" + i.ToString()][k];
                controlPoints.Add(new Vector4(-p[0].AsFloat, p[1].AsFloat, p[2].AsFloat, 1));
            }

            SceneManager.Instance.AddCurve(curveIngredientName, controlPoints);
            //break;
        }

        Debug.Log("*****");
        Debug.Log("Added curve ingredient: " + curveIngredientName);
        Debug.Log("Num curves: " + numCurves);
    }
Ejemplo n.º 22
0
 public void Save(ref JSONNode N) {
     N["TrueHQ"] = TrueHQ.ToString();
     N["regionNum"] = Location.regionCode.ToString();
     N["statusCode"] = Location.statusCode.ToString();
     N["gridNum"] = Location.gridCell.ToString();
     N["spawnLocation"] = Location.spawnLocation.ToString();
 }
Ejemplo n.º 23
0
 void fromJson(JSONNode data)
 {
     Initialize (
         int.Parse((string) data ["id"]),
         (string) data ["answer"]
     );
 }
Ejemplo n.º 24
0
	public RegionData(JSONNode N) {
		RegionPolicies = new Dictionary<string, PolicyData>();
		countryList = new Dictionary<string, CountryData>();
		gridSquares = new List<int>();

		recoveryFunding = 10;
        spriteLocation = N["picture"];
        name = N["name"];
        agentCount = N["personnel"]["agentCount"].AsInt;
        responseTeamCount = N["personnel"]["responseTeamCount"].AsInt;
        agentEffectiveness = N["personnel"]["agentEffectiveness"].AsFloat;
        responseTeamEffectiveness = N["personnel"]["responseTeamEffectiveness"].AsFloat;
        regionPicture = Resources.Load<Sprite>(N["picture"]);
        abilityName = N["ability"]["name"];
        abilityDesc = N["ability"]["desc"];
       
        if (N["policies"] != null) {
            foreach (JSONNode policy in N["policies"].Children)
                RegionPolicies.Add(policy["name"], new PolicyData(policy.ToString()));
        }
        //Problem is past this point?
        foreach (JSONNode country in N["countries"].AsArray)
			countryList.Add (country["name"], new CountryData(country));

        gridSquares = GameUtils.ParseIntList(N["gridSquares"]);
	}
    /**
     * Parse json response from blockscan
     * call asset's function if same name asset are found in json response
     * */
    public void ParseJson(JSONNode jsonResponse)
    {
        //check if asset has been found at this address (bad format address?)
        if (jsonResponse == null) {
            Debug.Log ("no asset found at this address");
            return;
        }

        Debug.Log ("jsonReponse text: " + jsonResponse.ToString ());
        Debug.Log ("jsonResponse data count: " + jsonResponse ["data"].Count);

        //store number of asset found in json response
        int nbrOfAsset = jsonResponse ["data"].Count;

        //iterate to check if asset name are the same in assetName array and asset from json response
        for (int i = 0; i < nbrOfAsset; i++) {
            for (int y = 0; y < assetName.Length; y++){
                if (jsonResponse ["data"] [i] ["asset"].Value == assetName[y]){
                    string methodName = "Asset"+i;

                    //Get the method information using the method info class
                    MethodInfo mi = this.GetType().GetMethod(methodName);

                    //Invoke the method Asset1, Asset2, etc..
                    var arguments = new object[] { y };
                    mi.Invoke(this, arguments);
                }
            }
            Debug.Log ("asset name: " + jsonResponse ["data"] [i] ["asset"].Value);
            Debug.Log ("asset balance: " + jsonResponse ["data"] [i] ["balance"].Value);
        }
    }
Ejemplo n.º 26
0
 private Stats parseJSONStats(JSONNode stats)
 {
     Teaching t = new Teaching(stats["teaching"][0].AsInt, stats["teaching"][1].AsInt,stats["teaching"][2].AsInt,stats["teaching"][3].AsInt,stats["teaching"][4].AsInt);
     Combat c = new Combat(stats["combat"][0].AsInt,stats["combat"][1].AsInt,stats["combat"][2].AsInt,stats["combat"][3].AsInt,stats["combat"][4].AsInt);
     Intelligence i = new Intelligence(stats["intelligence"][0].AsInt,stats["intelligence"][1].AsInt,stats["intelligence"][2].AsInt,stats["intelligence"][3].AsInt,stats["intelligence"][4].AsInt);
     return new Stats(t, c, i);
 }
    public override void OnInteractClick(GameObject actor)
    {
        string resourceName = GetDialogResourceName ();

        json = null;
        if (!jsonOptions.ContainsKey (resourceName)) {
            LoadDialog (resourceName);
        }
        if (!jsonOptions.ContainsKey (resourceName)) {
            Debug.LogError ("No dialog found for resource named " + resourceName);
            return;
        }
        json = jsonOptions [resourceName];

        if (json == null) {
            Debug.LogError ("No dialog found for resource named " + resourceName);
            return;
        }

        states = new Dictionary<int, JSONNode> ();
        JSONArray jsonStates = json ["states"].AsArray;
        foreach (JSONNode stateChild in jsonStates.Children) {
            states [stateChild ["state"].AsInt] = stateChild;
        }

        dialogState = GetInitialDialogState ();
        InvokeJson (json ["onEnter"]);
        DialogManager.Show ();
        ShowDialogState ();
    }
Ejemplo n.º 28
0
    public static void AddCurveIngredients(JSONNode ingredientDictionary , params string[] pathElements)
    {
        var name = ingredientDictionary["name"];
        var path = MyUtility.GetUrlPath(pathElements.ToList(), name);
        var numCurves = ingredientDictionary["nbCurve"].AsInt;
        var pdbName = ingredientDictionary["source"]["pdb"].Value.Replace(".pdb", "");

        SceneManager.Get.AddCurveIngredient(path, pdbName);

        for (int i = 0; i < numCurves; i++)
        {
            //if (i < nCurve-10) continue;
            var controlPoints = new List<Vector4>();
            if (ingredientDictionary["curve" + i.ToString()].Count < 4) continue;

            for (int k = 0; k < ingredientDictionary["curve" + i.ToString()].Count; k++)
            {
                var p = ingredientDictionary["curve" + i.ToString()][k];
                controlPoints.Add(new Vector4(-p[0].AsFloat, p[1].AsFloat, p[2].AsFloat, 1));
            }

            SceneManager.Get.AddCurveIntance(path, controlPoints);
            //break;
        }

        Debug.Log("*****");
        Debug.Log("Added curve ingredient: " + path);
        Debug.Log("Num curves: " + numCurves);
    }
Ejemplo n.º 29
0
	public void Start ()
	{
		answers = new string[2];
		string kanjiInput = System.IO.File.ReadAllText ("assets/moon_speak.json");
		parsedInput = JSON.Parse (kanjiInput);
		populateLevel();

	}
Ejemplo n.º 30
0
 private void Deserialize(JSONNode node)
 {
     batteryLevel = node ["batteryLevel"].AsInt;
     iconURL = node["iconURL"].Value;
     identifier = node["identifier"].Value;
     name = node["name"].Value;
     temperature = node["temperature"].AsInt;
 }
Ejemplo n.º 31
0
 public static Champion parseChampionJSON(JSONNode json)
 {
     return(new Champion(json["id"], json["playerId"], json["championKey"], json["championName"], json["createdAt"], json["updatedAt"]));
 }
Ejemplo n.º 32
0
    public void RegisterUpAPICall()
    {
        LoadingCanvas.Instance.ShowLoadingPopUp("Loading...");
        Debug.Log("the Name of the Country and Code is: " + GetDropDownValue() + " " + Configuration.Instance.GetCountryCode(GetDropDownValue()).ToString());
        Web.Create()
        .SetUrl(Configuration.Instance.GetApi(Configuration.ApiKey.REGISTRATION), Web.RequestType.POST, Web.ResponseType.TEXT)
        .AddField(Constants.NAME, iName.text)
        .AddField(Constants.USER_NAME, iUserName.text)
        .AddField(Constants.PASSWORD, iPassword.text)
        .AddField(Constants.GENDER, genderString)
        .AddField("country", GetDropDownValue())
        .AddField("country_code", Configuration.Instance.GetCountryCode(GetDropDownValue()).ToString())
        .SetOnSuccessDelegate((Web _web, Response _response) =>
        {
            Debug.Log(_response.GetText());
            LoadingCanvas.Instance.HideLoadingPopUp();

            JSONNode node = JSONNode.Parse(_response.GetText());

            if (node["status"].Value == ErrorCode.SUCCESS_CODE)
            {
                Database.PutString(Database.Key.ACCESS_TOKEN, node["result"]["access_token"].Value);
                Database.PutString(Database.Key.PLAYER_ID, node["result"]["id"].Value);
                // Database.Instance.PutString(Database.Key.FIRST_NAME, node["result"]["first_name"].Value);
                // Database.Instance.PutString(Database.Key.LAST_NAME, node["result"]["last_name"].Value);


                Database.PutString(Database.Key.IMAGE, node["result"]["image"].Value);


                UIManager.instance.TransitionTo(UIPage.PageType.AVATAR);
            }
            else if ((node["status"]).Value == ErrorCode.UNIQUIE_MOBILE)
            {
                PopupCanvas.Instance.ShowAlertPopUp("Mobile Number already registered");
            }
            else if (node["status"].Value == ErrorCode.ERROR_LOGIN_GAME_RUNNING)
            {
                PopupCanvas.Instance.ShowAlertPopUp(node["message"].Value);
#if _D_I
                Debug.Log(node["message"].Value);
#endif
            }
            else
            {
                PopupCanvas.Instance.ShowAlertPopUp(node["message"].Value);
            }

            _web.Close();
        })
        .SetOnFailureDelegate((Web _web, Response _response) =>
        {
            Debug.Log(_response.GetText());
            LoadingCanvas.Instance.HideLoadingPopUp();
            if (_response.GetText().Contains("check the connectivity"))
            {
                PopupCanvas.Instance.ShowAlertPopUp("Please check your internet connection!");
            }
            else
            {
                PopupCanvas.Instance.ShowAlertPopUp("Server not found!");
            }
            Debug.Log(_response.GetText());
            _web.Close();
        })
        .Connect();
    }
Ejemplo n.º 33
0
 public override ITrackableBlock InitializeFromJSON(Players.Player player, JSONNode node)
 {
     InitializeJob(player, (Vector3Int)node["position"], node.GetAs <int>("npcID"));
     return(this);
 }
Ejemplo n.º 34
0
 public static JSONNode Parse(string aJSON)
 {
     return(JSONNode.Parse(aJSON));
 }
Ejemplo n.º 35
0
    void loadJsonJoints(JSONNode jsonJoints)
    {
        int JointCount = 0;

        for (int i = 0, numberOfJoints = jsonJoints.Count; i < numberOfJoints; i++)
        {
            JSONNode jsonJoint = jsonJoints[i];
            int      jointType = jsonJoint["jointType"].AsInt;

            GameObject bodyA = loadedObjects[jsonJoint["bodyA"].AsInt];
            GameObject bodyB = loadedObjects[jsonJoint["bodyB"].AsInt];

            JSONNode localAnchorA     = jsonJoint["localAnchorA"];
            Vector2  anchorA          = new Vector2(localAnchorA[0].AsFloat / RATIO, -localAnchorA[1].AsFloat / RATIO);
            JSONNode localAnchorB     = jsonJoint["localAnchorB"];
            Vector2  anchorB          = new Vector2(localAnchorB[0].AsFloat / RATIO, -localAnchorB[1].AsFloat / RATIO);
            bool     collideConnected = jsonJoint["collideConnected"].AsBool;
            string   userData         = jsonJoint["userData"].Value;

            if (jointType == (int)JointTypes.JOINT_DISTANCE || jointType == (int)JointTypes.JOINT_ROPE)
            {
                DistanceJoint2D joint = bodyA.AddComponent <DistanceJoint2D>();
                joint.connectedBody   = bodyB.GetComponent <Rigidbody2D>();
                joint.anchor          = anchorA;
                joint.connectedAnchor = anchorB;

                // distance joint
                if (jsonJoint["length"] != null)
                {
                    joint.distance        = jsonJoint["length"].AsFloat / RATIO;
                    joint.maxDistanceOnly = true;
                }
                // rope joint
                else if (jsonJoint["maxLength"] != null)
                {
                    joint.distance = jsonJoint["maxLength"].AsFloat / RATIO;
                }

                joint.enableCollision = collideConnected;
                joint.name           += '_';
                joint.name           += userData.Length > 0 ? userData : "joint" + JointCount++;
            }
            else if (jointType == (int)JointTypes.JOINT_REVOLUTE)
            {
                HingeJoint2D joint = bodyA.AddComponent <HingeJoint2D>();
                joint.connectedBody   = bodyB.GetComponent <Rigidbody2D>();
                joint.anchor          = anchorA;
                joint.connectedAnchor = anchorB;
                joint.enableCollision = collideConnected;
                joint.name           += '_';
                joint.name           += userData.Length > 0 ? userData : "joint" + JointCount++;

                // limits are not working properly
                bool  enableLimits       = jsonJoint["enableLimit"].AsBool;
                float referenceAngle     = -jsonJoint["referenceAngle"].AsFloat;
                float angleBetweenBodies = Mathf.Atan2(bodyB.transform.position.y - bodyA.transform.position.y,
                                                       bodyB.transform.position.x - bodyA.transform.position.x) * 180 / Mathf.PI;
                float upperAngle     = -jsonJoint["lowerAngle"].AsFloat;
                float lowerAngle     = -jsonJoint["upperAngle"].AsFloat;
                bool  enableMotor    = jsonJoint["enableMotor"].AsBool;
                float motorSpeed     = -jsonJoint["motorSpeed"].AsFloat;
                float maxMotorTorque = jsonJoint["maxMotorTorque"].AsFloat;

                joint.useLimits = enableLimits;
                JointAngleLimits2D limits = new JointAngleLimits2D();
                limits.max     = angleBetweenBodies + upperAngle;
                limits.min     = angleBetweenBodies + lowerAngle;
                joint.limits   = limits;
                joint.useMotor = enableMotor;
                JointMotor2D motor = new JointMotor2D();
                motor.maxMotorTorque = maxMotorTorque;
                motor.motorSpeed     = motorSpeed;
                joint.motor          = motor;
            }
            else if (jointType == (int)JointTypes.JOINT_WHEEL)
            {
                WheelJoint2D joint = bodyA.AddComponent <WheelJoint2D>();
                joint.connectedBody   = bodyB.GetComponent <Rigidbody2D>();
                joint.anchor          = anchorA;
                joint.connectedAnchor = anchorB;
                joint.enableCollision = collideConnected;
                joint.name           += '_';
                joint.name           += userData.Length > 0 ? userData : "joint" + JointCount++;

                bool     enableMotor    = jsonJoint["enableMotor"].AsBool;
                float    motorSpeed     = -jsonJoint["motorSpeed"].AsFloat;
                float    maxMotorTorque = jsonJoint["maxMotorTorque"].AsFloat;
                float    dampingRatio   = jsonJoint["dampingRatio"].AsFloat;
                float    frequency      = jsonJoint["frequencyHZ"].AsFloat;
                JSONNode localAxisA     = jsonJoint["localAxisA"];
                float    angle          = Mathf.Atan2(-localAxisA[1].AsFloat, localAxisA[0].AsFloat) * 180 / Mathf.PI;

                joint.useMotor = enableMotor;
                JointMotor2D motor = new JointMotor2D();
                motor.maxMotorTorque = maxMotorTorque;
                motor.motorSpeed     = motorSpeed;
                joint.motor          = motor;

                JointSuspension2D suspension = new JointSuspension2D();
                suspension.dampingRatio = dampingRatio;
                suspension.frequency    = frequency;
                suspension.angle        = angle;
                joint.suspension        = suspension;
            }
            else if (jointType == (int)JointTypes.JOINT_PRISMATIC)
            {
                SliderJoint2D joint = bodyA.AddComponent <SliderJoint2D>();
                joint.connectedBody   = bodyB.GetComponent <Rigidbody2D>();
                joint.anchor          = anchorA;
                joint.connectedAnchor = anchorB;
                joint.enableCollision = collideConnected;
                joint.name           += '_';
                joint.name           += userData.Length > 0 ? userData : "joint" + JointCount++;

                bool     enableLimits     = jsonJoint["enableLimit"].AsBool;
                float    referenceAngle   = -jsonJoint["referenceAngle"].AsFloat;
                float    upperTranslation = jsonJoint["upperTranslation"].AsFloat / RATIO;
                float    lowerTranslation = jsonJoint["lowerTranslation"].AsFloat / RATIO;
                bool     enableMotor      = jsonJoint["enableMotor"].AsBool;
                float    motorSpeed       = -jsonJoint["motorSpeed"].AsFloat;
                float    maxMotorTorque   = jsonJoint["maxMotorTorque"].AsFloat;
                JSONNode localAxisA       = jsonJoint["localAxisA"];
                float    angle            = Mathf.Atan2(-localAxisA[1].AsFloat, localAxisA[0].AsFloat) * 180 / Mathf.PI;

                joint.useLimits = enableLimits;
                JointTranslationLimits2D limits = new JointTranslationLimits2D();
                limits.max     = upperTranslation;
                limits.min     = lowerTranslation;
                joint.limits   = limits;
                joint.useMotor = enableMotor;
                JointMotor2D motor = new JointMotor2D();
                motor.maxMotorTorque = maxMotorTorque;
                motor.motorSpeed     = motorSpeed;
                joint.motor          = motor;
                joint.angle          = angle;
            }
        }
    }
Ejemplo n.º 36
0
    List <Fixture> loadJsonFixtures(JSONNode jsonFixtures)
    {
        List <Fixture> fixtures = new List <Fixture>();

        for (int i = 0, numberOfFixtures = jsonFixtures.Count; i < numberOfFixtures; i++)
        {
            JSONNode jsonFixture = jsonFixtures[i];

            float density     = jsonFixture["density"].AsFloat;
            float friction    = jsonFixture["friction"].AsFloat;
            float restitution = jsonFixture["restitution"].AsFloat;
            bool  isSensor    = jsonFixture["isSensor"].AsBool;

            JSONNode jsonShapes = jsonFixture["shapes"];
            for (int j = 0, numberOfShapes = jsonShapes.Count; j < numberOfShapes; j++)
            {
                JSONNode jsonShape = jsonShapes[j];

                JSONNode pos       = jsonShape["position"];
                Vector2  position  = new Vector2(pos[0].AsFloat / RATIO, -pos[1].AsFloat / RATIO);
                int      shapeType = jsonShape["type"].AsInt;

                Fixture fixture = new Fixture();
                fixture.physicsMaterial            = new PhysicsMaterial2D();
                fixture.physicsMaterial.friction   = friction;
                fixture.physicsMaterial.bounciness = restitution;
                fixture.density = density;

                if (shapeType == (int)ShapeTypes.SHAPE_BOX)
                {
                    float width  = jsonShape["width"].AsFloat / RATIO;
                    float height = jsonShape["height"].AsFloat / RATIO;
                    fixture.shapeType = (int)ShapeTypes.SHAPE_BOX;
                    fixture.size      = new Vector2(width, height);
                    fixture.offset    = position;
                }
                else if (shapeType == (int)ShapeTypes.SHAPE_CIRCLE)
                {
                    float radius = 2 * jsonShape["radius"].AsFloat / RATIO;
                    fixture.shapeType = (int)ShapeTypes.SHAPE_CIRCLE;
                    fixture.size      = new Vector2(radius, radius);
                    fixture.offset    = position;
                }
                else if (shapeType == (int)ShapeTypes.SHAPE_POLYGON)
                {
                    JSONNode jsonVertices = jsonShape["vertices"];
                    fixture.vertices = new Vector2[jsonVertices.Count];
                    for (int k = 0, numberOfVertices = jsonVertices.Count; k < numberOfVertices; k++)
                    {
                        fixture.vertices[k] = new Vector2(jsonVertices[k][0].AsFloat / RATIO,
                                                          -jsonVertices[k][1].AsFloat / RATIO);
                    }
                    fixture.shapeType = (int)ShapeTypes.SHAPE_POLYGON;
                    fixture.offset    = position;
                }
                else if (shapeType == (int)ShapeTypes.SHAPE_CHAIN)
                {
                    JSONNode jsonVertices = jsonShape["vertices"];
                    fixture.vertices = new Vector2[jsonVertices.Count];
                    for (int k = 0, numberOfVertices = jsonVertices.Count; k < numberOfVertices; k++)
                    {
                        fixture.vertices[k] = new Vector2(jsonVertices[k][0].AsFloat / RATIO,
                                                          -jsonVertices[k][1].AsFloat / RATIO);
                    }
                    fixture.shapeType = (int)ShapeTypes.SHAPE_CHAIN;
                    fixture.offset    = position;
                }
                fixture.isTrigger = isSensor;
                fixtures.Add(fixture);
            }
        }

        return(fixtures);
    }
Ejemplo n.º 37
0
 public static JSONNode Parse(string aJSON)
 {
     return(JSONNode.Parse(new JSONStringParseData(aJSON)));
 }
Ejemplo n.º 38
0
 public Int32Msg(JSONNode msg)
 {
     _data = msg["data"].AsInt;
 }
Ejemplo n.º 39
0
 public new static ROSBridgeMsg ParseMessage(JSONNode msg)
 {
     return(new GuiNotificationMsg(msg));
 }
    public void SetId(SocketIOEvent obj)
    {
        var data = JSONNode.Parse(obj.data.ToString());

        socket_id = data["ID"].ToString().Replace("\"", "");
    }
Ejemplo n.º 41
0
 public static JSONNode ParseIosReceipt(byte[] bytes)
 {
     return(JSONNode.Parse(new JSONBytesParseData(bytes), true));
 }
Ejemplo n.º 42
0
        static ItemTypesServer.ItemTypeRaw RotatedTypeLit(string name, string suffix, string sideType, JSONNode copy)
        {
            if (copy.HasChild("torches"))
            {
                if (copy["torches"].HasChild("a"))
                {
                    RotateOffset(copy["torches"]["a"], suffix);
                }
                if (copy["torches"].HasChild("b"))
                {
                    RotateOffset(copy["torches"]["b"], suffix);
                }
            }

            return(new ItemTypesServer.ItemTypeRaw(
                       name + suffix,
                       new JSONNode()
                       .SetAs("parentType", name)
                       .SetAs("side" + suffix, sideType)
                       .SetAs("customData", copy)
                       ));
        }
Ejemplo n.º 43
0
        static void ItemRotator(Dictionary <string, ItemTypesServer.ItemTypeRaw> items, RotatorSettings settings, JSONNode customDataLitOnly)
        {
            ItemTypesServer.ItemTypeRaw unlitXP = RotatedTypeUnlit(settings.BaseType.name, "x+", settings.rotatedSideUnlit);
            ItemTypesServer.ItemTypeRaw unlitXN = RotatedTypeUnlit(settings.BaseType.name, "x-", settings.rotatedSideUnlit);
            ItemTypesServer.ItemTypeRaw unlitZP = RotatedTypeUnlit(settings.BaseType.name, "z+", settings.rotatedSideUnlit);
            ItemTypesServer.ItemTypeRaw unlitZN = RotatedTypeUnlit(settings.BaseType.name, "z-", settings.rotatedSideUnlit);

            settings.BaseType.description
            .SetAs("isRotatable", true)
            .SetAs("rotatablex+", unlitXP.name)
            .SetAs("rotatablex-", unlitXN.name)
            .SetAs("rotatablez+", unlitZP.name)
            .SetAs("rotatablez-", unlitZN.name);
            if (settings.sideTopUnlit != null)
            {
                settings.BaseType.description.SetAs("sidey+", settings.sideTopUnlit);
            }

            items[unlitXP.name]           = unlitXP;
            items[unlitXN.name]           = unlitXN;
            items[unlitZP.name]           = unlitZP;
            items[unlitZN.name]           = unlitZN;
            items[settings.BaseType.name] = settings.BaseType;


            if (customDataLitOnly != null)
            {
                string litBaseName = settings.BaseType.name + "lit";

                ItemTypesServer.ItemTypeRaw litXP = RotatedTypeLit(litBaseName, "x+", settings.rotatedSideLit, customDataLitOnly.DeepClone());
                ItemTypesServer.ItemTypeRaw litXN = RotatedTypeLit(litBaseName, "x-", settings.rotatedSideLit, customDataLitOnly.DeepClone());
                ItemTypesServer.ItemTypeRaw litZP = RotatedTypeLit(litBaseName, "z+", settings.rotatedSideLit, customDataLitOnly.DeepClone());
                ItemTypesServer.ItemTypeRaw litZN = RotatedTypeLit(litBaseName, "z-", settings.rotatedSideLit, customDataLitOnly.DeepClone());

                ItemTypesServer.ItemTypeRaw baseLitType = new ItemTypesServer.ItemTypeRaw(
                    litBaseName,
                    new JSONNode()
                    .SetAs("parentType", settings.BaseType.name)
                    .SetAs("isRotatable", true)
                    .SetAs("rotatablex+", litXP.name)
                    .SetAs("rotatablex-", litXN.name)
                    .SetAs("rotatablez+", litZP.name)
                    .SetAs("rotatablez-", litZN.name)
                    .SetAs("sidey+", settings.sideTopLit)
                    );

                items[litXP.name]       = litXP;
                items[litXN.name]       = litXN;
                items[litZP.name]       = litZP;
                items[litZN.name]       = litZN;
                items[baseLitType.name] = baseLitType;

                RegisteringChangeTypes.Add(() =>
                                           ItemTypesServer.RegisterChangeTypes(settings.BaseType.name, new List <string>()
                {
                    litXP.name, litXN.name, litZP.name, litZN.name,
                    unlitXP.name, unlitXN.name, unlitZP.name, unlitZN.name
                })
                                           );
            }
            else
            {
                RegisteringChangeTypes.Add(() =>
                                           ItemTypesServer.RegisterChangeTypes(settings.BaseType.name, new List <string>()
                {
                    unlitXP.name, unlitXN.name, unlitZP.name, unlitZN.name
                })
                                           );
            }
        }
Ejemplo n.º 44
0
    // Update is called once per frame
    void OnInspectorUpdate()
    {
        Repaint();
        float currentTimeSecond = convertToSeconds(DateTime.Now);

        if (access_token.Length > 0 && currentTimeSecond - lastTokenTime > expiresIn)
        {
            access_token = "";
            relog();
        }

        if (publisher != null && publisher.www != null && publisher.www.isDone)
        {
            state = publisher.getState();
            www   = publisher.www;
            switch (state)
            {
            case ExporterState.CHECK_VERSION:
                JSONNode githubResponse = JSON.Parse(this.jsonify(www.text));
                if (githubResponse != null && githubResponse[0]["tag_name"] != null)
                {
                    latestVersion = githubResponse[0]["tag_name"];
                    if (exporterVersion != latestVersion)
                    {
                        bool update = EditorUtility.DisplayDialog("Exporter update", "A new version is available \n(you have version " + exporterVersion + ")\nIt's strongly rsecommended that you update now. The latest version may include important bug fixes and improvements", "Update", "Skip");
                        if (update)
                        {
                            Application.OpenURL(latestReleaseUrl);
                        }
                    }
                    else
                    {
                        resizeWindow(fullSize);
                    }
                }
                else
                {
                    latestVersion = "";
                    resizeWindow(fullSize + new Vector2(0, 15));
                }
                publisher.setIdle();
                break;

            case ExporterState.REQUEST_CODE:
                JSONNode accessResponse = JSON.Parse(this.jsonify(www.text));
                if (accessResponse["access_token"] != null)
                {
                    access_token  = accessResponse["access_token"];
                    expiresIn     = accessResponse["expires_in"].AsFloat;
                    lastTokenTime = convertToSeconds(DateTime.Now);
                    publisher.getAccountType(access_token);
                    if (exporterVersion != latestVersion)
                    {
                        resizeWindow(fullSize + new Vector2(0, 20));
                    }
                    else
                    {
                        resizeWindow(fullSize);
                    }
                }
                else
                {
                    string errorDesc = accessResponse["error_description"];
                    EditorUtility.DisplayDialog("Authentication failed", "Failed to authenticate on Sketchfab.com.\nPlease check your credentials\n\nError: " + errorDesc, "Ok");
                    publisher.setIdle();
                }

                break;

            case ExporterState.PUBLISH_MODEL:
                //foreach(string key in www.responseHeaders.Keys)
                //{
                //    Debug.Log("[" + key + "] = " + www.responseHeaders[key]);
                //}
                if (www.responseHeaders["STATUS"].Contains("201") == true)
                {
                    string urlid = www.responseHeaders["LOCATION"].Split('/')[www.responseHeaders["LOCATION"].Split('/').Length - 1];
                    string url   = skfbUrl + "models/" + urlid;
                    Application.OpenURL(url);
                }
                else
                {
                    EditorUtility.DisplayDialog("Upload failed", www.responseHeaders["STATUS"], "Ok");
                }
                publisher.setIdle();
                break;

            case ExporterState.GET_CATEGORIES:
                string jsonify = this.jsonify(www.text);
                if (!jsonify.Contains("results"))
                {
                    Debug.Log(jsonify);
                    Debug.Log("Failed to retrieve categories");
                    publisher.setIdle();
                    break;
                }

                JSONArray categoriesArray = JSON.Parse(jsonify)["results"].AsArray;
                foreach (JSONNode node in categoriesArray)
                {
                    categories.Add(node["name"], node["slug"]);
                    categoriesNames.Add(node["name"]);
                }
                publisher.setIdle();
                break;

            case ExporterState.USER_ACCOUNT_TYPE:
                string accountRequest = this.jsonify(www.text);
                if (!accountRequest.Contains("account"))
                {
                    Debug.Log(accountRequest);
                    Debug.Log("Failed to retrieve user account type");
                    publisher.setIdle();
                    break;
                }

                var userSettings = JSON.Parse(accountRequest);
                isUserPro       = userSettings["account"].ToString().Contains("free") == false;
                userDisplayName = userSettings["displayName"];
                publisher.setIdle();
                break;
            }
        }
    }
Ejemplo n.º 45
0
    void loadJsonBodies(JSONNode jsonBodies)
    {
        int BodyCount = 0;

        for (int i = 0, numberOfBodies = jsonBodies.Count; i < numberOfBodies; i++)
        {
            JSONNode jsonBody = jsonBodies[i];

            int      bodyType        = jsonBody["type"].AsInt;
            JSONNode pos             = jsonBody["position"];
            Vector3  position        = new Vector3(pos[0].AsFloat / RATIO, -pos[1].AsFloat / RATIO, 0);
            float    rotation        = -jsonBody["rotation"].AsFloat;
            float    linearDamping   = jsonBody["linearDamping"].AsFloat;
            float    angularDamping  = jsonBody["angularDamping"].AsFloat;
            string   userData        = jsonBody["userData"].Value;
            bool     isFixedRotation = jsonBody["isFixedRotation"].AsBool;
            bool     isBullet        = jsonBody["isBullet"].AsBool;


            GameObject body = new GameObject(userData.Length > 0 ? userData : "body" + BodyCount++);
            body.transform.position = position;
            body.transform.rotation = Quaternion.Euler(0, 0, rotation);
            body.AddComponent <DebugRenderer>();

            float          density  = 0;
            List <Fixture> fixtures = loadJsonFixtures(jsonBody["fixtures"]);
            for (int j = 0, numberOfFixtures = fixtures.Count; j < numberOfFixtures; j++)
            {
                Fixture fixture = fixtures[j];
                density += fixture.density;
                if (fixture.shapeType == (int)ShapeTypes.SHAPE_BOX)
                {
                    BoxCollider2D boxCollider = body.AddComponent <BoxCollider2D>();
                    boxCollider.isTrigger      = fixture.isTrigger;
                    boxCollider.offset         = fixture.offset;
                    boxCollider.size           = fixture.size;
                    boxCollider.sharedMaterial = fixture.physicsMaterial;
                }
                else if (fixture.shapeType == (int)ShapeTypes.SHAPE_CIRCLE)
                {
                    CircleCollider2D circleCollider = body.AddComponent <CircleCollider2D>();
                    circleCollider.isTrigger      = fixture.isTrigger;
                    circleCollider.offset         = fixture.offset;
                    circleCollider.radius         = fixture.size.x;
                    circleCollider.sharedMaterial = fixture.physicsMaterial;
                }
                else if (fixture.shapeType == (int)ShapeTypes.SHAPE_POLYGON)
                {
                    PolygonCollider2D polyCollider = body.AddComponent <PolygonCollider2D>();
                    polyCollider.isTrigger = fixture.isTrigger;
                    polyCollider.offset    = fixture.offset;
                    polyCollider.SetPath(0, fixture.vertices);
                    polyCollider.sharedMaterial = fixture.physicsMaterial;
                }
                else if (fixture.shapeType == (int)ShapeTypes.SHAPE_CHAIN)
                {
                    EdgeCollider2D edgeCollider = body.AddComponent <EdgeCollider2D>();
                    edgeCollider.isTrigger      = fixture.isTrigger;
                    edgeCollider.offset         = fixture.offset;
                    edgeCollider.points         = fixture.vertices;
                    edgeCollider.sharedMaterial = fixture.physicsMaterial;
                }
            }

            body.AddComponent <Rigidbody2D>();
            Rigidbody2D rigidBody2D = body.GetComponent <Rigidbody2D>();
            rigidBody2D.isKinematic = bodyType == 1 || bodyType == 0;
            rigidBody2D.fixedAngle  = isFixedRotation;
            rigidBody2D.mass        = density;
            rigidBody2D.angularDrag = angularDamping;
            rigidBody2D.drag        = linearDamping;

            if (isBullet)
            {
                rigidBody2D.collisionDetectionMode = CollisionDetectionMode2D.Continuous;
            }
            else
            {
                rigidBody2D.collisionDetectionMode = CollisionDetectionMode2D.None;
            }

            loadedObjects.Add(body);
        }
    }
Ejemplo n.º 46
0
 public static JSONNode Parse(byte[] bytes)
 {
     return(JSONNode.Parse(new JSONBytesParseData(bytes)));
 }
Ejemplo n.º 47
0
    List <GameObject> buttonList = new List <GameObject>();   // list with buttons -for reseting-

    //	 Builder Function
    public void DrawOnList(JSONNode N, string listType)
    {
        // vars
        int        itemCount   = N.Count;
        int        columnCount = 1;
        GameObject itemPrefab  = null;

        // *******************************
        //      Button Prefab Selector
        // *******************************
        switch (listType)
        {
        // show the full list of game
        case "fullOnlineList":
            itemPrefab = downloadGameButton;
            break;

        // show the downloaded games list
        case "downloadedList":
            itemPrefab = loadGameButton;
            break;

        case "availableClasses":
            itemPrefab = availableClassesButton;
            break;

        case "SubscribedClasses":
            itemPrefab = availableClassesButton;
            break;
        }

        // clean list before drawing another on
        foreach (GameObject b in buttonList)
        {
            Destroy(b);
        }

        // Get the prefab transform and the container transform
        RectTransform rowRectTransform       = itemPrefab.GetComponent <RectTransform>();
        RectTransform containerRectTransform = gameObject.GetComponent <RectTransform>();
        // calculate the width and height of each child item.
        float width  = containerRectTransform.rect.width / columnCount;
        float ratio  = width / rowRectTransform.rect.width;
        float height = rowRectTransform.rect.height * ratio;
        // set how many rows it will have based on the number of itens and the number of columns
        int rowCount = itemCount / columnCount;

        if (itemCount % rowCount > 0)
        {
            rowCount++;
        }
        //adjust the height of the container so that it will just barely fit all its children
        float scrollHeight = height * rowCount;

        containerRectTransform.offsetMin = new Vector2(containerRectTransform.offsetMin.x, -scrollHeight / 2);
        containerRectTransform.offsetMax = new Vector2(containerRectTransform.offsetMax.x, scrollHeight / 2);


        // load downloaded games
        JSONNode downloadedGames = AssetManager.singleton.LoadGamesData();

        for (int i = 0, j = 0; i < itemCount; i++)
        {
            // If the amount of itens placed are a multiple of columnCount, jump to the nex row
            if (i % columnCount == 0)
            {
                j++;
            }
            // Create a new item, name it, and set the parent
            GameObject newItem = Instantiate(itemPrefab) as GameObject;
            newItem.name = gameObject.name + " item at (" + i + "," + j + ")";
            newItem.transform.SetParent(gameObject.transform);
            buttonList.Add(newItem);

            // *******************************
            //        newItem Customizer
            // *******************************

            // *******************************************
            // Customize newItem for Full Online Game List
            if (listType.Equals("fullOnlineList"))
            {
                Text[]   Textos     = newItem.GetComponentsInChildren <Text>();
                Button[] ButtonList = newItem.GetComponentsInChildren <Button>(true);
                // Deactivate DeleteButton by default
                ButtonList[1].gameObject.SetActive(false);
                string GameID = N[i]["gameID"].Value;
                // Set newItem Texts
                Textos[0].text = N[i]["gameName"].Value;
                Textos[1].text = "<b>Description:</b> " + N[i]["description"].Value;
                // Add Download Game and Delete Game Listener
                ButtonList[0].onClick.AddListener(() => DownloadGame(GameID, ButtonList));
                ButtonList[1].onClick.AddListener(() => DeleteGame(GameID, ButtonList));
                // check if the game was already downloaded
                // and set it as downloaded
                if (downloadedGames != null)
                {
                    for (int k = 0; k < downloadedGames.Count; k++)
                    {
                        if (downloadedGames[k]["gameID"].AsInt == N[i]["gameID"].AsInt)
                        {
                            ButtonList[0].gameObject.SetActive(false);
                            ButtonList[1].gameObject.SetActive(true);
                        }
                    }
                }
            }

            // ******************************************
            // Customize newItem for Downloaded Game List
            if (listType.Equals("downloadedList"))
            {
                Text[] Textos = newItem.GetComponentsInChildren <Text>();
                // Set newItem Texts
                Textos[0].text = N[i]["gameName"].Value;
                Textos[1].text = "<b>Description:</b> " + N[i]["description"].Value;
                JSONNode gamedata = N[i];                        // still no ideia, braw
                newItem.GetComponentInChildren <Button>()
                .onClick.AddListener(() => LoadGame(gamedata));
            }

            // ******************************************
            // Customize newItem for AvailableClasses
            if (listType.Equals("availableClasses"))
            {
                Text[] Textos  = newItem.GetComponentsInChildren <Text>();
                string classID = N[i]["classID"].Value;
                // Set newItem Texts
                Textos[0].text = N[i]["className"].Value;
                Textos[1].text = "Professor: " + N[i]["professor"]["fullName"].Value;
                Textos[2].text = "Class Description: " + N[i]["classDescription"].Value;
                newItem.GetComponentInChildren <Button>()
                .onClick.AddListener(() => CGR_subscribeToClass(classID));
            }

            // ******************************************
            // Customize newItem for Subscribed Classes
            if (listType.Equals("SubscribedClasses"))
            {
                Text[] Textos        = newItem.GetComponentsInChildren <Text>();
                string gameReference = N[i]["gameReference"].Value;
                string gameEntry     = N[i]["gameEntryID"].Value;
                // Set newItem Texts
                Textos[0].text = N[i]["classe"]["className"].Value;
                Textos[1].text = "Professor: " + N[i]["classe"]["professor"]["fullName"].Value;
                Textos[2].text = "Game name: " + N[i]["gameName"].Value;
                newItem.GetComponentInChildren <Button>()
                .onClick.AddListener(() => CGR_LoadGame(gameReference, gameEntry));
            }

            // *******************************
            //    End of newItem Customizer
            // *******************************

            // move and size the new item
            RectTransform rectTransform = newItem.GetComponent <RectTransform>();
            float         x             = -containerRectTransform.rect.width / 2 + width * (i % columnCount);
            float         y             = containerRectTransform.rect.height / 2 - height * j;
            rectTransform.offsetMin = new Vector2(x, y);
            x = rectTransform.offsetMin.x + width;
            y = rectTransform.offsetMin.y + height;
            rectTransform.offsetMax = new Vector2(x, y);
            rectTransform.sizeDelta.Set(0, 0);
        }
        // activate scrollbar
        scrollbar.SetActive(true);
    }
Ejemplo n.º 48
0
 //********************************************//
 //           Button Callbacks
 //********************************************//
 // Load a Game Callback
 void LoadGame(JSONNode gamedata)
 {
     Transition.singleton.FadeOutTo("BattleScene"); // set the loader
     PersistData.singleton.CurrentGame = gamedata;  // save gamedata
 }
Ejemplo n.º 49
0
 public new static ROSBridgeMsg ParseMessage(JSONNode msg)
 {
     return(new ObjInstanceMsg(msg));
 }
Ejemplo n.º 50
0
    public ShipData()
    {
        JSONNode json;

        if (!initMainData)
        {
            initMainData = true;
            Sprite[] sprites;
            sprites = Resources.LoadAll <Sprite>("textures/devices");
            for (int i = 0; i < sprites.Length; i++)
            {
                if (sprites[i].name.IndexOf("mainShip") > -1)
                {
                    string s = sprites[i].name.Remove(0, 8);
                    tiles.Add(int.Parse(s), sprites[i]);
                }
                if (sprites[i].name.IndexOf("pirateShip") > -1)
                {
                    string s = sprites[i].name.Remove(0, 10);
                    tilesPirate.Add(int.Parse(s), sprites[i]);
                }
            }
            tileResource = Resources.Load("Tile") as GameObject;

            json = JSONNode.Parse(Resources.Load <TextAsset>("Data/Devices").text)["devices"];
            for (int i = 0; i < json.Count; i++)
            {
                int id = int.Parse(json.AsObject.keyAt(i));
                devices.Add(id, new DeviceData(id, json[i]));
            }

            json = JSONNode.Parse(Resources.Load <TextAsset>("Data/MainShip").text);
            for (int i = 0; i < json["ship"].Count; i++)
            {
                ship.Add(new TilePoint(json["ship"][i]["x"].AsInt, json["ship"][i]["y"].AsInt), new DeviceData(json["ship"][i]["device"]["id"].AsInt, json["ship"][i]["device"]));
            }

            json = JSONNode.Parse(Resources.Load <TextAsset>("Data/Enemies").text)["enemies"];
            for (int i = 0; i < json.Count; i++)
            {
                enemyShips.Add(json.AsObject.keyAt(i), new EnemyData(json[i]));
            }
        }


        levels = new Dictionary <int, LevelData>();
        json   = JSONNode.Parse(Resources.Load <TextAsset>("Data/EnemyWaves").text)["levels"];
        for (int i = 0; i < json.Count; i++)
        {
            int id = int.Parse(json.AsObject.keyAt(i));
            levels.Add(id, new LevelData(json[i]));
        }
        levelCount = levels.Count;

        json           = JSONNode.Parse(Resources.Load <TextAsset>("Data/MainShip").text);
        knowledge      = json["properties"]["knowledge"].AsInt;
        scraps         = json["properties"]["scraps"].AsInt;
        scrapInventory = json["properties"]["scrapInventory"].AsInt;
        metals         = json["properties"]["metals"].AsInt;
        metalPrice     = json["properties"]["metalPrice"].AsInt;

        Gui.UpdateScraps();
        Gui.UpdateMetals();
        Gui.UpdateKnowledge();

        mainShip = HexaShip.createShip(ship, Vector3.zero);

        loadLevel(1);
    }
Ejemplo n.º 51
0
 public new static ROSBridgeMsg ParseMessage(JSONNode msg)
 {
     return(new TFSubscriptionActionFeedbackMsg(msg));
 }
Ejemplo n.º 52
0
 public static ROSBridgeMsg ParseMessage(JSONNode msg)
 {
     return(new TFMessageMsg(msg));
 }
Ejemplo n.º 53
0
 public new static ROSBridgeMsg ParseMessage(JSONNode msg)
 {
     return(new LearningRequestActionResultMsg(msg));
 }
Ejemplo n.º 54
0
 public static ROSBridgeMsg ParseMessage(JSONNode msg)
 {
     return(new TFSubscriptionActionGoalMsg(msg));
 }
Ejemplo n.º 55
0
 public void AddModifier(string id, JSONNode modifier)
 {
     statsModifiers[id] = modifier;
     SetDirtyAfterSetModifier(modifier);
 }
Ejemplo n.º 56
0
 public new static ROSBridgeMsg ParseMessage(JSONNode msg)
 {
     return(new CollisionObjectsMsg(msg));
 }
Ejemplo n.º 57
0
 public void AddModifier(string id, JSONNode modifier, object source)
 {
     AddModifier(id, modifier);
     statsModifiersSources[source] = id;
 }
Ejemplo n.º 58
0
		protected virtual void parseSuccessResult(JSONNode __result) {
			// Extend
		}
Ejemplo n.º 59
0
    // TODO: Get rid of hard coded default values.
    private void ConstructGradient(JSONNode legendSpecs, ref ChannelEncoding channelEncoding)
    {
        colorLine = gameObject.GetComponentInChildren <LineRenderer>(true);

        bool       addTicks   = false;
        Transform  ticks      = gameObject.transform.Find("Ticks");
        GameObject tickPrefab = null;

        if (ticks != null)
        {
            addTicks = true;
            ticks.gameObject.SetActive(true);
            tickPrefab = Resources.Load("Legend/LegendTick") as GameObject;
        }

        if (colorLine == null)
        {
            throw new Exception("Cannot find ColorLine LineRenderer object in legend.");
        }

        colorLine.gameObject.SetActive(true);
        colorLine.material = new Material(Shader.Find("Sprites/Default"));

        float width  = 0.2f;
        float height = 0.05f;

        if (legendSpecs["gradientWidth"] == null || legendSpecs["gradientHeight"] == null)
        {
            width  = legendSpecs["gradientWidth"].AsFloat * DxR.Vis.SIZE_UNIT_SCALE_FACTOR;
            height = legendSpecs["gradientHeight"].AsFloat * DxR.Vis.SIZE_UNIT_SCALE_FACTOR;
        }

        List <Vector3>          positionsList = new List <Vector3>();
        List <GradientColorKey> colorKeyList  = new List <GradientColorKey>();
        List <GradientAlphaKey> alphaKeyList  = new List <GradientAlphaKey>();

        float alpha       = 1.0f;
        int   domainCount = channelEncoding.scale.domain.Count;

        for (int i = 0; i < domainCount; i++)
        {
            float pct = channelEncoding.scale.GetDomainPct(channelEncoding.scale.domain[i]);
            positionsList.Add(new Vector3(width * pct, 0.0f, 0.0f));
            Color col;
            ColorUtility.TryParseHtmlString(channelEncoding.scale.range[i], out col);
            colorKeyList.Add(new GradientColorKey(col, pct));
            alphaKeyList.Add(new GradientAlphaKey(alpha, pct));

            if (addTicks && tickPrefab != null)
            {
                GameObject tick = Instantiate(tickPrefab, ticks.transform.position, ticks.transform.rotation, ticks.transform);

                Vector3 pos = Vector3.zero;
                pos.x = width * pct;
                pos.y = 0.04f;             // TODO: Get this from text size.
                tick.transform.Translate(pos);

                tick.GetComponent <TextMesh>().text = channelEncoding.scale.domain[i];
            }
        }

        colorLine.positionCount = positionsList.Count;
        colorLine.SetPositions(positionsList.ToArray());
        colorLine.startWidth = height;
        colorLine.endWidth   = height;

        Gradient gradient = new Gradient();

        gradient.SetKeys(colorKeyList.ToArray(), alphaKeyList.ToArray());
        colorLine.colorGradient = gradient;

        colorLine.transform.parent = gameObject.transform;

        gameObject.GetComponent <HoloToolkit.Unity.Collections.ObjectCollection>().Rows       = 3;      // TODO: Update this if no ticks are shown.
        gameObject.GetComponent <HoloToolkit.Unity.Collections.ObjectCollection>().CellHeight = 0.08f;
        gameObject.GetComponent <HoloToolkit.Unity.Collections.ObjectCollection>().UpdateCollection();
    }
Ejemplo n.º 60
0
 public new static ROSBridgeMsg ParseMessage(JSONNode msg)
 {
     return(new InterfaceStateMsg(msg));
 }