void Furnitures::loadJsonSheet(const std::string& jsonSheetPath, const double zoomX, const double zoomY)
 {
     Json::Reader jsonReader;
     Json::Value jsonRoot;
     ifstream jsonFile;
     
     jsonFile.open(jsonSheetPath.c_str(), ios::binary);
     if (jsonFile.is_open())
     {
         if (jsonReader.parse(jsonFile, jsonRoot))
         {
             for(Json::Value::iterator it = jsonRoot.begin(); it != jsonRoot.end(); it++)
             {
                 SDL_Rect rect;
                 rect = {(*it)["x"].asInt(), (*it)["y"].asInt(), (*it)["w"].asInt(), (*it)["h"].asInt()};
                 
                 if (zoomX != 1 && zoomY != 1)
                 {
                     rect.x *= zoomX;
                     rect.y *= zoomY;
                     rect.w *= zoomX;
                     rect.h *= zoomY;
                 }
                 
                 furnituresPixelDimensions.insert(make_pair(it.key().asString(), rect));
             }
         }
     }
     else
     {
         SDL_LogMessage(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_ERROR,
                        "Error reading Json SpriteSheet file in : %s because:", jsonSheetPath.c_str(), strerror( errno ));
         throw error::READ_SPRITESHEETS_JSON_FAIL;
     }
     
 }    
Exemplo n.º 2
0
  int load_config(const char *cfg_root)
  {
    Json::Value root;
    if (this->load_json_cfg(cfg_root, TIANFU_SKILL_UPGRADE_CFG_PATH, root) != 0)
      return -1;

    for(Json::Value::iterator iter = root.begin();
        iter != root.end();
        ++iter)
    {
      int lvl = ::atoi(iter.key().asCString());
      if (lvl > global_param_cfg::tianfu_lvl_limit)
        return -1;
      tianfu_skill_upgrade_cfg_obj *p = new tianfu_skill_upgrade_cfg_obj();
      this->upgrade_cfg_obj_map_.insert(lvl, p);

      p->cost_ = (*iter)["cost"].asInt();
      p->exp_  = (*iter)["exp"].asInt();
      p->item_cid_ = (*iter)["item_cid"].asInt();
      p->item_cnt_ = (*iter)["item_cnt"].asInt();
      p->item_exp_ = (*iter)["item_exp"].asInt();
    }
    return 0;
  }
Exemplo n.º 3
0
int gameplay_ctrl_db_proc::load_activity_data()
{
	ctrl_data::instance()->map_act_.clear();


    Json::Value root;
    Game_Data::Container_Mgr::instance()->get_json_value_by_file_name( root, ACTIVITY_CFG_FILE);

  for (Json::Value::iterator p = root.begin();
       p != root.end();
       p++)
  {
    //load each activity
    std::string s_act_id = p.key().asCString();
    activity *act = new activity;
    act->id_ = atoi(s_act_id.c_str());
  
    if (load_act_item(act,root[s_act_id]) == 0)
      gameplay_ctrl_data_mgr::load_act_item(act);
  }

  cout << "\n load activity data over----------------" << endl;
  return 0; 
}
Exemplo n.º 4
0
  int load_json(Json::Value &root, skill_cfg_obj *sco, const int skill_cid)
  {
    sco->skill_cid_ = skill_cid;
    sco->career_ = root["career"].asInt();
    sco->hurt_delay_ = root["hurt_delay"].asInt();
    Json::Value &detail_v = root["info"];
    if (detail_v.empty()) return -1;

    for (Json::Value::iterator iter = detail_v.begin();
         iter != detail_v.end();
         ++iter)
    {
      int i = ::atoi(iter.key().asCString());
      Json::Value &dv = *iter;
      if (!dv.empty())
      {
        if (i < 1 || i >= MAX_SKILL_LEVEL)
        {
          e_log->error("skill lvl is invalid! lvl = %d", i);
          return -1;
        }

        skill_detail *sd = new skill_detail();
        sd->cur_lvl_ = i;
        sco->details_[i] = sd;
        if (this->load_json(dv, sd) != 0)
          return -1;
      }
    }
    if (sco->get_detail(1) == NULL)
    {
      e_log->error("skill %d not found lvl 1 info!", skill_cid);
      return -1;
    }
    return 0;
  }
Exemplo n.º 5
0
bool CPhilipsHue::GetLights(const Json::Value &root)
{
	if (root["lights"].empty())
		return false;

	for (Json::Value::iterator iLight = root["lights"].begin(); iLight != root["lights"].end(); ++iLight)
	{
		Json::Value light = *iLight;
		if (light.isObject())
		{
			std::string szLID = iLight.key().asString();
			int lID = atoi(szLID.c_str());
			_tHueLight tlight;
			int BrightnessLevel = 0;
			tlight.level = 0;
			tlight.sat = 0;
			tlight.hue = 0;
			int tbri = 0;
			bool bIsOn = light["state"]["on"].asBool();
			bool bDoSend = true;
			_eHueLightType LType = HLTYPE_NORMAL;
			
			if (bIsOn)
			{
				tlight.cmd = light2_sOn;
			}
			else
				tlight.cmd = light2_sOff;
				
			if (!light["state"]["bri"].empty())
			{
				//Lamp with brightness control
				LType = HLTYPE_DIM;
				tbri = light["state"]["bri"].asInt();
				if ((tbri != 0) && (tbri != 255))
					tbri += 1; //hue reports 255 as 254
				tlight.level = tbri;
				BrightnessLevel = int((100.0f / 255.0f)*float(tbri));
				if (bIsOn)
				{
					tlight.cmd = (BrightnessLevel != 0) ? light2_sSetLevel : light2_sOn;
				}
				else
					tlight.cmd = light2_sOff;
			}
			if ((!light["state"]["sat"].empty()) && (!light["state"]["hue"].empty()))
			{
				//Lamp with hue/sat control
				LType = HLTYPE_RGBW;
				tlight.sat = light["state"]["sat"].asInt();
				tlight.hue = light["state"]["hue"].asInt();
				if (bIsOn)
				{
					tlight.cmd = (BrightnessLevel != 0) ? Limitless_SetBrightnessLevel : Limitless_LedOn;
				}
				else
					tlight.cmd = Limitless_LedOff;
			}
			if (m_lights.find(lID) != m_lights.end())
			{
				_tHueLight alight = m_lights[lID];
				if (
					(alight.cmd == tlight.cmd) &&
					(alight.level == tlight.level) &&
					(alight.sat == tlight.sat) &&
					(alight.hue == tlight.hue)
					)
				{
					bDoSend = false;
				}
			}
			m_lights[lID] = tlight;
			if (bDoSend)
			{
				InsertUpdateSwitch(lID, LType, bIsOn, BrightnessLevel, tlight.sat, tlight.hue, light["name"].asString(), "");
			}
		}
	}
	return true;
}
Exemplo n.º 6
0
bool Resource::Load()
{
	if (m_loaded)
		return true;

	Json::Reader reader;
	Json::Value data;

	std::string filename = "lang/" + m_name + "/" + m_langCode + ".json";
	RefCountedPtr<FileSystem::FileData> fd = FileSystem::gameDataFiles.ReadFile(filename);
	if (!fd) {
		Output("couldn't open language file '%s'\n", filename.c_str());
		return false;
	}

	if (!reader.parse(fd->GetData(), fd->GetData()+fd->GetSize(), data)) {
		Output("couldn't read language file '%s': %s\n", filename.c_str(), reader.getFormattedErrorMessages().c_str());
		return false;
	}

	fd.Reset();

	for (Json::Value::iterator i = data.begin(); i != data.end(); ++i) {
		const std::string token(i.key().asString());
		if (token.empty()) {
			Output("%s: found empty token, skipping it\n", filename.c_str());
			continue;
		}
		if (!valid_token(token)) {
			Output("%s: invalid token '%s', skipping it\n", filename.c_str(), token.c_str());
			continue;
		}

		Json::Value message((*i).get("message", Json::nullValue));
		if (message.isNull()) {
			Output("%s: no 'message' key for token '%s', skipping it\n", filename.c_str(), token.c_str());
			continue;
		}

		if (!message.isString()) {
			Output("%s: value for token '%s' is not a string, skipping it\n", filename.c_str(), token.c_str());
			continue;
		}

		std::string text(message.asString());
		if (text.empty()) {
			Output("%s: empty value for token '%s', skipping it\n", filename.c_str(), token.c_str());
			continue;
		}

		// extracted quoted string
		if (text[0] == '"' && text[text.size()-1] == '"')
			text = text.substr(1, text.size()-2);

		// adjust for escaped newlines
		{
			std::string adjustedText;
			adjustedText.reserve(text.size());

			unsigned int ii;
			for (ii = 0; ii < text.size()-1; ii++) {
				const char *c = &text[ii];
				if (c[0] == '\\' && c[1] == 'n') {
					ii++;
					adjustedText += '\n';
				}
				else
					adjustedText += *c;
			}
			if (ii != text.size())
				adjustedText += text[ii++];
			assert(ii == text.size());
			text = adjustedText;
		}

		m_strings[token] = text;
	}

	m_loaded = true;
	return true;
}
Exemplo n.º 7
0
 void ConfigManager::each( std::function< void( std::string, Json::Value& ) > func ) {
   for( Json::Value::iterator jsonIterator = configRoot.begin(); jsonIterator != configRoot.end(); ++jsonIterator ) {
     func( jsonIterator.key().asString(), *jsonIterator );
   }
 }
Exemplo n.º 8
0
ShipType::ShipType(const Id &_id, const std::string &path) 
{
	Json::Reader reader;
	Json::Value data;

	auto fd = FileSystem::gameDataFiles.ReadFile(path);
	if (!fd) {
		Output("couldn't open ship def '%s'\n", path.c_str());
		return;
	}

	if (!reader.parse(fd->GetData(), fd->GetData()+fd->GetSize(), data)) {
		Output("couldn't read ship def '%s': %s\n", path.c_str(), reader.getFormattedErrorMessages().c_str());
		return;
	}

	// determine what kind (tag) of ship this is.
	const std::string tagStr = data.get("tag", "").asString();
	if( tagStr.empty() || strcasecmp(tagStr.c_str(), "ship")==0 ) {
		tag = TAG_SHIP;
	} else if( strcasecmp(tagStr.c_str(), "static")==0 ) {
		tag = TAG_STATIC_SHIP;
	} else if( strcasecmp(tagStr.c_str(), "missile")==0 ) {
		tag = TAG_MISSILE;
	}

	id = _id;
	name = data.get("name", "").asString();
	shipClass = data.get("ship_class", "").asString();
	manufacturer = data.get("manufacturer", "").asString();
	modelName = data.get("model", "").asString();
	cockpitName = data.get("cockpit", "").asString();

	linThrust[THRUSTER_REVERSE] = data.get("reverse_thrust", 0.0f).asFloat();
	linThrust[THRUSTER_FORWARD] = data.get("forward_thrust", 0.0f).asFloat();
	linThrust[THRUSTER_UP] = data.get("up_thrust", 0.0f).asFloat();
	linThrust[THRUSTER_DOWN] = data.get("down_thrust", 0.0f).asFloat();
	linThrust[THRUSTER_LEFT] = data.get("left_thrust", 0.0f).asFloat();
	linThrust[THRUSTER_RIGHT] = data.get("right_thrust", 0.0f).asFloat();
	angThrust = data.get("angular_thrust", 0.0f).asFloat();

	// invert values where necessary
	linThrust[THRUSTER_FORWARD] *= -1.f;
	linThrust[THRUSTER_LEFT] *= -1.f;
	linThrust[THRUSTER_DOWN] *= -1.f;
	// angthrust fudge (XXX: why?)
	angThrust = angThrust * 0.5f;

	hullMass = data.get("hull_mass", 100).asInt();
	capacity = data.get("capacity", 0).asInt();
	fuelTankMass = data.get("fuel_tank_mass", 5).asInt();

	for( Json::Value::iterator slot = data["slots"].begin() ; slot != data["slots"].end() ; ++slot ) {
		const std::string slotname = slot.key().asString();
		slots[slotname] = data["slots"].get(slotname, 0).asInt();
	}

	{
		const auto it = slots.find("engine");
		if (it != slots.end()) 
		{ 
			it->second = Clamp(it->second, 0, 1); 
		}
	}

	effectiveExhaustVelocity = data.get("effective_exhaust_velocity", -1.0f).asFloat();
	const float thruster_fuel_use = data.get("thruster_fuel_use", -1.0f).asFloat();

	if(effectiveExhaustVelocity < 0 && thruster_fuel_use < 0) {
		// default value of v_c is used
		effectiveExhaustVelocity = 55000000;
	} else if(effectiveExhaustVelocity < 0 && thruster_fuel_use >= 0) {
		// v_c undefined and thruster fuel use defined -- use it!
		effectiveExhaustVelocity = GetEffectiveExhaustVelocity(fuelTankMass, thruster_fuel_use, linThrust[ShipType::THRUSTER_FORWARD]);
	} else {
		if(thruster_fuel_use >= 0) {
			Output("Warning: Both thruster_fuel_use and effective_exhaust_velocity defined for %s, using effective_exhaust_velocity.\n", modelName.c_str());
		}
	}
	
	baseprice = data.get("price", 0.0).asDouble();
	minCrew = data.get("min_crew", 1).asInt();
	maxCrew = data.get("max_crew", 1).asInt();
	hyperdriveClass = data.get("hyperdrive_class", 1).asInt();
}
Exemplo n.º 9
0
void CNest::GetMeterDetails()
{
	std::string sResult;
#ifdef DEBUG_NextThermostatR
	sResult = ReadFile("E:\\nest.json");
#else
	if (m_UserName.size()==0)
		return;
	if (m_Password.size()==0)
		return;
	if (m_bDoLogin)
	{
		if (!Login())
		return;
	}
	std::vector<std::string> ExtraHeaders;

	ExtraHeaders.push_back("user-agent:Nest/1.1.0.10 CFNetwork/548.0.4");
	ExtraHeaders.push_back("Authorization:Basic " + m_AccessToken);
	ExtraHeaders.push_back("X-nl-user-id:" + m_UserID);
	ExtraHeaders.push_back("X-nl-protocol-version:1");

	//Get Data
	std::string sURL = m_TransportURL + NEST_GET_STATUS + m_UserID;
	if (!HTTPClient::GET(sURL, ExtraHeaders, sResult))
	{
		_log.Log(LOG_ERROR, "Nest: Error getting current state!");
		m_bDoLogin = true;
		return;
	}
#endif

#ifdef DEBUG_NextThermostatW
	SaveString2Disk(sResult, "E:\\nest.json");
#endif

	Json::Value root;
	Json::Reader jReader;
	if (!jReader.parse(sResult, root))
	{
		_log.Log(LOG_ERROR, "Nest: Invalid data received!");
		m_bDoLogin = true;
		return;
	}

	bool bHaveShared = !root["shared"].empty();
	bool bHaveTopaz = !root["topaz"].empty();

	if ((!bHaveShared) && (!bHaveTopaz))
	{
		_log.Log(LOG_ERROR, "Nest: request not successful, restarting..!");
		m_bDoLogin = true;
		return;
	}

	//Protect
	if (bHaveTopaz)
	{
		if (root["topaz"].size() < 1)
		{
			_log.Log(LOG_ERROR, "Nest: request not successful, restarting..!");
			m_bDoLogin = true;
			return;
		}
		Json::Value::Members members = root["topaz"].getMemberNames();
		if (members.size() < 1)
		{
			_log.Log(LOG_ERROR, "Nest: request not successful, restarting..!");
			m_bDoLogin = true;
			return;
		}
		int SwitchIndex = 1;
		for (Json::Value::iterator itDevice = root["topaz"].begin(); itDevice != root["topaz"].end(); ++itDevice)
		{
			Json::Value device = *itDevice;
			std::string devstring = itDevice.key().asString();
			if (device["where_id"].empty())
				continue;
			std::string whereid = device["where_id"].asString();
			//lookup name
			std::string devName = devstring;
			if (!root["where"].empty())
			{
				for (Json::Value::iterator itWhere = root["where"].begin(); itWhere != root["where"].end(); ++itWhere)
				{
					Json::Value iwhere = *itWhere;
					if (!iwhere["wheres"].empty())
					{
						for (Json::Value::iterator itWhereNest = iwhere["wheres"].begin(); itWhereNest != iwhere["wheres"].end(); ++itWhereNest)
						{
							Json::Value iwhereItt = *itWhereNest;
							if (!iwhereItt["where_id"].empty())
							{
								std::string tmpWhereid = iwhereItt["where_id"].asString();
								if (tmpWhereid == whereid)
								{
									devName = iwhereItt["name"].asString();
									break;
								}
							}
						}
					}
					
				}
			}
			bool bIAlarm = false;
			bool bBool;
			if (!device["component_speaker_test_passed"].empty())
			{
				bBool = device["component_speaker_test_passed"].asBool();
				if (!bBool)
					bIAlarm = true;
			}
			if (!device["component_smoke_test_passed"].empty())
			{
				bBool = device["component_smoke_test_passed"].asBool();
				if (!bBool)
					bIAlarm = true;
			}
			if (!device["component_heat_test_passed"].empty())
			{
				bBool = device["component_heat_test_passed"].asBool();
				if (!bBool)
					bIAlarm = true;
			}
			if (!device["component_buzzer_test_passed"].empty())
			{
				bBool = device["component_buzzer_test_passed"].asBool();
				if (!bBool)
					bIAlarm = true;
			}
			if (!device["component_us_test_passed"].empty())
			{
				bBool = device["component_us_test_passed"].asBool();
				if (!bBool)
					bIAlarm = true;
			}
			if (!device["component_temp_test_passed"].empty())
			{
				bBool = device["component_temp_test_passed"].asBool();
				if (!bBool)
					bIAlarm = true;
			}
			if (!device["component_wifi_test_passed"].empty())
			{
				bBool = device["component_wifi_test_passed"].asBool();
				if (!bBool)
					bIAlarm = true;
			}
			if (!device["component_als_test_passed"].empty())
			{
				bBool = device["component_als_test_passed"].asBool();
				if (!bBool)
					bIAlarm = true;
			}
			if (!device["component_co_test_passed"].empty())
			{
				bBool = device["component_co_test_passed"].asBool();
				if (!bBool)
					bIAlarm = true;
			}
			if (!device["component_hum_test_passed"].empty())
			{
				bBool = device["component_hum_test_passed"].asBool();
				if (!bBool)
					bIAlarm = true;
			}
			UpdateSmokeSensor(SwitchIndex, bIAlarm, devName);
			SwitchIndex++;
		}
	}

	//Thermostat
	if (!bHaveShared)
		return;
	if (root["shared"].size()<1)
	{
		if (bHaveTopaz)
			return;
		_log.Log(LOG_ERROR, "Nest: request not successful, restarting..!");
		m_bDoLogin = true;
		return;
	}

	size_t iThermostat = 0;
	for (Json::Value::iterator ittStructure = root["structure"].begin(); ittStructure != root["structure"].end(); ++ittStructure)
	{
		Json::Value nstructure = *ittStructure;
		if (!nstructure.isObject())
			continue;
		std::string StructureID = ittStructure.key().asString();
		std::string StructureName = nstructure["name"].asString();

		for (Json::Value::iterator ittDevice = nstructure["devices"].begin(); ittDevice != nstructure["devices"].end(); ++ittDevice)
		{
			std::string devID = (*ittDevice).asString();
			if (devID.find("device.")==std::string::npos)
				continue;
			std::string Serial = devID.substr(7);
			if (root["device"].empty())
				continue;
			if (root["device"][Serial].empty())
				continue; //not found !?
			if (root["shared"][Serial].empty())
				continue; //Nothing shared?


			Json::Value ndevice = root["device"][Serial];
			if (!ndevice.isObject())
				continue;

			std::string Name = "Thermostat";
			if (!ndevice["where_id"].empty())
			{
				//Lookup our 'where' (for the Name of the thermostat)
				std::string where_id = ndevice["where_id"].asString();

				if (!root["where"].empty())
				{
					if (!root["where"][StructureID].empty())
					{
						for (Json::Value::iterator ittWheres = root["where"][StructureID]["wheres"].begin(); ittWheres != root["where"][StructureID]["wheres"].end(); ++ittWheres)
						{
							Json::Value nwheres = *ittWheres;
							if (nwheres["where_id"] == where_id)
							{
								Name = StructureName + " " + nwheres["name"].asString();
								break;
							}
						}
					}
				}
			}

			_tNestThemostat ntherm;
			ntherm.Serial = Serial;
			ntherm.StructureID = StructureID;
			ntherm.Name = Name;
			m_thermostats[iThermostat] = ntherm;

			Json::Value nshared = root["shared"][Serial];

			//Setpoint
			if (!nshared["target_temperature"].empty())
			{
				float currentSetpoint = nshared["target_temperature"].asFloat();
				SendSetPointSensor((const unsigned char)(iThermostat * 3) + 1, currentSetpoint, Name + " Setpoint");
			}
			//Room Temperature/Humidity
			if (!nshared["current_temperature"].empty())
			{
				float currentTemp = nshared["current_temperature"].asFloat();
				int Humidity = root["device"][Serial]["current_humidity"].asInt();
				SendTempHumSensor((iThermostat * 3) + 2, 255, currentTemp, Humidity, Name + " TempHum");
			}

			// Check if thermostat is currently Heating
			if (nshared["can_heat"].asBool() && !nshared["hvac_heater_state"].empty())
			{
				bool bIsHeating = nshared["hvac_heater_state"].asBool();
				UpdateSwitch((unsigned char)(113 + (iThermostat * 3)), bIsHeating, Name + " HeatingOn");
			}

			// Check if thermostat is currently Cooling
			if (nshared["can_cool"].asBool() && !nshared["hvac_ac_state"].empty())
			{
				bool bIsCooling = nshared["hvac_ac_state"].asBool();
				UpdateSwitch((unsigned char)(114 + (iThermostat * 3)), bIsCooling, Name + " CoolingOn");
			}

			//Away
			if (!nstructure["away"].empty())
			{
				bool bIsAway = nstructure["away"].asBool();
				SendSwitch((iThermostat * 3) + 3, 1, 255, bIsAway, 0, Name + " Away");
			}
			iThermostat++;
		}
	}
}
Exemplo n.º 10
0
  int load_config(const char *cfg_root)
  {
    Json::Value root;
    if (this->load_json_cfg(cfg_root, KAI_FU_ACT_CFG_PATH, root) != 0)
      return -1;

    for (Json::Value::iterator iter = root.begin();
         iter != root.end();
         ++iter)
    {
      int act_id = ::atoi(iter.key().asCString());
      ilist<kai_fu_act_cfg_obj *> *pl = new ilist<kai_fu_act_cfg_obj *>();
      this->kai_fu_act_cfg_map_.insert(std::make_pair(act_id, pl));
      Json::Value &sub_v = *iter;
      for (Json::Value::iterator sub_iter = sub_v.begin();
           sub_iter != sub_v.end();
           ++sub_iter)
      {
        kai_fu_act_cfg_obj *p = new kai_fu_act_cfg_obj();
        pl->push_back(p);
        p->param_ = (*sub_iter)["param"].asInt();
        p->open_ = (*sub_iter)["open"].asBool();

        {
          Json::Value &award_v = (*sub_iter)["award"];
          if (award_v.empty()) continue;
          char *tok_p = NULL;
          char *token = NULL;
          char bf[256] = {0};
          ::strncpy(bf, award_v.asCString(), sizeof(bf) - 1);
          for (token = ::strtok_r(bf, ";", &tok_p);
               token != NULL;
               token = ::strtok_r(NULL, ";", &tok_p))
          {
            item_amount_bind_t item;
            int bind = 0;
            ::sscanf(token, "%d,%d,%d", &item.cid_, &item.amount_, &bind);
            item.bind_ = bind;
            p->award_list_.push_back(item);
            if (!item_config::instance()->find(item.cid_))
              return -1;
          }
        }
        {
          Json::Value &award_v = (*sub_iter)["award_2"];
          if (award_v.empty()) continue;
          char *tok_p = NULL;
          char *token = NULL;
          char bf[256] = {0};
          ::strncpy(bf, award_v.asCString(), sizeof(bf) - 1);
          for (token = ::strtok_r(bf, ";", &tok_p);
               token != NULL;
               token = ::strtok_r(NULL, ";", &tok_p))
          {
            item_amount_bind_t item;
            int bind = 0;
            ::sscanf(token, "%d,%d,%d", &item.cid_, &item.amount_, &bind);
            item.bind_ = bind;
            p->award_list_2_.push_back(item);
            if (!item_config::instance()->find(item.cid_))
              return -1;
          }
        }
      }
    }
    return 0;
  }
Exemplo n.º 11
0
void Game::loadResources() {
	Log::Out << "Game: Loading resources..." << endl;
	istream* resourcesFile = Pack::GetInstance()->GetStream("resources.json");

	if (!resourcesFile->good()) {
		Log::Out << "Couldn't load file resources.json" << endl;
		return;
	}

	Json::Value root;
	(*resourcesFile) >> root;
	delete resourcesFile;

	Log::Out << "Game: Initializing Scanlines..." << endl;
	Json::Value shaders = root["outputShaders"];
	if (Json::Value::null != shaders) {
		ShaderMgr* shaderMgr = ShaderMgr::GetInstance();
		for (Json::Value::iterator itShaderDesc = shaders.begin(); itShaderDesc != shaders.end(); ++itShaderDesc) {
			vector<Shader*> shaderPtrs;
			Json::Value child = *itShaderDesc;
			string name = child["name"].asString();
			Json::Value pathArray = child["shaderPaths"];
			for (Json::Value::iterator itShaderPath = pathArray.begin(); itShaderPath != pathArray.end(); ++itShaderPath) {
				string shaderFile = itShaderPath->asString();
				ShaderType shaderType = shaderFile.find(".vertex") == string::npos ? Fragment : Vertex;
				stringstream ss;
				ss << "Loading " << ((shaderType == Vertex) ? "vertex" : "fragment") << " shader: " << shaderFile;
				drawStatusMsg(ss.str());
				shaderPtrs.push_back(shaderMgr->LoadShader(shaderFile, shaderType));
			}
			Program* p = new Program(shaderPtrs);
			if (p->ProgramId != 0) {
				p->Textures.push_back(_g->GetFramebufferTexture());
			}
			Json::Value texArray = child["additionalTextures"];
			for (Json::Value::iterator itTexturePath = texArray.begin(); itTexturePath != texArray.end(); ++itTexturePath) {
				string texPath = itTexturePath->asString();
				p->Textures.push_back(Frame(texPath).Texture);
			}
			this->_blitProgramMap[name] = p;
			if (child.isMember("default") && child["default"].asBool()) {
				this->_blitProgram = p;
			}
		}
		if (this->_blitProgram == NULL && this->_blitProgramMap.size() > 0) {
			this->_blitProgram = (this->_blitProgramMap.end())->second;
		}
	}

	Json::Value images = root["images"];
	if (Json::Value::null != images) {
		TextureMgr* texMgr = TextureMgr::GetInstance();
		for (Json::Value::iterator img = images.begin(); img != images.end(); ++img) {
			string file = img->asString();
			stringstream ss;
			ss << "Loading image: " << file;
			drawStatusMsg(ss.str());
			texMgr->LoadTexture(file);
		}
	}
	Json::Value music = root["music"];
	if (Json::Value::null != music) {
		MusicManager* musicMgr = MusicManager::GetInstance();
		for (Json::Value::iterator mus = music.begin(); mus != music.end(); ++mus) {
			string file = mus->asString();
			stringstream ss;
			ss << "Loading song " << file;
			drawStatusMsg(ss.str());
			musicMgr->LoadMusic(mus->asString());
		}
	}
	Json::Value effects = root["fx"];
	if (Json::Value::null != effects) {
		MusicManager* musicMgr = MusicManager::GetInstance();
		for (Json::Value::iterator fx = effects.begin(); fx != effects.end(); ++fx) {
			stringstream ss;
			string file = fx->asString();
			ss << "Loading effect " << file;
			drawStatusMsg(ss.str());
			musicMgr->LoadMusic(fx->asString());
		}
	}
	drawStatusMsg("Done!");
}
Exemplo n.º 12
0
void Myself::parse(const std::string& body) throw(ParseJsonError)
{
    User::parse(body);
    
    Json::Value root;
    Json::Reader reader;
    
    if(!reader.parse(body,root)) throw ParseJsonError(reader.getFormattedErrorMessages().c_str());
    
    for (Json::Value::iterator it = root.begin(); it != root.end(); ++it)
    {
        if(it.key().asString() == "total_private_repos")
        {
            _totalPrivateRepos = root.get(it.key().asString(), 0).asInt();
        } else
        if(it.key().asString() == "owned_private_repos")
        {
            _ownedPrivateRepos = root.get(it.key().asString(), 0).asInt();
        } else
        if(it.key().asString() == "private_gists")
        {
            _privateGists = root.get(it.key().asString(), 0).asInt();
        } else
        if(it.key().asString() == "disk_usage")
        {
            _diskUsage = root.get(it.key().asString(), 0).asInt();
        } else
        if(it.key().asString() == "collaborators")
        {
            _collaborators = root.get(it.key().asString(), 0).asInt();
        } else
        if(it.key().asString() == "plan")
        {
            _plan.name = root.get(it.key().asString(), 0).get("name",0).asString();
            _plan.space = root.get(it.key().asString(), 0).get("space",0).asInt();
            _plan.privateRepos = root.get(it.key().asString(), 0).get("private_repos",0).asInt();
            _plan.collaborators = root.get(it.key().asString(), 0).get("collaborators",0).asInt();
        }
    }
    
}
Exemplo n.º 13
0
bool CPhilipsHue::GetLights(const Json::Value &root)
{
	if (root["lights"].empty())
		return false;

	for (Json::Value::iterator iLight = root["lights"].begin(); iLight != root["lights"].end(); ++iLight)
	{
		Json::Value light = *iLight;
		if (light.isObject())
		{
			std::string szLID = iLight.key().asString();
			int lID = atoi(szLID.c_str());
			std::string ltype = light["type"].asString();
			if (
				(ltype == "Dimmable plug-in unit") ||
				(ltype == "Dimmable light") ||
				(ltype == "Color temperature light")
				)
			{
				//Normal light (with dim option)
				bool bIsOn = light["state"]["on"].asBool();
				int tbri = light["state"]["bri"].asInt();
				if ((tbri != 0) && (tbri != 255))
					tbri += 1; //hue reports 255 as 254
				int BrightnessLevel = int((100.0f / 255.0f)*float(tbri));
				_tHueLight tlight;
				if (bIsOn)
				{
					tlight.cmd = (BrightnessLevel != 0) ? light2_sSetLevel : light2_sOn;
				}
				else
					tlight.cmd = light2_sOff;
				tlight.level = BrightnessLevel;
				tlight.sat = 0;
				tlight.hue = 0;
				bool bDoSend = true;
				if (m_lights.find(lID) != m_lights.end())
				{
					_tHueLight alight = m_lights[lID];
					if (
						(alight.cmd == tlight.cmd) &&
						(alight.level == tlight.level)
						)
					{
						bDoSend = false;
					}
				}
				m_lights[lID] = tlight;
				if (bDoSend)
					InsertUpdateSwitch(lID, HLTYPE_DIM, bIsOn, BrightnessLevel, 0, 0, light["name"].asString(), "");
			}
			else if (
				(ltype == "Extended color light") ||
				(ltype == "Color light")
				)
			{
				//RGBW type
				bool bIsOn = light["state"]["on"].asBool();
				int tbri = light["state"]["bri"].asInt();
				int tsat = light["state"]["sat"].asInt();
				int thue = light["state"]["hue"].asInt();
				if ((tbri != 0) && (tbri != 255))
					tbri += 1; //hue reports 255 as 254
				int BrightnessLevel = int((100.0f / 255.0f)*float(tbri));
				_tHueLight tlight;
				if (bIsOn)
				{
					tlight.cmd = (BrightnessLevel != 0) ? Limitless_SetBrightnessLevel : Limitless_LedOn;
				}
				else
					tlight.cmd = Limitless_LedOff;
				tlight.level = BrightnessLevel;
				tlight.sat = tsat;
				tlight.hue = thue;
				bool bDoSend = true;
				if (m_lights.find(lID) != m_lights.end())
				{
					_tHueLight alight = m_lights[lID];
					if (
						(alight.cmd == tlight.cmd) &&
						(alight.level == tlight.level) &&
						(alight.sat == tlight.sat) &&
						(alight.hue == tlight.hue)
						)
					{
						bDoSend = false;
					}
				}
				m_lights[lID] = tlight;
				if (bDoSend)
				{
					InsertUpdateSwitch(lID, HLTYPE_RGBW, bIsOn, BrightnessLevel, tsat, thue, light["name"].asString(), "");
				}
			}
		}
	}
	return true;
}
Exemplo n.º 14
0
bool CPhilipsHue::GetScenes(const Json::Value &root)
{
	if (root["scenes"].empty())
		return false;

	for (Json::Value::iterator iScene = root["scenes"].begin(); iScene != root["scenes"].end(); ++iScene)
	{
		Json::Value scene = *iScene;
		if (scene.isObject())
		{
			_tHueScene hscene;
			hscene.id = iScene.key().asString();;
			hscene.name = scene["name"].asString();
			hscene.lastupdated = scene["lastupdated"].asString();
			if (hscene.lastupdated.empty())
				continue; //old scene/legacy scene
			
			//Strip some info
			size_t tpos = hscene.name.find(" from ");
			if (tpos != std::string::npos)
			{
				hscene.name = hscene.name.substr(0, tpos);
			}

			bool bDoSend = true;
			if (m_scenes.find(hscene.id) != m_scenes.end())
			{
				_tHueScene ascene = m_scenes[hscene.id];
				if (ascene.lastupdated == hscene.lastupdated)
				{
					bDoSend = false;
				}
			}
			m_scenes[hscene.id] = hscene;

			if (bDoSend)
			{
				int sID = -1;
				std::vector<std::vector<std::string> > result;
				result = m_sql.safe_query("SELECT ID FROM WOLNodes WHERE (HardwareID==%d) AND (MacAddress=='%q')", m_HwdID, hscene.id.c_str());
				if (!result.empty())
				{
					//existing scene
					sID = atoi(result[0][0].c_str());
				}
				else
				{
					//New scene
					m_sql.safe_query("INSERT INTO WOLNodes (HardwareID, Name, MacAddress) VALUES (%d, '%q', '%q')", m_HwdID, hscene.name.c_str(), hscene.id.c_str());
					result = m_sql.safe_query("SELECT ID FROM WOLNodes WHERE (HardwareID==%d) AND (MacAddress=='%q')", m_HwdID, hscene.id.c_str());
					if (result.empty())
					{
						_log.Log(LOG_ERROR, "Philips Hue: Problem adding new Scene!!");
						return false;
					}
					sID = atoi(result[0][0].c_str());
				}
				std::string Name = "Scene " + hscene.name;
				InsertUpdateSwitch(2000 + sID, HLTYPE_SCENE, false, 100, 0, 0, Name, hscene.id);
			}
		}
	}
	return true;
}
Exemplo n.º 15
0
bool CPhilipsHue::GetGroups(const Json::Value &root)
{
	//Groups (0=All)

	if (root["groups"].empty())
		return false;

	for (Json::Value::iterator iGroup = root["groups"].begin(); iGroup != root["groups"].end(); ++iGroup)
	{
		Json::Value group = *iGroup;
		if (group.isObject())
		{
			std::string szGID = iGroup.key().asString();
			int gID = atoi(szGID.c_str());
			bool bIsOn = false;
			int tbri = 255;
			int tsat = 255;
			int thue = 255;

			if (!group["action"]["on"].empty())
				bIsOn = group["action"]["on"].asBool();
			if (!group["action"]["bri"].empty())
				tbri = group["action"]["bri"].asInt();
			if (!group["action"]["sat"].empty())
				tsat = group["action"]["sat"].asInt();
			if (!group["action"]["hue"].empty())
				thue = group["action"]["hue"].asInt();
			if ((tbri != 0) && (tbri != 255))
				tbri += 1; //hue reports 255 as 254
			int BrightnessLevel = int((100.0f / 255.0f)*float(tbri));
			_tHueLight tstate;
			if (bIsOn)
			{
				tstate.cmd = (BrightnessLevel != 0) ? Limitless_SetBrightnessLevel : Limitless_LedOn;
			}
			else
				tstate.cmd = Limitless_LedOff;
			tstate.level = BrightnessLevel;
			tstate.sat = tsat;
			tstate.hue = thue;
			bool bDoSend = true;
			if (m_groups.find(gID) != m_groups.end())
			{
				_tHueGroup agroup = m_groups[gID];
				if (
					(agroup.gstate.cmd == tstate.cmd) &&
					(agroup.gstate.level == tstate.level) &&
					(agroup.gstate.sat == tstate.sat) &&
					(agroup.gstate.hue == tstate.hue)
					)
				{
					bDoSend = false;
				}
			}
			m_groups[gID].gstate = tstate;
			if (bDoSend)
			{
				std::string Name = "Group " + group["name"].asString();
				InsertUpdateSwitch(1000 + gID, HLTYPE_RGBW, bIsOn, BrightnessLevel, tsat, thue, Name, "");
			}
		}
	}
	//Special Request for Group0 (All Lights)
	std::stringstream sstr2;
	sstr2 << "http://" << m_IPAddress
		<< ":" << m_Port
		<< "/api/" << m_UserName
		<< "/groups/0";
	std::string sResult;
	std::vector<std::string> ExtraHeaders;
	if (!HTTPClient::GET(sstr2.str(), ExtraHeaders, sResult))
	{
		//No group all(0)
		return true;
	}
	Json::Reader jReader;
	Json::Value root2;
	bool ret = jReader.parse(sResult, root2);
	ret = jReader.parse(sResult, root2);
	if (!ret)
	{
		_log.Log(LOG_ERROR, "Philips Hue: Invalid data received, or invalid IPAddress/Username!");
		return false;
	}

	if (sResult.find("\"error\":") != std::string::npos)
	{
		//We had an error
		_log.Log(LOG_ERROR, "Philips Hue: Error received: %s", root2[0]["error"]["description"].asString().c_str());
		return false;
	}

	if (sResult.find("lights") == std::string::npos)
	{
		return false;
	}
	bool bIsOn = false;
	int tbri = 255;
	int tsat = 255;
	int thue = 255;

	if (!root2["action"]["on"].empty())
		bIsOn = root2["action"]["on"].asBool();
	if (!root2["action"]["bri"].empty())
		tbri = root2["action"]["bri"].asInt();
	if (!root2["action"]["sat"].empty())
		tsat = root2["action"]["sat"].asInt();
	if (!root2["action"]["hue"].empty())
		thue = root2["action"]["hue"].asInt();
	if ((tbri != 0) && (tbri != 255))
		tbri += 1; //hue reports 255 as 254
	int BrightnessLevel = int((100.0f / 255.0f)*float(tbri));
	_tHueLight tstate;
	if (bIsOn)
	{
		tstate.cmd = (BrightnessLevel != 0) ? Limitless_SetBrightnessLevel : Limitless_LedOn;
	}
	else
		tstate.cmd = Limitless_LedOff;
	tstate.level = BrightnessLevel;
	tstate.sat = tsat;
	tstate.hue = thue;
	bool bDoSend = true;
	int gID = 0;
	if (m_groups.find(gID) != m_groups.end())
	{
		_tHueGroup agroup = m_groups[gID];
		if (
			(agroup.gstate.cmd == tstate.cmd) &&
			(agroup.gstate.level == tstate.level) &&
			(agroup.gstate.sat == tstate.sat) &&
			(agroup.gstate.hue == tstate.hue)
			)
		{
			bDoSend = false;
		}
	}
	m_groups[gID].gstate = tstate;
	if (bDoSend)
	{
		std::string Name = "Group All Lights";
		InsertUpdateSwitch(1000 + gID, HLTYPE_RGBW, bIsOn, BrightnessLevel, tsat, thue, Name,"");
	}
	return true;
}
Exemplo n.º 16
0
  int load_config(const char *cfg_root)
  {
    Json::Value root;
    if (this->load_json_cfg(cfg_root, TIMING_MST_CONFIG_PATH, root) != 0)
      return -1;

    for(Json::Value::iterator iter = root.begin();
        iter != root.end();
        ++iter)
    {
      const int index = ::atoi(iter.key().asCString());
      if (index <= 0 || index >= MAX_TIMING_MST_IDX)
      {
        e_log->rinfo("index[%d] error!", index);
        return -1;
      }

      timing_mst_cfg_obj *obj = new timing_mst_cfg_obj();
      this->obj_list_.push_back(obj);

      obj->index_ = index;
      obj->scene_cid_ = (*iter)["scene_cid"].asInt();
      obj->mst_cid_   = (*iter)["monster_cid"].asInt();
      obj->coord_x_   = (*iter)["coord_x"].asInt();
      obj->coord_y_   = (*iter)["coord_y"].asInt();
      obj->range_     = (*iter)["range"].asInt();
      if (!scene_config::instance()->can_move(obj->scene_cid_,
                                              obj->coord_x_,
                                              obj->coord_y_))
      {
        e_log->rinfo("%s [%d,%d] can not move",
                     TIMING_MST_CONFIG_PATH,
                     obj->coord_x_, obj->coord_y_);
        return -1;
      }

      char *tok_p = NULL;
      char *token = NULL;
      char bf[256] = {0};
      ::strncpy(bf, (*iter)["month"].asCString(), sizeof(bf));
      for(token = ::strtok_r(bf, ",", &tok_p);
          token != NULL;
          token = ::strtok_r(NULL, ",", &tok_p))
        obj->month_list_.push_back(::atoi(token));

      ::strncpy(bf, (*iter)["week"].asCString(), sizeof(bf));
      for(token = ::strtok_r(bf, ",", &tok_p);
          token != NULL;
          token = ::strtok_r(NULL, ",", &tok_p))
        obj->wday_list_.push_back(::atoi(token));

      ::strncpy(bf, (*iter)["day"].asCString(), sizeof(bf));
      for(token = ::strtok_r(bf, ",", &tok_p);
          token != NULL;
          token = ::strtok_r(NULL, ",", &tok_p))
        obj->mday_list_.push_back(::atoi(token));

      ::strncpy(bf, (*iter)["refresh_time"].asCString(), sizeof(bf));
      for(token = ::strtok_r(bf, ",", &tok_p);
          token != NULL;
          token = ::strtok_r(NULL, ",", &tok_p))
      {
        int hour = 0;
        int min = 0;
        ::sscanf(token, "%d:%d", &hour, &min);
        obj->time_list_.push_back(pair_t<char>(hour, min));
      }
    }
    return 0;
  }
Exemplo n.º 17
0
ShipType::ShipType(const Id &_id, const std::string &path)
{
	Json::Reader reader;
	Json::Value data;

	isGlobalColorDefined = false;

	auto fd = FileSystem::gameDataFiles.ReadFile(path);
	if (!fd) {
		Output("couldn't open ship def '%s'\n", path.c_str());
		return;
	}

	if (!reader.parse(fd->GetData(), fd->GetData()+fd->GetSize(), data)) {
		Output("couldn't read ship def '%s': %s\n", path.c_str(), reader.getFormattedErrorMessages().c_str());
		return;
	}

	// determine what kind (tag) of ship this is.
	const std::string tagStr = data.get("tag", "").asString();
	if( tagStr.empty() || strcasecmp(tagStr.c_str(), "ship")==0 ) {
		tag = TAG_SHIP;
	} else if( strcasecmp(tagStr.c_str(), "static")==0 ) {
		tag = TAG_STATIC_SHIP;
	} else if( strcasecmp(tagStr.c_str(), "missile")==0 ) {
		tag = TAG_MISSILE;
	}

	id = _id;
	name = data.get("name", "").asString();
	shipClass = data.get("ship_class", "").asString();
	manufacturer = data.get("manufacturer", "").asString();
	modelName = data.get("model", "").asString();
	cockpitName = data.get("cockpit", "").asString();

	linThrust[THRUSTER_REVERSE] = data.get("reverse_thrust", 0.0f).asFloat();
	linThrust[THRUSTER_FORWARD] = data.get("forward_thrust", 0.0f).asFloat();
	linThrust[THRUSTER_UP] = data.get("up_thrust", 0.0f).asFloat();
	linThrust[THRUSTER_DOWN] = data.get("down_thrust", 0.0f).asFloat();
	linThrust[THRUSTER_LEFT] = data.get("left_thrust", 0.0f).asFloat();
	linThrust[THRUSTER_RIGHT] = data.get("right_thrust", 0.0f).asFloat();
	angThrust = data.get("angular_thrust", 0.0f).asFloat();

	// Parse global thrusters color
	bool error = false;
	int parse = 0;
	for( Json::Value::iterator thruster_color = data["thruster_global_color"].begin() ; thruster_color != data["thruster_global_color"].end() ; ++thruster_color ) {
		const std::string colorchannel = thruster_color.key().asString();
		if (colorchannel.length()!=1) {
			error = true;
			break;
		}
		if (colorchannel.at(0) == 'r') {
			globalThrusterColor.r = data["thruster_global_color"].get(colorchannel, 0).asInt();
			parse++;
			continue;
		} else if (colorchannel.at(0) == 'g') {
			globalThrusterColor.g = data["thruster_global_color"].get(colorchannel, 0).asInt();
			parse++;
			continue;
		} else if (colorchannel.at(0) == 'b') {
			globalThrusterColor.b = data["thruster_global_color"].get(colorchannel, 0).asInt();
			parse++;
			continue;
		} else {
			// No 'r', no 'g', no 'b', no good :/
			error = true;
			break;
		}
	}
	if (error==true) {
		Output("In file \"%s.json\" global thrusters custom color must be \"r\",\"g\" and \"b\"\n", modelName.c_str());
	} else if (parse>0 && parse<3) {
		Output("In file \"%s.json\" global thrusters custom color is malformed\n", modelName.c_str());
	} else if (parse==3) {
		globalThrusterColor.a = 255;
		isGlobalColorDefined = true;
	}
	// Parse direction thrusters color
	for (int i=0; i<THRUSTER_MAX; i++) isDirectionColorDefined[i]=false;
	error = false;
	for( Json::Value::iterator thruster_color = data["thruster_direction_color"].begin() ; thruster_color != data["thruster_direction_color"].end() ; ++thruster_color ) {
		const std::string th_color_dir = thruster_color.key().asString();
		Json::Value dir_color = data["thruster_direction_color"].get(th_color_dir, 0);
		Color color;
		if (!dir_color.isMember("r")||!dir_color.isMember("g")||!dir_color.isMember("b")) {
			error = true;
			continue /* for */;
		} else {
			color.r = dir_color["r"].asInt();
			color.g = dir_color["g"].asInt();
			color.b = dir_color["b"].asInt();
			color.a = 255;
		}
		if (th_color_dir.find("forward")!=std::string::npos) {
			isDirectionColorDefined[THRUSTER_FORWARD]=true;
			directionThrusterColor[THRUSTER_FORWARD]= color;
		}
		if (th_color_dir.find("retro")!=std::string::npos) {
			isDirectionColorDefined[THRUSTER_REVERSE]=true;
			directionThrusterColor[THRUSTER_REVERSE]= color;
		}
		if (th_color_dir.find("left")!=std::string::npos) {
			isDirectionColorDefined[THRUSTER_LEFT]=true;
			directionThrusterColor[THRUSTER_LEFT]= color;
		}
		if (th_color_dir.find("right")!=std::string::npos) {
			isDirectionColorDefined[THRUSTER_RIGHT]=true;
			directionThrusterColor[THRUSTER_RIGHT]= color;
		}
		if (th_color_dir.find("up")!=std::string::npos) {
			isDirectionColorDefined[THRUSTER_UP]=true;
			directionThrusterColor[THRUSTER_UP]= color;
		}
		if (th_color_dir.find("down")!=std::string::npos) {
			isDirectionColorDefined[THRUSTER_DOWN]=true;
			directionThrusterColor[THRUSTER_DOWN]= color;
		}
	}
	if (error==true) {
		for (int i=0; i<THRUSTER_MAX; i++) isDirectionColorDefined[i]=false;
		Output("In file \"%s.json\" directional thrusters custom color must be \"r\",\"g\" and \"b\"\n", modelName.c_str());
	}
	// invert values where necessary
	linThrust[THRUSTER_FORWARD] *= -1.f;
	linThrust[THRUSTER_LEFT] *= -1.f;
	linThrust[THRUSTER_DOWN] *= -1.f;
	// angthrust fudge (XXX: why?)
	angThrust = angThrust * 0.5f;

	hullMass = data.get("hull_mass", 100).asInt();
	capacity = data.get("capacity", 0).asInt();
	fuelTankMass = data.get("fuel_tank_mass", 5).asInt();

	for( Json::Value::iterator slot = data["slots"].begin() ; slot != data["slots"].end() ; ++slot ) {
		const std::string slotname = slot.key().asString();
		slots[slotname] = data["slots"].get(slotname, 0).asInt();
	}

	for( Json::Value::iterator role = data["roles"].begin(); role != data["roles"].end(); ++role ) {
		const std::string rolename = role.key().asString();
		roles[rolename] = data["roles"].get(rolename, 0).asBool();
	}

	for(int it=0;it<4;it++) thrusterUpgrades[it] = 1.0 + (double(it)/10.0);
	for( Json::Value::iterator slot = data["thrust_upgrades"].begin() ; slot != data["thrust_upgrades"].end() ; ++slot ) {
		const std::string slotname = slot.key().asString();
		const int index = Clamp(atoi(&slotname.c_str()[9]), 1, 3);
		thrusterUpgrades[index] = data["thrust_upgrades"].get(slotname, 0).asDouble();
	}

	atmosphericPressureLimit = data.get("atmospheric_pressure_limit", 10.0).asDouble();	// 10 atmosphere is about 90 metres underwater (on Earth)

	{
		const auto it = slots.find("engine");
		if (it != slots.end())
		{
			it->second = Clamp(it->second, 0, 1);
		}
	}

	effectiveExhaustVelocity = data.get("effective_exhaust_velocity", -1.0f).asFloat();
	const float thruster_fuel_use = data.get("thruster_fuel_use", -1.0f).asFloat();

	if(effectiveExhaustVelocity < 0 && thruster_fuel_use < 0) {
		// default value of v_c is used
		effectiveExhaustVelocity = 55000000;
	} else if(effectiveExhaustVelocity < 0 && thruster_fuel_use >= 0) {
		// v_c undefined and thruster fuel use defined -- use it!
		effectiveExhaustVelocity = GetEffectiveExhaustVelocity(fuelTankMass, thruster_fuel_use, linThrust[Thruster::THRUSTER_FORWARD]);
	} else {
		if(thruster_fuel_use >= 0) {
			Output("Warning: Both thruster_fuel_use and effective_exhaust_velocity defined for %s, using effective_exhaust_velocity.\n", modelName.c_str());
		}
	}

	baseprice = data.get("price", 0.0).asDouble();
	minCrew = data.get("min_crew", 1).asInt();
	maxCrew = data.get("max_crew", 1).asInt();
	hyperdriveClass = data.get("hyperdrive_class", 1).asInt();
}
Exemplo n.º 18
0
	//½âÎöJsonÖµ
	Bool  ParseJsonVal(const Json::Value* pJsonVal, HawkJson::JsonVal* pVal)
	{
		if (!pJsonVal || !pVal)
			return false;

		if (pJsonVal->isBool())
		{
			pVal->Type = HawkJson::JSON_STRING;
			pVal->Str  = pJsonVal->asBool()? "true":"false";
		}
		else if (pJsonVal->isInt())
		{
			pVal->Type = HawkJson::JSON_STRING;
			pVal->Str  = HawkStringUtil::IntToString<AString>(pJsonVal->asInt());
		}
		else if (pJsonVal->isUInt())
		{
			pVal->Type = HawkJson::JSON_STRING;
			pVal->Str  = HawkStringUtil::UIntToString<AString>(pJsonVal->asUInt());
		}
		else if (pJsonVal->isDouble())
		{
			pVal->Type = HawkJson::JSON_STRING;
			pVal->Str  = HawkStringUtil::DoubleToString<AString>(pJsonVal->asDouble());
		}
		else if (pJsonVal->isString())
		{
			pVal->Type = HawkJson::JSON_STRING;
			pVal->Str  = pJsonVal->asString();
		}
		else if (pJsonVal->isArray())
		{
			pVal->Type = HawkJson::JSON_ARRAY;
			for (Size_t i=0;i<pJsonVal->size();i++)
			{
				const Json::Value& sJsonVal = pJsonVal->get(i, Json::Value::null);
				if (sJsonVal.isNull())
					return false;

				HawkJson::JsonVal* pSubVal = new HawkJson::JsonVal;
				if (ParseJsonVal(&sJsonVal, pSubVal))
				{
					pVal->Arr.push_back(pSubVal);
				}
				else
				{
					HAWK_DELETE(pSubVal);
				}
			}
		}
		else if (pJsonVal->isObject())
		{
			pVal->Type = HawkJson::JSON_OBJECT;
			for(Json::Value::iterator it = pJsonVal->begin(); it !=  pJsonVal->end(); it++)
			{
				const Json::Value& sJsonKey = it.key();
				if (sJsonKey.isNull())
					return false;

				AString sKey = sJsonKey.asString();
				const Json::Value& sJsonVal = pJsonVal->get(sKey.c_str(),Json::Value::null);
				if (sJsonVal.isNull())
					return false;

				HawkJson::JsonVal* pSubVal = new HawkJson::JsonVal;
				if (ParseJsonVal(&sJsonVal, pSubVal))
				{
					pVal->Obj[sKey] = pSubVal;
				}
				else
				{
					HAWK_DELETE(pSubVal);
					return false;
				}
			}
		}

		return true;
	}