<commit_before>#include "Board.h"
#include "Pipe.h"

const int Board::x_offset = 227;
const int Board::y_offset = 35;
const int Board::slotSize = 48;
const int Board::lines = BOARD_LINES;
const int Board::columns = BOARD_COLUMNS;

Board::Board (SDL_Surface* s, SDL_Rect* c, SDL_Surface* back, SDL_Surface* pipe1, SDL_Surface* pipe2)
{
    screen = s;
    coordinates = c;
    background = back;
    pipes_sprite1 = pipe1;
    pipes_sprite2 = pipe2;
    starting_time = SDL_GetTicks();
    flow_started = false;
    game_in_progress = true;

    for (int line = 0; line < lines; line++) {
        for (int column = 0; column < columns; column++) {
            slots[line][column] = NULL;
        }
    }

    for (int p = 0; p < POOL_SIZE; p++) {
        pool[p] = new Pipe(pipes_sprite1, pipes_sprite2);
    }
}

void Board::mouseClick (int x, int y)
{
    int x_min = x_offset, x_max = x_min + (lines * slotSize);
    int y_min = y_offset, y_max = y_min + (columns * slotSize);

    // Check limits
    if (x >= x_min && x <= x_max && y >= y_min && y <= y_max) {
        int line = (x - x_min) / slotSize;
        int column = (y - y_min) / slotSize;
        Pipe **pipe = &slots[line][column];

        if (*pipe) {
            if ((*pipe)->isBlocked())
                return;

            delete *pipe;
        }

        // Get top of the pool
        *pipe = pool[0];
        rotatePool();
    }
}

void Board::rotatePool (void)
{
    for (int p = 0; p < POOL_SIZE - 1; p++) {
        pool[p] = pool[p + 1];
    }

    pool[POOL_SIZE - 1] = new Pipe(pipes_sprite1, pipes_sprite2);
}

SDL_Rect Board::getSlotScreenPosition (int line, int column)
{
    SDL_Rect pos;

    pos.x = (line * slotSize) + x_offset;
    pos.y = (column * slotSize) + y_offset;

    return pos;
}

Pipe* Board::getCurrentPipe() {
    return slots[current_pipe_column][current_pipe_line];
}

void Board::Update() {
    if(game_in_progress) {
        updatePipes();
        updateStartingFlow();
        updateNextPipe();
    }
}

void Board::updatePipes() {
    for (int l = 0; l < lines; l++) {
        for (int c = 0; c < columns; c++) {
            if (slots[l][c] != NULL) {
                slots[l][c]->Update();
            }
        }
    }
}

void Board::updateStartingFlow() {
    if (flow_started == false && SDL_GetTicks() - starting_time > INITIAL_DELAY) {
        if (slots[INITIAL_COLUMN][INITIAL_LINE] != NULL) {
            current_pipe_column = INITIAL_COLUMN;
            current_pipe_line = INITIAL_LINE;
            getCurrentPipe()->StartFlow(FLOW_LEFT);
            flow_started = true;
        } else {
            gameOver();
        }
    }
}

void Board::updateNextPipe() {
    if (flow_started == true && getCurrentPipe()->isFlowFinished()) {
        int flow_direction = getCurrentPipe()->getFlowTurnPosition();
        int next_flow;

        switch(flow_direction) {
            case FLOW_TOP:
                current_pipe_line -= 1;
                next_flow = FLOW_DOWN;
                break;
            case FLOW_RIGHT:
                current_pipe_column += 1;
                next_flow = FLOW_LEFT;
                break;
            case FLOW_DOWN:
                current_pipe_line += 1;
                next_flow = FLOW_TOP;
                break;
            case FLOW_LEFT:
                current_pipe_column -= 1;
                next_flow = FLOW_RIGHT;
                break;
        }

        if (((current_pipe_column >= BOARD_COLUMNS || current_pipe_column < 0) &&
            (current_pipe_line >= BOARD_LINES || current_pipe_line < 0)) ||
            getCurrentPipe() == NULL) {
            gameOver();
        } else {
            getCurrentPipe()->StartFlow(next_flow);
        }
    }
}

void Board::Draw ()
{
    // Draw background
    SDL_BlitSurface(background, 0, screen, coordinates);

    // Draw all board pipes
    for (int l = 0; l < lines; l++) {
        for (int c = 0; c < columns; c++) {
            // if != NULL we have a pipe to draw
            if (slots[l][c] != NULL) {
                SDL_Rect pos = getSlotScreenPosition(l, c);
                slots[l][c]->Draw(screen, &pos);
            }
        }
    }

    // Draw pool pipes
    SDL_Rect pos = {
        .x = POOL_OFFSET_X,
        .y = POOL_OFFSET_Y,
    };

    for (int p = POOL_SIZE - 1; p > 0; p--, pos.y += POOL_SPACING) {
        pool[p]->Draw(screen, &pos);
    }

    pos.y = POOL_TOP_Y;
    pool[0]->Draw(screen, &pos);
}

void Board::gameOver() {
    game_in_progress = false;
}
<commit_msg>Moves check to getCurrentPipe<commit_after>#include "Board.h"
#include "Pipe.h"

const int Board::x_offset = 227;
const int Board::y_offset = 35;
const int Board::slotSize = 48;
const int Board::lines = BOARD_LINES;
const int Board::columns = BOARD_COLUMNS;

Board::Board (SDL_Surface* s, SDL_Rect* c, SDL_Surface* back, SDL_Surface* pipe1, SDL_Surface* pipe2)
{
    screen = s;
    coordinates = c;
    background = back;
    pipes_sprite1 = pipe1;
    pipes_sprite2 = pipe2;
    starting_time = SDL_GetTicks();
    flow_started = false;
    game_in_progress = true;

    for (int line = 0; line < lines; line++) {
        for (int column = 0; column < columns; column++) {
            slots[line][column] = NULL;
        }
    }

    for (int p = 0; p < POOL_SIZE; p++) {
        pool[p] = new Pipe(pipes_sprite1, pipes_sprite2);
    }
}

void Board::mouseClick (int x, int y)
{
    int x_min = x_offset, x_max = x_min + (lines * slotSize);
    int y_min = y_offset, y_max = y_min + (columns * slotSize);

    // Check limits
    if (x >= x_min && x <= x_max && y >= y_min && y <= y_max) {
        int line = (x - x_min) / slotSize;
        int column = (y - y_min) / slotSize;
        Pipe **pipe = &slots[line][column];

        if (*pipe) {
            if ((*pipe)->isBlocked())
                return;

            delete *pipe;
        }

        // Get top of the pool
        *pipe = pool[0];
        rotatePool();
    }
}

void Board::rotatePool (void)
{
    for (int p = 0; p < POOL_SIZE - 1; p++) {
        pool[p] = pool[p + 1];
    }

    pool[POOL_SIZE - 1] = new Pipe(pipes_sprite1, pipes_sprite2);
}

SDL_Rect Board::getSlotScreenPosition (int line, int column)
{
    SDL_Rect pos;

    pos.x = (line * slotSize) + x_offset;
    pos.y = (column * slotSize) + y_offset;

    return pos;
}

Pipe* Board::getCurrentPipe() {
    if(current_pipe_column >= BOARD_COLUMNS || current_pipe_column < 0 ||
       current_pipe_line >= BOARD_LINES || current_pipe_line < 0) {
       return NULL;
    } else {
        return slots[current_pipe_column][current_pipe_line];
    }
}

void Board::Update() {
    if(game_in_progress) {
        updatePipes();
        updateStartingFlow();
        updateNextPipe();
    }
}

void Board::updatePipes() {
    for (int l = 0; l < lines; l++) {
        for (int c = 0; c < columns; c++) {
            if (slots[l][c] != NULL) {
                slots[l][c]->Update();
            }
        }
    }
}

void Board::updateStartingFlow() {
    if (flow_started == false && SDL_GetTicks() - starting_time > INITIAL_DELAY) {
        if (slots[INITIAL_COLUMN][INITIAL_LINE] != NULL) {
            current_pipe_column = INITIAL_COLUMN;
            current_pipe_line = INITIAL_LINE;
            getCurrentPipe()->StartFlow(FLOW_LEFT);
            flow_started = true;
        } else {
            gameOver();
        }
    }
}

void Board::updateNextPipe() {
    if (flow_started == true && getCurrentPipe()->isFlowFinished()) {
        int flow_direction = getCurrentPipe()->getFlowTurnPosition();
        int next_flow;

        switch(flow_direction) {
            case FLOW_TOP:
                current_pipe_line -= 1;
                next_flow = FLOW_DOWN;
                break;
            case FLOW_RIGHT:
                current_pipe_column += 1;
                next_flow = FLOW_LEFT;
                break;
            case FLOW_DOWN:
                current_pipe_line += 1;
                next_flow = FLOW_TOP;
                break;
            case FLOW_LEFT:
                current_pipe_column -= 1;
                next_flow = FLOW_RIGHT;
                break;
        }

        if (getCurrentPipe() == NULL) {
            gameOver();
        } else {
            getCurrentPipe()->StartFlow(next_flow);
        }
    }
}

void Board::Draw ()
{
    // Draw background
    SDL_BlitSurface(background, 0, screen, coordinates);

    // Draw all board pipes
    for (int l = 0; l < lines; l++) {
        for (int c = 0; c < columns; c++) {
            // if != NULL we have a pipe to draw
            if (slots[l][c] != NULL) {
                SDL_Rect pos = getSlotScreenPosition(l, c);
                slots[l][c]->Draw(screen, &pos);
            }
        }
    }

    // Draw pool pipes
    SDL_Rect pos = {
        .x = POOL_OFFSET_X,
        .y = POOL_OFFSET_Y,
    };

    for (int p = POOL_SIZE - 1; p > 0; p--, pos.y += POOL_SPACING) {
        pool[p]->Draw(screen, &pos);
    }

    pos.y = POOL_TOP_Y;
    pool[0]->Draw(screen, &pos);
}

void Board::gameOver() {
    game_in_progress = false;
}
<|endoftext|>


<commit_before>#include "FirmwareDialog.hpp"

#include <ostream>
#include <numeric>
#include <boost/format.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/log/trivial.hpp>

#include <wx/app.h>
#include <wx/sizer.h>
#include <wx/settings.h>
#include <wx/panel.h>
#include <wx/button.h>
#include <wx/filepicker.h>
#include <wx/textctrl.h>
#include <wx/stattext.h>
#include <wx/combobox.h>

#include "libslic3r/Utils.hpp"
#include "avrdude/avrdude-slic3r.hpp"
#include "GUI.hpp"

namespace fs = boost::filesystem;

namespace Slic3r {

// Private

struct FirmwareDialog::priv
{
	std::string avrdude_config;

	wxComboBox *port_picker;
	wxFilePickerCtrl *hex_picker;
	wxStaticText *status;
	wxTextCtrl *txt_stdout;
	wxButton *btn_flash;

	priv() : avrdude_config((fs::path(::Slic3r::resources_dir()) / "avrdude" / "avrdude.conf").string()) {}

	void find_serial_ports();
	void perform_upload();
};

void FirmwareDialog::priv::find_serial_ports()
{
	auto ports = GUI::scan_serial_ports();

	port_picker->Clear();
	for (const auto &port : ports) { port_picker->Append(port); }

	if (ports.size() > 0 && port_picker->GetValue().IsEmpty()) {
		port_picker->SetSelection(0);
	}
}

void FirmwareDialog::priv::perform_upload()
{
	auto filename = hex_picker->GetPath();
	auto port = port_picker->GetValue();
	if (filename.IsEmpty() || port.IsEmpty()) { return; }

	// Note: we're not using wxTextCtrl's ability to act as a std::ostream
	// because its imeplementation doesn't handle conversion from local charset
	// which mangles error messages from perror().

	auto message_fn = [this](const char *msg, unsigned /* size */) {
		// TODO: also log into boost? (Problematic with progress bars.)
		this->txt_stdout->AppendText(wxString(msg));
		wxTheApp->Yield();
	};

	txt_stdout->SetValue(wxEmptyString);
	status->SetLabel(_(L("Flashing in progress. Please do not disconnect the printer!")));
	auto status_color_orig = status->GetForegroundColour();
	status->SetForegroundColour(GUI::get_label_clr_modified());
	btn_flash->Disable();

	std::vector<std::string> args {{
		"-v",
		"-p", "atmega2560",
		"-c", "wiring",
		"-P", port.ToStdString(),
		"-b", "115200",   // XXX: is this ok to hardcode?
		"-D",
		"-U", (boost::format("flash:w:%1%:i") % filename.ToStdString()).str()
	}};

	BOOST_LOG_TRIVIAL(info) << "Invoking avrdude, arguments: "
		<< std::accumulate(std::next(args.begin()), args.end(), args[0], [](std::string a, const std::string &b) {
			return a + ' ' + b;
		});

	auto res = AvrDude::main(std::move(args), avrdude_config, std::move(message_fn));

	BOOST_LOG_TRIVIAL(info) << "avrdude exit code: " << res;

	btn_flash->Enable();

	status->SetForegroundColour(status_color_orig);
	status->SetLabel(
		res == 0 ? _(L("Flashing succeeded!")) : _(L("Flashing failed. Please see the avrdude log below."))
	);
}

// Public

FirmwareDialog::FirmwareDialog(wxWindow *parent) :
	wxDialog(parent, wxID_ANY, _(L("Firmware flasher"))),
	// p(new priv(this))
	p(new priv())
{
	enum {
		DIALOG_MARGIN = 15,
		SPACING = 10,
	};

	wxFont bold_font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);
	bold_font.MakeBold();
	wxFont mono_font(wxFontInfo().Family(wxFONTFAMILY_TELETYPE));
	mono_font.MakeSmaller();

	auto *panel = new wxPanel(this);
	wxBoxSizer *vsizer = new wxBoxSizer(wxVERTICAL);
	panel->SetSizer(vsizer);

	auto *txt_port_picker = new wxStaticText(panel, wxID_ANY, _(L("Serial port:")));
	p->port_picker = new wxComboBox(panel, wxID_ANY);
	auto *btn_rescan = new wxButton(panel, wxID_ANY, _(L("Rescan")));
	auto *port_sizer = new wxBoxSizer(wxHORIZONTAL);
	port_sizer->Add(p->port_picker, 1, wxEXPAND | wxRIGHT, SPACING);
	port_sizer->Add(btn_rescan, 0);

	auto *txt_hex_picker = new wxStaticText(panel, wxID_ANY, _(L("Firmware image:")));
	p->hex_picker = new wxFilePickerCtrl(panel, wxID_ANY);

	auto *txt_status = new wxStaticText(panel, wxID_ANY, _(L("Status:")));
	p->status = new wxStaticText(panel, wxID_ANY, _(L("Ready")));
	p->status->SetFont(bold_font);

	auto *sizer_pickers = new wxFlexGridSizer(2, SPACING, SPACING);
	sizer_pickers->AddGrowableCol(1);
	sizer_pickers->Add(txt_port_picker, 0, wxALIGN_CENTER_VERTICAL);
	sizer_pickers->Add(port_sizer, 0, wxEXPAND);
	sizer_pickers->Add(txt_hex_picker, 0, wxALIGN_CENTER_VERTICAL);
	sizer_pickers->Add(p->hex_picker, 0, wxEXPAND);
	sizer_pickers->Add(txt_status, 0, wxALIGN_CENTER_VERTICAL);
	sizer_pickers->Add(p->status, 0, wxEXPAND);
	vsizer->Add(sizer_pickers, 0, wxEXPAND | wxBOTTOM, SPACING);

	p->txt_stdout = new wxTextCtrl(panel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE | wxTE_READONLY);
	p->txt_stdout->SetFont(mono_font);
	vsizer->Add(p->txt_stdout, 1, wxEXPAND | wxBOTTOM, SPACING);

	p->btn_flash = new wxButton(panel, wxID_ANY, _(L("Flash!")));
	auto *bsizer = new wxBoxSizer(wxHORIZONTAL);
	bsizer->AddStretchSpacer();
	bsizer->Add(p->btn_flash);
	vsizer->Add(bsizer, 0, wxEXPAND);

	auto *topsizer = new wxBoxSizer(wxVERTICAL);
	topsizer->Add(panel, 1, wxEXPAND | wxALL, DIALOG_MARGIN);
	SetSizerAndFit(topsizer);
	SetMinSize(wxSize(400, 400));
	SetSize(wxSize(800, 800));

	p->find_serial_ports();

	p->btn_flash->Bind(wxEVT_BUTTON, [this](wxCommandEvent &) { this->p->perform_upload(); });
	btn_rescan->Bind(wxEVT_BUTTON, [this](wxCommandEvent &) { this->p->find_serial_ports(); });

	// Bind(EVT_BONJOUR_REPLY, &FirmwareDialog::on_reply, this);

	// Bind(EVT_BONJOUR_COMPLETE, [this](wxCommandEvent &) {
	// 	this->timer_state = 0;
	// });

	// Bind(wxEVT_TIMER, &FirmwareDialog::on_timer, this);
}

FirmwareDialog::~FirmwareDialog()
{
	// Needed bacuse of forward defs
}

void FirmwareDialog::run(wxWindow *parent)
{
	FirmwareDialog dialog(parent);
	dialog.ShowModal();
}

}
<commit_msg>FirmwareUpdater: Disable dialog close while flashing<commit_after>#include "FirmwareDialog.hpp"

#include <ostream>
#include <numeric>
#include <boost/format.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/log/trivial.hpp>

#include <wx/app.h>
#include <wx/event.h>
#include <wx/sizer.h>
#include <wx/settings.h>
#include <wx/panel.h>
#include <wx/button.h>
#include <wx/filepicker.h>
#include <wx/textctrl.h>
#include <wx/stattext.h>
#include <wx/combobox.h>

#include "libslic3r/Utils.hpp"
#include "avrdude/avrdude-slic3r.hpp"
#include "GUI.hpp"

namespace fs = boost::filesystem;

namespace Slic3r {

// Private

struct FirmwareDialog::priv
{
	std::string avrdude_config;

	wxComboBox *port_picker;
	wxFilePickerCtrl *hex_picker;
	wxStaticText *status;
	wxTextCtrl *txt_stdout;
	wxButton *btn_close;
	wxButton *btn_flash;

	bool flashing;

	priv() :
		avrdude_config((fs::path(::Slic3r::resources_dir()) / "avrdude" / "avrdude.conf").string()),
		flashing(false)
	{}

	void find_serial_ports();
	void set_flashing(bool flashing, int res = 0);
	void perform_upload();
};

void FirmwareDialog::priv::find_serial_ports()
{
	auto ports = GUI::scan_serial_ports();

	port_picker->Clear();
	for (const auto &port : ports) { port_picker->Append(port); }

	if (ports.size() > 0 && port_picker->GetValue().IsEmpty()) {
		port_picker->SetSelection(0);
	}
}

void FirmwareDialog::priv::set_flashing(bool value, int res)
{
	flashing = value;

	if (value) {
		txt_stdout->SetValue(wxEmptyString);
		status->SetLabel(_(L("Flashing in progress. Please do not disconnect the printer!")));
		// auto status_color_orig = status->GetForegroundColour();
		status->SetForegroundColour(GUI::get_label_clr_modified());
		btn_close->Disable();
		btn_flash->Disable();
	} else {
		auto text_color = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT);
		btn_close->Enable();
		btn_flash->Enable();
		status->SetForegroundColour(text_color);
		status->SetLabel(
			res == 0 ? _(L("Flashing succeeded!")) : _(L("Flashing failed. Please see the avrdude log below."))
		);
	}
}

void FirmwareDialog::priv::perform_upload()
{
	auto filename = hex_picker->GetPath();
	auto port = port_picker->GetValue();
	if (filename.IsEmpty() || port.IsEmpty()) { return; }

	set_flashing(true);

	// Note: we're not using wxTextCtrl's ability to act as a std::ostream
	// because its imeplementation doesn't handle conversion from local charset
	// which mangles error messages from perror().

	auto message_fn = [this](const char *msg, unsigned /* size */) {
		// TODO: also log into boost? (Problematic with progress bars.)
		this->txt_stdout->AppendText(wxString(msg));
		wxTheApp->Yield();
	};

	std::vector<std::string> args {{
		"-v",
		"-p", "atmega2560",
		"-c", "wiring",
		"-P", port.ToStdString(),
		"-b", "115200",   // XXX: is this ok to hardcode?
		"-D",
		"-U", (boost::format("flash:w:%1%:i") % filename.ToStdString()).str()
	}};

	BOOST_LOG_TRIVIAL(info) << "Invoking avrdude, arguments: "
		<< std::accumulate(std::next(args.begin()), args.end(), args[0], [](std::string a, const std::string &b) {
			return a + ' ' + b;
		});

	auto res = AvrDude::main(std::move(args), avrdude_config, std::move(message_fn));

	BOOST_LOG_TRIVIAL(info) << "avrdude exit code: " << res;

	set_flashing(false, res);
}

// Public

FirmwareDialog::FirmwareDialog(wxWindow *parent) :
	wxDialog(parent, wxID_ANY, _(L("Firmware flasher"))),
	p(new priv())
{
	enum {
		DIALOG_MARGIN = 15,
		SPACING = 10,
	};

	wxFont bold_font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);
	bold_font.MakeBold();
	wxFont mono_font(wxFontInfo().Family(wxFONTFAMILY_TELETYPE));
	mono_font.MakeSmaller();

	auto *panel = new wxPanel(this);
	wxBoxSizer *vsizer = new wxBoxSizer(wxVERTICAL);
	panel->SetSizer(vsizer);

	auto *txt_port_picker = new wxStaticText(panel, wxID_ANY, _(L("Serial port:")));
	p->port_picker = new wxComboBox(panel, wxID_ANY);
	auto *btn_rescan = new wxButton(panel, wxID_ANY, _(L("Rescan")));
	auto *port_sizer = new wxBoxSizer(wxHORIZONTAL);
	port_sizer->Add(p->port_picker, 1, wxEXPAND | wxRIGHT, SPACING);
	port_sizer->Add(btn_rescan, 0);

	auto *txt_hex_picker = new wxStaticText(panel, wxID_ANY, _(L("Firmware image:")));
	p->hex_picker = new wxFilePickerCtrl(panel, wxID_ANY);

	auto *txt_status = new wxStaticText(panel, wxID_ANY, _(L("Status:")));
	p->status = new wxStaticText(panel, wxID_ANY, _(L("Ready")));
	p->status->SetFont(bold_font);

	auto *sizer_pickers = new wxFlexGridSizer(2, SPACING, SPACING);
	sizer_pickers->AddGrowableCol(1);
	sizer_pickers->Add(txt_port_picker, 0, wxALIGN_CENTER_VERTICAL);
	sizer_pickers->Add(port_sizer, 0, wxEXPAND);
	sizer_pickers->Add(txt_hex_picker, 0, wxALIGN_CENTER_VERTICAL);
	sizer_pickers->Add(p->hex_picker, 0, wxEXPAND);
	sizer_pickers->Add(txt_status, 0, wxALIGN_CENTER_VERTICAL);
	sizer_pickers->Add(p->status, 0, wxEXPAND);
	vsizer->Add(sizer_pickers, 0, wxEXPAND | wxBOTTOM, SPACING);

	p->txt_stdout = new wxTextCtrl(panel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE | wxTE_READONLY);
	p->txt_stdout->SetFont(mono_font);
	vsizer->Add(p->txt_stdout, 1, wxEXPAND | wxBOTTOM, SPACING);

	p->btn_close = new wxButton(panel, wxID_CLOSE);
	p->btn_flash = new wxButton(panel, wxID_ANY, _(L("Flash!")));
	auto *bsizer = new wxBoxSizer(wxHORIZONTAL);
	bsizer->Add(p->btn_close);
	bsizer->AddStretchSpacer();
	bsizer->Add(p->btn_flash);
	vsizer->Add(bsizer, 0, wxEXPAND);

	auto *topsizer = new wxBoxSizer(wxVERTICAL);
	topsizer->Add(panel, 1, wxEXPAND | wxALL, DIALOG_MARGIN);
	SetSizerAndFit(topsizer);
	SetMinSize(wxSize(400, 400));
	SetSize(wxSize(800, 800));

	p->find_serial_ports();

	p->btn_close->Bind(wxEVT_BUTTON, [this](wxCommandEvent &) { this->Close(); });
	p->btn_flash->Bind(wxEVT_BUTTON, [this](wxCommandEvent &) { this->p->perform_upload(); });
	btn_rescan->Bind(wxEVT_BUTTON, [this](wxCommandEvent &) { this->p->find_serial_ports(); });

	Bind(wxEVT_CLOSE_WINDOW, [this](wxCloseEvent &evt) {
		if (evt.CanVeto() && this->p->flashing) {
			evt.Veto();
		} else {
			evt.Skip();
		}
	});
}

FirmwareDialog::~FirmwareDialog()
{
	// Needed bacuse of forward defs
}

void FirmwareDialog::run(wxWindow *parent)
{
	FirmwareDialog dialog(parent);
	dialog.ShowModal();
}

}
<|endoftext|>


<commit_before>/// @file
/// @author  Kresimir Spes
/// @author  Boris Mikic
/// @author  Ivan Vucica
/// @version 3.34
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://opensource.org/licenses/BSD-3-Clause

#include <stdio.h>

#include <hltypes/exception.h>
#include <hltypes/hltypesUtil.h>
#include <hltypes/hstring.h>

#include "Color.h"

namespace april
{
	// predefined colors
	Color Color::White(255, 255, 255);
	Color Color::Black(0, 0, 0);
	Color Color::Grey(127, 127, 127);
	Color Color::Red(255, 0, 0);
	Color Color::Green(0, 255, 0);
	Color Color::Blue(0, 0, 255);
	Color Color::Yellow(255, 255, 0);
	Color Color::Magenta(255, 0, 255);
	Color Color::Cyan(0, 255, 255);
	Color Color::Orange(255, 127, 0);
	Color Color::Pink(255, 0, 127);
	Color Color::Teal(0, 255, 127);
	Color Color::Neon(127, 255, 0);
	Color Color::Purple(127, 0, 255);
	Color Color::Aqua(0, 127, 255);
	Color Color::LightGrey(191, 191, 191);
	Color Color::LightRed(255, 127, 127);
	Color Color::LightGreen(127, 255, 127);
	Color Color::LightBlue(127, 127, 255);
	Color Color::LightYellow(255, 255, 127);
	Color Color::LightMagenta(255, 127, 255);
	Color Color::LightCyan(127, 255, 255);
	Color Color::LightOrange(255, 191, 127);
	Color Color::LightPink(255, 127, 191);
	Color Color::LightTeal(127, 255, 191);
	Color Color::LightNeon(191, 255, 127);
	Color Color::LightPurple(191, 127, 255);
	Color Color::LightAqua(127, 191, 255);
	Color Color::DarkGrey(63, 63, 63);
	Color Color::DarkRed(127, 0, 0);
	Color Color::DarkGreen(0, 127, 0);
	Color Color::DarkBlue(0, 0, 127);
	Color Color::DarkYellow(127, 127, 0);
	Color Color::DarkMagenta(127, 0, 127);
	Color Color::DarkCyan(0, 127, 127);
	Color Color::DarkOrange(127, 63, 0);
	Color Color::DarkPink(127, 0, 63);
	Color Color::DarkTeal(0, 127, 63);
	Color Color::DarkNeon(63, 127, 0);
	Color Color::DarkPurple(63, 0, 127);
	Color Color::DarkAqua(0, 63, 127);
	Color Color::Clear(0, 0, 0, 0);
	Color Color::Blank(255, 255, 255, 0);

	Color::Color()
	{
		this->r = 255;
		this->g = 255;
		this->b = 255;
		this->a = 255;
	}

	Color::Color(int r, int g, int b, int a)
	{
		this->set(r, g, b, a);
	}

	Color::Color(unsigned char r, unsigned char g, unsigned char b, unsigned char a)
	{
		this->set(r, g, b, a);
	}

	Color::Color(unsigned int color)
	{
		this->set(color);
	}

	Color::Color(chstr hex)
	{
		this->set(hex);
	}

	Color::Color(const char* hex)
	{
		this->set(hstr(hex));
	}

	Color::Color(const Color& color, unsigned char a)
	{
		this->set(color, a);
	}

	void Color::set(int r, int g, int b, int a)
	{
		this->r = (unsigned char)r;
		this->g = (unsigned char)g;
		this->b = (unsigned char)b;
		this->a = (unsigned char)a;
	}

	void Color::set(unsigned char r, unsigned char g, unsigned char b, unsigned char a)
	{
		this->r = r;
		this->g = g;
		this->b = b;
		this->a = a;
	}

	void Color::set(unsigned int color)
	{
		this->r = (unsigned char)((color >> 24) & 0xFF);
		this->g = (unsigned char)((color >> 16) & 0xFF);
		this->b = (unsigned char)((color >> 8) & 0xFF);
		this->a = (unsigned char)(color & 0xFF);
	}

	void Color::set(chstr hex)
	{
		hstr value = (hex.starts_with("0x") ? hex(2, -1) : hex);
		if (value.size() != 6 && value.size() != 8 && !value.is_hex())
		{
			throw hl_exception("Color format must be either 0xRRGGBBAA or 0xRRGGBB (with or without 0x prefix)");
		}
		this->r = (unsigned char)value(0, 2).unhex();
		this->g = (unsigned char)value(2, 2).unhex();
		this->b = (unsigned char)value(4, 2).unhex();
		this->a = (value.size() == 8 ? (unsigned char)value(6, 2).unhex() : 255);
	}

	void Color::set(const char* hex)
	{
		this->set(hstr(hex));
	}

	void Color::set(const Color& color, unsigned char a)
	{
		this->r = color.r;
		this->g = color.g;
		this->b = color.b;
		this->a = a;
	}

	hstr Color::hex(bool rgbOnly) const
	{
		return (!rgbOnly ? hsprintf("%02X%02X%02X%02X", this->r, this->g, this->b, this->a) : hsprintf("%02X%02X%02X", this->r, this->g, this->b));
	}

	Color::operator unsigned int() const
	{
		return ((this->r << 24) | (this->g << 16) | (this->b << 8) | this->a);
	}

	bool Color::operator==(const Color& other) const
	{
		return (this->r == other.r && this->g == other.g && this->b == other.b && this->a == other.a);
	}

	bool Color::operator!=(const Color& other) const
	{
		return (this->r != other.r || this->g != other.g || this->b != other.b || this->a != other.a);
	}

	Color Color::operator+(const Color& other) const
	{
		Color result(*this);
		result += other;
		return result;
	}

	Color Color::operator-(const Color& other) const
	{
		Color result(*this);
		result -= other;
		return result;
	}

	Color Color::operator*(const Color& other) const
	{
		Color result(*this);
		result *= other;
		return result;
	}

	Color Color::operator/(const Color& other) const
	{
		Color result(*this);
		result /= other;
		return result;
	}

	Color Color::operator*(float value) const
	{
		Color result(*this);
		result *= value;
		return result;
	}

	Color Color::operator/(float value) const
	{
		Color result(*this);
		result /= value;
		return result;
	}

	Color Color::operator+=(const Color& other)
	{
		this->r = (unsigned char)hclamp((int)this->r + other.r, 0, 255);
		this->g = (unsigned char)hclamp((int)this->g + other.g, 0, 255);
		this->b = (unsigned char)hclamp((int)this->b + other.b, 0, 255);
		this->a = (unsigned char)hclamp((int)this->a + other.a, 0, 255);
		return (*this);
	}

	Color Color::operator-=(const Color& other)
	{
		this->r = (unsigned char)hclamp((int)this->r - other.r, 0, 255);
		this->g = (unsigned char)hclamp((int)this->g - other.g, 0, 255);
		this->b = (unsigned char)hclamp((int)this->b - other.b, 0, 255);
		this->a = (unsigned char)hclamp((int)this->a - other.a, 0, 255);
		return (*this);
	}

	Color Color::operator*=(const Color& other)
	{
		this->r = (unsigned char)hclamp((int)(this->r_f() * other.r), 0, 255);
		this->g = (unsigned char)hclamp((int)(this->g_f() * other.g), 0, 255);
		this->b = (unsigned char)hclamp((int)(this->b_f() * other.b), 0, 255);
		this->a = (unsigned char)hclamp((int)(this->a_f() * other.a), 0, 255);
		return (*this);
	}

	Color Color::operator/=(const Color& other)
	{
		this->r = (unsigned char)hclamp((int)(this->r_f() / other.r), 0, 255);
		this->g = (unsigned char)hclamp((int)(this->g_f() / other.g), 0, 255);
		this->b = (unsigned char)hclamp((int)(this->b_f() / other.b), 0, 255);
		this->a = (unsigned char)hclamp((int)(this->a_f() / other.a), 0, 255);
		return (*this);
	}

	Color Color::operator*=(float value)
	{
		this->r = (unsigned char)hclamp((int)(this->r * value), 0, 255);
		this->g = (unsigned char)hclamp((int)(this->g * value), 0, 255);
		this->b = (unsigned char)hclamp((int)(this->b * value), 0, 255);
		this->a = (unsigned char)hclamp((int)(this->a * value), 0, 255);
		return (*this);
	}

	Color Color::operator/=(float value)
	{
		float val = 1.0f / value;
		this->r = (unsigned char)hclamp((int)(this->r * val), 0, 255);
		this->g = (unsigned char)hclamp((int)(this->g * val), 0, 255);
		this->b = (unsigned char)hclamp((int)(this->b * val), 0, 255);
		this->a = (unsigned char)hclamp((int)(this->a * val), 0, 255);
		return (*this);
	}

}
<commit_msg>fixed hex color error checking<commit_after>/// @file
/// @author  Kresimir Spes
/// @author  Boris Mikic
/// @author  Ivan Vucica
/// @version 3.34
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://opensource.org/licenses/BSD-3-Clause

#include <stdio.h>

#include <hltypes/exception.h>
#include <hltypes/hltypesUtil.h>
#include <hltypes/hstring.h>

#include "Color.h"

namespace april
{
	// predefined colors
	Color Color::White(255, 255, 255);
	Color Color::Black(0, 0, 0);
	Color Color::Grey(127, 127, 127);
	Color Color::Red(255, 0, 0);
	Color Color::Green(0, 255, 0);
	Color Color::Blue(0, 0, 255);
	Color Color::Yellow(255, 255, 0);
	Color Color::Magenta(255, 0, 255);
	Color Color::Cyan(0, 255, 255);
	Color Color::Orange(255, 127, 0);
	Color Color::Pink(255, 0, 127);
	Color Color::Teal(0, 255, 127);
	Color Color::Neon(127, 255, 0);
	Color Color::Purple(127, 0, 255);
	Color Color::Aqua(0, 127, 255);
	Color Color::LightGrey(191, 191, 191);
	Color Color::LightRed(255, 127, 127);
	Color Color::LightGreen(127, 255, 127);
	Color Color::LightBlue(127, 127, 255);
	Color Color::LightYellow(255, 255, 127);
	Color Color::LightMagenta(255, 127, 255);
	Color Color::LightCyan(127, 255, 255);
	Color Color::LightOrange(255, 191, 127);
	Color Color::LightPink(255, 127, 191);
	Color Color::LightTeal(127, 255, 191);
	Color Color::LightNeon(191, 255, 127);
	Color Color::LightPurple(191, 127, 255);
	Color Color::LightAqua(127, 191, 255);
	Color Color::DarkGrey(63, 63, 63);
	Color Color::DarkRed(127, 0, 0);
	Color Color::DarkGreen(0, 127, 0);
	Color Color::DarkBlue(0, 0, 127);
	Color Color::DarkYellow(127, 127, 0);
	Color Color::DarkMagenta(127, 0, 127);
	Color Color::DarkCyan(0, 127, 127);
	Color Color::DarkOrange(127, 63, 0);
	Color Color::DarkPink(127, 0, 63);
	Color Color::DarkTeal(0, 127, 63);
	Color Color::DarkNeon(63, 127, 0);
	Color Color::DarkPurple(63, 0, 127);
	Color Color::DarkAqua(0, 63, 127);
	Color Color::Clear(0, 0, 0, 0);
	Color Color::Blank(255, 255, 255, 0);

	Color::Color()
	{
		this->r = 255;
		this->g = 255;
		this->b = 255;
		this->a = 255;
	}

	Color::Color(int r, int g, int b, int a)
	{
		this->set(r, g, b, a);
	}

	Color::Color(unsigned char r, unsigned char g, unsigned char b, unsigned char a)
	{
		this->set(r, g, b, a);
	}

	Color::Color(unsigned int color)
	{
		this->set(color);
	}

	Color::Color(chstr hex)
	{
		this->set(hex);
	}

	Color::Color(const char* hex)
	{
		this->set(hstr(hex));
	}

	Color::Color(const Color& color, unsigned char a)
	{
		this->set(color, a);
	}

	void Color::set(int r, int g, int b, int a)
	{
		this->r = (unsigned char)r;
		this->g = (unsigned char)g;
		this->b = (unsigned char)b;
		this->a = (unsigned char)a;
	}

	void Color::set(unsigned char r, unsigned char g, unsigned char b, unsigned char a)
	{
		this->r = r;
		this->g = g;
		this->b = b;
		this->a = a;
	}

	void Color::set(unsigned int color)
	{
		this->r = (unsigned char)((color >> 24) & 0xFF);
		this->g = (unsigned char)((color >> 16) & 0xFF);
		this->b = (unsigned char)((color >> 8) & 0xFF);
		this->a = (unsigned char)(color & 0xFF);
	}

	void Color::set(chstr hex)
	{
		hstr value = (hex.starts_with("0x") ? hex(2, -1) : hex);
        int size = value.size();
		if ((size != 6 && size != 8) || !value.is_hex())
		{
			throw hl_exception("Color format must be either 0xRRGGBBAA or 0xRRGGBB (with or without 0x prefix)");
		}
		this->r = (unsigned char)value(0, 2).unhex();
		this->g = (unsigned char)value(2, 2).unhex();
		this->b = (unsigned char)value(4, 2).unhex();
		this->a = (value.size() == 8 ? (unsigned char)value(6, 2).unhex() : 255);
	}

	void Color::set(const char* hex)
	{
		this->set(hstr(hex));
	}

	void Color::set(const Color& color, unsigned char a)
	{
		this->r = color.r;
		this->g = color.g;
		this->b = color.b;
		this->a = a;
	}

	hstr Color::hex(bool rgbOnly) const
	{
		return (!rgbOnly ? hsprintf("%02X%02X%02X%02X", this->r, this->g, this->b, this->a) : hsprintf("%02X%02X%02X", this->r, this->g, this->b));
	}

	Color::operator unsigned int() const
	{
		return ((this->r << 24) | (this->g << 16) | (this->b << 8) | this->a);
	}

	bool Color::operator==(const Color& other) const
	{
		return (this->r == other.r && this->g == other.g && this->b == other.b && this->a == other.a);
	}

	bool Color::operator!=(const Color& other) const
	{
		return (this->r != other.r || this->g != other.g || this->b != other.b || this->a != other.a);
	}

	Color Color::operator+(const Color& other) const
	{
		Color result(*this);
		result += other;
		return result;
	}

	Color Color::operator-(const Color& other) const
	{
		Color result(*this);
		result -= other;
		return result;
	}

	Color Color::operator*(const Color& other) const
	{
		Color result(*this);
		result *= other;
		return result;
	}

	Color Color::operator/(const Color& other) const
	{
		Color result(*this);
		result /= other;
		return result;
	}

	Color Color::operator*(float value) const
	{
		Color result(*this);
		result *= value;
		return result;
	}

	Color Color::operator/(float value) const
	{
		Color result(*this);
		result /= value;
		return result;
	}

	Color Color::operator+=(const Color& other)
	{
		this->r = (unsigned char)hclamp((int)this->r + other.r, 0, 255);
		this->g = (unsigned char)hclamp((int)this->g + other.g, 0, 255);
		this->b = (unsigned char)hclamp((int)this->b + other.b, 0, 255);
		this->a = (unsigned char)hclamp((int)this->a + other.a, 0, 255);
		return (*this);
	}

	Color Color::operator-=(const Color& other)
	{
		this->r = (unsigned char)hclamp((int)this->r - other.r, 0, 255);
		this->g = (unsigned char)hclamp((int)this->g - other.g, 0, 255);
		this->b = (unsigned char)hclamp((int)this->b - other.b, 0, 255);
		this->a = (unsigned char)hclamp((int)this->a - other.a, 0, 255);
		return (*this);
	}

	Color Color::operator*=(const Color& other)
	{
		this->r = (unsigned char)hclamp((int)(this->r_f() * other.r), 0, 255);
		this->g = (unsigned char)hclamp((int)(this->g_f() * other.g), 0, 255);
		this->b = (unsigned char)hclamp((int)(this->b_f() * other.b), 0, 255);
		this->a = (unsigned char)hclamp((int)(this->a_f() * other.a), 0, 255);
		return (*this);
	}

	Color Color::operator/=(const Color& other)
	{
		this->r = (unsigned char)hclamp((int)(this->r_f() / other.r), 0, 255);
		this->g = (unsigned char)hclamp((int)(this->g_f() / other.g), 0, 255);
		this->b = (unsigned char)hclamp((int)(this->b_f() / other.b), 0, 255);
		this->a = (unsigned char)hclamp((int)(this->a_f() / other.a), 0, 255);
		return (*this);
	}

	Color Color::operator*=(float value)
	{
		this->r = (unsigned char)hclamp((int)(this->r * value), 0, 255);
		this->g = (unsigned char)hclamp((int)(this->g * value), 0, 255);
		this->b = (unsigned char)hclamp((int)(this->b * value), 0, 255);
		this->a = (unsigned char)hclamp((int)(this->a * value), 0, 255);
		return (*this);
	}

	Color Color::operator/=(float value)
	{
		float val = 1.0f / value;
		this->r = (unsigned char)hclamp((int)(this->r * val), 0, 255);
		this->g = (unsigned char)hclamp((int)(this->g * val), 0, 255);
		this->b = (unsigned char)hclamp((int)(this->b * val), 0, 255);
		this->a = (unsigned char)hclamp((int)(this->a * val), 0, 255);
		return (*this);
	}

}
<|endoftext|>


<commit_before>//
// Methods for plane generator
//
#include <math.h>
#include "CylSrc.hh"

void vlCylinderSource::SetResolution(int res)
{
  if ( res != this->Resolution )
    {
    this->Resolution = res;
    this->Resolution = (this->Resolution < 3 ? 3 :
        (this->Resolution > MAX_RESOLUTION ? MAX_RESOLUTION : this->Resolution));
    this->Modified();
    }
}
int vlCylinderSource::GetResolution()
{
  return this->Resolution;
}

void vlCylinderSource::SetHeight(float h)
{
  if ( h != this->Height )
    {
    this->Height = h;
    this->Height = (this->Height > 0.0 ? this->Height : 1.0);
    this->Modified();
    }
}
float vlCylinderSource::GetHeight()
{
  return this->Height;
}

void vlCylinderSource::SetRadius(float h)
{
  if ( h != this->Radius )
    {
    this->Radius = h;
    this->Radius = (this->Radius > 0.0 ? this->Radius : 0.5);
    this->Modified();
    }
}
float vlCylinderSource::GetRadius()
{
  return this->Radius;
}

void vlCylinderSource::SetCapping(int flag)
{
  if ( flag != this->Capping )
    {
    this->Capping = flag;
    this->Modified();
    }
}
int vlCylinderSource::GetCapping()
{
  return this->Capping;
}

void vlCylinderSource::Execute()
{
  float angle= 2.0*3.141592654/this->Resolution;
  int numPolys, numPts;
  float xbot[3], tcbot[2], nbot[3];
  float xtop[3], tctop[2], ntop[3];
  int i, idx;
  int pts[MAX_RESOLUTION];
  vlFloatPoints *newPoints;
  vlFloatNormals *newNormals;
  vlFloatTCoords *newTCoords;
  vlCellArray *newPolys;
  vlPointData *newPtData;
//
// Set things up; allocate memory
//
  this->Initialize();

  if ( this->Capping )
    {
    numPts = 4*this->Resolution;
    numPolys = this->Resolution + 2;
    }
  else
    {
    numPts = 2*this->Resolution;
    numPolys = this->Resolution;
    }

  newPoints = new vlFloatPoints;
  newPoints->Initialize(numPts);

  newNormals = new vlFloatNormals;
  newNormals->Initialize(numPts);

  newTCoords = new vlFloatTCoords;
  newTCoords->Initialize(numPts,2);

  newPtData = new vlPointData;

  newPolys = new vlCellArray;
  newPolys->Initialize(newPolys->EstimateSize(numPolys,this->Resolution));
//
// Generate points and point data for sides
//
  for (i=0; i<this->Resolution; i++)
    {
    // x coordinate
    xbot[0] = xtop[0] = nbot[0] = ntop[0] = this->Radius * cos((double)i*angle);
    tcbot[0] = tctop[0] = fabs(2.0*i/this->Resolution - 1.0);

    // y coordinate
    xbot[1] = 0.5 * this->Height;
    xtop[1] = -0.5 * this->Height;
    nbot[1] = ntop[1] = 0.0;
    tcbot[1] = 0.0;
    tctop[1] = 1.0;

    // z coordinate
    xbot[2] = xtop[2] = nbot[2] = ntop[2] = -this->Radius * sin((double)i*angle);

    idx = 2*i;
    newPoints->InsertPoint(idx,xbot);
    newPoints->InsertPoint(idx+1,xtop);
    newTCoords->InsertTCoord(idx,tcbot);
    newTCoords->InsertTCoord(idx+1,tctop);
    newNormals->InsertNormal(idx,nbot);
    newNormals->InsertNormal(idx+1,ntop);
    }
//
// Generate polygons for sides
//
  for (i=0; i<this->Resolution; i++)
    {
    pts[0] = 2*i;
    pts[1] = pts[0] + 1;
    pts[2] = (pts[1] + 2) % (2*this->Resolution);
    pts[3] = pts[2] - 1;
    newPolys->InsertNextCell(4,pts);
    }
//
// Generate points and point data for top/bottom polygons
//
  if ( this->Capping )
    {
    for (i=0; i<this->Resolution; i++)
      {
      // x coordinate
      xbot[0] = xtop[0] = this->Radius * cos((double)i*angle);
      nbot[0] = ntop[0] = 0.0;
      tcbot[0] = tctop[0] = xbot[0];

      // y coordinate
      xbot[1] = 0.5 * this->Height;
      xtop[1] = -0.5 * this->Height;
      nbot[1] = -1.0;
      ntop[1] =  1.0;

      // z coordinate
      xbot[2] = xtop[2] = -this->Radius * sin((double)i*angle);
      tcbot[1] = tctop[1] = xbot[2];

      idx = 2*this->Resolution;
      newPoints->InsertPoint(idx+i,xbot);
      newTCoords->InsertTCoord(idx+i,tcbot);
      newNormals->InsertNormal(idx+i,nbot);

      idx = 3*this->Resolution;
      newPoints->InsertPoint(idx+i,xtop);
      newTCoords->InsertTCoord(idx+i,tctop);
      newNormals->InsertNormal(idx+i,ntop);
      }
//
// Generate polygons for top/bottom polygons
//
    for (i=0; i<this->Resolution; i++)
      {
      pts[i] = 2*this->Resolution + i;
      }
    newPolys->InsertNextCell(this->Resolution,pts);
    for (i=0; i<this->Resolution; i++)
      {
      pts[i] = 3*this->Resolution + i;
      }
    newPolys->InsertNextCell(this->Resolution,pts);

    } // if capping
//
// Update ourselves
//
  this->SetPoints(newPoints);
  this->SetPointData(newPtData);
  newPtData->SetNormals(newNormals);
  newPtData->SetTCoords(newTCoords);

  newPolys->Squeeze(); // since we've estimated size; reclaim some space
  this->SetPolys(newPolys);
}
<commit_msg>*** empty log message ***<commit_after>//
// Methods for cylinder generator
//
#include <math.h>
#include "CylSrc.hh"

void vlCylinderSource::SetResolution(int res)
{
  if ( res != this->Resolution )
    {
    this->Resolution = res;
    this->Resolution = (this->Resolution < 3 ? 3 :
        (this->Resolution > MAX_RESOLUTION ? MAX_RESOLUTION : this->Resolution));
    this->Modified();
    }
}
int vlCylinderSource::GetResolution()
{
  return this->Resolution;
}

void vlCylinderSource::SetHeight(float h)
{
  if ( h != this->Height )
    {
    this->Height = h;
    this->Height = (this->Height > 0.0 ? this->Height : 1.0);
    this->Modified();
    }
}
float vlCylinderSource::GetHeight()
{
  return this->Height;
}

void vlCylinderSource::SetRadius(float h)
{
  if ( h != this->Radius )
    {
    this->Radius = h;
    this->Radius = (this->Radius > 0.0 ? this->Radius : 0.5);
    this->Modified();
    }
}
float vlCylinderSource::GetRadius()
{
  return this->Radius;
}

void vlCylinderSource::SetCapping(int flag)
{
  if ( flag != this->Capping )
    {
    this->Capping = flag;
    this->Modified();
    }
}
int vlCylinderSource::GetCapping()
{
  return this->Capping;
}

void vlCylinderSource::Execute()
{
  float angle= 2.0*3.141592654/this->Resolution;
  int numPolys, numPts;
  float xbot[3], tcbot[2], nbot[3];
  float xtop[3], tctop[2], ntop[3];
  int i, idx;
  int pts[MAX_RESOLUTION];
  vlFloatPoints *newPoints;
  vlFloatNormals *newNormals;
  vlFloatTCoords *newTCoords;
  vlCellArray *newPolys;
  vlPointData *newPtData;
//
// Set things up; allocate memory
//
  this->Initialize();

  if ( this->Capping )
    {
    numPts = 4*this->Resolution;
    numPolys = this->Resolution + 2;
    }
  else
    {
    numPts = 2*this->Resolution;
    numPolys = this->Resolution;
    }

  newPoints = new vlFloatPoints;
  newPoints->Initialize(numPts);

  newNormals = new vlFloatNormals;
  newNormals->Initialize(numPts);

  newTCoords = new vlFloatTCoords;
  newTCoords->Initialize(numPts,2);

  newPtData = new vlPointData;

  newPolys = new vlCellArray;
  newPolys->Initialize(newPolys->EstimateSize(numPolys,this->Resolution));
//
// Generate points and point data for sides
//
  for (i=0; i<this->Resolution; i++)
    {
    // x coordinate
    xbot[0] = xtop[0] = nbot[0] = ntop[0] = this->Radius * cos((double)i*angle);
    tcbot[0] = tctop[0] = fabs(2.0*i/this->Resolution - 1.0);

    // y coordinate
    xbot[1] = 0.5 * this->Height;
    xtop[1] = -0.5 * this->Height;
    nbot[1] = ntop[1] = 0.0;
    tcbot[1] = 0.0;
    tctop[1] = 1.0;

    // z coordinate
    xbot[2] = xtop[2] = nbot[2] = ntop[2] = -this->Radius * sin((double)i*angle);

    idx = 2*i;
    newPoints->InsertPoint(idx,xbot);
    newPoints->InsertPoint(idx+1,xtop);
    newTCoords->InsertTCoord(idx,tcbot);
    newTCoords->InsertTCoord(idx+1,tctop);
    newNormals->InsertNormal(idx,nbot);
    newNormals->InsertNormal(idx+1,ntop);
    }
//
// Generate polygons for sides
//
  for (i=0; i<this->Resolution; i++)
    {
    pts[0] = 2*i;
    pts[1] = pts[0] + 1;
    pts[2] = (pts[1] + 2) % (2*this->Resolution);
    pts[3] = pts[2] - 1;
    newPolys->InsertNextCell(4,pts);
    }
//
// Generate points and point data for top/bottom polygons
//
  if ( this->Capping )
    {
    for (i=0; i<this->Resolution; i++)
      {
      // x coordinate
      xbot[0] = xtop[0] = this->Radius * cos((double)i*angle);
      nbot[0] = ntop[0] = 0.0;
      tcbot[0] = tctop[0] = xbot[0];

      // y coordinate
      xbot[1] = 0.5 * this->Height;
      xtop[1] = -0.5 * this->Height;
      nbot[1] = -1.0;
      ntop[1] =  1.0;

      // z coordinate
      xbot[2] = xtop[2] = -this->Radius * sin((double)i*angle);
      tcbot[1] = tctop[1] = xbot[2];

      idx = 2*this->Resolution;
      newPoints->InsertPoint(idx+i,xbot);
      newTCoords->InsertTCoord(idx+i,tcbot);
      newNormals->InsertNormal(idx+i,nbot);

      idx = 3*this->Resolution;
      newPoints->InsertPoint(idx+i,xtop);
      newTCoords->InsertTCoord(idx+i,tctop);
      newNormals->InsertNormal(idx+i,ntop);
      }
//
// Generate polygons for top/bottom polygons
//
    for (i=0; i<this->Resolution; i++)
      {
      pts[i] = 2*this->Resolution + i;
      }
    newPolys->InsertNextCell(this->Resolution,pts);
    for (i=0; i<this->Resolution; i++)
      {
      pts[i] = 3*this->Resolution + i;
      }
    newPolys->InsertNextCell(this->Resolution,pts);

    } // if capping
//
// Update ourselves
//
  this->SetPoints(newPoints);
  this->SetPointData(newPtData);
  newPtData->SetNormals(newNormals);
  newPtData->SetTCoords(newTCoords);

  newPolys->Squeeze(); // since we've estimated size; reclaim some space
  this->SetPolys(newPolys);
}
<|endoftext|>


<commit_before><commit_msg>[graf2d] Remove code that forced a segfault if gDebug == gVirtualX<commit_after><|endoftext|>


<commit_before>#include "Layer.h"
#include "Neuron.h"
#include "Functions.h"
#include <vector>
#include <iostream>

Layer::Layer(int neuronCount, int inputCount, float momentum, float learningConstant, std::string functionUsed){

	this->neurons.resize(neuronCount + 1);
	this->inputs = inputCount;
	this->functionUsed = functionUsed;

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

		this->neurons[i] = new Neuron(inputCount, learningConstant, momentum);

	}

	this->neurons[neuronCount] = new BiasNeuron();
}

Layer::~Layer(){

	for(int i = 0; i < this->getSize(); i++){

		delete this->neurons[i];

	}

}

std::vector<float> Layer::feed(std::vector<float> &in){

	std::vector<float> out;
	out.resize(this->getSize());

	for(int i = 0; i < this->getSize(); i++){

		out[i] = this->neurons[i]->feed(in, this->functionUsed);

	}

	return out;
}

std::vector<Neuron *> Layer::getNeurons(){

	return this->neurons;

}

int Layer::getSize(){

	return this->neurons.size();

}

OutputLayer::OutputLayer(int neuronCount, int inputCount, float momentum, float learningConstant, std::string functionUsed) :
 Layer(neuronCount, inputCount, momentum, learningConstant, functionUsed){

	this->neurons.pop_back();
	this->inputs--;

}

HiddenLayer::HiddenLayer(int neuronCount, int inputCount, float momentum, float learningConstant, std::string functionUsed):
  Layer(neuronCount, inputCount, momentum, learningConstant, functionUsed){

}

InputLayer::InputLayer(int neuronCount): Layer(neuronCount, 1, 0, 0, "sigmoid"){
	this->neurons.pop_back();
	this->inputs--;
}

std::vector<float> InputLayer::feed(std::vector<float> &in){

  	return in;

}

// The training function takes as arguments respectively: The deltas of the next layer in order, the pointer to the next layer, the
// activations of the current layer that is being trained and the activations of the previous layer in order
// The algorithm used for training as you may have already guessed is backpropagation
std::vector<float> HiddenLayer::train(std::vector<float> &nextDeltas, Layer *next, std::vector<float> &activations, std::vector<float> &prevActivations){

	std::vector<Neuron *> nextLayer = next->getNeurons();
	std::vector<float> layerDeltas, neuronDeltas;
	layerDeltas.resize(this->getSize());

	for(int i = 0; i < this->getSize(); i++){

		float sum = 0.0;

		for(int j = 0; j < nextLayer.size(); j++){

			sum += nextDeltas[j] * nextLayer[j]->getWeights()[i];

		}

		layerDeltas[i] = sum * Functions::getFunctionDerivative(activations[i], this->functionUsed);
		Neuron *current = this->neurons[i];
		neuronDeltas.resize(prevActivations.size());

		for(int j = 0; j < prevActivations.size(); j++){

			neuronDeltas[i] = layerDeltas[i] * prevActivations[j];

		}

		current->train(neuronDeltas);
		neuronDeltas.clear();
	}
	return layerDeltas;
}

std::vector<float> OutputLayer::train(std::vector<float> &target,
std::vector<float> &activations,
std::vector<float> &prevActivations){

	std::vector<float> layerDeltas;
	layerDeltas.resize(this->getSize());

	for(int i = 0; i < this->getSize(); i++){

		Neuron *current = this->neurons[i];
		layerDeltas[i]  = (activations[i] - target[i] * Functions::getFunctionDerivative(activations[i], this->functionUsed));
		std::vector<float> deltas;
		deltas.resize(prevActivations.size());

		for(int j = 0; j < prevActivations.size(); j++){

		deltas[j] = prevActivations[j] * layerDeltas[i];

		}

		current->train(deltas);
	}
	return layerDeltas;
}
<commit_msg>Fixed the errors, just need to check if the network runs correctly<commit_after>#include "Layer.h"
#include "Neuron.h"
#include "Functions.h"
#include <vector>
#include <iostream>

Layer::Layer(int neuronCount, int inputCount, float momentum, float learningConstant, std::string functionUsed){

	this->neurons.resize(neuronCount + 1);
	this->inputs = inputCount;
	this->functionUsed = functionUsed;

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

		this->neurons[i] = new Neuron(inputCount, learningConstant, momentum);

	}

	this->neurons[neuronCount] = new BiasNeuron();
}

Layer::~Layer(){

	for(int i = 0; i < this->getSize(); i++){

		delete this->neurons[i];

	}

}

std::vector<float> Layer::feed(std::vector<float> &in){

	std::vector<float> out;
	out.resize(this->getSize());

	for(int i = 0; i < this->getSize(); i++){

		out[i] = this->neurons[i]->feed(in, this->functionUsed);

	}

	return out;
}

std::vector<Neuron *> Layer::getNeurons(){

	return this->neurons;

}

int Layer::getSize(){

	return this->neurons.size();

}

OutputLayer::OutputLayer(int neuronCount, int inputCount, float momentum, float learningConstant, std::string functionUsed) :
 Layer(neuronCount, inputCount, momentum, learningConstant, functionUsed){

	this->neurons.pop_back();
	this->inputs--;

}

HiddenLayer::HiddenLayer(int neuronCount, int inputCount, float momentum, float learningConstant, std::string functionUsed):
  Layer(neuronCount, inputCount, momentum, learningConstant, functionUsed){

}

InputLayer::InputLayer(int neuronCount): Layer(neuronCount, 1, 0, 0, "sigmoid"){
	this->neurons.pop_back();
	this->inputs--;
}

std::vector<float> InputLayer::feed(std::vector<float> &in){

  	return in;

}

// The training function takes as arguments respectively: The deltas of the next layer in order, the pointer to the next layer, the
// activations of the current layer that is being trained and the activations of the previous layer in order
// The algorithm used for training as you may have already guessed is backpropagation
std::vector<float> HiddenLayer::train(std::vector<float> &nextDeltas, Layer *next, std::vector<float> &activations, std::vector<float> &prevActivations){

	std::vector<Neuron *> nextLayer = next->getNeurons();
	std::vector<float> layerDeltas;
	layerDeltas.resize(this->getSize());

	for(int i = 0; i < this->getSize(); i++){

		float sum = 0.0;

		std::vector<float> neuronDeltas;
		for(int j = 0; j < nextLayer.size(); j++){

			if(!nextLayer[j]->getWeights().empty())
				sum += nextDeltas[j] * nextLayer[j]->getWeights()[i];

		}

		layerDeltas[i] = sum * Functions::getFunctionDerivative(activations[i], this->functionUsed);
		Neuron *current = this->neurons[i];
		neuronDeltas.resize(prevActivations.size());

		for(int j = 0; j < prevActivations.size(); j++){

			neuronDeltas[j] = layerDeltas[i] * prevActivations[j];

		}

		current->train(neuronDeltas);
	}
	return layerDeltas;
}

std::vector<float> OutputLayer::train(std::vector<float> &target,
std::vector<float> &activations,
std::vector<float> &prevActivations){

	std::vector<float> layerDeltas;
	layerDeltas.resize(this->getSize());

	for(int i = 0; i < this->getSize(); i++){

		Neuron *current = this->neurons[i];
		layerDeltas[i]  = (activations[i] - target[i] * Functions::getFunctionDerivative(activations[i], this->functionUsed));
		std::vector<float> deltas;
		deltas.resize(prevActivations.size());

		for(int j = 0; j < prevActivations.size(); j++){

			deltas[j] = prevActivations[j] * layerDeltas[i];

		}

		current->train(deltas);
	}
	return layerDeltas;
}
<|endoftext|>


<commit_before>// Scintilla source code edit control
// @file LexPB.cxx
// Lexer for PowerBasic by Roland Walter, roland@rowalt.de (for PowerBasic see www.powerbasic.com)
//
// Changes:
// 17.10.2003 Toggling of subs/functions now until next sub/function - this gives better results
// 29.10.2003 1. Bug: Toggling didn't work for subs/functions added in editor
//            2. Own colors for PB constants and Inline Assembler SCE_B_CONSTANT and SCE_B_ASM
//            3. Several smaller syntax coloring improvements and speed optimizations
//
// Copyright for Scintilla: 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>

#include "Platform.h"

#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"

static inline bool IsTypeCharacter(const int ch)
{
    return ch == '%' || ch == '&' || ch == '@' || ch == '!' || ch == '#' || ch == '$' || ch == '?';
}

static inline bool IsAWordChar(const int ch)
{
    return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_');
}

static inline bool IsAWordStart(const int ch)
{
    return (ch < 0x80) && (isalnum(ch) || ch == '_');
}

bool MatchUpperCase(Accessor &styler, int pos, const char *s)   //Same as styler.Match() but uppercase comparison (a-z,A-Z and space only)
{
    char ch;
    for (int i=0; *s; i++)
    {
        ch=styler.SafeGetCharAt(pos+i);
        if (ch > 0x60) ch -= '\x20';
        if (*s != ch) return false;
        s++;
    }
    return true;
}

static void ColourisePBDoc(unsigned int startPos, int length, int initStyle,WordList *keywordlists[],Accessor &styler) {

    WordList &keywords = *keywordlists[0];

    styler.StartAt(startPos);

    StyleContext sc(startPos, length, initStyle, styler);

    for (; sc.More(); sc.Forward()) {
        switch (sc.state)
        {
            case SCE_B_OPERATOR:
            {
                sc.SetState(SCE_B_DEFAULT);
                break;
            }
            case SCE_B_KEYWORD:
            {
                if (!IsAWordChar(sc.ch))
                {
                    if (!IsTypeCharacter(sc.ch))
                    {
                        char s[100];
                        sc.GetCurrentLowered(s, sizeof(s));
                        if (keywords.InList(s))
                        {
                            if (strcmp(s, "rem") == 0)
                            {
                                sc.ChangeState(SCE_B_COMMENT);
                                if (sc.atLineEnd) {sc.SetState(SCE_B_DEFAULT);}
                            }
                            else if (strcmp(s, "asm") == 0)
                            {
                                sc.ChangeState(SCE_B_ASM);
                                if (sc.atLineEnd) {sc.SetState(SCE_B_DEFAULT);}
                            }
                            else
                            {
                                sc.SetState(SCE_B_DEFAULT);
                            }
                        }
                        else
                        {
                            sc.ChangeState(SCE_B_IDENTIFIER);
                            sc.SetState(SCE_B_DEFAULT);
                        }
                    }
                }
                break;
            }
            case SCE_B_NUMBER:
            {
                if (!IsAWordChar(sc.ch)) {sc.SetState(SCE_B_DEFAULT);}
                break;
            }
            case SCE_B_STRING:
            {
                if (sc.ch == '\"'){sc.ForwardSetState(SCE_B_DEFAULT);}
                break;
            }
            case SCE_B_CONSTANT:
            {
                if (!IsAWordChar(sc.ch)) {sc.SetState(SCE_B_DEFAULT);}
                break;
            }
            case SCE_B_COMMENT:
            {
                if (sc.atLineEnd) {sc.SetState(SCE_B_DEFAULT);}
                break;
            }
            case SCE_B_ASM:
            {
                if (sc.atLineEnd) {sc.SetState(SCE_B_DEFAULT);}
                break;
            }
        }  //switch (sc.state)

        // Determine if a new state should be entered:
        if (sc.state == SCE_B_DEFAULT)
        {
            if (sc.ch == '\'') {sc.SetState(SCE_B_COMMENT);}
            else if (sc.ch == '\"') {sc.SetState(SCE_B_STRING);}
            else if (sc.ch == '&' && tolower(sc.chNext) == 'h') {sc.SetState(SCE_B_NUMBER);}
            else if (sc.ch == '&' && tolower(sc.chNext) == 'b') {sc.SetState(SCE_B_NUMBER);}
            else if (sc.ch == '&' && tolower(sc.chNext) == 'o') {sc.SetState(SCE_B_NUMBER);}
            else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {sc.SetState(SCE_B_NUMBER);}
            else if (IsAWordStart(sc.ch)) {sc.SetState(SCE_B_KEYWORD);}
            else if (sc.ch == '%') {sc.SetState(SCE_B_CONSTANT);}
            else if (sc.ch == '$') {sc.SetState(SCE_B_CONSTANT);}
            else if (sc.ch == '#') {sc.SetState(SCE_B_KEYWORD);}
            else if (sc.ch == '!') {sc.SetState(SCE_B_ASM);}
            else if (isoperator(static_cast<char>(sc.ch)) || (sc.ch == '\\')) {sc.SetState(SCE_B_OPERATOR);}
        }
    }      //for (; sc.More(); sc.Forward())
    sc.Complete();
}

//The folding routine for PowerBasic toggles SUBs and FUNCTIONs only. This was exactly what I wanted,
//nothing more. I had worked with this kind of toggling for several years when I used the great good old
//GFA Basic which is dead now. After testing the feature of toggling FOR-NEXT loops, WHILE-WEND loops
//and so on too I found this is more disturbing then helping (for me). So if You think in another way
//you can (or must) write Your own toggling routine ;-)
static void FoldPBDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler)
{
    // No folding enabled, no reason to continue...
    if( styler.GetPropertyInt("fold") == 0 )
        return;

    unsigned int endPos = startPos + length;
    int lineCurrent = styler.GetLine(startPos);
    int levelCurrent = SC_FOLDLEVELBASE;
    if (lineCurrent > 0)
        levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
    int levelNext = levelCurrent;
    char chNext = styler[startPos];

    bool fNewLine=true;
    for (unsigned int i = startPos; i < endPos; i++)
    {
        char ch = chNext;
        chNext = styler.SafeGetCharAt(i + 1);

        if (fNewLine)            //Begin of a new line (The Sub/Function/Macro keywords may occur at begin of line only)
        {
            fNewLine=false;

            switch (ch)
            {
            case ' ':      //Most lines start with space - so check this first
                {
                    int levelUse = levelCurrent;
                    int lev = levelUse | levelNext << 16;
                    styler.SetLevel(lineCurrent, lev);
                    break;
                }
            case 'F':
            case 'S':
            case 'C':
            case 'f':
            case 's':
            case 'c':
                {
                    if( MatchUpperCase(styler,i,"FUNCTION") )
                    {
                        styler.SetLevel(lineCurrent, (SC_FOLDLEVELBASE << 16) | SC_FOLDLEVELHEADERFLAG);
                        levelNext=SC_FOLDLEVELBASE+1;
                    }
                else if( MatchUpperCase(styler,i,"SUB") )
                    {
                        styler.SetLevel(lineCurrent, (SC_FOLDLEVELBASE << 16) | SC_FOLDLEVELHEADERFLAG);
                        levelNext=SC_FOLDLEVELBASE+1;
                    }
                else if( MatchUpperCase(styler,i,"CALLBACK FUNCTION") )
                    {
                        styler.SetLevel(lineCurrent, (SC_FOLDLEVELBASE << 16) | SC_FOLDLEVELHEADERFLAG);
                        levelNext=SC_FOLDLEVELBASE+1;
                    }
                else if( MatchUpperCase(styler,i,"STATIC FUNCTION") )
                    {
                        styler.SetLevel(lineCurrent, (SC_FOLDLEVELBASE << 16) | SC_FOLDLEVELHEADERFLAG);
                        levelNext=SC_FOLDLEVELBASE+1;
                    }
                else if( MatchUpperCase(styler,i,"STATIC SUB") )
                    {
                        styler.SetLevel(lineCurrent, (SC_FOLDLEVELBASE << 16) | SC_FOLDLEVELHEADERFLAG);
                        levelNext=SC_FOLDLEVELBASE+1;
                    }
                break;
                }
            default:
                {
                    int levelUse = levelCurrent;
                    int lev = levelUse | levelNext << 16;
                    styler.SetLevel(lineCurrent, lev);
                    break;
                }
            }  //switch (ch)
        }  //if( fNewLine )

        switch (ch)
        {
            case '\n':
            {
                lineCurrent++;
                levelCurrent = levelNext;
                fNewLine=true;
                break;
            }
            case '\r':
            {
                if (chNext != '\n')
                {
                    lineCurrent++;
                    levelCurrent = levelNext;
                    fNewLine=true;
                }
                break;
            }
        }  //switch (ch)
    }  //for (unsigned int i = startPos; i < endPos; i++)
}

static const char * const pbWordListDesc[] = {
    "Keywords",
    0
};

LexerModule lmPB(SCLEX_POWERBASIC, ColourisePBDoc, "powerbasic", FoldPBDoc, pbWordListDesc);
<commit_msg>Patch from Roland: Toggling for macros added Further folding speed optimitations (for eople dealing with very large listings)<commit_after>// Scintilla source code edit control
// @file LexPB.cxx
// Lexer for PowerBasic by Roland Walter, roland@rowalt.de (for PowerBasic see www.powerbasic.com)
//
// Changes:
// 17.10.2003: Toggling of subs/functions now until next sub/function - this gives better results
// 29.10.2003: 1. Bug: Toggling didn't work for subs/functions added in editor
//             2. Own colors for PB constants and Inline Assembler SCE_B_CONSTANT and SCE_B_ASM
//             3. Several smaller syntax coloring improvements and speed optimizations
// 12.07.2004: 1. Toggling for macros added
//             2. Further folding speed optimitations (for people dealing with very large listings)
//
// Necessary changes for the PB lexer in Scintilla project:
//  - In SciLexer.h and Scintilla.iface:
//
//    #define SCLEX_POWERBASIC 51       //ID for PowerBasic lexer
//    (...)
//    #define SCE_B_DEFAULT 0           //in both VB and PB lexer
//    #define SCE_B_COMMENT 1           //in both VB and PB lexer
//    #define SCE_B_NUMBER 2            //in both VB and PB lexer
//    #define SCE_B_KEYWORD 3           //in both VB and PB lexer
//    #define SCE_B_STRING 4            //in both VB and PB lexer
//    #define SCE_B_PREPROCESSOR 5      //VB lexer only, not in PB lexer
//    #define SCE_B_OPERATOR 6          //in both VB and PB lexer
//    #define SCE_B_IDENTIFIER 7        //in both VB and PB lexer
//    #define SCE_B_DATE 8              //VB lexer only, not in PB lexer
//    #define SCE_B_CONSTANT 13         //PB lexer only, not in VB lexer
//    #define SCE_B_ASM 14              //PB lexer only, not in VB lexer

//  - Statement added to KeyWords.cxx:      'LINK_LEXER(lmPB);'
//  - Statement added to scintilla_vc6.mak: '$(DIR_O)\LexPB.obj: ...\src\LexPB.cxx $(LEX_HEADERS)'
//
// Copyright for Scintilla: 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>

#include "Platform.h"

#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"

static inline bool IsTypeCharacter(const int ch)
{
    return ch == '%' || ch == '&' || ch == '@' || ch == '!' || ch == '#' || ch == '$' || ch == '?';
}

static inline bool IsAWordChar(const int ch)
{
    return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_');
}

static inline bool IsAWordStart(const int ch)
{
    return (ch < 0x80) && (isalnum(ch) || ch == '_');
}

bool MatchUpperCase(Accessor &styler, int pos, const char *s)   //Same as styler.Match() but uppercase comparison (a-z,A-Z and space only)
{
    char ch;
    for (int i=0; *s; i++)
    {
        ch=styler.SafeGetCharAt(pos+i);
        if (ch > 0x60) ch -= '\x20';
        if (*s != ch) return false;
        s++;
    }
    return true;
}

static void ColourisePBDoc(unsigned int startPos, int length, int initStyle,WordList *keywordlists[],Accessor &styler) {

    WordList &keywords = *keywordlists[0];

    styler.StartAt(startPos);

    StyleContext sc(startPos, length, initStyle, styler);

    for (; sc.More(); sc.Forward()) {
        switch (sc.state)
        {
            case SCE_B_OPERATOR:
            {
                sc.SetState(SCE_B_DEFAULT);
                break;
            }
            case SCE_B_KEYWORD:
            {
                if (!IsAWordChar(sc.ch))
                {
                    if (!IsTypeCharacter(sc.ch))
                    {
                        char s[100];
                        sc.GetCurrentLowered(s, sizeof(s));
                        if (keywords.InList(s))
                        {
                            if (strcmp(s, "rem") == 0)
                            {
                                sc.ChangeState(SCE_B_COMMENT);
                                if (sc.atLineEnd) {sc.SetState(SCE_B_DEFAULT);}
                            }
                            else if (strcmp(s, "asm") == 0)
                            {
                                sc.ChangeState(SCE_B_ASM);
                                if (sc.atLineEnd) {sc.SetState(SCE_B_DEFAULT);}
                            }
                            else
                            {
                                sc.SetState(SCE_B_DEFAULT);
                            }
                        }
                        else
                        {
                            sc.ChangeState(SCE_B_IDENTIFIER);
                            sc.SetState(SCE_B_DEFAULT);
                        }
                    }
                }
                break;
            }
            case SCE_B_NUMBER:
            {
                if (!IsAWordChar(sc.ch)) {sc.SetState(SCE_B_DEFAULT);}
                break;
            }
            case SCE_B_STRING:
            {
                if (sc.ch == '\"'){sc.ForwardSetState(SCE_B_DEFAULT);}
                break;
            }
            case SCE_B_CONSTANT:
            {
                if (!IsAWordChar(sc.ch)) {sc.SetState(SCE_B_DEFAULT);}
                break;
            }
            case SCE_B_COMMENT:
            {
                if (sc.atLineEnd) {sc.SetState(SCE_B_DEFAULT);}
                break;
            }
            case SCE_B_ASM:
            {
                if (sc.atLineEnd) {sc.SetState(SCE_B_DEFAULT);}
                break;
            }
        }  //switch (sc.state)

        // Determine if a new state should be entered:
        if (sc.state == SCE_B_DEFAULT)
        {
            if (sc.ch == '\'') {sc.SetState(SCE_B_COMMENT);}
            else if (sc.ch == '\"') {sc.SetState(SCE_B_STRING);}
            else if (sc.ch == '&' && tolower(sc.chNext) == 'h') {sc.SetState(SCE_B_NUMBER);}
            else if (sc.ch == '&' && tolower(sc.chNext) == 'b') {sc.SetState(SCE_B_NUMBER);}
            else if (sc.ch == '&' && tolower(sc.chNext) == 'o') {sc.SetState(SCE_B_NUMBER);}
            else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {sc.SetState(SCE_B_NUMBER);}
            else if (IsAWordStart(sc.ch)) {sc.SetState(SCE_B_KEYWORD);}
            else if (sc.ch == '%') {sc.SetState(SCE_B_CONSTANT);}
            else if (sc.ch == '$') {sc.SetState(SCE_B_CONSTANT);}
            else if (sc.ch == '#') {sc.SetState(SCE_B_KEYWORD);}
            else if (sc.ch == '!') {sc.SetState(SCE_B_ASM);}
            else if (isoperator(static_cast<char>(sc.ch)) || (sc.ch == '\\')) {sc.SetState(SCE_B_OPERATOR);}
        }
    }      //for (; sc.More(); sc.Forward())
    sc.Complete();
}

//The folding routine for PowerBasic toggles SUBs and FUNCTIONs only. This was exactly what I wanted,
//nothing more. I had worked with this kind of toggling for several years when I used the great good old
//GFA Basic which is dead now. After testing the feature of toggling FOR-NEXT loops, WHILE-WEND loops
//and so on too I found this is more disturbing then helping (for me). So if You think in another way
//you can (or must) write Your own toggling routine ;-)
static void FoldPBDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler)
{
    // No folding enabled, no reason to continue...
    if( styler.GetPropertyInt("fold") == 0 )
        return;

    unsigned int endPos = startPos + length;
    int lineCurrent = styler.GetLine(startPos);
    int levelCurrent = SC_FOLDLEVELBASE;
    if (lineCurrent > 0)
        levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
    int levelNext = levelCurrent;
    char chNext = styler[startPos];

    bool fNewLine=true;
    bool fMightBeMultiLineMacro=false;
    bool fBeginOfCommentFound=false;
    for (unsigned int i = startPos; i < endPos; i++)
    {
        char ch = chNext;
        chNext = styler.SafeGetCharAt(i + 1);

        if (fNewLine)            //Begin of a new line (The Sub/Function/Macro keywords may occur at begin of line only)
        {
            fNewLine=false;
            fBeginOfCommentFound=false;
            switch (ch)
            {
            case ' ':      //Most lines start with space - so check this first, the code is the same as for 'default:'
            case '\t':     //Handle tab too
                {
                    int levelUse = levelCurrent;
                    int lev = levelUse | levelNext << 16;
                    styler.SetLevel(lineCurrent, lev);
                    break;
                }
            case 'F':
            case 'f':
                {
					switch (chNext)
					{
                    case 'U':
                    case 'u':
						{
							if( MatchUpperCase(styler,i,"FUNCTION") )
							{
								styler.SetLevel(lineCurrent, (SC_FOLDLEVELBASE << 16) | SC_FOLDLEVELHEADERFLAG);
								levelNext=SC_FOLDLEVELBASE+1;
							}
							break;
						}
					}
                break;
                }
            case 'S':
            case 's':
                {
					switch (chNext)
					{
                    case 'U':
                    case 'u':
						{
							if( MatchUpperCase(styler,i,"SUB") )
							{
								styler.SetLevel(lineCurrent, (SC_FOLDLEVELBASE << 16) | SC_FOLDLEVELHEADERFLAG);
								levelNext=SC_FOLDLEVELBASE+1;
							}
							break;
						}
                    case 'T':
                    case 't':
						{
							if( MatchUpperCase(styler,i,"STATIC FUNCTION") )
							{
								styler.SetLevel(lineCurrent, (SC_FOLDLEVELBASE << 16) | SC_FOLDLEVELHEADERFLAG);
								levelNext=SC_FOLDLEVELBASE+1;
							}
							else if( MatchUpperCase(styler,i,"STATIC SUB") )
							{
								styler.SetLevel(lineCurrent, (SC_FOLDLEVELBASE << 16) | SC_FOLDLEVELHEADERFLAG);
								levelNext=SC_FOLDLEVELBASE+1;
							}
							break;
						}
					}
                break;
                }
            case 'C':
            case 'c':
                {
					switch (chNext)
					{
                    case 'A':
                    case 'a':
						{
							if( MatchUpperCase(styler,i,"CALLBACK FUNCTION") )
							{
								styler.SetLevel(lineCurrent, (SC_FOLDLEVELBASE << 16) | SC_FOLDLEVELHEADERFLAG);
								levelNext=SC_FOLDLEVELBASE+1;
							}
							break;
						}
					}
                break;
                }
            case 'M':
            case 'm':
                {
					switch (chNext)
					{
                    case 'A':
                    case 'a':
						{
							if( MatchUpperCase(styler,i,"MACRO") )
							{
								fMightBeMultiLineMacro=true;  //Set folder level at end of line, we have to check for single line macro
							}
							break;
						}
					}
                break;
                }
            default:
                {
                    int levelUse = levelCurrent;
                    int lev = levelUse | levelNext << 16;
                    styler.SetLevel(lineCurrent, lev);
                    break;
                }
            }  //switch (ch)
        }  //if( fNewLine )

        switch (ch)
        {
            case '=':                              //To test single line macros
            {
                if (fBeginOfCommentFound==false)
                    fMightBeMultiLineMacro=false;  //The found macro is a single line macro only;
                break;
            }
            case '\'':                             //A comment starts
            {
                fBeginOfCommentFound=true;
                break;
            }
            case '\n':
            {
                if (fMightBeMultiLineMacro)        //The current line is the begin of a multi line macro
                {
                    fMightBeMultiLineMacro=false;
                    styler.SetLevel(lineCurrent, (SC_FOLDLEVELBASE << 16) | SC_FOLDLEVELHEADERFLAG);
                    levelNext=SC_FOLDLEVELBASE+1;
                }
                lineCurrent++;
                levelCurrent = levelNext;
                fNewLine=true;
                break;
            }
            case '\r':
            {
                if (chNext != '\n')
                {
                    lineCurrent++;
                    levelCurrent = levelNext;
                    fNewLine=true;
                }
                break;
            }
        }  //switch (ch)
    }  //for (unsigned int i = startPos; i < endPos; i++)
}

static const char * const pbWordListDesc[] = {
    "Keywords",
    0
};

LexerModule lmPB(SCLEX_POWERBASIC, ColourisePBDoc, "powerbasic", FoldPBDoc, pbWordListDesc);
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <iostream>
#include <iomanip>
#include <fstream>
#include <ctype.h>

#include "Lexer.h"

using namespace std;

void Lexer::lex(ifstream* inStream){
	stream = inStream;
}

bool Lexer::next(){
	char current;
	*stream >> current;

	while((current == '\n' || current == ' ') && !stream->eof()){
		*stream >> current;
	}

	if(stream->eof()){
		return false;
	}

	if(current == '"'){
		currentToken = string(1, current);

		while(*stream >> current && current != '"'){
			currentToken += current;
		}

		currentToken += current;
	} else if(isalpha(current)){
		currentToken = string(1, current);

		while(*stream >> current && isalpha(current)){
			currentToken += current;
		}

		stream->putback(current);
	} else {
		currentToken = string(1, current);
	}

	if(stream->eof()){
		return false;
	}

	if(currentToken[0] == 0){
		return false;
	}

	return true;
}

string Lexer::getCurrentToken() const{
	return currentToken;
}

bool Lexer::isWord() const{
	return isalpha(currentToken[0]);
}

bool Lexer::isLitteral() const{
	return currentToken[0] == '"';
}

bool Lexer::isAssign() const{
	return currentToken == "=";
}

bool Lexer::isParenth() const{
	return isLeftParenth() || isRightParenth();
}

bool Lexer::isLeftParenth() const{
	return currentToken == "(";
}

bool Lexer::isRightParenth() const{
	return currentToken == ")";
}

bool Lexer::isStop() const{
	return currentToken == ";";
}
<commit_msg>Improve Lexer using isspace for white space detection<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <iostream>
#include <iomanip>
#include <fstream>
#include <cctype>

#include "Lexer.h"

using namespace std;

void Lexer::lex(ifstream* inStream){
	stream = inStream;
}

bool Lexer::next(){
	char current;
	*stream >> current;

	while(isspace(current) && !stream->eof()){
		*stream >> current;
	}

	if(stream->eof()){
		return false;
	}

	if(current == '"'){
		currentToken = string(1, current);

		while(*stream >> current && current != '"'){
			currentToken += current;
		}

		currentToken += current;
	} else if(isalpha(current)){
		currentToken = string(1, current);

		while(*stream >> current && isalpha(current)){
			currentToken += current;
		}

		stream->putback(current);
	} else {
		currentToken = string(1, current);
	}

	if(stream->eof()){
		return false;
	}

	if(currentToken[0] == 0){
		return false;
	}

	return true;
}

string Lexer::getCurrentToken() const{
	return currentToken;
}

bool Lexer::isWord() const{
	return isalpha(currentToken[0]);
}

bool Lexer::isLitteral() const{
	return currentToken[0] == '"';
}

bool Lexer::isAssign() const{
	return currentToken == "=";
}

bool Lexer::isParenth() const{
	return isLeftParenth() || isRightParenth();
}

bool Lexer::isLeftParenth() const{
	return currentToken == "(";
}

bool Lexer::isRightParenth() const{
	return currentToken == ")";
}

bool Lexer::isStop() const{
	return currentToken == ";";
}
<|endoftext|>


<commit_before>/*
 * This file is part of the Gluon Development Platform
 * Copyright (c) 2014 Arjen Hiemstra <ahiemstra@heimr.nl>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#include "factoryplugin.h"

#include "material.h"
#include "materialinstance.h"
#include "materialelement.h"
#include "entity.h"
#include "technique.h"

using namespace GluonGraphics;

FactoryPlugin::FactoryPlugin( QObject* parent )
    : GluonCore::FactoryPlugin( parent )
{

}

FactoryPlugin::~FactoryPlugin()
{
}

GluonCore::GluonObjectList FactoryPlugin::typesToRegister()
{
    return GluonCore::GluonObjectList()
        << new Material( this )
        << new MaterialInstance( this )
        << new MaterialElement( this )
        << new Entity( this )
        << new Technique( this );
}
<commit_msg>Make sure to do qRegisterMetaType for MaterialInstance<commit_after>/*
 * This file is part of the Gluon Development Platform
 * Copyright (c) 2014 Arjen Hiemstra <ahiemstra@heimr.nl>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#include "factoryplugin.h"

#include "material.h"
#include "materialinstance.h"
#include "materialelement.h"
#include "entity.h"
#include "technique.h"

using namespace GluonGraphics;

FactoryPlugin::FactoryPlugin( QObject* parent )
    : GluonCore::FactoryPlugin( parent )
{

}

FactoryPlugin::~FactoryPlugin()
{
}

GluonCore::GluonObjectList FactoryPlugin::typesToRegister()
{
    qRegisterMetaType< MaterialInstance* >();
    return GluonCore::GluonObjectList()
        << new Material( this )
        << new MaterialInstance( this )
        << new MaterialElement( this )
        << new Entity( this )
        << new Technique( this );
}
<|endoftext|>


<commit_before>/*
 *   Copyright (c) 2014 - 2015 Kulykov Oleh <nonamedemail@gmail.com>
 *
 *   Permission is hereby granted, free of charge, to any person obtaining a copy
 *   of this software and associated documentation files (the "Software"), to deal
 *   in the Software without restriction, including without limitation the rights
 *   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *   copies of the Software, and to permit persons to whom the Software is
 *   furnished to do so, subject to the following conditions:
 *
 *   The above copyright notice and this permission notice shall be included in
 *   all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *   THE SOFTWARE.
 */

#include "../fayecpp.h"

#if defined(HAVE_RECORE_SDK_CONFIG_H)
#include "recore_sdk_config.h"
#endif

#if defined(HAVE_FAYECPP_CONFIG_H)
#include "fayecpp_config.h"
#endif

#if defined(HAVE_STDARG_H)
#include <stdarg.h>
#endif

#if defined(HAVE_ANDROID_LOG_H)
#include <android/log.h>
#define LOG_TAG "RECore"
#endif

#if defined(HAVE_QT)
#include <QDebug>
#endif

#include <stdio.h>
#include <time.h>

namespace FayeCpp {

	void RELog::log(const char * logString, ...)
	{
		if (logString)
		{
			va_list args;
			va_start(args, logString);

#if defined(HAVE_ANDROID_LOG_H)
			__android_log_vprint(ANDROID_LOG_INFO, LOG_TAG, logString, args);
#else
			RELog::logA(logString, args);
#endif

			va_end(args);
		}
	}

	void RELog::logA(const char * logString, va_list arguments)
	{
		if (logString)
		{
#if defined(HAVE_ANDROID_LOG_H)
			__android_log_vprint(ANDROID_LOG_INFO, LOG_TAG, logString, arguments);
#elif defined(HAVE_QT)
            char buff[1024*2] = { 0 };
            vsprintf(buff, logString, arguments);
            qDebug() << buff;
#else
			const time_t now = time(NULL);
			char timeString[32] = { 0 };

			if (strftime(timeString, 32 ,"%n%Y-%m-%d %X ", localtime(&now)))
				fputs(timeString, stdout);
			else
				fprintf(stdout, "\n");
			vfprintf(stdout, logString, arguments);
			fflush(stdout);
#endif
		}
	}

}

<commit_msg>Worked windows build<commit_after>/*
 *   Copyright (c) 2014 - 2015 Kulykov Oleh <nonamedemail@gmail.com>
 *
 *   Permission is hereby granted, free of charge, to any person obtaining a copy
 *   of this software and associated documentation files (the "Software"), to deal
 *   in the Software without restriction, including without limitation the rights
 *   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *   copies of the Software, and to permit persons to whom the Software is
 *   furnished to do so, subject to the following conditions:
 *
 *   The above copyright notice and this permission notice shall be included in
 *   all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *   THE SOFTWARE.
 */

#include "../fayecpp.h"

#if defined(HAVE_RECORE_SDK_CONFIG_H)
#include "recore_sdk_config.h"
#endif

#if defined(HAVE_FAYECPP_CONFIG_H)
#include "fayecpp_config.h"
#endif

#if defined(HAVE_STDARG_H)
#include <stdarg.h>
#endif

#if defined(HAVE_ANDROID_LOG_H)
#include <android/log.h>
#define LOG_TAG "RECore"
#endif

#if defined(HAVE_QT)
#include <QDebug>
#endif

#include <stdio.h>
#include <time.h>

namespace FayeCpp {

	void RELog::log(const char * logString, ...)
	{
		if (logString)
		{
			va_list args;
			va_start(args, logString);

#if defined(HAVE_ANDROID_LOG_H)
			__android_log_vprint(ANDROID_LOG_INFO, LOG_TAG, logString, args);
#else
			RELog::logA(logString, args);
#endif

			va_end(args);
		}
	}

	void RELog::logA(const char * logString, va_list arguments)
	{
		if (logString)
		{
#if defined(HAVE_ANDROID_LOG_H)
			__android_log_vprint(ANDROID_LOG_INFO, LOG_TAG, logString, arguments);
#elif defined(HAVE_QT)
            char buff[1024*2] = { 0 };
            vsprintf(buff, logString, arguments);
            qDebug() << buff;
#else

			fprintf(stdout, "\n");
#ifndef __RE_OS_WINDOWS__
			const time_t now = time(NULL);
			char timeString[32] = { 0 };

			if (strftime(timeString, 32 ,"%Y-%m-%d %X ", localtime(&now)))
				fprintf(stdout, timeString);
#endif
			vfprintf(stdout, logString, arguments);
			fflush(stdout);
#endif
		}
	}

}

<|endoftext|>


<commit_before>// Copyright 2005-2016 The Mumble Developers. All rights reserved.
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file at the root of the
// Mumble source tree or at <https://www.mumble.info/LICENSE>.

#include "murmur_pch.h"

// Ensure boost_system is header only.
#define BOOST_ERROR_CODE_HEADER_ONLY
// Ensure boost_chrono is header only.
#define BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING
#define BOOST_CHRONO_HEADER_ONLY

#include <boost/chrono.hpp>

#include "Timer.h"

Timer::Timer(bool start) {
	uiStart = start ? now() : 0;
}

quint64 Timer::elapsed() const {
	Q_ASSERT(uiStart != 0);
	return now() - uiStart;
}

bool Timer::isElapsed(quint64 us) {
	Q_ASSERT(uiStart != 0);
	if (elapsed() > us) {
		uiStart += us;
		return true;
	}
	return false;
}

quint64 Timer::restart() {
	quint64 n = now();
	quint64 e = n - uiStart;
	uiStart = n;
	return e;
}

bool Timer::isStarted() const {
	return uiStart != 0;
}

bool Timer::operator<(const Timer &other) const {
	return uiStart > other.uiStart;
}

bool Timer::operator>(const Timer &other) const {
	return uiStart < other.uiStart;
}

quint64 Timer::now() {
	using namespace boost::chrono;
	time_point<steady_clock> now = steady_clock::now();
	time_point<steady_clock>::duration epochDuration = now.time_since_epoch();
	microseconds epochDurationUsec = duration_cast<microseconds>(epochDuration);
	return static_cast<quint64>(epochDurationUsec.count());
}
<commit_msg>Timer: revert PR #2333 ("use boost::chrono::steady_clock as the underlyingmonotonic timer.")<commit_after>// Copyright 2005-2016 The Mumble Developers. All rights reserved.
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file at the root of the
// Mumble source tree or at <https://www.mumble.info/LICENSE>.

#include "murmur_pch.h"

#include "Timer.h"

Timer::Timer(bool start) {
	uiStart = start ? now() : 0;
}

quint64 Timer::elapsed() const {
	Q_ASSERT(uiStart != 0);
	return now() - uiStart;
}

bool Timer::isElapsed(quint64 us) {
	Q_ASSERT(uiStart != 0);
	if (elapsed() > us) {
		uiStart += us;
		return true;
	}
	return false;
}

quint64 Timer::restart() {
	quint64 n = now();
	quint64 e = n - uiStart;
	uiStart = n;
	return e;
}

bool Timer::isStarted() const {
	return uiStart != 0;
}

bool Timer::operator<(const Timer &other) const {
	return uiStart > other.uiStart;
}

bool Timer::operator>(const Timer &other) const {
	return uiStart < other.uiStart;
}

#if defined(Q_OS_WIN)
#include <windows.h>

quint64 Timer::now() {
	static double scale = 0;

	if (scale == 0) {
		LARGE_INTEGER freq;
		QueryPerformanceFrequency(&freq);
		scale = 1000000. / freq.QuadPart;
	}

	LARGE_INTEGER li;
	QueryPerformanceCounter(&li);
	quint64 e = li.QuadPart;

	return static_cast<quint64>(e * scale);
}
#elif defined(Q_OS_UNIX)
#include <sys/time.h>
quint64 Timer::now() {
	struct timeval tv;
	gettimeofday(&tv, NULL);
	quint64 e= tv.tv_sec * 1000000LL;
	e += tv.tv_usec;
	return e;
}
#else
quint64 Timer::now() {
	static QTime ticker;
	quint64 elapsed = ticker.elapsed();
	return elapsed * 1000LL;
}
#endif
<|endoftext|>