<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2017 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef NET_IP4_CIDR_HPP
#define NET_IP4_CIDR_HPP

#include "addr.hpp"

namespace net {
namespace ip4 {

class Cidr {
public:
  Cidr(uint8_t p1, uint8_t p2, uint8_t p3, uint8_t p4, uint8_t mask)
  {
    uint32_t ip_whole = Addr{p1,p2,p3,p4}.whole;
    uint32_t ip_mask = net::ntohl((0xFFFFFFFFUL << (32 - mask)) & 0xFFFFFFFFUL);

    uint32_t from_ip = ip_whole & ip_mask;
    uint32_t to_ip = from_ip | ~ip_mask;

    from_ = Addr{from_ip};
    to_ = Addr{to_ip};
  }

  // Possibly not necessary
  Cidr(Addr from, Addr to)
  : from_{from}, to_{to}
  {}

  bool contains(Addr ip) {
    return ip >= from_ and ip <= to_;
  }

  Addr from() {
    return from_;
  }

  Addr to() {
    return to_;
  }

private:
  Addr from_; // network address
  Addr to_;   // broadcast address
}; //< class Cidr

} //< namespace ip4
} //< namespace net

#endif
<commit_msg>IPv4 Cidr: Adding missing const and noexcept, and specifying constexpr on constructor<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2017 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef NET_IP4_CIDR_HPP
#define NET_IP4_CIDR_HPP

#include "addr.hpp"

namespace net {
namespace ip4 {

class Cidr {
public:

  /**
   * @brief      Constructor
   *
   * Create an IPv4 cidr object to represent the cidr <p1.p2.p3.p4/mask>
   *
   * @param[in]  p1    The first part of the IPv4 cidr
   * @param[in]  p2    The second part of the IPv4 cidr
   * @param[in]  p3    The third part of the IPv4 cidr
   * @param[in]  p4    The fourth part of the IPv4 cidr
   * @param[in]  mask  A number between 0 and 32, representing the number
   *                    of leading 1 bits in the netmask, f.ex.:
   *                    32 represents the netmask 255.255.255.255
   *                    24 represents the netmask 255.255.255.0
   */
  constexpr Cidr(const uint8_t p1, const uint8_t p2, const uint8_t p3, const uint8_t p4,
    const uint8_t mask) noexcept
  {
    Expects(mask >= 0 and mask <= 32);

    const uint32_t ip_whole = Addr{p1,p2,p3,p4}.whole;
    const uint32_t ip_mask = net::ntohl((0xFFFFFFFFUL << (32 - mask)) & 0xFFFFFFFFUL);

    const uint32_t from_ip = ip_whole & ip_mask;
    const uint32_t to_ip = from_ip | ~ip_mask;

    from_ = Addr{from_ip};
    to_ = Addr{to_ip};
  }

  bool contains(Addr ip) const noexcept {
    return ip >= from_ and ip <= to_;
  }

  Addr from() const noexcept {
    return from_;
  }

  Addr to() const noexcept {
    return to_;
  }

private:
  Addr from_; // network address
  Addr to_;   // broadcast address
}; //< class Cidr

} //< namespace ip4
} //< namespace net

#endif
<|endoftext|>


<commit_before>#include <QtGlobal>
#include <QDir>
#include <QFileInfo>
#include <QSettings>
#include <QDebug>
#include <QIcon>

#include "icontheme.h"

QStringList IconTheme::base_dirs = QIcon::themeSearchPaths();

IconTheme::IconTheme(const QString &theme_name): theme_name(theme_name)
{
    if (theme_name.isNull()) {
        return;
    }
    for (const QString &dir: base_dirs) {
        if (!QFileInfo::exists(QString("%1/%2/index.theme").arg(dir).arg(theme_name))) {
            continue;
        }
        base_path = dir + "/" + theme_name;
        break;
    }
    // theme directory not found or doesn't contain index.theme file
    if (base_path.isNull()) {
        qDebug() << "index.theme not found";
        return;
    }
    QSettings theme_index(base_path + "/index.theme", QSettings::IniFormat);
    theme_index.beginGroup("Icon Theme");
    display_name = theme_index.value("Name").toString();
    parent_themes = theme_index.value("Inherits").toStringList();
    QStringList dir_list = theme_index.value("Directories").toStringList();
    theme_dirs.reserve(dir_list.size());
    for (const QString &dir: dir_list) {
        theme_index.beginGroup(dir);
        int size = theme_index.value("Size", 0).toInt();
        theme_dirs.append(Directory{
            size,
            theme_index.value("Scale", 1).toInt(),
            theme_index.value("Context", "").toString(),
            theme_index.value("Type", "Threshold").toString(),
            theme_index.value("MaxSize", size).toInt(),
            theme_index.value("MinSize", size).toInt(),
            theme_index.value("Threshold", 2).toInt(),
            dir
        });
        theme_index.endGroup();
    }
    // load icons
    for (int i = 0, len = theme_dirs.size(); i < len; i++) {
        QDir dir(base_path + "/" + theme_dirs[i].path);
        for (const QFileInfo &icon: dir.entryInfoList({"*.png", "*.svg", "*.xpm"}, QDir::Files | QDir::Readable)) {
            QString icon_name = icon.completeBaseName();
            QString ext = icon.suffix();
            FileExtension ext_type = FileExtension::XPM;
            if (ext == "png")
                ext_type = FileExtension::PNG;
            else if (ext == "svg")
                ext_type = FileExtension::SVG;
            theme_icons[icon_name].append(std::pair<uint, FileExtension>{i, ext_type});
        }
    }
}

QStringList IconTheme::themes()
{
    QSet<QString> themes;
    for (QDir dir: base_dirs) {
        // skip embedded themes
        if (dir.path().startsWith(':'))
            continue;
        for (const QString& theme: dir.entryList(QDir::Dirs | QDir::Readable |
                                                 QDir::NoDotAndDotDot))
        {
            if (!QFileInfo::exists(dir.filePath(theme + "/index.theme")))
                continue;
            themes += theme;
        }
    }
    return themes.toList();
}

void IconTheme::add_themes_dir(const QString &path)
{
    base_dirs.append(path);
    QIcon::setThemeSearchPaths(base_dirs);
}

void IconTheme::add_themes_dirs(const QStringList &paths)
{
    base_dirs.append(paths);
    QIcon::setThemeSearchPaths(base_dirs);
}

void IconTheme::set_themes_dirs(const QStringList &paths)
{
    base_dirs = paths;
    QIcon::setThemeSearchPaths(base_dirs);
}

<commit_msg>Fixed issue with directory information was not loading<commit_after>#include <QtGlobal>
#include <QDir>
#include <QFileInfo>
#include <QSettings>
#include <QDebug>
#include <QIcon>

#include "icontheme.h"

QStringList IconTheme::base_dirs = QIcon::themeSearchPaths();

IconTheme::IconTheme(const QString &theme_name): theme_name(theme_name)
{
    if (theme_name.isNull()) {
        return;
    }
    for (const QString &dir: base_dirs) {
        if (!QFileInfo::exists(QString("%1/%2/index.theme").arg(dir).arg(theme_name))) {
            continue;
        }
        base_path = dir + "/" + theme_name;
        break;
    }
    // theme directory not found or doesn't contain index.theme file
    if (base_path.isNull()) {
        qDebug() << "index.theme not found";
        return;
    }
    QSettings theme_index(base_path + "/index.theme", QSettings::IniFormat);
    theme_index.beginGroup("Icon Theme");
    display_name = theme_index.value("Name").toString();
    parent_themes = theme_index.value("Inherits").toStringList();
    QStringList dir_list = theme_index.value("Directories").toStringList();
    theme_index.endGroup();

    theme_dirs.reserve(dir_list.size());
    for (const QString &dir: dir_list) {
        theme_index.beginGroup(dir);
        int size = theme_index.value("Size", 0).toInt();
        theme_dirs.append(Directory{
            size,
            theme_index.value("Scale", 1).toInt(),
            theme_index.value("Context", "").toString(),
            theme_index.value("Type", "Threshold").toString(),
            theme_index.value("MaxSize", size).toInt(),
            theme_index.value("MinSize", size).toInt(),
            theme_index.value("Threshold", 2).toInt(),
            dir
        });
        theme_index.endGroup();
    }
    // load icons
    for (int i = 0, len = theme_dirs.size(); i < len; i++) {
        QDir dir(base_path + "/" + theme_dirs[i].path);
        for (const QFileInfo &icon: dir.entryInfoList({"*.png", "*.svg", "*.xpm"}, QDir::Files | QDir::Readable)) {
            QString icon_name = icon.completeBaseName();
            QString ext = icon.suffix();
            FileExtension ext_type = FileExtension::XPM;
            if (ext == "png")
                ext_type = FileExtension::PNG;
            else if (ext == "svg")
                ext_type = FileExtension::SVG;
            theme_icons[icon_name].append(std::pair<uint, FileExtension>{i, ext_type});
        }
    }
}

QStringList IconTheme::themes()
{
    QSet<QString> themes;
    for (QDir dir: base_dirs) {
        // skip embedded themes
        if (dir.path().startsWith(':'))
            continue;
        for (const QString& theme: dir.entryList(QDir::Dirs | QDir::Readable |
                                                 QDir::NoDotAndDotDot))
        {
            if (!QFileInfo::exists(dir.filePath(theme + "/index.theme")))
                continue;
            themes += theme;
        }
    }
    return themes.toList();
}

void IconTheme::add_themes_dir(const QString &path)
{
    base_dirs.append(path);
    QIcon::setThemeSearchPaths(base_dirs);
}

void IconTheme::add_themes_dirs(const QStringList &paths)
{
    base_dirs.append(paths);
    QIcon::setThemeSearchPaths(base_dirs);
}

void IconTheme::set_themes_dirs(const QStringList &paths)
{
    base_dirs = paths;
    QIcon::setThemeSearchPaths(base_dirs);
}

<|endoftext|>


<commit_before>
#include "async_modbus_task.h"

using namespace v8;

class ReadRegistersTask : public AsyncModbusTask
{
private:

	const int address_;

	const int register_count_;

	//! The result of reading.
	uint16_t* const results_;

	int registers_read_;

public:

	ReadRegistersTask(modbus_t* context, int address, int register_count, const Persistent<Function>& callback)
	: AsyncModbusTask(context, callback),
	  address_(address),
	  register_count_(register_count),
	  results_(new uint16_t[register_count]),
	  registers_read_(0);
	{
	}

	virtual ~ReadRegistersTask()
	{
		delete [] results_;
	}

	virtual void work()
	{
		const int r = modbus_read_registers(context_, address_, register_count_, results_);

		if( -1 == r )
		{
			setModbusError(errno);
		}
		else
		{
			registers_read_ = r;
		}
	}

	virtual void after()
	{
		HandleScope scope;

		Local<Value> error = error_flag_ ? Exception::Error(String::New(error_message_.c_str())) : Local<Value>::New(Null());

		v8::Local<v8::Array> register_data = v8::Array::New(registers_read_);

		for( int i=0; i<registers_read_; ++i )
		{
			register_data->Set(i, Integer::New(results_[i]));
		}

		const unsigned argc = 2;

		Local<Value> argv[argc] = {error, register_data};

		TryCatch try_catch;
		{
			callback_->Call(Context::GetCurrent()->Global(), argc, argv);

			if( try_catch.HasCaught() )
			{
				node::FatalException(try_catch);
			}
		}
	}
};

//! Shedules int modbus_read_registers(modbus_t *ctx, int addr, int nb, uint16_t *dest)
Handle<Value> read_registers(const Arguments& args)
{
	HandleScope scope;

	if( args.Length() < 4 )
	{
		return ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));
	}

	if( !args[0]->IsExternal() || !args[1]->IsNumber() || !args[2]->IsNumber() || !args[3]->IsFunction() )
	{
		return ThrowException(Exception::TypeError(String::New("Wrong arguments")));
	}

	modbus_t* const context = static_cast<modbus_t*>(External::Cast(*args[0])->Value());

	if( !context )
	{
		return ThrowException(Exception::Error(String::New("Unable to cast argument to libmodbus context")));
	}

	Local<Function> callback = Local<Function>::Cast(args[3]);

	AsyncModbusTask* const task = new ReadRegistersTask(
					context,				// ctx
					args[1]->Int32Value(),	// addr
					args[2]->Int32Value(),	// nb
					Persistent<Function>::New(callback)
					);

	if( ! task->queue() )
	{
		delete task;

		// TODO: really throw exeception ?
		return ThrowException(Exception::Error(String::New("Unable to queue work request")));
	}

	return Undefined();
}
<commit_msg>bugfix<commit_after>
#include "async_modbus_task.h"

using namespace v8;

class ReadRegistersTask : public AsyncModbusTask
{
private:

	const int address_;

	const int register_count_;

	//! The result of reading.
	uint16_t* const results_;

	int registers_read_;

public:

	ReadRegistersTask(modbus_t* context, int address, int register_count, const Persistent<Function>& callback)
	: AsyncModbusTask(context, callback),
	  address_(address),
	  register_count_(register_count),
	  results_(new uint16_t[register_count]),
	  registers_read_(0)
	{
	}

	virtual ~ReadRegistersTask()
	{
		delete [] results_;
	}

	virtual void work()
	{
		const int r = modbus_read_registers(context_, address_, register_count_, results_);

		if( -1 == r )
		{
			setModbusError(errno);
		}
		else
		{
			registers_read_ = r;
		}
	}

	virtual void after()
	{
		HandleScope scope;

		Local<Value> error = error_flag_ ? Exception::Error(String::New(error_message_.c_str())) : Local<Value>::New(Null());

		v8::Local<v8::Array> register_data = v8::Array::New(registers_read_);

		for( int i=0; i<registers_read_; ++i )
		{
			register_data->Set(i, Integer::New(results_[i]));
		}

		const unsigned argc = 2;

		Local<Value> argv[argc] = {error, register_data};

		TryCatch try_catch;
		{
			callback_->Call(Context::GetCurrent()->Global(), argc, argv);

			if( try_catch.HasCaught() )
			{
				node::FatalException(try_catch);
			}
		}
	}
};

//! Shedules int modbus_read_registers(modbus_t *ctx, int addr, int nb, uint16_t *dest)
Handle<Value> read_registers(const Arguments& args)
{
	HandleScope scope;

	if( args.Length() < 4 )
	{
		return ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));
	}

	if( !args[0]->IsExternal() || !args[1]->IsNumber() || !args[2]->IsNumber() || !args[3]->IsFunction() )
	{
		return ThrowException(Exception::TypeError(String::New("Wrong arguments")));
	}

	modbus_t* const context = static_cast<modbus_t*>(External::Cast(*args[0])->Value());

	if( !context )
	{
		return ThrowException(Exception::Error(String::New("Unable to cast argument to libmodbus context")));
	}

	Local<Function> callback = Local<Function>::Cast(args[3]);

	AsyncModbusTask* const task = new ReadRegistersTask(
					context,				// ctx
					args[1]->Int32Value(),	// addr
					args[2]->Int32Value(),	// nb
					Persistent<Function>::New(callback)
					);

	if( ! task->queue() )
	{
		delete task;

		// TODO: really throw exeception ?
		return ThrowException(Exception::Error(String::New("Unable to queue work request")));
	}

	return Undefined();
}
<|endoftext|>


<commit_before>// Copyright 2010 Google
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "stdio.h"
#include "time.h"

#include "base/logging.h"

namespace google_base {
DateLogger::DateLogger() {
#if defined(_MSC_VER)
  _tzset();
#endif
}

char* const DateLogger::HumanDate() {
#if defined(_MSC_VER)
  _strtime_s(buffer_, sizeof(buffer_));
#else
  time_t time_value = time(NULL);
  struct tm now;
  localtime_r(&time_value, &now);
  snprintf(buffer_, sizeof(buffer_), "%02d:%02d:%02d\0",
           now.tm_hour, now.tm_min, now.tm_sec);
#endif
  return buffer_;
}
}  // namespace google_base
<commit_msg>Fix string format warnings<commit_after>// Copyright 2010 Google
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "stdio.h"
#include "time.h"

#include "base/logging.h"

namespace google_base {
DateLogger::DateLogger() {
#if defined(_MSC_VER)
  _tzset();
#endif
}

char* const DateLogger::HumanDate() {
#if defined(_MSC_VER)
  _strtime_s(buffer_, sizeof(buffer_));
#else
  time_t time_value = time(NULL);
  struct tm now;
  localtime_r(&time_value, &now);
  snprintf(buffer_, sizeof(buffer_), "%02d:%02d:%02d",
           now.tm_hour, now.tm_min, now.tm_sec);
#endif
  return buffer_;
}
}  // namespace google_base
<|endoftext|>


<commit_before>#include "game_window.h"
#include <sstream>

bool GameWindow::sdlInitialized = false;

bool GameWindow::initialize() {
	Logger::getInstance()->writeInformation("Initializing graphics");
	if (GameWindow::sdlInitialized) {
		Logger::getInstance()->writeWarning("SDL already initialized");
	} else {
		atexit(SDL_Quit);
		if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) {
			Logger::getInstance()->writeError("SDL could not initialize!");
			Logger::getInstance()->writeError(SDL_GetError());
			GameWindow::sdlInitialized = false;
		} else {
			GameWindow::sdlInitialized = true;
		}
	}
	return GameWindow::sdlInitialized;
}

GameWindow::GameWindow() {
	this->parser = new ParserYAML(CONFIG_FILE_PATH);
	this->model = NULL;
	this->exit = false;
	this->focus_x = 0;
	this->focus_y = 0;

	Logger::getInstance()->writeInformation("Creating window");

	GameWindow::initialize();
	window = SDL_CreateWindow("Trabajo Práctico 7542",
		SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
		ANCHO_DEFAULT, ALTO_DEFAULT,
		SDL_WINDOW_SHOWN);

	Logger::getInstance()->writeInformation("Creating renderer");
	renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED );

	// TODO: IMG_INIT

	SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); // Color: negro opaco
	SDL_RenderClear(renderer); // Limpio pantalla inicialmente
	SDL_RenderPresent( renderer );
}

GameWindow::~GameWindow() {
	map<std::string, SpriteSheet*>::const_iterator itr;
	for(itr = spritesSheets.begin(); itr != spritesSheets.end(); ++itr){
		delete itr->second;
	}

	delete parser;
	delete model;

	Logger::getInstance()->writeInformation("Destroying renderer");
	if (renderer != NULL) {
		SDL_DestroyRenderer(renderer);
		renderer = NULL;
	}

	Logger::getInstance()->writeInformation("Destroying window");
	if (window != NULL) {
		Logger::getInstance()->writeWarning("Window never initialized");
		SDL_DestroyWindow(window);
		window = NULL;
	}
}

bool GameWindow::endOfGame(){
	return this->exit;
}

void GameWindow::render(){
	//	Dibujar
	SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
	SDL_RenderClear(renderer);
	std::vector<std::shared_ptr<Entity>> entities = this->model->getBoard()->getEntities();
	std::map<std::string,SpriteSheet*>::iterator it;
	SpriteSheet* ss;
	for (std::size_t i =0; i < entities.size(); ++i){
		it = this->spritesSheets.find(entities[i]->name);
		if(it != this->spritesSheets.end()){
			ss = it->second;
			ss->render(*entities[i], 0, renderer);
		}
		else
			Logger::getInstance()->writeWarning("No existe SpriteSheet para este tipo de entidad" + entities[i]->name);
	}

	SDL_RenderPresent( renderer );
	return;
}

void GameWindow::restart(){
	//model->restart()	PARA NO TENER Q INSTANCIAR UN NUEVO MODEL
	delete model;

	map<std::string, SpriteSheet*>::const_iterator itr;
	for(itr = spritesSheets.begin(); itr != spritesSheets.end(); ++itr){
		delete itr->second;
	}

	init();
}

void GameWindow::init(){
	this->parser->parse();

	this->model = new Game(parser);

	this->spritesSheets["agua"] = new SpriteSheet("resources//agua.png", 0, 0, TILE_HEIGHT_DEFAULT, TILE_WIDTH_DEFAULT,  1, 0, 0, *this);
	this->spritesSheets["pasto"] = new SpriteSheet("resources//pasto.png", 0, 0, TILE_HEIGHT_DEFAULT, TILE_WIDTH_DEFAULT, 1, 0, 0, *this);
	this->spritesSheets["piedra"] = new SpriteSheet("resources//piedra.png", 0, 0, TILE_HEIGHT_DEFAULT, TILE_WIDTH_DEFAULT, 1, 0, 0, *this);
	this->spritesSheets["chancho"] = new SpriteSheet("resources//chanchos.png", 10, 10, 44, 48, 15, 0, 1, *this);
}

void GameWindow::update(){
	model->update();
	return;
}

void GameWindow::processInput(){
	int mouse_x_screen, mouse_y_screen;

	//	Procesar input del usuario
	while(SDL_PollEvent(EventHandler::getInstance()->getEvent())) {
		if(EventHandler::getInstance()->getEvent()->type == SDL_QUIT )
			this->exit = true;
		if(EventHandler::getInstance()->getEvent()->type == SDL_KEYDOWN ){
			Logger::getInstance()->writeInformation("Teclado");
			if(EventHandler::getInstance()->getEvent()->key.keysym.sym == SDLK_r){
				restart();
			}
		}
		if( EventHandler::getInstance()->getEvent()->type == SDL_MOUSEBUTTONUP ){
			SDL_GetMouseState(&mouse_x_screen, &mouse_y_screen);
			std::ostringstream oss;
			oss << "Mouse en " << mouse_x_screen << "," << mouse_y_screen;

			// Conversion de coordenadas en pantalla a coordenadas mapa

			double XsTerm = (double)(mouse_x_screen - ANCHO_DEFAULT/2)/(double)TILE_WIDTH_DEFAULT;
			double YsTerm = (double)(mouse_y_screen - ALTO_DEFAULT/2)/(double)TILE_HEIGHT_DEFAULT;

			double x_mapa = focus_x + XsTerm + YsTerm + .5;
			double y_mapa = focus_y - XsTerm + YsTerm + .5;

			oss << "; mapa: " << x_mapa << "," << y_mapa;

			Logger::getInstance()->writeInformation(oss.str().c_str());
			if( EventHandler::getInstance()->getEvent()->button.button == SDL_BUTTON_LEFT ) {
				Logger::getInstance()->writeInformation("Boton Izquierdo");
				model->getBoard()->getProtagonist().setTarget(x_mapa, y_mapa);
			}
			if( EventHandler::getInstance()->getEvent()->button.button == SDL_BUTTON_RIGHT) {
				Logger::getInstance()->writeInformation("Boton derecho");
			}
		}
	}
}

void GameWindow::scroll(){
	Uint8 mouse_b;
	int mouse_x, mouse_y;
	const double SCROLL_SPEED = 5;

	double ds = SCROLL_SPEED * model->getBoard()->dt / 1000; //deltascroll
		SDL_GetMouseState(&mouse_x, &mouse_y);

		if(mouse_x <= MARGEN_PANTALLA_DEFAULT)
		{
			double dsi = (1.0 - ((double)mouse_x / (double)MARGEN_PANTALLA_DEFAULT)) * ds;

			focus_x -= dsi;
			focus_y += dsi;
			Logger::getInstance()->writeInformation("Scrolleando hacia la izquierda");
		}
		else if(mouse_x >= ANCHO_DEFAULT - MARGEN_PANTALLA_DEFAULT){

			double dsi = ((double)(mouse_x + MARGEN_PANTALLA_DEFAULT - ANCHO_DEFAULT)/(double)MARGEN_PANTALLA_DEFAULT) * ds;

			focus_x += dsi;
			focus_y -= dsi;
			Logger::getInstance()->writeInformation("Scrolleando hacia la derecha");
		}
		if(mouse_y <= MARGEN_PANTALLA_DEFAULT)
		{
			double dsi = (1.0 - ((double)mouse_y / (double)MARGEN_PANTALLA_DEFAULT)) * ds;
			focus_x -= dsi;
			focus_y -= dsi;
			Logger::getInstance()->writeInformation("Scrolleando hacia arriba");
		}
		if(mouse_y >= ALTO_DEFAULT - MARGEN_PANTALLA_DEFAULT)
		{
			double dsi = ((double)(mouse_y + MARGEN_PANTALLA_DEFAULT - ALTO_DEFAULT)/(double)MARGEN_PANTALLA_DEFAULT) * ds;

			focus_x += dsi;
			focus_y += dsi;
			Logger::getInstance()->writeInformation("Scrolleando hacia abajo");
		}

		auto & board = *(model->getBoard());

		if(focus_x >= board.sizeX - 1){
			focus_x = board.sizeX - 1;
		}
		else if(focus_x < 0){
			focus_x = 0;
		}

		if(focus_y >= board.sizeY - 1){
			focus_y = board.sizeY - 1;
		}else if(focus_y < 0){
			focus_y = 0;
		}
}

int GameWindow::start(){
	init();

	while (!endOfGame())
	{
		scroll();
		processInput();
		update();
		render();

		SDL_Delay(model->getBoard()->dt); // TODO: Optimizar, sacar hardcodeo
	}
	return 0;
}

<commit_msg>Empiezo centrado en el protagonista<commit_after>#include "game_window.h"
#include <sstream>

bool GameWindow::sdlInitialized = false;

bool GameWindow::initialize() {
	Logger::getInstance()->writeInformation("Initializing graphics");
	if (GameWindow::sdlInitialized) {
		Logger::getInstance()->writeWarning("SDL already initialized");
	} else {
		atexit(SDL_Quit);
		if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) {
			Logger::getInstance()->writeError("SDL could not initialize!");
			Logger::getInstance()->writeError(SDL_GetError());
			GameWindow::sdlInitialized = false;
		} else {
			GameWindow::sdlInitialized = true;
		}
	}
	return GameWindow::sdlInitialized;
}

GameWindow::GameWindow() {
	this->parser = new ParserYAML(CONFIG_FILE_PATH);
	this->model = NULL;
	this->exit = false;
	this->focus_x = 0;
	this->focus_y = 0;

	Logger::getInstance()->writeInformation("Creating window");

	GameWindow::initialize();
	window = SDL_CreateWindow("Trabajo Práctico 7542",
		SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
		ANCHO_DEFAULT, ALTO_DEFAULT,
		SDL_WINDOW_SHOWN);

	Logger::getInstance()->writeInformation("Creating renderer");
	renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED );

	// TODO: IMG_INIT

	SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); // Color: negro opaco
	SDL_RenderClear(renderer); // Limpio pantalla inicialmente
	SDL_RenderPresent( renderer );
}

GameWindow::~GameWindow() {
	map<std::string, SpriteSheet*>::const_iterator itr;
	for(itr = spritesSheets.begin(); itr != spritesSheets.end(); ++itr){
		delete itr->second;
	}

	delete parser;
	delete model;

	Logger::getInstance()->writeInformation("Destroying renderer");
	if (renderer != NULL) {
		SDL_DestroyRenderer(renderer);
		renderer = NULL;
	}

	Logger::getInstance()->writeInformation("Destroying window");
	if (window != NULL) {
		Logger::getInstance()->writeWarning("Window never initialized");
		SDL_DestroyWindow(window);
		window = NULL;
	}
}

bool GameWindow::endOfGame(){
	return this->exit;
}

void GameWindow::render(){
	//	Dibujar
	SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
	SDL_RenderClear(renderer);
	std::vector<std::shared_ptr<Entity>> entities = this->model->getBoard()->getEntities();
	std::map<std::string,SpriteSheet*>::iterator it;
	SpriteSheet* ss;
	for (std::size_t i =0; i < entities.size(); ++i){
		it = this->spritesSheets.find(entities[i]->name);
		if(it != this->spritesSheets.end()){
			ss = it->second;
			ss->render(*entities[i], 0, renderer);
		}
		else
			Logger::getInstance()->writeWarning("No existe SpriteSheet para este tipo de entidad" + entities[i]->name);
	}

	SDL_RenderPresent( renderer );
	return;
}

void GameWindow::restart(){
	//model->restart()	PARA NO TENER Q INSTANCIAR UN NUEVO MODEL
	delete model;

	map<std::string, SpriteSheet*>::const_iterator itr;
	for(itr = spritesSheets.begin(); itr != spritesSheets.end(); ++itr){
		delete itr->second;
	}

	init();
}

void GameWindow::init(){
	this->parser->parse();

	this->model = new Game(parser);

	this->spritesSheets["agua"] = new SpriteSheet("resources//agua.png", 0, 0, TILE_HEIGHT_DEFAULT, TILE_WIDTH_DEFAULT,  1, 0, 0, *this);
	this->spritesSheets["pasto"] = new SpriteSheet("resources//pasto.png", 0, 0, TILE_HEIGHT_DEFAULT, TILE_WIDTH_DEFAULT, 1, 0, 0, *this);
	this->spritesSheets["piedra"] = new SpriteSheet("resources//piedra.png", 0, 0, TILE_HEIGHT_DEFAULT, TILE_WIDTH_DEFAULT, 1, 0, 0, *this);
	this->spritesSheets["chancho"] = new SpriteSheet("resources//chanchos.png", 10, 10, 44, 48, 15, 0, 1, *this);
}

void GameWindow::update(){
	model->update();
	return;
}

void GameWindow::processInput(){
	int mouse_x_screen, mouse_y_screen;

	//	Procesar input del usuario
	while(SDL_PollEvent(EventHandler::getInstance()->getEvent())) {
		if(EventHandler::getInstance()->getEvent()->type == SDL_QUIT )
			this->exit = true;
		if(EventHandler::getInstance()->getEvent()->type == SDL_KEYDOWN ){
			Logger::getInstance()->writeInformation("Teclado");
			if(EventHandler::getInstance()->getEvent()->key.keysym.sym == SDLK_r){
				restart();
			}
		}
		if( EventHandler::getInstance()->getEvent()->type == SDL_MOUSEBUTTONUP ){
			SDL_GetMouseState(&mouse_x_screen, &mouse_y_screen);
			std::ostringstream oss;
			oss << "Mouse en " << mouse_x_screen << "," << mouse_y_screen;

			// Conversion de coordenadas en pantalla a coordenadas mapa

			double XsTerm = (double)(mouse_x_screen - ANCHO_DEFAULT/2)/(double)TILE_WIDTH_DEFAULT;
			double YsTerm = (double)(mouse_y_screen - ALTO_DEFAULT/2)/(double)TILE_HEIGHT_DEFAULT;

			double x_mapa = focus_x + XsTerm + YsTerm + .5;
			double y_mapa = focus_y - XsTerm + YsTerm + .5;

			oss << "; mapa: " << x_mapa << "," << y_mapa;

			Logger::getInstance()->writeInformation(oss.str().c_str());
			if( EventHandler::getInstance()->getEvent()->button.button == SDL_BUTTON_LEFT ) {
				Logger::getInstance()->writeInformation("Boton Izquierdo");
				model->getBoard()->getProtagonist().setTarget(x_mapa, y_mapa);
			}
			if( EventHandler::getInstance()->getEvent()->button.button == SDL_BUTTON_RIGHT) {
				Logger::getInstance()->writeInformation("Boton derecho");
			}
		}
	}
}

void GameWindow::scroll(){
	Uint8 mouse_b;
	int mouse_x, mouse_y;
	const double SCROLL_SPEED = 5;

	double ds = SCROLL_SPEED * model->getBoard()->dt / 1000; //deltascroll
		SDL_GetMouseState(&mouse_x, &mouse_y);

		if(mouse_x <= MARGEN_PANTALLA_DEFAULT)
		{
			double dsi = (1.0 - ((double)mouse_x / (double)MARGEN_PANTALLA_DEFAULT)) * ds;

			focus_x -= dsi;
			focus_y += dsi;
			Logger::getInstance()->writeInformation("Scrolleando hacia la izquierda");
		}
		else if(mouse_x >= ANCHO_DEFAULT - MARGEN_PANTALLA_DEFAULT){

			double dsi = ((double)(mouse_x + MARGEN_PANTALLA_DEFAULT - ANCHO_DEFAULT)/(double)MARGEN_PANTALLA_DEFAULT) * ds;

			focus_x += dsi;
			focus_y -= dsi;
			Logger::getInstance()->writeInformation("Scrolleando hacia la derecha");
		}
		if(mouse_y <= MARGEN_PANTALLA_DEFAULT)
		{
			double dsi = (1.0 - ((double)mouse_y / (double)MARGEN_PANTALLA_DEFAULT)) * ds;
			focus_x -= dsi;
			focus_y -= dsi;
			Logger::getInstance()->writeInformation("Scrolleando hacia arriba");
		}
		if(mouse_y >= ALTO_DEFAULT - MARGEN_PANTALLA_DEFAULT)
		{
			double dsi = ((double)(mouse_y + MARGEN_PANTALLA_DEFAULT - ALTO_DEFAULT)/(double)MARGEN_PANTALLA_DEFAULT) * ds;

			focus_x += dsi;
			focus_y += dsi;
			Logger::getInstance()->writeInformation("Scrolleando hacia abajo");
		}

		auto & board = *(model->getBoard());

		if(focus_x >= board.sizeX - 1){
			focus_x = board.sizeX - 1;
		}
		else if(focus_x < 0){
			focus_x = 0;
		}

		if(focus_y >= board.sizeY - 1){
			focus_y = board.sizeY - 1;
		}else if(focus_y < 0){
			focus_y = 0;
		}
}

int GameWindow::start(){
	init();
	{
		auto protagonist = model->getBoard()->getProtagonist();
		focus_x = protagonist.getX();
		focus_y = protagonist.getY();
	}

	while (!endOfGame())
	{
		scroll();
		processInput();
		update();
		render();

		SDL_Delay(model->getBoard()->dt); // TODO: Optimizar, sacar hardcodeo
	}
	return 0;
}

<|endoftext|>


<commit_before>/*****************************************************************************
 * Licensed to Qualys, Inc. (QUALYS) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * QUALYS licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ****************************************************************************/

/**
 * @file
 * @brief Predicate --- Validate implementation
 *
 * @author Christopher Alfeld <calfeld@qualys.com>
 */

#include "validate.hpp"

#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>

using namespace std;

namespace IronBee {
namespace Predicate {
namespace Validate {

namespace  {

node_cp nth_child(
    NodeReporter  reporter,
    size_t         n
)
{
    size_t num_children = reporter.node()->children().size();

    if (reporter.node()->children().size() <= n) {
        reporter.error(
            "Wanted " + boost::lexical_cast<string>(n+1) +
            "th child.  But there are only " +
            boost::lexical_cast<string>(num_children) + " children."
        );
        return node_cp();
    }

    return *boost::next(reporter.node()->children().begin(), n);
}

template <typename BaseClass>
bool is_a(const node_cp& node)
{
    return boost::dynamic_pointer_cast<const BaseClass>(node);
}

}

void n_children(NodeReporter reporter, size_t n)
{
    size_t actual_children = reporter.node()->children().size();
    if (actual_children != n) {
        reporter.error(
            "Expected " + boost::lexical_cast<string>(n) + " children " +
            " but have " + boost::lexical_cast<string>(actual_children) +
            "."
        );
    }
}

void n_or_more_children(NodeReporter reporter, size_t n)
{
    size_t actual_children = reporter.node()->children().size();
    if (actual_children != n) {
        reporter.error(
            "Expected at least " + boost::lexical_cast<string>(n) +
            " children  but have " +
            boost::lexical_cast<string>(actual_children) + "."
        );
    }
}

void n_or_fewer_children(NodeReporter reporter, size_t n)
{
    size_t actual_children = reporter.node()->children().size();
    if (actual_children != n) {
        reporter.error(
            "Expected at most " + boost::lexical_cast<string>(n) +
            " children but have " +
            boost::lexical_cast<string>(actual_children) + "."
        );
    }
}

void nth_child_is_string_literal(NodeReporter reporter, size_t n)
{
    node_cp child = nth_child(reporter, n);
    if (child && ! is_a<String>(child)) {
        reporter.error(
            "Child " + boost::lexical_cast<string>(n+1) + " must be a "
            "string literal."
        );
    }
}

void nth_child_is_null(NodeReporter reporter, size_t n)
{
    node_cp child = nth_child(reporter, n);
    if (child && ! is_a<Null>(child)) {
        reporter.error(
            "Child " + boost::lexical_cast<string>(n+1) + " must be a null."
        );
    }
}

void no_child_is_literal(NodeReporter reporter)
{
    size_t i = 0;
    BOOST_FOREACH(const node_cp& child, reporter.node()->children()) {
        if (is_a<Literal>(child)) {
            reporter.error(
                "Child " + boost::lexical_cast<string>(i+1) + " must  not be"
                "literal."
            );
        }
        ++i;
    }
}

void no_child_is_null(NodeReporter reporter)
{
    size_t i = 0;
    BOOST_FOREACH(const node_cp& child, reporter.node()->children()) {
        if (is_a<Null>(child)) {
            reporter.error(
                "Child " + boost::lexical_cast<string>(i+1) + " must  not be"
                "null."
            );
        }
        ++i;
    }
}

} // Validate
} // Predicate
} // IronBee
<commit_msg>predicate/validate: Fix bugs in NOrMoreChildren and NOrFewerChildren.<commit_after>/*****************************************************************************
 * Licensed to Qualys, Inc. (QUALYS) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * QUALYS licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ****************************************************************************/

/**
 * @file
 * @brief Predicate --- Validate implementation
 *
 * @author Christopher Alfeld <calfeld@qualys.com>
 */

#include "validate.hpp"

#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>

using namespace std;

namespace IronBee {
namespace Predicate {
namespace Validate {

namespace  {

node_cp nth_child(
    NodeReporter  reporter,
    size_t         n
)
{
    size_t num_children = reporter.node()->children().size();

    if (reporter.node()->children().size() <= n) {
        reporter.error(
            "Wanted " + boost::lexical_cast<string>(n+1) +
            "th child.  But there are only " +
            boost::lexical_cast<string>(num_children) + " children."
        );
        return node_cp();
    }

    return *boost::next(reporter.node()->children().begin(), n);
}

template <typename BaseClass>
bool is_a(const node_cp& node)
{
    return boost::dynamic_pointer_cast<const BaseClass>(node);
}

}

void n_children(NodeReporter reporter, size_t n)
{
    size_t actual_children = reporter.node()->children().size();
    if (actual_children != n) {
        reporter.error(
            "Expected " + boost::lexical_cast<string>(n) + " children " +
            " but have " + boost::lexical_cast<string>(actual_children) +
            "."
        );
    }
}

void n_or_more_children(NodeReporter reporter, size_t n)
{
    size_t actual_children = reporter.node()->children().size();
    if (actual_children < n) {
        reporter.error(
            "Expected at least " + boost::lexical_cast<string>(n) +
            " children  but have " +
            boost::lexical_cast<string>(actual_children) + "."
        );
    }
}

void n_or_fewer_children(NodeReporter reporter, size_t n)
{
    size_t actual_children = reporter.node()->children().size();
    if (actual_children > n) {
        reporter.error(
            "Expected at most " + boost::lexical_cast<string>(n) +
            " children but have " +
            boost::lexical_cast<string>(actual_children) + "."
        );
    }
}

void nth_child_is_string_literal(NodeReporter reporter, size_t n)
{
    node_cp child = nth_child(reporter, n);
    if (child && ! is_a<String>(child)) {
        reporter.error(
            "Child " + boost::lexical_cast<string>(n+1) + " must be a "
            "string literal."
        );
    }
}

void nth_child_is_null(NodeReporter reporter, size_t n)
{
    node_cp child = nth_child(reporter, n);
    if (child && ! is_a<Null>(child)) {
        reporter.error(
            "Child " + boost::lexical_cast<string>(n+1) + " must be a null."
        );
    }
}

void no_child_is_literal(NodeReporter reporter)
{
    size_t i = 0;
    BOOST_FOREACH(const node_cp& child, reporter.node()->children()) {
        if (is_a<Literal>(child)) {
            reporter.error(
                "Child " + boost::lexical_cast<string>(i+1) + " must  not be"
                "literal."
            );
        }
        ++i;
    }
}

void no_child_is_null(NodeReporter reporter)
{
    size_t i = 0;
    BOOST_FOREACH(const node_cp& child, reporter.node()->children()) {
        if (is_a<Null>(child)) {
            reporter.error(
                "Child " + boost::lexical_cast<string>(i+1) + " must  not be"
                "null."
            );
        }
        ++i;
    }
}

} // Validate
} // Predicate
} // IronBee
<|endoftext|>


<commit_before>#ifndef __Data_course__
#define __Data_course__

#include "general.hpp"
#include "major.hpp"
#include "id.hpp"
using namespace std;

class Course {
private: // variables
	ID id;
	string title;
	string description;

	vector<Major> majors;
	vector<Department> department;
	string concentrations;
	string conversations;
	string professor;

	int half_semester;
	bool pass_fail;
	float credits;
	string location;

	course_type_t courseType;
	gened_t* geneds;

	bool days[7];
	float time[7];
private: // methods
	void init(string identifier);
	void copy(const Course& c);
public:
	Course();
	Course(string str);
	Course(const Course& c);
	Course& operator= (const Course &c);
	Course(istream &is);

	friend bool operator== (const Course &c1, const Course &c2);
    friend bool operator!= (Course &c1, Course &c2);
	friend Course getCourse(string identifier);

	void cleanTitle();

	Department getDepartment(int i = 0);
	string getProfessor();
	ID getID();
	string getType();
	int getNumber();
	string getSection();

	ostream& getData(ostream& os);
	void display();
	void showAll();
};

extern vector<Course> all_courses;

ostream& operator<<(ostream& os, Course& item);
Course getCourse(string identifier);

#endif
<commit_msg>Include gened in Course<commit_after>#ifndef __Data_course__
#define __Data_course__

#include "general.hpp"
#include "major.hpp"
#include "id.hpp"
#include "gened.hpp"
using namespace std;

class Course {
private: // variables
	ID id;
	string title;
	string description;

	vector<Major> majors;
	vector<Department> department;
	string concentrations;
	string conversations;
	string professor;

	int half_semester;
	bool pass_fail;
	float credits;
	string location;

	course_type_t courseType;
	gened_t* geneds;

	bool days[7];
	float time[7];
private: // methods
	void init(string identifier);
	void copy(const Course& c);
public:
	Course();
	Course(string str);
	Course(const Course& c);
	Course& operator= (const Course &c);
	Course(istream &is);

	friend bool operator== (const Course &c1, const Course &c2);
    friend bool operator!= (Course &c1, Course &c2);
	friend Course getCourse(string identifier);

	void cleanTitle();

	Department getDepartment(int i = 0);
	string getProfessor();
	ID getID();
	string getType();
	int getNumber();
	string getSection();

	ostream& getData(ostream& os);
	void display();
	void showAll();
};

extern vector<Course> all_courses;

ostream& operator<<(ostream& os, Course& item);
Course getCourse(string identifier);

#endif
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkXMLUnstructuredDataWriter.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkXMLUnstructuredDataWriter.h"
#include "vtkObjectFactory.h"
#include "vtkPointSet.h"
#include "vtkDataCompressor.h"
#include "vtkCellArray.h"
#include "vtkDataArray.h"
#include "vtkIdTypeArray.h"
#include "vtkUnsignedCharArray.h"
#include "vtkPoints.h"
#include "vtkDataSetAttributes.h"

vtkCxxRevisionMacro(vtkXMLUnstructuredDataWriter, "1.1");

//----------------------------------------------------------------------------
vtkXMLUnstructuredDataWriter::vtkXMLUnstructuredDataWriter()
{
  this->NumberOfPieces = 1;
  this->WritePiece = -1;
  this->GhostLevel = 0;
  this->CellPoints = vtkIdTypeArray::New();
  this->CellOffsets = vtkIdTypeArray::New();
  this->CellPoints->SetName("connectivity");
  this->CellOffsets->SetName("offsets");
}

//----------------------------------------------------------------------------
vtkXMLUnstructuredDataWriter::~vtkXMLUnstructuredDataWriter()
{
  this->CellPoints->Delete();
  this->CellOffsets->Delete();
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredDataWriter::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
  os << indent << "NumberOfPieces: " << this->NumberOfPieces << "\n";
  os << indent << "WritePiece: " << this->WritePiece << "\n";
  os << indent << "GhostLevel: " << this->GhostLevel << "\n";
}

//----------------------------------------------------------------------------
vtkPointSet* vtkXMLUnstructuredDataWriter::GetInputAsPointSet()
{
  if(this->NumberOfInputs < 1)
    {
    return 0;
    }

  return static_cast<vtkPointSet*>(this->Inputs[0]);
}

//----------------------------------------------------------------------------
int vtkXMLUnstructuredDataWriter::WriteData()
{
  vtkIndent indent = vtkIndent().GetNextIndent();

  vtkPointSet* input = this->GetInputAsPointSet();
  input->UpdateInformation();

  // We don't want to write more pieces than the pipeline can produce,
  // but we need to preserve the user's requested number of pieces in
  // case the input changes later.  If MaximumNumberOfPieces is lower
  // than 1, any number of pieces can be produced by the pipeline.
  int maxPieces = input->GetMaximumNumberOfPieces();
  int numPieces = this->NumberOfPieces;
  if((maxPieces > 0) && (this->NumberOfPieces > maxPieces))
    {
    this->NumberOfPieces = maxPieces;
    }

  // Write the file.
  this->StartFile();
  if(this->DataMode == vtkXMLWriter::Appended)
    {
    this->WriteAppendedMode(indent);
    }
  else
    {
    this->WriteInlineMode(indent);
    }
  this->EndFile();

  // Restore the user's number of pieces.
  this->NumberOfPieces = numPieces;

  return 1;
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredDataWriter::WriteInlineMode(vtkIndent indent)
{
  ostream& os = *(this->Stream);
  vtkIndent nextIndent = indent.GetNextIndent();
  vtkPointSet* input = this->GetInputAsPointSet();

  // Open the primary element.
  os << indent << "<" << this->GetDataSetName() << ">\n";

  if((this->WritePiece < 0) || (this->WritePiece >= this->NumberOfPieces))
    {
    // Loop over each piece and write it.
    int i;
    for(i=0; i < this->NumberOfPieces; ++i)
      {
      this->SetInputUpdateExtent(i, this->NumberOfPieces, this->GhostLevel);
      input->Update();

      // Open the piece's element.
      os << nextIndent << "<Piece";
      this->WriteInlinePieceAttributes();
      os << ">\n";

      this->WriteInlinePiece(nextIndent.GetNextIndent());

      // Close the piece's element.
      os << nextIndent << "</Piece>\n";
      }
    }
  else
    {
    // Write just the one requested piece.
    this->SetInputUpdateExtent(this->WritePiece, this->NumberOfPieces,
                               this->GhostLevel);
    input->Update();

    // Open the piece's element.
    os << nextIndent << "<Piece";
    this->WriteInlinePieceAttributes();
    os << ">\n";

    this->WriteInlinePiece(nextIndent.GetNextIndent());

    // Close the piece's element.
    os << nextIndent << "</Piece>\n";
    }

  // Close the primary element.
  os << indent << "</" << this->GetDataSetName() << ">\n";
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredDataWriter::WriteInlinePieceAttributes()
{
  vtkPointSet* input = this->GetInputAsPointSet();
  this->WriteScalarAttribute("NumberOfPoints",
                             input->GetPoints()->GetNumberOfPoints());
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredDataWriter::WriteInlinePiece(vtkIndent indent)
{
  vtkPointSet* input = this->GetInputAsPointSet();
  this->WritePointsInline(input->GetPoints(), indent);
  this->WritePointDataInline(input->GetPointData(), indent);
  this->WriteCellDataInline(input->GetCellData(), indent);
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredDataWriter::WriteAppendedMode(vtkIndent indent)
{
  ostream& os = *(this->Stream);
  vtkIndent nextIndent = indent.GetNextIndent();

  this->NumberOfPointsPositions = new unsigned long[this->NumberOfPieces];
  this->PointsPositions = new unsigned long[this->NumberOfPieces];
  this->PointDataPositions = new unsigned long*[this->NumberOfPieces];
  this->CellDataPositions = new unsigned long*[this->NumberOfPieces];

  // Update the first piece of the input to get the form of the data.
  vtkPointSet* input = this->GetInputAsPointSet();
  int piece = this->WritePiece;
  if((piece < 0) || (piece >= this->NumberOfPieces)) { piece = 0; }
  input->SetUpdateExtent(piece, this->NumberOfPieces, this->GhostLevel);
  input->Update();

  // Open the primary element.
  os << indent << "<" << this->GetDataSetName() << ">\n";

  if((this->WritePiece < 0) || (this->WritePiece >= this->NumberOfPieces))
    {
    // Loop over each piece and write its structure.
    int i;
    for(i=0; i < this->NumberOfPieces; ++i)
      {
      // Open the piece's element.
      os << nextIndent << "<Piece";
      this->WriteAppendedPieceAttributes(i);
      os << ">\n";

      this->WriteAppendedPiece(i, nextIndent.GetNextIndent());

      // Close the piece's element.
      os << nextIndent << "</Piece>\n";
      }
    }
  else
    {
    // Write just the requested piece.
    // Open the piece's element.
    os << nextIndent << "<Piece";
    this->WriteAppendedPieceAttributes(this->WritePiece);
    os << ">\n";

    this->WriteAppendedPiece(this->WritePiece, nextIndent.GetNextIndent());

    // Close the piece's element.
    os << nextIndent << "</Piece>\n";
    }

  // Close the primary element.
  os << indent << "</" << this->GetDataSetName() << ">\n";

  this->StartAppendedData();

  if((this->WritePiece < 0) || (this->WritePiece >= this->NumberOfPieces))
    {
    // Loop over each piece and write its data.
    int i;
    for(i=0; i < this->NumberOfPieces; ++i)
      {
      input->SetUpdateExtent(i, this->NumberOfPieces, this->GhostLevel);
      input->Update();
      this->WriteAppendedPieceData(i);
      }
    }
  else
    {
    // Write just the requested piece.
    input->SetUpdateExtent(this->WritePiece, this->NumberOfPieces,
                           this->GhostLevel);
    input->Update();
    this->WriteAppendedPieceData(this->WritePiece);
    }

  this->EndAppendedData();

  delete [] this->NumberOfPointsPositions;
  delete [] this->PointsPositions;
  delete [] this->PointDataPositions;
  delete [] this->CellDataPositions;
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredDataWriter::WriteAppendedPieceAttributes(int index)
{
  this->NumberOfPointsPositions[index] =
    this->ReserveAttributeSpace("NumberOfPoints");
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredDataWriter::WriteAppendedPiece(int index,
                                                      vtkIndent indent)
{
  vtkPointSet* input = this->GetInputAsPointSet();

  this->PointDataPositions[index] =
    this->WritePointDataAppended(input->GetPointData(), indent);

  this->CellDataPositions[index] =
    this->WriteCellDataAppended(input->GetCellData(), indent);

  this->PointsPositions[index] =
    this->WritePointsAppended(input->GetPoints(), indent);
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredDataWriter::WriteAppendedPieceData(int index)
{
  ostream& os = *(this->Stream);
  vtkPointSet* input = this->GetInputAsPointSet();

  unsigned long returnPosition = os.tellp();
  os.seekp(this->NumberOfPointsPositions[index]);
  this->WriteScalarAttribute("NumberOfPoints",
                             input->GetPoints()->GetNumberOfPoints());
  os.seekp(returnPosition);

  this->WritePointDataAppendedData(input->GetPointData(),
                               this->PointDataPositions[index]);

  this->WriteCellDataAppendedData(input->GetCellData(),
                                  this->CellDataPositions[index]);

  this->WritePointsAppendedData(input->GetPoints(),
                                this->PointsPositions[index]);
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredDataWriter::WriteCellsInline(const char* name,
                                                    vtkCellArray* cells,
                                                    vtkDataArray* types,
                                                    vtkIndent indent)
{
  this->ConvertCells(cells);

  ostream& os = *(this->Stream);
  os << indent << "<" << name << ">\n";
  this->WriteDataArrayInline(this->CellPoints, indent.GetNextIndent());
  this->WriteDataArrayInline(this->CellOffsets, indent.GetNextIndent());
  if(types)
    {
    this->WriteDataArrayInline(types, indent.GetNextIndent(), "types");
    }
  os << indent << "</" << name << ">\n";
}

//----------------------------------------------------------------------------
unsigned long*
vtkXMLUnstructuredDataWriter::WriteCellsAppended(const char* name,
                                                 vtkDataArray* types,
                                                 vtkIndent indent)
{
  unsigned long* positions = new unsigned long[3];
  ostream& os = *(this->Stream);
  os << indent << "<" << name << ">\n";
  positions[0] = this->WriteDataArrayAppended(this->CellPoints,
                                              indent.GetNextIndent());
  positions[1] = this->WriteDataArrayAppended(this->CellOffsets,
                                              indent.GetNextIndent());
  if(types)
    {
    positions[2] = this->WriteDataArrayAppended(types, indent.GetNextIndent(),
                                                "types");
    }
  os << indent << "</" << name << ">\n";
  return positions;
}

//----------------------------------------------------------------------------
void
vtkXMLUnstructuredDataWriter::WriteCellsAppendedData(vtkCellArray* cells,
                                                     vtkDataArray* types,
                                                     unsigned long* positions)
{
  this->ConvertCells(cells);
  this->WriteDataArrayAppendedData(this->CellPoints, positions[0]);
  this->WriteDataArrayAppendedData(this->CellOffsets, positions[1]);
  if(types)
    {
    this->WriteDataArrayAppendedData(types, positions[2]);
    }
  delete [] positions;
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredDataWriter::ConvertCells(vtkCellArray* cells)
{
  vtkIdTypeArray* connectivity = cells->GetData();
  vtkIdType numberOfCells = cells->GetNumberOfCells();
  vtkIdType numberOfTuples = connectivity->GetNumberOfTuples();

  this->CellPoints->SetNumberOfTuples(numberOfTuples - numberOfCells);
  this->CellOffsets->SetNumberOfTuples(numberOfCells);

  vtkIdType* inCell = connectivity->GetPointer(0);
  vtkIdType* outCellPointsBase = this->CellPoints->GetPointer(0);
  vtkIdType* outCellPoints = outCellPointsBase;
  vtkIdType* outCellOffset = this->CellOffsets->GetPointer(0);

  vtkIdType i;
  for(i=0;i < numberOfCells; ++i)
    {
    vtkIdType numberOfPoints = *inCell++;
    memcpy(outCellPoints, inCell, sizeof(vtkIdType)*numberOfPoints);
    outCellPoints += numberOfPoints;
    inCell += numberOfPoints;
    *outCellOffset++ = outCellPoints - outCellPointsBase;
    }
}
<commit_msg>ERR: If input->GetPoints() is null, there are 0 points.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkXMLUnstructuredDataWriter.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkXMLUnstructuredDataWriter.h"
#include "vtkObjectFactory.h"
#include "vtkPointSet.h"
#include "vtkDataCompressor.h"
#include "vtkCellArray.h"
#include "vtkDataArray.h"
#include "vtkIdTypeArray.h"
#include "vtkUnsignedCharArray.h"
#include "vtkPoints.h"
#include "vtkDataSetAttributes.h"

vtkCxxRevisionMacro(vtkXMLUnstructuredDataWriter, "1.2");

//----------------------------------------------------------------------------
vtkXMLUnstructuredDataWriter::vtkXMLUnstructuredDataWriter()
{
  this->NumberOfPieces = 1;
  this->WritePiece = -1;
  this->GhostLevel = 0;
  this->CellPoints = vtkIdTypeArray::New();
  this->CellOffsets = vtkIdTypeArray::New();
  this->CellPoints->SetName("connectivity");
  this->CellOffsets->SetName("offsets");
}

//----------------------------------------------------------------------------
vtkXMLUnstructuredDataWriter::~vtkXMLUnstructuredDataWriter()
{
  this->CellPoints->Delete();
  this->CellOffsets->Delete();
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredDataWriter::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
  os << indent << "NumberOfPieces: " << this->NumberOfPieces << "\n";
  os << indent << "WritePiece: " << this->WritePiece << "\n";
  os << indent << "GhostLevel: " << this->GhostLevel << "\n";
}

//----------------------------------------------------------------------------
vtkPointSet* vtkXMLUnstructuredDataWriter::GetInputAsPointSet()
{
  if(this->NumberOfInputs < 1)
    {
    return 0;
    }

  return static_cast<vtkPointSet*>(this->Inputs[0]);
}

//----------------------------------------------------------------------------
int vtkXMLUnstructuredDataWriter::WriteData()
{
  vtkIndent indent = vtkIndent().GetNextIndent();

  vtkPointSet* input = this->GetInputAsPointSet();
  input->UpdateInformation();

  // We don't want to write more pieces than the pipeline can produce,
  // but we need to preserve the user's requested number of pieces in
  // case the input changes later.  If MaximumNumberOfPieces is lower
  // than 1, any number of pieces can be produced by the pipeline.
  int maxPieces = input->GetMaximumNumberOfPieces();
  int numPieces = this->NumberOfPieces;
  if((maxPieces > 0) && (this->NumberOfPieces > maxPieces))
    {
    this->NumberOfPieces = maxPieces;
    }

  // Write the file.
  this->StartFile();
  if(this->DataMode == vtkXMLWriter::Appended)
    {
    this->WriteAppendedMode(indent);
    }
  else
    {
    this->WriteInlineMode(indent);
    }
  this->EndFile();

  // Restore the user's number of pieces.
  this->NumberOfPieces = numPieces;

  return 1;
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredDataWriter::WriteInlineMode(vtkIndent indent)
{
  ostream& os = *(this->Stream);
  vtkIndent nextIndent = indent.GetNextIndent();
  vtkPointSet* input = this->GetInputAsPointSet();

  // Open the primary element.
  os << indent << "<" << this->GetDataSetName() << ">\n";

  if((this->WritePiece < 0) || (this->WritePiece >= this->NumberOfPieces))
    {
    // Loop over each piece and write it.
    int i;
    for(i=0; i < this->NumberOfPieces; ++i)
      {
      this->SetInputUpdateExtent(i, this->NumberOfPieces, this->GhostLevel);
      input->Update();

      // Open the piece's element.
      os << nextIndent << "<Piece";
      this->WriteInlinePieceAttributes();
      os << ">\n";

      this->WriteInlinePiece(nextIndent.GetNextIndent());

      // Close the piece's element.
      os << nextIndent << "</Piece>\n";
      }
    }
  else
    {
    // Write just the one requested piece.
    this->SetInputUpdateExtent(this->WritePiece, this->NumberOfPieces,
                               this->GhostLevel);
    input->Update();

    // Open the piece's element.
    os << nextIndent << "<Piece";
    this->WriteInlinePieceAttributes();
    os << ">\n";

    this->WriteInlinePiece(nextIndent.GetNextIndent());

    // Close the piece's element.
    os << nextIndent << "</Piece>\n";
    }

  // Close the primary element.
  os << indent << "</" << this->GetDataSetName() << ">\n";
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredDataWriter::WriteInlinePieceAttributes()
{
  vtkPointSet* input = this->GetInputAsPointSet();
  this->WriteScalarAttribute("NumberOfPoints",
                             input->GetPoints()->GetNumberOfPoints());
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredDataWriter::WriteInlinePiece(vtkIndent indent)
{
  vtkPointSet* input = this->GetInputAsPointSet();
  this->WritePointsInline(input->GetPoints(), indent);
  this->WritePointDataInline(input->GetPointData(), indent);
  this->WriteCellDataInline(input->GetCellData(), indent);
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredDataWriter::WriteAppendedMode(vtkIndent indent)
{
  ostream& os = *(this->Stream);
  vtkIndent nextIndent = indent.GetNextIndent();

  this->NumberOfPointsPositions = new unsigned long[this->NumberOfPieces];
  this->PointsPositions = new unsigned long[this->NumberOfPieces];
  this->PointDataPositions = new unsigned long*[this->NumberOfPieces];
  this->CellDataPositions = new unsigned long*[this->NumberOfPieces];

  // Update the first piece of the input to get the form of the data.
  vtkPointSet* input = this->GetInputAsPointSet();
  int piece = this->WritePiece;
  if((piece < 0) || (piece >= this->NumberOfPieces)) { piece = 0; }
  input->SetUpdateExtent(piece, this->NumberOfPieces, this->GhostLevel);
  input->Update();

  // Open the primary element.
  os << indent << "<" << this->GetDataSetName() << ">\n";

  if((this->WritePiece < 0) || (this->WritePiece >= this->NumberOfPieces))
    {
    // Loop over each piece and write its structure.
    int i;
    for(i=0; i < this->NumberOfPieces; ++i)
      {
      // Open the piece's element.
      os << nextIndent << "<Piece";
      this->WriteAppendedPieceAttributes(i);
      os << ">\n";

      this->WriteAppendedPiece(i, nextIndent.GetNextIndent());

      // Close the piece's element.
      os << nextIndent << "</Piece>\n";
      }
    }
  else
    {
    // Write just the requested piece.
    // Open the piece's element.
    os << nextIndent << "<Piece";
    this->WriteAppendedPieceAttributes(this->WritePiece);
    os << ">\n";

    this->WriteAppendedPiece(this->WritePiece, nextIndent.GetNextIndent());

    // Close the piece's element.
    os << nextIndent << "</Piece>\n";
    }

  // Close the primary element.
  os << indent << "</" << this->GetDataSetName() << ">\n";

  this->StartAppendedData();

  if((this->WritePiece < 0) || (this->WritePiece >= this->NumberOfPieces))
    {
    // Loop over each piece and write its data.
    int i;
    for(i=0; i < this->NumberOfPieces; ++i)
      {
      input->SetUpdateExtent(i, this->NumberOfPieces, this->GhostLevel);
      input->Update();
      this->WriteAppendedPieceData(i);
      }
    }
  else
    {
    // Write just the requested piece.
    input->SetUpdateExtent(this->WritePiece, this->NumberOfPieces,
                           this->GhostLevel);
    input->Update();
    this->WriteAppendedPieceData(this->WritePiece);
    }

  this->EndAppendedData();

  delete [] this->NumberOfPointsPositions;
  delete [] this->PointsPositions;
  delete [] this->PointDataPositions;
  delete [] this->CellDataPositions;
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredDataWriter::WriteAppendedPieceAttributes(int index)
{
  this->NumberOfPointsPositions[index] =
    this->ReserveAttributeSpace("NumberOfPoints");
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredDataWriter::WriteAppendedPiece(int index,
                                                      vtkIndent indent)
{
  vtkPointSet* input = this->GetInputAsPointSet();

  this->PointDataPositions[index] =
    this->WritePointDataAppended(input->GetPointData(), indent);

  this->CellDataPositions[index] =
    this->WriteCellDataAppended(input->GetCellData(), indent);

  this->PointsPositions[index] =
    this->WritePointsAppended(input->GetPoints(), indent);
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredDataWriter::WriteAppendedPieceData(int index)
{
  ostream& os = *(this->Stream);
  vtkPointSet* input = this->GetInputAsPointSet();

  unsigned long returnPosition = os.tellp();
  os.seekp(this->NumberOfPointsPositions[index]);
  vtkPoints* points = input->GetPoints();
  this->WriteScalarAttribute("NumberOfPoints",
                             (points?points->GetNumberOfPoints():0));
  os.seekp(returnPosition);

  this->WritePointDataAppendedData(input->GetPointData(),
                               this->PointDataPositions[index]);

  this->WriteCellDataAppendedData(input->GetCellData(),
                                  this->CellDataPositions[index]);

  this->WritePointsAppendedData(input->GetPoints(),
                                this->PointsPositions[index]);
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredDataWriter::WriteCellsInline(const char* name,
                                                    vtkCellArray* cells,
                                                    vtkDataArray* types,
                                                    vtkIndent indent)
{
  this->ConvertCells(cells);

  ostream& os = *(this->Stream);
  os << indent << "<" << name << ">\n";
  this->WriteDataArrayInline(this->CellPoints, indent.GetNextIndent());
  this->WriteDataArrayInline(this->CellOffsets, indent.GetNextIndent());
  if(types)
    {
    this->WriteDataArrayInline(types, indent.GetNextIndent(), "types");
    }
  os << indent << "</" << name << ">\n";
}

//----------------------------------------------------------------------------
unsigned long*
vtkXMLUnstructuredDataWriter::WriteCellsAppended(const char* name,
                                                 vtkDataArray* types,
                                                 vtkIndent indent)
{
  unsigned long* positions = new unsigned long[3];
  ostream& os = *(this->Stream);
  os << indent << "<" << name << ">\n";
  positions[0] = this->WriteDataArrayAppended(this->CellPoints,
                                              indent.GetNextIndent());
  positions[1] = this->WriteDataArrayAppended(this->CellOffsets,
                                              indent.GetNextIndent());
  if(types)
    {
    positions[2] = this->WriteDataArrayAppended(types, indent.GetNextIndent(),
                                                "types");
    }
  os << indent << "</" << name << ">\n";
  return positions;
}

//----------------------------------------------------------------------------
void
vtkXMLUnstructuredDataWriter::WriteCellsAppendedData(vtkCellArray* cells,
                                                     vtkDataArray* types,
                                                     unsigned long* positions)
{
  this->ConvertCells(cells);
  this->WriteDataArrayAppendedData(this->CellPoints, positions[0]);
  this->WriteDataArrayAppendedData(this->CellOffsets, positions[1]);
  if(types)
    {
    this->WriteDataArrayAppendedData(types, positions[2]);
    }
  delete [] positions;
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredDataWriter::ConvertCells(vtkCellArray* cells)
{
  vtkIdTypeArray* connectivity = cells->GetData();
  vtkIdType numberOfCells = cells->GetNumberOfCells();
  vtkIdType numberOfTuples = connectivity->GetNumberOfTuples();

  this->CellPoints->SetNumberOfTuples(numberOfTuples - numberOfCells);
  this->CellOffsets->SetNumberOfTuples(numberOfCells);

  vtkIdType* inCell = connectivity->GetPointer(0);
  vtkIdType* outCellPointsBase = this->CellPoints->GetPointer(0);
  vtkIdType* outCellPoints = outCellPointsBase;
  vtkIdType* outCellOffset = this->CellOffsets->GetPointer(0);

  vtkIdType i;
  for(i=0;i < numberOfCells; ++i)
    {
    vtkIdType numberOfPoints = *inCell++;
    memcpy(outCellPoints, inCell, sizeof(vtkIdType)*numberOfPoints);
    outCellPoints += numberOfPoints;
    inCell += numberOfPoints;
    *outCellOffset++ = outCellPoints - outCellPointsBase;
    }
}
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <string>
#include <sys/stat.h>
#include "rawtiles.hpp"

void write_raw_tile(char *outdir, int z, int tx, int ty, std::string pbf) {
	mkdir(outdir, S_IRWXU | S_IRWXG | S_IRWXO);
	std::string curdir(outdir);
    std::string slash( "/" );
    std::string newdir = curdir + slash + std::to_string(z);
	mkdir(newdir.c_str(), S_IRWXU | S_IRWXG | S_IRWXO);
   	newdir = newdir + "/" + std::to_string(tx);
   	mkdir(newdir.c_str(), S_IRWXU | S_IRWXG | S_IRWXO);
   	newdir = newdir + "/" + std::to_string(ty) + ".pbf";

    std::ofstream pbfFile (newdir, std::ios::out | std::ios::binary);
    pbfFile.write (pbf.data(), pbf.size());
    pbfFile.close();
}<commit_msg>Fix indentation for rawtiles.cpp<commit_after>#include <iostream>
#include <fstream>
#include <string>
#include <sys/stat.h>
#include "rawtiles.hpp"

void write_raw_tile(char *outdir, int z, int tx, int ty, std::string pbf) {
	mkdir(outdir, S_IRWXU | S_IRWXG | S_IRWXO);
	std::string curdir(outdir);
	std::string slash( "/" );
	std::string newdir = curdir + slash + std::to_string(z);
	mkdir(newdir.c_str(), S_IRWXU | S_IRWXG | S_IRWXO);
	newdir = newdir + "/" + std::to_string(tx);
	mkdir(newdir.c_str(), S_IRWXU | S_IRWXG | S_IRWXO);
	newdir = newdir + "/" + std::to_string(ty) + ".pbf";

	std::ofstream pbfFile (newdir, std::ios::out | std::ios::binary);
	pbfFile.write (pbf.data(), pbf.size());
	pbfFile.close();
}<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkImageRectilinearWipe.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkImageRectilinearWipe.h"

#include "vtkImageData.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkStreamingDemandDrivenPipeline.h"

vtkStandardNewMacro(vtkImageRectilinearWipe);

//----------------------------------------------------------------------------
vtkImageRectilinearWipe::vtkImageRectilinearWipe()
{
  this->Position[0] = 0;
  this->Position[1] = 0;
  this->Axis[0] = 0;
  this->Axis[1] = 1;
  this->Wipe = VTK_WIPE_QUAD;
  this->SetNumberOfInputPorts(2);
}

//----------------------------------------------------------------------------
// This templated function executes the filter for any type of data.
// Handles the two input operations
template <class T>
void vtkImageRectilinearWipeExecute2(vtkImageRectilinearWipe *self,
                           vtkImageData *inData, T *inPtr,
                           vtkImageData *outData,
                           T *outPtr,
                           int outExt[6], int id)
{
  int idxR, idxY, idxZ;
  int maxY, maxZ;
  vtkIdType inIncX, inIncY, inIncZ;
  vtkIdType outIncX, outIncY, outIncZ;
  int rowLength;
  unsigned long count = 0;
  unsigned long target;

  // find the region to loop over
  rowLength = (outExt[1] - outExt[0]+1)*inData->GetNumberOfScalarComponents();
  maxY = outExt[3] - outExt[2];
  maxZ = outExt[5] - outExt[4];

  target = static_cast<unsigned long>((maxZ+1)*(maxY+1)/50.0);
  target++;

  // Get increments to march through data
  inData->GetContinuousIncrements(outExt, inIncX, inIncY, inIncZ);
  outData->GetContinuousIncrements(outExt, outIncX, outIncY, outIncZ);

  // Loop through output pixels
  for (idxZ = 0; idxZ <= maxZ; idxZ++)
    {
    for (idxY = 0; idxY <= maxY; idxY++)
      {
      if (!id)
        {
        if (!(count%target))
          {
          self->UpdateProgress(count/(50.0*target));
          }
        count++;
        }
      for (idxR = 0; idxR < rowLength; idxR++)
        {
        *outPtr = *inPtr;
        outPtr++;
        inPtr++;
        }
      outPtr += outIncY;
      inPtr += inIncY;
      }
    outPtr += outIncZ;
    inPtr += inIncZ;
    }
}

//----------------------------------------------------------------------------
// This function adjusts the extents of the wipe to the output extents.
int vtkImageRectilinearWipeClampExtents(int wipeExt[6], int outExt[6])
{
  int status = 1;

  for (int i = 0; i < 3; i++)
    {
    // the lower and upper extents cannot be below the lower output extent
    if (wipeExt[2*i] < outExt[2*i])
      {
      wipeExt[2*i] = outExt[2*i];
      }
    if (wipeExt[2*i + 1] < outExt[2*i])
      {
      wipeExt[2*i + 1] = outExt[2*i];
      status = 0;
      }

    // the lower and upper extents cannot be above the upper output extent
    if (wipeExt[2*i] > outExt[2*i + 1])
      {
      wipeExt[2*i] = outExt[2*i + 1];
      status = 0;
      }
    if (wipeExt[2*i + 1] > outExt[2*i + 1])
      {
      wipeExt[2*i + 1] = outExt[2*i + 1];
      }
    }
  return status;
}
//----------------------------------------------------------------------------
// This method is passed a input and output regions, and executes the filter
// algorithm to fill the output from the inputs based on the Wipe ivar.
void vtkImageRectilinearWipe::ThreadedRequestData(
  vtkInformation * vtkNotUsed( request ),
  vtkInformationVector ** vtkNotUsed( inputVector ),
  vtkInformationVector * vtkNotUsed( outputVector ),
  vtkImageData ***inData,
  vtkImageData **outData,
  int outExt[6], int id)
{
  void *inPtr;
  void *outPtr;
  int wipeExt[6];
  int wholeExt[6];
  int whichInput = 0;

  // Make sure the inputs/output are valid
  if (inData[0][0] == NULL)
    {
    vtkErrorMacro(<< "Input " << 0 << " must be specified.");
    return;
    }

  // this filter expects that input is the same type as output.
  if (inData[0][0]->GetScalarType() != outData[0]->GetScalarType())
    {
    vtkErrorMacro(<< "Execute: input ScalarType, "
                  << inData[0][0]->GetScalarType()
                  << ", must match out ScalarType "
                  << outData[0]->GetScalarType());
    return;
    }

  if (inData[1][0] == NULL)
    {
    vtkErrorMacro(<< "Input " << 1 << " must be specified.");
    return;
    }

  // this filter expects that inputs that have the same number of components
  if (inData[0][0]->GetNumberOfScalarComponents() !=
      inData[1][0]->GetNumberOfScalarComponents())
    {
    vtkErrorMacro(<< "Execute: input1 NumberOfScalarComponents, "
                  << inData[0][0]->GetNumberOfScalarComponents()
                  << ", must match out input2 NumberOfScalarComponents "
                  << inData[1][0]->GetNumberOfScalarComponents());
    return;
    }

  // Wipe pattern depends on the whole extent.
  outData[0]->GetWholeExtent(wholeExt);

  // Each quadrant is processed separately
  // lower left

  memcpy (wipeExt, wholeExt, 6 * sizeof (int));
  wipeExt[2*this->Axis[0]+1] += this->Position[this->Axis[0]];
  wipeExt[2*this->Axis[1]+1] += this->Position[this->Axis[1]];

  if (vtkImageRectilinearWipeClampExtents(wipeExt, outExt))
    {

    outPtr = outData[0]->GetScalarPointerForExtent(wipeExt);

    switch (this->Wipe)
      {
      case VTK_WIPE_QUAD:
        whichInput = 0;
        break;
      case VTK_WIPE_HORIZONTAL:
        whichInput = 0;
        break;
      case VTK_WIPE_VERTICAL:
        whichInput = 0;
        break;
      case VTK_WIPE_LOWER_LEFT:
        whichInput = 0;
        break;
      case VTK_WIPE_LOWER_RIGHT:
        whichInput = 1;
        break;
      case VTK_WIPE_UPPER_LEFT:
        whichInput = 1;
        break;
      case VTK_WIPE_UPPER_RIGHT:
        whichInput = 1;
        break;
      }
    inPtr = inData[whichInput][0]->GetScalarPointerForExtent(wipeExt);
    switch (inData[0][0]->GetScalarType())
      {
      vtkTemplateMacro(
        vtkImageRectilinearWipeExecute2(this,
                                        inData[whichInput][0],
                                        static_cast<VTK_TT *>(inPtr),
                                        outData[0],
                                        static_cast<VTK_TT *>(outPtr),
                                        wipeExt, id));
      default:
        vtkErrorMacro(<< "Execute: Unknown ScalarType");
        return;
      }
    }

  // lower right
  memcpy (wipeExt, wholeExt, 6 * sizeof (int));
  wipeExt[2*this->Axis[0]] += (this->Position[this->Axis[0]]+1);
  wipeExt[2*this->Axis[1]+1] =
    wipeExt[2*this->Axis[1]] + this->Position[this->Axis[1]];

  wipeExt[0] = wholeExt[0] + this->Position[0] + 1;
  wipeExt[1] = wholeExt[1];
  wipeExt[2] = wholeExt[2];
  wipeExt[3] = wholeExt[2] + this->Position[1];
  wipeExt[4] = wholeExt[4];
  wipeExt[5] = wholeExt[5];
  if (vtkImageRectilinearWipeClampExtents(wipeExt, outExt))
    {
    switch (this->Wipe)
      {
      case VTK_WIPE_QUAD:
        whichInput = 1;
        break;
      case VTK_WIPE_HORIZONTAL:
        whichInput = 1;
        break;
      case VTK_WIPE_VERTICAL:
        whichInput = 0;
        break;
      case VTK_WIPE_LOWER_LEFT:
        whichInput = 1;
        break;
      case VTK_WIPE_LOWER_RIGHT:
        whichInput = 0;
        break;
      case VTK_WIPE_UPPER_LEFT:
        whichInput = 1;
        break;
      case VTK_WIPE_UPPER_RIGHT:
        whichInput = 1;
        break;
      }
    inPtr = inData[whichInput][0]->GetScalarPointerForExtent(wipeExt);
    outPtr = outData[0]->GetScalarPointerForExtent(wipeExt);
    switch (inData[0][0]->GetScalarType())
      {
      vtkTemplateMacro(
        vtkImageRectilinearWipeExecute2(this,
                                        inData[whichInput][0],
                                        static_cast<VTK_TT *>(inPtr),
                                        outData[0],
                                        static_cast<VTK_TT *>(outPtr),
                                        wipeExt, id));
      default:
        vtkErrorMacro(<< "Execute: Unknown ScalarType");
        return;
      }
    }

  // upper left
  memcpy (wipeExt, wholeExt, 6 * sizeof (int));
  wipeExt[2*this->Axis[0]+1] = wipeExt[2*this->Axis[0]] + this->Position[this->Axis[0]];
  wipeExt[2*this->Axis[1]] += (this->Position[this->Axis[1]] + 1);

  if (vtkImageRectilinearWipeClampExtents(wipeExt, outExt))
    {

    switch (this->Wipe)
      {
      case VTK_WIPE_QUAD:
        whichInput = 1;
        break;
      case VTK_WIPE_HORIZONTAL:
        whichInput = 0;
        break;
      case VTK_WIPE_VERTICAL:
        whichInput = 1;
        break;
      case VTK_WIPE_LOWER_LEFT:
        whichInput = 1;
        break;
      case VTK_WIPE_LOWER_RIGHT:
        whichInput = 1;
        break;
      case VTK_WIPE_UPPER_LEFT:
        whichInput = 0;
        break;
      case VTK_WIPE_UPPER_RIGHT:
        whichInput = 1;
        break;
      }
    inPtr = inData[whichInput][0]->GetScalarPointerForExtent(wipeExt);
    outPtr = outData[0]->GetScalarPointerForExtent(wipeExt);
    switch (inData[0][0]->GetScalarType())
      {
      vtkTemplateMacro(
        vtkImageRectilinearWipeExecute2(this,
                                        inData[whichInput][0],
                                        static_cast<VTK_TT *>(inPtr),
                                        outData[0],
                                        static_cast<VTK_TT *>(outPtr),
                                        wipeExt, id));
      default:
        vtkErrorMacro(<< "Execute: Unknown ScalarType");
        return;
      }
    }

  // upper right
  memcpy (wipeExt, wholeExt, 6 * sizeof (int));
  wipeExt[2*this->Axis[0]] += (this->Position[this->Axis[0]] + 1);
  wipeExt[2*this->Axis[1]] += (this->Position[this->Axis[1]] + 1);

  if (vtkImageRectilinearWipeClampExtents(wipeExt, outExt))
    {
    switch (this->Wipe)
      {
      case VTK_WIPE_QUAD:
        whichInput = 0;
        break;
      case VTK_WIPE_HORIZONTAL:
        whichInput = 1;
        break;
      case VTK_WIPE_VERTICAL:
        whichInput = 1;
        break;
      case VTK_WIPE_LOWER_LEFT:
        whichInput = 1;
        break;
      case VTK_WIPE_LOWER_RIGHT:
        whichInput = 1;
        break;
      case VTK_WIPE_UPPER_LEFT:
        whichInput = 1;
        break;
      case VTK_WIPE_UPPER_RIGHT:
        whichInput = 0;
        break;
      }
    inPtr = inData[whichInput][0]->GetScalarPointerForExtent(wipeExt);
    outPtr = outData[0]->GetScalarPointerForExtent(wipeExt);
    switch (inData[0][0]->GetScalarType())
      {
      vtkTemplateMacro(
        vtkImageRectilinearWipeExecute2(this,
                                        inData[whichInput][0],
                                        static_cast<VTK_TT *>(inPtr),
                                        outData[0],
                                        static_cast<VTK_TT *>(outPtr),
                                        wipeExt, id));
      default:
        vtkErrorMacro(<< "Execute: Unknown ScalarType");
        return;
      }
    }
}

void vtkImageRectilinearWipe::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
  os << indent << "Position: (" << this->Position[0] << ", "
     << this->Position[1] << ")\n";
  os << indent << "Wipe: ";
  switch (this->Wipe)
    {
    case VTK_WIPE_QUAD:
      os << "Quad" << endl;
      break;
    case VTK_WIPE_HORIZONTAL:
      os << "Horizontal" << endl;
      break;
    case VTK_WIPE_VERTICAL:
      os << "Vertical" << endl;
      break;
    case VTK_WIPE_LOWER_LEFT:
      os << "LowerLeft" << endl;
      break;
    case VTK_WIPE_LOWER_RIGHT:
      os << "LowerRight" << endl;
      break;
    case VTK_WIPE_UPPER_LEFT:
      os << "UpperLeft" << endl;
      break;
    case VTK_WIPE_UPPER_RIGHT:
      os << "UpperRight" << endl;
      break;
    }
}

<commit_msg>BUG: Fix missing printself ivar.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkImageRectilinearWipe.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkImageRectilinearWipe.h"

#include "vtkImageData.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkStreamingDemandDrivenPipeline.h"

vtkStandardNewMacro(vtkImageRectilinearWipe);

//----------------------------------------------------------------------------
vtkImageRectilinearWipe::vtkImageRectilinearWipe()
{
  this->Position[0] = 0;
  this->Position[1] = 0;
  this->Axis[0] = 0;
  this->Axis[1] = 1;
  this->Wipe = VTK_WIPE_QUAD;
  this->SetNumberOfInputPorts(2);
}

//----------------------------------------------------------------------------
// This templated function executes the filter for any type of data.
// Handles the two input operations
template <class T>
void vtkImageRectilinearWipeExecute2(vtkImageRectilinearWipe *self,
                           vtkImageData *inData, T *inPtr,
                           vtkImageData *outData,
                           T *outPtr,
                           int outExt[6], int id)
{
  int idxR, idxY, idxZ;
  int maxY, maxZ;
  vtkIdType inIncX, inIncY, inIncZ;
  vtkIdType outIncX, outIncY, outIncZ;
  int rowLength;
  unsigned long count = 0;
  unsigned long target;

  // find the region to loop over
  rowLength = (outExt[1] - outExt[0]+1)*inData->GetNumberOfScalarComponents();
  maxY = outExt[3] - outExt[2];
  maxZ = outExt[5] - outExt[4];

  target = static_cast<unsigned long>((maxZ+1)*(maxY+1)/50.0);
  target++;

  // Get increments to march through data
  inData->GetContinuousIncrements(outExt, inIncX, inIncY, inIncZ);
  outData->GetContinuousIncrements(outExt, outIncX, outIncY, outIncZ);

  // Loop through output pixels
  for (idxZ = 0; idxZ <= maxZ; idxZ++)
    {
    for (idxY = 0; idxY <= maxY; idxY++)
      {
      if (!id)
        {
        if (!(count%target))
          {
          self->UpdateProgress(count/(50.0*target));
          }
        count++;
        }
      for (idxR = 0; idxR < rowLength; idxR++)
        {
        *outPtr = *inPtr;
        outPtr++;
        inPtr++;
        }
      outPtr += outIncY;
      inPtr += inIncY;
      }
    outPtr += outIncZ;
    inPtr += inIncZ;
    }
}

//----------------------------------------------------------------------------
// This function adjusts the extents of the wipe to the output extents.
int vtkImageRectilinearWipeClampExtents(int wipeExt[6], int outExt[6])
{
  int status = 1;

  for (int i = 0; i < 3; i++)
    {
    // the lower and upper extents cannot be below the lower output extent
    if (wipeExt[2*i] < outExt[2*i])
      {
      wipeExt[2*i] = outExt[2*i];
      }
    if (wipeExt[2*i + 1] < outExt[2*i])
      {
      wipeExt[2*i + 1] = outExt[2*i];
      status = 0;
      }

    // the lower and upper extents cannot be above the upper output extent
    if (wipeExt[2*i] > outExt[2*i + 1])
      {
      wipeExt[2*i] = outExt[2*i + 1];
      status = 0;
      }
    if (wipeExt[2*i + 1] > outExt[2*i + 1])
      {
      wipeExt[2*i + 1] = outExt[2*i + 1];
      }
    }
  return status;
}
//----------------------------------------------------------------------------
// This method is passed a input and output regions, and executes the filter
// algorithm to fill the output from the inputs based on the Wipe ivar.
void vtkImageRectilinearWipe::ThreadedRequestData(
  vtkInformation * vtkNotUsed( request ),
  vtkInformationVector ** vtkNotUsed( inputVector ),
  vtkInformationVector * vtkNotUsed( outputVector ),
  vtkImageData ***inData,
  vtkImageData **outData,
  int outExt[6], int id)
{
  void *inPtr;
  void *outPtr;
  int wipeExt[6];
  int wholeExt[6];
  int whichInput = 0;

  // Make sure the inputs/output are valid
  if (inData[0][0] == NULL)
    {
    vtkErrorMacro(<< "Input " << 0 << " must be specified.");
    return;
    }

  // this filter expects that input is the same type as output.
  if (inData[0][0]->GetScalarType() != outData[0]->GetScalarType())
    {
    vtkErrorMacro(<< "Execute: input ScalarType, "
                  << inData[0][0]->GetScalarType()
                  << ", must match out ScalarType "
                  << outData[0]->GetScalarType());
    return;
    }

  if (inData[1][0] == NULL)
    {
    vtkErrorMacro(<< "Input " << 1 << " must be specified.");
    return;
    }

  // this filter expects that inputs that have the same number of components
  if (inData[0][0]->GetNumberOfScalarComponents() !=
      inData[1][0]->GetNumberOfScalarComponents())
    {
    vtkErrorMacro(<< "Execute: input1 NumberOfScalarComponents, "
                  << inData[0][0]->GetNumberOfScalarComponents()
                  << ", must match out input2 NumberOfScalarComponents "
                  << inData[1][0]->GetNumberOfScalarComponents());
    return;
    }

  // Wipe pattern depends on the whole extent.
  outData[0]->GetWholeExtent(wholeExt);

  // Each quadrant is processed separately
  // lower left

  memcpy (wipeExt, wholeExt, 6 * sizeof (int));
  wipeExt[2*this->Axis[0]+1] += this->Position[this->Axis[0]];
  wipeExt[2*this->Axis[1]+1] += this->Position[this->Axis[1]];

  if (vtkImageRectilinearWipeClampExtents(wipeExt, outExt))
    {

    outPtr = outData[0]->GetScalarPointerForExtent(wipeExt);

    switch (this->Wipe)
      {
      case VTK_WIPE_QUAD:
        whichInput = 0;
        break;
      case VTK_WIPE_HORIZONTAL:
        whichInput = 0;
        break;
      case VTK_WIPE_VERTICAL:
        whichInput = 0;
        break;
      case VTK_WIPE_LOWER_LEFT:
        whichInput = 0;
        break;
      case VTK_WIPE_LOWER_RIGHT:
        whichInput = 1;
        break;
      case VTK_WIPE_UPPER_LEFT:
        whichInput = 1;
        break;
      case VTK_WIPE_UPPER_RIGHT:
        whichInput = 1;
        break;
      }
    inPtr = inData[whichInput][0]->GetScalarPointerForExtent(wipeExt);
    switch (inData[0][0]->GetScalarType())
      {
      vtkTemplateMacro(
        vtkImageRectilinearWipeExecute2(this,
                                        inData[whichInput][0],
                                        static_cast<VTK_TT *>(inPtr),
                                        outData[0],
                                        static_cast<VTK_TT *>(outPtr),
                                        wipeExt, id));
      default:
        vtkErrorMacro(<< "Execute: Unknown ScalarType");
        return;
      }
    }

  // lower right
  memcpy (wipeExt, wholeExt, 6 * sizeof (int));
  wipeExt[2*this->Axis[0]] += (this->Position[this->Axis[0]]+1);
  wipeExt[2*this->Axis[1]+1] =
    wipeExt[2*this->Axis[1]] + this->Position[this->Axis[1]];

  wipeExt[0] = wholeExt[0] + this->Position[0] + 1;
  wipeExt[1] = wholeExt[1];
  wipeExt[2] = wholeExt[2];
  wipeExt[3] = wholeExt[2] + this->Position[1];
  wipeExt[4] = wholeExt[4];
  wipeExt[5] = wholeExt[5];
  if (vtkImageRectilinearWipeClampExtents(wipeExt, outExt))
    {
    switch (this->Wipe)
      {
      case VTK_WIPE_QUAD:
        whichInput = 1;
        break;
      case VTK_WIPE_HORIZONTAL:
        whichInput = 1;
        break;
      case VTK_WIPE_VERTICAL:
        whichInput = 0;
        break;
      case VTK_WIPE_LOWER_LEFT:
        whichInput = 1;
        break;
      case VTK_WIPE_LOWER_RIGHT:
        whichInput = 0;
        break;
      case VTK_WIPE_UPPER_LEFT:
        whichInput = 1;
        break;
      case VTK_WIPE_UPPER_RIGHT:
        whichInput = 1;
        break;
      }
    inPtr = inData[whichInput][0]->GetScalarPointerForExtent(wipeExt);
    outPtr = outData[0]->GetScalarPointerForExtent(wipeExt);
    switch (inData[0][0]->GetScalarType())
      {
      vtkTemplateMacro(
        vtkImageRectilinearWipeExecute2(this,
                                        inData[whichInput][0],
                                        static_cast<VTK_TT *>(inPtr),
                                        outData[0],
                                        static_cast<VTK_TT *>(outPtr),
                                        wipeExt, id));
      default:
        vtkErrorMacro(<< "Execute: Unknown ScalarType");
        return;
      }
    }

  // upper left
  memcpy (wipeExt, wholeExt, 6 * sizeof (int));
  wipeExt[2*this->Axis[0]+1] = wipeExt[2*this->Axis[0]] + this->Position[this->Axis[0]];
  wipeExt[2*this->Axis[1]] += (this->Position[this->Axis[1]] + 1);

  if (vtkImageRectilinearWipeClampExtents(wipeExt, outExt))
    {

    switch (this->Wipe)
      {
      case VTK_WIPE_QUAD:
        whichInput = 1;
        break;
      case VTK_WIPE_HORIZONTAL:
        whichInput = 0;
        break;
      case VTK_WIPE_VERTICAL:
        whichInput = 1;
        break;
      case VTK_WIPE_LOWER_LEFT:
        whichInput = 1;
        break;
      case VTK_WIPE_LOWER_RIGHT:
        whichInput = 1;
        break;
      case VTK_WIPE_UPPER_LEFT:
        whichInput = 0;
        break;
      case VTK_WIPE_UPPER_RIGHT:
        whichInput = 1;
        break;
      }
    inPtr = inData[whichInput][0]->GetScalarPointerForExtent(wipeExt);
    outPtr = outData[0]->GetScalarPointerForExtent(wipeExt);
    switch (inData[0][0]->GetScalarType())
      {
      vtkTemplateMacro(
        vtkImageRectilinearWipeExecute2(this,
                                        inData[whichInput][0],
                                        static_cast<VTK_TT *>(inPtr),
                                        outData[0],
                                        static_cast<VTK_TT *>(outPtr),
                                        wipeExt, id));
      default:
        vtkErrorMacro(<< "Execute: Unknown ScalarType");
        return;
      }
    }

  // upper right
  memcpy (wipeExt, wholeExt, 6 * sizeof (int));
  wipeExt[2*this->Axis[0]] += (this->Position[this->Axis[0]] + 1);
  wipeExt[2*this->Axis[1]] += (this->Position[this->Axis[1]] + 1);

  if (vtkImageRectilinearWipeClampExtents(wipeExt, outExt))
    {
    switch (this->Wipe)
      {
      case VTK_WIPE_QUAD:
        whichInput = 0;
        break;
      case VTK_WIPE_HORIZONTAL:
        whichInput = 1;
        break;
      case VTK_WIPE_VERTICAL:
        whichInput = 1;
        break;
      case VTK_WIPE_LOWER_LEFT:
        whichInput = 1;
        break;
      case VTK_WIPE_LOWER_RIGHT:
        whichInput = 1;
        break;
      case VTK_WIPE_UPPER_LEFT:
        whichInput = 1;
        break;
      case VTK_WIPE_UPPER_RIGHT:
        whichInput = 0;
        break;
      }
    inPtr = inData[whichInput][0]->GetScalarPointerForExtent(wipeExt);
    outPtr = outData[0]->GetScalarPointerForExtent(wipeExt);
    switch (inData[0][0]->GetScalarType())
      {
      vtkTemplateMacro(
        vtkImageRectilinearWipeExecute2(this,
                                        inData[whichInput][0],
                                        static_cast<VTK_TT *>(inPtr),
                                        outData[0],
                                        static_cast<VTK_TT *>(outPtr),
                                        wipeExt, id));
      default:
        vtkErrorMacro(<< "Execute: Unknown ScalarType");
        return;
      }
    }
}

void vtkImageRectilinearWipe::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
  os << indent << "Position: (" << this->Position[0] << ", "
     << this->Position[1] << ")\n";
  os << indent << "Position: (" << this->Axis[0] << ", "
     << this->Axis[1] << ", " << this->Axis[1] << ")\n";
  os << indent << "Wipe: ";
  switch (this->Wipe)
    {
    case VTK_WIPE_QUAD:
      os << "Quad" << endl;
      break;
    case VTK_WIPE_HORIZONTAL:
      os << "Horizontal" << endl;
      break;
    case VTK_WIPE_VERTICAL:
      os << "Vertical" << endl;
      break;
    case VTK_WIPE_LOWER_LEFT:
      os << "LowerLeft" << endl;
      break;
    case VTK_WIPE_LOWER_RIGHT:
      os << "LowerRight" << endl;
      break;
    case VTK_WIPE_UPPER_LEFT:
      os << "UpperLeft" << endl;
      break;
    case VTK_WIPE_UPPER_RIGHT:
      os << "UpperRight" << endl;
      break;
    }
}

<|endoftext|>


<commit_before>#ifndef LUCE_HEADER_UTILITY_CPP98HEADER_HH
#define LUCE_HEADER_UTILITY_CPP98HEADER_HH

// http://en.cppreference.com/w/cpp/header

// Utility
#include <bitset>
#include <csetjmp>
#include <csignal>
#include <cstdarg>
#include <cstddef>
#include <cstdlib>
#include <ctime>
#include <functional>
#include <typeinfo>
#include <utility>

// Memory
#include <memory>
#include <new>

// Numeric limit
#include <cfloat>
#include <climits>
#include <limits>

// Error
#include <cassert>
#include <cerrno>
#include <exception>
#include <stdexcept>

// String
#include <cctype>
#include <cstring>
#include <cwchar>
#include <cwctype>
#include <string>

// Container
#include <deque>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>

// Algorithm
#include <algorithm>

// Iterator
#include <iterator>

// Numberic
#include <cmath>
#include <complex>
#include <numeric>
#include <valarray>

// IO
#include <cstdio>
#include <fstream>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <ostream>
#include <sstream>
#include <strstream>
#include <streambuf>

// Localization
#include <locale>
#include <clocale>

// Etc
#include <ciso646>

#endif<commit_msg>Fix Misprint<commit_after>#ifndef LUCE_HEADER_UTILITY_CPP98HEADER_HH
#define LUCE_HEADER_UTILITY_CPP98HEADER_HH

// http://en.cppreference.com/w/cpp/header

// Utility
#include <bitset>
#include <csetjmp>
#include <csignal>
#include <cstdarg>
#include <cstddef>
#include <cstdlib>
#include <ctime>
#include <functional>
#include <typeinfo>
#include <utility>

// Memory
#include <memory>
#include <new>

// Numeric limit
#include <cfloat>
#include <climits>
#include <limits>

// Error
#include <cassert>
#include <cerrno>
#include <exception>
#include <stdexcept>

// String
#include <cctype>
#include <cstring>
#include <cwchar>
#include <cwctype>
#include <string>

// Container
#include <deque>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>

// Algorithm
#include <algorithm>

// Iterator
#include <iterator>

// Numeric
#include <cmath>
#include <complex>
#include <numeric>
#include <valarray>

// IO
#include <cstdio>
#include <fstream>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <ostream>
#include <sstream>
#include <strstream>
#include <streambuf>

// Localization
#include <locale>
#include <clocale>

// Etc
#include <ciso646>

#endif<|endoftext|>


<commit_before>/* This is free and unencumbered software released into the public domain. */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "md5.h"
<commit_msg>Added a static assertion to ensure sizeof(md5) is correct.<commit_after>/* This is free and unencumbered software released into the public domain. */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "md5.h"

using namespace rfc1321;

static_assert(sizeof(md5) == 16, "sizeof(rfc1321::md5) != 16");
<|endoftext|>