Esempio n. 1
0
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);
}
Esempio n. 2
0
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);
	}
}
Esempio n. 3
0
  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!");
    }
  }
Esempio n. 4
0
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);
            }
            else if (key1.compare("conditions") == 0)
            {
                rapidjson::Value condsItem(rapidjson::kArrayType);
                
                length = pTriggerArray[i1].GetChildNum();
                stExpCocoNode *pConditionsArray = pTriggerArray[i1].GetChildArray(pCocoLoader);
                for (int i6 = 0; i6 < length; ++i6)
                {
                    rapidjson::Value cond(rapidjson::kObjectType);
                    
                    num = pConditionsArray[i6].GetChildNum();
                    stExpCocoNode *pConditionArray = pConditionsArray[i6].GetChildArray(pCocoLoader);
                    for (int i7 = 0; i7 < num; ++i7)
                    {
                        std::string key4 = pConditionArray[i7].GetName(pCocoLoader);
                        const char *str4 = pConditionArray[i7].GetValue(pCocoLoader);
                        if (key4.compare("classname") == 0)
                        {
                            if (str4 != nullptr)
                            {
                                cond.AddMember("classname", rapidjson::Value(str4,allocator), allocator);
                            }
                        }
                        else if (key4.compare("dataitems") == 0)
                        {
                            rapidjson::Value dataitems(rapidjson::kArrayType);
                            size = pConditionArray[i7].GetChildNum();
                            stExpCocoNode *pDataItemsArray = pConditionArray[i7].GetChildArray(pCocoLoader);
                            for (int i8 = 0; i8 < size; ++i8)
                            {
                                rapidjson::Value dataitem(rapidjson::kObjectType);
                                extent = pDataItemsArray[i8].GetChildNum();
                                stExpCocoNode *pDataItemArray = pDataItemsArray[i8].GetChildArray(pCocoLoader);
                                for (int i9 = 0; i9 < extent; ++i9)
                                {
                                    std::string key5 = pDataItemArray[i9].GetName(pCocoLoader);
                                    const char *str5 = pDataItemArray[i9].GetValue(pCocoLoader);
                                    if (key5.compare("key") == 0)
                                    {
                                        if (str5 != nullptr)
                                        {
                                            dataitem.AddMember("key", rapidjson::Value(str5,allocator), allocator);
                                        }
                                    }
                                    else
                                    {
                                        rapidjson::Type type = pDataItemArray[i9].GetType(pCocoLoader);
                                        if (type == rapidjson::kStringType)
                                        {
                                            dataitem.AddMember("value", rapidjson::Value(str5,allocator), allocator);
                                        }
                                        else
                                        {
                                            int nV = atoi(str5);
                                            float fV = utils::atof(str5);
                                            if (fabs(nV - fV) < 0.0000001)
                                            {
                                                dataitem.AddMember("value", nV, allocator);
                                            }
                                            else
                                            {
                                                dataitem.AddMember("value", fV, allocator);
                                            }
                                        }
                                    }
                                }
                                dataitems.PushBack(dataitem, allocator);
                            }
                            cond.AddMember("dataitems", dataitems, allocator);
                        }
                    }
                    condsItem.PushBack(cond, allocator);
                }
                
                vElemItem.AddMember("conditions", condsItem, allocator);
            }
            else if (key1.compare("events") == 0)
            {
                rapidjson::Value eventsItem(rapidjson::kArrayType);
                
                length = pTriggerArray[i1].GetChildNum();
                stExpCocoNode *pEventsArray = pTriggerArray[i1].GetChildArray(pCocoLoader);
                for (int i10 = 0; i10 < length; ++i10)
                {
                    rapidjson::Value event(rapidjson::kObjectType);
                    stExpCocoNode *pEventArray = pEventsArray->GetChildArray(pCocoLoader);
                    std::string key6 = pEventArray[0].GetName(pCocoLoader);
                    const char *str6 = pEventArray[0].GetValue(pCocoLoader);
                    if (key6.compare("id") == 0 && str6 != nullptr)
                    {
                        event.AddMember("id", atoi(str6), allocator);
                        eventsItem.PushBack(event, allocator);
                    }
                }
                vElemItem.AddMember("events", eventsItem, allocator);
            }
            else if (key1.compare("id") == 0)
            {
                if (str1 != nullptr)
                {
                    vElemItem.AddMember("id", atoi(str1), allocator);
                }
            }
        }
        document.PushBack(vElemItem, allocator);
    }
}
Esempio n. 5
0
 void _Parse(const std::string& json) {
     document_.Parse(json.c_str());
     _CheckError();
 }
Esempio n. 6
0
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;
}
Esempio n. 7
0
// -----------------------------------------------------------------------------
// 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();
}
Esempio n. 8
0
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;
}
Esempio n. 9
0
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;;
	}
}
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)
{
  if (_shaderCache.HasMember(p_GpuProgramName))
  {
    _shaderCache[p_GpuProgramName].SetUint(p_ShaderHash);
  }
  else
  {
    rapidjson::Value fileName =
        rapidjson::Value(p_GpuProgramName, _shaderCache.GetAllocator());
    _shaderCache.AddMember(fileName, p_ShaderHash, _shaderCache.GetAllocator());
  }

  _INTR_STRING cacheFileName = _shaderCachePath + p_GpuProgramName + ".cached";
  _INTR_OFSTREAM of(cacheFileName.c_str(), std::ofstream::binary);
  of.write((const char*)p_SpirvBuffer.data(),
           p_SpirvBuffer.size() * sizeof(uint32_t));
  of.close();

  saveShaderCache();
}

void loadShaderFromCache(const char* p_GpuProgranName,
                         SpirvBuffer& p_SpirvBuffer)
{
  _INTR_STRING cacheFileName = _shaderCachePath + p_GpuProgranName + ".cached";
  _INTR_IFSTREAM ifs(cacheFileName.c_str(), std::ifstream::binary);

  ifs.seekg(0, ifs.end);
  std::streamoff size = ifs.tellg();
  ifs.seekg(0);

  if (size != -1)
  {
    p_SpirvBuffer.resize((size_t)size / sizeof(uint32_t));
    ifs.read((char*)p_SpirvBuffer.data(), size);
  }
  else
  {
    _INTR_LOG_WARNING("Shader cache file '%s' not found!",
                      cacheFileName.c_str());
  }

  ifs.close();
}

void GpuProgramManager::init()
{
  _INTR_LOG_INFO("Inititializing GPU Program Manager...");

  Dod::Resources::ResourceManagerBase<
      GpuProgramData, _INTR_MAX_GPU_PROGRAM_COUNT>::_initResourceManager();

  {
    Dod::Resources::ResourceManagerEntry managerEntry;
    managerEntry.createFunction =
        Resources::GpuProgramManager::createGpuProgram;
    managerEntry.destroyFunction =
        Resources::GpuProgramManager::destroyGpuProgram;
    managerEntry.createResourcesFunction =
        Resources::GpuProgramManager::createResources;
    managerEntry.destroyResourcesFunction =
        Resources::GpuProgramManager::destroyResources;
    managerEntry.getActiveResourceAtIndexFunction =
        Resources::GpuProgramManager::getActiveResourceAtIndex;
    managerEntry.getActiveResourceCountFunction =
        Resources::GpuProgramManager::getActiveResourceCount;
    managerEntry.loadFromMultipleFilesFunction =
        Resources::GpuProgramManager::loadFromMultipleFiles;
    managerEntry.saveToMultipleFilesFunction =
        Resources::GpuProgramManager::saveToMultipleFiles;
    managerEntry.getResourceFlagsFunction = GpuProgramManager::_resourceFlags;
    Application::_resourceManagerMapping[_N(GpuProgram)] = managerEntry;
  }

  {
    Dod::PropertyCompilerEntry compilerEntry;
    compilerEntry.compileFunction =
        Resources::GpuProgramManager::compileDescriptor;
    compilerEntry.initFunction =
        Resources::GpuProgramManager::initFromDescriptor;
    compilerEntry.ref = Dod::Ref();
    Application::_resourcePropertyCompilerMapping[_N(GpuProgram)] =
        compilerEntry;
  }

  glslang::InitializeProcess();
  Helper::initResource(_defaultResource);
  loadShaderCache();
}

void GpuProgramManager::reflectPipelineLayout(
    uint32_t p_PoolCount, const Dod::RefArray& p_GpuPrograms,
    Dod::Ref p_PipelineLayoutToInit)
{

  _INTR_ARRAY(BindingDescription) bindingDecs;

  for (uint32_t i = 0u; i < p_GpuPrograms.size(); ++i)
  {
    GpuProgramRef gpuProgramRef = p_GpuPrograms[i];

    spirv_cross::CompilerGLSL glsl(
        GpuProgramManager::_spirvBuffer(gpuProgramRef));
    spirv_cross::ShaderResources resources = glsl.get_shader_resources();

    // Uniform buffers
    for (uint32_t i = 0u; i < resources.uniform_buffers.size(); ++i)
    {
      spirv_cross::Resource& res = resources.uniform_buffers[i];

      if (glsl.get_decoration(res.id, spv::DecorationDescriptorSet) != 0u)
        continue;

      const bool isDynamic = res.name == "PerInstance" ||
                             res.name == "PerMaterial" ||
                             res.name == "PerFrame";

      BindingDescription bd;
      {
        bd.name = res.name.c_str();
        bd.bindingType = isDynamic ? BindingType::kUniformBufferDynamic
                                   : BindingType::kUniformBuffer;
        bd.binding = glsl.get_decoration(res.id, spv::DecorationBinding);
        bd.poolCount = p_PoolCount;
        bd.shaderStage = GpuProgramManager::_descGpuProgramType(gpuProgramRef);
      }

      bindingDecs.push_back(bd);
    }

    // Images
    for (uint32_t i = 0u; i < resources.sampled_images.size(); ++i)
    {
      spirv_cross::Resource& res = resources.sampled_images[i];

      if (glsl.get_decoration(res.id, spv::DecorationDescriptorSet) != 0u)
        continue;

      BindingDescription bd;
      {
        bd.name = res.name.c_str();
        bd.bindingType = BindingType::kImageAndSamplerCombined;
        bd.binding = glsl.get_decoration(res.id, spv::DecorationBinding);
        bd.poolCount = p_PoolCount;
        bd.shaderStage = GpuProgramManager::_descGpuProgramType(gpuProgramRef);
      }

      bindingDecs.push_back(bd);
    }

    // Storage Images
    for (uint32_t i = 0u; i < resources.storage_images.size(); ++i)
    {
      spirv_cross::Resource& res = resources.storage_images[i];

      if (glsl.get_decoration(res.id, spv::DecorationDescriptorSet) != 0u)
        continue;

      BindingDescription bd;
      {
        bd.name = res.name.c_str();
        bd.bindingType = BindingType::kStorageImage;
        bd.binding = glsl.get_decoration(res.id, spv::DecorationBinding);
        bd.poolCount = p_PoolCount;
        bd.shaderStage = GpuProgramManager::_descGpuProgramType(gpuProgramRef);
      }

      bindingDecs.push_back(bd);
    }

    // Storage Buffers
    for (uint32_t i = 0u; i < resources.storage_buffers.size(); ++i)
    {
      spirv_cross::Resource& res = resources.storage_buffers[i];

      if (glsl.get_decoration(res.id, spv::DecorationDescriptorSet) != 0u)
        continue;

      BindingDescription bd;
      {
        bd.name = res.name.c_str();
        bd.bindingType = BindingType::kStorageBuffer;
        bd.binding = glsl.get_decoration(res.id, spv::DecorationBinding);
        bd.poolCount = p_PoolCount;
        bd.shaderStage = GpuProgramManager::_descGpuProgramType(gpuProgramRef);
      }

      bindingDecs.push_back(bd);
    }
  }

  std::sort(bindingDecs.begin(), bindingDecs.end(),
            [](const BindingDescription& p_Left,
               const BindingDescription& p_Right) -> bool {
              return p_Left.binding < p_Right.binding;
            });

  PipelineLayoutManager::_descBindingDescs(p_PipelineLayoutToInit) =
      std::move(bindingDecs);
}

void GpuProgramManager::compileShaders(GpuProgramRefArray p_Refs,
                                       bool p_ForceRecompile,
                                       bool p_UpdateResources)
{
  _INTR_LOG_INFO("Loading/Compiling GPU Programs...");

  GpuProgramRefArray changedGpuPrograms;

  for (uint32_t gpIdx = 0u; gpIdx < p_Refs.size(); ++gpIdx)
  {
    GpuProgramRef ref = p_Refs[gpIdx];
    const _INTR_STRING gpuProgramName =
        "gpu_program_" + StringUtil::toString(_name(ref)._hash);

    SpirvBuffer& spirvBuffer = _spirvBuffer(ref);
    spirvBuffer.clear();

    EShLanguage stage = Helper::mapGpuProgramTypeToEshLang(
        (GpuProgramType::Enum)_descGpuProgramType(ref));
    glslang::TShader shader(stage);
    glslang::TProgram program;

    const EShMessages messages =
        (EShMessages)(EShMsgSpvRules | EShMsgVulkanRules);

    const _INTR_STRING& fileName = _descGpuProgramName(ref);
    _INTR_STRING filePath = _shaderPath + fileName;

    _INTR_FSTREAM inFileStream =
        _INTR_FSTREAM(filePath.c_str(), std::ios::in | std::ios::binary);
    _INTR_STRING glslString;
    uint32_t shaderHash = 0u;

    if (inFileStream)
    {
      _INTR_OSTRINGSTREAM contents;
      contents << inFileStream.rdbuf();
      inFileStream.close();
      glslString = contents.str();

      // Add pre processor defines
      {
        _INTR_ARRAY(_INTR_STRING) preProcessorDefines;
        StringUtil::split(_descPreprocessorDefines(ref), ";",
                          preProcessorDefines);

        _INTR_STRING defineStr;
        for (uint32_t i = 0u; i < preProcessorDefines.size(); ++i)
        {
          _INTR_LOG_INFO("Adding preprocessor #define '%s'...",
                         preProcessorDefines[i].c_str());
          defineStr += preProcessorDefines[i] + "\n";
        }

        StringUtil::replace(glslString, "/* __PREPROCESSOR DEFINES__ */",
                            defineStr);
      }

      shaderHash =
          Math::hash(glslString.c_str(), sizeof(char) * glslString.length());

      if (!p_ForceRecompile)
      {
        if (isShaderUpToDate(shaderHash, gpuProgramName.c_str()))
        {
          loadShaderFromCache(gpuProgramName.c_str(), spirvBuffer);
          continue;
        }
      }
    }
    else
    {
      _INTR_LOG_WARNING(
          "Shader for GPU program '%s' not found, trying to load from cache...",
          _descGpuProgramName(ref).c_str());
      loadShaderFromCache(gpuProgramName.c_str(), spirvBuffer);
      continue;
    }

    _INTR_LOG_INFO("Compiling GPU program '%s'...",
                   _descGpuProgramName(ref).c_str());

    const char* glslStringChar = glslString.c_str();
    shader.setStrings(&glslStringChar, 1);

    if (!shader.parse(&_defaultResource, 100, ECoreProfile, false, false,
                      messages, _includer))
    {
      _INTR_LOG_WARNING("Parsing of GPU program failed...");
      _INTR_LOG_WARNING(shader.getInfoLog());
      _INTR_LOG_WARNING(shader.getInfoDebugLog());

      // Try to load the previous shader from the cache
      loadShaderFromCache(gpuProgramName.c_str(), spirvBuffer);
      continue;
    }

    program.addShader(&shader);

    if (!program.link(messages))
    {
      _INTR_LOG_WARNING("Linking of GPU program failed...");
      _INTR_LOG_WARNING(shader.getInfoLog());
      _INTR_LOG_WARNING(shader.getInfoDebugLog());

      // Try to load the previous shader from the cache
      loadShaderFromCache(gpuProgramName.c_str(), spirvBuffer);
      continue;
    }

    _INTR_LOG_WARNING(shader.getInfoLog());
    _INTR_LOG_WARNING(shader.getInfoDebugLog());

    glslang::GlslangToSpv(*program.getIntermediate(stage), spirvBuffer);
    addShaderToCache(shaderHash, gpuProgramName.c_str(), spirvBuffer);

    changedGpuPrograms.push_back(ref);
  }

  // Update all pipelines which reference this GPU program
  PipelineRefArray changedPipelines;
  for (uint32_t gpIdx = 0u; gpIdx < changedGpuPrograms.size(); ++gpIdx)
  {
    GpuProgramRef ref = changedGpuPrograms[gpIdx];

    for (uint32_t pipIdx = 0u;
         pipIdx < Resources::PipelineManager::getActiveResourceCount();
         ++pipIdx)
    {
      Resources::PipelineRef pipelineRef =
          Resources::PipelineManager::getActiveResourceAtIndex(pipIdx);

      if (Resources::PipelineManager::_descVertexProgram(pipelineRef) == ref ||
          Resources::PipelineManager::_descFragmentProgram(pipelineRef) ==
              ref ||
          Resources::PipelineManager::_descGeometryProgram(pipelineRef) ==
              ref ||
          Resources::PipelineManager::_descComputeProgram(pipelineRef) == ref)
      {
        changedPipelines.push_back(pipelineRef);
      }
    }
  }

  if (p_UpdateResources)
  {
    PipelineManager::destroyResources(changedPipelines);
    GpuProgramManager::destroyResources(changedGpuPrograms);

    GpuProgramManager::createResources(changedGpuPrograms);
    PipelineManager::createResources(changedPipelines);
  }
}

void GpuProgramManager::compileShader(GpuProgramRef p_Ref,
                                      bool p_ForceRecompile,
                                      bool p_UpdateResources)
{
  GpuProgramRefArray refs = {p_Ref};
  compileShaders(refs, p_ForceRecompile, p_UpdateResources);
}

void GpuProgramManager::compileAllShaders(bool p_ForceRecompile,
                                          bool p_UpdateResources)
{
  compileShaders(_activeRefs, p_ForceRecompile, p_UpdateResources);
}

// <-

void GpuProgramManager::createResources(const GpuProgramRefArray& p_Refs)
{
  for (uint32_t i = 0u; i < p_Refs.size(); ++i)
  {
    GpuProgramRef ref = p_Refs[i];
    const SpirvBuffer& spirvBuffer = _spirvBuffer(ref);

    // No spirv buffer? Retrieve it from the cache or compile the shader
    if (spirvBuffer.empty())
    {
      compileShader(ref, false, false);
      if (spirvBuffer.empty())
      {
        continue;
      }
    }

    VkShaderModule& module = _vkShaderModule(ref);

    // Shader module
    {
      VkShaderModuleCreateInfo creationInfo;
      creationInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
      creationInfo.pNext = nullptr;
      creationInfo.flags = 0;
      creationInfo.codeSize = spirvBuffer.size() * sizeof(uint32_t);
      creationInfo.pCode = spirvBuffer.data();

      _INTR_ASSERT(module == VK_NULL_HANDLE);
      VkResult result = vkCreateShaderModule(RenderSystem::_vkDevice,
                                             &creationInfo, nullptr, &module);
      _INTR_VK_CHECK_RESULT(result);
    }

    // Pipeline state
    {
      VkPipelineShaderStageCreateInfo& pipelineCreateInfo =
          _vkPipelineShaderStageCreateInfo(ref);
      pipelineCreateInfo.sType =
          VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
      pipelineCreateInfo.pNext = nullptr;
      pipelineCreateInfo.pSpecializationInfo = nullptr;
      pipelineCreateInfo.flags = 0u;
      pipelineCreateInfo.stage = Helper::mapGpuProgramTypeToVkShaderStage(
          (GpuProgramType::Enum)_descGpuProgramType(ref));
      pipelineCreateInfo.pName = _descEntryPoint(ref).c_str();
      pipelineCreateInfo.module = module;
    }
  }
}

// <-
}
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;
}
	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());
	}
	void save(const std::string &value, rapidjson::Value &json, rapidjson::Document &document)
	{
		rapidjson::Value v(rapidjson::kArrayType);
		json.AddMember("string", value.c_str(), document.GetAllocator());
	}
	void save(const glm::uvec2 &value, rapidjson::Value &json, rapidjson::Document &document)
	{
		rapidjson::Value v(rapidjson::kArrayType);
		v.PushBack(value.x, document.GetAllocator()).PushBack(value.y, document.GetAllocator());
		json.AddMember("uvec2", v, document.GetAllocator());
	}
Esempio n. 15
0
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());
}
Esempio n. 16
0
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
    }
}
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;
}
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;
}
Esempio n. 19
0
#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"},
};
// -----------------------------------------------------------------------------
// Worker function for creating a DoubleWishboneReduced suspension using data in
// the specified RapidJSON document.
// -----------------------------------------------------------------------------
void DoubleWishboneReduced::Create(const rapidjson::Document& d) {
    // Read top-level data
    assert(d.HasMember("Type"));
    assert(d.HasMember("Template"));
    assert(d.HasMember("Name"));

    SetName(d["Name"].GetString());

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

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

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

    m_uprightMass = d["Upright"]["Mass"].GetDouble();
    m_points[UPRIGHT] = loadVector(d["Upright"]["COM"]);
    m_uprightInertia = loadVector(d["Upright"]["Inertia"]);
    m_uprightRadius = d["Upright"]["Radius"].GetDouble();

    // Read UCA data
    assert(d.HasMember("Upper Control Arm"));
    assert(d["Upper Control Arm"].IsObject());

    m_points[UCA_F] = loadVector(d["Upper Control Arm"]["Location Chassis Front"]);
    m_points[UCA_B] = loadVector(d["Upper Control Arm"]["Location Chassis Back"]);
    m_points[UCA_U] = loadVector(d["Upper Control Arm"]["Location Upright"]);

    // Read LCA data
    assert(d.HasMember("Lower Control Arm"));
    assert(d["Lower Control Arm"].IsObject());

    m_points[LCA_F] = loadVector(d["Lower Control Arm"]["Location Chassis Front"]);
    m_points[LCA_B] = loadVector(d["Lower Control Arm"]["Location Chassis Back"]);
    m_points[LCA_U] = loadVector(d["Lower Control Arm"]["Location Upright"]);

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

    m_points[TIEROD_C] = loadVector(d["Tierod"]["Location Chassis"]);
    m_points[TIEROD_U] = loadVector(d["Tierod"]["Location Upright"]);

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

    m_points[SHOCK_C] = loadVector(d["Shock"]["Location Chassis"]);
    m_points[SHOCK_U] = loadVector(d["Shock"]["Location Upright"]);
    m_springRestLength = d["Shock"]["Free Length"].GetDouble();
    m_shockForceCB = new LinearSpringDamperForce(d["Shock"]["Spring Coefficient"].GetDouble(),
                                                 d["Shock"]["Damping Coefficient"].GetDouble());

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

    m_axleInertia = d["Axle"]["Inertia"].GetDouble();
}
Esempio n. 21
0
void MapInfo::load(const std::string& json_file)
{
  std::ifstream file(json_file);
  if (!file) {
    logger << Log::WARN << "Did not find minimap: " << json_file << Log::ENDL;
    map_json.Parse("{}");
    // disable map entirely
    this->tex = nullptr;
    this->current_map = "";
    return;
  }

  const std::string str((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
  const auto& res = map_json.Parse(str.c_str());
  DM_ASSERT(map_json.IsObject(), "Could not parse map JSON file properly!");
  if (res.HasParseError()) {
    DM_ASSERT(false, "Could not parse map JSON file properly!");
  }

  if (map_json.HasMember("filename")) {
    this->set_map(map_json["filename"].GetString());
  }

  this->mask.enabled = map_json.HasMember("mask");
  if (this->mask.enabled)
  {
    auto mask_json = map_json["mask"].GetObject();
    if (mask_json.HasMember("active")) {
      this->mask.enabled = mask_json["active"].GetBool();
    }
    if (this->mask.enabled)
    {
      this->mask.radius = mask_json["radius"].GetInt();
      this->mask.border = mask_json["border"].GetInt();
      if (this->map_changed) {
        // create new mask
        this->mask.reset(tex->getWidth(), tex->getHeight());
      }
    }
  }

  // play area is used to restrict the player icon
  // the player location is transformed from the world into this area
  if (map_json.HasMember("play_area"))
  {
    auto area = map_json["play_area"].GetArray();
    this->play_area = glm::ivec4(area[0].GetInt(), area[1].GetInt(),
                                 area[2].GetInt(), area[3].GetInt());
  }
  else {
    // use whole image if play area is not specified
    this->play_area = glm::ivec4(0, 0, tex->getWidth(), tex->getHeight());
  }

  this->gridmode = map_json.HasMember("grid");
  if (this->gridmode)
  {
    auto& grid = map_json["grid"];
    this->grid_base_coord = glm::ivec2(grid["base_x"].GetInt(),
                                       grid["base_y"].GetInt());
    this->grid_dimensions = glm::ivec2(grid["size_x"].GetInt(),
                                       grid["size_y"].GetInt());
    // grid to pixel multiplier
    const int w = this->grid_pixel_multiplier().x;
    const int h = this->grid_pixel_multiplier().y;
    logger << Log::INFO << "Map screen is a grid of " << w << "x" << h << " pixels" << Log::ENDL;
  }
  else
  {
    const int w = this->tex->getWidth();
    const int h = this->tex->getHeight();
    // not a grid
    logger << Log::INFO << "Map screen is a bitmap of size " << w << "x" << h << " pixels" << Log::ENDL;
  }
  
  this->icons.clear();
  if (map_json.HasMember("icons") == false) return;
  auto& icon_json = map_json["icons"];
  const std::string icon_file = icon_json["filename"].GetString();
  this->sprite_texid = textures.add(icon_file);
  
  for (auto& m : icon_json.GetObject())
  {
    if (std::string("icon") == m.name.GetString())
    {
      const auto icon = m.value.GetObject();
      int px = icon["x"].GetInt();
      int py = icon["y"].GetInt();
      assert(icon.HasMember("sprite") && "Icons must have a sprite object");
      const auto sprite = icon["sprite"].GetObject();
      short x = sprite["x"].GetInt();
      short y = sprite["y"].GetInt();
      short w = sprite["w"].GetInt();
      short h = sprite["h"].GetInt();
      
      const Sprite spr {x, y, w, h, sprite_texid};
      this->icons.push_back(Icon{spr, glm::ivec2(px, py)});
    }
  }
  
  /// border clouds & shadows ///
  this->border.clear();
  if (map_json.HasMember("clouds"))
  {
    assert(map_json.HasMember("shadows") && "Clouds must have a shadow array");
    auto clouds = map_json["clouds"].GetArray();
    auto shadows = map_json["shadows"].GetArray();
    
    const size_t count = std::max(clouds.Size(), shadows.Size());
    for (size_t i = 0; i < count; i++)
    {
      // load clouds & shadows separately
      std::unique_ptr<Texture> cldtex = nullptr;
      if (clouds.Size() > i) {
        cldtex = load_texture(clouds[i].GetString());
        if (cldtex == nullptr) {
          logger << Log::WARN << "Missing cloud layer: " << clouds[i].GetString() << Log::ENDL;
        }
      }
      std::unique_ptr<Texture> shdtex = nullptr;
      if (shadows.Size() > i) {
        shdtex = load_texture(shadows[i].GetString());
        if (shdtex == nullptr) {
          logger << Log::WARN << "Missing shadow layer: " << shadows[i].GetString() << Log::ENDL;
        }
      }
      border.push_back(BorderLayer{
            std::move(cldtex), std::move(shdtex), glm::mat4{}
        });
    }
    logger << Log::INFO << "Found " << count << " cloud & shadow layers" << Log::ENDL;
  }
}
Esempio n. 22
0
rapidjson::Value xmrig::String::toJSON(rapidjson::Document &doc) const
{
    using namespace rapidjson;

    return isNull() ? Value(kNullType) : Value(m_data, doc.GetAllocator());
}