int YARPFoBDeviceDriver::open (void *res)
{

	// gather system resources and parameters
	FoBResources& d = RES(system_resources);
	FoBOpenParameters *param = (FoBOpenParameters*) res;

	d.groupID = param->nGroupID;

	// Open the device Driver
	if ( ! birdRS232WakeUp(d.groupID, d.standalone, d.nDevices,
						   &(param->comPort),param->baudRate,param->timeOut,param->timeOut) )
		return YARP_FAIL;
	
	// set measurement rate
	BIRDSYSTEMCONFIG birdSysConfig;
	if ( ! birdGetSystemConfig(d.groupID,&birdSysConfig) )
		return YARP_FAIL;
	birdSysConfig.dMeasurementRate = param->measurementRate;
	if ( ! birdSetSystemConfig(d.groupID,&birdSysConfig) )
		return YARP_FAIL;

	// set transmitter operation mode
	BYTE pbuffer[3] = { 'P', 18, param->transOpMode };
	if ( ! birdRS232SendCommand(d.groupID, 0, (void*)pbuffer, 3) )
		return YARP_FAIL;

	// gather scaling; set connected flag to true
	BIRDDEVICECONFIG birdDevConfig;
	if ( ! birdGetDeviceConfig(d.groupID,0,&birdDevConfig) )
		return YARP_FAIL;
	d.posScaling = birdDevConfig.wScaling;
	d.connected = true;

	// ok, bail out
	return YARP_OK;	

}
Exemple #2
0
RES ResourceFormatLoaderBitMap::load(const String &p_path, const String& p_original_path, Error *r_error) {

	if (r_error)
		*r_error=ERR_FILE_CANT_OPEN;

	BitMap* ptr = memnew(BitMap);
	Ref<BitMap> bitmap( ptr );


	Image image;

	Error err = ImageLoader::load_image(p_path,&image);

	ERR_EXPLAIN("Failed loading image for BitMap: "+p_path);
	ERR_FAIL_COND_V(err, RES());

	bitmap->create_from_image_alpha(image);
	if (r_error)
		*r_error=OK;

	return bitmap;

}
		ParticleModernArtSystem() : wyQuadParticleSystem(1000){
			// duration
	        setDuration(PARTICLE_DURATION_INFINITY);

			// Gravity mode: radial
	        setRadialAccelerationVariance(70, 10);

			// Gravity mode: tangential
	        setTangentialAccelerationVariance(80, 0);

			// Gravity mode: speed of particles
	        setSpeedVariance(50, 10);

			// angle
	        setDirectionAngleVariance(0, 360);

			// life of particles
	        setLifeVariance(2.0f, 0.3f);

			// emits per frame
	        setEmissionRate(getMaxParticles() / getLife());

	        // color of particles
	        setStartColorVariance(0.5f, 0.5f, 0.5f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f);
	        setEndColorVariance(0.1f, 0.1f, 0.1f, 0.2f, 0.1f, 0.1f, 0.1f, 0.2f);

			// size, in pixels
	        setStartSizeVariance(1.0f, 1.0f);
	        setEndSizeVariance(32.0f, 8.0f);

	        //set texture
	        setTexture(wyTexture2D::makePNG(RES("R.drawable.fire")));

	    	// additive
	    	setBlendAdditive(false);
		}
RES ResourceFormatImporter::load(const String &p_path, const String &p_original_path, Error *r_error) {

	PathAndType pat;
	Error err = _get_path_and_type(p_path, pat);

	if (err != OK) {

		if (r_error)
			*r_error = err;

		return RES();
	}

	RES res = ResourceLoader::_load(pat.path, p_path, pat.type, false, r_error);

#ifdef TOOLS_ENABLED
	if (res.is_valid()) {
		res->set_import_last_modified_time(res->get_last_modified_time()); //pass this, if used
		res->set_import_path(pat.path);
	}
#endif

	return res;
}
		ParticleBigFlowerSystem() : wyQuadParticleSystem(50){
	    	// duration
	        setDuration(PARTICLE_DURATION_INFINITY);

	    	// Gravity Mode: speed of particles
	        setSpeedVariance(160, 20);

	    	// Gravity Mode: radial
	        setRadialAccelerationVariance(-120, 0);

	    	// Gravity Mode: tagential
	        setTangentialAccelerationVariance(30, 0);

	    	// angle
	        setDirectionAngleVariance(90, 360);

	    	// life of particles
	        setLifeVariance(4, 1);

	        // color of particles
	        setStartColorVariance(0.5f, 0.5f, 0.5f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f);
	        setEndColorVariance(0.1f, 0.1f, 0.1f, 0.2f, 0.1f, 0.1f, 0.1f, 0.2f);

	    	// size, in pixels
	        setStartSizeVariance(80.0f, 40.0f);
	        setEndSizeVariance(PARTICLE_START_SIZE_EQUAL_TO_END_SIZE, 0);

	    	// emits per second
	        setEmissionRate(getMaxParticles() / getLife());

	        //set texture
	        setTexture(wyTexture2D::makePNG(RES("R.drawable.stars")));

	    	// additive
	    	setBlendAdditive(true);
		}
		ParticleFireworkSystem() : wyQuadParticleSystem(300){
			// duration
			setDuration(PARTICLE_DURATION_INFINITY);

			// gravity
			setParticleGravity(0, -90);

			// angle
			setDirectionAngleVariance(90, 20);

			// speed of particles
			setSpeedVariance(180, 50);

			// life of particles
			setLifeVariance(3.5f, 1.0f);

			// emits per frame
			setEmissionRate(getMaxParticles() / getLife());

			// color of particles
			setStartColorVariance(0.5f, 0.5f, 0.5f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f);
			setEndColorVariance(0.1f, 0.1f, 0.1f, 0.2f, 0.1f, 0.1f, 0.1f, 0.2f);

			// size, in pixels
			setStartSizeVariance(8.0f, 2.0f);
			setEndSizeVariance(PARTICLE_START_SIZE_EQUAL_TO_END_SIZE, 0);

	    	// emits per second
	        setEmissionRate(getMaxParticles() / getLife());

	        //set texture
	        setTexture(wyTexture2D::makePNG(RES("R.drawable.fire")));

	    	// additive
	    	setBlendAdditive(false);
		}
 wyEaseTestLayer(){
     m_Sprite = wySprite::make(wyTexture2D::makePNG(RES("R.drawable.grossini")));
     m_Sprite->retain();
     addChildLocked(m_Sprite);
     m_Sprite->setPosition(60, wyDevice::winHeight/ 2);
 };
RES ResourcePreloader::get_resource(const StringName& p_name) const {

	ERR_FAIL_COND_V(!resources.has(p_name),RES());
	return resources[p_name];
}
Exemple #9
0
    bool MainMenu::init()
    {
        if(!cocos2d::Scene::init())
            return false;
        
        auto sz = cocos2d::Director::getInstance()->getVisibleSize();
        auto origin = cocos2d::Director::getInstance()->getVisibleOrigin();
        
#ifdef RESET_GAMEPLAY
        cocos2d::UserDefault::getInstance()->setIntegerForKey("WizardWay_level",0); //USERDATA
#endif
#ifdef ALL_AVAILABLE
        cocos2d::UserDefault::getInstance()->setIntegerForKey("WizardWay_level",10); //USERDATA
#endif
        loadSpriteSheetFromXml("uipack_rpg_sheet.png", "uipack_rpg_sheet.xml");
        
		auto* backgroundImage = cocos2d::Sprite::create(RES("menu","Sphash.jpg"));
		float scaleFactorH = sz.height / backgroundImage->getContentSize().height;
        float scaleFactorW = sz.width / backgroundImage->getContentSize().width;
        
        auto* layout = cocos2d::ui::Layout::create();
        layout->setBackGroundImage(RES("menu","Sphash.jpg"));
        layout->cocos2d::Node::setPosition(sz.width/2+origin.x, sz.height/2+origin.y);
        layout->setScale(scaleFactorW, scaleFactorH);
        
        auto* box = cocos2d::ui::RelativeBox::create({220,180});
        box->setAnchorPoint({0.5, 0.5});
        box->setBackGroundImage("panel_brown.png", cocos2d::ui::TextureResType::PLIST);
        box->setBackGroundImageScale9Enabled(true);
        layout->addChild(box);
        
        auto buttonNewGame = cocos2d::ui::Button::create("buttonLong_beige.png", "buttonLong_beige_pressed.png", "buttonLong_blue.png", cocos2d::ui::TextureResType::PLIST);
        buttonNewGame->setTitleText("Play MagicWars");
        buttonNewGame->addTouchEventListener([&](Ref* sender, cocos2d::ui::Widget::TouchEventType type){
            if(type==cocos2d::ui::Widget::TouchEventType::ENDED)
            {
                auto scene = CampaignSelect::create();
                cocos2d::Director::getInstance()->replaceScene(cocos2d::TransitionFade::create(1.5, scene));
            }
        });
        buttonNewGame->setPosition({0,50});
        layout->addChild(buttonNewGame);
        
        auto buttonSandbox = cocos2d::ui::Button::create("buttonLong_beige.png", "buttonLong_beige_pressed.png", "buttonLong_blue.png", cocos2d::ui::TextureResType::PLIST);
        buttonSandbox->setTitleText("Sandbox");
        buttonSandbox->addTouchEventListener([&](Ref* sender, cocos2d::ui::Widget::TouchEventType type){
            if(type==cocos2d::ui::Widget::TouchEventType::ENDED)
            {
                CampaignReader::Mission mission{"Песочница", "map_L_frument.txt", "map_sandbox_triggers.txt", "mapRule_frument.txt", "", "", {}, 0, 0};
                auto scene = HelloWorld::createScene(mission);
                cocos2d::Director::getInstance()->replaceScene(cocos2d::TransitionFade::create(1, scene));
            }
        });
#ifndef SANDBOX
        buttonSandbox->setEnabled(false);
#endif
        buttonSandbox->setPosition({0,0});
        layout->addChild(buttonSandbox);
        
        addChild(layout);
        
        return true;
    }
Exemple #10
0
    bool CampaignSelect::init()
    {
        if(!cocos2d::Scene::init())
            return false;
        
        cocos2d::UserDefault::getInstance()->setBoolForKey("WizardWay", true); //USERDATA

        auto sz = cocos2d::Director::getInstance()->getVisibleSize();
        auto origin = cocos2d::Director::getInstance()->getVisibleOrigin();
        
        auto* background = cocos2d::Layer::create();
        
        auto* backgroundImage = cocos2d::Sprite::create(RES("menu","background1.jpg"));
        float scaleFactorH = sz.height / backgroundImage->getContentSize().height;
        float scaleFactorW = sz.width / backgroundImage->getContentSize().width;
        backgroundImage->setScale(scaleFactorW, scaleFactorH);
        backgroundImage->setAnchorPoint(cocos2d::Vec2::ZERO);
        backgroundImage->setPosition(origin);
        background->addChild(backgroundImage);
        
        auto* menu = cocos2d::Menu::create();
        std::vector<cocos2d::Vec2> positions{ {-0.2f*sz.width, 0.2f*sz.height}, {0.2f*sz.width, 0.2f*sz.height}, {-0.2f*sz.width, -0.2f*sz.height}, {0.2f*sz.width, -0.2f*sz.height} };
        std::vector<bool> enable;
        std::vector<std::string> campaignNames{"WizardWay", "CorpseCollector", "KingHeritage", "EternalSentry"};
        std::vector<std::string> labels{"Путь волшебника","Коллекционер мертвецов","Наследие короля","Вечный часовой"};
        
        for(auto i : campaignNames)
            enable.push_back(cocos2d::UserDefault::getInstance()->getBoolForKey(i.c_str(), false));
        
        for( int i : {1, 2, 3, 4})
        {
            std::string name = "camp"+std::to_string(i);
            auto* campaign_buton = cocos2d::MenuItemImage::create(RES("menu", name+".png"), RES("menu", name+".png"), RES("menu", name+"_d.png"), [i, campaignNames](cocos2d::Ref* pSender)
                                                          {
                                                              cocos2d::UserDefault::getInstance()->setStringForKey("CurrentCampaignName", campaignNames[i-1]);
                                                              if(cocos2d::UserDefault::getInstance()->getIntegerForKey((campaignNames[i-1]+"_level").c_str(), 0))
                                                              {
                                                                  auto scene = MagicWars_NS::TravelScene::create();
                                                                  cocos2d::Director::getInstance()->replaceScene(cocos2d::TransitionFade::create(1, scene));
                                                              }
                                                              else
                                                              {
                                                                  cocos2d::Director::getInstance()->getEventDispatcher()->removeAllEventListeners();
                                                                  auto scene = MissionBrief::create(campaignNames[i-1], 0);
                                                                  cocos2d::Director::getInstance()->replaceScene(cocos2d::TransitionFade::create(3, scene));
                                                              }
                                                          });
            float scale = std::min(scaleFactorH, scaleFactorW) * 0.65;
            campaign_buton->setPosition(positions[i-1]);
            campaign_buton->setEnabled(enable[i-1]);
            campaign_buton->setScale(scale);

            auto* frame = cocos2d::Sprite::create(RES("menu", "frame.png"));
            frame->setPosition(cocos2d::Vec2{campaign_buton->getContentSize().width/2,campaign_buton->getContentSize().height/2});
            campaign_buton->addChild(frame);
            
            auto label = cocos2d::Label::createWithTTF(labels[i-1], RES("fonts","Washington.ttf"), 40);
            label->setPosition(cocos2d::Vec2{campaign_buton->getContentSize().width/2,0});
            campaign_buton->addChild(label);
            
            menu->addChild(campaign_buton);
        }
        
        background->addChild(menu);
        
        addChild(background);
        
        return true;
    }
Exemple #11
0
RES ResourceLoader::load(const String &p_path, const String &p_type_hint, bool p_no_cache, Error *r_error) {

	if (r_error)
		*r_error = ERR_CANT_OPEN;

	String local_path;
	if (p_path.is_rel_path())
		local_path = "res://" + p_path;
	else
		local_path = ProjectSettings::get_singleton()->localize_path(p_path);

	if (!p_no_cache) {

		{
			bool success = _add_to_loading_map(local_path);
			if (!success) {
				ERR_EXPLAIN("Resource: '" + local_path + "' is already being loaded. Cyclic reference?");
				ERR_FAIL_V(RES());
			}
		}

		//lock first if possible
		if (ResourceCache::lock) {
			ResourceCache::lock->read_lock();
		}

		//get ptr
		Resource **rptr = ResourceCache::resources.getptr(local_path);

		if (rptr) {
			RES res(*rptr);
			//it is possible this resource was just freed in a thread. If so, this referencing will not work and resource is considered not cached
			if (res.is_valid()) {
				//referencing is fine
				if (r_error)
					*r_error = OK;
				if (ResourceCache::lock) {
					ResourceCache::lock->read_unlock();
				}
				_remove_from_loading_map(local_path);
				return res;
			}
		}
		if (ResourceCache::lock) {
			ResourceCache::lock->read_unlock();
		}
	}

	bool xl_remapped = false;
	String path = _path_remap(local_path, &xl_remapped);

	if (path == "") {
		if (!p_no_cache) {
			_remove_from_loading_map(local_path);
		}
		ERR_EXPLAIN("Remapping '" + local_path + "'failed.");
		ERR_FAIL_V(RES());
	}

	print_verbose("Loading resource: " + path);
	RES res = _load(path, local_path, p_type_hint, p_no_cache, r_error);

	if (res.is_null()) {
		if (!p_no_cache) {
			_remove_from_loading_map(local_path);
		}
		return RES();
	}
	if (!p_no_cache)
		res->set_path(local_path);

	if (xl_remapped)
		res->set_as_translation_remapped(true);

#ifdef TOOLS_ENABLED

	res->set_edited(false);
	if (timestamp_on_load) {
		uint64_t mt = FileAccess::get_modified_time(path);
		//printf("mt %s: %lli\n",remapped_path.utf8().get_data(),mt);
		res->set_last_modified_time(mt);
	}
#endif

	if (!p_no_cache) {
		_remove_from_loading_map(local_path);
	}

	if (_loaded_callback) {
		_loaded_callback(res, p_path);
	}

	return res;
}
Exemple #12
0
int main(int argc,char * argv[])
{
	int i = 0, j = 0, rc;
	MDB_env *env;
	MDB_dbi dbi;
	MDB_val key, data;
	MDB_txn *txn;
	MDB_stat mst;
	MDB_cursor *cursor, *cur2;
	MDB_cursor_op op;
	int count;
	int *values;
	char sval[32] = "";

	srandom(time(NULL));

	    count = (random()%384) + 64;
	    values = (int *)malloc(count*sizeof(int));

	    for(i = 0;i<count;i++) {
			values[i] = random()%1024;
	    }
    
		E(mdb_env_create(&env));
		E(mdb_env_set_mapsize(env, 10485760));
		E(mdb_env_open(env, "./testdb", MDB_FIXEDMAP /*|MDB_NOSYNC*/, 0664));
		E(mdb_txn_begin(env, NULL, 0, &txn));
		E(mdb_open(txn, NULL, 0, &dbi));
   
		key.mv_size = sizeof(int);
		key.mv_data = sval;
		data.mv_size = sizeof(sval);
		data.mv_data = sval;

		printf("Adding %d values\n", count);
	    for (i=0;i<count;i++) {	
			sprintf(sval, "%03x %d foo bar", values[i], values[i]);
			if (RES(MDB_KEYEXIST, mdb_put(txn, dbi, &key, &data, MDB_NOOVERWRITE))) {
				j++;
				data.mv_size = sizeof(sval);
				data.mv_data = sval;
			}
	    }
		if (j) printf("%d duplicates skipped\n", j);
		E(mdb_txn_commit(txn));
		E(mdb_env_stat(env, &mst));

		E(mdb_txn_begin(env, NULL, 1, &txn));
		E(mdb_cursor_open(txn, dbi, &cursor));
		while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) {
			printf("key: %p %.*s, data: %p %.*s\n",
				key.mv_data,  (int) key.mv_size,  (char *) key.mv_data,
				data.mv_data, (int) data.mv_size, (char *) data.mv_data);
		}
		CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
		mdb_cursor_close(cursor);
		mdb_txn_abort(txn);

		j=0;
		key.mv_data = sval;
	    for (i= count - 1; i > -1; i-= (random()%5)) {	
			j++;
			txn=NULL;
			E(mdb_txn_begin(env, NULL, 0, &txn));
			sprintf(sval, "%03x ", values[i]);
			if (RES(MDB_NOTFOUND, mdb_del(txn, dbi, &key, NULL))) {
				j--;
				mdb_txn_abort(txn);
			} else {
				E(mdb_txn_commit(txn));
			}
	    }
	    free(values);
		printf("Deleted %d values\n", j);

		E(mdb_env_stat(env, &mst));
		E(mdb_txn_begin(env, NULL, 1, &txn));
		E(mdb_cursor_open(txn, dbi, &cursor));
		printf("Cursor next\n");
		while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) {
			printf("key: %.*s, data: %.*s\n",
				(int) key.mv_size,  (char *) key.mv_data,
				(int) data.mv_size, (char *) data.mv_data);
		}
		CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
		printf("Cursor last\n");
		E(mdb_cursor_get(cursor, &key, &data, MDB_LAST));
		printf("key: %.*s, data: %.*s\n",
			(int) key.mv_size,  (char *) key.mv_data,
			(int) data.mv_size, (char *) data.mv_data);
		printf("Cursor prev\n");
		while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_PREV)) == 0) {
			printf("key: %.*s, data: %.*s\n",
				(int) key.mv_size,  (char *) key.mv_data,
				(int) data.mv_size, (char *) data.mv_data);
		}
		CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
		printf("Cursor last/prev\n");
		E(mdb_cursor_get(cursor, &key, &data, MDB_LAST));
			printf("key: %.*s, data: %.*s\n",
				(int) key.mv_size,  (char *) key.mv_data,
				(int) data.mv_size, (char *) data.mv_data);
		E(mdb_cursor_get(cursor, &key, &data, MDB_PREV));
			printf("key: %.*s, data: %.*s\n",
				(int) key.mv_size,  (char *) key.mv_data,
				(int) data.mv_size, (char *) data.mv_data);

		mdb_txn_abort(txn);

		printf("Deleting with cursor\n");
		E(mdb_txn_begin(env, NULL, 0, &txn));
		E(mdb_cursor_open(txn, dbi, &cur2));
		for (i=0; i<50; i++) {
			if (RES(MDB_NOTFOUND, mdb_cursor_get(cur2, &key, &data, MDB_NEXT)))
				break;
			printf("key: %p %.*s, data: %p %.*s\n",
				key.mv_data,  (int) key.mv_size,  (char *) key.mv_data,
				data.mv_data, (int) data.mv_size, (char *) data.mv_data);
			E(mdb_del(txn, dbi, &key, NULL));
		}

		printf("Restarting cursor in txn\n");
		for (op=MDB_FIRST, i=0; i<=32; op=MDB_NEXT, i++) {
			if (RES(MDB_NOTFOUND, mdb_cursor_get(cur2, &key, &data, op)))
				break;
			printf("key: %p %.*s, data: %p %.*s\n",
				key.mv_data,  (int) key.mv_size,  (char *) key.mv_data,
				data.mv_data, (int) data.mv_size, (char *) data.mv_data);
		}
		mdb_cursor_close(cur2);
		E(mdb_txn_commit(txn));

		printf("Restarting cursor outside txn\n");
		E(mdb_txn_begin(env, NULL, 0, &txn));
		E(mdb_cursor_open(txn, dbi, &cursor));
		for (op=MDB_FIRST, i=0; i<=32; op=MDB_NEXT, i++) {
			if (RES(MDB_NOTFOUND, mdb_cursor_get(cursor, &key, &data, op)))
				break;
			printf("key: %p %.*s, data: %p %.*s\n",
				key.mv_data,  (int) key.mv_size,  (char *) key.mv_data,
				data.mv_data, (int) data.mv_size, (char *) data.mv_data);
		}
		mdb_cursor_close(cursor);
		mdb_close(env, dbi);

		mdb_txn_abort(txn);
		mdb_env_close(env);

	return 0;
}
Exemple #13
0
RES ResourceFormatLoaderImage::load(const String &p_path, const String &p_original_path, Error *r_error) {

	FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
	if (!f) {
		if (r_error) {
			*r_error = ERR_CANT_OPEN;
		}
		return RES();
	}

	uint8_t header[4] = { 0, 0, 0, 0 };
	f->get_buffer(header, 4);

	bool unrecognized = header[0] != 'G' || header[1] != 'D' || header[2] != 'I' || header[3] != 'M';
	if (unrecognized) {
		memdelete(f);
		if (r_error) {
			*r_error = ERR_FILE_UNRECOGNIZED;
		}
		ERR_FAIL_V(RES());
	}

	String extension = f->get_pascal_string();

	int idx = -1;

	for (int i = 0; i < ImageLoader::loader.size(); i++) {
		if (ImageLoader::loader[i]->recognize(extension)) {
			idx = i;
			break;
		}
	}

	if (idx == -1) {
		memdelete(f);
		if (r_error) {
			*r_error = ERR_FILE_UNRECOGNIZED;
		}
		ERR_FAIL_V(RES());
	}

	Ref<Image> image;
	image.instance();

	Error err = ImageLoader::loader[idx]->load_image(image, f, false, 1.0);

	memdelete(f);

	if (err != OK) {
		if (r_error) {
			*r_error = err;
		}
		return RES();
	}

	if (r_error) {
		*r_error = OK;
	}

	return image;
}
RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error, const String &p_path) {

    String l = f->get_line();

    enum Status {

        STATUS_NONE,
        STATUS_READING_ID,
        STATUS_READING_STRING,
    };

    Status status=STATUS_NONE;

    String msg_id;
    String msg_str;
    String config;
    int msg_line=0;

    if (r_error)
        *r_error=ERR_FILE_CORRUPT;

    Ref<Translation> translation = Ref<Translation>( memnew( Translation ));
    int line = 1;

    while(true) {

        String l = f->get_line();

        if (f->eof_reached()) {

            if ( status == STATUS_READING_STRING) {

                if (msg_id!="")
                    translation->add_message(msg_id,msg_str);
                else if (config=="")
                    config=msg_str;
                break;

            } else if ( status==STATUS_NONE)
                break;

            memdelete(f);
            ERR_EXPLAIN(p_path+":"+itos(line)+" Unexpected EOF while reading 'msgid' at file: ");
            ERR_FAIL_V(RES());
        }

        l=l.strip_edges();

        if (l.begins_with("msgid")) {

            if (status==STATUS_READING_ID) {

                memdelete(f);
                ERR_EXPLAIN(p_path+":"+itos(line)+" Unexpected 'msgid', was expecting 'msgstr' while parsing: ");
                ERR_FAIL_V(RES());
            }

            if (msg_id!="")
                translation->add_message(msg_id,msg_str);
            else if (config=="")
                config=msg_str;

            l=l.substr(5,l.length()).strip_edges();
            status=STATUS_READING_ID;
            msg_id="";
            msg_str="";
            msg_line=line;
        }

        if (l.begins_with("msgstr")) {

            if (status!=STATUS_READING_ID) {

                memdelete(f);
                ERR_EXPLAIN(p_path+":"+itos(line)+" Unexpected 'msgstr', was expecting 'msgid' while parsing: ");
                ERR_FAIL_V(RES());
            }

            l=l.substr(6,l.length()).strip_edges();
            status=STATUS_READING_STRING;
            msg_line=line;
        }

        if (l=="" || l.begins_with("#")) {
            line++;
            continue; //nothing to read or comment
        }

        if (!l.begins_with("\"") || status==STATUS_NONE) {
            //not a string? failure!
            ERR_EXPLAIN(p_path+":"+itos(line)+" Invalid line '"+l+"' while parsing: ");
            ERR_FAIL_V(RES());

        }

        l=l.substr(1,l.length());
        //find final quote
        int end_pos=-1;
        for(int i=0; i<l.length(); i++) {

            if (l[i]=='"' && (i==0 || l[i-1]!='\\')) {
                end_pos=i;
                break;
            }
        }

        if (end_pos==-1) {
            ERR_EXPLAIN(p_path+":"+itos(line)+" Expected '\"' at end of message while parsing file: ");
            ERR_FAIL_V(RES());
        }

        l=l.substr(0,end_pos);
        l=l.c_unescape();


        if (status==STATUS_READING_ID)
            msg_id+=l;
        else
            msg_str+=l;

        line++;
    }


    f->close();
    memdelete(f);

    if (config=="") {
        ERR_EXPLAIN("No config found in file: "+p_path);
        ERR_FAIL_V(RES());
    }

    Vector<String> configs = config.split("\n");
    for(int i=0; i<configs.size(); i++) {

        String c = configs[i].strip_edges();
        int p = c.find(":");
        if (p==-1)
            continue;
        String prop = c.substr(0,p).strip_edges();
        String value = c.substr(p+1,c.length()).strip_edges();

        if (prop=="X-Language") {
            translation->set_locale(value);
        }
    }

    if (r_error)
        *r_error=OK;

    return translation;
}
Exemple #15
0
RES ResourceLoader::load(const String &p_path, const String& p_type_hint, bool p_no_cache, Error *r_error) {

	if (r_error)
		*r_error=ERR_CANT_OPEN;

	String local_path;
	if (p_path.is_rel_path())
		local_path="res://"+p_path;
	else
		local_path = Globals::get_singleton()->localize_path(p_path);

	local_path=find_complete_path(local_path,p_type_hint);
	ERR_FAIL_COND_V(local_path=="",RES());

	if (!p_no_cache && ResourceCache::has(local_path)) {

		if (OS::get_singleton()->is_stdout_verbose())
			print_line("load resource: "+local_path+" (cached)");

		return RES( ResourceCache::get(local_path ) );
	}

	String remapped_path = PathRemap::get_singleton()->get_remap(local_path);

	if (OS::get_singleton()->is_stdout_verbose())
		print_line("load resource: "+remapped_path);

	String extension=remapped_path.extension();
	bool found=false;

	for (int i=0;i<loader_count;i++) {

		if (!loader[i]->recognize(extension))
			continue;
		if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
			continue;
		found=true;
		RES res = loader[i]->load(remapped_path,local_path,r_error);
		if (res.is_null())
			continue;
		if (!p_no_cache)
			res->set_path(local_path);
#ifdef TOOLS_ENABLED

		res->set_edited(false);
		if (timestamp_on_load) {
			uint64_t mt = FileAccess::get_modified_time(remapped_path);
			//printf("mt %s: %lli\n",remapped_path.utf8().get_data(),mt);
			res->set_last_modified_time(mt);
		}
#endif

		return res;
	}

	if (found) {
		ERR_EXPLAIN("Failed loading resource: "+p_path);
	} else {
		ERR_EXPLAIN("No loader found for resource: "+p_path);
	}
	ERR_FAIL_V(RES());
	return RES();
}
Exemple #16
0
double Potential_JS::Lzmax(double E,double RC){
	RE_st RES(E,this);int status;
	minimiser1D min(&Lzmax_fn,RC/2.,SMALL,RC,1e-4,0.,&status,&RES);
    double r = min.minimise(100);
    return -Lzmax_fn(r,&RES);
}
Exemple #17
0
RES ResourceLoader::load(const String &p_path, const String &p_type_hint, bool p_no_cache, Error *r_error) {

	if (r_error)
		*r_error = ERR_CANT_OPEN;

	String local_path;
	if (p_path.is_rel_path())
		local_path = "res://" + p_path;
	else
		local_path = ProjectSettings::get_singleton()->localize_path(p_path);

	bool xl_remapped = false;
	String path = _path_remap(local_path, &xl_remapped);

	ERR_FAIL_COND_V(path == "", RES());

	if (!p_no_cache && ResourceCache::has(path)) {

		if (OS::get_singleton()->is_stdout_verbose())
			print_line("load resource: " + path + " (cached)");

		return RES(ResourceCache::get(path));
	}

	if (OS::get_singleton()->is_stdout_verbose())
		print_line("load resource: " + path);
	bool found = false;

	// Try all loaders and pick the first match for the type hint
	for (int i = 0; i < loader_count; i++) {

		if (!loader[i]->recognize_path(path, p_type_hint)) {
			continue;
		}
		found = true;
		RES res = loader[i]->load(path, path, r_error);
		if (res.is_null()) {
			continue;
		}
		if (!p_no_cache)
			res->set_path(local_path);

		if (xl_remapped)
			res->set_as_translation_remapped(true);

#ifdef TOOLS_ENABLED

		res->set_edited(false);
		if (timestamp_on_load) {
			uint64_t mt = FileAccess::get_modified_time(path);
			//printf("mt %s: %lli\n",remapped_path.utf8().get_data(),mt);
			res->set_last_modified_time(mt);
		}
#endif

		return res;
	}

	if (found) {
		ERR_EXPLAIN("Failed loading resource: " + path);
	} else {
		ERR_EXPLAIN("No loader found for resource: " + path);
	}
	ERR_FAIL_V(RES());
	return RES();
}
Exemple #18
0
int main(int argc,char * argv[])
{
	int i = 0, j = 0, rc;
	MDB_env *env;
	MDB_dbi dbi;
	MDB_val key, data;
	MDB_txn *txn;
	MDB_stat mst;
	MDB_cursor *cursor;
	int count;
	int *values;
	char sval[32] = "";
	int env_oflags;
	struct stat db_stat, exe_stat;

	(void) argc;
	(void) argv;
	srand(time(NULL));

	count = (rand()%384) + 64;
	values = (int *)malloc(count*sizeof(int));

	for(i = 0;i<count;i++) {
		values[i] = rand()%1024;
	}

	E(mdb_env_create(&env));
	E(mdb_env_set_maxreaders(env, 1));
	E(mdb_env_set_mapsize(env, 10485760));
	E(mdb_env_set_maxdbs(env, 4));

	E(stat("/proc/self/exe", &exe_stat)?errno:0);
	E(stat(DBPATH "/.", &db_stat)?errno:0);
	env_oflags = MDB_FIXEDMAP | MDB_NOSYNC;
	if (major(db_stat.st_dev) != major(exe_stat.st_dev)) {
		/* LY: Assume running inside a CI-environment:
		 *  1) don't use FIXEDMAP to avoid EBUSY in case collision,
		 *     which could be inspired by address space randomisation feature.
		 *  2) drop MDB_NOSYNC expecting that DBPATH is at a tmpfs or some dedicated storage.
		 */
		env_oflags = 0;
	}
	/* LY: especially here we always needs MDB_NOSYNC
	 * for testing mdbx_env_close_ex() and "redo-to-steady" on open. */
	env_oflags |= MDB_NOSYNC;
	E(mdb_env_open(env, DBPATH, env_oflags, 0664));

	E(mdb_txn_begin(env, NULL, 0, &txn));
	if (mdb_dbi_open(txn, "id1", MDB_CREATE, &dbi) == MDB_SUCCESS)
		E(mdb_drop(txn, dbi, 1));
	E(mdb_dbi_open(txn, "id1", MDB_CREATE, &dbi));

	key.mv_size = sizeof(int);
	key.mv_data = sval;
	data.mv_size = sizeof(sval);
	data.mv_data = sval;

	printf("Adding %d values\n", count);
	for (i=0;i<count;i++) {
		sprintf(sval, "%03x %d foo bar", values[i], values[i]);
		if (RES(MDB_KEYEXIST, mdb_put(txn, dbi, &key, &data, MDB_NOOVERWRITE)))
			j++;
	}
	if (j) printf("%d duplicates skipped\n", j);
	E(mdb_txn_commit(txn));
	E(mdb_env_stat(env, &mst));

	printf("check-preset-a\n");
	E(mdb_txn_begin(env, NULL, MDB_RDONLY, &txn));
	E(mdb_cursor_open(txn, dbi, &cursor));
	int present_a = 0;
	while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) {
		printf("key: %p %.*s, data: %p %.*s\n",
			key.mv_data,  (int) key.mv_size,  (char *) key.mv_data,
			data.mv_data, (int) data.mv_size, (char *) data.mv_data);
		++present_a;
	}
	CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
	CHECK(present_a == count - j, "mismatch");
	mdb_cursor_close(cursor);
	mdb_txn_abort(txn);
	mdb_env_sync(env, 1);

	int deleted = 0;
	key.mv_data = sval;
	for (i = count - 1; i > -1; i -= (rand()%5)) {
		txn=NULL;
		E(mdb_txn_begin(env, NULL, 0, &txn));
		sprintf(sval, "%03x ", values[i]);
		if (RES(MDB_NOTFOUND, mdb_del(txn, dbi, &key, NULL))) {
			mdb_txn_abort(txn);
		} else {
			E(mdb_txn_commit(txn));
			deleted++;
		}
	}
	free(values);
	printf("Deleted %d values\n", deleted);

	printf("check-preset-b.cursor-next\n");
	E(mdb_env_stat(env, &mst));
	E(mdb_txn_begin(env, NULL, MDB_RDONLY, &txn));
	E(mdb_cursor_open(txn, dbi, &cursor));
	int present_b = 0;
	while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) {
		printf("key: %.*s, data: %.*s\n",
			(int) key.mv_size,  (char *) key.mv_data,
			(int) data.mv_size, (char *) data.mv_data);
		++present_b;
	}
	CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
	CHECK(present_b == present_a - deleted, "mismatch");

	printf("check-preset-b.cursor-prev\n");
	j = 1;
	while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_PREV)) == 0) {
		printf("key: %.*s, data: %.*s\n",
			(int) key.mv_size,  (char *) key.mv_data,
			(int) data.mv_size, (char *) data.mv_data);
		++j;
	}
	CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
	CHECK(present_b == j, "mismatch");
	mdb_cursor_close(cursor);
	mdb_txn_abort(txn);

	mdb_dbi_close(env, dbi);
	/********************* LY: kept DB dirty ****************/
	mdbx_env_close_ex(env, 1);
	E(mdb_env_create(&env));
	E(mdb_env_set_maxdbs(env, 4));
	E(mdb_env_open(env, DBPATH, env_oflags, 0664));

	printf("check-preset-c.cursor-next\n");
	E(mdb_env_stat(env, &mst));
	E(mdb_txn_begin(env, NULL, MDB_RDONLY, &txn));
	E(mdb_dbi_open(txn, "id1", 0, &dbi));
	E(mdb_cursor_open(txn, dbi, &cursor));
	int present_c = 0;
	while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) {
		printf("key: %.*s, data: %.*s\n",
			(int) key.mv_size,  (char *) key.mv_data,
			(int) data.mv_size, (char *) data.mv_data);
		++present_c;
	}
	CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
	printf("Rolled back %d deletion(s)\n", present_c - (present_a - deleted));
	CHECK(present_c > present_a - deleted, "mismatch");

	printf("check-preset-d.cursor-prev\n");
	j = 1;
	while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_PREV)) == 0) {
		printf("key: %.*s, data: %.*s\n",
			(int) key.mv_size,  (char *) key.mv_data,
			(int) data.mv_size, (char *) data.mv_data);
		++j;
	}
	CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
	CHECK(present_c == j, "mismatch");
	mdb_cursor_close(cursor);
	mdb_txn_abort(txn);

	mdb_dbi_close(env, dbi);
	mdbx_env_close_ex(env, 0);

	return 0;
}
Exemple #19
0
int main(int argc,char * argv[])
{
	int i = 0, j = 0, rc;
	MDB_env *env;
	MDB_dbi dbi;
	MDB_val key, data, sdata;
	MDB_txn *txn;
	MDB_stat mst;
	MDB_cursor *cursor;
	int count;
	int *values;
	long kval;
	char *sval;

	srand(time(NULL));

	E(mdb_env_create(&env));
	E(mdb_env_set_mapsize(env, 10485760));
	E(mdb_env_set_maxdbs(env, 4));
	E(mdb_env_open(env, "./testdb", MDB_FIXEDMAP|MDB_NOSYNC, 0664));

	E(mdb_txn_begin(env, NULL, 0, &txn));
	E(mdb_dbi_open(txn, "id6", MDB_CREATE|MDB_INTEGERKEY, &dbi));
	E(mdb_cursor_open(txn, dbi, &cursor));
	E(mdb_stat(txn, dbi, &mst));

	sval = calloc(1, mst.ms_psize / 4);
	key.mv_size = sizeof(long);
	key.mv_data = &kval;
	sdata.mv_size = mst.ms_psize / 4 - 30;
	sdata.mv_data = sval;

	printf("Adding 12 values, should yield 3 splits\n");
	for (i=0;i<12;i++) {
		kval = i*5;
		sprintf(sval, "%08x", kval);
		data = sdata;
		(void)RES(MDB_KEYEXIST, mdb_cursor_put(cursor, &key, &data, MDB_NOOVERWRITE));
	}
	printf("Adding 12 more values, should yield 3 splits\n");
	for (i=0;i<12;i++) {
		kval = i*5+4;
		sprintf(sval, "%08x", kval);
		data = sdata;
		(void)RES(MDB_KEYEXIST, mdb_cursor_put(cursor, &key, &data, MDB_NOOVERWRITE));
	}
	printf("Adding 12 more values, should yield 3 splits\n");
	for (i=0;i<12;i++) {
		kval = i*5+1;
		sprintf(sval, "%08x", kval);
		data = sdata;
		(void)RES(MDB_KEYEXIST, mdb_cursor_put(cursor, &key, &data, MDB_NOOVERWRITE));
	}
	E(mdb_cursor_get(cursor, &key, &data, MDB_FIRST));

	do {
		printf("key: %p %s, data: %p %.*s\n",
			key.mv_data,  mdb_dkey(&key, dkbuf),
			data.mv_data, (int) data.mv_size, (char *) data.mv_data);
	} while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0);
	CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
	mdb_cursor_close(cursor);
	mdb_txn_commit(txn);

#if 0
	j=0;

	for (i= count - 1; i > -1; i-= (rand()%5)) {
		j++;
		txn=NULL;
		E(mdb_txn_begin(env, NULL, 0, &txn));
		sprintf(kval, "%03x", values[i & ~0x0f]);
		sprintf(sval, "%03x %d foo bar", values[i], values[i]);
		key.mv_size = sizeof(int);
		key.mv_data = kval;
		data.mv_size = sizeof(sval);
		data.mv_data = sval;
		if (RES(MDB_NOTFOUND, mdb_del(txn, dbi, &key, &data))) {
			j--;
			mdb_txn_abort(txn);
		} else {
			E(mdb_txn_commit(txn));
		}
	}
	free(values);
	printf("Deleted %d values\n", j);

	E(mdb_env_stat(env, &mst));
	E(mdb_txn_begin(env, NULL, MDB_RDONLY, &txn));
	E(mdb_cursor_open(txn, dbi, &cursor));
	printf("Cursor next\n");
	while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) {
		printf("key: %.*s, data: %.*s\n",
			(int) key.mv_size,  (char *) key.mv_data,
			(int) data.mv_size, (char *) data.mv_data);
	}
	CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
	printf("Cursor prev\n");
	while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_PREV)) == 0) {
		printf("key: %.*s, data: %.*s\n",
			(int) key.mv_size,  (char *) key.mv_data,
			(int) data.mv_size, (char *) data.mv_data);
	}
	CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
	mdb_cursor_close(cursor);
	mdb_txn_abort(txn);

	mdb_dbi_close(env, dbi);
#endif
	mdb_env_close(env);

	return 0;
}
Exemple #20
0
int main(int argc,char * argv[])
{
	int i = 0, j = 0, rc;
	MDB_env *env;
	MDB_dbi dbi;
	MDB_val key, data;
	MDB_txn *txn;
	MDB_stat mst;
	MDB_cursor *cursor;
	int count;
	int *values;
	char sval[32];
	char kval[sizeof(int)];

	srand(time(NULL));

	memset(sval, 0, sizeof(sval));

	count = (rand()%384) + 64;
	values = (int *)je_malloc(count*sizeof(int));

	for(i = 0;i<count;i++) {
		values[i] = rand()%1024;
	}

	E(mdb_env_create(&env));
	E(mdb_env_set_mapsize(env, 10485760));
	E(mdb_env_set_maxdbs(env, 4));
	E(mdb_env_open(env, "/tmp/testdb", MDB_FIXEDMAP|MDB_NOSYNC, 0664));
	E(mdb_txn_begin(env, NULL, 0, &txn));
	E(mdb_open(txn, "id2", MDB_CREATE|MDB_DUPSORT, &dbi));

	key.mv_size = sizeof(int);
	key.mv_data = kval;
	data.mv_size = sizeof(sval);
	data.mv_data = sval;

	printf("Adding %d values\n", count);
	for (i=0;i<count;i++) {
		if (!(i & 0x0f))
			sprintf(kval, "%03x", values[i]);
		sprintf(sval, "%03x %d foo bar", values[i], values[i]);
		if (RES(MDB_KEYEXIST, mdb_put(txn, dbi, &key, &data, MDB_NODUPDATA)))
			j++;
	}
	if (j) printf("%d duplicates skipped\n", j);
	E(mdb_txn_commit(txn));
	E(mdb_env_stat(env, &mst));

	E(mdb_txn_begin(env, NULL, 1, &txn));
	E(mdb_cursor_open(txn, dbi, &cursor));
	while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) {
		printf("key: %p %.*s, data: %p %.*s\n",
			key.mv_data,  (int) key.mv_size,  (char *) key.mv_data,
			data.mv_data, (int) data.mv_size, (char *) data.mv_data);
	}
	CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
	mdb_cursor_close(cursor);
	mdb_txn_abort(txn);

	j=0;

	for (i= count - 1; i > -1; i-= (rand()%5)) {
		j++;
		txn=NULL;
		E(mdb_txn_begin(env, NULL, 0, &txn));
		sprintf(kval, "%03x", values[i & ~0x0f]);
		sprintf(sval, "%03x %d foo bar", values[i], values[i]);
		key.mv_size = sizeof(int);
		key.mv_data = kval;
		data.mv_size = sizeof(sval);
		data.mv_data = sval;
		if (RES(MDB_NOTFOUND, mdb_del(txn, dbi, &key, &data))) {
			j--;
			mdb_txn_abort(txn);
		} else {
			E(mdb_txn_commit(txn));
		}
	}
	je_free(values);
	printf("Deleted %d values\n", j);

	E(mdb_env_stat(env, &mst));
	E(mdb_txn_begin(env, NULL, 1, &txn));
	E(mdb_cursor_open(txn, dbi, &cursor));
	printf("Cursor next\n");
	while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) {
		printf("key: %.*s, data: %.*s\n",
			(int) key.mv_size,  (char *) key.mv_data,
			(int) data.mv_size, (char *) data.mv_data);
	}
	CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
	printf("Cursor prev\n");
	while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_PREV)) == 0) {
		printf("key: %.*s, data: %.*s\n",
			(int) key.mv_size,  (char *) key.mv_data,
			(int) data.mv_size, (char *) data.mv_data);
	}
	CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
	mdb_cursor_close(cursor);
	mdb_close(env, dbi);

	mdb_txn_abort(txn);
	mdb_env_close(env);

	return 0;
}
RES ResourceFormatLoaderImage::load(const String &p_path,const String& p_original_path) {
	
	
	if (p_path.extension()=="cube") {
		// open as cubemap txture

		CubeMap* ptr = memnew(CubeMap);
		Ref<CubeMap> cubemap( ptr );

		Error err;
		FileAccess *f = FileAccess::open(p_path,FileAccess::READ,&err);
		if (err) {
		
			ERR_FAIL_COND_V( err, RES() );
		}
		
		String base_path=p_path.substr( 0, p_path.find_last("/")+1 );

		for(int i=0;i<6;i++) {
		
			String file = f->get_line().strip_edges();
			Image image;
			
			Error err = ImageLoader::load_image(base_path+file,&image);

			
			if (err) {
			
				memdelete(f);
				ERR_FAIL_COND_V( err, RES() );
			}
			
			if (i==0) {
			
				//cubemap->create(image.get_width(),image.get_height(),image.get_format(),Texture::FLAGS_DEFAULT|Texture::FLAG_CUBEMAP);
			}
			
			static const CubeMap::Side cube_side[6]= {
				CubeMap::SIDE_LEFT,
				CubeMap::SIDE_RIGHT,
				CubeMap::SIDE_BOTTOM,
				CubeMap::SIDE_TOP,
				CubeMap::SIDE_FRONT,
				CubeMap::SIDE_BACK
			};
			
			cubemap->set_side(cube_side[i],image);
		}
		
		memdelete(f);

		cubemap->set_name(p_path.get_file());

		return cubemap;
	
	} else {
		// simple image	

		ImageTexture* ptr = memnew(ImageTexture);
		Ref<ImageTexture> texture( ptr );

		uint64_t begtime;
		double total;

		Image image;

		if (debug_load_times)
			begtime=OS::get_singleton()->get_ticks_usec();


		Error err = ImageLoader::load_image(p_path,&image);

		if (!err && debug_load_times) {
			double total=(double)(OS::get_singleton()->get_ticks_usec()-begtime)/1000000.0;
			print_line("IMAGE: "+itos(image.get_width())+"x"+itos(image.get_height()));
			print_line("  -load: "+rtos(total));
		}


		ERR_EXPLAIN("Failed loading image: "+p_path);
		ERR_FAIL_COND_V(err, RES());		

#ifdef DEBUG_ENABLED
#ifdef TOOLS_ENABLED

		if (max_texture_size && (image.get_width() > max_texture_size || image.get_height() > max_texture_size)) {


			if (bool(Globals::get_singleton()->get("debug/max_texture_size_alert"))) {
				OS::get_singleton()->alert("Texture is too large: '"+p_path+"', at "+itos(image.get_width())+"x"+itos(image.get_height())+". Max allowed size is: "+itos(max_texture_size)+"x"+itos(max_texture_size)+".","BAD ARTIST, NO COOKIE!");
			}

			ERR_EXPLAIN("Texture is too large: '"+p_path+"', at "+itos(image.get_width())+"x"+itos(image.get_height())+". Max allowed size is: "+itos(max_texture_size)+"x"+itos(max_texture_size)+".");
			ERR_FAIL_V(RES());
		}
#endif
#endif
		
		
		uint32_t flags=0;
		if (bool(GLOBAL_DEF("texture_import/filter",true)))
			flags|=Texture::FLAG_FILTER;
		if (bool(GLOBAL_DEF("texture_import/gen_mipmaps",true)))
			flags|=Texture::FLAG_MIPMAPS;
		if (bool(GLOBAL_DEF("texture_import/repeat",true)))
			flags|=Texture::FLAG_REPEAT;



		if (debug_load_times)
			begtime=OS::get_singleton()->get_ticks_usec();

		//print_line("img: "+p_path+" flags: "+itos(flags));
		texture->create_from_image( image,flags );
		texture->set_name(p_path.get_file());


		if (debug_load_times) {
			total=(double)(OS::get_singleton()->get_ticks_usec()-begtime)/1000000.0;
			print_line("  -make texture: "+rtos(total));
		}

		return RES( texture );
	}
	

}
Exemple #22
0
RES ResourceFormatLoaderImage::load(const String &p_path, const String& p_original_path, Error *r_error) {
	
	if (r_error)
		*r_error=ERR_CANT_OPEN;

	if (p_path.extension()=="cube") {
		// open as cubemap txture

		CubeMap* ptr = memnew(CubeMap);
		Ref<CubeMap> cubemap( ptr );

		Error err;
		FileAccess *f = FileAccess::open(p_path,FileAccess::READ,&err);
		if (err) {
		
			ERR_FAIL_COND_V( err, RES() );
		}
		
		String base_path=p_path.substr( 0, p_path.find_last("/")+1 );

		for(int i=0;i<6;i++) {
		
			String file = f->get_line().strip_edges();
			Image image;
			
			Error err = ImageLoader::load_image(base_path+file,&image);

			
			if (err) {
			
				memdelete(f);
				ERR_FAIL_COND_V( err, RES() );
			}
			
			if (i==0) {
			
				//cubemap->create(image.get_width(),image.get_height(),image.get_format(),Texture::FLAGS_DEFAULT|Texture::FLAG_CUBEMAP);
			}
			
			static const CubeMap::Side cube_side[6]= {
				CubeMap::SIDE_LEFT,
				CubeMap::SIDE_RIGHT,
				CubeMap::SIDE_BOTTOM,
				CubeMap::SIDE_TOP,
				CubeMap::SIDE_FRONT,
				CubeMap::SIDE_BACK
			};
			
			cubemap->set_side(cube_side[i],image);
		}
		
		memdelete(f);

		cubemap->set_name(p_path.get_file());
		if (r_error)
			*r_error=OK;

		return cubemap;
	
	} else {
		// simple image	

		ImageTexture* ptr = memnew(ImageTexture);
		Ref<ImageTexture> texture( ptr );

		uint64_t begtime;
		double total;

		Image image;

		if (debug_load_times)
			begtime=OS::get_singleton()->get_ticks_usec();


		Error err = ImageLoader::load_image(p_path,&image);

		if (!err && debug_load_times) {
			double total=(double)(OS::get_singleton()->get_ticks_usec()-begtime)/1000000.0;
			print_line("IMAGE: "+itos(image.get_width())+"x"+itos(image.get_height()));
			print_line("  -load: "+rtos(total));
		}


		ERR_EXPLAIN("Failed loading image: "+p_path);
		ERR_FAIL_COND_V(err, RES());		
		if (r_error)
			*r_error=ERR_FILE_CORRUPT;

#ifdef DEBUG_ENABLED
#ifdef TOOLS_ENABLED

		if (max_texture_size && (image.get_width() > max_texture_size || image.get_height() > max_texture_size)) {


			if (bool(Globals::get_singleton()->get("debug/max_texture_size_alert"))) {
				OS::get_singleton()->alert("Texture is too large: '"+p_path+"', at "+itos(image.get_width())+"x"+itos(image.get_height())+". Max allowed size is: "+itos(max_texture_size)+"x"+itos(max_texture_size)+".","BAD ARTIST, NO COOKIE!");
			}

			ERR_EXPLAIN("Texture is too large: '"+p_path+"', at "+itos(image.get_width())+"x"+itos(image.get_height())+". Max allowed size is: "+itos(max_texture_size)+"x"+itos(max_texture_size)+".");
			ERR_FAIL_V(RES());
		}
#endif
#endif
		
		
		uint32_t flags=0;

		FileAccess *f2 = FileAccess::open(p_path+".flags",FileAccess::READ);
		Map<String,bool> flags_found;
		if (f2) {

			while(!f2->eof_reached()) {
				String l2 = f2->get_line();
				int eqpos = l2.find("=");
				if (eqpos!=-1) {
					String flag=l2.substr(0,eqpos).strip_edges();
					String val=l2.substr(eqpos+1,l2.length()).strip_edges().to_lower();
					flags_found[flag]=(val=="true" || val=="1")?true:false;
				}
			}
			memdelete(f2);
		}


		if (flags_found.has("filter")) {
			if (flags_found["filter"])
				flags|=Texture::FLAG_FILTER;
		} else if (bool(GLOBAL_DEF("image_loader/filter",true))) {
			flags|=Texture::FLAG_FILTER;
		}


		if (flags_found.has("gen_mipmaps")) {
			if (flags_found["gen_mipmaps"])
				flags|=Texture::FLAG_MIPMAPS;
		} else if (bool(GLOBAL_DEF("image_loader/gen_mipmaps",true))) {
			flags|=Texture::FLAG_MIPMAPS;
		}

		if (flags_found.has("repeat")) {
			if (flags_found["repeat"])
				flags|=Texture::FLAG_REPEAT;
		} else if (bool(GLOBAL_DEF("image_loader/repeat",true))) {
			flags|=Texture::FLAG_REPEAT;
		}

		if (flags_found.has("anisotropic")) {
			if (flags_found["anisotropic"])
				flags|=Texture::FLAG_ANISOTROPIC_FILTER;
		}

		if (flags_found.has("tolinear")) {
			if (flags_found["tolinear"])
				flags|=Texture::FLAG_CONVERT_TO_LINEAR;
		}
		
		if (flags_found.has("mirroredrepeat")) {
			if (flags_found["mirroredrepeat"])
				flags|=Texture::FLAG_MIRRORED_REPEAT;
		}

		if (debug_load_times)
			begtime=OS::get_singleton()->get_ticks_usec();

		//print_line("img: "+p_path+" flags: "+itos(flags));
		texture->create_from_image( image,flags );
		texture->set_name(p_path.get_file());


		if (debug_load_times) {
			total=(double)(OS::get_singleton()->get_ticks_usec()-begtime)/1000000.0;
			print_line("  -make texture: "+rtos(total));
		}

		if (r_error)
			*r_error=OK;

		return RES( texture );
	}
	

}
Exemple #23
0
int main(int argc,char * argv[])
{
	int i = 0, j = 0, rc;
	MDB_env *env;
	MDB_dbi dbi;
	MDB_val key, data;
	MDB_txn *txn;
	MDB_stat mst;
	MDB_cursor *cursor;
	int count;
	int *values;
	char sval[8];
	char kval[sizeof(int)];

	memset(sval, 0, sizeof(sval));

	count = 510;
	values = (int *)malloc(count*sizeof(int));

	for(i = 0;i<count;i++) {
		values[i] = i*5;
	}

	E(mdb_env_create(&env));
	E(mdb_env_set_mapsize(env, 10485760));
	E(mdb_env_set_maxdbs(env, 4));
	E(mdb_env_open(env, "./testdb", MDB_FIXEDMAP|MDB_NOSYNC, 0664));
	E(mdb_txn_begin(env, NULL, 0, &txn));
	E(mdb_open(txn, "id4", MDB_CREATE|MDB_DUPSORT|MDB_DUPFIXED, &dbi));

	key.mv_size = sizeof(int);
	key.mv_data = kval;
	data.mv_size = sizeof(sval);
	data.mv_data = sval;

	printf("Adding %d values\n", count);
	strcpy(kval, "001");
	for (i=0;i<count;i++) {
		sprintf(sval, "%07x", values[i]);
		if (RES(MDB_KEYEXIST, mdb_put(txn, dbi, &key, &data, MDB_NODUPDATA)))
			j++;
	}
	if (j) printf("%d duplicates skipped\n", j);
	E(mdb_txn_commit(txn));
	E(mdb_env_stat(env, &mst));

	/* there should be one full page of dups now.
	 */
	E(mdb_txn_begin(env, NULL, 1, &txn));
	E(mdb_cursor_open(txn, dbi, &cursor));
	while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) {
		printf("key: %p %.*s, data: %p %.*s\n",
			key.mv_data,  (int) key.mv_size,  (char *) key.mv_data,
			data.mv_data, (int) data.mv_size, (char *) data.mv_data);
	}
	CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
	mdb_cursor_close(cursor);
	mdb_txn_abort(txn);

	/* test all 3 branches of split code:
	 * 1: new key in lower half
	 * 2: new key at split point
	 * 3: new key in upper half
	 */

	key.mv_size = sizeof(int);
	key.mv_data = kval;
	data.mv_size = sizeof(sval);
	data.mv_data = sval;

	sprintf(sval, "%07x", values[3]+1);
	E(mdb_txn_begin(env, NULL, 0, &txn));
	(void)RES(MDB_KEYEXIST, mdb_put(txn, dbi, &key, &data, MDB_NODUPDATA));
	mdb_txn_abort(txn);

	sprintf(sval, "%07x", values[255]+1);
	E(mdb_txn_begin(env, NULL, 0, &txn));
	(void)RES(MDB_KEYEXIST, mdb_put(txn, dbi, &key, &data, MDB_NODUPDATA));
	mdb_txn_abort(txn);

	sprintf(sval, "%07x", values[500]+1);
	E(mdb_txn_begin(env, NULL, 0, &txn));
	(void)RES(MDB_KEYEXIST, mdb_put(txn, dbi, &key, &data, MDB_NODUPDATA));
	E(mdb_txn_commit(txn));

	/* Try MDB_NEXT_MULTIPLE */
	E(mdb_txn_begin(env, NULL, 0, &txn));
	E(mdb_cursor_open(txn, dbi, &cursor));
	while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT_MULTIPLE)) == 0) {
		printf("key: %.*s, data: %.*s\n",
			(int) key.mv_size,  (char *) key.mv_data,
			(int) data.mv_size, (char *) data.mv_data);
	}
	CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
	mdb_cursor_close(cursor);
	mdb_txn_abort(txn);
	j=0;

	for (i= count - 1; i > -1; i-= (rand()%3)) {
		j++;
		txn=NULL;
		E(mdb_txn_begin(env, NULL, 0, &txn));
		sprintf(sval, "%07x", values[i]);
		key.mv_size = sizeof(int);
		key.mv_data = kval;
		data.mv_size = sizeof(sval);
		data.mv_data = sval;
		if (RES(MDB_NOTFOUND, mdb_del(txn, dbi, &key, &data))) {
			j--;
			mdb_txn_abort(txn);
		} else {
			E(mdb_txn_commit(txn));
		}
	}
	free(values);
	printf("Deleted %d values\n", j);

	E(mdb_env_stat(env, &mst));
	E(mdb_txn_begin(env, NULL, 1, &txn));
	E(mdb_cursor_open(txn, dbi, &cursor));
	printf("Cursor next\n");
	while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) {
		printf("key: %.*s, data: %.*s\n",
			(int) key.mv_size,  (char *) key.mv_data,
			(int) data.mv_size, (char *) data.mv_data);
	}
	CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
	printf("Cursor prev\n");
	while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_PREV)) == 0) {
		printf("key: %.*s, data: %.*s\n",
			(int) key.mv_size,  (char *) key.mv_data,
			(int) data.mv_size, (char *) data.mv_data);
	}
	CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get");
	mdb_cursor_close(cursor);
	mdb_close(env, dbi);

	mdb_txn_abort(txn);
	mdb_env_close(env);

	return 0;
}
//--------------------------------------------------------------------------------------
//       Class:  YARPSoundDeviceDriver
//      Method:  Body()
// Description:  Here, the body of the thread should be implemented
//--------------------------------------------------------------------------------------
void 
YARPSoundDeviceDriver::Body (void)
{
	SoundResources& d = RES(system_resources);
	MSG		msg;

	const int prio = ACE_Sched_Params::next_priority (ACE_SCHED_OTHER, GetPriority(), ACE_SCOPE_THREAD);
	SetPriority (prio);
	
	//----------------------------------------------------------------------
	//  Wait for a message sent by the audio driver
	//----------------------------------------------------------------------
	while (GetMessage(&msg, 0, 0, 0) == 1 && !IsTerminated()) {

		switch (msg.message) {
			case MM_WIM_DATA: //Buffer filled 
				/*********************************************************************************
				 * the msg.lParam contains a pointer to the WAVEHDR structure for the filled buffer. *
				 *********************************************************************************/
				if (((WAVEHDR *)msg.lParam)->dwBytesRecorded) {
					//----------------------------------------------------------------------
					//  Here write in the local buffer using the syncronization mutexes
					//----------------------------------------------------------------------
					if (d._bmutex.PollingWait () == 1) { // buffer acquired. Reading from the buffer
						if (d.m_InRecord)
							memcpy (d._rawBuffer, 
									((WAVEHDR *)msg.lParam)->lpData, 
                                    ((WAVEHDR *)msg.lParam)->dwBytesRecorded); // Note: is this right?
                                                                               // The buffer could not be full...
						if (d._canpost) {
							d._canpost = false;
							d._new_frame.Post();
						}
						d._bmutex.Post ();
					}
					else
					{
						//----------------------------------------------------------------------
						//  can't acquire, it means the buffer is still in use.
						//  silently ignores this condition.
						//----------------------------------------------------------------------
						ACE_DEBUG ((LM_DEBUG, "lost a frame, acq thread\n"));
					}
				}

				//----------------------------------------------------------------------
				//  Requeue the used buffer	
				//----------------------------------------------------------------------
				waveInAddBuffer(d.m_WaveInHandle, 
								(WAVEHDR *)msg.lParam, 
								sizeof(WAVEHDR));

				break;
				/* Our main thread is opening the WAVE device */
			case MM_WIM_OPEN:
				ACE_DEBUG ((LM_DEBUG, "yarpsounddriver: sound device opened\n"));
				break;
				/* Our main thread is closing the WAVE device */
			case MM_WIM_CLOSE:
				break;
			default:
				//ACE_DEBUG ((LM_DEBUG, "yarpsounddriver: received an unknown message\n"));
				break;
		}
	}

	ACE_DEBUG ((LM_DEBUG, "acquisition thread returning...\n"));
}
Exemple #25
0
RES ResourceFormatLoaderShader::load(const String &p_path, const String& p_original_path, Error *r_error) {

	if (r_error)
		*r_error=ERR_FILE_CANT_OPEN;

	String fragment_code;
	String vertex_code;
	String light_code;

	int mode=-1;

	Error err;
	FileAccess *f = FileAccess::open(p_path,FileAccess::READ,&err);


	ERR_EXPLAIN("Unable to open shader file: "+p_path);
	ERR_FAIL_COND_V(err,RES());
	String base_path = p_path.get_base_dir();

	if (r_error)
		*r_error=ERR_FILE_CORRUPT;

	Ref<Shader> shader;//( memnew( Shader ) );

	int line=0;

	while(!f->eof_reached()) {

		String l = f->get_line();
		line++;

		if (mode<=0) {
			l = l.strip_edges();
			int comment = l.find(";");
			if (comment!=-1)
				l=l.substr(0,comment);
		}

		if (mode<1)
			vertex_code+="\n";
		if (mode<2)
			fragment_code+="\n";

		if (mode < 1 && l=="")
			continue;

		if (l.begins_with("[")) {
			l=l.strip_edges();
			if (l=="[params]") {
				if (mode>=0) {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Misplaced [params] section.");
					ERR_FAIL_V(RES());
				}
				mode=0;
			}  else if (l=="[vertex]") {
				if (mode>=1) {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Misplaced [vertex] section.");
					ERR_FAIL_V(RES());
				}
				mode=1;
			}  else if (l=="[fragment]") {
				if (mode>=2) {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Misplaced [fragment] section.");
					ERR_FAIL_V(RES());
				}
				mode=1;
			} else {
				memdelete(f);
				ERR_EXPLAIN(p_path+":"+itos(line)+": Unknown section type: '"+l+"'.");
				ERR_FAIL_V(RES());
			}
			continue;
		}

		if (mode==0) {

			int eqpos = l.find("=");
			if (eqpos==-1) {
				memdelete(f);
				ERR_EXPLAIN(p_path+":"+itos(line)+": Expected '='.");
				ERR_FAIL_V(RES());
			}


			String right=l.substr(eqpos+1,l.length()).strip_edges();
			if (right=="") {
				memdelete(f);
				ERR_EXPLAIN(p_path+":"+itos(line)+": Expected value after '='.");
				ERR_FAIL_V(RES());
			}

			Variant value;

			if (right=="true") {
				value = true;
			} else if (right=="false") {
				value = false;
			} else if (right.is_valid_float()) {
				//is number
				value = right.to_double();
			} else if (right.is_valid_html_color()) {
				//is html color
				value = Color::html(right);
			} else {
				//attempt to parse a constructor
				int popenpos = right.find("(");

				if (popenpos==-1) {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid constructor syntax: "+right);
					ERR_FAIL_V(RES());
				}

				int pclosepos = right.find_last(")");

				if (pclosepos==-1) {
					ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid constructor parameter syntax: "+right);
					ERR_FAIL_V(RES());

				}

				String type = right.substr(0,popenpos);
				String param = right.substr(popenpos+1,pclosepos-popenpos-1).strip_edges();


				if (type=="tex") {

					if (param=="") {

						value=RID();
					} else {

						String path;

						if (param.is_abs_path())
							path=param;
						else
							path=base_path+"/"+param;

						Ref<Texture> texture = ResourceLoader::load(path);
						if (!texture.is_valid()) {
							memdelete(f);
							ERR_EXPLAIN(p_path+":"+itos(line)+": Couldn't find icon at path: "+path);
							ERR_FAIL_V(RES());
						}

						value=texture;
					}

				} else if (type=="vec3") {

					if (param=="") {
						value=Vector3();
					} else {
						Vector<String> params = param.split(",");
						if (params.size()!=3) {
							memdelete(f);
							ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid param count for vec3(): '"+right+"'.");
							ERR_FAIL_V(RES());

						}

						Vector3 v;
						for(int i=0;i<3;i++)
							v[i]=params[i].to_double();
						value=v;
					}


				} else if (type=="xform") {

					if (param=="") {
						value=Transform();
					} else {

						Vector<String> params = param.split(",");
						if (params.size()!=12) {
							memdelete(f);
							ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid param count for xform(): '"+right+"'.");
							ERR_FAIL_V(RES());

						}

						Transform t;
						for(int i=0;i<9;i++)
							t.basis[i%3][i/3]=params[i].to_double();
						for(int i=0;i<3;i++)
							t.origin[i]=params[i-9].to_double();

						value=t;
					}

				} else {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid constructor type: '"+type+"'.");
					ERR_FAIL_V(RES());

				}

			}

			String left= l.substr(0,eqpos);

//			shader->set_param(left,value);
		} else if (mode==1) {

			vertex_code+=l;

		} else if (mode==2) {

			fragment_code+=l;
		}
	}

	shader->set_code(vertex_code,fragment_code,light_code);

	f->close();
	memdelete(f);
	if (r_error)
		*r_error=OK;

	return shader;
}
int YARPPicoloDeviceDriver::getWidth (void *cmd)
{
	*(int *)cmd = RES(system_resources)._nWidth;
	return YARP_OK;
}
RES ResourceFormatLoaderWAV::load(const String &p_path,const String& p_original_path) {

	Error err;
	FileAccess *file=FileAccess::open(p_path, FileAccess::READ,&err);

	ERR_FAIL_COND_V( err!=OK, RES() );

	/* CHECK RIFF */
	char riff[5];
	riff[4]=0;
	file->get_buffer((uint8_t*)&riff,4); //RIFF

	if (riff[0]!='R' || riff[1]!='I' || riff[2]!='F' || riff[3]!='F') {

		file->close();
		memdelete(file);
		ERR_FAIL_V( RES() );
	}


	/* GET FILESIZE */
	uint32_t filesize=file->get_32();

	/* CHECK WAVE */

	char wave[4];

	file->get_buffer((uint8_t*)&wave,4); //RIFF

	if (wave[0]!='W' || wave[1]!='A' || wave[2]!='V' || wave[3]!='E') {


		file->close();
		memdelete(file);
		ERR_EXPLAIN("Not a WAV file (no WAVE RIFF Header)")
		ERR_FAIL_V( RES() );
	}

	bool format_found=false;
	bool data_found=false;
	int format_bits=0;
	int format_channels=0;
	int format_freq=0;
	Sample::LoopFormat loop=Sample::LOOP_NONE;
	int loop_begin=0;
	int loop_end=0;


	Ref<Sample> sample( memnew( Sample ) );


	while (!file->eof_reached()) {


		/* chunk */
		char chunkID[4];
		file->get_buffer((uint8_t*)&chunkID,4); //RIFF

		/* chunk size */
		uint32_t chunksize=file->get_32();
		uint32_t file_pos=file->get_pos(); //save file pos, so we can skip to next chunk safely

		if (file->eof_reached()) {

			//ERR_PRINT("EOF REACH");
			break;
		}

		if (chunkID[0]=='f' && chunkID[1]=='m' && chunkID[2]=='t' && chunkID[3]==' ' && !format_found) {
			/* IS FORMAT CHUNK */

			uint16_t compression_code=file->get_16();


			if (compression_code!=1) {
				ERR_PRINT("Format not supported for WAVE file (not PCM). Save WAVE files as uncompressed PCM instead.");
				break;
			}

			format_channels=file->get_16();
			if (format_channels!=1 && format_channels !=2) {

				ERR_PRINT("Format not supported for WAVE file (not stereo or mono)");
				break;

			}

			format_freq=file->get_32(); //sampling rate

			file->get_32(); // average bits/second (unused)
			file->get_16(); // block align (unused)
			format_bits=file->get_16(); // bits per sample

			if (format_bits%8) {

				ERR_PRINT("Strange number of bits in sample (not 8,16,24,32)");
				break;
			}

			/* Dont need anything else, continue */
			format_found=true;
		}


		if (chunkID[0]=='d' && chunkID[1]=='a' && chunkID[2]=='t' && chunkID[3]=='a' && !data_found) {
			/* IS FORMAT CHUNK */
			data_found=true;

			if (!format_found) {
				ERR_PRINT("'data' chunk before 'format' chunk found.");
				break;

			}

			int frames=chunksize;
			frames/=format_channels;
			frames/=(format_bits>>3);


			sample->create(
					(format_bits==8) ? Sample::FORMAT_PCM8 : Sample::FORMAT_PCM16,
					(format_channels==2)?true:false,
					frames );
			sample->set_mix_rate( format_freq );

			DVector<uint8_t> data;
			data.resize(chunksize);
			DVector<uint8_t>::Write dataw = data.write();
			void * data_ptr = dataw.ptr();

			for (int i=0;i<frames;i++) {


				for (int c=0;c<format_channels;c++) {


					if (format_bits==8) {
						// 8 bit samples are UNSIGNED

						uint8_t s = file->get_8();
						s-=128;
						int8_t *sp=(int8_t*)&s;

						int8_t *data_ptr8=&((int8_t*)data_ptr)[i*format_channels+c];

						*data_ptr8=*sp;

					} else {
						//16+ bits samples are SIGNED
						// if sample is > 16 bits, just read extra bytes

						uint32_t data=0;
						for (int b=0;b<(format_bits>>3);b++) {

							data|=((uint32_t)file->get_8())<<(b*8);
						}
						data<<=(32-format_bits);


						int32_t s=data;

						int16_t *data_ptr16=&((int16_t*)data_ptr)[i*format_channels+c];

						*data_ptr16=s>>16;
					}
				}

			}

			dataw=DVector<uint8_t>::Write();

			sample->set_data(data);


			if (file->eof_reached()) {
				file->close();
				memdelete(file);
				ERR_EXPLAIN("Premature end of file.");
				ERR_FAIL_V(RES());
			}
		}

		if (chunkID[0]=='s' && chunkID[1]=='m' && chunkID[2]=='p' && chunkID[3]=='l') {
			//loop point info!

			for(int i=0;i<10;i++)
				file->get_32(); // i wish to know why should i do this... no doc!

			loop=file->get_32()?Sample::LOOP_PING_PONG:Sample::LOOP_FORWARD;
			loop_begin=file->get_32();
			loop_end=file->get_32();

		}
		file->seek( file_pos+chunksize );
	}
int YARPPicoloDeviceDriver::getHeight (void *cmd)
{
	*(int *)cmd = RES(system_resources)._nHeight;
	return YARP_OK;
}
Exemple #29
0
Ref<ResourceInteractiveLoader> ResourceLoader::load_interactive(const String &p_path, const String &p_type_hint, bool p_no_cache, Error *r_error) {

	if (r_error)
		*r_error = ERR_CANT_OPEN;

	String local_path;
	if (p_path.is_rel_path())
		local_path = "res://" + p_path;
	else
		local_path = ProjectSettings::get_singleton()->localize_path(p_path);

	if (!p_no_cache) {

		bool success = _add_to_loading_map(local_path);
		if (!success) {
			ERR_EXPLAIN("Resource: '" + local_path + "' is already being loaded. Cyclic reference?");
			ERR_FAIL_V(RES());
		}

		if (ResourceCache::has(local_path)) {

			print_verbose("Loading resource: " + local_path + " (cached)");
			Ref<Resource> res_cached = ResourceCache::get(local_path);
			Ref<ResourceInteractiveLoaderDefault> ril = Ref<ResourceInteractiveLoaderDefault>(memnew(ResourceInteractiveLoaderDefault));

			ril->resource = res_cached;
			ril->path_loading = local_path;
			ril->path_loading_thread = Thread::get_caller_id();
			return ril;
		}
	}

	bool xl_remapped = false;
	String path = _path_remap(local_path, &xl_remapped);
	if (path == "") {
		if (!p_no_cache) {
			_remove_from_loading_map(local_path);
		}
		ERR_EXPLAIN("Remapping '" + local_path + "'failed.");
		ERR_FAIL_V(RES());
	}

	print_verbose("Loading resource: " + path);

	bool found = false;
	for (int i = 0; i < loader_count; i++) {

		if (!loader[i]->recognize_path(path, p_type_hint))
			continue;
		found = true;
		Ref<ResourceInteractiveLoader> ril = loader[i]->load_interactive(path, local_path, r_error);
		if (ril.is_null())
			continue;
		if (!p_no_cache) {
			ril->set_local_path(local_path);
			ril->path_loading = local_path;
			ril->path_loading_thread = Thread::get_caller_id();
		}

		if (xl_remapped)
			ril->set_translation_remapped(true);

		return ril;
	}

	if (!p_no_cache) {
		_remove_from_loading_map(local_path);
	}

	if (found) {
		ERR_EXPLAIN("Failed loading resource: " + path);
	} else {
		ERR_EXPLAIN("No loader found for resource: " + path);
	}
	ERR_FAIL_V(Ref<ResourceInteractiveLoader>());
	return Ref<ResourceInteractiveLoader>();
}
Exemple #30
0
RES ResourceFormatLoaderTheme::load(const String &p_path, const String& p_original_path, Error *r_error) {
    if (r_error)
        *r_error=ERR_CANT_OPEN;

    Error err;
    FileAccess *f = FileAccess::open(p_path,FileAccess::READ,&err);

    ERR_EXPLAIN("Unable to open theme file: "+p_path);
    ERR_FAIL_COND_V(err,RES());
    String base_path = p_path.get_base_dir();
    Ref<Theme> theme( memnew( Theme ) );
    Map<StringName,Variant> library;
    if (r_error)
        *r_error=ERR_FILE_CORRUPT;

    bool reading_library=false;
    int line=0;

    while(!f->eof_reached()) {

        String l = f->get_line().strip_edges();
        line++;

        int comment = l.find(";");
        if (comment!=-1)
            l=l.substr(0,comment);
        if (l=="")
            continue;

        if (l.begins_with("[")) {
            if (l=="[library]") {
                reading_library=true;
            }  else if (l=="[theme]") {
                reading_library=false;
            } else {
                memdelete(f);
                ERR_EXPLAIN(p_path+":"+itos(line)+": Unknown section type: '"+l+"'.");
                ERR_FAIL_V(RES());
            }
            continue;
        }

        int eqpos = l.find("=");
        if (eqpos==-1) {
            memdelete(f);
            ERR_EXPLAIN(p_path+":"+itos(line)+": Expected '='.");
            ERR_FAIL_V(RES());
        }


        String right=l.substr(eqpos+1,l.length()).strip_edges();
        if (right=="") {
            memdelete(f);
            ERR_EXPLAIN(p_path+":"+itos(line)+": Expected value after '='.");
            ERR_FAIL_V(RES());
        }

        Variant value;

        if (right.is_valid_integer()) {
            //is number
            value = right.to_int();
        } else if (right.is_valid_html_color()) {
            //is html color
            value = Color::html(right);
        } else if (right.begins_with("@")) { //reference

            String reference = right.substr(1,right.length());
            if (!library.has(reference)) {
                memdelete(f);
                ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid reference to '"+reference+"'.");
                ERR_FAIL_V(RES());

            }

            value=library[reference];

        } else if (right.begins_with("default")) { //use default
            //do none
        } else {
            //attempt to parse a constructor
            int popenpos = right.find("(");

            if (popenpos==-1) {
                memdelete(f);
                ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid constructor syntax: "+right);
                ERR_FAIL_V(RES());
            }

            int pclosepos = right.find_last(")");

            if (pclosepos==-1) {
                ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid constructor parameter syntax: "+right);
                ERR_FAIL_V(RES());

            }

            String type = right.substr(0,popenpos);
            String param = right.substr(popenpos+1,pclosepos-popenpos-1);



            if (type=="icon") {

                String path;

                if (param.is_abs_path())
                    path=param;
                else
                    path=base_path+"/"+param;

                Ref<Texture> texture = ResourceLoader::load(path);
                if (!texture.is_valid()) {
                    memdelete(f);
                    ERR_EXPLAIN(p_path+":"+itos(line)+": Couldn't find icon at path: "+path);
                    ERR_FAIL_V(RES());
                }

                value=texture;

            } else if (type=="sbox") {

                String path;

                if (param.is_abs_path())
                    path=param;
                else
                    path=base_path+"/"+param;

                Ref<StyleBox> stylebox = ResourceLoader::load(path);
                if (!stylebox.is_valid()) {
                    memdelete(f);
                    ERR_EXPLAIN(p_path+":"+itos(line)+": Couldn't find stylebox at path: "+path);
                    ERR_FAIL_V(RES());
                }

                value=stylebox;

            } else if (type=="sboxt") {

                Vector<String> params = param.split(",");
                if (params.size()!=5 && params.size()!=9) {
                    memdelete(f);
                    ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid param count for sboxt(): '"+right+"'.");
                    ERR_FAIL_V(RES());

                }

                String path=params[0];

                if (!param.is_abs_path())
                    path=base_path+"/"+path;

                Ref<Texture> tex = ResourceLoader::load(path);
                if (tex.is_null()) {
                    memdelete(f);
                    ERR_EXPLAIN(p_path+":"+itos(line)+": Could not open texture for sboxt at path: '"+params[0]+"'.");
                    ERR_FAIL_V(RES());

                }

                Ref<StyleBoxTexture> sbtex( memnew(StyleBoxTexture) );

                sbtex->set_texture(tex);

                for(int i=0; i<4; i++) {
                    if (!params[i+1].is_valid_integer()) {

                        memdelete(f);
                        ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid expand margin parameter for sboxt #"+itos(i+1) +", expected integer constant, got: '"+params[i+1]+"'.");
                        ERR_FAIL_V(RES());
                    }

                    int margin = params[i+1].to_int();
                    sbtex->set_expand_margin_size(Margin(i),margin);
                }

                if (params.size()==9) {

                    for(int i=0; i<4; i++) {

                        if (!params[i+5].is_valid_integer()) {
                            memdelete(f);
                            ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid expand margin parameter for sboxt #"+itos(i+5) +", expected integer constant, got: '"+params[i+5]+"'.");
                            ERR_FAIL_V(RES());
                        }

                        int margin = params[i+5].to_int();
                        sbtex->set_margin_size(Margin(i),margin);
                    }
                }

                value = sbtex;
            } else if (type=="sboxf") {

                Vector<String> params = param.split(",");
                if (params.size()<2) {

                    memdelete(f);
                    ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid param count for sboxf(): '"+right+"'.");
                    ERR_FAIL_V(RES());

                }

                Ref<StyleBoxFlat> sbflat( memnew(StyleBoxFlat) );

                if (!params[0].is_valid_integer()) {

                    memdelete(f);
                    ERR_EXPLAIN(p_path+":"+itos(line)+": Expected integer numeric constant for parameter 0 (border size).");
                    ERR_FAIL_V(RES());

                }

                sbflat->set_border_size(params[0].to_int());

                if (!params[0].is_valid_integer()) {

                    memdelete(f);
                    ERR_EXPLAIN(p_path+":"+itos(line)+": Expected integer numeric constant for parameter 0 (border size).");
                    ERR_FAIL_V(RES());

                }


                int left = MIN( params.size()-1, 3 );

                int ccodes=0;

                for(int i=0; i<left; i++) {

                    if (params[i+1].is_valid_html_color())
                        ccodes++;
                    else
                        break;
                }

                Color normal;
                Color bright;
                Color dark;

                if (ccodes<1) {
                    memdelete(f);
                    ERR_EXPLAIN(p_path+":"+itos(line)+": Expected at least 1, 2 or 3 html color codes.");
                    ERR_FAIL_V(RES());
                } else if (ccodes==1) {

                    normal=Color::html(params[1]);
                    bright=Color::html(params[1]);
                    dark=Color::html(params[1]);
                } else if (ccodes==2) {

                    normal=Color::html(params[1]);
                    bright=Color::html(params[2]);
                    dark=Color::html(params[2]);
                } else {

                    normal=Color::html(params[1]);
                    bright=Color::html(params[2]);
                    dark=Color::html(params[3]);
                }

                sbflat->set_dark_color(dark);
                sbflat->set_light_color(bright);
                sbflat->set_bg_color(normal);

                if (params.size()==ccodes+5) {
                    //margins
                    for(int i=0; i<4; i++) {

                        if (!params[i+ccodes+1].is_valid_integer()) {
                            memdelete(f);
                            ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid expand margin parameter for sboxf #"+itos(i+ccodes+1) +", expected integer constant, got: '"+params[i+ccodes+1]+"'.");
                            ERR_FAIL_V(RES());
                        }

//						int margin = params[i+ccodes+1].to_int();
                        //sbflat->set_margin_size(Margin(i),margin);
                    }
                } else if (params.size()!=ccodes+1) {
                    memdelete(f);
                    ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid amount of margin parameters for sboxt.");
                    ERR_FAIL_V(RES());

                }


                value=sbflat;

            } else {
                memdelete(f);
                ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid constructor type: '"+type+"'.");
                ERR_FAIL_V(RES());

            }

        }


        //parse left and do something with it
        String left= l.substr(0,eqpos);

        if (reading_library) {

            left=left.strip_edges();
            if (!left.is_valid_identifier()) {
                memdelete(f);
                ERR_EXPLAIN(p_path+":"+itos(line)+": <LibraryItem> is not a valid identifier.");
                ERR_FAIL_V(RES());
            }
            if (library.has(left)) {
                memdelete(f);
                ERR_EXPLAIN(p_path+":"+itos(line)+": Already in library: '"+left+"'.");
                ERR_FAIL_V(RES());
            }

            library[left]=value;
        } else {

            int pointpos = left.find(".");
            if (pointpos==-1) {
                memdelete(f);
                ERR_EXPLAIN(p_path+":"+itos(line)+": Expected 'control.item=..' assign syntax.");
                ERR_FAIL_V(RES());
            }

            String control=left.substr(0,pointpos).strip_edges();
            if (!control.is_valid_identifier()) {
                memdelete(f);
                ERR_EXPLAIN(p_path+":"+itos(line)+": <Control> is not a valid identifier.");
                ERR_FAIL_V(RES());
            }
            String item=left.substr(pointpos+1,left.size()).strip_edges();
            if (!item.is_valid_identifier()) {
                memdelete(f);
                ERR_EXPLAIN(p_path+":"+itos(line)+": <Item> is not a valid identifier.");
                ERR_FAIL_V(RES());
            }

            if (value.get_type()==Variant::NIL) {
                //try to use exiting
                if (Theme::get_default()->has_stylebox(item,control))
                    value=Theme::get_default()->get_stylebox(item,control);
                else if (Theme::get_default()->has_font(item,control))
                    value=Theme::get_default()->get_font(item,control);
                else if (Theme::get_default()->has_icon(item,control))
                    value=Theme::get_default()->get_icon(item,control);
                else if (Theme::get_default()->has_color(item,control))
                    value=Theme::get_default()->get_color(item,control);
                else if (Theme::get_default()->has_constant(item,control))
                    value=Theme::get_default()->get_constant(item,control);
                else {
                    memdelete(f);
                    ERR_EXPLAIN(p_path+":"+itos(line)+": Default not present for: '"+control+"."+item+"'.");
                    ERR_FAIL_V(RES());
                }

            }

            if (value.get_type()==Variant::OBJECT) {

                Ref<Resource> res = value;
                if (!res.is_valid()) {

                    memdelete(f);
                    ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid resource (NULL).");
                    ERR_FAIL_V(RES());
                }

                if (res->cast_to<StyleBox>()) {

                    theme->set_stylebox(item,control,res);
                } else if (res->cast_to<Font>()) {
                    theme->set_font(item,control,res);
                } else if (res->cast_to<Font>()) {
                    theme->set_font(item,control,res);
                } else if (res->cast_to<Texture>()) {
                    theme->set_icon(item,control,res);
                } else {
                    memdelete(f);
                    ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid resource type.");
                    ERR_FAIL_V(RES());
                }
            } else if (value.get_type()==Variant::COLOR) {

                theme->set_color(item,control,value);

            } else if (value.get_type()==Variant::INT) {

                theme->set_constant(item,control,value);

            } else {

                memdelete(f);
                ERR_EXPLAIN(p_path+":"+itos(line)+": Couldn't even determine what this setting is! what did you do!?");
                ERR_FAIL_V(RES());
            }

        }


    }

    f->close();
    memdelete(f);

    if (r_error)
        *r_error=OK;

    return theme;
}