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

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

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

		}

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

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

		scenes[sceneName] = sceneData;
	}

	settings = root["startscene"];
	startScene = scenes[settings.asCString()];
}
Example #2
0
void GetVal(Json::Value &config, char** setting)
{
	if (config.isNull())
		return;

	*setting = strdup(config.asCString());
}
Example #3
0
//////////////////////////////////////////////////////////////////////////
// addAllPackageCrossRefs
void CsPackageImporter::addAllPackageCrossRefs( Json::Value& Root )
{
	std::lock_guard< std::recursive_mutex > Lock( BuildingLock_ );
	BcAssert( BuildingBeginCount_ > 0 );

	// If it's a string value, attempt to match it.
	if( Root.type() == Json::stringValue )
	{
		std::cmatch Match;
		std::regex_match( Root.asCString(), Match, GRegex_ResourceReference );
		
		// Try the weak match.
		// TODO: Merge into  regex.
		if( Match.size() == 0 )
		{
			std::regex_match( Root.asCString(), Match, GRegex_WeakResourceReference );
		}

		if( Match.size() == 4 )
		{
			BcU32 RefIndex = addPackageCrossRef( Root.asCString() );

			// If we find it, replace string reference with a cross ref index.
			if( RefIndex != BcErrorCode )
			{
				PSY_LOG("Adding crossref %u: %s\n", RefIndex, Root.asCString() );
				Root = Json::Value( RefIndex );
			}
		}
	}
	else if( Root.type() == Json::arrayValue )
	{
		for( BcU32 Idx = 0; Idx < Root.size(); ++Idx )
		{
			addAllPackageCrossRefs( Root[ Idx ] );
		}
	}
	else if( Root.type() == Json::objectValue )
	{
		Json::Value::Members MemberValues = Root.getMemberNames();

		for( BcU32 Idx = 0; Idx < MemberValues.size(); ++Idx )
		{
			addAllPackageCrossRefs( Root[ MemberValues[ Idx ] ] );
		}
	}
}
/// 从 Json 解析数据到 dictNode 中
static void parseFromJsonToDictionary(const Json::Value & jsonNode, CCDictionary * dictNode)
{
	Json::Value::Members members = jsonNode.getMemberNames();
	for (Json::Value::Members::iterator beg = members.begin(); beg != members.end(); ++beg)
	{
        std::string name = *beg;
		Json::Value child = jsonNode[name];
		
		if (child.isArray())
		{
			CCArray * arr = CCArray::create();
			parseFromJsonToArray(child, arr);
			dictNode->setObject(arr, name);
		}
		else if (child.isObject())
		{
			CCDictionary * dict = CCDictionary::create();
			parseFromJsonToDictionary(child, dict);
			dictNode->setObject(dict, name);
		}
		else if (child.isString())
		{
			CCString * str = CCString::createWithFormat("%s", child.asCString());
			dictNode->setObject(str, name);
		}
		else if (child.isInt())
		{
			CCString * str = CCString::createWithFormat("%d", child.asInt());
			dictNode->setObject(str, name);
		}
		else if (child.isUInt())
		{
			CCString * str = CCString::createWithFormat("%u", child.asUInt());
			dictNode->setObject(str, name);
		}
		else if (child.isInt64())
		{
			CCString * str = CCString::createWithFormat("%lld", child.asInt64());
			dictNode->setObject(str, name);
			
		}
		else if (child.isUInt64())
		{
			CCString * str = CCString::createWithFormat("%llu", child.asUInt64());
			dictNode->setObject(str, name);
		}
		else if (child.isDouble())
		{
			CCString * str = CCString::createWithFormat("%f", child.asDouble());
			dictNode->setObject(str, name);
		}
		else if (child.isBool())
		{
			CCString * str = CCString::createWithFormat("%d", child.asInt());
			dictNode->setObject(str, name);
		}
	}
}
Example #5
0
// Constructor
DrvSDL::DrvSDL(std::string name, LCDControl *v,
    Json::Value *config, int layers) :
    LCDCore(v, name, config, LCD_GRAPHIC, (LCDGraphic *)this),
    LCDGraphic((LCDCore *)this), drvFB(0) {

    GraphicRealBlit = DrvSDLBlit;

    Json::Value *val = CFG_Fetch(config, name + ".cols", new Json::Value(SCREEN_W));
    cols_ = val->asInt();
    delete val;

    val = CFG_Fetch(config, name + ".rows", new Json::Value(SCREEN_H));
    rows_ = val->asInt();
    delete val;

    val = CFG_Fetch(config, name + ".update", new Json::Value(150));
    update_ = val->asInt();
    delete val;

    val = CFG_Fetch(config, name + ".fill", new Json::Value(0));
    fill_ = val->asInt();
    delete val;

    val = CFG_Fetch_Raw(config, name + ".pixels", new Json::Value("1x1"));
    sscanf(val->asCString(), "%dx%d", &pixels.x, &pixels.y);
    delete val;

    GraphicInit(rows_, cols_, 8, 7, layers);

    if(!(drvFB = (RGBA *)malloc(rows_ * pixels.y * cols_ * pixels.x * sizeof(RGBA))))
	LCDError("Could not allocate frame buffer for DrvSDL");

    wrapper_ = new SDLWrapper((SDLInterface *)this);

    update_thread_ = new SDLUpdateThread(this);

    //gif_thread_ = new SDLGifThread(this);

    if(SDL_Init(SDL_INIT_VIDEO) != 0) {
        LCDError("DrvSDL: Unable to init SDL: %s", SDL_GetError());
    }

    surface_ = SDL_SetVideoMode(cols_ * pixels.x, rows_ * pixels.y, 32, 
        SDL_RESIZABLE);

    SDL_WM_SetCaption("LCDControl", "LCDControl");

    if( surface_ == NULL) {
        LCDError("DrvSDL: Unable to set %dx%d video: %s", cols_, rows_, SDL_GetError());
    }

/*
    sdl_timer_.setInterval(update_);
    QObject::connect(&sdl_timer_, SIGNAL(timeout()),
        wrapper_, SLOT(DrvUpdateSDL()));
*/
}
Example #6
0
	void Deserialize_Enum(
		const Json::Value& srcValue,
		const mxEnumType& enumInfo,
		void *rawMem	
		)
	{
		const UINT newValue = enumInfo.GetItemIndexByString( srcValue.asCString() );

		enumInfo.m_accessor.Set_Value( rawMem, newValue );
	}
Example #7
0
int GetJsonInt(const Json::Value& _jsValue)
{
	if ( _jsValue.type() == Json::intValue)
		return _jsValue.asInt();
	else if (_jsValue.type() == Json::stringValue)
		return atoi(_jsValue.asCString());
	else if (_jsValue.isBool())
		return (int)_jsValue.asBool();
	return 0;
}
void MusicConfigLoader::ReadTags(Json::Value& node, std::set<CString>& setTags)
{
   ATLASSERT(node.isArray());

   // enumerate array member
   for (Json::Value::UInt index = 0, max = node.size(); index < max; index++)
   {
      Json::Value valItem = node[index];
      setTags.insert(CString(valItem.asCString()));
   }
}
void EepromMapPrivateTestCase::testGetString(void)
{
  EepromMapPrivate* eepromMap = this->createEepromMap();
  Json::Value nameValues = eepromMap->getEepromMap()["eeprom_map"]["MACHINE_NAME"]["value"];
  Json::Value expectedValue = nameValues[0];
  QString expectedName = QString(expectedValue.asCString()); 
  QString path = QString("MACHINE_NAME");
  std::vector<QString> * gotValues = eepromMap->getString(path);
  QString gotName = (*gotValues)[0];
  CPPUNIT_ASSERT(expectedName == gotName);
}
bool ShopItemInfoFromServer::parseShopBuyInfoFromServer()
{
    m_mapBuyShopInfo.clear();
    const char* pMessage = m_strShopBuyList.c_str();

    CCLOG("download step m_strShopBuyList %s",pMessage);
    if (pMessage == NULL || pMessage == "" || pMessage == "error")
    {
        return false;
    }

    Json::Value jsonValue;
    if (!parseJsonStr(pMessage, jsonValue)) 
    {
        CCLOGERROR("UpdateInfoFromServer Error: %s",pMessage);
        return false;
    }

    bool isArray = jsonValue.isArray();
    if (isArray)
    {
        unsigned int arraySize = jsonValue.size();
        for (int i = 0; i < arraySize; i++)
        {
            const Json::Value jProduct_id = jsonValue[i]["id"];
            const Json::Value jAmount = jsonValue[i]["count"];

            if (false == jProduct_id.isNull() &&
                false == jAmount.isNull())
            {
                int id = atoi(jProduct_id.asCString());
                int amount = atoi(jAmount.asCString());

                m_mapBuyShopInfo.insert(std::make_pair(id, amount));
            }
        }
    }

    return true;
}
Example #11
0
// Recursive function to convert JSON --> Lua table
static bool push_json_value_helper(lua_State *L, const Json::Value &value,
		int nullindex)
{
	switch(value.type()) {
		case Json::nullValue:
		default:
			lua_pushvalue(L, nullindex);
			break;
		case Json::intValue:
			lua_pushinteger(L, value.asInt());
			break;
		case Json::uintValue:
			lua_pushinteger(L, value.asUInt());
			break;
		case Json::realValue:
			lua_pushnumber(L, value.asDouble());
			break;
		case Json::stringValue:
			{
				const char *str = value.asCString();
				lua_pushstring(L, str ? str : "");
			}
			break;
		case Json::booleanValue:
			lua_pushboolean(L, value.asInt());
			break;
		case Json::arrayValue:
			lua_newtable(L);
			for (Json::Value::const_iterator it = value.begin();
					it != value.end(); ++it) {
				push_json_value_helper(L, *it, nullindex);
				lua_rawseti(L, -2, it.index() + 1);
			}
			break;
		case Json::objectValue:
			lua_newtable(L);
			for (Json::Value::const_iterator it = value.begin();
					it != value.end(); ++it) {
#ifndef JSONCPP_STRING
				const char *str = it.memberName();
				lua_pushstring(L, str ? str : "");
#else
				std::string str = it.name();
				lua_pushstring(L, str.c_str());
#endif
				push_json_value_helper(L, *it, nullindex);
				lua_rawset(L, -3);
			}
			break;
	}
	return true;
}
Example #12
0
// helpers
CString UnpackValue(Json::Value& v)
{
	// we expect we are in UNICODE mode
	const char* c = v.asCString();
	if (!c) return CString();
	int s = strlen(c);
	int l = MultiByteToWideChar(CP_UTF8, 0, c, s, 0, 0);
	wchar_t* buf = new wchar_t[l+1];
	CAPtrGuard guard(buf);
	MultiByteToWideChar(CP_UTF8, 0, c, s, buf, l);
	buf[l] = 0;
	return CString(buf);
}
Example #13
0
/***************以下函数用于读取json静态数据***************/
unsigned int to_uint(const Json::Value& val)
{
    if ( val.isIntegral() )
        return val.asUInt();

    if ( val.isDouble() )
        return (unsigned int)val.asDouble();

    if ( val.isString() )
        return strtoul(val.asCString(), NULL, 0 );

    return 0;
}
Example #14
0
WidgetScript::WidgetScript(LCDCore *v, std::string n, Json::Value *section) :
    Widget(v, n, section, 0, 0, 0, WIDGET_TYPE_KEYPAD) {

    Json::Value *scriptFile = v->CFG_Fetch_Raw(section, "file", NULL);
    if(scriptFile) {
        FILE *file = fopen( scriptFile->asCString(), "rb");
        if( !file ) {
            LCDError("WidgetScript: Unable to open file <%s>", scriptFile->asCString());
            return;
        }
        fseek(file, 0, SEEK_END);
        long size = ftell(file);
        fseek(file, 0, SEEK_SET);
        char *buffer = new char[size+1];
        buffer[size] = 0x0;
        if( fread( buffer, 1, size, file) != (unsigned long) size)
            return;
        std::string script = buffer;
        delete []buffer;
        fclose(file);
        v->Eval(script);
    }
}
Example #15
0
int Widget::WidgetColor(Json::Value *section, std::string key, RGBA *C) {

    C->R = 0;
    C->G = 0;
    C->B = 0;
    C->A = 0;

    Json::Value *val = NULL;
    
    val = visitor_->CFG_Fetch_Raw(section, key);

    if (val == NULL)
        return 0;

    if (color2RGBA(val->asCString(), C) < 0) {
        LCDError("widget '%s': ignoring illegal %s color '%s'", 
            name_.c_str(), key.c_str(), val->asCString());
        return 0;
    }

    delete val;
    return 1;
}
size_t ServiceSMSTwilio::curl_output(void *ptr, size_t size, size_t nmemb, void *userdata)
{
	int ret = size*nmemb;
	if (ret == 0)
		return ret;
	TwilioMessage *msg = (TwilioMessage *)userdata;
	if (!msg || !msg->service)
		return ret;

	if (!msg->service->checkSent_Task(msg)) {
		log(LOG_ERROR,"Error: ServiceSMSTwilio checkSentTask false");
		return ret;
	}

	msg->curl_response.append((char *)ptr, size*nmemb);
	Json::Reader jr;
	Json::Value root;
	if (!jr.parse(msg->curl_response, root))
		return ret;
	if (SessionManager::getOptions().paramsTwilioSMS.Log && nmemb > 0)
		log(LOG_NORMAL, "TwilioSMS parsed response: %s", (char *)ptr);

	Json::Value v = root["sid"];
	string id = v.asCString();
	v = root["status"];
	int status = StatusStrToCode(v.asCString());
	int error = 0;
	if (status == SMS_STATUS_UNDELIVERED) {
		v = root["error_code"];
		error = v.asInt();
	}

	if (User::storeSMSTwilio(msg->service->getCon(), id,  msg->phone_id, status, error, msg->type))
		return ret;
	return ret;
}
Example #17
0
inline void duk_push_json(duk_context *ctx, Json::Value val) {
	Json::ValueType type = val.type();

	int length, obj_index;

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

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

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

				duk_put_prop(ctx, obj_index);

				it ++;
			}
			break;
	}
}
Example #18
0
// Programmer must free memory
Json::Value *CFG::CFG_Fetch(Json::Value *section, std::string key, 
    Json::Value *defval) {

    Json::Value *val = CFG_Fetch_Raw(section, key, defval ? 
        new Json::Value(*defval) : defval);

    if(!val)
        return defval;

    if( val->isNumeric() ) {
        if( defval ) delete defval;
        return val;
    } else if ( val->isString() ) {
        Json::Value *val2 = new Json::Value(Eval(val->asCString()));
        return val2 ? val2 : defval;
    }
    return defval;
}
Example #19
0
State const* MessageFactory::ParseGameBoardStateMessage(Json::Value const& root) const {
    int sequence = root.get("sequence", -1).asInt();
    double timestamp = root.get("timestamp", 0.0).asDouble();
    Json::Value states = root.get("states", "not found");

    Json::Value mine = states.get(USERNAME, "not found");
    int piece = mine.get("piece_number", -1).asInt();
    Json::Value boardV = mine.get("board_state", "0");
    if (boardV.asString().size() != BOARD_DESC_SIZE) {
        return new ErrorState("Invalid board description.");
    }
    char* board = new char[BOARD_DESC_SIZE];
    memcpy((void*)board, (void*)boardV.asCString(), BOARD_DESC_SIZE);
    Json::Value clearedV = mine.get("cleared_rows", "not found");
    std::vector<int>* cleared = new std::vector<int>();
    for (unsigned i = 0; i < clearedV.size(); ++i) {
        cleared->push_back(clearedV[i].asInt());
    }

    return new GameBoardState(sequence, timestamp, board, piece, cleared);
}
void EepromMapPrivateTestCase::testSetString(void)
{
  EepromMapPrivate* eepromMap = this->createEepromMap();
  Json::Value the_map = eepromMap->getEepromMap();
  Json::Value the_value = the_map["eeprom_map"]["MACHINE_NAME"]["value"];
  Json::Value the_name = the_value[0];
  std::string currentNameInMap = the_name.asString();

  std::string currentName = "The Replicator";
  CPPUNIT_ASSERT(currentName == currentNameInMap);

  //Change the name
  QString newName = QString("the_awesomecator");
  std::vector<QString> newValues;
  newValues.push_back(newName);  
  //The Path
  QString path = QString("MACHINE_NAME");
  eepromMap->setString(path, newValues);
  Json::Value gotMap = eepromMap->getEepromMap();
  Json::Value gotValues = gotMap["eeprom_map"]["MACHINE_NAME"]["value"];
  Json::Value gotName = gotValues[0];
  QString gotString = QString(gotName.asCString());
  CPPUNIT_ASSERT(newName == gotString);
}
Example #21
0
	bool loadAnimatedTextureFromPath(const char* aPngPath, const char* aJsonPath, OpenGLAnimatedTextureInfo** aAnimatedTextureInfo)
	{
		//Success flag
		bool success = false;

		//Open the input stream
		std::ifstream inputStream;
		inputStream.open(aJsonPath, std::ifstream::in);

		//Parse the json file
		Json::Value root;
		Json::Reader reader;
		if(reader.parse(inputStream, root, false) == true)
		{
			//Get the frames data
			const Json::Value frames = root["frames"];

			//Dereference the Animated texture struct
			OpenGLAnimatedTextureInfo* animatedTextureInfo = *aAnimatedTextureInfo;
			animatedTextureInfo->frameCount = frames.size();

			//Load the full animated texture image
			OpenGLTextureLoader::loadTextureFromPath(aPngPath, &animatedTextureInfo->textureInfo);

			//Create the animated texture frames array
			animatedTextureInfo->frames = new OpenGLTexture *[animatedTextureInfo->frameCount];

			//Cycle through and setup each frame in the animation
			for(int index = 0; index < (int)(animatedTextureInfo->frameCount); index++)
			{
				//Allocate the frameInfo struct and copy the textureInfo struct
				OpenGLTextureInfo* frameInfo = new OpenGLTextureInfo(*animatedTextureInfo->textureInfo);

				//
				Json::Value atlasKey = frames[index]["filename"];

				//
				Json::Value frame = frames[index]["frame"];
				unsigned int x = frame["x"].asInt();
				unsigned int y = frame["y"].asInt();
				unsigned int width = frame["w"].asInt();
				unsigned int height = frame["h"].asInt();

				//Set the frame info's position and size
				frameInfo->sourceWidth = width;
				frameInfo->sourceHeight = height;
				frameInfo->sourceX = x;
				frameInfo->sourceY = y;

				//Set the frame's key
				frameInfo->textureFilename = std::string(atlasKey.asCString());

				//Set the frame in the animated texture info frames array
				animatedTextureInfo->frames[index] = new OpenGLTexture(frameInfo);

				//Free the frame info
				delete frameInfo;
				frameInfo = NULL;
			}

			//Set the success flag to true
			success = true;
		}

		//Close the input stream
		inputStream.close();

		//Was this operation successful
		return success;
	}
WidgetHistogram::WidgetHistogram(LCDCore *v, std::string n, Json::Value *section, 
    int row, int col, int layer) : Widget(v, n, section, row, col, layer, 
    WIDGET_TYPE_HISTOGRAM | WIDGET_TYPE_RC | WIDGET_TYPE_SPECIAL) {


    if(lcd_type_ == LCD_TEXT)
        Draw = TextHistogramDraw;
    else if(lcd_type_ == LCD_GRAPHIC)
        Draw = GraphicHistogramDraw;
    else
        Draw = NULL;

    min_ = max_ = 0;
    string_ = "";
    offset_ = 0;

    expression_ = new Property(v, section, "expression", new Json::Value("0"));
    expr_min_ = new Property(v, section, "min", NULL);
    expr_max_ = new Property(v, section, "max", NULL);

    fg_valid_ = WidgetColor(section, "foreground", &fg_color_);
    bg_valid_ = WidgetColor(section, "background", &bg_color_);

    Json::Value *val = v->CFG_Fetch(section, "width", new Json::Value(10));
    cols_ = val->asInt();
    delete val;

    val = v->CFG_Fetch(section, "height", new Json::Value(1));
    rows_ = val->asInt();
    delete val;

    LCDError("1 cols_ %d, rows_ %d", cols_, rows_);
    int diff = (col_ + cols_) - v->GetLCD()->LCOLS;
    if(diff > 0) cols_ -= diff;

    diff = (row_ + rows_) - v->GetLCD()->LROWS;
    if(diff > 0) rows_ -= diff;
    LCDError("2 cols_ %d, rows_ %d", cols_, rows_);

    val = v->CFG_Fetch(section, "gap", new Json::Value(0));
    gap_ = val->asInt();
    delete val;

    val = v->CFG_Fetch_Raw(section, "direction", new Json::Value("E"));
    if( val->asString() == "E" )
        direction_ = DIR_EAST;
    else if (val->asString() == "W" )
        direction_ = DIR_WEST;
    else {
        LCDError("Widget %s has unknown direction '%s'; Use (E)ast or (W)est. Using E.",
            name_.c_str(), val->asCString());
        direction_ = DIR_EAST;
    }
    delete val;

    val = v->CFG_Fetch(section, "update", new Json::Value(1000));
    update_ = val->asInt();
    delete val;
   
    history_.resize(cols_);

/*
    timer_ = new QTimer();
    timer_->setSingleShot(false);
    timer_->setInterval(update_);
    QObject::connect(timer_, SIGNAL(timeout()), this, SLOT(Update()));

    QObject::connect(v->GetWrapper(), SIGNAL(_ResizeLCD(int, int, int, int)),
        this, SLOT(Resize(int, int, int, int)));
*/
}
Example #23
0
bool JSONImporter::runOnScop(Scop &scop) {
  S = &scop;
  Region &R = S->getRegion();
  Dependences *D = &getAnalysis<Dependences>();

  std::string FileName = ImportDir + "/" + getFileName(S);

  std::string FunctionName = R.getEntry()->getParent()->getName();
  errs() << "Reading JScop '" << R.getNameStr() << "' in function '"
         << FunctionName << "' from '" << FileName << "'.\n";
  OwningPtr<MemoryBuffer> result;
  error_code ec = MemoryBuffer::getFile(FileName, result);

  if (ec) {
    errs() << "File could not be read: " << ec.message() << "\n";
    return false;
  }

  Json::Reader reader;
  Json::Value jscop;

  bool parsingSuccessful = reader.parse(result->getBufferStart(), jscop);

  if (!parsingSuccessful) {
    errs() << "JSCoP file could not be parsed\n";
    return false;
  }

  isl_set *OldContext = S->getContext();
  isl_set *NewContext =
      isl_set_read_from_str(S->getIslCtx(), jscop["context"].asCString());

  for (unsigned i = 0; i < isl_set_dim(OldContext, isl_dim_param); i++) {
    isl_id *id = isl_set_get_dim_id(OldContext, isl_dim_param, i);
    NewContext = isl_set_set_dim_id(NewContext, isl_dim_param, i, id);
  }

  isl_set_free(OldContext);
  S->setContext(NewContext);

  StatementToIslMapTy &NewScattering = *(new StatementToIslMapTy());

  int index = 0;

  for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
    Json::Value schedule = jscop["statements"][index]["schedule"];
    isl_map *m = isl_map_read_from_str(S->getIslCtx(), schedule.asCString());
    isl_space *Space = (*SI)->getDomainSpace();

    // Copy the old tuple id. This is necessary to retain the user pointer,
    // that stores the reference to the ScopStmt this scattering belongs to.
    m = isl_map_set_tuple_id(m, isl_dim_in,
                             isl_space_get_tuple_id(Space, isl_dim_set));
    isl_space_free(Space);
    NewScattering[*SI] = m;
    index++;
  }

  if (!D->isValidScattering(&NewScattering)) {
    errs() << "JScop file contains a scattering that changes the "
           << "dependences. Use -disable-polly-legality to continue anyways\n";
    return false;
  }

  for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
    ScopStmt *Stmt = *SI;

    if (NewScattering.find(Stmt) != NewScattering.end())
      Stmt->setScattering(NewScattering[Stmt]);
  }

  int statementIdx = 0;
  for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
    ScopStmt *Stmt = *SI;

    int memoryAccessIdx = 0;
    for (ScopStmt::memacc_iterator MI = Stmt->memacc_begin(),
                                   ME = Stmt->memacc_end();
         MI != ME; ++MI) {
      Json::Value accesses = jscop["statements"][statementIdx]["accesses"][
          memoryAccessIdx]["relation"];
      isl_map *newAccessMap =
          isl_map_read_from_str(S->getIslCtx(), accesses.asCString());
      isl_map *currentAccessMap = (*MI)->getAccessRelation();

      if (isl_map_dim(newAccessMap, isl_dim_param) !=
          isl_map_dim(currentAccessMap, isl_dim_param)) {
        errs() << "JScop file changes the number of parameter dimensions\n";
        isl_map_free(currentAccessMap);
        isl_map_free(newAccessMap);
        return false;
      }

      // We need to copy the isl_ids for the parameter dimensions to the new
      // map. Without doing this the current map would have different
      // ids then the new one, even though both are named identically.
      for (unsigned i = 0; i < isl_map_dim(currentAccessMap, isl_dim_param);
           i++) {
        isl_id *id = isl_map_get_dim_id(currentAccessMap, isl_dim_param, i);
        newAccessMap = isl_map_set_dim_id(newAccessMap, isl_dim_param, i, id);
      }

      // Copy the old tuple id. This is necessary to retain the user pointer,
      // that stores the reference to the ScopStmt this access belongs to.
      isl_id *Id = isl_map_get_tuple_id(currentAccessMap, isl_dim_in);
      newAccessMap = isl_map_set_tuple_id(newAccessMap, isl_dim_in, Id);

      if (!isl_map_has_equal_space(currentAccessMap, newAccessMap)) {
        errs() << "JScop file contains access function with incompatible "
               << "dimensions\n";
        isl_map_free(currentAccessMap);
        isl_map_free(newAccessMap);
        return false;
      }
      if (isl_map_dim(newAccessMap, isl_dim_out) != 1) {
        errs() << "New access map in JScop file should be single dimensional\n";
        isl_map_free(currentAccessMap);
        isl_map_free(newAccessMap);
        return false;
      }
      if (!isl_map_is_equal(newAccessMap, currentAccessMap)) {
        // Statistics.
        ++NewAccessMapFound;
        newAccessStrings.push_back(accesses.asCString());
        (*MI)->setNewAccessRelation(newAccessMap);
      } else {
        isl_map_free(newAccessMap);
      }
      isl_map_free(currentAccessMap);
      memoryAccessIdx++;
    }
    statementIdx++;
  }

  return false;
}
Example #24
0
std::string LCDCore::AddWidget(std::string layout, int row, 
    int col, int layer, std::string object) {
    std::stringstream strm;
    std::string name;
    strm << layout << ":" << "script_widget" << 0;
    strm >> name;
    strm.clear();
    strm.str("");
    int i = 0;
    while(widgets_.find(name) != widgets_.end()) {
        strm << layout << ":" << "script_widget" << ":" << ++i;
        strm >> name;
        strm.clear();
        strm.str("");
    }

    Json::Reader reader;
    Json::Value *root = new Json::Value();;
    if(!reader.parse(object, *root)) {
        LCDError("Error parsing script: %s", reader.getFormatedErrorMessages().c_str());
        return "";
    }
    
    Json::Value *type = CFG_Fetch_Raw(root, "type");

    if(type) {
           Widget *widget = (Widget *)NULL;
           if(type->asString() == "text") {
               widget = (Widget *) new WidgetText(this, name, root,
                   row, col, layer);
           } else if (type->asString() == "bar") {
               widget = (Widget *) new WidgetBar(this, name, root,
                   row, col, layer);
           } else if (type->asString() == "icon") {
               widget = (Widget *) new WidgetIcon(this, name, root,
                   row, col, layer);
           } else if (type->asString() == "histogram") {
               widget = (Widget *) new WidgetHistogram(this, name, root,
                   row, col, layer);
           } else if (type->asString() == "bignums") {
               widget = (Widget *) new WidgetBignums(this, name, root,
                   row, col, layer);
           } else if (type->asString() == "key") {
               widget = (Widget *) new WidgetKey(this, name, root);
           } else if (type->asString() == "timer") {
               widget = (Widget *) new WidgetTimer(this, name, root);
           } else if (type->asString() == "script") {
               widget = (Widget *) new WidgetScript(this, name, root);
           } else {
               LCDError("Unknown widget type: %s", type->asCString());
           }
           if(widget) {
               widgets_[name] = widget;
               widget->Start();
           }
           delete type;
           return name;
    } else {
        LCDError("Widget has no type <%s>", object.c_str());
    }
    return "";
}
Example #25
0
void LCDCore::CFGSetup() {
    int i = 1;
    std::stringstream strm;
    std::string str;

    //app_->ProcessVariables(CFG_Get_Root(), (Evaluator *)this);

    Json::Value *section = CFG_Fetch_Raw(CFG_Get_Root(), name_);
    if(!section) {
        LCDError("Device <%s> doesn't exist.", name_.c_str());
        return;
    }

    Json::Value *val = CFG_Fetch(section, "layout-timeout", new Json::Value(0));
    layout_timeout_ = val->asInt();
    delete val;

    val = CFG_Fetch(section, "transition-speed", new Json::Value(200));
    transition_speed_ = val->asInt();
    delete val;

    val = CFG_Fetch_Raw(section, "clear_on_layout_change", new Json::Value(true));
    clear_on_layout_change_ = val->asBool();
    delete val;

    val = CFG_Fetch_Raw(section, "transitions-off", new Json::Value(false));
    transitions_off_ = val->asBool();
    delete val;

    Json::Value *layout = CFG_Fetch_Raw(section, "layout0");

    while(layout) {
        layouts_.push_back(layout->asCString());
        strm << "layout" << i;
        strm >> str;
        strm.clear();
        strm.str("");
        delete layout;
        layout = CFG_Fetch_Raw(section, str);
        i++;
    }

    if(i == 1) { delete layout; return; }

    Json::Value *widget = CFG_Fetch_Raw(section, "widget0");

    i = 1;
    while(widget && widget->isString()) {
        static_widgets_.push_back(widget->asCString());
        strm << "widget" << i;
        strm >> str;
        strm.clear();
        strm.str("");
        delete widget;
        widget = CFG_Fetch_Raw(section, str);
        i++;
    }

    if(i == 1) delete widget;

    for(unsigned int i = 0; i < layouts_.size(); i++ ) {
        layout = CFG_Fetch_Raw(CFG_Get_Root(), layouts_[i]);
        if(!layout) {
            LCDError("Missing layout <%s>", layouts_[i].c_str());
            continue;
        }
        Json::Value *val = CFG_Fetch(layout, "keyless", new Json::Value(0));
        if(val->asInt()) {
            keyless_layouts_[layouts_[i]] = true;
        }
        delete val;

        LCDError("layers: %d", lcd_->LAYERS);

        for(int layer = 0; layer < lcd_->LAYERS; layer++) {
            strm << "layer" << layer + 1;
            strm >> str;
            strm.clear();
            strm.str("");
            Json::Value *cfg_layer = CFG_Fetch_Raw(layout, str);
            if(!cfg_layer)
                continue;
            for(int row = 0; row < lcd_->LROWS; row++) {
                strm << "row" << row + 1; 
                strm >> str;
                strm.clear();
                strm.str("");
                Json::Value *cfg_row = CFG_Fetch_Raw(cfg_layer, str);
                if(!cfg_row)
                    continue;
                for(int col = 0; col < lcd_->LCOLS; col++) {
                    strm << "col" << col + 1;
                    strm >> str;
                    strm.clear();
                    strm.str("");
                    Json::Value *cfg_col = CFG_Fetch_Raw(cfg_row, str);

                    if(!cfg_col || !cfg_col->isString()) {
                        if(cfg_col) delete cfg_col;
                        continue;
                    }

                    widget_template w = widget_template();
                    w.key = cfg_col->asString();
                    w.row = row;
                    w.col = col;
                    w.layer = layer;
                    widget_templates_[layouts_[i]].push_back(w);
                    delete cfg_col;
                }
                delete cfg_row;
            }
            delete cfg_layer;
        }

        for(int row = 0; row < lcd_->LROWS; row++ ) {
            strm << "row" << row + 1;
            strm >> str;
            strm.clear();
            strm.str("");
            Json::Value *cfg_row = CFG_Fetch_Raw(layout, str);
            if(!cfg_row) 
                continue;
            for(int col = 0; col < lcd_->LCOLS; col++ ) {
                strm << "col" << col + 1;
                strm >> str;
                strm.clear();
                strm.str("");
                Json::Value *cfg_col = CFG_Fetch_Raw(cfg_row, str);

                if(!cfg_col || !cfg_col->isString()) {
                    if(cfg_col) delete cfg_col;
                    continue;
                }

                widget_template w = widget_template();
                w.key = cfg_col->asString();
                w.row = row;
                w.col = col;
                w.layer = 0;
                widget_templates_[layouts_[i]].push_back(w);
                delete cfg_col;
            }
            delete cfg_row;
        }
    }

    for(unsigned int j = 0; j < static_widgets_.size(); j++ ) {
        widget_template w = widget_template();
        w.key = static_widgets_[j];
        w.row = 0;
        w.col = 0;
        widget_templates_[name_].push_back(w);
    }

    delete section;
    delete layout;
    delete widget;
}
void ApplyUserAttributes(std::string name, AtNode* node,std::vector<std::string> tags,ProcArgs & args)
{

   bool foundInPath = false;
   for(std::vector<std::string>::iterator it=args.userAttributes.begin(); it!=args.userAttributes.end(); ++it)
   {
      Json::Value userAttributes;                        
      if(it->find("/") != std::string::npos) // Based on path
      {
        if(name.find(*it) != std::string::npos)
        {
          userAttributes = args.userAttributesRoot[*it];
          foundInPath = true;
        }
      } 
      else if(matchPattern(name,*it)) // based on wildcard expression
      {
          userAttributes = args.userAttributesRoot[*it];
          foundInPath = true;
      }
      else if(foundInPath == false)
      {
        if (std::find(tags.begin(), tags.end(), *it) != tags.end())
        {
          userAttributes = args.userAttributesRoot[*it];
        }
      }

      if(userAttributes.size() > 0)
      {
        for( Json::ValueIterator itr = userAttributes.begin() ; itr != userAttributes.end() ; itr++ ) 
        {
            std::string attribute = itr.key().asString();

            if( AiNodeLookUpUserParameter(node,attribute.c_str()))
              continue;

            const AtNodeEntry* nodeEntry = AiNodeGetNodeEntry(node);
            Json::Value val = args.userAttributesRoot[*it][attribute];
            if( val.isString() ) 
            {
              AddUserGeomParams(node,attribute.c_str(),AI_TYPE_STRING);
              AiNodeSetStr(node, attribute.c_str(), val.asCString());
            } 
            else if( val.isBool() ) 
            {
              AddUserGeomParams(node,attribute.c_str(),AI_TYPE_BOOLEAN);
              AiNodeSetBool(node, attribute.c_str(), val.asBool());
            }
            else if( val.isInt() ) 
            {
              AddUserGeomParams(node,attribute.c_str(),AI_TYPE_INT);
              AiNodeSetInt(node, attribute.c_str(), val.asInt());
            }
            else if( val.isUInt() ) 
            {
              AddUserGeomParams(node,attribute.c_str(),AI_TYPE_UINT);
              AiNodeSetUInt(node, attribute.c_str(), val.asUInt());
            }
            else if(val.isDouble())
            {
              AddUserGeomParams(node,attribute.c_str(),AI_TYPE_FLOAT);
              AiNodeSetFlt(node, attribute.c_str(), val.asDouble());
            }
            else if(val.isArray()) 
            {              

              // in the future we will convert to an arnold array type for now lets just 
              // write out a json string

              AddUserGeomParams(node,attribute.c_str(),AI_TYPE_STRING);
              Json::FastWriter writer;
              AiNodeSetStr(node, attribute.c_str(), writer.write(val).c_str());
              
              // AddUserGeomParams(node,attribute.c_str(),AI_TYPE_ARRAY );

              // // get the type of the first entry, this will be our key as to
              // // what type of data is in this array
              // Json::Value firstValue = val[0];
              // if (firstValue.isString())
              // {
              //   AtArray* arrayValues = AiArrayAllocate( val.size() , 1, AI_TYPE_STRING);

              //   for( uint idx = 0 ; idx != val.size() ; idx++ ) 
              //   {
              //     AiMsgInfo("[ABC] adding string %s to user array attribute '%s'",val[idx].asCString(),attribute.c_str());
              //     AiArraySetStr(arrayValues,idx,val[idx].asCString());
              //   }

              //   AiNodeSetArray(node, attribute.c_str(), arrayValues);         
              // }
     
            }

            // TODO color, matrix, vector

         }
      }
   }
}
Example #27
0
WidgetBar::WidgetBar(LCDCore *v, std::string n, Json::Value *section,
                     int row, int col, int layer) : Widget(v, n, section, row, col, layer,
                                 WIDGET_TYPE_BAR | WIDGET_TYPE_RC | WIDGET_TYPE_SPECIAL) {

    lcd_type_ = v->GetType();

    if(lcd_type_ == LCD_TEXT)
        Draw = TextBarDraw;
    else if(lcd_type_ == LCD_GRAPHIC)
        Draw = GraphicBarDraw;
    else
        Draw = NULL;

    expression_ = new Property(v, section, "expression", new Json::Value("0"));
    expression2_ = new Property(v, section, "expression2", NULL);
    expr_min_ = new Property(v, section, "min", NULL);
    expr_max_ = new Property(v, section, "max", NULL);

    color_valid_[0] = WidgetColor(section, "barcolor0", &color_[0]);
    color_valid_[1] = WidgetColor(section, "barcolor1", &color_[1]);

    fg_valid_ = WidgetColor(section, "foreground", &fg_color_);
    bg_valid_ = WidgetColor(section, "background", &bg_color_);

    Json::Value *val = v->CFG_Fetch(section, "length", new Json::Value(10));
    cols_ = val->asInt();
    delete val;

    val = v->CFG_Fetch(section, "height", new Json::Value(1));
    rows_ = val->asInt();
    delete val;

    //LCDError("1 cols %d, rows %d", cols_, rows_);
    int diff = (col_ + cols_) - v->GetLCD()->LCOLS;
    if(diff > 0) cols_ -= diff;

    diff = (row_ + rows_) - v->GetLCD()->LROWS;
    if(diff > 0) rows_ -= diff;

    //LCDError("2 cols %d, rows %d", cols_, rows_);
    val = v->CFG_Fetch_Raw(section, "direction", new Json::Value("E"));
    if( val->asString() == "E" ) {
        direction_ = DIR_EAST;
    } else if ( val->asString() == "W" ) {
        direction_ = DIR_WEST;
    } else {
        LCDError("Widget %s has unknown direction '%s'; Use (E)ast or (W)est. Using (E).",
                 name_.c_str(), val->asCString());
        direction_ = DIR_EAST;
    }
    delete val;

    val = v->CFG_Fetch(section, "update", new Json::Value(1000));
    update_ = val->asInt();
    delete val;

    val = v->CFG_Fetch_Raw(section, "style", new Json::Value("N"));

    if( val->asString() == "H" ) {
        style_ = STYLE_HOLLOW;
    } else if (val->asString() == "N") {
        style_ = STYLE_NORMAL;
    } else {
        LCDError("Widget %s has unknown style '%s'; known styles are 'N' or 'H'; using 'N'.",
                 name_.c_str(), val->asCString());
        style_ = STYLE_NORMAL;
    }

    val1_ = val2_ = 0.0;
    min_ = max_ = 0.0;

    timer_ = v->timers_->AddTimer(bar_update, this, update_, true);
    /*
        timer_ = new QTimer();
        timer_->setSingleShot(false);
        timer_->setInterval(update_);
        QObject::connect(timer_, SIGNAL(timeout()), this, SLOT(Update()));

        QObject::connect(visitor_->GetWrapper(), SIGNAL(_ResizeLCD(int, int, int, int)),
            this, SLOT(Resize(int, int, int, int)));
    */
}
Example #28
0
bool JSONImporter::runOnScop(Scop &S) {
  const Dependences &D =
      getAnalysis<DependenceInfo>().getDependences(Dependences::AL_Statement);
  const DataLayout &DL = S.getFunction().getParent()->getDataLayout();

  std::string FileName = ImportDir + "/" + getFileName(S);

  std::string FunctionName = S.getFunction().getName();
  errs() << "Reading JScop '" << S.getNameStr() << "' in function '"
         << FunctionName << "' from '" << FileName << "'.\n";
  ErrorOr<std::unique_ptr<MemoryBuffer>> result =
      MemoryBuffer::getFile(FileName);
  std::error_code ec = result.getError();

  if (ec) {
    errs() << "File could not be read: " << ec.message() << "\n";
    return false;
  }

  Json::Reader reader;
  Json::Value jscop;

  bool parsingSuccessful = reader.parse(result.get()->getBufferStart(), jscop);

  if (!parsingSuccessful) {
    errs() << "JSCoP file could not be parsed\n";
    return false;
  }

  isl_set *OldContext = S.getContext();
  isl_set *NewContext =
      isl_set_read_from_str(S.getIslCtx(), jscop["context"].asCString());

  for (unsigned i = 0; i < isl_set_dim(OldContext, isl_dim_param); i++) {
    isl_id *id = isl_set_get_dim_id(OldContext, isl_dim_param, i);
    NewContext = isl_set_set_dim_id(NewContext, isl_dim_param, i, id);
  }

  isl_set_free(OldContext);
  S.setContext(NewContext);

  StatementToIslMapTy NewSchedule;

  int index = 0;

  for (ScopStmt &Stmt : S) {
    Json::Value schedule = jscop["statements"][index]["schedule"];
    isl_map *m = isl_map_read_from_str(S.getIslCtx(), schedule.asCString());
    isl_space *Space = Stmt.getDomainSpace();

    // Copy the old tuple id. This is necessary to retain the user pointer,
    // that stores the reference to the ScopStmt this schedule belongs to.
    m = isl_map_set_tuple_id(m, isl_dim_in,
                             isl_space_get_tuple_id(Space, isl_dim_set));
    for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
      isl_id *id = isl_space_get_dim_id(Space, isl_dim_param, i);
      m = isl_map_set_dim_id(m, isl_dim_param, i, id);
    }
    isl_space_free(Space);
    NewSchedule[&Stmt] = m;
    index++;
  }

  if (!D.isValidSchedule(S, &NewSchedule)) {
    errs() << "JScop file contains a schedule that changes the "
           << "dependences. Use -disable-polly-legality to continue anyways\n";
    for (StatementToIslMapTy::iterator SI = NewSchedule.begin(),
                                       SE = NewSchedule.end();
         SI != SE; ++SI)
      isl_map_free(SI->second);
    return false;
  }

  auto ScheduleMap = isl_union_map_empty(S.getParamSpace());
  for (ScopStmt &Stmt : S) {
    if (NewSchedule.find(&Stmt) != NewSchedule.end())
      ScheduleMap = isl_union_map_add_map(ScheduleMap, NewSchedule[&Stmt]);
    else
      ScheduleMap = isl_union_map_add_map(ScheduleMap, Stmt.getSchedule());
  }

  S.setSchedule(ScheduleMap);

  int statementIdx = 0;
  for (ScopStmt &Stmt : S) {
    int memoryAccessIdx = 0;
    for (MemoryAccess *MA : Stmt) {
      Json::Value accesses = jscop["statements"][statementIdx]["accesses"]
                                  [memoryAccessIdx]["relation"];
      isl_map *newAccessMap =
          isl_map_read_from_str(S.getIslCtx(), accesses.asCString());
      isl_map *currentAccessMap = MA->getAccessRelation();

      if (isl_map_dim(newAccessMap, isl_dim_param) !=
          isl_map_dim(currentAccessMap, isl_dim_param)) {
        errs() << "JScop file changes the number of parameter dimensions\n";
        isl_map_free(currentAccessMap);
        isl_map_free(newAccessMap);
        return false;
      }

      isl_id *OutId = isl_map_get_tuple_id(currentAccessMap, isl_dim_out);
      newAccessMap = isl_map_set_tuple_id(newAccessMap, isl_dim_out, OutId);

      if (MA->isArrayKind()) {
        // We keep the old alignment, thus we cannot allow accesses to memory
        // locations that were not accessed before if the alignment of the
        // access is not the default alignment.
        bool SpecialAlignment = true;
        if (LoadInst *LoadI = dyn_cast<LoadInst>(MA->getAccessInstruction())) {
          SpecialAlignment =
              DL.getABITypeAlignment(LoadI->getType()) != LoadI->getAlignment();
        } else if (StoreInst *StoreI =
                       dyn_cast<StoreInst>(MA->getAccessInstruction())) {
          SpecialAlignment =
              DL.getABITypeAlignment(StoreI->getValueOperand()->getType()) !=
              StoreI->getAlignment();
        }

        if (SpecialAlignment) {
          isl_set *newAccessSet = isl_map_range(isl_map_copy(newAccessMap));
          isl_set *currentAccessSet =
              isl_map_range(isl_map_copy(currentAccessMap));
          bool isSubset = isl_set_is_subset(newAccessSet, currentAccessSet);
          isl_set_free(newAccessSet);
          isl_set_free(currentAccessSet);

          if (!isSubset) {
            errs() << "JScop file changes the accessed memory\n";
            isl_map_free(currentAccessMap);
            isl_map_free(newAccessMap);
            return false;
          }
        }
      }

      // We need to copy the isl_ids for the parameter dimensions to the new
      // map. Without doing this the current map would have different
      // ids then the new one, even though both are named identically.
      for (unsigned i = 0; i < isl_map_dim(currentAccessMap, isl_dim_param);
           i++) {
        isl_id *id = isl_map_get_dim_id(currentAccessMap, isl_dim_param, i);
        newAccessMap = isl_map_set_dim_id(newAccessMap, isl_dim_param, i, id);
      }

      // Copy the old tuple id. This is necessary to retain the user pointer,
      // that stores the reference to the ScopStmt this access belongs to.
      isl_id *Id = isl_map_get_tuple_id(currentAccessMap, isl_dim_in);
      newAccessMap = isl_map_set_tuple_id(newAccessMap, isl_dim_in, Id);

      if (!isl_map_has_equal_space(currentAccessMap, newAccessMap)) {
        errs() << "JScop file contains access function with incompatible "
               << "dimensions\n";
        isl_map_free(currentAccessMap);
        isl_map_free(newAccessMap);
        return false;
      }

      auto NewAccessDomain = isl_map_domain(isl_map_copy(newAccessMap));
      auto CurrentAccessDomain = isl_map_domain(isl_map_copy(currentAccessMap));

      NewAccessDomain =
          isl_set_intersect_params(NewAccessDomain, S.getContext());
      CurrentAccessDomain =
          isl_set_intersect_params(CurrentAccessDomain, S.getContext());

      if (isl_set_is_subset(CurrentAccessDomain, NewAccessDomain) ==
          isl_bool_false) {
        errs() << "Mapping not defined for all iteration domain elements\n";
        isl_set_free(CurrentAccessDomain);
        isl_set_free(NewAccessDomain);
        isl_map_free(currentAccessMap);
        isl_map_free(newAccessMap);
        return false;
      }

      isl_set_free(CurrentAccessDomain);
      isl_set_free(NewAccessDomain);

      if (!isl_map_is_equal(newAccessMap, currentAccessMap)) {
        // Statistics.
        ++NewAccessMapFound;
        newAccessStrings.push_back(accesses.asCString());
        MA->setNewAccessRelation(newAccessMap);
      } else {
        isl_map_free(newAccessMap);
      }
      isl_map_free(currentAccessMap);
      memoryAccessIdx++;
    }
    statementIdx++;
  }

  return false;
}
void ApplyOverrides(std::string name, AtNode* node, std::vector<std::string> tags, ProcArgs & args)
{
   bool foundInPath = false;
   for(std::vector<std::string>::iterator it=args.overrides.begin(); it!=args.overrides.end(); ++it)
   {
      Json::Value overrides;                        
      if(it->find("/") != std::string::npos) // Based on path
      {
        if(name.find(*it) != std::string::npos)
        {
          overrides = args.overrideRoot[*it];
          foundInPath = true;
        }
      } 
      else if(matchPattern(name,*it)) // based on wildcard expression
      {
          overrides = args.overrideRoot[*it];
          foundInPath = true;
      }
      else if(foundInPath == false)
      {
        if (std::find(tags.begin(), tags.end(), *it) != tags.end())
        {
          overrides = args.overrideRoot[*it];
        }
      }

      if(overrides.size() > 0)
      {
        for( Json::ValueIterator itr = overrides.begin() ; itr != overrides.end() ; itr++ ) 
        {
          std::string attribute = itr.key().asString();

          const AtNodeEntry* nodeEntry = AiNodeGetNodeEntry(node);
          const AtParamEntry* paramEntry = AiNodeEntryLookUpParameter(nodeEntry, attribute.c_str());

          if ( paramEntry != NULL && attribute!="invert_normals" || attribute == "matte")
          {

            Json::Value val = args.overrideRoot[*it][itr.key().asString()];
            if( val.isString() ) 
              AiNodeSetStr(node, attribute.c_str(), val.asCString());
            else if( val.isBool() )
            {
              if(attribute == "matte")
              {
                  AiMsgDebug("[ABC] adding enable_matte to %s", AiNodeGetName(node));
                  AddUserGeomParams(node,"enable_matte",AI_TYPE_BOOLEAN);
                  AiNodeSetBool(node,"enable_matte", val.asBool());
              }
              else
              {
                  AiNodeSetBool(node, attribute.c_str(), val.asBool());
              }
            }
            else if( val.isInt() ) 
            {
              //make the difference between Byte & int!
              int typeEntry = AiParamGetType(paramEntry);
              if(typeEntry == AI_TYPE_BYTE)
              { 
                if(attribute=="visibility")
                {
                  AtByte attrViz = val.asInt();
                  // special case, we must determine it against the general viz.
                  AtByte procViz = AiNodeGetByte( args.proceduralNode, "visibility" );
                  AtByte compViz = AI_RAY_ALL;
                  {
                    compViz &= ~AI_RAY_GLOSSY;
                    if(procViz > compViz)
                      procViz &= ~AI_RAY_GLOSSY;
                    else
                      attrViz &= ~AI_RAY_GLOSSY;
                    compViz &= ~AI_RAY_DIFFUSE;
                    if(procViz > compViz)
                      procViz &= ~AI_RAY_DIFFUSE;
                    else
                      attrViz &= ~AI_RAY_DIFFUSE;
                    compViz &= ~AI_RAY_REFRACTED;
                    if(procViz > compViz)
                      procViz &= ~AI_RAY_REFRACTED;
                    else
                      attrViz &= ~AI_RAY_REFRACTED;
                    compViz &= ~AI_RAY_REFLECTED;
                    if(procViz > compViz)
                      procViz &= ~AI_RAY_REFLECTED;
                    else
                      attrViz &= ~AI_RAY_REFLECTED;
                    compViz &= ~AI_RAY_SHADOW;
                    if(procViz > compViz)
                      procViz &= ~AI_RAY_SHADOW;
                    else
                      attrViz &= ~AI_RAY_SHADOW;
                    compViz &= ~AI_RAY_CAMERA;
                    if(procViz > compViz)
                      procViz &= ~AI_RAY_CAMERA;
                    else
                      attrViz &= ~AI_RAY_CAMERA;
                  }

                  AiNodeSetByte(node, attribute.c_str(), attrViz);
                }
                else
                  AiNodeSetByte(node, attribute.c_str(), val.asInt());
              }
              else 
                AiNodeSetInt(node, attribute.c_str(), val.asInt());
            }
            else if( val.isUInt() ) 
              AiNodeSetUInt(node, attribute.c_str(), val.asUInt());
            else if( val.isDouble() ) 
              AiNodeSetFlt(node, attribute.c_str(), val.asDouble());
          }
        }
      }

   }
}
Example #30
0
void
Locations::readFile(std::string filename)
{

	if(filename!="")
	{

		std::ifstream t(filename.c_str());
		std::stringstream buffer;
		buffer << t.rdbuf();

		Json::Value root;   // will contains the root value after parsing.
		Json::Reader reader;
		bool parsingSuccessful = reader.parse( buffer.str(), root );
		if ( !parsingSuccessful )
		{
			// report to the user the failure and their locations in the document.
			std::cout  << "Failed to parse configuration\n"
					<< reader.getFormattedErrorMessages();
			return;
		}

		Json::Value locations = root["locations"];

		if(locations.isArray())
		{
			for(int i=0; i< locations.size(); i++)
			{
				if(locations[i].isMember("name") &&
				   locations[i].isMember("position") &&
				   locations[i].isMember("orientation") &&
				   locations[i].isMember("description"))
				{
					Json::Value name = locations[i]["name"];
					Json::Value position = locations[i]["position"];
					Json::Value orientation = locations[i]["orientation"];
					Json::Value description = locations[i]["description"];

					geometry_msgs::Pose pose;

					if(position.size()==3)
					{
						pose.position.x = position[0].asDouble();
						pose.position.y = position[1].asDouble();
						pose.position.z = position[2].asDouble();
					}else
						ROS_ERROR("Error parsing [%s][%s element]: field position requires 3 values", filename.c_str(),  name.asCString());

					if(orientation.size()==4)
					{
						pose.orientation.x = orientation[0].asDouble();
						pose.orientation.y = orientation[1].asDouble();
						pose.orientation.z = orientation[2].asDouble();
						pose.orientation.w = orientation[3].asDouble();
					}else
						ROS_ERROR("Error parsing [%s][%s element]: field orientation requires 4 values", filename.c_str(), name.asCString());

					locations_[name.asString()] = pose;
				}else
				{
					if(!locations[i].isMember("name"))
							ROS_ERROR("Error parsing [%s][%d element]: Missing field \"name\"", filename.c_str(), i);
					if(!locations[i].isMember("position"))
							ROS_ERROR("Error parsing [%s][%d element]: Missing field \"position\"", filename.c_str(), i);
					if(!locations[i].isMember("orientation"))
							ROS_ERROR("Error parsing [%s][%d element]: Missing field \"orientation\"", filename.c_str(), i);
					if(!locations[i].isMember("description"))
							ROS_ERROR("Error parsing [%s][%d element]: Missing field \"description\"", filename.c_str(), i);

				}
			}
		}

	}
}