Ejemplo n.º 1
0
//-----------------------------------------------------------------------------------
void EngineConfig::LoadSceneSettings(Json::Value root, Json::Reader reader)
{
	Json::Value settings = root["scenes"];
	int componentCount = settings.size();

	for( int i=0; i< componentCount; ++i )
	{
		Json::Value componentVal = settings[i];
		Json::Value::Members members = componentVal.getMemberNames();

		map<std::string, std::string> mapValues;
		for( Json::Value::Members::iterator it = members.begin(); it != members.end(); ++it)
		{
			std::string memberName = *it;
			std::string value = componentVal[memberName].asString();
			
			mapValues[memberName] = value;

		}

		std::string sceneName = mapValues["name"];
		std::string fileName = mapValues["file"];

		SceneData *sceneData = new SceneData( sceneName, fileName );

		scenes[sceneName] = sceneData;
	}

	settings = root["startscene"];
	startScene = scenes[settings.asCString()];
}
Ejemplo n.º 2
0
FB::variant jsonValueToVariant( Json::Value root )
{
    Json::Value def;
    if (root.isString())
        return root.asString();
    else if (root.isBool())
        return root.asBool();
    else if (root.isDouble())
        return root.asDouble();
    else if (root.isInt())
        return root.asInt();
    else if (root.isUInt())
        return root.asUInt();
    else if (root.isNull())
        return FB::FBNull();
    else if (root.isArray()) {
        FB::VariantList outList;
        for (size_t i = 0; i < root.size(); ++i) {
            outList.push_back(jsonValueToVariant(root.get(i, def)));
        }
        return outList;
    } else if (root.isObject()) {
        Json::Value::Members members = root.getMemberNames();
        FB::VariantMap outMap;
        for (Json::Value::Members::iterator it = members.begin(); it != members.end(); ++it)
        {
            outMap[*it] = jsonValueToVariant(root.get(*it, def));
        }
        return outMap;
    } else {
        return FB::FBVoid();
    }
}
/**
 * Updates a configuration map with the given json node.
 *
 * @param configurationMap The configuration map to be updated.
 * @param currentNode The node to be used to update the configuration map.
 */
void JsonConfigurationParser::updateConfigurationMap(ConfigurationMap *configurationMap, const Json::Value &currentNode) {
    // retrieves the menber names
    Json::Value::Members currentNodeMembers = currentNode.getMemberNames();

    // retrieves the current node members iterator
    Json::Value::Members::iterator currentNodeMembersIterator = currentNodeMembers.begin();

    // itearates over all the current node members
    while(currentNodeMembersIterator != currentNodeMembers.end()) {
        // retrieves the property name
        std::string &propertyName = *currentNodeMembersIterator;

        // retrieves the property value
        Json::Value propertyValue = currentNode[propertyName];

        // creates the configuration value
        ConfigurationValue *configurationValue = this->createConfigurationValue(propertyValue);

        // sets the propery in the configuration map
        configurationMap->setProperty(propertyName, configurationValue);

        // increments the current node members iterator
        currentNodeMembersIterator++;
    }
}
Ejemplo n.º 4
0
void JsonParameters::importParameters(Json::Value parametersImport)
{
    if (parametersImport.isObject()) {
        Json::Value::Members members = parametersImport.getMemberNames();
        Json::Value::Members::iterator it;

        for (it=members.begin(); it!=members.end(); it++) {
            string name = *it;
            JsonParameter *parameter = getParameter(name);
            if (parameter != NULL) {
                if (parameter->canDeserialize(parametersImport[name])) {
                    parameter->deserialize(parametersImport[name]);
                } else {
                    std::cerr << "Can't load parameter " << name << std::endl;
                }
            } else {
                std::cerr << "Non-existent parameter: " << name << std::endl;
            }
        }
    } else {
        if (!parametersImport.isNull()) {
            std::cerr << "Parameters values should be an object" << std::endl;
        }
    }
}
Ejemplo n.º 5
0
void SceneLoader::Load(const char* strFileName, GameObject *rootGameObject)
{
	GameObject *pGo = 0;
	Json::Value root;
	Json::Reader reader;

	const char* jsonText = ReadFileIntoString( strFileName );

	if( !reader.parse( jsonText, root ) )
	{
		return;
	}


	Json::Value componentsVal = root["objects"];
	int componentCount = componentsVal.size();

	for( int i=0; i< componentCount; ++i )
	{
		Json::Value componentVal = componentsVal[i];
		Json::Value::Members members = componentVal.getMemberNames();
		
		std::map<std::string, std::string> mapParams;
		for( Json::Value::Members::iterator it = members.begin(); it != members.end(); ++it)
		{
			std::string memberName = *it;
			std::string value = componentVal[memberName].asString();

			mapParams[memberName] = value;
		}

		CreateSceneObject( rootGameObject, mapParams );
	}
}
Ejemplo n.º 6
0
configGoodsItem*  CData::getConfigOfGoods(int tempid)
{
    
    if(m_config_goods_dic->count() < 1)
    {
//        const char * path=FileUtils::getInstance()->fullPathForFilename("itemconfig.json").c_str();
//        ifstream ifs;
//        ifs.open(path);
//        assert(ifs.is_open());
        Json::Reader reader;
        Json::Value root;
        Json::Value items;
        
        Json::Value::Members members;
        
//        Json::Value::iterator it;
        Json::Value::Members::iterator it;
        
        string path = FileUtils::getInstance()->fullPathForFilename("item.json");
        __String* str = __String::createWithContentsOfFile(path.c_str());
            
        if(reader.parse(str->getCString(), root)){
            
            members = root.getMemberNames();
            it = members.begin();
            while (it != members.end()) {
                
                items = root[std::string(*it)];
                
                configGoodsItem * item= new configGoodsItem();
                char inttostr[20]="";
                sprintf(inttostr, "%d",tempid);
                
                item->bodytype=items["bodyType"].asInt();
                item->name=items["name"].asString();
                item->pinzhi=items["baseQuality"].asInt();
                item->des=items["description"].asString();
                item->tempid = items["id"].asInt();
                item->icon = items["icon"].asInt();
                item->maxexp = items["maxexp"].asInt();
                item->growTemp = items["growTemp"].asInt();
                item->comprice = items["comprice"].asInt();
                item->compound = items["compound"].asInt();
                
                
                m_config_goods_dic->setObject(item, item->tempid);
                
                it++;
            }
        
         //   ifs.close();
    
        }

    }
    
    
    return (configGoodsItem*)m_config_goods_dic->objectForKey(tempid);
    
}
Ejemplo n.º 7
0
void Registry::Interface::_parseWidgets(Json::Value& value,
                                        const Engine::Object& loader) {
  unsigned int index = _spans.size() - 1;
  for (Json::Value::iterator it = value["widgets"].begin();
        it != value["widgets"].end();
        ++it) {
    if ((*it).isObject()) {
      if ((*it).isMember("widget")) {
        _spans[index]++;
        const char* widget_name = (*it)["widget"].asCString();

        const Registry::Widget& widget = loader.loadWidget(widget_name);
        Apsis::World::Object& object = *(new Apsis::World::Object);

        if ((*it).isMember("properties")) {
          Json::Value::Members members = (*it)["properties"].getMemberNames();
          for (Json::Value::Members::iterator property_it = members.begin();
                property_it != members.end();
                ++property_it) {
            const char* name = (*property_it).c_str();
            unsigned int property_id = Apsis::Registry::Property::id(name);

            if ((*it)["properties"][name].isDouble()) {
              object.set(property_id, (*it)["properties"][name].asDouble());
            }
            else if ((*it)["properties"][name].isString()) {
              object.set(property_id, (*it)["properties"][name].asCString());
            }
            else if ((*it)["properties"][name].isIntegral()) {
              object.set(property_id, (long)(*it)["properties"][name].asInt());
            }
          }
        }

        // Defaults
        for (unsigned int i = 0; i < widget.propertyCount(); i++) {
          const char* name = widget.propertyName(i);
          const char* def  = widget.propertyDefault(i);

          if (!object.has(name)) {
            object.set(name, def);
          }
        }

        // Push to tree
        _widgets.push_back(&widget);
        _objects.push_back(&object);

        // Child windows
        _spans.push_back(0);
        if ((*it).isMember("widgets")) {
          _parseWidgets(*it, loader);
        }
      }
    }
    else {
      throw "Interface file's 'widgets' section is malformed.";
    }
  }
}
Ejemplo n.º 8
0
bool CTestjsoncpp::test_Parse()
{
	std::wstring wstrJson = ReleaseJsonStr();
	std::string strJson = wstr2str(wstrJson, CP_UTF8);
	Json::Reader jsonReader;
	Json::Value root;
	jsonReader.parse(strJson, root);

	std::string strresult = root["result"].asString();
	std::cout << "result:" << strresult << std::endl;

	std::cout << "data:" << std::endl;
	Json::Value jvData = root["data"];
	if(jvData.isArray())
	{
		std::cout << "[" << std::endl;
		//item
		for (Json::Value::iterator it = jvData.begin(); it != jvData.end(); ++it)
		{
			std::cout << "{" << std::endl;
			Json::Value item = *it;
			Json::Value::Members memItem = item.getMemberNames();
			//mem in item
			for (Json::Value::Members::iterator itItem = memItem.begin(); itItem != memItem.end(); ++itItem)
			{
				std::string strKey = *itItem;
				std::string strValue = item[strKey].asString();
				std::cout << strKey << ":" << strValue << std::endl;
			}
			std::cout << "}" << std::endl;
		}
		std::cout << "]" << std::endl;
	}
	return false;
}
Ejemplo n.º 9
0
int Database::load()
{
    if (open() != 0)
        return -1;
    Json::Reader reader;
    if (!reader.parse(file_in, root, false)){
        ERR("Json reader parse error, maybe empty file\n");
        root.clear();
        return -1;
    }
    try {
        Json::Value::Members member = root.getMemberNames();
        Json::Value::Members::iterator it = member.begin();
        for (; it != member.end(); it++){
            if (load_obj(string_to_wstring(*it)) == NULL)
                ERR("Load object error\n");
        }
    }
    catch (Json::LogicError & e) {
    	cout << e.what() << endl;
        ERR("Json file data not correct\n");
        close_json();
        return -1;
    }
    
    return 0;
}
Ejemplo n.º 10
0
/// 从 Json 解析数据到 dictNode 中
static void parseFromJsonToDictionary(const Json::Value & jsonNode, CCDictionary * dictNode)
{
	Json::Value::Members members = jsonNode.getMemberNames();
	for (Json::Value::Members::iterator beg = members.begin(); beg != members.end(); ++beg)
	{
        std::string name = *beg;
		Json::Value child = jsonNode[name];
		
		if (child.isArray())
		{
			CCArray * arr = CCArray::create();
			parseFromJsonToArray(child, arr);
			dictNode->setObject(arr, name);
		}
		else if (child.isObject())
		{
			CCDictionary * dict = CCDictionary::create();
			parseFromJsonToDictionary(child, dict);
			dictNode->setObject(dict, name);
		}
		else if (child.isString())
		{
			CCString * str = CCString::createWithFormat("%s", child.asCString());
			dictNode->setObject(str, name);
		}
		else if (child.isInt())
		{
			CCString * str = CCString::createWithFormat("%d", child.asInt());
			dictNode->setObject(str, name);
		}
		else if (child.isUInt())
		{
			CCString * str = CCString::createWithFormat("%u", child.asUInt());
			dictNode->setObject(str, name);
		}
		else if (child.isInt64())
		{
			CCString * str = CCString::createWithFormat("%lld", child.asInt64());
			dictNode->setObject(str, name);
			
		}
		else if (child.isUInt64())
		{
			CCString * str = CCString::createWithFormat("%llu", child.asUInt64());
			dictNode->setObject(str, name);
		}
		else if (child.isDouble())
		{
			CCString * str = CCString::createWithFormat("%f", child.asDouble());
			dictNode->setObject(str, name);
		}
		else if (child.isBool())
		{
			CCString * str = CCString::createWithFormat("%d", child.asInt());
			dictNode->setObject(str, name);
		}
	}
}
Ejemplo n.º 11
0
void JsonTree::init( const string &key, const Json::Value &value, bool setType, NodeType nodeType, ValueType valueType )
{
    mKey = key;
	mNodeType = nodeType;
	mParent = 0;
	mValue = "";
	mValueType = valueType;

	if( ! value.isNull() && ( value.isArray() || value.isObject() ) ) {
        if( value.isArray() ) {
            mNodeType = NODE_ARRAY;
            for ( uint32_t i = 0; i < value.size(); i++ ) {
                pushBack( JsonTree( "", value[ i ] ) );
            }
        }
		else if( value.isObject() ) {
            mNodeType = NODE_OBJECT;
            Json::Value::Members members = value.getMemberNames();
            for( Json::Value::Members::const_iterator memberIt = members.begin(); memberIt != members.end(); ++memberIt ) {
				string key = *memberIt;
                pushBack( JsonTree( key, value[ key ] ) );
            }
        }
    }
	else {
		if( value.isBool() ) {
			mValue = toString( value.asBool() );
			if( setType ) {
				mValueType = VALUE_BOOL;
			}
		}
		else if ( value.isDouble() ) { 
			mValue = toString( value.asDouble() );
			if ( setType ) {
				mValueType = VALUE_DOUBLE;
			}
		}
		else if ( value.isInt() ) { 
			mValue = toString( value.asInt() );
			if ( setType ) {
				mValueType = VALUE_INT;
			}
		}
		else if ( value.isString() ) { 
			mValue = toString( value.asString() );
			if ( setType ) {
				mValueType = VALUE_STRING;
			}
		}
		else if ( value.isUInt() ) { 
			mValue = toString( value.asUInt() );
			if ( setType ) {
				mValueType = VALUE_UINT;
			}
		}
	}
}
Ejemplo n.º 12
0
bool VehicleInfo::getVehicleData(Json::Value &message,Json::Value &result)
{
    Json::Value vehicle;
    Json::Value data;
    Json::Value params;
    bool ret = false;

    params = message["params"];

    vehicle = g_VehicleInfoJson["vehicle"];

    Json::Value::Members mem = params.getMemberNames();
    for (Json::Value::Members::iterator iter = mem.begin(); iter != mem.end(); iter++) {
        std::string infoitem = std::string(*iter);
        if (infoitem != "appID" && infoitem != "request") {
            Json::Value require = params[infoitem];
            if (!require.isBool())
                continue;
            if (!require.asBool())
                continue;

            if (vehicle.isMember(infoitem))
                data[infoitem] = vehicle[infoitem];
            ret = true;
        }
    }

    if (ret) {
        Json::Value::Members mem = data.getMemberNames();
        for (Json::Value::Members::iterator iter = mem.begin(); iter != mem.end(); iter++) {
            std::string infoitem = std::string(*iter);
            result[infoitem] = data[infoitem];
        }

        result["code"] = 0;
        result["method"] = "VehicleInfo.GetVehicleData";
    } else {
        result["message"] = "Params rpc, are not avaliable";
        result["code"] = 9;
        result["method"]="VehicleInfo.GetVehicleData";
    }

    return ret;
}
Ejemplo n.º 13
0
configMonsterItem* CData::getConfigOfMonster(int tempid)
{
    if(m_config_monster_dic->count() < 1)
    {
        //   const char * path=FileUtils::getInstance()->fullPathForFilename("hero.json").c_str();
        //        ifstream ifs;
        //        ifs.open(path);
        //        assert(ifs.is_open());
        
        Json::Reader reader;
        Json::Value root;
        Json::Value items;
        
        Json::Value::Members members;
        
        //        Json::Value::iterator it;
        Json::Value::Members::iterator it;
        
        string path = FileUtils::getInstance()->fullPathForFilename("monster.json");
        __String* str = __String::createWithContentsOfFile(path.c_str());
        
        if(reader.parse(str->getCString(), root)){
            
            members = root.getMemberNames();
            it = members.begin();
            while (it != members.end()) {
                
                items = root[std::string(*it)];
                
                configMonsterItem * item= new configMonsterItem();
                char inttostr[20]="";
                sprintf(inttostr, "%d",tempid);
                
                
                
                item->id = items["id"].asInt();
                item->nickname = items["nickname"].asString();//" : "蛮夷邪士",
                                
                m_config_monster_dic->setObject(item, item->id);
                
                it++;
            }
            
                      
        }
        
    }
    
    
    return (configMonsterItem*)m_config_monster_dic->objectForKey(tempid);

}
Ejemplo n.º 14
0
int loadConfig(const char* filepath, Config& config)
{
	std::ifstream confFile;
	confFile.open(filepath);
	if (!confFile.is_open())
	{
		cerr << "could not open config file: " << filepath << endl;
		return -1;
	}
	else
	{
		cout << "config file opened" << endl;
	}

	confFile.seekg(0, ios::end);
	int fileLen = confFile.tellg();
	char *confStr = NULL;
	confStr = new char[fileLen+1];
	confFile.seekg(0, ios::beg);
	confFile.get(confStr, fileLen+1);
	//confStr[fileLen] = 0;

	Json::Reader reader;
	Json::Value confRoot;

	if (!reader.parse(confStr, confRoot))
	{
		cerr << "error parsing config file: " << endl << reader.getFormattedErrorMessages() << endl;
		return -2;
	}
	else
	{
		config.com.num = confRoot["COM"]["num"].asInt();
		config.com.baud = confRoot["COM"]["baud"].asInt();
		config.sock.port = confRoot["socket"]["port"].asInt();
		config.sock.rbuff = confRoot["socket"]["read_buffer"].asInt();
		config.sock.wbuff = confRoot["socket"]["send_buffer"].asInt();

		Json::Value::Members styleNames = confRoot["style"].getMemberNames();
		for (Json::Value::Members::iterator itr = styleNames.begin(); itr != styleNames.end();itr++)
		{
			config.style.styles.insert(map<string, string>::value_type(*itr, confRoot["style"][*itr].asString()));
		}
	}
	confFile.close();
	
	delete[] confStr;
	
	return 0;
	
}
Ejemplo n.º 15
0
Resource *ResourceManager::_load(std::string filename)
{
    Json::Reader reader(Json::Features::strictMode());

    Json::Value root;

    if (not reader.parse(readFile(filename), root))
    {
        std::cout << reader.getFormattedErrorMessages() << std::endl;
        return NULL;
    }

    std::unordered_map<std::string, ResPtr<Resource> > externalResources;

    if (root.isMember("external resources"))
    {
        Json::Value externResVal = root["external resources"];
        Json::Value::Members members = externResVal.getMemberNames();

        for (Json::Value::Members::iterator it = members.begin(); it != members.end(); ++it)
        {
            std::string name = *it;
            ResPtr<Resource> resource = load(externResVal[name].asString());

            externalResources[name] = resource;
        }
    }

    std::string resourceType = root["type"].asString();

    if (resourceType == "texture")
    {
        return loadTexture(getMember(root, "texture"), externalResources);
    } else if (resourceType == "model")
    {
        return loadModel(getMember(root, "model"), externalResources);
    } else if (resourceType == "mesh")
    {
        return loadMesh(getMember(root, "mesh"), externalResources);
    } else if (resourceType == "shader")
    {
        return loadShader(getMember(root, "shader"), externalResources);
    } else if (resourceType == "material")
    {
        return loadMaterial(getMember(root, "material"), externalResources);
    } else
    {
        throw std::runtime_error("Unknown resource type.");
    }
}
Ejemplo n.º 16
0
void SceneObject::initWith(Json::Value _val) 
{
	Json::Value::Members mems = _val.getMemberNames();
	Json::Value::Members::iterator mit;
	for (mit = mems.begin(); mit != mems.end(); mit++) {
		if ((*mit) == "Name") {
			m_Name = _val["Name"].asString();
		}else{
			if (Component_maker::ComponentExists((*mit))) {
				addComponent(Component_maker::makeComponent((*mit), this));
				m_Components[(*mit)]->initWith(_val[(*mit)]);
			}
		}
	}
}
Ejemplo n.º 17
0
bool OnlineProcess::init() {
    
    bool ret = parseJson(fileName_, configs_);
    if( !ret ) {
        std::cout<< "error in parse json" <<std::endl;
        return false;
    }
    sourceDir_ = "../source";
    if ( configs_["source_dir"].isString() ) {  
        sourceDir_ = configs_["source_dir"].asString();
    }
    
    ret = initResource();
    if( !ret ) {
        std::cout<<"init resource error " <<std::endl;
        return false;
    }
    //useLocalIdf_ = configs_["use_local_idf"].asBool();
    
	wordSplitDicVec_.clear();
    size_t size = configs_["wordsplit_dic"].size();
    for(size_t i=0 ; i<size ; i++ ){
        std::string name = sourceDir_ +"/" + configs_["wordsplit_dic"][i].asString();
        wordSplitDicVec_.push_back(name);
    }
    
	Tools& tools_  = ProcessResource::instance().tools() ;
	int result = tools_.m_wordsplit->load(wordSplitDicVec_);
    if ( result != 0 ) {
        std::cout<<"init wordsplit error" <<std::endl;
        return false;
    }
    
    Json::Value& strategy = configs_["strategy"];
    Json::Value::Members members = strategy.getMemberNames();
    Json::Value::Members::iterator iter  = members.begin();
    for( ;iter != members.end(); iter++ ) {
        std::string name  = *iter; 
        std::string ruleFile = strategy[name].asString();
        ProcessStrategy& ps = strategies_[name];
        ret = ps.init(ruleFile, *this);
        if( !ret ) {
            std::cout<<" init failed: "<< name <<std::endl;
            return false;
        }
    }
    return true;
}
Ejemplo n.º 18
0
    static inline
    void
    pack(msgpack::packer<Stream>& packer, const Json::Value& source) {
        switch(source.type()) {
        case Json::objectValue: {
            packer.pack_map(source.size());

            const Json::Value::Members keys(source.getMemberNames());

            for(auto it = keys.begin(); it != keys.end(); ++it) {
                packer << *it;
                pack(packer, source[*it]);
            }
        } break;

        case Json::arrayValue: {
            packer.pack_array(source.size());

            for(auto it = source.begin(); it != source.end(); ++it) {
                pack(packer, *it);
            }
        } break;

        case Json::booleanValue: {
            packer << source.asBool();
        } break;

        case Json::stringValue: {
            packer << source.asString();
        } break;

        case Json::realValue: {
            packer << source.asDouble();
        } break;

        case Json::intValue: {
            packer << source.asLargestInt();
        } break;

        case Json::uintValue: {
            packer << source.asLargestUInt();
        } break;

        case Json::nullValue: {
            packer << msgpack::type::nil();
        }}
    }
Ejemplo n.º 19
0
static void JsonToLLSD(const Json::Value &root, LLSD &output)
{
	if(root.isObject())
	{
		Json::Value::Members keys = root.getMemberNames();
		for(Json::Value::Members::const_iterator itr = keys.begin(); itr != keys.end(); ++itr)
		{
			LLSD elem;
			JsonToLLSD(root[*itr], elem);
			output[*itr] = elem;
		}
	}
	else if(root.isArray())
	{
		for(Json::Value::const_iterator itr = root.begin(); itr != root.end(); ++itr)
		{
			LLSD elem;
			JsonToLLSD(*itr, elem);
			output.append(elem);
		}
	}
	else
	{
		switch(root.type())
		{
			case Json::intValue:
				output = root.asInt();
				break;
			case Json::realValue:
			case Json::uintValue:
				output = root.asDouble();
				break;
			case Json::stringValue:
				output = root.asString();
				break;
			case Json::booleanValue:
				output = root.asBool();
				break;
			case Json::nullValue:
				output = LLSD();
				break;
			default:
				break;
		}
	}
}
Ejemplo n.º 20
0
inline void duk_push_json(duk_context *ctx, Json::Value val) {
	Json::ValueType type = val.type();

	int length, obj_index;

	switch (type) {
		case Json::nullValue:
			duk_push_null(ctx);
			break;
		case Json::intValue:
		case Json::uintValue:
		case Json::realValue:
			duk_push_number(ctx, val.asDouble());
			break;
		case Json::stringValue:
			duk_push_string(ctx, val.asCString());
			break;
		case Json::booleanValue:
			duk_push_boolean(ctx, val.asBool());
			break;
		case Json::arrayValue:
			length = val.size();
			obj_index = duk_push_array(ctx);

			for (int ndx = 0; ndx < length; ndx ++) {
				duk_push_json(ctx, val[ndx]);
				duk_put_prop_index(ctx, obj_index, ndx);
			}
			break;
		case Json::objectValue:
			obj_index = duk_push_object(ctx);

			Json::Value::Members keys = val.getMemberNames();
			Json::Value::Members::iterator it = keys.begin();
			while (it != keys.end()) {
				Json::Value value = val[*it];
				duk_push_string(ctx, it->c_str());
				duk_push_json(ctx, value);

				duk_put_prop(ctx, obj_index);

				it ++;
			}
			break;
	}
}
Ejemplo n.º 21
0
    void
    walk(const Json::Value& source) {
        switch(source.type()) {
        case Json::objectValue: {
            ++m_objects;

            const Json::Value::Members keys(source.getMemberNames());

            for(auto it = keys.begin(); it != keys.end(); ++it) {
                walk(source[*it]);
            }
        } break;

        case Json::arrayValue: {
            ++m_arrays;

            for(auto it = source.begin(); it != source.end(); ++it) {
                walk(*it);
            }
        } break;

        case Json::booleanValue: {
            ++m_bools;
        } break;

        case Json::stringValue: {
            ++m_strings;
        } break;

        case Json::realValue: {
            ++m_doubles;
        } break;

        case Json::intValue: {
            ++m_ints;
        } break;

        case Json::uintValue: {
            ++m_ints;
        } break;

        case Json::nullValue: {
            ++m_nulls;
        }}
    }
Ejemplo n.º 22
0
//-----------------------------------------------------------------------------------
void EngineConfig::LoadRenderSettings(Json::Value root, Json::Reader reader)
{
	Json::Value rendererSettings = root["renderer"];
	int componentCount = rendererSettings.size();

	for( int i=0; i< componentCount; ++i )
	{
		Json::Value componentVal = rendererSettings[i];
		Json::Value::Members members = componentVal.getMemberNames();

		for( Json::Value::Members::iterator it = members.begin(); it != members.end(); ++it)
		{
			std::string memberName = *it;
			std::string value = componentVal[memberName].asString();

			if( memberName == "api" )
			{
				if( value == "dx9" )
				{
					EngineConfig::renderConfig.RenderAPI = RendererConfig::DX9;
				}
				else if( value == "opengl" )
				{
					EngineConfig::renderConfig.RenderAPI = RendererConfig::OPENGL;
				}
			}
			else if( memberName == "screenwidth" )
			{
				sscanf_s(value.c_str(), "%d", &EngineConfig::renderConfig.ScreenWidth);
			}
			else if( memberName == "screenheight" )
			{
				sscanf_s(value.c_str(), "%d", &EngineConfig::renderConfig.ScreenHeight);
			}
			else if( memberName == "fullscreen" )
			{
				int bfullScreen = 0;
				sscanf_s(value.c_str(), "%d", &bfullScreen);

				EngineConfig::renderConfig.FullScreen = (bool) bfullScreen;
			}
		}
	}
}
Ejemplo n.º 23
0
config_t::component_map_t
config_t::parse(const Json::Value& config) {
    component_map_t components;

    if(config.empty()) {
        return components;
    }

    const Json::Value::Members names(config.getMemberNames());

    for(auto it = names.begin(); it != names.end(); ++it) {
        components[*it] = {
            config[*it].get("type", "unspecified").asString(),
            config[*it]["args"]
        };
    }

    return components;
}
Ejemplo n.º 24
0
Material *MaterialLoader::Load(const char* strFileName)
{
	Material *mat = 0;
	Json::Value root;
	Json::Reader reader;

	const char* jsonText = ReadFileIntoString( strFileName );

	if( !reader.parse( jsonText, root ) )
	{
		return 0;
	}

	Json::Value nameVal = root["name"];
	std::string name = nameVal.asString();
	mat = new Material( name.c_str() );

	Json::Value shaderVal = root["shader"];
	std::string shader = shaderVal.asString();
	mat->SetShaderProgram(shader.c_str());

	Json::Value componentsVal = root["parameters"];
	int componentCount = componentsVal.size();

	for( int i=0; i< componentCount; ++i )
	{
		Json::Value componentVal = componentsVal[i];
		Json::Value::Members members = componentVal.getMemberNames();
		
		std::map<std::string, std::string> mapParams;
		for( Json::Value::Members::iterator it = members.begin(); it != members.end(); ++it)
		{
			std::string memberName = *it;
			std::string value = componentVal[memberName].asString();

			mapParams[memberName] = value;
		}

		SetShaderParam( mat, mapParams );
	}

	return mat;
}
Ejemplo n.º 25
0
bool JsonSerializer::deserialize(const string& in, list<pair<string, any> >& lst)
{
	Json::Value root;
	Json::Reader reader;

	reader.parse(in, root);

	Json::Value::Members member;
	member = root.getMemberNames();
	for (auto it = member.begin(); it != member.end(); it++)
	{
		any any;
		auto value = root[(*it)];
		recurseWrite(value, any);
		lst.push_back(make_pair(*it, any));
	}

	return true;
}
Ejemplo n.º 26
0
bool CStreamManager::ReadJson(string strJson)
{
	Json::Value objRead;

	if (!m_JsonReader.parse(strJson, objRead))
	{
		return false;
	}

	Json::Value::Members members = objRead.getMemberNames();
	Json::Value::Members::iterator it;
	for (it = members.begin(); it != members.end(); it++)
	{
		string strResult = it->c_str();
		cout << "result key : " << strResult << endl;
		strResult = objRead[strResult].asString();
		cout << "result value : " << strResult << endl;
	}

	return true;
}
//-------------------------------------------------------------------------------------
void SpaceAvatarSelect::kbengine_onEvent(const KBEngine::EventData* lpEventData)
{
    switch(lpEventData->id)
    {
    case CLIENT_EVENT_SCRIPT:
    {
        const KBEngine::EventData_Script* peventdata = static_cast<const KBEngine::EventData_Script*>(lpEventData);
        if(peventdata->name == "update_avatars")
        {
            for(KBEngine::uint32 i=0; i<g_avatars.size(); i++)
            {
                mTrayMgr->destroyWidget(g_avatars[i]);
            }

            g_avatars.clear();

            Json::Reader reader;
            Json::Value root;

            if (reader.parse(peventdata->datas.c_str(), root))
            {
                Json::Value::Members mem = root.getMemberNames();
                for (auto iter = mem.begin(); iter != mem.end(); iter++)
                {
                    Json::Value& val = root[*iter];
                    std::string name = val[1].asString();
                    KBEngine::DBID dbid = val[Json::Value::UInt(0)].asUInt();

                    Ogre::String str = Ogre::String(name) + "_" + KBEngine::StringConv::val2str(dbid);
                    g_avatars.push_back(str);
                    mTrayMgr->createButton(OgreBites::TL_CENTER, str, str, 300);
                }
            }
        }
    }
    break;
    default:
        break;
    };
}
Ejemplo n.º 28
0
void Config::load(SceneRenderer * sceneRenderer, Manager * manager) {
    Json::Value root;   // will contains the root value after parsing.
	Json::Reader reader;

	std::ifstream file;
	file.open(fileName);
    bool parsingSuccessful = reader.parse(file, root, false);
	file.close();
	if(!parsingSuccessful) {
		// report to the user the failure and their locations in the document.
		System::Console::WriteLine("Failed to parse configuration\n");
		System::Console::WriteLine(gcnew System::String(reader.getFormatedErrorMessages().c_str()));
		throw std::runtime_error("Failed to parse configuration file: "+fileName);
	}

	Json::Value sceneJSON = root.get("scene", NULL);
	Scene * scene = sceneRenderer->getScene();
	Json::Value bgColorJSON = sceneJSON.get("backgroundColor", NULL);
	if(bgColorJSON != NULL) {
		scene->setBackgroundColor(jsonToColor(bgColorJSON));
	}

	Json::Value lightsJSON = sceneJSON.get("lights", NULL);
	if(lightsJSON != NULL) {
		Json::Value::Members lightsName = lightsJSON.getMemberNames();
		for(std::vector<std::string>::iterator it = lightsName.begin(); it != lightsName.end(); it++) {
			std::string lightName = *it;
			Json::Value lightJSON = lightsJSON[lightName];
			RGBColor lightColor = jsonToColor(lightJSON["color"]);
			LightSource * light;
			std::string lightTypeStr = lightJSON["type"].asString();
			if(lightTypeStr == "AmbientLightSource") {
				light = new AmbientLightSource(lightColor);
			} else if(lightTypeStr == "PointLightSource") {
				light = new PointLightSource(jsonToP3(lightJSON["position"]), lightColor);
				Json::Value specularCoefJSON = lightJSON.get("specularCoef", NULL);
				PointLightSource * pLight = static_cast<PointLightSource*>(light);
				if(specularCoefJSON != NULL) {
					pLight->setSpecularCoef(specularCoefJSON.asDouble());
				}
				Json::Value specularExpJSON = lightJSON.get("specularExponent", NULL);
				if(specularExpJSON != NULL) {
					pLight->setSpecularExponent(specularExpJSON.asDouble());
				}
			}
			Json::Value diffuseCoefJSON = lightJSON.get("diffuseCoef", NULL);
			if(diffuseCoefJSON != NULL) {
				light->setDiffuseCoef(diffuseCoefJSON.asDouble());
			}
			//scene->addLightSource(light);
			manager->getLightSources()->add(lightName, light, lightTypeStr);
		}
	}

	Json::Value objectsJSON = sceneJSON.get("objects", NULL);
	if(objectsJSON != NULL) {
		Json::Value::Members objectsName = objectsJSON.getMemberNames();
		for(std::vector<std::string>::iterator it = objectsName.begin(); it != objectsName.end(); it++) {
			std::string objectName = *it;
			Json::Value object3DJSON = objectsJSON[objectName];
			Object3D * object3D;
			std::string oject3DTypeStr = object3DJSON["type"].asString();
			if(oject3DTypeStr == "Sphere") {
				object3D = new Sphere(jsonToP3(object3DJSON["center"]),
									  object3DJSON["radius"].asDouble());
			} else if(oject3DTypeStr == "Plane") {
				
				if(object3DJSON.get("u", NULL) != NULL) {
					object3D = new Plane(jsonToP3(object3DJSON["p"]),
									 jsonToP3(object3DJSON["u"]),
									 jsonToP3(object3DJSON["v"]));
				} else {
					object3D = new Plane(jsonToP3(object3DJSON["p"]),
										 jsonToP3(object3DJSON["normal"]));
				}
			} else if(oject3DTypeStr == "Triangle") {
				object3D = new Triangle(jsonToP3(object3DJSON["A"]),
									    jsonToP3(object3DJSON["B"]),
										jsonToP3(object3DJSON["C"]));
			}
			//scene->addObject3D(object3D);
			manager->getObjects3D()->add(objectName, object3D, oject3DTypeStr);
		}
	}

	Json::Value polyhedraJSON = sceneJSON.get("polyhedra", NULL);
	if(polyhedraJSON != NULL) {
		Json::Value::Members polyhedraName = polyhedraJSON.getMemberNames();
		for(std::vector<std::string>::iterator it = polyhedraName.begin(); it != polyhedraName.end(); it++) {
			std::string objectName = *it;
			Json::Value polyhedronJSON = polyhedraJSON[objectName];
			Polyhedron * polyhedron;
			std::string polyhedronTypeStr = polyhedronJSON["type"].asString();
			if(polyhedronTypeStr == "Parallelepiped") {
				polyhedron = new Parallelepiped(jsonToP3(polyhedronJSON["A"]),
												jsonToP3(polyhedronJSON["B"]),
												jsonToP3(polyhedronJSON["C"]),
												jsonToP3(polyhedronJSON["D"]));
			} else if(polyhedronTypeStr == "Maya") {
				std::vector<Triangle*> triangles;
				std::string filename = polyhedronJSON["FileName"].asString();
				Json::Value pJSON = polyhedronJSON.get("p", NULL);
				P3 centerObj(0,0,0);
				if(pJSON != NULL) centerObj = jsonToP3(polyhedronJSON["p"]);
				Json::Value scaleJSON = polyhedronJSON.get("scale", NULL);
				double scale = 1.0;
				if(scaleJSON != NULL) scale = scaleJSON.asDouble();
				parseObjFile(filename, &triangles, centerObj, scale);
				polyhedron = new Polyhedron(triangles);
			} else continue;
			/*std::vector<Triangle*> triangles = polyhedron->getTriangles();
			for(std::vector<Triangle*>::iterator it = triangles.begin(); it != triangles.end(); it++) {
				scene->addObject3D(*it);
			}*/
			manager->getPolyhedra()->add(objectName, polyhedron, polyhedronTypeStr);
		}
	}

	Json::Value texturesJSON = root.get("textures", NULL);
	if(texturesJSON != NULL) {
		Json::Value::Members texturesName = texturesJSON.getMemberNames();
		for(std::vector<std::string>::iterator it = texturesName.begin(); it != texturesName.end(); it++) {
			std::string textureName = *it;
			Json::Value textureJSON = texturesJSON[textureName];
			Texture * texture = new Texture(textureJSON["FileName"].asString());
			manager->getTextures()->add(textureName, texture);
		}
	}

	Json::Value sceneRendererJSON = root.get("sceneRenderer", NULL);
	if(sceneRendererJSON == NULL) 
		throw std::runtime_error("sceneRenderer not defined in "+fileName);
	Json::Value cameraJSON = sceneRendererJSON["camera"];
	Camera * camera = new Camera(jsonToP3(cameraJSON["position"]),
								 jsonToP3(cameraJSON["direction"]),
								 cameraJSON.get("rotation", 0).asDouble());
	sceneRenderer->setCamera(camera);
	sceneRenderer->setCameraScreenDist(sceneRendererJSON.get("cameraScreenDist", 200).asDouble());
	manager->getCameras()->add("camera1", camera);

	std::string methodType = sceneRendererJSON["method"].get("type", "OrthographicProjection").asString();
	RenderingMethod * renderingMethod = NULL;
	if(methodType == "OrthographicProjection") {
		renderingMethod = new OrthographicProjection();
	} else if(methodType == "RayCasting") {
		renderingMethod = new RayCasting();
	} else if(methodType == "RayTracing") {
		renderingMethod = new RayTracing();
	}
	if(renderingMethod != NULL)
		sceneRenderer->setRenderingMethod(renderingMethod);

	Json::Value modelsJSON = sceneRendererJSON.get("models", NULL);
	if(modelsJSON != NULL) {
		Json::Value::Members modelsName = modelsJSON.getMemberNames();
		for(std::vector<std::string>::iterator it = modelsName.begin(); it != modelsName.end(); it++) {
			std::string modelName = *it;
			Json::Value modelJSON = modelsJSON[modelName];
			Json::Value modelTypeJSON = modelJSON.get("type", NULL);
			if(modelTypeJSON != NULL) {
				std::string modelTypeStr = modelTypeJSON.asString();
				Model * model;
				if(modelTypeStr == "SphereModel") {
					model = new SphereModel();
				} else if( modelTypeStr == "PlaneModel"	|| modelTypeStr == "TriangleModel") {
					model = new PlaneModel();
				} else if(modelTypeStr == "PolyhedronModel" || modelTypeStr == "ParallelepipedModel" || modelTypeStr == "MayaModel") {
					model = new PolyhedronModel();
				}
				Json::Value textureJSON = modelJSON.get("texture", NULL);
				if(textureJSON != NULL) {
					model->setTexture(manager->getTextures()->get(textureJSON.asString()));
				}
				Json::Value colorJSON = modelJSON.get("color", NULL);
				if(colorJSON != NULL) {
					model->setColor(jsonToColor(colorJSON));
				}
				Json::Value bumpJSON = modelJSON.get("bump", NULL);
				if(bumpJSON != NULL) {
					model->setBump(manager->getTextures()->get(bumpJSON.asString()));
				}
				Json::Value materialJSON = modelJSON.get("material", NULL);
				if(materialJSON != NULL) {
					model->setMaterial(jsonToMaterial(materialJSON));
				}
				Json::Value textureScaleJSON = modelJSON.get("textureScale", NULL);
				if(textureScaleJSON != NULL) {
					model->setTextureScale(textureScaleJSON.asDouble());
				}
				manager->getModels()->add(modelName, model);
				Json::Value modelObjectsJSON = modelJSON.get("objects", NULL);
				if(modelObjectsJSON != NULL) {
					for(unsigned int i=0; i < modelObjectsJSON.size(); i++) {
						std::string objectName = modelObjectsJSON[i].asString();
						Object3D * object3D = manager->getObjects3D()->get(objectName);
						Polyhedron * polyhedron = manager->getPolyhedra()->get(objectName);
						if(object3D != NULL) {
							sceneRenderer->getObject3DRenderer(object3D)->setModel(model);
						} else if(polyhedron != NULL) {
							std::vector<Triangle*> triangles = polyhedron->getTriangles();
							for(std::vector<Triangle*>::iterator it = triangles.begin(); it != triangles.end(); it++) {
								sceneRenderer->getObject3DRenderer(*it)->setModel(model);
							}
						} else continue;
					}
				}
			}
		}
	}
}
Ejemplo n.º 29
0
bool PVRIptvData::LoadEPG(time_t iStart, time_t iEnd) 
{
  PLATFORM::CLockObject critical(m_mutex);

  if (!m_manager.isLoggedIn())
  {
    XBMC->Log(LOG_NOTICE, "Not logged in. EPG not loaded.");
    m_bEGPLoaded = true;
    return false;
  }

  std::string epgString = m_manager.getEpg(); // TODO: add time range

  Json::Reader reader;
  Json::Value root;

  if (!reader.parse(epgString, root))
  {
    XBMC->Log(LOG_NOTICE, "Cannot parse EPG data. EPG not loaded.");
    m_bEGPLoaded = true;
    return false;
  }

  if (m_epg.size() > 0)
  {
    m_epg.clear();
  }

  Json::Value channels = root["channels"];
  Json::Value::Members chIds = channels.getMemberNames();
  for (Json::Value::Members::iterator i = chIds.begin(); i != chIds.end(); i++)
  {
    std::string strChId = *i;

    PVRIptvChannel* iptvchannel = FindChannel(strChId, "");
    if (iptvchannel != NULL)
    {
      PVRIptvEpgChannel epgChannel;
      epgChannel.strId = strChId;
      epgChannel.strName = iptvchannel->strChannelName;

      Json::Value epgData = channels[strChId];
      for (int j = 0; j < epgData.size(); j++)
      {
        Json::Value epgEntry = epgData[j];

        PVRIptvEpgEntry iptventry;
        iptventry.iBroadcastId = j;
        iptventry.iGenreType = 0;
        iptventry.iGenreSubType = 0;
        iptventry.iChannelId = iptvchannel->iUniqueId;
        iptventry.strTitle = epgEntry.get("title", "").asString();
        iptventry.strPlot = epgEntry.get("description", "").asString();
        iptventry.startTime = ParseDateTime(epgEntry.get("startTime", "").asString());
        iptventry.endTime = ParseDateTime(epgEntry.get("endTime", "").asString());

        XBMC->Log(LOG_DEBUG, "Loading TV show: %s - %s", strChId.c_str(), iptventry.strTitle.c_str());

        epgChannel.epg.push_back(iptventry);
      }

      m_epg.push_back(epgChannel);
    }

  }

  m_bEGPLoaded = true;
  XBMC->Log(LOG_NOTICE, "EPG Loaded.");

  return true;
}
Ejemplo n.º 30
0
size_t fluidinfo::Namespace::FWgetSubNamespaceInfo(void* ptr, size_t size, size_t nmemb, void* p)
{

    fluidinfo::Namespace *ns = (fluidinfo::Namespace*)p;
	std::cerr << "Content length: " << ns->lastContentLength << std::endl;

	if ( ns->idx_bufferGetNsInfo_ < ns->lastContentLength )
	{
		if ( !ns->bufferGetNsInfo_)
		{
			ns->bufferGetNsInfo_ = new char[ns->lastContentLength+1];
			memset(ns->bufferGetNsInfo_, 0, ns->lastContentLength+1);
			ns->idx_bufferGetNsInfo_ = 0;	
		}
		memcpy(ns->bufferGetNsInfo_ + ns->idx_bufferGetNsInfo_, ptr, size * nmemb);
		ns->idx_bufferGetNsInfo_ += size * nmemb;
	
		if ( ns->idx_bufferGetNsInfo_ < ns->lastContentLength )
			return size * nmemb;
	}
	
		std::cerr << ns->idx_bufferGetNsInfo_ << std::endl;
	
	//Now we have the whole buffer
	ns->idx_bufferGetNsInfo_ = 0;
	if ( !(size * nmemb) ) return 0;
	
	char* buf = ns->bufferGetNsInfo_;

    Json::Reader r;
    Json::Value root;

    r.parse((char*)buf, root);

    Json::Value::Members members = root.getMemberNames();

    for (Json::Value::Members::iterator it = members.begin(); it != members.end(); ++it)
    {

        if ( *it == "tagNames" ) {
			ns->_tagNames.clear();
            const Json::Value tagNames = root["tagNames"];
            for ( int index = 0; index < tagNames.size(); index++)
            {
                //tagNames[index].asString();
                ns->_tagNames.push_back(tagNames[index].asString());
            }
        }

        else if ( *it == "namespaceNames" ) {
			ns->_namespaceNames.clear();
            const Json::Value namespaceNames = root["namespaceNames"];
            for ( int index = 0; index < namespaceNames.size(); index++)
            {
                ns->_namespaceNames.push_back(namespaceNames[index].asString());
            }
        }

        else if ( *it == "id" ) {
            ns->_id = root["id"].asString();
            ns->_nonexistent = false;
        }

        else if ( *it == "description" ) {
            ns->_description = root["description"].asString();
        }

        else {
        }
    }

//    x->_id =  root["id"].asString();
//   x->_uri = root["URI"].asString();

    delete[] buf;
	ns->bufferGetNsInfo_ = NULL;

    return size * nmemb;
}