• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ rapidjson::Document类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中rapidjson::Document的典型用法代码示例。如果您正苦于以下问题:C++ Document类的具体用法?C++ Document怎么用?C++ Document使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Document类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: Process_Register

void Robot::Process_Register(rapidjson::Document& jsRequest, rapidjson::Document& jsResponse, string& sResponse)
{
	rapidjson::Document::AllocatorType& allocator = jsResponse.GetAllocator();

	int nErrcode = 0;
	string sErrmsg = "ok";
	if (!IsRegistered())
	{
		jsResponse.AddMember("question_bank_version", "1", allocator);
		string sRobotid = "";
		if (jsRequest.HasMember("body") && jsRequest["body"].IsObject())
		{
			rapidjson::Value& body = jsRequest["body"];
			if (body.HasMember("robot_id") && body["robot_id"].IsString())
			{
				sRobotid = body["robot_id"].GetString();
			}
			else if (jsRequest.HasMember("mac") && jsRequest["mac"].IsObject())
			{
				sRobotid = body["mac"].GetString();
			}
			if (!sRobotid.empty())
			{
				// 清除robot_id对应的旧链接
				SAContainerSingleLock csl(&RobotService::instance().m_robotManager.m_mapRobot, true);
				SPRobotPtr spRobot = RobotService::instance().m_robotManager.FindRobot(sRobotid);
				bool bSuccess = true;
				if (spRobot)
				{
					if (spRobot->isCreateisElapsed(10000))
					{  // 旧链接创建超过10s,可踢掉
						log.error( format("break session '%s'",spRobot->GetRobotID()));
						spRobot->Close();
						spRobot->SetValid(false);
					}
					else
					{
						log.warning(format("connect frequency too high,reserve old connection'%s'!", spRobot->GetRobotID()));
						SATCPConnectionPtr spSocket = m_spSocket;
						spSocket->Close();
						bSuccess = false;
						nErrcode = 6;
						sErrmsg = "connect frequency too high,reserve old connection!";
					}
				}
				if (bSuccess)
				{
					m_bIsRegistered = true;
					m_sID = sRobotid;
					RobotService::instance().m_robotManager.AddRobot(GetRobotPtr());
					//RobotService::instance().m_mapUnkownList.RemoveKey(m_sClient);
				}
				csl.Unlock();
			}
			else
			{
				nErrcode = 8;
				sErrmsg = "invalid msg data,miss robot_id param!";
				log.warning("invalid msg data,miss robot_id param!");
			}
		}
		else
		{
			nErrcode = 7;
			sErrmsg = "invalid msg data,miss necessary param!";
			log.warning("invalid msg data,miss necessary param!");
		}
	}
	else
	{
		nErrcode = 5;
		sErrmsg = "Process register failed,already registered!";
		log.error("Process register failed,already registered!");
	}
	jsResponse.AddMember("errcode", 0, allocator);
	jsResponse.AddMember("errmsg", "ok", allocator);
	sResponse = JsonDocToString(jsResponse);
}
开发者ID:zhangqiaoli,项目名称:robot,代码行数:78,代码来源:Robot.cpp


示例2: deserializeTextures

void deserializeTextures(std::vector<Texture> &textures, rapidjson::Document &doc)
{
	if (doc.HasParseError()) {
		std::cerr << "Incorrect json." << std::endl;
		return;
	}
	if (!doc.HasMember("textures")) {
		std::cerr << "Incorrect settings file. Directive lighting is absent." << std::endl;
		return;
	}


	rapidjson::Value& jTextures = doc["textures"];
	for (rapidjson::Value& jTex : jTextures.GetArray()) {
		Texture tex;
		assert(jTex.HasMember("file_path") && jTex["file_path"].IsString());
		tex.file_path = jTex["file_path"].GetString();

		if (jTex.HasMember("wrap_s_repeat"))
			tex.wrap_s_repeat = jTex["wrap_s_repeat"].GetBool();
		if (jTex.HasMember("wrap_t_repeat"))
			tex.wrap_t_repeat = jTex["wrap_t_repeat"].GetBool();

		if (jTex.HasMember("min_filter")) {
			if (jTex["min_filter"].IsInt()) {
				unsigned int glMinFiltervi[] = {
					GL_NEAREST,
					GL_LINEAR,
					GL_NEAREST_MIPMAP_NEAREST,
					GL_LINEAR_MIPMAP_NEAREST,
					GL_NEAREST_MIPMAP_LINEAR,
					GL_LINEAR_MIPMAP_LINEAR
				};
				tex.min_filter = glMinFiltervi[jTex["min_filter"].GetInt()];
			}
			else if (jTex["min_filter"].IsString()) {
				std::unordered_map<std::string, unsigned int> glMinFilters({
					{ "nearest", GL_NEAREST },
					{ "linear", GL_LINEAR },
					{ "nearest_mipmap_nearest", GL_NEAREST_MIPMAP_NEAREST },
					{ "linear_mipmap_nearest", GL_LINEAR_MIPMAP_NEAREST },
					{ "nearest_mipmap_linear", GL_NEAREST_MIPMAP_LINEAR },
					{ "linear_mipmap_linear", GL_LINEAR_MIPMAP_LINEAR }
				});
				tex.min_filter = glMinFilters[jTex["min_filter"].GetString()];
			}
		}

		if (jTex.HasMember("mag_filter")) {
			if (jTex["mag_filter"].IsInt())
				tex.mag_filter = (jTex["mag_filter"].GetInt() == 1 ? GL_NEAREST : GL_LINEAR);
			else if (jTex["mag_filter"].IsString())
				tex.mag_filter = (jTex["mag_filter"].GetString() == "nearest" ? GL_NEAREST : GL_LINEAR);
		}

		if (jTex.HasMember("env_mode")) {
			if (jTex["env_mode"].IsInt()) {
				unsigned int glEnvModevi[]{
					GL_REPLACE,
					GL_MODULATE,
					GL_ADD,
					GL_ADD_SIGNED,
					GL_INTERPOLATE,
					GL_SUBTRACT,
					GL_DOT3_RGB,
					GL_DOT3_RGBA
				};
				tex.env_mode = glEnvModevi[jTex["env_mode"].GetInt()];
			}
			else if (jTex["env_mode"].IsString()) {
				std::unordered_map<std::string, unsigned int> glEnvModes({
					{ "replace", GL_REPLACE },
					{ "modulate", GL_MODULATE },
					{ "add", GL_ADD },
					{ "add_signed", GL_ADD_SIGNED },
					{ "interpolate", GL_INTERPOLATE },
					{ "substract", GL_SUBTRACT },
					{ "dot3_rgb", GL_DOT3_RGB },
					{ "dot3_rgba", GL_DOT3_RGBA }
				});
				tex.env_mode = glEnvModes[jTex["env_mode"].GetString()];
			}
		}

		if (jTex.HasMember("detail_level"))
			tex.detail_level = jTex["detail_level"].GetInt();

		textures.push_back(tex);
	}
}
开发者ID:karkin96,项目名称:IU9,代码行数:90,代码来源:Texture.cpp


示例3: reinitialise

  void IKProblem::reinitialise(rapidjson::Document& document,
      boost::shared_ptr<PlanningProblem> problem)
  {
    clear();
    if (document.IsArray())
    {
        for (rapidjson::SizeType i = 0; i < document.Size(); i++)
        {
            rapidjson::Value& obj = document[i];
            if (obj.IsObject())
            {
                std::string constraintClass;
                getJSON(obj["class"], constraintClass);
                if (knownMaps_.find(constraintClass) != knownMaps_.end())
                {
                    TaskMap_ptr taskmap;
                    TaskMap_fac::Instance().createObject(
                    knownMaps_[constraintClass], taskmap);
                    taskmap->initialise(obj, server_, scenes_,problem);
                    std::string name = taskmap->getObjectName();
                    task_maps_[name] = taskmap;
                    TaskDefinition_ptr task;
                    TaskDefinition_fac::Instance().createObject("TaskSqrError", task);
                    TaskSqrError_ptr sqr = boost::static_pointer_cast<TaskSqrError>(task);
                    sqr->setTaskMap(taskmap);
                    int dim;
                    taskmap->taskSpaceDim(dim);
                    sqr->y_star0_.resize(dim);
                    sqr->rho0_(0) = 0.0;
                    sqr->rho1_(0) = 1.0;
                    sqr->object_name_ = name+ std::to_string((unsigned long) sqr.get());

                    // TODO: Better implementation of stting goals from JSON
                    sqr->y_star0_.setZero();

                    sqr->setTimeSteps(T_);
                    Eigen::VectorXd tspan(2);
                    Eigen::VectorXi tspani(2);

                    //	TODO fix ndarray problem

                    getJSON(obj["tspan"], tspan);
                    if (tspan(0) <= 0.0) tspan(0) = 0.0;
                    if (tspan(1) >= 1.0) tspan(1) = 1.0;
                    tspani(0) = (int) ((T_ - 1) * tspan(0));
                    tspani(1) = (int) ((T_ - 1) * tspan(1));
                    for (int t = tspani(0); t <= tspani(1); t++)
                    {
                        sqr->registerRho(Eigen::VectorXdRef_ptr(sqr->rho1_.segment(0, 1)),t);
                    }
                    sqr->wasFullyInitialised_ = true;
                    task_defs_[name] = task;
                }
                else
                {
                    // WARNING("Ignoring unknown constraint '"<<constraintClass<<"'");
                }
            }
            {
              throw_named("Invalid JSON document object!");
            }
        }


    }
    else
    {
        throw_named("Invalid JSON array!");
    }
  }
开发者ID:RiddickSky,项目名称:exotica,代码行数:70,代码来源:ik_problem.cpp


示例4: buildJson

void TriggerMng::buildJson(rapidjson::Document &document, cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)
{
    int count = pCocoNode[13].GetChildNum();
    int length = 0;
    int num = 0;
    int size = 0;
    int extent = 0;
    int border = 0;
    std::string key0;
    stExpCocoNode *pTriggersArray = pCocoNode[13].GetChildArray(pCocoLoader);
    
    document.SetArray();
    
    rapidjson::Document::AllocatorType& allocator = document.GetAllocator();
    for (int i0 = 0; i0 < count; ++i0)
    {
        rapidjson::Value vElemItem(rapidjson::kObjectType);
        
        border = pTriggersArray[i0].GetChildNum();
        stExpCocoNode *pTriggerArray = pTriggersArray[i0].GetChildArray(pCocoLoader);
        for (int i1 = 0; i1 < border; ++i1)
        {
            std::string key1 = pTriggerArray[i1].GetName(pCocoLoader);
            const char *str1 = pTriggerArray[i1].GetValue(pCocoLoader);
            
            if (key1.compare("actions") == 0)
            {
                rapidjson::Value actionsItem(rapidjson::kArrayType);
                
                length = pTriggerArray[i1].GetChildNum();
                stExpCocoNode *pActionsArray = pTriggerArray[i1].GetChildArray(pCocoLoader);
                for (int i2 = 0; i2 < length; ++i2)
                {
                    rapidjson::Value action(rapidjson::kObjectType);
                    
                    num = pActionsArray[i2].GetChildNum();
                    stExpCocoNode *pActionArray = pActionsArray[i2].GetChildArray(pCocoLoader);
                    for (int i3 = 0; i3 < num; ++i3)
                    {
                        std::string key2 = pActionArray[i3].GetName(pCocoLoader);
                        const char *str2 = pActionArray[i3].GetValue(pCocoLoader);
                        if (key2.compare("classname") == 0)
                        {
                            if (str2 != nullptr)
                            {
                                action.AddMember("classname", rapidjson::Value(str2,allocator), allocator);
                            }
                        }
                        else if (key2.compare("dataitems") == 0)
                        {
                            rapidjson::Value dataitems(rapidjson::kArrayType);
                            size = pActionArray[i3].GetChildNum();
                            stExpCocoNode *pDataItemsArray = pActionArray[i3].GetChildArray(pCocoLoader);
                            for (int i4 = 0; i4 < size; ++i4)
                            {
                                rapidjson::Value dataitem(rapidjson::kObjectType);
                                extent = pDataItemsArray[i4].GetChildNum();
                                stExpCocoNode *pDataItemArray = pDataItemsArray[i4].GetChildArray(pCocoLoader);
                                for (int i5 = 0; i5 < extent; ++i5)
                                {
                                    std::string key3 = pDataItemArray[i5].GetName(pCocoLoader);
                                    const char *str3 = pDataItemArray[i5].GetValue(pCocoLoader);
                                    if (key3.compare("key") == 0)
                                    {
                                        if (str3 != nullptr)
                                        {
                                            dataitem.AddMember("key", rapidjson::Value(str3,allocator), allocator);
                                        }
                                    }
                                    else
                                    {
                                        rapidjson::Type type = pDataItemArray[i5].GetType(pCocoLoader);
                                        if (type == rapidjson::kStringType)
                                        {
                                            dataitem.AddMember("value", rapidjson::Value(str3,allocator), allocator);
                                        }
                                        else
                                        {
                                            int nV = atoi(str3);
                                            float fV = utils::atof(str3);
                                            if (fabs(nV - fV) < 0.0000001)
                                            {
                                                dataitem.AddMember("value", nV, allocator);
                                            }
                                            else
                                            {
                                                dataitem.AddMember("value", fV, allocator);
                                            }
                                        }
                                    }
                                }
                                dataitems.PushBack(dataitem, allocator);
                            }
                            action.AddMember("dataitems", dataitems, allocator);
                        }
                    }
                    actionsItem.PushBack(action, allocator);
                }
                
                vElemItem.AddMember("actions", actionsItem, allocator);
//.........这里部分代码省略.........
开发者ID:1005491398,项目名称:Threes,代码行数:101,代码来源:TriggerMng.cpp


示例5: pyobj2doc

static bool
pyobj2doc(PyObject *object, rapidjson::Document& doc)
{
    if (PyBool_Check(object)) {
        if (Py_True == object) {
	        doc.SetBool(true);
        }
        else {
	        doc.SetBool(false);
        }
    }
    else if (Py_None == object) {
        doc.SetNull();
    }
    else if (PyFloat_Check(object)) {
        doc.SetDouble(PyFloat_AsDouble(object));
    }
    else if (PyInt_Check(object)) {
        doc.SetInt64(PyLong_AsLong(object));
    }
    else if (PyString_Check(object)) {
        doc.SetString(PyString_AsString(object), PyString_GET_SIZE(object));
    }
    else if (PyUnicode_Check(object)) {
        PyObject *utf8_item;
        utf8_item = PyUnicode_AsUTF8String(object);
        if (!utf8_item) {
            PyErr_SetString(PyExc_RuntimeError, "codec error.");
            return false;
        }
#ifdef PY3
        doc.SetString(PyBytes_AsString(utf8_item), PyBytes_GET_SIZE(utf8_item), doc.GetAllocator());
#else
        doc.SetString(PyString_AsString(utf8_item), PyString_GET_SIZE(utf8_item), doc.GetAllocator());
#endif
        Py_XDECREF(utf8_item);
    }
    else if (PyTuple_Check(object)) {
        int len = PyTuple_Size(object), i;
        doc.SetArray();
        rapidjson::Value _v;
        for (i = 0; i < len; ++i) {
            PyObject *elm = PyTuple_GetItem(object, i);
            if (false == pyobj2doc(elm, _v, doc)) {
                return false;
            }
            doc.PushBack(_v, doc.GetAllocator());
        }
    }
    else if (PyList_Check(object)) {
        int len = PyList_Size(object), i;
        doc.SetArray();
        rapidjson::Value _v;
        for (i = 0; i < len; ++i) {
            PyObject *elm = PyList_GetItem(object, i);
            if (false == pyobj2doc(elm, _v, doc)) {
                return false;
            }
            doc.PushBack(_v, doc.GetAllocator());
        }
    }
    else if (PyDict_Check(object)) {
        doc.SetObject();
        PyObject *key, *value;
        Py_ssize_t pos = 0;
        while (PyDict_Next(object, &pos, &key, &value)) {
            if (false == pyobj2doc_pair(key, value, doc)) {
                return false;
            }
        }
    }
    else {
        PyErr_SetString(PyExc_RuntimeError, "invalid python object");
        return false;
    }

    return true;
}
开发者ID:hhatto,项目名称:pyrapidjson,代码行数:78,代码来源:_pyrapidjson.cpp


示例6: Create

// -----------------------------------------------------------------------------
// Worker function for creating a SemiTrailingArm suspension using data in the
// specified RapidJSON document.
// -----------------------------------------------------------------------------
void SemiTrailingArm::Create(const rapidjson::Document& d) {
    // Invoke base class method.
    ChPart::Create(d);

    // Read Spindle data
    assert(d.HasMember("Spindle"));
    assert(d["Spindle"].IsObject());

    m_spindleMass = d["Spindle"]["Mass"].GetDouble();
    m_points[SPINDLE] = LoadVectorJSON(d["Spindle"]["COM"]);
    m_spindleInertia = LoadVectorJSON(d["Spindle"]["Inertia"]);
    m_spindleRadius = d["Spindle"]["Radius"].GetDouble();
    m_spindleWidth = d["Spindle"]["Width"].GetDouble();

    // Read trailing arm data
    assert(d.HasMember("Trailing Arm"));
    assert(d["Trailing Arm"].IsObject());

    m_armMass = d["Trailing Arm"]["Mass"].GetDouble();
    m_points[TA_CM] = LoadVectorJSON(d["Trailing Arm"]["COM"]);
    m_armInertia = LoadVectorJSON(d["Trailing Arm"]["Inertia"]);
    m_armRadius = d["Trailing Arm"]["Radius"].GetDouble();
    m_points[TA_O] = LoadVectorJSON(d["Trailing Arm"]["Location Chassis Outer"]);
    m_points[TA_I] = LoadVectorJSON(d["Trailing Arm"]["Location Chassis Inner"]);
    m_points[TA_S] = LoadVectorJSON(d["Trailing Arm"]["Location Spindle"]);

    // Read spring data and create force callback
    assert(d.HasMember("Spring"));
    assert(d["Spring"].IsObject());

    m_points[SPRING_C] = LoadVectorJSON(d["Spring"]["Location Chassis"]);
    m_points[SPRING_A] = LoadVectorJSON(d["Spring"]["Location Arm"]);
    m_springRestLength = d["Spring"]["Free Length"].GetDouble();

    if (d["Spring"].HasMember("Spring Coefficient")) {
        m_springForceCB = new LinearSpringForce(d["Spring"]["Spring Coefficient"].GetDouble());
    } else if (d["Spring"].HasMember("Curve Data")) {
        int num_points = d["Spring"]["Curve Data"].Size();
        MapSpringForce* springForceCB = new MapSpringForce();
        for (int i = 0; i < num_points; i++) {
            springForceCB->add_point(d["Spring"]["Curve Data"][i][0u].GetDouble(),
                                     d["Spring"]["Curve Data"][i][1u].GetDouble());
        }
        m_springForceCB = springForceCB;
    }

    // Read shock data and create force callback
    assert(d.HasMember("Shock"));
    assert(d["Shock"].IsObject());

    m_points[SHOCK_C] = LoadVectorJSON(d["Shock"]["Location Chassis"]);
    m_points[SHOCK_A] = LoadVectorJSON(d["Shock"]["Location Arm"]);

    if (d["Shock"].HasMember("Damping Coefficient")) {
        m_shockForceCB = new LinearDamperForce(d["Shock"]["Damping Coefficient"].GetDouble());
    } else if (d["Shock"].HasMember("Curve Data")) {
        int num_points = d["Shock"]["Curve Data"].Size();
        MapDamperForce* shockForceCB = new MapDamperForce();
        for (int i = 0; i < num_points; i++) {
            shockForceCB->add_point(d["Shock"]["Curve Data"][i][0u].GetDouble(),
                                    d["Shock"]["Curve Data"][i][1u].GetDouble());
        }
        m_shockForceCB = shockForceCB;
    }

    // Read axle inertia
    assert(d.HasMember("Axle"));
    assert(d["Axle"].IsObject());

    m_axleInertia = d["Axle"]["Inertia"].GetDouble();
}
开发者ID:projectchrono,项目名称:chrono,代码行数:75,代码来源:SemiTrailingArm.cpp


示例7: AddFace

int ytopen_sdk::AddFace(rapidjson::Document &result, const string& person_id, const std::vector<string>& imagePaths, int data_type, const string &tag)
{
    std::stringstream ss;
    ss<<host<<"/youtu/api/addface";

    string addr;
    addr.assign(ss.str());

    string req;
    string rsp;
    string imageData;

    StringBuffer sbuffer;
    Writer<StringBuffer> writer(sbuffer);

    writer.StartObject();
    writer.String("app_id"); writer.String(app_id.c_str());
    if(data_type == 0) {
        writer.String("images");
        writer.StartArray();
        for(int i = 0; i < imagePaths.size(); i++)
        {
            if(0 != read_image(imagePaths[i], imageData)) {
                cout << "read image failed " << imagePaths[i] << endl;
                continue;
            }
            string encode_data = b64_encode(imageData);
            writer.String(encode_data.c_str());
        }
        writer.EndArray();

    }else {
        writer.String("urls");
        writer.StartArray();
        for(int i = 0; i < imagePaths.size(); i++)
        {
            if(!imagePaths[i].empty()) {
                writer.String(imagePaths[i].c_str());
            }else {
                cout << "url empty." <<endl;
            }
        }
        writer.EndArray();
    }
    writer.String("person_id"); writer.String(person_id.c_str());
    writer.String("tag"); writer.String(tag.c_str());
    writer.EndObject();

    req = sbuffer.GetString();
    int ret = curl_method(addr, req, rsp);
    if(ret == 0) {
        result.Parse<rapidjson::kParseStopWhenDoneFlag>(rsp.c_str());
        if(result.HasParseError()) {
            std::cout << "RapidJson parse error " << result.GetParseError() << endl;
            return -1;
        }

    }else {
        return -1;
    }

    return 0;
}
开发者ID:Hali2reg,项目名称:Cplusplus_sdk,代码行数:63,代码来源:ytopen_sdk.cpp


示例8: preprocess_types

void preprocess_types(rapidjson::Document & d)
{
	/// pre record types
	for (auto & itr : d.GetArray()) {
		RAPIDJSON_ASSERT(itr.HasMember("category"));
		RAPIDJSON_ASSERT(itr.HasMember("name"));
		ensure_has_array_mem(itr, "attr", d);
		ensure_has_array_mem(itr, "msgid", d);
		ensure_has_object_mem(itr, "fields", d);
		ensure_has_array_mem(itr, "alias", d);
		s_type_lists[itr.FindMember("name")->value.GetString()] = &itr;
		for (auto & alias : itr.FindMember("alias")->value.GetArray()) {
			s_alias_lists[alias.GetString()] = & itr;
		}
		s_type_order.push_back(&itr);

	}

	/// messages enum
	for (auto & itr : d.GetArray()) {
		bool has_attr_msg = false;
		rapidjson::Value & attr_val = itr.FindMember("attr")->value;
		for (auto & sattr : attr_val.GetArray()) {
			RAPIDJSON_ASSERT(sattr.IsString());
			if (sattr == "msg") {
				has_attr_msg = true;
				attr_val.GetArray().Erase(&sattr);
			}
			else if (sattr == "export") {
				s_export_order.push_back(&itr);
			}
			else if (sattr == "pqxx") {
				add_pqxx(d, itr, true);
			}
		}

		rapidjson::Value & msgid_val = itr.FindMember("msgid")->value;
		if (has_attr_msg) {
			RAPIDJSON_ASSERT(itr.HasMember("name"));
			rapidjson::Value new_name(itr.FindMember("name")->value, d.GetAllocator());
			msgid_val.PushBack(new_name, d.GetAllocator());
		}

		for (const auto & smsgid : msgid_val.GetArray()) {
			RAPIDJSON_ASSERT(smsgid.IsString());
			s_msg_lists[smsgid.GetString()] = &itr;
		}

		if (msgid_val.GetArray().Size() > 0) {
			s_msg_order.push_back(&itr);
		}

		if (msgid_val.GetArray().Size() == 0) {
			itr.RemoveMember("msgid");
		}
	}

	for (auto i : s_pqxx_order) {
		std::cout << "\t" << i->FindMember("name")->value.GetString() << std::endl;;
	}
}
开发者ID:walkthetalk,项目名称:libem,代码行数:61,代码来源:preprocess.cpp


示例9: includeLocal

namespace Resources
{
// Global variables
// ->

_INTR_STRING _shaderPath = "assets/shaders/";
_INTR_STRING _shaderCachePath = "media/shaders/";
_INTR_STRING _shaderCacheFilePath = _shaderCachePath + "ShaderCache.json";

class GlslangIncluder : public glslang::TShader::Includer
{
public:
  IncludeResult* includeLocal(const char* p_RequestedSource,
                              const char* p_RequestingSource,
                              size_t p_InclusionDepth) override
  {
    const _INTR_STRING filePath = _shaderPath + p_RequestedSource;

    _INTR_FSTREAM inFileStream =
        _INTR_FSTREAM(filePath.c_str(), std::ios::in | std::ios::binary);
    _INTR_ASSERT(inFileStream);

    _INTR_OSTRINGSTREAM contents;
    contents << inFileStream.rdbuf();
    inFileStream.close();

    const _INTR_STRING sourceStr = contents.str();

    const char* sourceBuffer =
        (const char*)Memory::Tlsf::MainAllocator::allocate(
            (uint32_t)sourceStr.size());
    memcpy((void*)sourceBuffer, sourceStr.c_str(), sourceStr.size());

    IncludeResult result = {p_RequestedSource, sourceBuffer, sourceStr.size(),
                            nullptr};
    return new IncludeResult(result);
  }

  virtual void releaseInclude(IncludeResult* result) override
  {
    Memory::Tlsf::MainAllocator::free((void*)result->headerData);
    delete result;
  }
} _includer;

TBuiltInResource _defaultResource;
rapidjson::Document _shaderCache = rapidjson::Document(rapidjson::kObjectType);
// <-

bool isShaderUpToDate(uint32_t p_ShaderHash, const char* p_GpuProgramName)
{
  if (_shaderCache.HasMember(p_GpuProgramName))
  {
    return _shaderCache[p_GpuProgramName].GetUint() == p_ShaderHash;
  }

  return false;
}

void loadShaderCache()
{
  FILE* fp = fopen(_shaderCacheFilePath.c_str(), "rb");

  if (fp == nullptr)
  {
    _INTR_LOG_WARNING("Shader cache not available...");
    return;
  }

  char* readBuffer = (char*)Memory::Tlsf::MainAllocator::allocate(65536u);
  {
    rapidjson::FileReadStream is(fp, readBuffer, 65536u);
    _shaderCache.ParseStream(is);
    fclose(fp);
  }
  Memory::Tlsf::MainAllocator::free(readBuffer);
}

void saveShaderCache()
{
  FILE* fp = fopen(_shaderCacheFilePath.c_str(), "wb");

  if (fp == nullptr)
  {
    _INTR_LOG_ERROR("Failed to save shader cache...");
    return;
  }

  char* writeBuffer = (char*)Memory::Tlsf::MainAllocator::allocate(65536u);
  {
    rapidjson::FileWriteStream os(fp, writeBuffer, 65536u);
    rapidjson::PrettyWriter<rapidjson::FileWriteStream> writer(os);
    _shaderCache.Accept(writer);
    fclose(fp);
  }
  Memory::Tlsf::MainAllocator::free(writeBuffer);
}

void addShaderToCache(uint32_t p_ShaderHash, const char* p_GpuProgramName,
                      const SpirvBuffer& p_SpirvBuffer)
//.........这里部分代码省略.........
开发者ID:zvoronz,项目名称:Intrinsic,代码行数:101,代码来源:IntrinsicRendererResourcesGpuProgram.cpp


示例10: loadJSONsettingsFromDoc

int SettingRegistry::loadJSONsettingsFromDoc(rapidjson::Document& json_document, bool warn_duplicates)
{
    
    if (!json_document.IsObject())
    {
        cura::logError("JSON file is not an object.\n");
        return 3;
    }

    if (json_document.HasMember("machine_extruder_trains"))
    {
        categories.emplace_back("machine_extruder_trains", "Extruder Trains Settings Objects");
        SettingContainer* category_trains = &categories.back();
        const rapidjson::Value& trains = json_document["machine_extruder_trains"];
        if (trains.IsArray()) 
        {
            if (trains.Size() > 0 && trains[0].IsObject())
            {
                unsigned int idx = 0;
                for (auto it = trains.Begin(); it != trains.End(); ++it)
                {
                    SettingConfig* child = category_trains->addChild(std::to_string(idx), std::to_string(idx));
                    
                    for (rapidjson::Value::ConstMemberIterator setting_iterator = it->MemberBegin(); setting_iterator != it->MemberEnd(); ++setting_iterator)
                    {
                        _addSettingToContainer(child, setting_iterator, warn_duplicates, false);
                    }
                    
                    idx++;
                }
            }
        }
        else 
        {
            logError("Error: JSON machine_extruder_trains is not an array!\n");
        }
    }
    if (json_document.HasMember("machine_settings"))
    {
        categories.emplace_back("machine_settings", "Machine Settings");
        SettingContainer* category_machine_settings = &categories.back();
        
        const rapidjson::Value& json_object_container = json_document["machine_settings"];
        for (rapidjson::Value::ConstMemberIterator setting_iterator = json_object_container.MemberBegin(); setting_iterator != json_object_container.MemberEnd(); ++setting_iterator)
        {
            _addSettingToContainer(category_machine_settings, setting_iterator, warn_duplicates);
        }
    }
    
    if (json_document.HasMember("categories"))
    {
        for (rapidjson::Value::ConstMemberIterator category_iterator = json_document["categories"].MemberBegin(); category_iterator != json_document["categories"].MemberEnd(); ++category_iterator)
        {
            if (!category_iterator->value.IsObject())
            {
                continue;
            }
            if (!category_iterator->value.HasMember("label") || !category_iterator->value["label"].IsString())
            {
                continue;
            }
            if (!category_iterator->value.HasMember("settings") || !category_iterator->value["settings"].IsObject())
            {
                continue;
            }
            
            categories.emplace_back(category_iterator->name.GetString(), category_iterator->value["label"].GetString());
            SettingContainer* category = &categories.back();
            
            const rapidjson::Value& json_object_container = category_iterator->value["settings"];
            for (rapidjson::Value::ConstMemberIterator setting_iterator = json_object_container.MemberBegin(); setting_iterator != json_object_container.MemberEnd(); ++setting_iterator)
            {
                _addSettingToContainer(category, setting_iterator, warn_duplicates);
            }
        }
    }
    
    if (false && json_document.HasMember("overrides"))
    {
        const rapidjson::Value& json_object_container = json_document["overrides"];
        for (rapidjson::Value::ConstMemberIterator override_iterator = json_object_container.MemberBegin(); override_iterator != json_object_container.MemberEnd(); ++override_iterator)
        {
            SettingConfig* conf = getSettingConfig(override_iterator->name.GetString());
            _addSettingToContainer(conf, override_iterator, false);
        }
    }
    
    return 0;
}
开发者ID:nicanor-romero,项目名称:CuraEngine,代码行数:89,代码来源:settingRegistry.cpp


示例11: save

	void save(const int &value, rapidjson::Value &json, rapidjson::Document &document)
	{
		rapidjson::Value v(rapidjson::kNumberType);
		v.SetInt(value);
		json.AddMember("int", v, document.GetAllocator());
	}
开发者ID:r-lyeh-forks,项目名称:AGE,代码行数:6,代码来源:JsonSerializationBasicTypes.cpp


示例12: addOptionsToDoc

void MainWindow::addOptionsToDoc(rapidjson::Document &doc) {
    rapidjson::Value options(rapidjson::kObjectType);

    if (nodalDispCheckBox->isChecked()) {
        options.AddMember("save_nodal_displacements", true, doc.GetAllocator());
        rapidjson::Value rj_val;
        std::string val = nodalDispLineEdit->displayText().toStdString();
        rj_val.SetString(val.c_str(), val.length(), doc.GetAllocator());
        options.AddMember("nodal_displacements_filename", rj_val, doc.GetAllocator());
    }
    if (nodalForcesCheckBox->isChecked()) {
        options.AddMember("save_nodal_forces", true, doc.GetAllocator());
        rapidjson::Value rj_val;
        std::string val = nodalForcesLineEdit->displayText().toStdString();
        rj_val.SetString(val.c_str(), val.length(), doc.GetAllocator());
        options.AddMember("nodal_forces_filename", rj_val, doc.GetAllocator());
    }
    if (tieForcesCheckBox->isChecked()) {
        options.AddMember("save_tie_forces", true, doc.GetAllocator());
        rapidjson::Value rj_val;
        std::string val = tieForcesLineEdit->displayText().toStdString();
        rj_val.SetString(val.c_str(), val.length(), doc.GetAllocator());
        options.AddMember("ties_forces_filename", rj_val, doc.GetAllocator());
    }
    if (reportCheckBox->isChecked()) {
        options.AddMember("save_report", true, doc.GetAllocator());
        rapidjson::Value rj_val;
        std::string val = tieForcesLineEdit->displayText().toStdString();
        rj_val.SetString(val.c_str(), val.length(), doc.GetAllocator());
        options.AddMember("report_filename", rj_val, doc.GetAllocator());
    }
    options.AddMember("verbose", true, doc.GetAllocator());
    doc.AddMember("options", options, doc.GetAllocator());
}
开发者ID:latture,项目名称:threed-beam-fea,代码行数:34,代码来源:mainwindow.cpp


示例13: pyobj2doc

static void
pyobj2doc(PyObject *object, rapidjson::Document& doc)
{
    if (PyBool_Check(object)) {
        if (Py_True == object) {
	        doc.SetBool(true);
        }
        else {
	        doc.SetBool(false);
        }
    }
    else if (Py_None == object) {
        doc.SetNull();
    }
    else if (PyFloat_Check(object)) {
        doc.SetDouble(PyFloat_AsDouble(object));
    }
    else if (PyInt_Check(object)) {
        doc.SetInt(PyLong_AsLong(object));
    }
    else if (PyString_Check(object)) {
        doc.SetString(PyString_AsString(object), PyString_GET_SIZE(object));
    }
    else if (PyUnicode_Check(object)) {
#ifdef PY3
        PyObject *utf8_item;
        utf8_item = PyUnicode_AsUTF8String(object);
        if (!utf8_item) {
            // TODO: error handling
            printf("error\n");
        }

        doc.SetString(PyBytes_AsString(utf8_item),
                      PyBytes_Size(utf8_item), doc.GetAllocator());

        Py_XDECREF(utf8_item);
#else
        doc.SetString(PyBytes_AsString(object), PyBytes_GET_SIZE(object));
#endif
    }
    else if (PyTuple_Check(object)) {
        int len = PyTuple_Size(object), i;
        doc.SetArray();
        rapidjson::Value _v;
        for (i = 0; i < len; ++i) {
            PyObject *elm = PyList_GetItem(object, i);
            pyobj2doc(elm, _v, doc);
            doc.PushBack(_v, doc.GetAllocator());
        }
    }
    else if (PyList_Check(object)) {
        int len = PyList_Size(object), i;
        doc.SetArray();
        rapidjson::Value _v;
        for (i = 0; i < len; ++i) {
            PyObject *elm = PyList_GetItem(object, i);
            pyobj2doc(elm, _v, doc);
            doc.PushBack(_v, doc.GetAllocator());
        }
    }
    else if (PyDict_Check(object)) {
        doc.SetObject();
        PyObject *key, *value;
        Py_ssize_t pos = 0;
        while (PyDict_Next(object, &pos, &key, &value)) {
            pyobj2doc_pair(key, value, doc);
        }
    }
    else {
        // TODO: error handle
    }
}
开发者ID:ionelmc,项目名称:pyrapidjson,代码行数:72,代码来源:_pyrapidjson.cpp


示例14: loadModuleManifest

void ModuleManifest::loadModuleManifest(const rapidjson::Document &json)
{
    if ( json.HasMember(KEY_ModuleManifest_URL) && json[KEY_ModuleManifest_URL].IsString() )
    {
        _remoteModuleManifestUrl = json[KEY_ModuleManifest_URL].GetString();
    }
    
    if ( json.HasMember(KEY_FORCE_UPDATE) && json[KEY_FORCE_UPDATE].IsTrue() )
    {
        _forceUpdate = true;
    }
    else {
        _forceUpdate = false;
    }
    
    if ( json.HasMember(KEY_FORCE_ALERT) && json[KEY_FORCE_ALERT].IsTrue() )
    {
        _forceAlert = true;
    }
    else {
        _forceAlert = false;
    }
    
    // Retrieve package url
    if ( json.HasMember(KEY_PACKAGE_URL) && json[KEY_PACKAGE_URL].IsString() )
    {
        _packageUrl = json[KEY_PACKAGE_URL].GetString();
        // Append automatically "/"
        if (_packageUrl.size() > 0 && _packageUrl[_packageUrl.size() - 1] != '/')
        {
            _packageUrl.append("/");
        }
    }
    
    // Retrieve all assets
    if ( json.HasMember(KEY_ASSETS) )
    {
        const rapidjson::Value& assets = json[KEY_ASSETS];
        if (assets.IsObject())
        {
            for (rapidjson::Value::ConstMemberIterator itr = assets.MemberonBegin(); itr != assets.MemberonEnd(); ++itr)
            {
                std::string key = itr->name.GetString();
                Asset asset = parseAsset(key, itr->value);
                _assets.emplace(key, asset);
            }
        }
    }
    
    // Retrieve all search paths
    if ( json.HasMember(KEY_SEARCH_PATHS) )
    {
        const rapidjson::Value& paths = json[KEY_SEARCH_PATHS];
        if (paths.IsArray())
        {
            for (rapidjson::SizeType i = 0; i < paths.Size(); ++i)
            {
                if (paths[i].IsString()) {
                    _searchPaths.push_back(paths[i].GetString());
                }
            }
        }
    }
    
    _loaded = true;
}
开发者ID:darklinden,项目名称:cocos2dx-module-update,代码行数:66,代码来源:ModuleManifest.cpp


示例15: parseFromJson

int ServerConfig::parseFromJson(const rapidjson::Document& root){

	int ret = 0;

    if(!(root.HasMember("IP") && root["IP"].IsString()))
    {
        return -1;
    }
    IP = root["IP"].GetString();

    if(!(root.HasMember("Type") && root["Type"].IsString()))
    {
        return -1;
    }
    Type = root["Type"].GetString();

    if(!(root.HasMember("ZkUrl") && root["ZkUrl"].IsString()))
    {
        return -1;
    }
    ZkUrl = root["ZkUrl"].GetString();

    if(!(root.HasMember("NodePath") && root["NodePath"].IsString()))
    {
        return -1;
    }
    NodePath = root["NodePath"].GetString();

    if(!(root.HasMember("ModulePath") && root["ModulePath"].IsString()))
    {
        return -1;
    }
    ModulePath = root["ModulePath"].GetString();

    if(!(root.HasMember("ProjectPath") && root["ProjectPath"].IsString()))
    {
        return -1;
    }
    ProjectPath = root["ProjectPath"].GetString();

    if(!(root.HasMember("HttpIp") && root["HttpIp"].IsString()))
    {
        return -1;
    }
    HttpIp = root["HttpIp"].GetString();

    if(!(root.HasMember("LogPath") && root["LogPath"].IsString()))
    {
        return -1;
    }
    LogPath = root["LogPath"].GetString();

    if(!(root.HasMember("Debug") && root["Debug"].IsInt()))
    {
        return -1;
    }
    Debug = root["Debug"].GetInt();

    if(!(root.HasMember("Level") && root["Level"].IsInt()))
    {
        return -1;
    }
    Level = root["Level"].GetInt();

	ret = loadPortsConfigs(root["PortConfigs"]);
    //printf("Ip:%s, type:%s, zkurl:%s, nodepath:%s, module:%s, projeect:%s, httpip:%s, logpath:%s, debug:%d, level:%d\n", IP.c_str(), Type.c_str(), ZkUrl.c_str(), NodePath.c_str()
    //        , ModulePath.c_str(), ProjectPath.c_str()
    //        , HttpIp.c_str(), LogPath.c_str()
    //        , Debug, Level);

	return ret;
}
开发者ID:changjiashuai,项目名称:Teameeting-MsgServer,代码行数:72,代码来源:server_config.cpp


示例16:

#include "./SuperastCPP.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/stringbuffer.h"

#include <map>
#include <cassert>
#include <iostream>
#include <ostream>
#include <fstream>

// Our document
rapidjson::Document document;
rapidjson::Document::AllocatorType& allocator = document.GetAllocator();

// MAP TRANSLATIONS
const std::map<std::string,std::string> UNARY_OP_MAPPING {
    {"!", "not"},
    {"-", "neg"},
    {"+", "pos"},
};

const std::map<std::string,std::string> BINARY_OP_MAPPING {
    {"||", "or"},
    {"&&", "and"},
};

const std::map<std::string,std::string> VECTOR_TYPE_MAPPING {
    {"float", "double"},
    {"char", "string"},
};
开发者ID:super-ast,项目名称:cpptranslate,代码行数:30,代码来源:SuperastCPP.cpp


示例17: Create

该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ rapidjson::GenericValue类代码示例发布时间:2022-05-31
下一篇:
C++ rangelikelihood::Ptr类代码示例发布时间:2022-05-31
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap