Example #1
0
void Player::setTagPosition(int x, int y){
	auto spriteSize = m_node->getContentSize();
	Vec2 dstPos = Vec2(x + spriteSize.width / 2, y);

	Vec2 tiledPos = tileCoorForPosition(Vec2(dstPos.x, dstPos.y));

	int tiledGid = meta->getTileGIDAt(tiledPos);

	if (tiledGid != 0){
		Value properties = m_map->getPropertiesForGID(tiledGid);
		ValueMap propertiesMap = properties.asValueMap();

		if (propertiesMap.find("Collidable") != propertiesMap.end()){
			Value prop = propertiesMap.at("Collidable");
			if (prop.asString().compare("true") == 0){
				return;
			}
		}

		if (propertiesMap.find("food") != propertiesMap.end()){
			Value prop = propertiesMap.at("food");
			if (prop.asString().compare("true") == 0){
				TMXLayer* barrier = m_map->getLayer("barrier");
				barrier->removeTileAt(tiledPos);
			}
		}
	}
	
	Entity::setTagPosition(x, y);
	setViewPointByPlayer();
}
void AnimationCache::addAnimationsWithDictionary(const ValueMap& dictionary,const std::string& plist)
{
    if ( dictionary.find("animations") == dictionary.end() )
    {
        CCLOG("cocos2d: AnimationCache: No animations were found in provided dictionary.");
        return;
    }
    
    const Value& animations = dictionary.at("animations");
    unsigned int version = 1;

    if( dictionary.find("properties") != dictionary.end() )
    {
        const ValueMap& properties = dictionary.at("properties").asValueMap();
        version = properties.at("format").asInt();
        const ValueVector& spritesheets = properties.at("spritesheets").asValueVector();

        for(const auto &value : spritesheets) {
            std::string path = FileUtils::getInstance()->fullPathFromRelativeFile(value.asString(),plist);
            SpriteFrameCache::getInstance()->addSpriteFramesWithFile(path);
        }
    }

    switch (version) {
        case 1:
            parseVersion1(animations.asValueMap());
            break;
        case 2:
            parseVersion2(animations.asValueMap());
            break;
        default:
            CCASSERT(false, "Invalid animation format");
    }
}
Example #3
0
bool BrokableWall::init( const ValueMap &valueMap , const ValueMap &gidProperties )
{
	if (!BaseEntity::initWithMap(valueMap )) return false;
	//std::string img = Utils::getWallByType(this->m_nType);
	std::string img = gidProperties.find("source")->second.asString();
	m_durability = gidProperties.find("durability")->second.asInt();
	if (!BaseEntity::initWithFile(img)) return false;
	setPositionAndRotation();
	this->setPhysicsBody(PhysicsBody::createEdgeBox(this->getContentSize(), PhysicsMaterial(1.0f, 0.4f, 1.0f), 0));//ÃÜ¶È µ¯Á¦ Ħ²ÁÁ¦

	setContactTestBitmask(0x0002);
	setEntityType(Type_Brokable);
	return true;
}
//
// load file
//
void Configuration::loadConfigFile(const std::string& filename)
{
	ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(filename);
	CCASSERT(!dict.empty(), "cannot create dictionary");

	// search for metadata
	bool validMetadata = false;
	auto metadataIter = dict.find("metadata");
	if (metadataIter != dict.cend() && metadataIter->second.getType() == Value::Type::MAP)
    {
        
		const auto& metadata = metadataIter->second.asValueMap();
        auto formatIter = metadata.find("format");
        
		if (formatIter != metadata.cend())
        {
			int format = formatIter->second.asInt();

			// Support format: 1
			if (format == 1)
            {
				validMetadata = true;
			}
		}
	}

	if (! validMetadata)
    {
		CCLOG("Invalid config format for file: %s", filename.c_str());
		return;
	}

	auto dataIter = dict.find("data");
	if (dataIter == dict.cend() || dataIter->second.getType() != Value::Type::MAP)
    {
		CCLOG("Expected 'data' dict, but not found. Config file: %s", filename.c_str());
		return;
	}

	// Add all keys in the existing dictionary
    
	const auto& dataMap = dataIter->second.asValueMap();
    for (auto dataMapIter = dataMap.cbegin(); dataMapIter != dataMap.cend(); ++dataMapIter)
    {
        if (_valueDict.find(dataMapIter->first) == _valueDict.cend())
            _valueDict[dataMapIter->first] = dataMapIter->second;
        else
            CCLOG("Key already present. Ignoring '%s'",dataMapIter->first.c_str());
    }
}
Example #5
0
EntityParameterLevel UserDataManager::getEntityParameterLevel(EntityType entityType)
{
    this->load();

    // Return initial params if there are no data for entity parameters
    if (this->userData.find(USER_DATA_ENTITY_PARAMETER) == this->userData.end()) {
        EntityParameterLevel parameterLevel = ENTITY_INITIAL_LEVEL_PARAMETER.at(entityType);
        return parameterLevel;
    }

    std::string entityTypeString = std::to_string((int)entityType);
    ValueMap entityListParameterMap = this->userData[USER_DATA_ENTITY_PARAMETER].asValueMap();

    // Return initial params if there are no data for a selected entity
    if (entityListParameterMap.find(entityTypeString) == this->userData.end()) {
        EntityParameterLevel parameterLevel = ENTITY_INITIAL_LEVEL_PARAMETER.at(entityType);
        return parameterLevel;
    }

    ValueMap data = entityListParameterMap[entityTypeString].asValueMap();
    return EntityParameterLevel {
               data["rank"].asInt(),
               data["levelHp"].asInt(),
               data["levelAttack"].asInt(),
    };
}
Example #6
0
void UserDataManager::setEntityParameterLevel(EntityType entityType, EntityParameterLevel EntityParameterLevel)
{
    ValueMap entityListParameterMap;

    if (this->userData.find(USER_DATA_ENTITY_PARAMETER) == this->userData.end()) {
        entityListParameterMap = ValueMap();
    } else {
        entityListParameterMap = this->userData[USER_DATA_ENTITY_PARAMETER].asValueMap();
    }

    std::string entityTypeString = this->getEntityTypeStringByEntityType(entityType);
    ValueMap entityParameterMap;

    if (entityListParameterMap.find(entityTypeString) == entityListParameterMap.end()) {
        entityParameterMap = ValueMap();
    } else {
        entityParameterMap = entityListParameterMap[entityTypeString].asValueMap();
    }

    entityParameterMap["rank"] = EntityParameterLevel.rank;
    entityParameterMap["levelHp"] = EntityParameterLevel.hp;
    entityParameterMap["levelAttack"] = EntityParameterLevel.attack;

    entityListParameterMap[entityTypeString] = entityParameterMap;
    this->userData[USER_DATA_ENTITY_PARAMETER] = entityListParameterMap;

    this->save();
}
Example #7
0
void AppRequests::didFetchAppRequests(const Vector<screw::facebook::GraphRequest *> &requests) {
    for (GraphRequest *request : requests) {
        string dataStr = request->getDataString();
        Value &v = request->getValue();
        FB_LOG_INFO("AppRequests::didFetchAppRequests - data str = %s", dataStr.c_str());
        if (dataStr.length()) {
            ValueMap m;
            if (JsonUtils::parse(dataStr, m)) {
                if (m.find(AppRequestsDataTypeKey) == m.end()) {
                    FB_LOG("AppRequests::didFetchAppRequests - request data with no type (be aware) %s", v.getDescription().c_str());
                }
                ValueSetter::set(v, "data", Value(m));
                FB_LOG("AppRequests::didFetchAppRequests - parsed data = %s", Value(m).getDescription().c_str());
            } else {
                FB_LOG("AppRequests::didFetchAppRequests - non JSON request data (cleared) %s", v.getDescription().c_str());
                ValueSetter::clear(v, "data");
            }
        }
        _data->set(AppRequestsRequestsKey + "/" + request->getId(), v);
        
        //Delete request
        Request::requestForDelete(request->getId(), nullptr)->execute();
    }
    
    if (requests.size()) {
        _data->save();
    }
}
Example #8
0
    DayRecord* DayRecords::getDayRecord(int day) {
        if (_day_records.find(day) == _day_records.end()) {
            DayRecord* day_rec = new DayRecord(day);
            
            std::string filepath = DayRecords::getDataPath();
            
            if (FileUtils::getInstance()->isFileExist(filepath)) {
                ValueMap data = FileUtils::getInstance()->getValueMapFromFile(filepath);
                std::string strday = StringUtils::format("%d", day);
                if (data.find(strday) != data.end()) {
                    ValueMap daydata = data[strday].asValueMap();
                    day_rec->loadFromValueMap(daydata);
                    _day_records[day] = *day_rec;
                    return &_day_records[day];
                }

            }
            
        } else {
            return &_day_records[day];
        }
        DayRecord* day_rec = new DayRecord(day);
        _day_records[day] = *day_rec;
        return &_day_records[day];
    }
bool SpriteFrameCache::reloadTexture(const std::string& plist)
{
    CCASSERT(plist.size()>0, "plist filename should not be nullptr");

    auto it = _loadedFileNames->find(plist);
    if (it != _loadedFileNames->end()) {
        _loadedFileNames->erase(it);
    }
    else
    {
        //If one plist has't be loaded, we don't load it here.
        return false;
    }

    std::string fullPath = FileUtils::getInstance()->fullPathForFilename(plist);
    ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(fullPath);

    string texturePath("");

    if (dict.find("metadata") != dict.end())
    {
        ValueMap& metadataDict = dict["metadata"].asValueMap();
        // try to read  texture file name from meta data
        texturePath = metadataDict["textureFileName"].asString();
    }

    if (!texturePath.empty())
    {
        // build texture path relative to plist file
        texturePath = FileUtils::getInstance()->fullPathFromRelativeFile(texturePath, plist);
    }
    else
    {
        // build texture path by replacing file extension
        texturePath = plist;

        // remove .xxx
        size_t startPos = texturePath.find_last_of(".");
        texturePath = texturePath.erase(startPos);

        // append .png
        texturePath = texturePath.append(".png");
    }

    Texture2D *texture = nullptr;
    if (Director::getInstance()->getTextureCache()->reloadTexture(texturePath))
        texture = Director::getInstance()->getTextureCache()->getTextureForKey(texturePath);

    if (texture)
    {
        reloadSpriteFramesWithDictionary(dict, texture);
        _loadedFileNames->insert(plist);
    }
    else
    {
        CCLOG("cocos2d: SpriteFrameCache: Couldn't load texture");
    }
    return true;
}
/// UpdateCallGraphAfterInlining - Once we have cloned code over from a callee
/// into the caller, update the specified callgraph to reflect the changes we
/// made.  Note that it's possible that not all code was copied over, so only
/// some edges of the callgraph may remain.
static void UpdateCallGraphAfterInlining(CallSite CS,
                                         Function::iterator FirstNewBlock,
                                         ValueMap<const Value*, Value*> &VMap,
                                         InlineFunctionInfo &IFI) {
  CallGraph &CG = *IFI.CG;
  const Function *Caller = CS.getInstruction()->getParent()->getParent();
  const Function *Callee = CS.getCalledFunction();
  CallGraphNode *CalleeNode = CG[Callee];
  CallGraphNode *CallerNode = CG[Caller];

  // Since we inlined some uninlined call sites in the callee into the caller,
  // add edges from the caller to all of the callees of the callee.
  CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();

  // Consider the case where CalleeNode == CallerNode.
  CallGraphNode::CalledFunctionsVector CallCache;
  if (CalleeNode == CallerNode) {
    CallCache.assign(I, E);
    I = CallCache.begin();
    E = CallCache.end();
  }

  for (; I != E; ++I) {
    const Value *OrigCall = I->first;

    ValueMap<const Value*, Value*>::iterator VMI = VMap.find(OrigCall);
    // Only copy the edge if the call was inlined!
    if (VMI == VMap.end() || VMI->second == 0)
      continue;
    
    // If the call was inlined, but then constant folded, there is no edge to
    // add.  Check for this case.
    Instruction *NewCall = dyn_cast<Instruction>(VMI->second);
    if (NewCall == 0) continue;

    // Remember that this call site got inlined for the client of
    // InlineFunction.
    IFI.InlinedCalls.push_back(NewCall);

    // It's possible that inlining the callsite will cause it to go from an
    // indirect to a direct call by resolving a function pointer.  If this
    // happens, set the callee of the new call site to a more precise
    // destination.  This can also happen if the call graph node of the caller
    // was just unnecessarily imprecise.
    if (I->second->getFunction() == 0)
      if (Function *F = CallSite(NewCall).getCalledFunction()) {
        // Indirect call site resolved to direct call.
        CallerNode->addCalledFunction(CallSite::get(NewCall), CG[F]);
        
        continue;
      }
    
    CallerNode->addCalledFunction(CallSite::get(NewCall), I->second);
  }
  
  // Update the call graph by deleting the edge from Callee to Caller.  We must
  // do this after the loop above in case Caller and Callee are the same.
  CallerNode->removeCallEdgeFor(CS);
}
Example #11
0
void SpriteFrameCache::addSpriteFramesWithFile(const std::string& plist)
{
    CCASSERT(plist.size()>0, "plist filename should not be nullptr");

    std::string fullPath = FileUtils::getInstance()->fullPathForFilename(plist);
    if (fullPath.size() == 0)
    {
        // return if plist file doesn't exist
        CCLOG("cocos2d: SpriteFrameCache: can not find %s", plist.c_str());
        return;
    }

    if (_loadedFileNames->find(plist) == _loadedFileNames->end())
    {

        ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(fullPath);

        string texturePath("");

        if (dict.find("metadata") != dict.end())
        {
            ValueMap& metadataDict = dict["metadata"].asValueMap();
            // try to read  texture file name from meta data
            texturePath = metadataDict["textureFileName"].asString();
        }

        if (!texturePath.empty())
        {
            // build texture path relative to plist file
            texturePath = FileUtils::getInstance()->fullPathFromRelativeFile(texturePath.c_str(), plist);
        }
        else
        {
            // build texture path by replacing file extension
            texturePath = plist;

            // remove .xxx
            size_t startPos = texturePath.find_last_of(".");
            texturePath = texturePath.erase(startPos);

            // append .png
            texturePath = texturePath.append(".png");

            CCLOG("cocos2d: SpriteFrameCache: Trying to use file %s as texture", texturePath.c_str());
        }

        Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(texturePath.c_str());

        if (texture)
        {
            addSpriteFramesWithDictionary(dict, texture);
            _loadedFileNames->insert(plist);
        }
        else
        {
            CCLOG("cocos2d: SpriteFrameCache: Couldn't load texture");
        }
    }
}
/// RemapInstruction - Convert the instruction operands from referencing the
/// current values into those specified by VMap.
static inline void RemapInstruction(Instruction *I,
                                    ValueMap<const Value *, Value*> &VMap) {
    for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
        Value *Op = I->getOperand(op);
        ValueMap<const Value *, Value*>::iterator It = VMap.find(Op);
        if (It != VMap.end())
            I->setOperand(op, It->second);
    }
}
Example #13
0
void *valmap_find(valmap_t map, LLVMValueRef v)
{
  ValueMap<Value*,void*> *vmap = (ValueMap<Value*,void*>*)map;
  Value *val = unwrap(v);
  
  if(vmap->find(val)==vmap->end())
    return NULL;
 
  return (*vmap)[val];
}
Example #14
0
void WorldLayer::setPlayerPosition(Point position) {
	Point tileCoord = this->tileCoordForPosition(position);
	int tileFUCKEDUP = _meta->getTileGIDAt(tileCoord);
	if(tileFUCKEDUP) {
		Value shit = map->getPropertiesForGID(tileFUCKEDUP);
		ValueMap doubleShit = shit.asValueMap();
		auto temp = doubleShit.find("Collidable");
		CCLOG(( temp->second.asBool() ? "Yes" : "No" ));
	}
	
	p1->setPosition(position);
}
void SpriteFrameCache::addSpriteFramesWithDictionary(ValueMap& dict, const std::string &texturePath)
{
    std::string pixelFormatName;
    if (dict.find("metadata") != dict.end())
    {
        ValueMap& metadataDict = dict.at("metadata").asValueMap();
        if (metadataDict.find("pixelFormat") != metadataDict.end())
        {
            pixelFormatName = metadataDict.at("pixelFormat").asString();
        }
    }
    
    Texture2D *texture = nullptr;
    static std::unordered_map<std::string, Texture2D::PixelFormat> pixelFormats = {
        {"RGBA8888", Texture2D::PixelFormat::RGBA8888},
        {"RGBA4444", Texture2D::PixelFormat::RGBA4444},
        {"RGB5A1", Texture2D::PixelFormat::RGB5A1},
        {"RGBA5551", Texture2D::PixelFormat::RGB5A1},
        {"RGB565", Texture2D::PixelFormat::RGB565},
        {"A8", Texture2D::PixelFormat::A8},
        {"ALPHA", Texture2D::PixelFormat::A8},
        {"I8", Texture2D::PixelFormat::I8},
        {"AI88", Texture2D::PixelFormat::AI88},
        {"ALPHA_INTENSITY", Texture2D::PixelFormat::AI88},
        //{"BGRA8888", Texture2D::PixelFormat::BGRA8888}, no Image conversion RGBA -> BGRA
        {"RGB888", Texture2D::PixelFormat::RGB888}
    };

    auto pixelFormatIt = pixelFormats.find(pixelFormatName);
    if (pixelFormatIt != pixelFormats.end())
    {
        const Texture2D::PixelFormat pixelFormat = (*pixelFormatIt).second;
        const Texture2D::PixelFormat currentPixelFormat = Texture2D::getDefaultAlphaPixelFormat();
        Texture2D::setDefaultAlphaPixelFormat(pixelFormat);
        texture = Director::getInstance()->getTextureCache()->addImage(texturePath);
        Texture2D::setDefaultAlphaPixelFormat(currentPixelFormat);
    }
    else
    {
        texture = Director::getInstance()->getTextureCache()->addImage(texturePath);
    }
    
    if (texture)
    {
        addSpriteFramesWithDictionary(dict, texture);
    }
    else
    {
        CCLOG("cocos2d: SpriteFrameCache: Couldn't load texture");
    }
}
Example #16
0
    void DayRecord::loadFromValueMap(ValueMap &map) {

        _day = map["day"].asInt();
        _earned = map["earned"].asDouble();
        _spent = map["spent"].asDouble();
        _money = map["money"].asFloat();
        _diamond = map["diamond"].asInt();
        _reputation = map["reputation"].asFloat();
        _soldItems.clear();
        if (map.find("sold_items") != map.end()) {
            for (auto iter: map["sold_items"].asValueMap()) {
                _soldItems[iter.first] = iter.second.asInt();
            }
        }
        
        _boughtItems.clear();
        if (map.find("bought_items") != map.end()) {
            for (auto iter: map["bought_items"].asValueMap()) {
                _boughtItems[iter.first] = iter.second.asInt();
            }
        }
        
    }
Example #17
0
bool YellowWall::init( const ValueMap &valueMap, const ValueMap & gidProperties )
{
	if (!BaseEntity::initWithMap(valueMap)) return false;
	//std::string img = Utils::getWallByType(this->m_nType);
	std::string img = gidProperties.find("source")->second.asString();
	if (!BaseEntity::initWithFile(img)) return false;
	setPositionAndRotation();
	std::string type = gidProperties.find("type")->second.asString();
	if (type == "target")
	{
		this->setPhysicsBody(PhysicsBody::createEdgeBox(this->getContentSize(), PhysicsMaterial(1.0f, 0.2f, 1.0f), 0));
		this->setContactTestBitmask(0x0001);
		setEntityType(Type_Yellow);
	}
	else if (type == "flag")
	{
		this->playFlagAnimate();
		this->setPhysicsBody(PhysicsBody::createEdgeBox(this->getContentSize()));
		this->setContactTestBitmask(0x0002);
		setEntityType(Type_Flag);
	}
	
	return true;
}
Example #18
0
void HelloWorld::setPlayerPosition(Point position) {
	// This part is completely different from version 2.X
	// There might be a better way to do this since this is what made sense
	// in the moment
	cocos2d::Point tileCoord = this->tileCoordForPosition(position);
	int tileFUCKEDUP = _meta->tileGIDAt(tileCoord);
	if(tileFUCKEDUP) {
		Value shit = _tileMap->propertiesForGID(tileFUCKEDUP);
		ValueMap doubleShit = shit.asValueMap();
		auto temp = doubleShit.find("Collidable");
		CCLOG(( temp->second.asBool() ? "Yes" : "No" ));
	}
	
	_player->setPosition(position);
}
Example #19
0
	const std::string &getValue(const std::string &name, const std::string &defaultValue) const
	{
		ValueMap::const_iterator it = values.find(name);
		if(it == values.end())
		{
			if ((flags & VALUEMAP_MASK_LOG_NONEXISTING) != 0)
			{
				std::string msg = std::string("ParserGroupData::getValue - Given key \"");
				msg += name;
				msg += std::string("\" does not exist, returning default value.");
				Logger::getInstance()->warning(msg.c_str());
			}
			return defaultValue;
		}

		int *flag = const_cast<int *>(&((*it).second.second));
		*flag |= VALUEMAP_MASK_REFERENCED;
		return (*it).second.first;
	}
    string paramValueNumber(AstNode* nodep) {
	// Given a compilcated object create a number to use for param module assignment
	// Ideally would be relatively stable if design changes (not use pointer value),
	// and must return same value given same input node
	// Return must presently be numberic so doesn't collide with 'small' alphanumeric parameter names
	ValueMap::iterator it = m_valueMap.find(nodep);
	if (it != m_valueMap.end()) {
	    return cvtToStr(it->second);
	} else {
	    static int BUCKETS = 1000;
	    V3Hash hash (nodep->name());
	    int bucket = hash.hshval() % BUCKETS;
	    int offset = 0;
	    NextValueMap::iterator it = m_nextValueMap.find(bucket);
	    if (it != m_nextValueMap.end()) { offset = it->second; it->second = offset + 1; }
	    else { m_nextValueMap.insert(make_pair(bucket, offset + 1)); }
	    int num = bucket + offset * BUCKETS;
	    m_valueMap.insert(make_pair(nodep, num));
	    return cvtToStr(num);
	}
    }
Example #21
0
bool Session::snmpGet( const Identifier &identifier, Value &value, ErrorInfo *error )
{
    ValueMap vars;
    IdentifierList ids;

    ids << identifier;

    if ( !snmpGet( ids, vars, error ) )
        return false;

    ValueMap::ConstIterator it = vars.find( identifier );
    if ( it == vars.end() ) {
        if ( error )
            *error = ErrorInfo( ErrorInfo::ErrMissingVariables );
        return false;
    }

    value = it.data();

    return true;
}
Example #22
0
  // Try to clone everything in the llvm::Value hierarchy.
  LLVMValueRef CloneValue(LLVMValueRef Src) {
    // First, the value may be constant.
    if (LLVMIsAConstant(Src))
      return clone_constant(Src, M);

    // Function argument should always be in the map already.
    auto i = VMap.find(Src);
    if (i != VMap.end())
      return i->second;

    if (!LLVMIsAInstruction(Src))
      report_fatal_error("Expected an instruction");

    auto Ctx = LLVMGetModuleContext(M);
    auto Builder = LLVMCreateBuilderInContext(Ctx);
    auto BB = DeclareBB(LLVMGetInstructionParent(Src));
    LLVMPositionBuilderAtEnd(Builder, BB);
    auto Dst = CloneInstruction(Src, Builder);
    LLVMDisposeBuilder(Builder);
    return Dst;
  }
Example #23
0
bool EventTrigger::init( class MapLogic* map_logic, const ValueMap& event_data ) {
    this->setMapLogic( map_logic );
    _current_trigger_index = 0;
    _should_recycle = false;
    
    _event_data = event_data;
    const ValueMap& meta_data = event_data.at( "trigger_meta" ).asValueMap();
    auto itr = meta_data.find( "trigger_relation" );
    if( itr == meta_data.end() ) {
        _relation = "then";
    }
    else {
        _relation = itr->second.asString();
    }
    itr = meta_data.find( "is_repeated" );
    if( itr == meta_data.end() ) {
        _is_repeat = false;
    }
    else {
        _is_repeat = itr->second.asBool();
    }
    
    itr = event_data.find( "enabled" );
    if( itr != event_data.end() ) {
        this->setEnabled( itr->second.asBool() );
    }
    else {
        this->setEnabled( true );
    }
    
    const ValueVector& trigger_data = event_data.at( "triggers" ).asValueVector();
    _total_trigger_count = (int)trigger_data.size();
    for( auto itr = trigger_data.begin(); itr != trigger_data.end(); ++itr ) {
        Trigger* trigger = Trigger::create( itr->asValueMap() );
        this->addTrigger( trigger );
    }
    
    return true;
}
Example #24
0
void TmxMapHelper::objectToVertices(int mapHeihgt, int groupHeight,
	ValueMap &object, vector<float> &vertices)
{
	auto it = object.find("points");
	if (it == object.end())
		return;

	Vec2 origin(object["x"].asInt(), object["y"].asInt());
	origin.y = mapHeihgt - origin.y;

	ValueVector &points = it->second.asValueVector();
	vertices.clear();
	vertices.reserve(points.size() * 2);
	for (size_t i = 0; i < points.size(); ++i)
	{
		ValueMap &point = points[i].asValueMap();
		float x = origin.x + point["x"].asInt();
		float y = groupHeight - (origin.y + point["y"].asInt());
		vertices.push_back(x);
		vertices.push_back(y);
	}
}
Example #25
0
const Value * AMDGPUDAGToDAGISel::getBasePointerValue(const Value *V) {
  if (!V) {
    return NULL;
  }
  const Value *ret = NULL;
  ValueMap<const Value *, bool> ValueBitMap;
  std::queue<const Value *, std::list<const Value *> > ValueQueue;
  ValueQueue.push(V);
  while (!ValueQueue.empty()) {
    V = ValueQueue.front();
    if (ValueBitMap.find(V) == ValueBitMap.end()) {
      ValueBitMap[V] = true;
      if (dyn_cast<Argument>(V) && dyn_cast<PointerType>(V->getType())) {
        ret = V;
        break;
      } else if (dyn_cast<GlobalVariable>(V)) {
        ret = V;
        break;
      } else if (dyn_cast<Constant>(V)) {
        const ConstantExpr *CE = dyn_cast<ConstantExpr>(V);
        if (CE) {
          ValueQueue.push(CE->getOperand(0));
        }
      } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
        ret = AI;
        break;
      } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
        uint32_t numOps = I->getNumOperands();
        for (uint32_t x = 0; x < numOps; ++x) {
          ValueQueue.push(I->getOperand(x));
        }
      } else {
        assert(!"Found a Value that we didn't know how to handle!");
      }
    }
    ValueQueue.pop();
  }
  return ret;
}
bool ParticleSystem::initWithDictionary(ValueMap& dictionary, const std::string& dirname)
{
    bool ret = false;
    unsigned char *buffer = nullptr;
    unsigned char *deflated = nullptr;
    Image *image = nullptr;
    do 
    {
        int maxParticles = dictionary["maxParticles"].asInt();
        // self, not super
        if(this->initWithTotalParticles(maxParticles))
        {
            // Emitter name in particle designer 2.0
            _configName = dictionary["configName"].asString();

            // angle
            _angle = dictionary["angle"].asFloat();
            _angleVar = dictionary["angleVariance"].asFloat();

            // duration
            _duration = dictionary["duration"].asFloat();

            // blend function 
            if (_configName.length()>0)
            {
                _blendFunc.src = dictionary["blendFuncSource"].asFloat();
            }
            else
            {
                _blendFunc.src = dictionary["blendFuncSource"].asInt();
            }
            _blendFunc.dst = dictionary["blendFuncDestination"].asInt();

            // color
            _startColor.r = dictionary["startColorRed"].asFloat();
            _startColor.g = dictionary["startColorGreen"].asFloat();
            _startColor.b = dictionary["startColorBlue"].asFloat();
            _startColor.a = dictionary["startColorAlpha"].asFloat();

            _startColorVar.r = dictionary["startColorVarianceRed"].asFloat();
            _startColorVar.g = dictionary["startColorVarianceGreen"].asFloat();
            _startColorVar.b = dictionary["startColorVarianceBlue"].asFloat();
            _startColorVar.a = dictionary["startColorVarianceAlpha"].asFloat();

            _endColor.r = dictionary["finishColorRed"].asFloat();
            _endColor.g = dictionary["finishColorGreen"].asFloat();
            _endColor.b = dictionary["finishColorBlue"].asFloat();
            _endColor.a = dictionary["finishColorAlpha"].asFloat();

            _endColorVar.r = dictionary["finishColorVarianceRed"].asFloat();
            _endColorVar.g = dictionary["finishColorVarianceGreen"].asFloat();
            _endColorVar.b = dictionary["finishColorVarianceBlue"].asFloat();
            _endColorVar.a = dictionary["finishColorVarianceAlpha"].asFloat();

            // particle size
            _startSize = dictionary["startParticleSize"].asFloat();
            _startSizeVar = dictionary["startParticleSizeVariance"].asFloat();
            _endSize = dictionary["finishParticleSize"].asFloat();
            _endSizeVar = dictionary["finishParticleSizeVariance"].asFloat();

            // position
            float x = dictionary["sourcePositionx"].asFloat();
            float y = dictionary["sourcePositiony"].asFloat();
            this->setPosition( Point(x,y) );            
            _posVar.x = dictionary["sourcePositionVariancex"].asFloat();
            _posVar.y = dictionary["sourcePositionVariancey"].asFloat();

            // Spinning
            _startSpin = dictionary["rotationStart"].asFloat();
            _startSpinVar = dictionary["rotationStartVariance"].asFloat();
            _endSpin= dictionary["rotationEnd"].asFloat();
            _endSpinVar= dictionary["rotationEndVariance"].asFloat();

            _emitterMode = (Mode) dictionary["emitterType"].asInt();

            // Mode A: Gravity + tangential accel + radial accel
            if (_emitterMode == Mode::GRAVITY)
            {
                // gravity
                modeA.gravity.x = dictionary["gravityx"].asFloat();
                modeA.gravity.y = dictionary["gravityy"].asFloat();

                // speed
                modeA.speed = dictionary["speed"].asFloat();
                modeA.speedVar = dictionary["speedVariance"].asFloat();

                // radial acceleration
                modeA.radialAccel = dictionary["radialAcceleration"].asFloat();
                modeA.radialAccelVar = dictionary["radialAccelVariance"].asFloat();

                // tangential acceleration
                modeA.tangentialAccel = dictionary["tangentialAcceleration"].asFloat();
                modeA.tangentialAccelVar = dictionary["tangentialAccelVariance"].asFloat();
                
                // rotation is dir
                modeA.rotationIsDir = dictionary["rotationIsDir"].asBool();
            }

            // or Mode B: radius movement
            else if (_emitterMode == Mode::RADIUS)
            {
                if (_configName.length()>0)
                {
                    modeB.startRadius = dictionary["maxRadius"].asInt();
                }
                else
                {
                    modeB.startRadius = dictionary["maxRadius"].asFloat();
                }
                modeB.startRadiusVar = dictionary["maxRadiusVariance"].asFloat();
                if (_configName.length()>0)
                {
                    modeB.endRadius = dictionary["minRadius"].asInt();
                }
                else
                {
                    modeB.endRadius = dictionary["minRadius"].asFloat();
                }
                
                if (dictionary.find("minRadiusVariance") != dictionary.end())
                {
                    modeB.endRadiusVar = dictionary["minRadiusVariance"].asFloat();
                }
                else
                {
                    modeB.endRadiusVar = 0.0f;
                }
                
                if (_configName.length()>0)
                {
                    modeB.rotatePerSecond = dictionary["rotatePerSecond"].asInt();
                }
                else
                {
                    modeB.rotatePerSecond = dictionary["rotatePerSecond"].asFloat();
                }
                modeB.rotatePerSecondVar = dictionary["rotatePerSecondVariance"].asFloat();

            } else {
                CCASSERT( false, "Invalid emitterType in config file");
                CC_BREAK_IF(true);
            }

            // life span
            _life = dictionary["particleLifespan"].asFloat();
            _lifeVar = dictionary["particleLifespanVariance"].asFloat();

            // emission Rate
            _emissionRate = _totalParticles / _life;

            //don't get the internal texture if a batchNode is used
            if (!_batchNode)
            {
                // Set a compatible default for the alpha transfer
                _opacityModifyRGB = false;

                // texture        
                // Try to get the texture from the cache
                std::string textureName = dictionary["textureFileName"].asString();
                
                size_t rPos = textureName.rfind('/');
               
                if (rPos != string::npos)
                {
                    string textureDir = textureName.substr(0, rPos + 1);
                    
                    if (!dirname.empty() && textureDir != dirname)
                    {
                        textureName = textureName.substr(rPos+1);
                        textureName = dirname + textureName;
                    }
                }
                else if (!dirname.empty() && !textureName.empty())
                {
                	textureName = dirname + textureName;
                }
                
                Texture2D *tex = nullptr;
                
                if (textureName.length() > 0)
                {
                    // set not pop-up message box when load image failed
                    bool notify = FileUtils::getInstance()->isPopupNotify();
                    FileUtils::getInstance()->setPopupNotify(false);
                    tex = Director::getInstance()->getTextureCache()->addImage(textureName);
                    // reset the value of UIImage notify
                    FileUtils::getInstance()->setPopupNotify(notify);
                }
                
                if (tex)
                {
                    setTexture(tex);
                }
                else
                {                        
                    std::string textureData = dictionary["textureImageData"].asString();
                    CCASSERT(!textureData.empty(), "");
                    
                    auto dataLen = textureData.size();
                    if (dataLen != 0)
                    {
                        // if it fails, try to get it from the base64-gzipped data    
                        int decodeLen = base64Decode((unsigned char*)textureData.c_str(), (unsigned int)dataLen, &buffer);
                        CCASSERT( buffer != nullptr, "CCParticleSystem: error decoding textureImageData");
                        CC_BREAK_IF(!buffer);
                        
                        ssize_t deflatedLen = ZipUtils::inflateMemory(buffer, decodeLen, &deflated);
                        CCASSERT( deflated != nullptr, "CCParticleSystem: error ungzipping textureImageData");
                        CC_BREAK_IF(!deflated);
                        
                        // For android, we should retain it in VolatileTexture::addImage which invoked in Director::getInstance()->getTextureCache()->addUIImage()
                        image = new Image();
                        bool isOK = image->initWithImageData(deflated, deflatedLen);
                        CCASSERT(isOK, "CCParticleSystem: error init image with Data");
                        CC_BREAK_IF(!isOK);
                        
                        setTexture(Director::getInstance()->getTextureCache()->addImage(image, textureName.c_str()));

                        image->release();
                    }
                }
                
                if (!_configName.empty())
                {
                    _yCoordFlipped = dictionary["yCoordFlipped"].asInt();
                }
                
                CCASSERT( this->_texture != nullptr, "CCParticleSystem: error loading the texture");
            }
            ret = true;
        }
    } while (0);
    free(buffer);
    free(deflated);
    return ret;
}
Example #27
0
void SpriteFrameCache::addSpriteFramesWithDictionary(ValueMap& dictionary, Texture2D* texture)
{
    /*
    Supported Zwoptex Formats:

    ZWTCoordinatesFormatOptionXMLLegacy = 0, // Flash Version
    ZWTCoordinatesFormatOptionXML1_0 = 1, // Desktop Version 0.0 - 0.4b
    ZWTCoordinatesFormatOptionXML1_1 = 2, // Desktop Version 1.0.0 - 1.0.1
    ZWTCoordinatesFormatOptionXML1_2 = 3, // Desktop Version 1.0.2+
    */

    
    ValueMap& framesDict = dictionary["frames"].asValueMap();
    int format = 0;

    // get the format
    if (dictionary.find("metadata") != dictionary.end())
    {
        ValueMap& metadataDict = dictionary["metadata"].asValueMap();
        format = metadataDict["format"].asInt();
    }

    // check the format
    CCASSERT(format >=0 && format <= 3, "format is not supported for SpriteFrameCache addSpriteFramesWithDictionary:textureFilename:");

    for (auto iter = framesDict.begin(); iter != framesDict.end(); ++iter)
    {
        ValueMap& frameDict = iter->second.asValueMap();
        std::string spriteFrameName = iter->first;
        SpriteFrame* spriteFrame = _spriteFrames.at(spriteFrameName);
        if (spriteFrame)
        {
            continue;
        }
        
        if(format == 0) 
        {
            float x = frameDict["x"].asFloat();
            float y = frameDict["y"].asFloat();
            float w = frameDict["width"].asFloat();
            float h = frameDict["height"].asFloat();
            float ox = frameDict["offsetX"].asFloat();
            float oy = frameDict["offsetY"].asFloat();
            int ow = frameDict["originalWidth"].asInt();
            int oh = frameDict["originalHeight"].asInt();
            // check ow/oh
            if(!ow || !oh)
            {
                CCLOGWARN("cocos2d: WARNING: originalWidth/Height not found on the SpriteFrame. AnchorPoint won't work as expected. Regenrate the .plist");
            }
            // abs ow/oh
            ow = abs(ow);
            oh = abs(oh);
            // create frame
            spriteFrame = SpriteFrame::createWithTexture(texture,
                                                         Rect(x, y, w, h),
                                                         false,
                                                         Vec2(ox, oy),
                                                         Size((float)ow, (float)oh)
                                                         );
        } 
        else if(format == 1 || format == 2) 
        {
            Rect frame = RectFromString(frameDict["frame"].asString());
            bool rotated = false;

            // rotation
            if (format == 2)
            {
                rotated = frameDict["rotated"].asBool();
            }

            Vec2 offset = PointFromString(frameDict["offset"].asString());
            Size sourceSize = SizeFromString(frameDict["sourceSize"].asString());

            // create frame
            spriteFrame = SpriteFrame::createWithTexture(texture,
                                                         frame,
                                                         rotated,
                                                         offset,
                                                         sourceSize
                                                         );
        } 
        else if (format == 3)
        {
            // get values
            Size spriteSize = SizeFromString(frameDict["spriteSize"].asString());
            Vec2 spriteOffset = PointFromString(frameDict["spriteOffset"].asString());
            Size spriteSourceSize = SizeFromString(frameDict["spriteSourceSize"].asString());
            Rect textureRect = RectFromString(frameDict["textureRect"].asString());
            bool textureRotated = frameDict["textureRotated"].asBool();

            // get aliases
            ValueVector& aliases = frameDict["aliases"].asValueVector();

            for(const auto &value : aliases) {
                std::string oneAlias = value.asString();
                if (_spriteFramesAliases.find(oneAlias) != _spriteFramesAliases.end())
                {
                    CCLOGWARN("cocos2d: WARNING: an alias with name %s already exists", oneAlias.c_str());
                }

                _spriteFramesAliases[oneAlias] = Value(spriteFrameName);
            }
            
            // create frame
            spriteFrame = SpriteFrame::createWithTexture(texture,
                                                         Rect(textureRect.origin.x, textureRect.origin.y, spriteSize.width, spriteSize.height),
                                                         textureRotated,
                                                         spriteOffset,
                                                         spriteSourceSize);
        }

        // add sprite frame
        _spriteFrames.insert(spriteFrameName, spriteFrame);
    }
}
Example #28
0
int
TransportRegistry::load_transport_configuration(const OPENDDS_STRING& file_name,
                                                ACE_Configuration_Heap& cf)
{
  const ACE_Configuration_Section_Key &root = cf.root_section();

  // Create a vector to hold configuration information so we can populate
  // them after the transports instances are created.
  typedef std::pair<TransportConfig_rch, OPENDDS_VECTOR(OPENDDS_STRING) > ConfigInfo;
  OPENDDS_VECTOR(ConfigInfo) configInfoVec;

  // Record the transport instances created, so we can place them
  // in the implicit transport configuration for this file.
  OPENDDS_LIST(TransportInst_rch) instances;

  ACE_TString sect_name;

  for (int index = 0;
       cf.enumerate_sections(root, index, sect_name) == 0;
       ++index) {
    if (ACE_OS::strcmp(sect_name.c_str(), TRANSPORT_SECTION_NAME) == 0) {
      // found the [transport/*] section, now iterate through subsections...
      ACE_Configuration_Section_Key sect;
      if (cf.open_section(root, sect_name.c_str(), 0, sect) != 0) {
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("(%P|%t) TransportRegistry::load_transport_configuration: ")
                          ACE_TEXT("failed to open section %s\n"),
                          sect_name.c_str()),
                         -1);
      } else {
        // Ensure there are no properties in this section
        ValueMap vm;
        if (pullValues(cf, sect, vm) > 0) {
          // There are values inside [transport]
          ACE_ERROR_RETURN((LM_ERROR,
                            ACE_TEXT("(%P|%t) TransportRegistry::load_transport_configuration: ")
                            ACE_TEXT("transport sections must have a section name\n"),
                            sect_name.c_str()),
                           -1);
        }
        // Process the subsections of this section (the individual transport
        // impls).
        KeyList keys;
        if (processSections( cf, sect, keys ) != 0) {
          ACE_ERROR_RETURN((LM_ERROR,
                            ACE_TEXT("(%P|%t) TransportRegistry::load_transport_configuration: ")
                            ACE_TEXT("too many nesting layers in [%s] section.\n"),
                            sect_name.c_str()),
                           -1);
        }
        for (KeyList::const_iterator it=keys.begin(); it != keys.end(); ++it) {
          OPENDDS_STRING transport_id = (*it).first;
          ACE_Configuration_Section_Key inst_sect = (*it).second;

          ValueMap values;
          if (pullValues( cf, (*it).second, values ) != 0) {
            // Get the factory_id for the transport.
            OPENDDS_STRING transport_type;
            ValueMap::const_iterator vm_it = values.find("transport_type");
            if (vm_it != values.end()) {
              transport_type = (*vm_it).second;
            } else {
              ACE_ERROR_RETURN((LM_ERROR,
                                ACE_TEXT("(%P|%t) TransportRegistry::load_transport_configuration: ")
                                ACE_TEXT("missing transport_type in [transport/%C] section.\n"),
                                transport_id.c_str()),
                               -1);
            }
            // Create the TransportInst object and load the transport
            // configuration in ACE_Configuration_Heap to the TransportInst
            // object.
            TransportInst_rch inst = this->create_inst(transport_id,
                                                       transport_type);
            if (inst == 0) {
              ACE_ERROR_RETURN((LM_ERROR,
                                ACE_TEXT("(%P|%t) TransportRegistry::load_transport_configuration: ")
                                ACE_TEXT("Unable to create transport instance in [transport/%C] section.\n"),
                                transport_id.c_str()),
                               -1);
            }
            instances.push_back(inst);
            inst->load(cf, inst_sect);
          } else {
            ACE_ERROR_RETURN((LM_ERROR,
                              ACE_TEXT("(%P|%t) TransportRegistry::load_transport_configuration: ")
                              ACE_TEXT("missing transport_type in [transport/%C] section.\n"),
                              transport_id.c_str()),
                             -1);
          }
        }
      }
    } else if (ACE_OS::strcmp(sect_name.c_str(), CONFIG_SECTION_NAME) == 0) {
      // found the [config/*] section, now iterate through subsections...
      ACE_Configuration_Section_Key sect;
      if (cf.open_section(root, sect_name.c_str(), 0, sect) != 0) {
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("(%P|%t) TransportRegistry::load_transport_configuration: ")
                          ACE_TEXT("failed to open section [%s]\n"),
                          sect_name.c_str()),
                         -1);
      } else {
        // Ensure there are no properties in this section
        ValueMap vm;
        if (pullValues(cf, sect, vm) > 0) {
          // There are values inside [config]
          ACE_ERROR_RETURN((LM_ERROR,
                            ACE_TEXT("(%P|%t) TransportRegistry::load_transport_configuration: ")
                            ACE_TEXT("config sections must have a section name\n"),
                            sect_name.c_str()),
                           -1);
        }
        // Process the subsections of this section (the individual config
        // impls).
        KeyList keys;
        if (processSections( cf, sect, keys ) != 0) {
          // Don't allow multiple layers of nesting ([config/x/y]).
          ACE_ERROR_RETURN((LM_ERROR,
                            ACE_TEXT("(%P|%t) TransportRegistry::load_transport_configuration: ")
                            ACE_TEXT("too many nesting layers in [%s] section.\n"),
                            sect_name.c_str()),
                           -1);
        }
        for (KeyList::const_iterator it=keys.begin(); it != keys.end(); ++it) {
          OPENDDS_STRING config_id = (*it).first;

          // Create a TransportConfig object.
          TransportConfig_rch config = this->create_config(config_id);
          if (config == 0) {
            ACE_ERROR_RETURN((LM_ERROR,
                              ACE_TEXT("(%P|%t) TransportRegistry::load_transport_configuration: ")
                              ACE_TEXT("Unable to create transport config in [config/%C] section.\n"),
                              config_id.c_str()),
                             -1);
          }

          ValueMap values;
          pullValues( cf, (*it).second, values );

          ConfigInfo configInfo;
          configInfo.first = config;
          for (ValueMap::const_iterator it=values.begin();
               it != values.end(); ++it) {
            OPENDDS_STRING name = (*it).first;
            if (name == "transports") {
              OPENDDS_STRING value = (*it).second;

              char delim = ',';
              size_t pos = 0;
              OPENDDS_STRING token;
              while ((pos = value.find(delim)) != OPENDDS_STRING::npos) {
                token = value.substr(0, pos);
                configInfo.second.push_back(token);
                value.erase(0, pos + 1);
              }
              configInfo.second.push_back(value);

              configInfoVec.push_back(configInfo);
            } else if (name == "swap_bytes") {
              OPENDDS_STRING value = (*it).second;
              if ((value == "1") || (value == "true")) {
                config->swap_bytes_ = true;
              } else if ((value != "0") && (value != "false")) {
                ACE_ERROR_RETURN((LM_ERROR,
                                  ACE_TEXT("(%P|%t) TransportRegistry::load_transport_configuration: ")
                                  ACE_TEXT("Illegal value for swap_bytes (%C) in [config/%C] section.\n"),
                                  value.c_str(), config_id.c_str()),
                                 -1);
              }
            } else if (name == "passive_connect_duration") {
              OPENDDS_STRING value = (*it).second;
              if (!convertToInteger(value,
                                    config->passive_connect_duration_)) {
                ACE_ERROR_RETURN((LM_ERROR,
                                  ACE_TEXT("(%P|%t) TransportRegistry::load_transport_configuration: ")
                                  ACE_TEXT("Illegal integer value for passive_connect_duration (%s) in [config/%C] section.\n"),
                                  value.c_str(), config_id.c_str()),
                                 -1);
              }
            } else {
              ACE_ERROR_RETURN((LM_ERROR,
                                ACE_TEXT("(%P|%t) TransportRegistry::load_transport_configuration: ")
                                ACE_TEXT("Unexpected entry (%C) in [config/%C] section.\n"),
                                name.c_str(), config_id.c_str()),
                               -1);
            }
          }
          if (configInfo.second.size() == 0) {
            ACE_ERROR_RETURN((LM_ERROR,
                              ACE_TEXT("(%P|%t) TransportRegistry::load_transport_configuration: ")
                              ACE_TEXT("No transport instances listed in [config/%C] section.\n"),
                              config_id.c_str()),
                             -1);
          }
        }
      }
    } else if (ACE_OS::strncmp(sect_name.c_str(), OLD_TRANSPORT_PREFIX.c_str(),
                               OLD_TRANSPORT_PREFIX.length()) == 0) {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("(%P|%t) ERROR: ")
                        ACE_TEXT("Obsolete transport configuration found (%s).\n"),
                        sect_name.c_str()),
                       -1);
    }
  }

  // Populate the configurations with instances
  for (unsigned int i = 0; i < configInfoVec.size(); ++i) {
    TransportConfig_rch config = configInfoVec[i].first;
    OPENDDS_VECTOR(OPENDDS_STRING)& insts = configInfoVec[i].second;
    for (unsigned int j = 0; j < insts.size(); ++j) {
      TransportInst_rch inst = this->get_inst(insts[j]);
      if (inst == 0) {
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("(%P|%t) TransportRegistry::load_transport_configuration: ")
                          ACE_TEXT("The inst (%C) in [config/%C] section is undefined.\n"),
                          insts[j].c_str(), config->name().c_str()),
                         -1);
      }
      config->instances_.push_back(inst);
    }
  }

  // Create and populate the default configuration for this
  // file with all the instances from this file.
  if (!instances.empty()) {
    TransportConfig_rch config = this->create_config(file_name);
    if (config == 0) {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("(%P|%t) TransportRegistry::load_transport_configuration: ")
                        ACE_TEXT("Unable to create default transport config.\n"),
                        file_name.c_str()),
                       -1);
    }
    instances.sort(predicate);
    for (OPENDDS_LIST(TransportInst_rch)::const_iterator it = instances.begin();
         it != instances.end(); ++it) {
      config->instances_.push_back(*it);
    }
  }

  return 0;
}
Example #29
0
bool evaluate(AST_Identifier &exp, ValueMap &valmap) {
    if (valmap.find(exp.name) != valmap.end()) {
        return valmap[exp.name];
    }
    return false;
}
Example #30
0
void ShapeCacher::addShapesWithDictionary(ValueMap &dictionary, PhysicsBody *body)
{
	//decode the plist file
	int format = 0;
	// get the format
	if (dictionary.find("metadata") != dictionary.end())
	{
		ValueMap& metadataDict = dictionary["metadata"].asValueMap();
		format = metadataDict["format"].asInt();
	}
	// check the format
	CCASSERT(format == 1, "format is not supported for #addShapesWithDictionary#:");

	ValueMap& bodyDict = dictionary["bodies"].asValueMap();

	for (auto iter = bodyDict.begin(); iter != bodyDict.end(); ++iter)
	{
		ValueMap& dataDict = iter->second.asValueMap();

		/****************not used yet!***********************/
		//set anchorpoint	
		//Point anchorPoint = PointFromString(dataDict["anchorpoint"].asString());
	
		ValueVector& fixtureVector = dataDict["fixtures"].asValueVector();

		for (auto iter = fixtureVector.begin(); iter != fixtureVector.end(); ++iter)
		{
			ValueMap& fixtureDict =(ValueMap&)(*iter).asValueMap();

			/****************not used yet!***********************/

			/* //body->setCategoryBitmask(fixtureDict["filter_categoryBits"].asInt);
			/* //body->setCollisionBitmask(fixtureDict["filter_maskBits"].asInt);
			/* //body->setGroup(fixtureDict["filter_groupIndex"].asInt);

			/* //float friction    = fixtureDict["friction"].asFloat;
			/* //float density     = fixtureDict["density"].asFloat;
			/* //float restitution = fixtureDict["restitution"].asFloat;
			/* //int   isSensor    = fixtureDict["isSensor"].asInt;
			/* //std::string userdata = fixtureDict["userdataCbValue"].asString;
			/* 
			/* //std::string fixtureType = fixtureDict["fixture_type"].asString();
			/* 
			/* if (fixtureType == "POLYGON") 
			{*/
			/****************not used yet!***********************/
			ValueVector& polygonsVector = (fixtureDict["polygons"].asValueVector());

			for (auto iter = polygonsVector.begin(); iter != polygonsVector.end(); ++iter) 
			{
				int vertexNum = (*iter).asValueVector().size();;
				ValueVector polygonArray = (*iter).asValueVector();
				Point *polyVertex = new Point[vertexNum];
				int i = 0;
				for (auto piter = polygonArray.begin(); piter != polygonArray.end(), i < vertexNum; ++piter ,i++)
				{
					Point vertex = PointFromString((*piter).asString());
					polyVertex[i] = vertex;
				}
				body->addShape(PhysicsShapePolygon::create(polyVertex, vertexNum));
				CC_SAFE_DELETE_ARRAY(polyVertex);
			}

		}
		//	else if (fixtureType == "CIRCLE") 
		//	{

		//		continue;
		//		//ObjectDict *circleData = (ObjectDict *)fixtureData->objectForKey("circle");

		//		//b2CircleShape *circleShape = new b2CircleShape();

		//		//circleShape->m_radius = static_cast<CCString *>(circleData->objectForKey("radius"))->toFloat() / ptmRatio;
		//		//CCPoint p = CCPointFromString(static_cast<CCString *>(circleData->objectForKey("position"))->toStdString().c_str());
		//		//circleShape->m_p = b2Vec2(p.x / ptmRatio, p.y / ptmRatio);
		//		//fix->fixture.shape = circleShape;

		//		//// create a list
		//		//*nextFixtureDef = fix;
		//		//nextFixtureDef = &(fix->next);

		//	}
		//	else 
		//	{
		//		CCAssert(0, "Unknown fixtureType");
		//	}
		//}
	}
}