예제 #1
0
bool TournamentConfig::Save(const std::string &fileName)
{
    bool ret = true;

    JsonObject json;

    json.AddValue("version", TOURNAMENT_CONFIG_VERSION);

    JsonArray tournament;
    for (std::vector<Tarot::Distribution>::iterator iter =  mOptions.turns.begin(); iter !=  mOptions.turns.end(); ++iter)
    {
        std::string type;
        std::string file;
        std::uint32_t number = 0U;
        JsonObject obj;

        if (iter->mType == Tarot::Distribution::RANDOM_DEAL)
        {
            type = "random";
            file = "";
        }
        else if (iter->mType == Tarot::Distribution::CUSTOM_DEAL)
        {
            type = "custom";
            file = iter->mFile;
        }
        else
        {
            type = "numbered";
            number = iter->mSeed;
        }

        obj.AddValue("type", type);
        obj.AddValue("file", file);
        obj.AddValue("number", number);
        tournament.AddValue(obj);
    }
    json.AddValue("tournament", tournament);

    if (!JsonWriter::SaveToFile(json, fileName))
    {
        ret = false;
        TLogError("Saving tournament's configuration failed.");
    }
    return ret;
}
예제 #2
0
void load_technique(JsonObject &jo)
{
    ma_technique tec;

    tec.id = jo.get_string("id");
    //tec.name = _(jo.get_string("name").c_str());

    JsonArray jsarr = jo.get_array("messages");
    while (jsarr.has_more()) {
        tec.messages.push_back(_(jsarr.next_string().c_str()));
    }

    tec.reqs.unarmed_allowed = jo.get_bool("unarmed_allowed", false);
    tec.reqs.melee_allowed = jo.get_bool("melee_allowed", false);
    tec.reqs.min_melee = jo.get_int("min_melee", 0);
    tec.reqs.min_unarmed = jo.get_int("min_unarmed", 0);
    tec.reqs.req_buffs = jo.get_tags("req_buffs");

    tec.crit_tec = jo.get_bool("crit_tec", false);
    tec.defensive = jo.get_bool("defensive", false);
    tec.disarms = jo.get_bool("disarms", false);
    tec.grabs = jo.get_bool("grabs", false);
    tec.counters = jo.get_bool("counters", false);
    tec.miss_recovery = jo.get_bool("miss_recovery", false);
    tec.grab_break = jo.get_bool("grab_break", false);
    tec.flaming = jo.get_bool("flaming", false);
    tec.quick = jo.get_bool("quick", false);

    tec.hit = jo.get_int("pain", 0);
    tec.bash = jo.get_int("bash", 0);
    tec.cut = jo.get_int("cut", 0);
    tec.pain = jo.get_int("pain", 0);

    tec.bash_mult = jo.get_float("bash_mult", 1.0);
    tec.cut_mult = jo.get_float("cut_mult", 1.0);

    tec.down_dur = jo.get_int("down_dur", 0);
    tec.stun_dur = jo.get_int("stun_dur", 0);
    tec.knockback_dist = jo.get_int("knockback_dist", 0);
    tec.knockback_spread = jo.get_int("knockback_spread", 0);

    tec.aoe = jo.get_string("aoe", "");
    tec.flags = jo.get_tags("flags");

    ma_techniques[tec.id] = tec;
}
예제 #3
0
unsigned Item_factory::flags_from_json(JsonObject& jo, std::string member, std::string flag_type)
{
    //If none is found, just use the standard none action
    unsigned flag = 0;
    //Otherwise, grab the right label to look for
    if ( jo.has_array(member) ) {
        JsonArray jarr = jo.get_array(member);
        while (jarr.has_more()){
            set_flag_by_string(flag, jarr.next_string(), flag_type);
        }
    } else if ( jo.has_string(member) ) {
        //we should have gotten a string, if not an array
        set_flag_by_string(flag, jo.get_string(member), flag_type);
    }

    return flag;
}
예제 #4
0
void
StratumConnection::getAddressHistory(
    const bc::client::obelisk_codec::error_handler &onError,
    const bc::client::obelisk_codec::fetch_history_handler &onReply,
    const bc::payment_address &address, size_t fromHeight)
{
    JsonArray params;
    params.append(json_string(address.encoded().c_str()));

    auto errorShim = [onError](Status status)
    {
        onError(std::make_error_code(std::errc::bad_message));
    };

    auto decoder = [onReply](JsonPtr payload) -> Status
    {
        JsonArray arrayJson(payload);

        bc::client::history_list history;
        size_t size = arrayJson.size();
        history.reserve(size);
        for (size_t i = 0; i < size; i++)
        {
            struct HistoryJson:
                public JsonObject
            {
                ABC_JSON_CONSTRUCTORS(HistoryJson, JsonObject)
                ABC_JSON_STRING(txid, "tx_hash", nullptr)
                ABC_JSON_INTEGER(height, "height", 0)
            };
            HistoryJson json(arrayJson[i]);

            bc::hash_digest hash;
            if (!json.txidOk() || !bc::decode_hash(hash, json.txid()))
                return ABC_ERROR(ABC_CC_Error, "Bad txid");

            bc::client::history_row row;
            row.output.hash = hash;
            row.output_height = json.height();
            row.spend.hash = bc::null_hash;
            history.push_back(row);
        }

        onReply(history);
        return Status();
    };
예제 #5
0
void Item_factory::set_material_from_json(JsonObject& jo, std::string member, itype* new_item_template)
{
    //If the value isn't found, just return a group of null materials
    std::string material_list[2] = {"null", "null"};
    if( jo.has_array(member) ) {
        JsonArray jarr = jo.get_array(member);
        if (jarr.size() > 2) {
            debugmsg("Too many materials provided for item %s", new_item_template->id.c_str());
        }
        material_list[0] = jarr.get_string(0);
        material_list[1] = jarr.get_string(1);
    } else if ( jo.has_string(member) ) {
        material_list[0] = jo.get_string(member);
    }
    new_item_template->m1 = material_list[0];
    new_item_template->m2 = material_list[1];
}
예제 #6
0
QPixmap QSanRoomSkin::getProgressBarPixmap(int percentile) const
{
    QVariant allMaps_var = _m_imageConfig[S_SKIN_KEY_PROGRESS_BAR_IMAGE];
    if (!allMaps_var.canConvert<JsonArray>())
        return QPixmap(1, 1);

    JsonArray allMaps = allMaps_var.value<JsonArray>();

    for (int i = 0; i < allMaps.size(); i++) {
        if (!isNumber(allMaps[i].value<JsonArray>()[0])) continue;
        int thred = allMaps[i].value<JsonArray>()[0].toInt();
        if (thred >= percentile) {
            if (!isString(allMaps[i].value<JsonArray>()[1])) continue;
            return getPixmapFromFileName(allMaps[i].value<JsonArray>()[1].toString(), true);
        }
    }
    return QPixmap(1, 1);
}
예제 #7
0
bool IQSanComponentSkin::QSanShadowTextFont::tryParse(const QVariant &arg)
{
    if (!arg.isValid() || !arg.canConvert<JsonArray>()) return false;
    JsonArray args = arg.value<JsonArray>();
    if (args.size() < 4) return false;
    if (!QSanSimpleTextFont::tryParse(arg)) return false;
    if (args.size() >= 8) {
        m_shadowRadius = args[4].toInt();
        m_shadowDecadeFactor = args[5].toDouble();
        JsonUtils::tryParse(args[6], m_shadowOffset);

        JsonArray color = args[7].value<JsonArray>();
        m_shadowColor = QColor(color[0].toInt(), color[1].toInt(), color[2].toInt(), color[3].toInt());
    } else {
        m_shadowRadius = -1;
    }
    return true;
}
예제 #8
0
static void run_iterator_test() {
  StaticJsonDocument<JSON_ARRAY_SIZE(2)> doc;
  JsonArray array = doc.to<JsonArray>();
  array.add(12);
  array.add(34);

  TIterator it = array.begin();
  TIterator end = array.end();

  REQUIRE(end != it);
  REQUIRE(12 == it->template as<int>());
  REQUIRE(12 == static_cast<int>(*it));
  ++it;
  REQUIRE(end != it);
  REQUIRE(34 == it->template as<int>());
  REQUIRE(34 == static_cast<int>(*it));
  ++it;
  REQUIRE(end == it);
}
예제 #9
0
/*
 * Test a complex object.
 */
void JsonTest::testComplexObject() {
  JsonObject object;
  object.Add("age", 10);
  object.Add("name", "simon");
  object.Add("male", true);

  JsonArray *array = object.AddArray("lucky numbers");
  array->Append(2);
  array->Append(5);

  string expected = (
      "{\n"
      "  \"age\": 10,\n"
      "  \"lucky numbers\": [2, 5],\n"
      "  \"male\": true,\n"
      "  \"name\": \"simon\"\n"
      "}");
  OLA_ASSERT_EQ(expected, JsonWriter::AsString(object));
}
예제 #10
0
void sfx::load_sound_effects( JsonObject &jsobj )
{
    if( !sound_init_success ) {
        return;
    }
    const id_and_variant key( jsobj.get_string( "id" ), jsobj.get_string( "variant", "default" ) );
    const int volume = jsobj.get_int( "volume", 100 );
    auto &effects = sfx_resources.sound_effects[ key ];

    JsonArray jsarr = jsobj.get_array( "files" );
    while( jsarr.has_more() ) {
        sound_effect new_sound_effect;
        const std::string file = jsarr.next_string();
        new_sound_effect.volume = volume;
        new_sound_effect.resource_id = add_sfx_path( file );

        effects.push_back( new_sound_effect );
    }
}
예제 #11
0
void CreateProc::_ResizeFiles()
{
    AppSetting *setting = AppSetting::Instance();

    JsonObject *projData = new JsonObject();
    projData->Add("pid",_pid);

    JsonArray *pages = new JsonArray();
    projData->AddObject("pages", pages);

    for (auto fileItor = _filesMapping->begin(); fileItor != _filesMapping->end(); ++fileItor)
    {
        JsonObject *singleFile = new JsonObject();

        string srcFilename = FileSys::GetFilename(fileItor->first);
        string saveFilename = FileSys::GetFilename(fileItor->second);
        string fileExtension = FileSys::GetFileExtension(fileItor->first);

        singleFile->Add("filename", srcFilename);
        singleFile->Add("imagedir", fileItor->first);

        for (auto sizeItor = setting->pic_size->begin(); sizeItor != setting->pic_size->end(); ++sizeItor)
        {
            string optDir = FileSys::FormatDir(setting->file_save_dir + _zipRandName + "/" + sizeItor->first);
            FileSys::CreateDirectory(optDir);

            //  Resize Picture, but need to rename
            saveFilename = Assist::GenerateRandomFilename(saveFilename) + fileExtension;
            OpencvEx::ResizePictureFile(fileItor->second, optDir + saveFilename, sizeItor->second->x, sizeItor->second->y);

            singleFile->Add("image" + sizeItor->first, optDir + saveFilename);
        }

        pages->AddObject(singleFile);
        safe_del(singleFile);
    }

    //  push to server
    _PushJsonToServer(projData->ToString());

    safe_del(pages);
    safe_del(projData);
}
예제 #12
0
bool Item_factory::is_mod_target(JsonObject& jo, std::string member, std::string weapon)
{
    //If none is found, just use the standard none action
    unsigned is_included = false;
    //Otherwise, grab the right label to look for
    if ( jo.has_array(member) ) {
        JsonArray jarr = jo.get_array(member);
        while (jarr.has_more() && is_included == false){
            if (jarr.next_string() == weapon){
                is_included = true;
            }
        }
    } else {
        if (jo.get_string(member) == weapon){
            is_included = true;
        }
    }
    return is_included;
}
예제 #13
0
bool EffectHandler::save(JsonArray& array, uint8_t ID, const char * name)
{
	//Serial.printf("[EffectHandler::save] Effect = %s, ID = %s\n", _name, ID);

	int index = 0;

	for (JsonArray::iterator it = array.begin(); it != array.end(); ++it) {
		// *it contains the JsonVariant which can be casted as usuals
		//const char* value = *it;

		JsonObject& preset = *it;

		if (preset.containsKey("ID")) {

			if ( preset["ID"] == ID) {
				array.removeAt(index) ;
				DebugEffectHandlerf("[EffectHandler::save] preset %u removed\n", ID);
				break; 
			}

		}

		index++;
		// this also works:
		//value = it->as<const char*>();

	}

	JsonObject& current = array.createNestedObject();

	current["ID"] = ID;
	current["name"] = name;
	current["effect"] = _name;

	if (addJson(current)) {
		return true;
	} else {
		return false;
	}


};
예제 #14
0
void MonsterGroupManager::LoadMonsterGroup(JsonObject &jo)
{
    MonsterGroup g;

    g.name = jo.get_string("name");
    g.defaultMonster = jo.get_string("default");
    if (jo.has_array("monsters")){
        JsonArray monarr = jo.get_array("monsters");

        while (monarr.has_more()) {
            JsonObject mon = monarr.next_object();
            std::string name = mon.get_string("monster");
            int freq = mon.get_int("freq");
            int cost = mon.get_int("cost_multiplier");
            int pack_min = 1;
            int pack_max = 1;
            if(mon.has_member("pack_size")){
                JsonArray packarr = mon.get_array("pack_size");
                pack_min = packarr.next_int();
                pack_max = packarr.next_int();
            }
            int starts = 0;
            int ends = 0;
            if(mon.has_member("starts")){
                starts = mon.get_int("starts");
            }
            if(mon.has_member("ends")){
                ends = mon.get_int("ends");
            }
            MonsterGroupEntry new_mon_group = MonsterGroupEntry(name,freq,cost,pack_min,pack_max,starts,ends);
            if(mon.has_member("conditions")){
              JsonArray conditions_arr = mon.get_array("conditions");
              while(conditions_arr.has_more()){
                new_mon_group.conditions.push_back(conditions_arr.next_string());
              }
            }
            g.monsters.push_back(new_mon_group);
        }
    }

    monsterGroupMap[g.name] = g;
}
예제 #15
0
Status
loginServerMessages(JsonPtr &result, const std::list<std::string> &usernames)
{
    const auto url = ABC_SERVER_ROOT "/v2/messages";

    // Compute all userIds:
    JsonArray loginIds;
    std::map<std::string, std::string> loginIdMap;
    for (const auto &username: usernames)
    {
        std::shared_ptr<LoginStore> store;
        ABC_CHECK(LoginStore::create(store, username));
        const auto loginId = base64Encode(store->userId());
        loginIds.append(json_string(loginId.c_str()));
        loginIdMap[loginId] = username;
    }

    JsonObject request;
    ABC_CHECK(request.set("loginIds", loginIds));

    // Make the request:
    HttpReply reply;
    ABC_CHECK(AirbitzRequest().request(reply, url, "POST", request.encode()));
    ServerReplyJson replyJson;
    ABC_CHECK(replyJson.decode(reply));

    // Insert the original usernames into the results:
    JsonArray arrayJson(replyJson.results());
    size_t size = arrayJson.size();
    for (size_t i = 0; i < size; i++)
    {
        JsonObject objectJson(arrayJson[i]);
        const auto loginId = objectJson.getString("loginId", nullptr);
        if (!loginId) continue;
        const auto username = loginIdMap.find(loginId);
        if (username == loginIdMap.end()) continue;
        ABC_CHECK(objectJson.set("username", username->second));
    }

    result = arrayJson;
    return Status();
}
예제 #16
0
void requirements::load_obj_list(JsonArray &jsarr, std::vector< std::vector<T> > &objs) {
    while (jsarr.has_more()) {
        if(jsarr.test_array()) {
            std::vector<T> choices;
            JsonArray ja = jsarr.next_array();
            while (ja.has_more()) {
                choices.push_back(T());
                choices.back().load(ja);
            }
            if( !choices.empty() ) {
                objs.push_back( choices );
            }
        } else {
            // tool qualities don't normally use a list of alternatives
            // each quality is mandatory.
            objs.push_back(std::vector<T>(1));
            objs.back().back().load(jsarr);
        }
    }
}
예제 #17
0
std::set<std::string> JsonObject::get_tags(const std::string &name)
{
    std::set<std::string> ret;
    int pos = positions[name];
    if (pos <= start) {
        return ret; // empty set
    }
    jsin->seek(pos);
    // allow single string as tag
    if (jsin->test_string()) {
        ret.insert(jsin->get_string());
        return ret;
    }
    // otherwise assume it's an array and error if it isn't.
    JsonArray jsarr = jsin->get_array();
    while (jsarr.has_more()) {
        ret.insert(jsarr.next_string());
    }
    return ret;
}
예제 #18
0
void quality_requirement::load( JsonArray &jsarr )
{
    JsonObject quality_data = jsarr.next_object();
    type = quality_id( quality_data.get_string( "id" ) );
    level = quality_data.get_int( "level", 1 );
    count = quality_data.get_int( "amount", 1 );
    if( count <= 0 ) {
        quality_data.throw_error( "quality amount must be a positive number", "amount" );
    }
    // Note: level is not checked, negative values and 0 are allow, see butchering quality.
}
void ConfigurationReader::readPoints(JsonArray& points, Room* room) {
	char *name;
	char *type;
	Point *point;
	int ctrPin, btnPin;
	for(JsonArray::iterator it=points.begin(); it!=points.end(); ++it)
	{
	    JsonObject &jsonPoint = it->asObject();
	    name = jsonPoint[JSON_POINT_NAME];
	    type = jsonPoint[JSON_POINT_TYPE];
	    ctrPin = jsonPoint[JSON_POINT_CTRPIN];
	    btnPin = jsonPoint[JSON_POINT_BTNPIN];

	    if (strcmp(type, JSON_POINT_TYPE_LIGHT) == 0) {
	    	point = new LightPoint(ctrPin, btnPin, name);
	    	room->addPoint(point);
	    	point->printDiagnosticInfo();
	    }
	}
}
예제 #20
0
void tool_comp::load( JsonArray &ja )
{
    if( ja.test_string() ) {
        // constructions uses this format: [ "tool", ... ]
        type = ja.next_string();
        count = -1;
    } else {
        JsonArray comp = ja.next_array();
        type = comp.get_string( 0 );
        count = comp.get_int( 1 );
        requirement = comp.size() > 2 && comp.get_string( 2 ) == "LIST";
    }
    if( count == 0 ) {
        ja.throw_error( "tool count must not be 0" );
    }
    // Note: negative count means charges (of the tool) should be consumed
}
예제 #21
0
void map_data_common_t::load( JsonObject &jo, const std::string &src )
{
    if( jo.has_member( "examine_action" ) ) {
        examine = iexamine_function_from_string( jo.get_string( "examine_action" ) );
    } else {
        examine = iexamine_function_from_string( "none" );
    }

    if( jo.has_array( "harvest_by_season" ) ) {
        JsonArray jsarr = jo.get_array( "harvest_by_season" );
        while( jsarr.has_more() ) {
            JsonObject harvest_jo = jsarr.next_object();
            auto season_strings = harvest_jo.get_tags( "seasons" );
            std::set<season_type> seasons;
            std::transform( season_strings.begin(), season_strings.end(), std::inserter( seasons,
                            seasons.begin() ),
            []( const std::string & data ) {
                return io::string_to_enum<season_type>( data );
            } );

            harvest_id hl;
            if( harvest_jo.has_array( "entries" ) ) {
                // @todo: A better inline name - can't use id or name here because it's not set yet
                size_t num = harvest_list::all().size() + 1;
                hl = harvest_list::load( harvest_jo, src,
                                         string_format( "harvest_inline_%d", static_cast<int>( num ) ) );
            } else if( harvest_jo.has_string( "id" ) ) {
                hl = harvest_id( harvest_jo.get_string( "id" ) );
            } else {
                jo.throw_error( "Each harvest entry must specify either \"entries\" or \"id\"",
                                "harvest_by_season" );
            }

            for( season_type s : seasons ) {
                harvest_by_season[ s ] = hl;
            }
        }
    }

    optional( jo, false, "description", description, translated_string_reader );
}
예제 #22
0
void
StratumConnection::getTx(
    const bc::client::obelisk_codec::error_handler &onError,
    const bc::client::obelisk_codec::fetch_transaction_handler &onReply,
    const bc::hash_digest &txid)
{
    JsonArray params;
    params.append(json_string(bc::encode_hash(txid).c_str()));

    auto errorShim = [onError](Status status)
    {
        onError(std::make_error_code(std::errc::bad_message));
    };

    auto decoder = [onReply](JsonPtr payload) -> Status
    {
        if (!json_is_string(payload.get()))
            return ABC_ERROR(ABC_CC_JSONError, "Bad reply format");

        bc::data_chunk rawTx;
        if (!base16Decode(rawTx, json_string_value(payload.get())))
            return ABC_ERROR(ABC_CC_ParseError, "Bad transaction format");

        // Convert rawTx to bc::transaction_type:
        bc::transaction_type tx;
        try
        {
            auto deserial = bc::make_deserializer(rawTx.begin(), rawTx.end());
            bc::satoshi_load(deserial.iterator(), deserial.end(), tx);
        }
        catch (bc::end_of_stream)
        {
            return ABC_ERROR(ABC_CC_ParseError, "Bad transaction format");
        }

        onReply(tx);
        return Status();
    };

    sendMessage("blockchain.transaction.get", params, errorShim, decoder);
}
예제 #23
0
void melee_actor::load_internal( JsonObject &obj, const std::string & )
{
    // Optional:
    if( obj.has_array( "damage_max_instance" ) ) {
        JsonArray arr = obj.get_array( "damage_max_instance" );
        damage_max_instance = load_damage_instance( arr );
    } else if( obj.has_object( "damage_max_instance" ) ) {
        damage_max_instance = load_damage_instance( obj );
    }

    min_mul = obj.get_float( "min_mul", 0.0f );
    max_mul = obj.get_float( "max_mul", 1.0f );
    move_cost = obj.get_int( "move_cost", 100 );
    accuracy = obj.get_int( "accuracy", INT_MIN );

    optional( obj, was_loaded, "miss_msg_u", miss_msg_u, translated_string_reader,
              _( "The %s lunges at you, but you dodge!" ) );
    optional( obj, was_loaded, "no_dmg_msg_u", no_dmg_msg_u, translated_string_reader,
              _( "The %1$s bites your %2$s, but fails to penetrate armor!" ) );
    optional( obj, was_loaded, "hit_dmg_u", hit_dmg_u, translated_string_reader,
              _( "The %1$s bites your %2$s!" ) );
    optional( obj, was_loaded, "miss_msg_npc", miss_msg_npc, translated_string_reader,
              _( "The %s lunges at <npcname>, but they dodge!" ) );
    optional( obj, was_loaded, "no_dmg_msg_npc", no_dmg_msg_npc, translated_string_reader,
              _( "The %1$s bites <npcname>'s %2$s, but fails to penetrate armor!" ) );
    optional( obj, was_loaded, "hit_dmg_npc", hit_dmg_npc, translated_string_reader,
              _( "The %1$s bites <npcname>'s %2$s!" ) );

    if( obj.has_array( "body_parts" ) ) {
        JsonArray jarr = obj.get_array( "body_parts" );
        while( jarr.has_more() ) {
            JsonArray sub = jarr.next_array();
            const body_part bp = get_body_part_token( sub.get_string( 0 ) );
            const float prob = sub.get_float( 1 );
            body_parts.add_or_replace( bp, prob );
        }
    }

    if( obj.has_array( "effects" ) ) {
        JsonArray jarr = obj.get_array( "effects" );
        while( jarr.has_more() ) {
            JsonObject eff = jarr.next_object();
            effects.push_back( load_mon_effect_data( eff ) );
        }
    }
}
예제 #24
0
bool QSanProtocol::Packet::parse(const QByteArray &raw)
{
    if (raw.length() > S_MAX_PACKET_SIZE) {
        return false;
    }

    JsonDocument doc = JsonDocument::fromJson(raw);
    JsonArray result = doc.array();

    if (!JsonUtils::isNumberArray(result, 0, 3) || result.size() > 5)
        return false;

    globalSerial = result[0].toUInt();
    localSerial = result[1].toUInt();
    m_packetDescription = static_cast<PacketDescription>(result[2].toInt());
    m_command = (CommandType)result[3].toInt();

    if (result.size() == 5)
        m_messageBody = result[4];
    return true;
}
예제 #25
0
// loads JsonObject vehicle definition into a cached state so that it can be held until after itypes have been initialized
void game::load_vehicle(JsonObject &jo)
{
    vehicle_prototype *vproto = new vehicle_prototype;

    vproto->id = jo.get_string("id");
    vproto->name = jo.get_string("name");

    std::map<point, bool> cargo_spots;

    JsonArray parts = jo.get_array("parts");
    point pxy;
    std::string pid;
    while (parts.has_more()){
        JsonObject part = parts.next_object();
        pxy = point(part.get_int("x"), part.get_int("y"));
        pid = part.get_string("part");
        vproto->parts.push_back(std::pair<point, std::string>(pxy, pid));
        if ( vehicle_part_types[pid].has_flag("CARGO") ) {
            cargo_spots[pxy] = true;
        }
    }

    JsonArray items = jo.get_array("items");
    while(items.has_more()) {
        JsonObject spawn_info = items.next_object();
        vehicle_item_spawn next_spawn;
        next_spawn.x = spawn_info.get_int("x");
        next_spawn.y = spawn_info.get_int("y");
        next_spawn.chance = spawn_info.get_int("chance");
        if(next_spawn.chance <= 0 || next_spawn.chance > 100) {
            debugmsg("Invalid spawn chance in %s (%d, %d): %d%%",
                vproto->name.c_str(), next_spawn.x, next_spawn.y, next_spawn.chance);
        } else if ( cargo_spots.find( point(next_spawn.x, next_spawn.y) ) == cargo_spots.end() ) {
            debugmsg("Invalid spawn location (no CARGO vpart) in %s (%d, %d): %d%%",
                vproto->name.c_str(), next_spawn.x, next_spawn.y, next_spawn.chance);
        }
        if(spawn_info.has_array("items")) {
            //Array of items that all spawn together (ie jack+tire)
            JsonArray item_group = spawn_info.get_array("items");
            while(item_group.has_more()) {
                next_spawn.item_ids.push_back(item_group.next_string());
            }
        } else if(spawn_info.has_string("items")) {
            //Treat single item as array
            next_spawn.item_ids.push_back(spawn_info.get_string("items"));
        }
        if(spawn_info.has_array("item_groups")) {
            //Pick from a group of items, just like map::place_items
            JsonArray item_group_names = spawn_info.get_array("item_groups");
            while(item_group_names.has_more()) {
                next_spawn.item_groups.push_back(item_group_names.next_string());
            }
        } else if(spawn_info.has_string("item_groups")) {
            next_spawn.item_groups.push_back(spawn_info.get_string("item_groups"));
        }
        vproto->item_spawns.push_back(next_spawn);
    }

    vehprototypes.push(vproto);
}
예제 #26
0
void Item_factory::load_gun(JsonObject& jo)
{
    it_gun* gun_template = new it_gun();
    gun_template->ammo = jo.get_string("ammo");
    gun_template->skill_used = Skill::skill(jo.get_string("skill"));
    gun_template->dmg_bonus = jo.get_int("ranged_damage");
    gun_template->range = jo.get_int("range");
    gun_template->dispersion = jo.get_int("dispersion");
    gun_template->recoil = jo.get_int("recoil");
    gun_template->durability = jo.get_int("durability");
    gun_template->burst = jo.get_int("burst");
    gun_template->clip = jo.get_int("clip_size");
    gun_template->reload_time = jo.get_int("reload");
    gun_template->pierce = jo.get_int("pierce", 0);
    gun_template->ammo_effects = jo.get_tags("ammo_effects");

    if ( jo.has_array("valid_mod_locations") ) {
        JsonArray jarr = jo.get_array("valid_mod_locations");
        while (jarr.has_more()){
            JsonArray curr = jarr.next_array();
            gun_template->valid_mod_locations.insert(std::pair<std::string, int>(curr.get_string(0), curr.get_int(1)));
            gun_template->occupied_mod_locations.insert(std::pair<std::string, int>(curr.get_string(0), 0));
        }
    }

    itype *new_item_template = gun_template;
    load_basic_info(jo, new_item_template);
}
예제 #27
0
파일: aflAjax.cpp 프로젝트: mofon001/AflLib
JsonArray* SystemFile::getDirList(int pid,int level)
{
	String sql;
	sql.printf("SELECT file_id,file_name FROM tb_file2 WHERE file_lname='' AND file_pid=%d ORDER BY file_name;", pid);
	SQRes res = m_db->exec(sql);

	JsonArray* array = new JsonArray();
	while (res->next())
	{
		JsonHash* dir = new JsonHash();
		int id = atoi(res->getColumn(0));
		dir->add("id", createJson(id));
		dir->add("name", createJson(res->getColumn(1)));
		if (level)
		{
			JsonArray* child = getDirList(id, level - 1);
			dir->add("child", child);
		}
		array->add(dir);
	}
	return array;
}
예제 #28
0
Status
loginServerUploadLogs(const Account *account)
{
    const auto url = ABC_SERVER_ROOT "/account/debug";
    JsonPtr json;
    HttpReply reply;
    DataChunk logData = debugLogLoad();

    if (account)
    {
        JsonArray jsonArray;
        auto ids = account->wallets.list();
        for (const auto &id: ids)
        {
            std::shared_ptr<Wallet> wallet;
            if (cacheWallet(wallet, nullptr, id.c_str()))
            {
                DataChunk watchData;
                ABC_CHECK(fileLoad(watchData, watcherPath(*wallet)));
                jsonArray.append(
                    json_string(base64Encode(watchData).c_str()));
            }
        }

        json.reset(json_pack("{ss, ss, ss}",
                             ABC_SERVER_JSON_L1_FIELD, base64Encode(account->login.lobby.authId()).c_str(),
                             ABC_SERVER_JSON_LP1_FIELD, base64Encode(account->login.authKey()).c_str(),
                             "log", base64Encode(logData).c_str()));
        if (jsonArray)
            json_object_set(json.get(), "watchers", jsonArray.get());
    }
    else
    {
        json.reset(json_pack("{ss}", "log", base64Encode(logData).c_str()));
    }

    ABC_CHECK(AirbitzRequest().post(reply, url, json.encode()));
    return Status();
}
예제 #29
0
void ma_technique::load( JsonObject &jo, const std::string &src )
{
    optional( jo, was_loaded, "name", name, translated_string_reader );
    optional( jo, was_loaded, "description", description, translated_string_reader );

    if( jo.has_member( "messages" ) ) {
        JsonArray jsarr = jo.get_array("messages");
        player_message = jsarr.get_string( 0 );
        if( !player_message.empty() ) {
            player_message = _(player_message.c_str());
        }
        npc_message = jsarr.get_string( 1 );
        if( !npc_message.empty() ) {
            npc_message = _(npc_message.c_str());
        }
    }

    optional( jo, was_loaded, "crit_tec", crit_tec, false );
    optional( jo, was_loaded, "defensive", defensive, false );
    optional( jo, was_loaded, "disarms", disarms, false );
    optional( jo, was_loaded, "dummy", dummy, false );
    optional( jo, was_loaded, "dodge_counter", dodge_counter, false );
    optional( jo, was_loaded, "block_counter", block_counter, false );
    optional( jo, was_loaded, "miss_recovery", miss_recovery, false );
    optional( jo, was_loaded, "grab_break", grab_break, false );

    optional( jo, was_loaded, "weighting", weighting, 1 );

    optional( jo, was_loaded, "down_dur", down_dur, 0 );
    optional( jo, was_loaded, "stun_dur", stun_dur, 0 );
    optional( jo, was_loaded, "knockback_dist", knockback_dist, 0 );
    optional( jo, was_loaded, "knockback_spread", knockback_spread, 0 );

    optional( jo, was_loaded, "aoe", aoe, "" );
    optional( jo, was_loaded, "flags", flags, auto_flags_reader<>{} );

    reqs.load( jo, src );
    bonuses.load( jo );
}
예제 #30
0
void load_recipe_category( JsonObject &jsobj )
{
    std::string category = jsobj.get_string( "id" );

    if( category.find( "CC_" ) != 0 ) {
        jsobj.throw_error( "Crafting category id has to be prefixed with 'CC_'" );
    }

    craft_cat_list.push_back( category );

    std::string cat_name = get_cat_name( category );

    craft_subcat_list[category] = std::vector<std::string>();
    JsonArray subcats = jsobj.get_array( "recipe_subcategories" );
    while( subcats.has_more() ) {
        std::string subcat_id = subcats.next_string();
        if( subcat_id.find( "CSC_" + cat_name + "_" ) != 0 && subcat_id != "CSC_ALL" ) {
            jsobj.throw_error( "Crafting sub-category id has to be prefixed with CSC_<category_name>_" );
        }
        craft_subcat_list[category].push_back( subcat_id );
    }
}