bool LayerComponent::init(const std::string& filename, const Vector2f& offset)
{

	FileInputStream mapStream;
	if (!mapStream.open(filename))
	{
		err() << "loadMap: could not open file " << filename << endl;
		return false;
	}

	// convert FileInputStream to char* mapBuffer
	char* mapBuffer = new char[mapStream.getSize() + 1];
	mapStream.read(mapBuffer, mapStream.getSize());
	mapBuffer[mapStream.getSize()] = '\0';

	// now lets load a NLTmxMap
	NLTmxMap* tilemap = NLLoadTmxMap(mapBuffer);
	delete mapBuffer;

	err() << "Load tilemap with size: " << tilemap->width << ", "
		<< tilemap->height << " and tilesize: " << tilemap->tileWidth
		<< ", " << tilemap->tileHeight << std::endl;

	// load textures for every tileset
	for (auto tileset : tilemap->tilesets)
	{
		err() << "Load tileset: " << tileset->name << " width filename: "
			<< tileset->filename << " and tilesize: " << tileset->tileWidth
			<< ", " << tileset->tileHeight << std::endl;

		auto texture = make_shared<Texture>();
		if (!texture->loadFromFile(m_resourcePath + tileset->filename))
			err() << "Could not load texture " << m_resourcePath + tileset->filename << endl;
		m_tilesetTexture[tileset->name] = texture;
	}

	// go through all layers
	m_layers.resize(tilemap->layers.size());

	for (int layerIdx = 0; layerIdx < (int)tilemap->layers.size(); layerIdx++)
	{
		NLTmxMapLayer* layer = tilemap->layers[layerIdx];
		err() << "Load layer: " << layer->name << " with width: "
			<< layer->width << " and height: " << layer->height << std::endl;

		int size = layer->width * layer->height;

		// go over all elements in the layer
		for (int i = 0; i < size; i++)
		{
			int grid = layer->data[i];

			if (grid == 0)	continue;

			// get tileset and tileset texture
			NLTmxMapTileset* tileset = tilemap->getTilesetForGrid(grid);
			Vector2i tileSize(tilemap->tileWidth, tilemap->tileHeight);
			TexturePtr texture = m_tilesetTexture[tileset->name];
			assert(texture != nullptr);

			// horizontal tile count in tileset texture
			int tileCountX = texture->getSize().x / tileSize.x;

			// calcualte position of tile
			Vector2f position;
			position.x = (i % layer->width) * (float)tileSize.x;
			position.y = (i / layer->width) * (float)tileSize.y;
			position += offset;

			// calculate 2d idx of tile in tileset texture
			int idx = grid - tileset->firstGid;
			int idxX = idx % tileCountX;
			int idxY = idx / tileCountX;

			// calculate source area of tile in tileset texture
			IntRect source(idxX * tileSize.x, idxY * tileSize.y, tileSize.x, tileSize.y);

			// TODO create tile and put it into a layer
			auto sprite = make_shared<Sprite>();
			sprite->setTexture(*texture);
			sprite->setTextureRect(source);
			sprite->setPosition(position.x, position.y);

			m_layers[layerIdx].push_back(sprite);
		}
	}

	// go through all object layers
	for (auto group : tilemap->groups)
	{
		// go over all objects per layer
		for (auto object : group->objects)
		{
			Vector2f position(object->x, object->y);
			position += offset;

			FloatRect bounds(position.x, position.y, object->width, object->height);

			// TODO create object
			if (object->type == "Sprite")
			{
				auto sprite = loadSprite(object);
				m_objects[object->name] = sprite;
			}
		}
	}
	return true;
}
Example #2
0
Repository::Repository()
{
    loadFromFile();
}
Example #3
0
  bool Cursynth::textInput(int key) {
    if (state_ == PATCH_LOADING) {
      int num_patches = patches_.size();
      switch(key) {
        case '\n':
          // Finish loading patches.
          state_ = STANDARD;
          gui_.clearPatches();
          return true;
        case KEY_UP:
          // Go to previous patch.
          patch_load_index_ = CLAMP(patch_load_index_ - 1, 0, num_patches - 1);
          gui_.drawPatchLoading(patches_, patch_load_index_);
          loadFromFile(patches_[patch_load_index_]);
          return true;
        case KEY_DOWN:
          // Go to next patch.
          patch_load_index_ = CLAMP(patch_load_index_ + 1, 0, num_patches - 1);
          gui_.drawPatchLoading(patches_, patch_load_index_);
          loadFromFile(patches_[patch_load_index_]);
          return true;
      }
    }

    std::string current_control = gui_.getCurrentControl();
    Control* control = controls_.at(current_control);
    bool should_redraw_control = false;
    lock();
    switch(key) {
      case 'H':
      case KEY_F(1):
        startHelp();
        break;
      case 'S':
        startSave();
        break;
      case 'L':
        startLoad();
        break;
      case 'M':
      case 'm':
        if (state_ != MIDI_LEARN)
          state_ = MIDI_LEARN;
        else
          state_ = STANDARD;
        should_redraw_control = true;
        break;
      case 'C':
      case 'c':
        eraseMidiLearn(control);
        state_ = STANDARD;
        should_redraw_control = true;
        break;
      case KEY_UP:
        current_control = gui_.getPrevControl();
        state_ = STANDARD;
        gui_.drawControl(control, false);
        should_redraw_control = true;
        break;
      case KEY_DOWN:
        current_control = gui_.getNextControl();
        state_ = STANDARD;
        gui_.drawControl(control, false);
        should_redraw_control = true;
        break;
      case KEY_RIGHT:
        control->increment();
        should_redraw_control = true;
        break;
      case KEY_LEFT:
        control->decrement();
        should_redraw_control = true;
        break;
      default:
        // Check if they pressed the slider keys and change the current value.
        size_t slider_size = strlen(SLIDER) - 1;
        for (size_t i = 0; i <= slider_size; ++i) {
          if (SLIDER[i] == key) {
            control->setPercentage((1.0 * i) / slider_size);
            should_redraw_control = true;
            break;
          }
        }

        // Check if they pressed note keys and play the corresponding note.
        for (size_t i = 0; i < strlen(KEYBOARD); ++i) {
          if (KEYBOARD[i] == key) {
            synth_.noteOn(48 + i);
            break;
          }
        }
    }

    if (should_redraw_control) {
      control = controls_.at(current_control);
      gui_.drawControl(control, true);
      gui_.drawControlStatus(control, state_ == MIDI_LEARN);
    }

    unlock();
    return true;
  }
void HippoGridManager::discardAndReload()
{
	cleanup();
	loadFromFile();
}
Example #5
0
int main(int argc, char** argv) {
    FILE*   fileIn  = NULL;
    FILE*   fileOut = NULL;
    Symbol  symbols[ARRAY_LENGTH];
    Symbol* symbolsOrd[ARRAY_LENGTH]; //ordered pointers (by frequency)

    u64 fileLen = 0;

    BinTree* temp[2];
    BinTree* root;
    Stack    stack;

    if ( !argv[1] ) {
        printHelp();
        return EXIT_FAIL;
    }

    if ( !strcmp(argv[1], "-e") || !strcmp("--encode", argv[1]) ) {
        if ( !argv[2] || !argv[3] ) {
            printHelp();
            return EXIT_FAIL;
        }

        fileIn  = (FILE*)fopen(argv[2], "rt");
        if ( !fileIn ) {
            printf("Error: file <<%s>> doesn't exists\n", argv[2]);
            return EXIT_FAIL;
        }

        stackInit(&stack);
        initializeArrays(symbols, symbolsOrd, ARRAY_LENGTH);

        fileLen = readFile(fileIn, symbols); //read symbols; first pass
        if ( fileLen == 0 ) {
            printf("Error: file <<%s>> is empty\n", argv[2]);
            fclose(fileIn);
            return EXIT_FAIL;
        }

        fileOut = (FILE*)fopen(argv[3], "wb");
        if ( !fileOut ) {
            printf("Error: cannot create file <<%s>>\n", argv[3]);
            fclose(fileIn);
            return EXIT_FAIL;
        }

        //sort symbols by frequencies from lower to greatest
        qsort(symbolsOrd, ARRAY_LENGTH, sizeof(Symbol*), compareSym);
        fillStack(symbolsOrd, &stack, ARRAY_LENGTH); //prepare stack

        root = buildTree(&stack);

        createPath(root, 0); //0 - starting depth

        rewind(fileIn); //reopen fileIn; prepare second pass

        //write all compressed data
        saveToFile(fileIn, fileOut, symbols, root, argv[2], fileLen);

        //memory cleanup
        binTreeRemove(root);

        fclose(fileOut);
        fclose(fileIn);
    } else if ( !strcmp(argv[1], "-d") || !strcmp("--decode", argv[1]) ) {
        if ( !argv[2] ) {
            printHelp();
            return EXIT_FAIL;
        }

        fileIn = fopen(argv[2], "rb");
        if ( !fileIn ) {
            printf("Error: file <<%s>> doesn't exists\n", argv[2]);
            return EXIT_FAIL;
        }

        if ( !loadFromFile(fileIn, argv[3] ? argv[3] : NULL) ) {
            printf("Error: file <<%s>> corrupted or cannot create file <<%s>>\n",
                argv[2], argv[3]);
            fclose(fileIn);
            return EXIT_FAIL;
        }

        fclose(fileIn);
    } else {
        printHelp();
    }
    

    return EXIT_SUCCESS;
}
Example #6
0
TEST_F(LayouterOpsTest, load_layout_replace) {
  std::string data = loadFromFile("test/json/load_layout_replace.json");
  const auto& e = executeAndWait(data);
  ASSERT_EQ(e->partitionCount(), 3u);
  ASSERT_EQ(3u, StorageManager::getInstance()->getTable("revenue")->partitionCount());
}
Example #7
0
void ofxGuiGroup::load(){
    loadFromFile( filename );
}
Example #8
0
CSVMap* CSVFormatter::loadFromFile(const std::string& path, UChar32 sepchar, unsigned int headercount, const char* encoding) {
	return loadFromFile(path.c_str(), sepchar, headercount, encoding);
}
Example #9
0
CSVMap* CSVFormatter::loadFromFile(const UnicodeString& path, UChar32 sepchar, unsigned int headercount, const char* encoding) {
	std::string temp;
	path.toUTF8String(temp);
	return loadFromFile(temp.c_str(), sepchar, headercount, encoding);
}
Example #10
0
TEST_F(LoadTests, simple_query_with_load_with_header) {
  std::string q = loadFromFile("test/json/simple_query_load_with_header.json");
  const auto& out = executeAndWait(q);
  ASSERT_TRUE((bool)out);
  StorageManager::getInstance()->removeAll();
}
Example #11
0
TEST_F(LoadTests, load_exception) {
  std::string q = loadFromFile("test/json/load_exception.json");
  ASSERT_THROW( {
      executeAndWait(q);
    }, std::runtime_error);
Example #12
0
AddressBook::AddressBook(QWidget *parent)
    : QWidget(parent)
{
    QLabel *nameLabel = new QLabel(tr("Имя:"));         // создаем объект  QLabel nameLabel (поле ввода имени)
    nameLine = new QLineEdit;
    nameLine->setReadOnly(true);    // устанавливаем в режим только для чтения

    QLabel *addressLabel = new QLabel(tr("Адрес:"));  // создаем объект  QLabel addressLabel (поле ввода адреса)
    addressText = new QTextEdit;
    addressText->setReadOnly(true); // устанавливаем в режим только для чтения

    addButton = new QPushButton(tr("&Добавить"));        //  создаем экземпляр кнопоки
    addButton->show();                              //  устанавливаем ее отображение на экране после вызова функции show
    submitButton = new QPushButton(tr("&Принять"));  //  создаем экземпляр кнопоки
    submitButton->hide();                           //  устанавливаем ее отображение на экране после вызова функции hide(после нажатия кнопки "Add")
    cancelButton = new QPushButton(tr("&Отмена"));  //  создаем экземпляр кнопоки
    cancelButton->hide();                           //  устанавливаем ее отображение на экране после вызова функции hide(после нажатия кнопки "Add")

    nextButton = new QPushButton(tr("&Следующий"));      //  создаем экземпляр кнопки
    nextButton->setEnabled(false);                  //  отключаем ее
    previousButton = new QPushButton(tr("&Предыдущий"));
    previousButton->setEnabled(false);

    editButton = new QPushButton(tr("&Изменить"));
    editButton->setEnabled(false);
    removeButton = new QPushButton(tr("&Удалить"));
    removeButton->setEnabled(false);

    findButton = new QPushButton(tr("&Найти"));
    findButton->setEnabled(false);

    loadButton = new QPushButton(tr("&Загрузить..."));
    loadButton->setToolTip(tr("Загрузка контактов из файла"));
    saveButton = new QPushButton(tr("&Сохранить..."));
    saveButton->setToolTip(tr("Сохранить контакты в файл"));
    saveButton->setEnabled(false);

    cloudButton = new QPushButton(tr("&Хранилище"));
    cloudButton->setEnabled(false);
    webView = new QWebView;

    dialog = new finddialog;        // создаем объект (для отображения)

    connect(addButton, SIGNAL(clicked()), this, SLOT(addContact()));            //
    connect(submitButton, SIGNAL(clicked()), this, SLOT(submitContact()));      // Соединяем кнопки с соответствующими им слотами (при нажатии срабатывает SLOT, который вызывает функцию)
    connect(cancelButton, SIGNAL(clicked()), this, SLOT(cancel()));             //

    connect(nextButton, SIGNAL(clicked()), this, SLOT(next()));
    connect(previousButton, SIGNAL(clicked()), this, SLOT(previous()));

    connect(editButton, SIGNAL(clicked()), this, SLOT(editContact()));
    connect(removeButton, SIGNAL(clicked()), this, SLOT(removeContact()));

    connect(findButton, SIGNAL(clicked()), this, SLOT(findContact()));

    connect(loadButton, SIGNAL(clicked()), this, SLOT(loadFromFile()));
    connect(saveButton, SIGNAL(clicked()), this, SLOT(saveToFile()));

    connect(cloudButton, SIGNAL(clicked()), this, SLOT(cloudStorage()));

    QVBoxLayout *buttonLayout1 = new QVBoxLayout;       // Вертикальное расположение кнопок
    buttonLayout1->addWidget(addButton, Qt::AlignTop);  //  Расположение кнопок виджета
    buttonLayout1->addWidget(submitButton);             //
    buttonLayout1->addWidget(cancelButton);             //
    buttonLayout1->addWidget(editButton);
    buttonLayout1->addWidget(removeButton);
    buttonLayout1->addWidget(findButton);
    buttonLayout1->addWidget(loadButton);
    buttonLayout1->addWidget(saveButton);
    buttonLayout1->addWidget(cloudButton);
    buttonLayout1->addStretch();                        //  чтобы расположить кнопки ближе к верхней части виджета

    QHBoxLayout *buttonLayout2 = new QHBoxLayout;       // Горизонтальное расположение кнопок
    buttonLayout2->addWidget(previousButton);
    buttonLayout2->addWidget(nextButton);

    QGridLayout *mainLayout = new QGridLayout;          // Табличное размещение (таблица состоит из ячеек, позиции которых задаютсяф строками и столбцами)
    mainLayout->addWidget(nameLabel, 0, 0);             // поле ввода имени (в верхнем правом углу)
    mainLayout->addWidget(nameLine, 0, 1);
    mainLayout->addWidget(addressLabel, 1, 0, Qt::AlignTop); // Qt::AllignTop дополнительный параметр, который отвечает за расположение (чтобы поле располагалось не по центру)
    mainLayout->addWidget(addressText, 1, 1);
    mainLayout->addLayout(buttonLayout1, 1, 2);
    mainLayout->addLayout(buttonLayout2, 2, 1);

    setLayout(mainLayout);       // вызывает компоновку виджета
    setWindowTitle(tr("Адресная книга")); // название заголовка виджета

}
Example #13
0
AddressBook::AddressBook(QWidget *parent)
    : QWidget(parent)
{
    QLabel *nameLabel = new QLabel(tr("Name:"));
    nameLine = new QLineEdit;
    nameLine->setReadOnly(true);

    QLabel *addressLabel = new QLabel(tr("Address:"));
    addressText = new QTextEdit;
    addressText->setReadOnly(true);

    addButton = new QPushButton(tr("&Add"));

    editButton = new QPushButton(tr("&Edit"));
    editButton->setEnabled(false);
    removeButton = new QPushButton(tr("&Remove"));
    removeButton->setEnabled(false);
    findButton = new QPushButton(tr("&Find"));
    findButton->setEnabled(false);
    submitButton = new QPushButton(tr("&Submit"));
    submitButton->hide();
    cancelButton = new QPushButton(tr("&Cancel"));
    cancelButton->hide();

    nextButton = new QPushButton(tr("&Next"));
    nextButton->setEnabled(false);
    previousButton = new QPushButton(tr("&Previous"));
    previousButton->setEnabled(false);

    loadButton = new QPushButton(tr("&Load..."));
//! [tooltip 1]    
    loadButton->setToolTip(tr("Load contacts from a file"));
//! [tooltip 1]        
    saveButton = new QPushButton(tr("Sa&ve..."));
//! [tooltip 2]
    saveButton->setToolTip(tr("Save contacts to a file"));
//! [tooltip 2]
    saveButton->setEnabled(false);

    dialog = new FindDialog;

    connect(addButton, SIGNAL(clicked()), this, SLOT(addContact()));
    connect(submitButton, SIGNAL(clicked()), this, SLOT(submitContact()));
    connect(editButton, SIGNAL(clicked()), this, SLOT(editContact()));
    connect(cancelButton, SIGNAL(clicked()), this, SLOT(cancel()));
    connect(removeButton, SIGNAL(clicked()), this, SLOT(removeContact()));
    connect(findButton, SIGNAL(clicked()), this, SLOT(findContact()));
    connect(nextButton, SIGNAL(clicked()), this, SLOT(next()));
    connect(previousButton, SIGNAL(clicked()), this, SLOT(previous()));
    connect(loadButton, SIGNAL(clicked()), this, SLOT(loadFromFile()));
    connect(saveButton, SIGNAL(clicked()), this, SLOT(saveToFile()));
    
    QVBoxLayout *buttonLayout1 = new QVBoxLayout;
    buttonLayout1->addWidget(addButton);
    buttonLayout1->addWidget(editButton);
    buttonLayout1->addWidget(removeButton);
    buttonLayout1->addWidget(findButton);
    buttonLayout1->addWidget(submitButton);
    buttonLayout1->addWidget(cancelButton);
    buttonLayout1->addWidget(loadButton);
    buttonLayout1->addWidget(saveButton);
    buttonLayout1->addStretch();

    QHBoxLayout *buttonLayout2 = new QHBoxLayout;
    buttonLayout2->addWidget(previousButton);
    buttonLayout2->addWidget(nextButton);

    QGridLayout *mainLayout = new QGridLayout;
    mainLayout->addWidget(nameLabel, 0, 0);
    mainLayout->addWidget(nameLine, 0, 1);
    mainLayout->addWidget(addressLabel, 1, 0, Qt::AlignTop);
    mainLayout->addWidget(addressText, 1, 1);
    mainLayout->addLayout(buttonLayout1, 1, 2);
    mainLayout->addLayout(buttonLayout2, 2, 1);

    setLayout(mainLayout);
    setWindowTitle(tr("Simple Address Book"));
}
Example #14
0
u32 CIrrOdeWorld::setSurfaceXml(const wchar_t *sName) {
    m_sSurfaceFile=irr::core::stringw(sName);
    return loadFromFile(sName);
}
Example #15
0
void QHexEdit::dropEvent(QDropEvent *event)
{
    QString path = event->mimeData()->urls().at(0).toLocalFile();
    loadFromFile(path);
}
void FSData::processResponder(const LLSD& content, const std::string& url, bool save_to_file, const LLDate& last_modified)
{
	if (url == mFSDataURL)
	{
		if (!save_to_file)
		{
			LLSD data;
			LL_DEBUGS("fsdata") << "Loading fsdata.xml from  " << mFSdataFilename << LL_ENDL;
			if (loadFromFile(data, mFSdataFilename))
			{
				processData(data);
			}
			else
			{
				LL_WARNS("fsdata") << "Unable to download or load fsdata.xml" << LL_ENDL;
			}
		}
		else
		{
			processData(content);
			saveLLSD(content , mFSdataFilename, last_modified);
		}
		mFSDataDone = true;
	}
	else if (url == mAssetsURL)
	{
		if (!save_to_file)
		{
			LLSD data;
			LL_DEBUGS("fsdata") << "Loading assets.xml from  " << mAssestsFilename << LL_ENDL;
			if (loadFromFile(data, mAssestsFilename))
			{
				processAssets(data);
			}
			else
			{
				LL_WARNS("fsdata") << "Unable to download or load assets.xml" << LL_ENDL;
			}
		}
		else
		{
			processAssets(content);
			saveLLSD(content , mAssestsFilename, last_modified);
		}
	}
	else if (url == mAgentsURL)
	{
		if (!save_to_file)
		{
			LLSD data;
			LL_DEBUGS("fsdata") << "Loading agents.xml from  " << mAgentsFilename << LL_ENDL;
			if (loadFromFile(data, mAgentsFilename))
			{
				processAgents(data);
			}
			else
			{
				LL_WARNS("fsdata") << "Unable to download or load agents.xml" << LL_ENDL;
			}
		}
		else
		{
			processAgents(content);
			saveLLSD(content , mAgentsFilename, last_modified);
		}
		mAgentsDone = true;
		addAgents();
	}
	else if (url == LEGACY_CLIENT_LIST_URL)
	{
		if (!save_to_file)
		{
			updateClientTagsLocal();
		}
		else
		{
			processClientTags(content);
			saveLLSD(content , mClientTagsFilename, last_modified);
		}
	}
	else if (url == mFSdataDefaultsUrl)
	{
		if (!save_to_file)
		{
			// do nothing as this file is loaded during app startup.
		}
		else
		{
			saveLLSD(content , mFSdataDefaultsFilename, last_modified);
		}
	}
}
Database::Database()
{
    this->filename = "items.xml";
    loadFromFile();    
}
bool ServerNameIndication::setCTXFromFile(SSL *ssl, const std::string &name) {
  return s_certHandlerFn &&
    loadFromFile(name, s_certHandlerFn) && setCTXFromMemory(ssl, name);
  return false;
}